@threenative/assets 0.3.13 → 0.3.16

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",
@@ -18020,6 +18020,46 @@ function dequantizeAttributeArray(srcArray, componentType, normalized) {
18020
18020
  return dstArray;
18021
18021
  }
18022
18022
  var { TEXTURE_INFO, ROOT: ROOT$1 } = PropertyType;
18023
+ function cloneDocument(source) {
18024
+ const target = new Document().setLogger(source.getLogger());
18025
+ const resolve2 = createDefaultPropertyResolver(target, source);
18026
+ mergeDocuments(target, source, resolve2);
18027
+ target.getRoot().copy(source.getRoot(), resolve2);
18028
+ return target;
18029
+ }
18030
+ function mergeDocuments(target, source, resolve2) {
18031
+ resolve2 ||= createDefaultPropertyResolver(target, source);
18032
+ for (const sourceExtension of source.getRoot().listExtensionsUsed()) {
18033
+ const targetExtension = target.createExtension(sourceExtension.constructor);
18034
+ if (sourceExtension.isRequired()) targetExtension.setRequired(true);
18035
+ }
18036
+ return _copyToDocument(target, source, listNonRootProperties(source), resolve2);
18037
+ }
18038
+ function _copyToDocument(target, source, sourceProperties, resolve2) {
18039
+ resolve2 ||= createDefaultPropertyResolver(target, source);
18040
+ const propertyMap = /* @__PURE__ */ new Map();
18041
+ for (const sourceProp of sourceProperties) if (!propertyMap.has(sourceProp) && sourceProp.propertyType !== TEXTURE_INFO) propertyMap.set(sourceProp, resolve2(sourceProp));
18042
+ for (const [sourceProp, targetProp] of propertyMap.entries()) targetProp.copy(sourceProp, resolve2);
18043
+ return propertyMap;
18044
+ }
18045
+ function createDefaultPropertyResolver(target, source) {
18046
+ const propertyMap = /* @__PURE__ */ new Map([[source.getRoot(), target.getRoot()]]);
18047
+ return (sourceProp) => {
18048
+ if (sourceProp.propertyType === TEXTURE_INFO) return sourceProp;
18049
+ let targetProp = propertyMap.get(sourceProp);
18050
+ if (!targetProp) {
18051
+ const PropertyClass = sourceProp.constructor;
18052
+ targetProp = new PropertyClass(target.getGraph());
18053
+ propertyMap.set(sourceProp, targetProp);
18054
+ }
18055
+ return targetProp;
18056
+ };
18057
+ }
18058
+ function listNonRootProperties(document) {
18059
+ const visited = /* @__PURE__ */ new Set();
18060
+ for (const edge of document.getGraph().listEdges()) visited.add(edge.getChild());
18061
+ return Array.from(visited);
18062
+ }
18023
18063
  function create2() {
18024
18064
  var out = new ARRAY_TYPE2(4);
18025
18065
  if (ARRAY_TYPE2 != Float32Array) {
@@ -19496,6 +19536,7 @@ function textureBindings(root) {
19496
19536
  return {
19497
19537
  height: shape.height,
19498
19538
  key: keys[index] ?? `texture#${String(index)}`,
19539
+ unnamed: texture.getName() === "",
19499
19540
  levels: shape.levels,
19500
19541
  mimeType,
19501
19542
  slots: [...listTextureSlots(texture)].sort(),
@@ -19522,7 +19563,7 @@ function assertNoTextureDrift(source, output, logicalPath) {
19522
19563
  const before = source.textures[index];
19523
19564
  const after = output.textures[index];
19524
19565
  if (before === void 0 || after === void 0) continue;
19525
- if (before.key !== after.key) {
19566
+ if (before.key !== after.key && !before.unnamed) {
19526
19567
  failures.push(`texture ${String(index)} renamed ${before.key} -> ${after.key}`);
19527
19568
  continue;
19528
19569
  }
@@ -19712,6 +19753,7 @@ async function compressEmbeddedTextures(document, logicalPath, options = {}, rec
19712
19753
  const textures = root.listTextures();
19713
19754
  if (textures.length === 0) return void 0;
19714
19755
  const decoderFree = options.decoderFree === true;
19756
+ const retainable = (mime) => UNIVERSAL_IMAGE_CONTAINERS.has(mime) || mime === "image/webp" && options.webp === true;
19715
19757
  const transcoderBytes = Math.max(0, options.transcoderBytes ?? BASIS_TRANSCODER_BYTES);
19716
19758
  const quality = Math.min(255, Math.max(1, Math.round(options.quality ?? DEFAULT_ETC1S_QUALITY)));
19717
19759
  const keys = textureKeys(root);
@@ -19905,7 +19947,7 @@ async function compressEmbeddedTextures(document, logicalPath, options = {}, rec
19905
19947
  floor: options.floor
19906
19948
  }) : void 0;
19907
19949
  const jpegLimit = jpeg !== void 0 && jpeg.buffer.byteLength < image.byteLength ? jpeg.buffer.byteLength : image.byteLength;
19908
- const automatic = !explicit && target.width === decoded.width && target.height === decoded.height && UNIVERSAL_IMAGE_CONTAINERS.has(texture.getMimeType());
19950
+ const automatic = !explicit && target.width === decoded.width && target.height === decoded.height && retainable(texture.getMimeType());
19909
19951
  const charged = automatic && options.astc !== true;
19910
19952
  let selected;
19911
19953
  try {
@@ -19963,7 +20005,7 @@ async function compressEmbeddedTextures(document, logicalPath, options = {}, rec
19963
20005
  if (options.measureQuality !== false) scores[key] = jpeg.quality;
19964
20006
  continue;
19965
20007
  }
19966
- if (encoded === void 0 || encoded.byteLength >= image.byteLength && target.width === decoded.width && target.height === decoded.height && !explicit && UNIVERSAL_IMAGE_CONTAINERS.has(texture.getMimeType())) {
20008
+ if (encoded === void 0 || encoded.byteLength >= image.byteLength && target.width === decoded.width && target.height === decoded.height && !explicit && retainable(texture.getMimeType())) {
19967
20009
  const downsampled = target.width !== decoded.width || target.height !== decoded.height;
19968
20010
  let retained = image;
19969
20011
  if (downsampled) {
@@ -20743,6 +20785,28 @@ function mergeIdenticalMaterials(document) {
20743
20785
  };
20744
20786
  }
20745
20787
 
20788
+ // src/lod/coarse.ts
20789
+ async function coarseDocument(document) {
20790
+ const coarse = cloneDocument(document);
20791
+ let chained = 0;
20792
+ for (const mesh of coarse.getRoot().listMeshes())
20793
+ for (const primitive of mesh.listPrimitives()) {
20794
+ const chain = primitive.getExtension(TN_DISCRETE_LOD);
20795
+ if (chain === null) continue;
20796
+ const coarsest = chain.getIndices().at(-1);
20797
+ primitive.setExtension(TN_DISCRETE_LOD, null);
20798
+ if (coarsest === void 0) continue;
20799
+ primitive.setIndices(coarsest);
20800
+ compactPrimitive(primitive);
20801
+ chained += 1;
20802
+ }
20803
+ if (chained === 0) return void 0;
20804
+ for (const extension of coarse.getRoot().listExtensionsUsed())
20805
+ if (extension.extensionName === TN_DISCRETE_LOD) extension.dispose();
20806
+ await coarse.transform(prune({ propertyTypes: [PropertyType.ACCESSOR] }));
20807
+ return coarse;
20808
+ }
20809
+
20746
20810
  // src/lod/eligibility.ts
20747
20811
  var SUPPORTED_ATTRIBUTES = /* @__PURE__ */ new Set([
20748
20812
  "COLOR_0",
@@ -20889,10 +20953,36 @@ function authoredLodName(name) {
20889
20953
  }
20890
20954
 
20891
20955
  // src/lod/cards.ts
20892
- var MAX_CARD_TRIANGLES = 8;
20956
+ var MAX_CARD_TRIANGLES = 32;
20957
+ var MAX_CARD_SPAN = 0.25;
20958
+ var ALWAYS_CARD_TRIANGLES = 8;
20893
20959
  var CARD_KEEP_RATIOS = [0.5, 0.25];
20894
20960
  var TRIANGLE2 = 3;
20895
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
+ }
20896
20986
  function findCards(positions, indices) {
20897
20987
  const vertexCount = Math.floor(positions.length / 3);
20898
20988
  const parent = new Int32Array(vertexCount);
@@ -20925,9 +21015,10 @@ function findCards(positions, indices) {
20925
21015
  }
20926
21016
  const cards = [];
20927
21017
  const preserved = [];
21018
+ const maxSpan = MAX_CARD_SPAN * diagonalOf(positions, indices, 0, indices.length);
20928
21019
  for (const triangles of grouped.values()) {
20929
21020
  if (triangles.length === 0) continue;
20930
- if (triangles.length > MAX_CARD_TRIANGLES) {
21021
+ if (triangles.length > MAX_CARD_TRIANGLES || triangles.length > ALWAYS_CARD_TRIANGLES && triangleSpan(positions, indices, triangles) > maxSpan) {
20931
21022
  for (const triangle of triangles) preserved.push(triangle);
20932
21023
  continue;
20933
21024
  }
@@ -21661,6 +21752,15 @@ function generateCardsChain(primitive, maxLevels, minSaving) {
21661
21752
  vertexCopies: chain.copies
21662
21753
  };
21663
21754
  }
21755
+ function decodedComponents(accessor, array) {
21756
+ const floats = new Float32Array(array.length);
21757
+ for (let index = 0; index < array.length; index += 1)
21758
+ floats[index] = MathUtils.decodeNormalizedInt(
21759
+ array[index],
21760
+ accessor.getComponentType()
21761
+ );
21762
+ return floats;
21763
+ }
21664
21764
  function appendCardCopies(primitive, copies) {
21665
21765
  const base = primitive.getAttribute("POSITION")?.getCount() ?? 0;
21666
21766
  let added = 0;
@@ -21680,7 +21780,9 @@ function appendCardCopies(primitive, copies) {
21680
21780
  grown.set(array.subarray(vertex * size, vertex * size + size), at * size);
21681
21781
  at += 1;
21682
21782
  }
21683
- const extended = accessor.clone().setArray(grown);
21783
+ const metres = semantic === "POSITION" && accessor.getNormalized();
21784
+ const extended = accessor.clone().setArray(metres ? decodedComponents(accessor, grown) : grown);
21785
+ if (metres) extended.setNormalized(false);
21684
21786
  if (semantic === "POSITION") {
21685
21787
  at = base;
21686
21788
  for (const level of copies)
@@ -23221,11 +23323,14 @@ async function quantizeStaticGeometry(document, quantize2) {
23221
23323
  releaseDeformingMeshes(held);
23222
23324
  }
23223
23325
  }
23326
+ function clusteredMesh(mesh) {
23327
+ return mesh.listPrimitives().some((primitive) => primitive.getExtension(TN_VIRTUAL_GEOMETRY) !== null);
23328
+ }
23224
23329
  function holdDeformingMeshes(document) {
23225
23330
  const skinned = skinnedMeshes(document);
23226
23331
  const held = [];
23227
23332
  for (const mesh of document.getRoot().listMeshes()) {
23228
- if (!deformingMesh(mesh, skinned)) continue;
23333
+ if (!deformingMesh(mesh, skinned) && !clusteredMesh(mesh)) continue;
23229
23334
  const nodes = [];
23230
23335
  for (const parent of mesh.listParents()) {
23231
23336
  if (!(parent instanceof Node)) continue;
@@ -23261,7 +23366,7 @@ function releaseDeformingMeshes(held) {
23261
23366
  for (const { primitive, indices, position, targets } of primitives) {
23262
23367
  if (primitive.getIndices() !== indices)
23263
23368
  throw new Error(
23264
- "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."
23265
23370
  );
23266
23371
  releaseAttribute(primitive, position);
23267
23372
  for (const { target, position: delta } of targets) releaseAttribute(target, delta);
@@ -23391,14 +23496,14 @@ function createSharedImageStore(outputRoot, options = {}) {
23391
23496
  const memory = /* @__PURE__ */ new Map();
23392
23497
  let listing;
23393
23498
  let manifestQuality;
23394
- 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);
23395
23500
  const qualityInManifest = () => {
23396
23501
  manifestQuality ??= (async () => {
23397
23502
  const scores = /* @__PURE__ */ new Map();
23398
23503
  if (outputRoot === void 0) return scores;
23399
23504
  try {
23400
23505
  const manifest = JSON.parse(
23401
- await readFile(path2.join(outputRoot, "assets.manifest.json"), "utf8")
23506
+ await readFile(path6.join(outputRoot, "assets.manifest.json"), "utf8")
23402
23507
  );
23403
23508
  for (const entry of Object.values(manifest.entries ?? {})) {
23404
23509
  if (!Array.isArray(entry?.sharedImages)) continue;
@@ -23444,7 +23549,7 @@ function createSharedImageStore(outputRoot, options = {}) {
23444
23549
  const parsed = parseFileName(name);
23445
23550
  if (parsed === void 0) return void 0;
23446
23551
  const image = {
23447
- buffer: await readFile(path2.join(directory, name)),
23552
+ buffer: await readFile(path6.join(directory, name)),
23448
23553
  codec: parsed.codec,
23449
23554
  mimeType: parsed.mimeType,
23450
23555
  ...await (async () => {
@@ -23452,7 +23557,7 @@ function createSharedImageStore(outputRoot, options = {}) {
23452
23557
  if (cached !== void 0) return { quality: cached };
23453
23558
  try {
23454
23559
  const quality = readTextureQuality(
23455
- JSON.parse(await readFile(path2.join(directory, `${name}.quality.json`), "utf8"))
23560
+ JSON.parse(await readFile(path6.join(directory, `${name}.quality.json`), "utf8"))
23456
23561
  );
23457
23562
  return quality === void 0 ? {} : { quality };
23458
23563
  } catch (error) {
@@ -23464,7 +23569,7 @@ function createSharedImageStore(outputRoot, options = {}) {
23464
23569
  ...await (async () => {
23465
23570
  try {
23466
23571
  return readTranscoderRecord(
23467
- JSON.parse(await readFile(path2.join(directory, `${name}.transcoder.json`), "utf8"))
23572
+ JSON.parse(await readFile(path6.join(directory, `${name}.transcoder.json`), "utf8"))
23468
23573
  );
23469
23574
  } catch (error) {
23470
23575
  if (error.code === "ENOENT" || error instanceof SyntaxError)
@@ -23485,7 +23590,7 @@ function createSharedImageStore(outputRoot, options = {}) {
23485
23590
  if (known.has(key) && image.quality === void 0 && image.transcoderSavings === void 0 && image.transcoderRequired !== true)
23486
23591
  return;
23487
23592
  await mkdir(directory, { recursive: true });
23488
- const target = path2.join(directory, name);
23593
+ const target = path6.join(directory, name);
23489
23594
  const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
23490
23595
  try {
23491
23596
  await writeFile(temporary, image.buffer);
@@ -23526,8 +23631,8 @@ function createSharedImageStore(outputRoot, options = {}) {
23526
23631
  };
23527
23632
  }
23528
23633
  function sharedImageUri(logicalPath, outputPath) {
23529
- const from = path2.posix.dirname(logicalPath.split(path2.sep).join("/"));
23530
- 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);
23531
23636
  return relative.startsWith(".") || from === "." ? relative : `./${relative}`;
23532
23637
  }
23533
23638
  var GLB_MAGIC = 1179937895;
@@ -23538,9 +23643,9 @@ function padded(buffer, fill) {
23538
23643
  return remainder === 0 ? buffer : Buffer.concat([buffer, Buffer.alloc(4 - remainder, fill)]);
23539
23644
  }
23540
23645
  async function writeSharedGlb(io, document, logicalPath, uriFor) {
23541
- const basename = path2.posix.basename(
23542
- logicalPath.split(path2.sep).join("/"),
23543
- path2.extname(logicalPath)
23646
+ const basename = path6.posix.basename(
23647
+ logicalPath.split(path6.sep).join("/"),
23648
+ path6.extname(logicalPath)
23544
23649
  );
23545
23650
  const written = await io.writeJSON(document, { basename, format: Format.GLTF });
23546
23651
  const json = written.json;
@@ -23555,6 +23660,7 @@ async function writeSharedGlb(io, document, logicalPath, uriFor) {
23555
23660
  }
23556
23661
  delete resources[image.uri];
23557
23662
  image.uri = uriFor(bytes);
23663
+ image.name ??= path6.posix.basename(image.uri, path6.posix.extname(image.uri));
23558
23664
  }
23559
23665
  const buffers = json.buffers ?? [];
23560
23666
  const external = buffers.filter((buffer) => buffer.uri !== void 0);
@@ -23658,6 +23764,11 @@ var SHARED_TRANSCODER_ACCOUNTING_VERSION = 1;
23658
23764
  var MODEL_DEDUPE_VERSION = 1;
23659
23765
  var MODEL_REORDER_VERSION = 1;
23660
23766
  var MODEL_QUANTIZE_VERSION = 1;
23767
+ var MODEL_WEBP_RETAIN_VERSION = 1;
23768
+ function keepSmallerSource(textures) {
23769
+ return textures?.webp === true ? `universal-containers+webp-v${String(MODEL_WEBP_RETAIN_VERSION)}` : "universal-containers";
23770
+ }
23771
+ var MODEL_COARSE_COMPANION_VERSION = 1;
23661
23772
  var BBOX_TOLERANCE = 1e-3;
23662
23773
  var SIMPLIFY_BBOX_TOLERANCE = 0.01;
23663
23774
  var SIMPLIFY_RATIO_FLOOR = 0.5;
@@ -24088,6 +24199,9 @@ function modelPass(options = {}) {
24088
24199
  // Same reason again: which positions keep their source metres is part of the output, and a
24089
24200
  // warm entry from before they did would hand a game geometry its sidecars cannot address.
24090
24201
  quantizeVersion: MODEL_QUANTIZE_VERSION,
24202
+ // A warm entry from before the coarse companion carries no `streamedLods`, so a game served
24203
+ // from it never streams: the output gained a file, so the key moves.
24204
+ coarseCompanion: MODEL_COARSE_COMPANION_VERSION,
24091
24205
  // `"none"` and "absent" are different cache keys on purpose: absent bakes with defaults.
24092
24206
  virtual: options.virtual === "none" ? "none" : {
24093
24207
  ...options.virtual === void 0 ? {} : options.virtual,
@@ -24108,7 +24222,7 @@ function modelPass(options = {}) {
24108
24222
  // Retention is now conditioned on the container, so it is spelled out rather than
24109
24223
  // named by a boolean: a warm cache keyed on the old rule would keep shipping the
24110
24224
  // WebP-requiring models this replaced.
24111
- keepSmallerSource: "universal-containers",
24225
+ keepSmallerSource: keepSmallerSource(options.textures),
24112
24226
  overrides: options.textures?.overrides ?? [],
24113
24227
  quality: options.textures?.quality ?? null
24114
24228
  }
@@ -24244,6 +24358,18 @@ function modelPass(options = {}) {
24244
24358
  }
24245
24359
  assertNoTextureDrift(sourceTextures, textureBindings(verified), logicalPath);
24246
24360
  if (lod !== void 0 && lod.generated > 0) validateDiscreteLod(verified);
24361
+ const coarse = lod !== void 0 && lod.generated > 0 ? await coarseDocument(document) : void 0;
24362
+ if (coarse !== void 0) {
24363
+ const written = store === void 0 || shared === void 0 || shared.keys.length === 0 ? await writeAndVerify(coarse, logicalPath, options.vertexLayout) : await writeAndVerifyShared(coarse, logicalPath, store, shared, options.vertexLayout);
24364
+ const stats = reachableStats(written.verified);
24365
+ auxiliaryOutputs.push({
24366
+ buffer: written.buffer,
24367
+ extension: ".glb",
24368
+ manifestField: "streamedLods",
24369
+ metadata: { level: "coarsest", triangles: stats.triangles, vertices: stats.vertices },
24370
+ role: "coarse"
24371
+ });
24372
+ }
24247
24373
  const entry = {
24248
24374
  ...compact === void 0 ? {} : { compact },
24249
24375
  ...embeddedTextures === void 0 ? {} : { embeddedTextures },
@@ -24289,7 +24415,7 @@ function sharedSettings(texture, textureOptions) {
24289
24415
  jpeg: textureOptions.jpeg ?? null,
24290
24416
  jpegLadder: "colour-opaque-q75-90-v1",
24291
24417
  floor: resolveImageQualityFloor(textureOptions.floor),
24292
- keepSmallerSource: "universal-containers",
24418
+ keepSmallerSource: keepSmallerSource(textureOptions),
24293
24419
  maxSize: resolveTextureMaxSize(textureOptions.maxSize, listTextureSlots(texture)),
24294
24420
  overrides: textureOptions.overrides ?? [],
24295
24421
  quality: textureOptions.quality ?? null,
@@ -24352,7 +24478,7 @@ function declareSharedImage(store, logicalPath, auxiliaryOutputs, candidate) {
24352
24478
  const outputPath = store.outputPath(candidate.key, candidate.image);
24353
24479
  auxiliaryOutputs.set(outputPath, {
24354
24480
  buffer: candidate.image.buffer,
24355
- extension: path2.extname(outputPath),
24481
+ extension: path6.extname(outputPath),
24356
24482
  manifestField: "sharedImages",
24357
24483
  metadata: {
24358
24484
  codec: candidate.image.codec,
package/dist/index.d.ts CHANGED
@@ -42,6 +42,13 @@ type TextureMaxSize = number | Readonly<Record<string, number>>;
42
42
  interface IModelTexturesOptions {
43
43
  /** Internal target-selected raw ASTC output. */
44
44
  readonly astc?: boolean;
45
+ /**
46
+ * Internal: every runtime of this target decodes WebP (the web: browsers and the owned Wasm
47
+ * engine), so an authored WebP is a source the cook may keep, and a KTX2 must undercut its bytes
48
+ * to replace it, as it must a JPEG or PNG. PRD-867: without it, Midway's 300 KB WebP
49
+ * metallic-roughness and normal maps became 4 MB UASTC files.
50
+ */
51
+ readonly webp?: boolean;
45
52
  readonly floor?: Partial<IImageQualityFloor>;
46
53
  /** Internal reporting switch; selection still measures and enforces the floor. */
47
54
  readonly measureQuality?: boolean;
@@ -110,6 +117,8 @@ interface IEmbeddedTextureSummary {
110
117
  interface IModelTextureBinding {
111
118
  readonly height: number;
112
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;
113
122
  /** KTX2 mip levels; 1 for a still-uncompressed source image. */
114
123
  readonly levels: number;
115
124
  readonly mimeType: string;
@@ -1550,6 +1559,8 @@ interface ISpeciesSpec {
1550
1559
  };
1551
1560
  readonly lods?: readonly ISpeciesLODSpec[];
1552
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;
1553
1564
  }
1554
1565
  interface ICookTerrainWorldMaterialLayer {
1555
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)}`;
@@ -5214,7 +5215,13 @@ function skippedCompressionRows(entries, layout) {
5214
5215
  bytes,
5215
5216
  files,
5216
5217
  kind,
5217
- ...kind === "model" ? { decoders: layout.modelCompressionDecoders } : {},
5218
+ // The decoders this target lacks, not every one the model pass would use: a target that
5219
+ // decodes meshopt but not KTX2 withheld only KTX2 (PRD-861).
5220
+ ...kind === "model" ? {
5221
+ decoders: layout.modelCompressionDecoders.filter(
5222
+ (decoder) => decoder === "KTX2" ? !layout.runtimeDecoderCapabilities.ktx2 : !layout.runtimeDecoderCapabilities.meshopt
5223
+ )
5224
+ } : {},
5218
5225
  reason
5219
5226
  });
5220
5227
  }
@@ -16535,6 +16542,13 @@ function dequantizeAttributeArray(srcArray, componentType, normalized) {
16535
16542
  }
16536
16543
  var { TEXTURE_INFO, ROOT: ROOT$1 } = PropertyType;
16537
16544
  var NO_TRANSFER_TYPES = /* @__PURE__ */ new Set([TEXTURE_INFO, ROOT$1]);
16545
+ function cloneDocument(source) {
16546
+ const target = new Document().setLogger(source.getLogger());
16547
+ const resolve2 = createDefaultPropertyResolver(target, source);
16548
+ mergeDocuments(target, source, resolve2);
16549
+ target.getRoot().copy(source.getRoot(), resolve2);
16550
+ return target;
16551
+ }
16538
16552
  function mergeDocuments(target, source, resolve2) {
16539
16553
  resolve2 ||= createDefaultPropertyResolver(target, source);
16540
16554
  for (const sourceExtension of source.getRoot().listExtensionsUsed()) {
@@ -18839,10 +18853,36 @@ function virtualGeometryBytes(virtual) {
18839
18853
  }
18840
18854
 
18841
18855
  // src/lod/cards.ts
18842
- var MAX_CARD_TRIANGLES = 8;
18856
+ var MAX_CARD_TRIANGLES = 32;
18857
+ var MAX_CARD_SPAN = 0.25;
18858
+ var ALWAYS_CARD_TRIANGLES = 8;
18843
18859
  var CARD_KEEP_RATIOS = [0.5, 0.25];
18844
18860
  var TRIANGLE = 3;
18845
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
+ }
18846
18886
  function findCards(positions, indices) {
18847
18887
  const vertexCount = Math.floor(positions.length / 3);
18848
18888
  const parent = new Int32Array(vertexCount);
@@ -18875,9 +18915,10 @@ function findCards(positions, indices) {
18875
18915
  }
18876
18916
  const cards = [];
18877
18917
  const preserved = [];
18918
+ const maxSpan = MAX_CARD_SPAN * diagonalOf(positions, indices, 0, indices.length);
18878
18919
  for (const triangles of grouped.values()) {
18879
18920
  if (triangles.length === 0) continue;
18880
- if (triangles.length > MAX_CARD_TRIANGLES) {
18921
+ if (triangles.length > MAX_CARD_TRIANGLES || triangles.length > ALWAYS_CARD_TRIANGLES && triangleSpan(positions, indices, triangles) > maxSpan) {
18881
18922
  for (const triangle of triangles) preserved.push(triangle);
18882
18923
  continue;
18883
18924
  }
@@ -19954,6 +19995,15 @@ function generateCardsChain(primitive, maxLevels, minSaving) {
19954
19995
  vertexCopies: chain.copies
19955
19996
  };
19956
19997
  }
19998
+ function decodedComponents(accessor, array) {
19999
+ const floats = new Float32Array(array.length);
20000
+ for (let index = 0; index < array.length; index += 1)
20001
+ floats[index] = MathUtils.decodeNormalizedInt(
20002
+ array[index],
20003
+ accessor.getComponentType()
20004
+ );
20005
+ return floats;
20006
+ }
19957
20007
  function appendCardCopies(primitive, copies) {
19958
20008
  const base = primitive.getAttribute("POSITION")?.getCount() ?? 0;
19959
20009
  let added = 0;
@@ -19973,7 +20023,9 @@ function appendCardCopies(primitive, copies) {
19973
20023
  grown.set(array.subarray(vertex * size, vertex * size + size), at * size);
19974
20024
  at += 1;
19975
20025
  }
19976
- const extended = accessor.clone().setArray(grown);
20026
+ const metres = semantic === "POSITION" && accessor.getNormalized();
20027
+ const extended = accessor.clone().setArray(metres ? decodedComponents(accessor, grown) : grown);
20028
+ if (metres) extended.setNormalized(false);
19977
20029
  if (semantic === "POSITION") {
19978
20030
  at = base;
19979
20031
  for (const level of copies)
@@ -19984,6 +20036,9 @@ function appendCardCopies(primitive, copies) {
19984
20036
  }
19985
20037
  }
19986
20038
  function thinFoliageCards(document, keepRatio) {
20039
+ return thinCoveringCards(document, keepRatio, 0);
20040
+ }
20041
+ function thinCoveringCards(document, keepRatio, minCoverage) {
19987
20042
  if (!Number.isFinite(keepRatio) || keepRatio <= 0 || keepRatio >= 1)
19988
20043
  throw new Error("thinFoliageCards keepRatio must be in (0, 1).");
19989
20044
  let reduced = 0;
@@ -20006,6 +20061,11 @@ function thinFoliageCards(document, keepRatio) {
20006
20061
  );
20007
20062
  if (chain === null)
20008
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
+ );
20009
20069
  appendCardCopies(primitive, chain.copies);
20010
20070
  primitive.setIndices(
20011
20071
  (primitive.getIndices() ?? document.createAccessor().setType("SCALAR").setBuffer(primitive.getAttribute("POSITION").getBuffer())).clone().setArray(chain.indices.at(-1))
@@ -20908,6 +20968,7 @@ function textureBindings(root) {
20908
20968
  return {
20909
20969
  height: shape.height,
20910
20970
  key: keys[index] ?? `texture#${String(index)}`,
20971
+ unnamed: texture.getName() === "",
20911
20972
  levels: shape.levels,
20912
20973
  mimeType,
20913
20974
  slots: [...listTextureSlots(texture)].sort(),
@@ -20934,7 +20995,7 @@ function assertNoTextureDrift(source, output, logicalPath) {
20934
20995
  const before = source.textures[index];
20935
20996
  const after = output.textures[index];
20936
20997
  if (before === void 0 || after === void 0) continue;
20937
- if (before.key !== after.key) {
20998
+ if (before.key !== after.key && !before.unnamed) {
20938
20999
  failures.push(`texture ${String(index)} renamed ${before.key} -> ${after.key}`);
20939
21000
  continue;
20940
21001
  }
@@ -21124,6 +21185,7 @@ async function compressEmbeddedTextures(document, logicalPath, options = {}, rec
21124
21185
  const textures = root.listTextures();
21125
21186
  if (textures.length === 0) return void 0;
21126
21187
  const decoderFree = options.decoderFree === true;
21188
+ const retainable = (mime) => UNIVERSAL_IMAGE_CONTAINERS.has(mime) || mime === "image/webp" && options.webp === true;
21127
21189
  const transcoderBytes = Math.max(0, options.transcoderBytes ?? BASIS_TRANSCODER_BYTES);
21128
21190
  const quality2 = Math.min(255, Math.max(1, Math.round(options.quality ?? DEFAULT_ETC1S_QUALITY)));
21129
21191
  const keys = textureKeys(root);
@@ -21317,7 +21379,7 @@ async function compressEmbeddedTextures(document, logicalPath, options = {}, rec
21317
21379
  floor: options.floor
21318
21380
  }) : void 0;
21319
21381
  const jpegLimit = jpeg !== void 0 && jpeg.buffer.byteLength < image.byteLength ? jpeg.buffer.byteLength : image.byteLength;
21320
- const automatic = !explicit && target.width === decoded.width && target.height === decoded.height && UNIVERSAL_IMAGE_CONTAINERS.has(texture.getMimeType());
21382
+ const automatic = !explicit && target.width === decoded.width && target.height === decoded.height && retainable(texture.getMimeType());
21321
21383
  const charged = automatic && options.astc !== true;
21322
21384
  let selected;
21323
21385
  try {
@@ -21375,7 +21437,7 @@ async function compressEmbeddedTextures(document, logicalPath, options = {}, rec
21375
21437
  if (options.measureQuality !== false) scores[key] = jpeg.quality;
21376
21438
  continue;
21377
21439
  }
21378
- if (encoded === void 0 || encoded.byteLength >= image.byteLength && target.width === decoded.width && target.height === decoded.height && !explicit && UNIVERSAL_IMAGE_CONTAINERS.has(texture.getMimeType())) {
21440
+ if (encoded === void 0 || encoded.byteLength >= image.byteLength && target.width === decoded.width && target.height === decoded.height && !explicit && retainable(texture.getMimeType())) {
21379
21441
  const downsampled = target.width !== decoded.width || target.height !== decoded.height;
21380
21442
  let retained = image;
21381
21443
  if (downsampled) {
@@ -22013,9 +22075,9 @@ function parseModelQuantize(raw) {
22013
22075
  }
22014
22076
  return raw;
22015
22077
  }
22016
- function embeddedTexturesFor(configured, ktx2, astc = false) {
22078
+ function embeddedTexturesFor(configured, ktx2, astc = false, webp = false) {
22017
22079
  if (astc && configured !== "none") return { textures: { ...configured, astc: true } };
22018
- if (ktx2) return {};
22080
+ if (ktx2) return webp && configured !== "none" ? { textures: { ...configured, webp: true } } : {};
22019
22081
  if (configured !== void 0 && configured !== "none" && configured.maxSize !== void 0) {
22020
22082
  return {
22021
22083
  textures: {
@@ -24035,6 +24097,28 @@ function createLightmapPass(options, astc = false) {
24035
24097
  };
24036
24098
  }
24037
24099
 
24100
+ // src/lod/coarse.ts
24101
+ async function coarseDocument(document) {
24102
+ const coarse = cloneDocument(document);
24103
+ let chained = 0;
24104
+ for (const mesh of coarse.getRoot().listMeshes())
24105
+ for (const primitive of mesh.listPrimitives()) {
24106
+ const chain = primitive.getExtension(TN_DISCRETE_LOD);
24107
+ if (chain === null) continue;
24108
+ const coarsest = chain.getIndices().at(-1);
24109
+ primitive.setExtension(TN_DISCRETE_LOD, null);
24110
+ if (coarsest === void 0) continue;
24111
+ primitive.setIndices(coarsest);
24112
+ compactPrimitive(primitive);
24113
+ chained += 1;
24114
+ }
24115
+ if (chained === 0) return void 0;
24116
+ for (const extension of coarse.getRoot().listExtensionsUsed())
24117
+ if (extension.extensionName === TN_DISCRETE_LOD) extension.dispose();
24118
+ await coarse.transform(prune({ propertyTypes: [PropertyType.ACCESSOR] }));
24119
+ return coarse;
24120
+ }
24121
+
24038
24122
  // src/virtual/partition.ts
24039
24123
  function edgeKey(a, b) {
24040
24124
  return a < b ? a * 4294967296 + b : b * 4294967296 + a;
@@ -25106,11 +25190,14 @@ async function quantizeStaticGeometry(document, quantize2) {
25106
25190
  releaseDeformingMeshes(held);
25107
25191
  }
25108
25192
  }
25193
+ function clusteredMesh(mesh) {
25194
+ return mesh.listPrimitives().some((primitive) => primitive.getExtension(TN_VIRTUAL_GEOMETRY) !== null);
25195
+ }
25109
25196
  function holdDeformingMeshes(document) {
25110
25197
  const skinned = skinnedMeshes(document);
25111
25198
  const held = [];
25112
25199
  for (const mesh of document.getRoot().listMeshes()) {
25113
- if (!deformingMesh(mesh, skinned)) continue;
25200
+ if (!deformingMesh(mesh, skinned) && !clusteredMesh(mesh)) continue;
25114
25201
  const nodes = [];
25115
25202
  for (const parent of mesh.listParents()) {
25116
25203
  if (!(parent instanceof Node)) continue;
@@ -25146,7 +25233,7 @@ function releaseDeformingMeshes(held) {
25146
25233
  for (const { primitive, indices, position, targets } of primitives) {
25147
25234
  if (primitive.getIndices() !== indices)
25148
25235
  throw new Error(
25149
- "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."
25150
25237
  );
25151
25238
  releaseAttribute(primitive, position);
25152
25239
  for (const { target, position: delta } of targets) releaseAttribute(target, delta);
@@ -25440,6 +25527,7 @@ async function writeSharedGlb(io, document, logicalPath, uriFor) {
25440
25527
  }
25441
25528
  delete resources[image.uri];
25442
25529
  image.uri = uriFor(bytes);
25530
+ image.name ??= path9.posix.basename(image.uri, path9.posix.extname(image.uri));
25443
25531
  }
25444
25532
  const buffers = json.buffers ?? [];
25445
25533
  const external = buffers.filter((buffer) => buffer.uri !== void 0);
@@ -25543,6 +25631,11 @@ var SHARED_TRANSCODER_ACCOUNTING_VERSION = 1;
25543
25631
  var MODEL_DEDUPE_VERSION = 1;
25544
25632
  var MODEL_REORDER_VERSION = 1;
25545
25633
  var MODEL_QUANTIZE_VERSION = 1;
25634
+ var MODEL_WEBP_RETAIN_VERSION = 1;
25635
+ function keepSmallerSource(textures) {
25636
+ return textures?.webp === true ? `universal-containers+webp-v${String(MODEL_WEBP_RETAIN_VERSION)}` : "universal-containers";
25637
+ }
25638
+ var MODEL_COARSE_COMPANION_VERSION = 1;
25546
25639
  var BBOX_TOLERANCE = 1e-3;
25547
25640
  var SIMPLIFY_BBOX_TOLERANCE = 0.01;
25548
25641
  var SIMPLIFY_RATIO_FLOOR = 0.5;
@@ -25973,6 +26066,9 @@ function modelPass(options = {}) {
25973
26066
  // Same reason again: which positions keep their source metres is part of the output, and a
25974
26067
  // warm entry from before they did would hand a game geometry its sidecars cannot address.
25975
26068
  quantizeVersion: MODEL_QUANTIZE_VERSION,
26069
+ // A warm entry from before the coarse companion carries no `streamedLods`, so a game served
26070
+ // from it never streams: the output gained a file, so the key moves.
26071
+ coarseCompanion: MODEL_COARSE_COMPANION_VERSION,
25976
26072
  // `"none"` and "absent" are different cache keys on purpose: absent bakes with defaults.
25977
26073
  virtual: options.virtual === "none" ? "none" : {
25978
26074
  ...options.virtual === void 0 ? {} : options.virtual,
@@ -25993,7 +26089,7 @@ function modelPass(options = {}) {
25993
26089
  // Retention is now conditioned on the container, so it is spelled out rather than
25994
26090
  // named by a boolean: a warm cache keyed on the old rule would keep shipping the
25995
26091
  // WebP-requiring models this replaced.
25996
- keepSmallerSource: "universal-containers",
26092
+ keepSmallerSource: keepSmallerSource(options.textures),
25997
26093
  overrides: options.textures?.overrides ?? [],
25998
26094
  quality: options.textures?.quality ?? null
25999
26095
  }
@@ -26129,6 +26225,18 @@ function modelPass(options = {}) {
26129
26225
  }
26130
26226
  assertNoTextureDrift(sourceTextures, textureBindings(verified), logicalPath);
26131
26227
  if (lod !== void 0 && lod.generated > 0) validateDiscreteLod(verified);
26228
+ const coarse = lod !== void 0 && lod.generated > 0 ? await coarseDocument(document) : void 0;
26229
+ if (coarse !== void 0) {
26230
+ const written = store === void 0 || shared === void 0 || shared.keys.length === 0 ? await writeAndVerify(coarse, logicalPath, options.vertexLayout) : await writeAndVerifyShared(coarse, logicalPath, store, shared, options.vertexLayout);
26231
+ const stats = reachableStats(written.verified);
26232
+ auxiliaryOutputs.push({
26233
+ buffer: written.buffer,
26234
+ extension: ".glb",
26235
+ manifestField: "streamedLods",
26236
+ metadata: { level: "coarsest", triangles: stats.triangles, vertices: stats.vertices },
26237
+ role: "coarse"
26238
+ });
26239
+ }
26132
26240
  const entry = {
26133
26241
  ...compact === void 0 ? {} : { compact },
26134
26242
  ...embeddedTextures === void 0 ? {} : { embeddedTextures },
@@ -26174,7 +26282,7 @@ function sharedSettings(texture, textureOptions) {
26174
26282
  jpeg: textureOptions.jpeg ?? null,
26175
26283
  jpegLadder: "colour-opaque-q75-90-v1",
26176
26284
  floor: resolveImageQualityFloor(textureOptions.floor),
26177
- keepSmallerSource: "universal-containers",
26285
+ keepSmallerSource: keepSmallerSource(textureOptions),
26178
26286
  maxSize: resolveTextureMaxSize(textureOptions.maxSize, listTextureSlots(texture)),
26179
26287
  overrides: textureOptions.overrides ?? [],
26180
26288
  quality: textureOptions.quality ?? null,
@@ -26379,7 +26487,8 @@ function resolveLayout(cwd, options) {
26379
26487
  ...embeddedTexturesFor(
26380
26488
  configuredModels.textures,
26381
26489
  runtimeDecoderCapabilities.ktx2,
26382
- mobileAstc
26490
+ mobileAstc,
26491
+ options.platform === "web"
26383
26492
  )
26384
26493
  };
26385
26494
  const textures = configuredTextures === void 0 ? void 0 : mobileAstc ? { ...configuredTextures, astc: true } : configuredTextures;
@@ -26952,11 +27061,7 @@ async function nativePackageEntries(outputRoot, entries, cookOutputs) {
26952
27061
  if (bookkeeping.has(relative) || cookOutputs.has(relative) || isLeftover(relative)) continue;
26953
27062
  const data = await readFile(path9.join(outputRoot, relative));
26954
27063
  const name = `/${relative}`;
26955
- if (data.length === 0) {
26956
- skipped += 1;
26957
- continue;
26958
- }
26959
- const texture = await nativeTextureEntry(name, data);
27064
+ const texture = data.length === 0 ? void 0 : await nativeTextureEntry(name, data);
26960
27065
  const scene = data.length >= 4 && data.toString("latin1", 0, 4) === "glTF";
26961
27066
  specs.push(
26962
27067
  texture ?? {
@@ -27392,7 +27497,7 @@ function formatSkippedCompression(rows) {
27392
27497
  return `TN_ASSETS_PASS_SKIPPED ${row.pass}: omitted because the pass declares needsRuntimeDecoder=true and this target has no runtime decoder (reason: platform).`;
27393
27498
  }
27394
27499
  const decoders = (row.decoders ?? (row.kind === "model" ? ["meshopt", "KTX2"] : ["KTX2"])).join(" and ");
27395
- const action = row.kind === "model" && row.reason === "platform" ? "retained without decoder-backed compression while decoder-free model passes still ran" : "shipped as authored";
27500
+ const action = row.kind !== "model" || row.reason !== "platform" ? "shipped as authored" : decoders === "KTX2" ? "kept its textures out of KTX2 while meshopt and the decoder-free model passes ran" : "retained without decoder-backed compression while decoder-free model passes still ran";
27396
27501
  const reason = row.reason === "config" ? `assets.${row.kind}s is "none"` : `this target has no qualified ${decoders} decoder`;
27397
27502
  return `TN_ASSETS_COMPRESSION_SKIPPED ${row.kind}: ${String(row.files)} file(s), ${(row.bytes / 1e6).toFixed(1)} MB ${action} because ${reason}.`;
27398
27503
  });
@@ -28940,7 +29045,8 @@ async function parseSpecies(bytes) {
28940
29045
  validateDiscreteLod(doc.getRoot());
28941
29046
  return doc;
28942
29047
  }
28943
- 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;
28944
29050
  function documentTriangles(doc) {
28945
29051
  let total = 0;
28946
29052
  for (const mesh of doc.getRoot().listMeshes())
@@ -28974,7 +29080,7 @@ async function farLevelDocument(bytes, keep) {
28974
29080
  for (const extension of doc.getRoot().listExtensionsUsed())
28975
29081
  if (extension.extensionName === TN_DISCRETE_LOD) extension.dispose();
28976
29082
  try {
28977
- thinFoliageCards(doc, keep);
29083
+ thinCoveringCards(doc, keep, FAR_LEVEL_MIN_COVERAGE);
28978
29084
  } catch (error) {
28979
29085
  if (error instanceof Error && /^thinFoliageCards (requires static|cannot reduce)/.test(error.message))
28980
29086
  return void 0;
@@ -28996,8 +29102,8 @@ async function deriveFarLevels(speciesId, coarsest, firstIndex, maxDistance) {
28996
29102
  if (doc === void 0) return levels;
28997
29103
  const triangles = documentTriangles(doc);
28998
29104
  if (triangles <= 0 || triangles > (1 - LOD_MIN_SAVING) * previous) continue;
28999
- const distance = coarsest.distance * Math.sqrt(anchor / triangles);
29000
- if (maxDistance !== void 0 && distance >= maxDistance) break;
29105
+ const distance = coarsest.distance * Math.sqrt(anchor / triangles) / Math.SQRT2;
29106
+ if (distance >= maxDistance) break;
29001
29107
  const writer = await createGltfWriter();
29002
29108
  levels.push({
29003
29109
  distance: Math.round(distance * 10) / 10,
@@ -29279,7 +29385,15 @@ async function cookTerrainWorld(options) {
29279
29385
  const coarsest = lods.at(-1);
29280
29386
  if (coarsest !== void 0)
29281
29387
  lods.push(
29282
- ...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
+ )
29283
29397
  );
29284
29398
  const streamed = await assembleSpeciesFile(speciesId, nearDoc, lods);
29285
29399
  await generateDiscreteLod(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/assets",
3
- "version": "0.3.13",
3
+ "version": "0.3.16",
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.5"
54
+ "@threenative/blender-bridge": "0.2.8",
55
+ "@threenative/procedural-vegetation": "0.1.1"
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.8"
73
+ "@threenative/terrain": "0.1.11"
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",