@threenative/assets 0.3.14 → 0.3.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { parentPort } from 'worker_threads';
2
- import path2 from 'path';
2
+ import path6 from 'path';
3
3
  import { existsSync, statSync, accessSync, constants } from 'fs';
4
4
  import { mkdir, writeFile, rename, rm, readFile, mkdtemp, readdir } from 'fs/promises';
5
5
  import os, { tmpdir, platform, homedir } from 'os';
@@ -377,7 +377,7 @@ var KIND_BY_EXTENSION = {
377
377
  webp: "texture"
378
378
  };
379
379
  function classify(logicalPath) {
380
- const extension = path2.extname(logicalPath).slice(1).toLowerCase();
380
+ const extension = path6.extname(logicalPath).slice(1).toLowerCase();
381
381
  return KIND_BY_EXTENSION[extension] ?? "other";
382
382
  }
383
383
  function messageOf2(error) {
@@ -1066,13 +1066,13 @@ function binaryNames(platformName) {
1066
1066
  function pathCandidates(environment, platformName) {
1067
1067
  const raw = environment.PATH ?? environment.Path ?? "";
1068
1068
  if (raw.trim().length === 0) return [];
1069
- return raw.split(path2.delimiter).filter((directory) => directory.trim().length > 0).flatMap((directory) => binaryNames(platformName).map((name) => path2.join(directory, name)));
1069
+ return raw.split(path6.delimiter).filter((directory) => directory.trim().length > 0).flatMap((directory) => binaryNames(platformName).map((name) => path6.join(directory, name)));
1070
1070
  }
1071
1071
  function conventionalCandidates(platformName, home) {
1072
1072
  if (platformName === "darwin") {
1073
1073
  return [
1074
1074
  "/Applications/Blender.app/Contents/MacOS/Blender",
1075
- path2.join(home, "Applications/Blender.app/Contents/MacOS/Blender")
1075
+ path6.join(home, "Applications/Blender.app/Contents/MacOS/Blender")
1076
1076
  ];
1077
1077
  }
1078
1078
  if (platformName === "win32") {
@@ -1082,7 +1082,7 @@ function conventionalCandidates(platformName, home) {
1082
1082
  ];
1083
1083
  return roots.flatMap(
1084
1084
  (root) => ["5.2", "5.1", "5.0", "4.5", "4.2"].map(
1085
- (release) => path2.join(root, "Blender Foundation", `Blender ${release}`, "blender.exe")
1085
+ (release) => path6.join(root, "Blender Foundation", `Blender ${release}`, "blender.exe")
1086
1086
  )
1087
1087
  );
1088
1088
  }
@@ -1091,7 +1091,7 @@ function conventionalCandidates(platformName, home) {
1091
1091
  "/usr/local/bin/blender",
1092
1092
  "/snap/bin/blender",
1093
1093
  "/var/lib/flatpak/exports/bin/org.blender.Blender",
1094
- path2.join(home, ".local/bin/blender")
1094
+ path6.join(home, ".local/bin/blender")
1095
1095
  ];
1096
1096
  }
1097
1097
  function parseBlenderVersion(output) {
@@ -1124,7 +1124,7 @@ function resolveBlender(environment = process.env, options = {}) {
1124
1124
  const install = BLENDER_INSTALL_GUIDANCE;
1125
1125
  const override = environment.THREENATIVE_BLENDER_PATH;
1126
1126
  if (override !== void 0 && override.trim().length > 0) {
1127
- const candidate = path2.resolve(override.trim());
1127
+ const candidate = path6.resolve(override.trim());
1128
1128
  if (!executableFile(candidate)) {
1129
1129
  return {
1130
1130
  available: false,
@@ -1196,8 +1196,8 @@ var RESULT_PREFIX = "TN_BLENDER_RESULT ";
1196
1196
  var DEFAULT_TIMEOUT_MS = 3e5;
1197
1197
  function blenderScriptsDirectory(environment = process.env) {
1198
1198
  const override = environment.THREENATIVE_BLENDER_SCRIPTS;
1199
- if (override !== void 0 && override.trim().length > 0) return path2.resolve(override.trim());
1200
- return path2.resolve(fileURLToPath(import.meta.url), "..", "..", "gpl");
1199
+ if (override !== void 0 && override.trim().length > 0) return path6.resolve(override.trim());
1200
+ return path6.resolve(fileURLToPath(import.meta.url), "..", "..", "gpl");
1201
1201
  }
1202
1202
  function failure(cause, detail, stderr) {
1203
1203
  return {
@@ -1212,7 +1212,7 @@ function failure(cause, detail, stderr) {
1212
1212
  function temporaryRoot(environment) {
1213
1213
  const named = environment.TMPDIR ?? environment.TEMP ?? environment.TMP;
1214
1214
  if (named !== void 0 && named.trim().length > 0 && existsSync(named.trim())) {
1215
- return path2.resolve(named.trim());
1215
+ return path6.resolve(named.trim());
1216
1216
  }
1217
1217
  return os.tmpdir();
1218
1218
  }
@@ -1262,21 +1262,21 @@ function assertSourcePath(source) {
1262
1262
  if (typeof source !== "string" || source.trim().length === 0) {
1263
1263
  throw new Error("TN_BLENDER_BRIDGE: 'source' must be a non-empty path.");
1264
1264
  }
1265
- return path2.resolve(source);
1265
+ return path6.resolve(source);
1266
1266
  }
1267
1267
  async function run(request, options) {
1268
1268
  const environment = options.environment ?? process.env;
1269
1269
  const status = resolveBlender(environment);
1270
1270
  if (!status.available || status.path === void 0) return unavailable(status);
1271
1271
  const scripts = options.scriptsDirectory ?? blenderScriptsDirectory(environment);
1272
- const script = options.script ?? path2.join(scripts, "convert.py");
1272
+ const script = options.script ?? path6.join(scripts, "convert.py");
1273
1273
  if (!existsSync(script)) {
1274
1274
  return failure(
1275
1275
  "script-missing",
1276
1276
  `The Blender script '${script}' is not on disk. Set THREENATIVE_BLENDER_SCRIPTS to the package's gpl/ directory.`
1277
1277
  );
1278
1278
  }
1279
- const temporary = await mkdtemp(path2.join(temporaryRoot(environment), "tn-blender-"));
1279
+ const temporary = await mkdtemp(path6.join(temporaryRoot(environment), "tn-blender-"));
1280
1280
  let outcome;
1281
1281
  try {
1282
1282
  outcome = await runBlender(
@@ -1333,7 +1333,7 @@ async function convertModel(source, out, options = {}) {
1333
1333
  throw new Error("TN_BLENDER_BRIDGE: 'out' must be a non-empty path.");
1334
1334
  }
1335
1335
  return run(
1336
- { mode: "convert", out: path2.resolve(out), source: assertSourcePath(source) },
1336
+ { mode: "convert", out: path6.resolve(out), source: assertSourcePath(source) },
1337
1337
  options
1338
1338
  );
1339
1339
  }
@@ -1342,14 +1342,14 @@ async function convertModel(source, out, options = {}) {
1342
1342
  var BLENDER_IMPORT_PASS = "blender-import";
1343
1343
  var IMPORT_EXTENSIONS = new Set(BLENDER_SOURCE_EXTENSIONS);
1344
1344
  function scriptsDirectory() {
1345
- const here = path2.dirname(fileURLToPath(import.meta.url));
1345
+ const here = path6.dirname(fileURLToPath(import.meta.url));
1346
1346
  const candidates = [
1347
1347
  // Built: `dist/index.js` sits beside `dist/blender-gpl/`.
1348
- path2.join(here, "blender-gpl"),
1348
+ path6.join(here, "blender-gpl"),
1349
1349
  // Source: `src/passes/` -> the workspace sibling.
1350
- path2.resolve(here, "..", "..", "..", "blender-bridge", "gpl")
1350
+ path6.resolve(here, "..", "..", "..", "blender-bridge", "gpl")
1351
1351
  ];
1352
- const found = candidates.find((candidate) => existsSync(path2.join(candidate, "convert.py")));
1352
+ const found = candidates.find((candidate) => existsSync(path6.join(candidate, "convert.py")));
1353
1353
  if (found === void 0) {
1354
1354
  throw new Error(
1355
1355
  `TN_ASSETS_BLENDER_SCRIPTS_MISSING: no convert.py under ${candidates.join(" or ")}. This package's build copies them; run 'pnpm --filter @threenative/assets build'.`
@@ -1358,7 +1358,7 @@ function scriptsDirectory() {
1358
1358
  return found;
1359
1359
  }
1360
1360
  function needsBlenderImport(logicalPath) {
1361
- return IMPORT_EXTENSIONS.has(path2.extname(logicalPath).slice(1).toLowerCase());
1361
+ return IMPORT_EXTENSIONS.has(path6.extname(logicalPath).slice(1).toLowerCase());
1362
1362
  }
1363
1363
  function messageFor(logicalPath, result) {
1364
1364
  if (result.ok) throw new Error("TN_ASSETS_BLENDER_IMPORT: called with a successful result.");
@@ -1374,10 +1374,10 @@ function blenderImportPass(options = {}) {
1374
1374
  name: BLENDER_IMPORT_PASS,
1375
1375
  async apply(input, logicalPath) {
1376
1376
  if (!needsBlenderImport(logicalPath)) return input;
1377
- const staging = await mkdtemp(path2.join(tmpdir(), "tn-blender-import-"));
1378
- const extension = path2.extname(logicalPath).toLowerCase();
1379
- const source = path2.join(staging, `source${extension}`);
1380
- const out = path2.join(staging, "converted.glb");
1377
+ const staging = await mkdtemp(path6.join(tmpdir(), "tn-blender-import-"));
1378
+ const extension = path6.extname(logicalPath).toLowerCase();
1379
+ const source = path6.join(staging, `source${extension}`);
1380
+ const out = path6.join(staging, "converted.glb");
1381
1381
  try {
1382
1382
  await writeFile(source, input);
1383
1383
  const result = await convertModel(source, out, {
@@ -12596,7 +12596,7 @@ function textureStats(bytes, mimeType) {
12596
12596
  }
12597
12597
  function resolveBasisTranscoder(cwd) {
12598
12598
  try {
12599
- const javascriptPath = createRequire(path2.join(cwd, "package.json")).resolve(
12599
+ const javascriptPath = createRequire(path6.join(cwd, "package.json")).resolve(
12600
12600
  "three/examples/jsm/libs/basis/basis_transcoder.js"
12601
12601
  );
12602
12602
  return { javascriptPath, wasmPath: javascriptPath.replace(/\.js$/u, ".wasm") };
@@ -16821,8 +16821,8 @@ function imageQuality(source, decoded, width, height, options = {}) {
16821
16821
  var basisPromise;
16822
16822
  async function basisModule2() {
16823
16823
  basisPromise ??= (async () => {
16824
- const paths = resolveBasisTranscoder(path2.dirname(fileURLToPath(import.meta.url)));
16825
- const directory = path2.dirname(paths.javascriptPath);
16824
+ const paths = resolveBasisTranscoder(path6.dirname(fileURLToPath(import.meta.url)));
16825
+ const directory = path6.dirname(paths.javascriptPath);
16826
16826
  const shim = { exports: {} };
16827
16827
  new Function(
16828
16828
  "module",
@@ -19536,6 +19536,7 @@ function textureBindings(root) {
19536
19536
  return {
19537
19537
  height: shape.height,
19538
19538
  key: keys[index] ?? `texture#${String(index)}`,
19539
+ unnamed: texture.getName() === "",
19539
19540
  levels: shape.levels,
19540
19541
  mimeType,
19541
19542
  slots: [...listTextureSlots(texture)].sort(),
@@ -19562,7 +19563,7 @@ function assertNoTextureDrift(source, output, logicalPath) {
19562
19563
  const before = source.textures[index];
19563
19564
  const after = output.textures[index];
19564
19565
  if (before === void 0 || after === void 0) continue;
19565
- if (before.key !== after.key) {
19566
+ if (before.key !== after.key && !before.unnamed) {
19566
19567
  failures.push(`texture ${String(index)} renamed ${before.key} -> ${after.key}`);
19567
19568
  continue;
19568
19569
  }
@@ -20952,10 +20953,36 @@ function authoredLodName(name) {
20952
20953
  }
20953
20954
 
20954
20955
  // src/lod/cards.ts
20955
- var MAX_CARD_TRIANGLES = 8;
20956
+ var MAX_CARD_TRIANGLES = 32;
20957
+ var MAX_CARD_SPAN = 0.25;
20958
+ var ALWAYS_CARD_TRIANGLES = 8;
20956
20959
  var CARD_KEEP_RATIOS = [0.5, 0.25];
20957
20960
  var TRIANGLE2 = 3;
20958
20961
  var MAX_CARD_SCALE = 2;
20962
+ function diagonalOf(positions, indices, from, to) {
20963
+ const min2 = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
20964
+ const max2 = [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY];
20965
+ for (let at = from; at < to; at += 1) {
20966
+ const vertex = indices[at] * 3;
20967
+ for (let axis = 0; axis < 3; axis += 1) {
20968
+ const value = positions[vertex + axis];
20969
+ if (value < min2[axis]) min2[axis] = value;
20970
+ if (value > max2[axis]) max2[axis] = value;
20971
+ }
20972
+ }
20973
+ if (!Number.isFinite(min2[0])) return 0;
20974
+ return Math.hypot(
20975
+ max2[0] - min2[0],
20976
+ max2[1] - min2[1],
20977
+ max2[2] - min2[2]
20978
+ );
20979
+ }
20980
+ function triangleSpan(positions, indices, triangles) {
20981
+ const corners = new Uint32Array(triangles.length * TRIANGLE2);
20982
+ for (const [at, triangle] of triangles.entries())
20983
+ corners.set(indices.subarray(triangle, triangle + TRIANGLE2), at * TRIANGLE2);
20984
+ return diagonalOf(positions, corners, 0, corners.length);
20985
+ }
20959
20986
  function findCards(positions, indices) {
20960
20987
  const vertexCount = Math.floor(positions.length / 3);
20961
20988
  const parent = new Int32Array(vertexCount);
@@ -20988,9 +21015,10 @@ function findCards(positions, indices) {
20988
21015
  }
20989
21016
  const cards = [];
20990
21017
  const preserved = [];
21018
+ const maxSpan = MAX_CARD_SPAN * diagonalOf(positions, indices, 0, indices.length);
20991
21019
  for (const triangles of grouped.values()) {
20992
21020
  if (triangles.length === 0) continue;
20993
- if (triangles.length > MAX_CARD_TRIANGLES) {
21021
+ if (triangles.length > MAX_CARD_TRIANGLES || triangles.length > ALWAYS_CARD_TRIANGLES && triangleSpan(positions, indices, triangles) > maxSpan) {
20994
21022
  for (const triangle of triangles) preserved.push(triangle);
20995
21023
  continue;
20996
21024
  }
@@ -23295,11 +23323,14 @@ async function quantizeStaticGeometry(document, quantize2) {
23295
23323
  releaseDeformingMeshes(held);
23296
23324
  }
23297
23325
  }
23326
+ function clusteredMesh(mesh) {
23327
+ return mesh.listPrimitives().some((primitive) => primitive.getExtension(TN_VIRTUAL_GEOMETRY) !== null);
23328
+ }
23298
23329
  function holdDeformingMeshes(document) {
23299
23330
  const skinned = skinnedMeshes(document);
23300
23331
  const held = [];
23301
23332
  for (const mesh of document.getRoot().listMeshes()) {
23302
- if (!deformingMesh(mesh, skinned)) continue;
23333
+ if (!deformingMesh(mesh, skinned) && !clusteredMesh(mesh)) continue;
23303
23334
  const nodes = [];
23304
23335
  for (const parent of mesh.listParents()) {
23305
23336
  if (!(parent instanceof Node)) continue;
@@ -23335,7 +23366,7 @@ function releaseDeformingMeshes(held) {
23335
23366
  for (const { primitive, indices, position, targets } of primitives) {
23336
23367
  if (primitive.getIndices() !== indices)
23337
23368
  throw new Error(
23338
- "TN_ASSETS_MODEL_DEFORMING_RENUMBERED: quantization rewrote the index buffer of a deforming primitive; its positions were held in source space and can no longer be addressed by index."
23369
+ "TN_ASSETS_MODEL_HELD_RENUMBERED: quantization rewrote the index buffer of a primitive whose positions were held in source space, so they can no longer be addressed by index \u2014 a sidecar or a cluster DAG holds those indices."
23339
23370
  );
23340
23371
  releaseAttribute(primitive, position);
23341
23372
  for (const { target, position: delta } of targets) releaseAttribute(target, delta);
@@ -23465,14 +23496,14 @@ function createSharedImageStore(outputRoot, options = {}) {
23465
23496
  const memory = /* @__PURE__ */ new Map();
23466
23497
  let listing;
23467
23498
  let manifestQuality;
23468
- const directory = outputRoot === void 0 ? void 0 : path2.join(outputRoot, SHARED_IMAGES_DIRECTORY);
23499
+ const directory = outputRoot === void 0 ? void 0 : path6.join(outputRoot, SHARED_IMAGES_DIRECTORY);
23469
23500
  const qualityInManifest = () => {
23470
23501
  manifestQuality ??= (async () => {
23471
23502
  const scores = /* @__PURE__ */ new Map();
23472
23503
  if (outputRoot === void 0) return scores;
23473
23504
  try {
23474
23505
  const manifest = JSON.parse(
23475
- await readFile(path2.join(outputRoot, "assets.manifest.json"), "utf8")
23506
+ await readFile(path6.join(outputRoot, "assets.manifest.json"), "utf8")
23476
23507
  );
23477
23508
  for (const entry of Object.values(manifest.entries ?? {})) {
23478
23509
  if (!Array.isArray(entry?.sharedImages)) continue;
@@ -23518,7 +23549,7 @@ function createSharedImageStore(outputRoot, options = {}) {
23518
23549
  const parsed = parseFileName(name);
23519
23550
  if (parsed === void 0) return void 0;
23520
23551
  const image = {
23521
- buffer: await readFile(path2.join(directory, name)),
23552
+ buffer: await readFile(path6.join(directory, name)),
23522
23553
  codec: parsed.codec,
23523
23554
  mimeType: parsed.mimeType,
23524
23555
  ...await (async () => {
@@ -23526,7 +23557,7 @@ function createSharedImageStore(outputRoot, options = {}) {
23526
23557
  if (cached !== void 0) return { quality: cached };
23527
23558
  try {
23528
23559
  const quality = readTextureQuality(
23529
- JSON.parse(await readFile(path2.join(directory, `${name}.quality.json`), "utf8"))
23560
+ JSON.parse(await readFile(path6.join(directory, `${name}.quality.json`), "utf8"))
23530
23561
  );
23531
23562
  return quality === void 0 ? {} : { quality };
23532
23563
  } catch (error) {
@@ -23538,7 +23569,7 @@ function createSharedImageStore(outputRoot, options = {}) {
23538
23569
  ...await (async () => {
23539
23570
  try {
23540
23571
  return readTranscoderRecord(
23541
- JSON.parse(await readFile(path2.join(directory, `${name}.transcoder.json`), "utf8"))
23572
+ JSON.parse(await readFile(path6.join(directory, `${name}.transcoder.json`), "utf8"))
23542
23573
  );
23543
23574
  } catch (error) {
23544
23575
  if (error.code === "ENOENT" || error instanceof SyntaxError)
@@ -23559,7 +23590,7 @@ function createSharedImageStore(outputRoot, options = {}) {
23559
23590
  if (known.has(key) && image.quality === void 0 && image.transcoderSavings === void 0 && image.transcoderRequired !== true)
23560
23591
  return;
23561
23592
  await mkdir(directory, { recursive: true });
23562
- const target = path2.join(directory, name);
23593
+ const target = path6.join(directory, name);
23563
23594
  const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
23564
23595
  try {
23565
23596
  await writeFile(temporary, image.buffer);
@@ -23600,8 +23631,8 @@ function createSharedImageStore(outputRoot, options = {}) {
23600
23631
  };
23601
23632
  }
23602
23633
  function sharedImageUri(logicalPath, outputPath) {
23603
- const from = path2.posix.dirname(logicalPath.split(path2.sep).join("/"));
23604
- const relative = path2.posix.relative(from === "." ? "" : from, outputPath);
23634
+ const from = path6.posix.dirname(logicalPath.split(path6.sep).join("/"));
23635
+ const relative = path6.posix.relative(from === "." ? "" : from, outputPath);
23605
23636
  return relative.startsWith(".") || from === "." ? relative : `./${relative}`;
23606
23637
  }
23607
23638
  var GLB_MAGIC = 1179937895;
@@ -23612,9 +23643,9 @@ function padded(buffer, fill) {
23612
23643
  return remainder === 0 ? buffer : Buffer.concat([buffer, Buffer.alloc(4 - remainder, fill)]);
23613
23644
  }
23614
23645
  async function writeSharedGlb(io, document, logicalPath, uriFor) {
23615
- const basename = path2.posix.basename(
23616
- logicalPath.split(path2.sep).join("/"),
23617
- path2.extname(logicalPath)
23646
+ const basename = path6.posix.basename(
23647
+ logicalPath.split(path6.sep).join("/"),
23648
+ path6.extname(logicalPath)
23618
23649
  );
23619
23650
  const written = await io.writeJSON(document, { basename, format: Format.GLTF });
23620
23651
  const json = written.json;
@@ -23629,6 +23660,7 @@ async function writeSharedGlb(io, document, logicalPath, uriFor) {
23629
23660
  }
23630
23661
  delete resources[image.uri];
23631
23662
  image.uri = uriFor(bytes);
23663
+ image.name ??= path6.posix.basename(image.uri, path6.posix.extname(image.uri));
23632
23664
  }
23633
23665
  const buffers = json.buffers ?? [];
23634
23666
  const external = buffers.filter((buffer) => buffer.uri !== void 0);
@@ -24446,7 +24478,7 @@ function declareSharedImage(store, logicalPath, auxiliaryOutputs, candidate) {
24446
24478
  const outputPath = store.outputPath(candidate.key, candidate.image);
24447
24479
  auxiliaryOutputs.set(outputPath, {
24448
24480
  buffer: candidate.image.buffer,
24449
- extension: path2.extname(outputPath),
24481
+ extension: path6.extname(outputPath),
24450
24482
  manifestField: "sharedImages",
24451
24483
  metadata: {
24452
24484
  codec: candidate.image.codec,
package/dist/index.d.ts CHANGED
@@ -117,6 +117,8 @@ interface IEmbeddedTextureSummary {
117
117
  interface IModelTextureBinding {
118
118
  readonly height: number;
119
119
  readonly key: string;
120
+ /** The image came unnamed; the cook may name it by its shared file, which is not a rename. */
121
+ readonly unnamed: boolean;
120
122
  /** KTX2 mip levels; 1 for a still-uncompressed source image. */
121
123
  readonly levels: number;
122
124
  readonly mimeType: string;
@@ -1557,6 +1559,8 @@ interface ISpeciesSpec {
1557
1559
  };
1558
1560
  readonly lods?: readonly ISpeciesLODSpec[];
1559
1561
  readonly maxDistance?: number;
1562
+ /** Metres where the engine's whole-asset impostor takes over: no far level is derived past it. */
1563
+ readonly impostorDistance?: number;
1560
1564
  }
1561
1565
  interface ICookTerrainWorldMaterialLayer {
1562
1566
  readonly id: string;
package/dist/index.js CHANGED
@@ -344,7 +344,8 @@ function parseBudget(value) {
344
344
  function skipKeys(images) {
345
345
  const repeats = /* @__PURE__ */ new Map();
346
346
  return images.map((image, index) => {
347
- const base = image.name === void 0 || image.name === "" ? `texture#${String(index)}` : image.name;
347
+ const assigned = image.uri !== void 0 && image.name === path9.posix.basename(image.uri, path9.posix.extname(image.uri));
348
+ const base = image.name === void 0 || image.name === "" || assigned ? `texture#${String(index)}` : image.name;
348
349
  const seen = repeats.get(base) ?? 0;
349
350
  repeats.set(base, seen + 1);
350
351
  return seen === 0 ? base : `${base}#${String(index)}`;
@@ -18852,10 +18853,36 @@ function virtualGeometryBytes(virtual) {
18852
18853
  }
18853
18854
 
18854
18855
  // src/lod/cards.ts
18855
- var MAX_CARD_TRIANGLES = 8;
18856
+ var MAX_CARD_TRIANGLES = 32;
18857
+ var MAX_CARD_SPAN = 0.25;
18858
+ var ALWAYS_CARD_TRIANGLES = 8;
18856
18859
  var CARD_KEEP_RATIOS = [0.5, 0.25];
18857
18860
  var TRIANGLE = 3;
18858
18861
  var MAX_CARD_SCALE = 2;
18862
+ function diagonalOf(positions, indices, from, to) {
18863
+ const min2 = [Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY];
18864
+ const max2 = [Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY];
18865
+ for (let at = from; at < to; at += 1) {
18866
+ const vertex = indices[at] * 3;
18867
+ for (let axis = 0; axis < 3; axis += 1) {
18868
+ const value = positions[vertex + axis];
18869
+ if (value < min2[axis]) min2[axis] = value;
18870
+ if (value > max2[axis]) max2[axis] = value;
18871
+ }
18872
+ }
18873
+ if (!Number.isFinite(min2[0])) return 0;
18874
+ return Math.hypot(
18875
+ max2[0] - min2[0],
18876
+ max2[1] - min2[1],
18877
+ max2[2] - min2[2]
18878
+ );
18879
+ }
18880
+ function triangleSpan(positions, indices, triangles) {
18881
+ const corners = new Uint32Array(triangles.length * TRIANGLE);
18882
+ for (const [at, triangle] of triangles.entries())
18883
+ corners.set(indices.subarray(triangle, triangle + TRIANGLE), at * TRIANGLE);
18884
+ return diagonalOf(positions, corners, 0, corners.length);
18885
+ }
18859
18886
  function findCards(positions, indices) {
18860
18887
  const vertexCount = Math.floor(positions.length / 3);
18861
18888
  const parent = new Int32Array(vertexCount);
@@ -18888,9 +18915,10 @@ function findCards(positions, indices) {
18888
18915
  }
18889
18916
  const cards = [];
18890
18917
  const preserved = [];
18918
+ const maxSpan = MAX_CARD_SPAN * diagonalOf(positions, indices, 0, indices.length);
18891
18919
  for (const triangles of grouped.values()) {
18892
18920
  if (triangles.length === 0) continue;
18893
- if (triangles.length > MAX_CARD_TRIANGLES) {
18921
+ if (triangles.length > MAX_CARD_TRIANGLES || triangles.length > ALWAYS_CARD_TRIANGLES && triangleSpan(positions, indices, triangles) > maxSpan) {
18894
18922
  for (const triangle of triangles) preserved.push(triangle);
18895
18923
  continue;
18896
18924
  }
@@ -20008,6 +20036,9 @@ function appendCardCopies(primitive, copies) {
20008
20036
  }
20009
20037
  }
20010
20038
  function thinFoliageCards(document, keepRatio) {
20039
+ return thinCoveringCards(document, keepRatio, 0);
20040
+ }
20041
+ function thinCoveringCards(document, keepRatio, minCoverage) {
20011
20042
  if (!Number.isFinite(keepRatio) || keepRatio <= 0 || keepRatio >= 1)
20012
20043
  throw new Error("thinFoliageCards keepRatio must be in (0, 1).");
20013
20044
  let reduced = 0;
@@ -20030,6 +20061,11 @@ function thinFoliageCards(document, keepRatio) {
20030
20061
  );
20031
20062
  if (chain === null)
20032
20063
  throw new Error("thinFoliageCards cannot reduce this MASK primitive as whole cards.");
20064
+ const coverage = chain.levels.at(-1)?.areaCoverage ?? 1;
20065
+ if (coverage < minCoverage)
20066
+ throw new Error(
20067
+ `thinFoliageCards cannot reduce this MASK primitive to ${keepRatio} and keep ${minCoverage} of its card area (got ${coverage.toFixed(2)}).`
20068
+ );
20033
20069
  appendCardCopies(primitive, chain.copies);
20034
20070
  primitive.setIndices(
20035
20071
  (primitive.getIndices() ?? document.createAccessor().setType("SCALAR").setBuffer(primitive.getAttribute("POSITION").getBuffer())).clone().setArray(chain.indices.at(-1))
@@ -20932,6 +20968,7 @@ function textureBindings(root) {
20932
20968
  return {
20933
20969
  height: shape.height,
20934
20970
  key: keys[index] ?? `texture#${String(index)}`,
20971
+ unnamed: texture.getName() === "",
20935
20972
  levels: shape.levels,
20936
20973
  mimeType,
20937
20974
  slots: [...listTextureSlots(texture)].sort(),
@@ -20958,7 +20995,7 @@ function assertNoTextureDrift(source, output, logicalPath) {
20958
20995
  const before = source.textures[index];
20959
20996
  const after = output.textures[index];
20960
20997
  if (before === void 0 || after === void 0) continue;
20961
- if (before.key !== after.key) {
20998
+ if (before.key !== after.key && !before.unnamed) {
20962
20999
  failures.push(`texture ${String(index)} renamed ${before.key} -> ${after.key}`);
20963
21000
  continue;
20964
21001
  }
@@ -25153,11 +25190,14 @@ async function quantizeStaticGeometry(document, quantize2) {
25153
25190
  releaseDeformingMeshes(held);
25154
25191
  }
25155
25192
  }
25193
+ function clusteredMesh(mesh) {
25194
+ return mesh.listPrimitives().some((primitive) => primitive.getExtension(TN_VIRTUAL_GEOMETRY) !== null);
25195
+ }
25156
25196
  function holdDeformingMeshes(document) {
25157
25197
  const skinned = skinnedMeshes(document);
25158
25198
  const held = [];
25159
25199
  for (const mesh of document.getRoot().listMeshes()) {
25160
- if (!deformingMesh(mesh, skinned)) continue;
25200
+ if (!deformingMesh(mesh, skinned) && !clusteredMesh(mesh)) continue;
25161
25201
  const nodes = [];
25162
25202
  for (const parent of mesh.listParents()) {
25163
25203
  if (!(parent instanceof Node)) continue;
@@ -25193,7 +25233,7 @@ function releaseDeformingMeshes(held) {
25193
25233
  for (const { primitive, indices, position, targets } of primitives) {
25194
25234
  if (primitive.getIndices() !== indices)
25195
25235
  throw new Error(
25196
- "TN_ASSETS_MODEL_DEFORMING_RENUMBERED: quantization rewrote the index buffer of a deforming primitive; its positions were held in source space and can no longer be addressed by index."
25236
+ "TN_ASSETS_MODEL_HELD_RENUMBERED: quantization rewrote the index buffer of a primitive whose positions were held in source space, so they can no longer be addressed by index \u2014 a sidecar or a cluster DAG holds those indices."
25197
25237
  );
25198
25238
  releaseAttribute(primitive, position);
25199
25239
  for (const { target, position: delta } of targets) releaseAttribute(target, delta);
@@ -25487,6 +25527,7 @@ async function writeSharedGlb(io, document, logicalPath, uriFor) {
25487
25527
  }
25488
25528
  delete resources[image.uri];
25489
25529
  image.uri = uriFor(bytes);
25530
+ image.name ??= path9.posix.basename(image.uri, path9.posix.extname(image.uri));
25490
25531
  }
25491
25532
  const buffers = json.buffers ?? [];
25492
25533
  const external = buffers.filter((buffer) => buffer.uri !== void 0);
@@ -29004,7 +29045,8 @@ async function parseSpecies(bytes) {
29004
29045
  validateDiscreteLod(doc.getRoot());
29005
29046
  return doc;
29006
29047
  }
29007
- var FAR_LEVEL_KEEP_RATIOS = [0.25, 0.06];
29048
+ var FAR_LEVEL_KEEP_RATIOS = [0.25, 0.06, 0.015, 4e-3];
29049
+ var FAR_LEVEL_MIN_COVERAGE = 0.5;
29008
29050
  function documentTriangles(doc) {
29009
29051
  let total = 0;
29010
29052
  for (const mesh of doc.getRoot().listMeshes())
@@ -29038,7 +29080,7 @@ async function farLevelDocument(bytes, keep) {
29038
29080
  for (const extension of doc.getRoot().listExtensionsUsed())
29039
29081
  if (extension.extensionName === TN_DISCRETE_LOD) extension.dispose();
29040
29082
  try {
29041
- thinFoliageCards(doc, keep);
29083
+ thinCoveringCards(doc, keep, FAR_LEVEL_MIN_COVERAGE);
29042
29084
  } catch (error) {
29043
29085
  if (error instanceof Error && /^thinFoliageCards (requires static|cannot reduce)/.test(error.message))
29044
29086
  return void 0;
@@ -29060,8 +29102,8 @@ async function deriveFarLevels(speciesId, coarsest, firstIndex, maxDistance) {
29060
29102
  if (doc === void 0) return levels;
29061
29103
  const triangles = documentTriangles(doc);
29062
29104
  if (triangles <= 0 || triangles > (1 - LOD_MIN_SAVING) * previous) continue;
29063
- const distance = coarsest.distance * Math.sqrt(anchor / triangles);
29064
- if (maxDistance !== void 0 && distance >= maxDistance) break;
29105
+ const distance = coarsest.distance * Math.sqrt(anchor / triangles) / Math.SQRT2;
29106
+ if (distance >= maxDistance) break;
29065
29107
  const writer = await createGltfWriter();
29066
29108
  levels.push({
29067
29109
  distance: Math.round(distance * 10) / 10,
@@ -29343,7 +29385,15 @@ async function cookTerrainWorld(options) {
29343
29385
  const coarsest = lods.at(-1);
29344
29386
  if (coarsest !== void 0)
29345
29387
  lods.push(
29346
- ...await deriveFarLevels(speciesId, coarsest, lods.length + 1, spec.maxDistance)
29388
+ ...await deriveFarLevels(
29389
+ speciesId,
29390
+ coarsest,
29391
+ lods.length + 1,
29392
+ Math.min(
29393
+ spec.maxDistance ?? Number.POSITIVE_INFINITY,
29394
+ spec.impostorDistance ?? Number.POSITIVE_INFINITY
29395
+ )
29396
+ )
29347
29397
  );
29348
29398
  const streamed = await assembleSpeciesFile(speciesId, nearDoc, lods);
29349
29399
  await generateDiscreteLod(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/assets",
3
- "version": "0.3.14",
3
+ "version": "0.3.17",
4
4
  "license": "MIT",
5
5
  "description": "Content-addressed asset compile step for ThreeNative games.",
6
6
  "keywords": [
@@ -46,12 +46,13 @@
46
46
  "@types/node": "20.19.43",
47
47
  "@types/pngjs": "6.0.5",
48
48
  "@types/three": "0.187.0",
49
+ "@typescript/native": "npm:typescript@7.0.2",
49
50
  "ooz-wasm": "2.0.0",
50
51
  "publint": "0.3.22",
51
52
  "tsup": "8.5.1",
52
53
  "typescript": "npm:@typescript/typescript6@6.0.2",
53
- "@typescript/native": "npm:typescript@7.0.2",
54
- "@threenative/blender-bridge": "0.2.6"
54
+ "@threenative/procedural-environment": "0.1.2",
55
+ "@threenative/blender-bridge": "0.2.9"
55
56
  },
56
57
  "dependencies": {
57
58
  "@gltf-transform/core": "4.4.2",
@@ -69,7 +70,7 @@
69
70
  "three-mesh-bvh": "0.9.14",
70
71
  "wasm-media-encoders": "0.7.0",
71
72
  "xatlasjs": "0.2.0",
72
- "@threenative/terrain": "0.1.9"
73
+ "@threenative/terrain": "0.1.12"
73
74
  },
74
75
  "scripts": {
75
76
  "build": "tsup --config tsup.config.ts && node scripts/copy-basis-encoder.mjs && node scripts/bundle-blender-gpl.mjs && publint",