@needle-tools/gltf-build-pipeline 1.6.0-alpha.7 → 2.1.0-alpha

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.
@@ -2,11 +2,13 @@ import micromatch from 'micromatch';
2
2
  import os from 'os';
3
3
  import semver from 'semver';
4
4
  import tmp from 'tmp';
5
+ import { ETC1S_DEFAULTS, UASTC_DEFAULTS } from "@gltf-transform/cli";
5
6
  import { TextureChannel } from '@gltf-transform/core';
6
7
  // import { TextureBasisu } from '@gltf-transform/extensions';
7
8
  // import { getTextureChannelMask, listTextureSlots } from '@gltf-transform/functions';
8
9
  import { execSync } from 'child_process';
9
10
  import { spawn, commandExists, waitExit, MICROMATCH_OPTIONS } from './util.js';
11
+ import { TextureResizeFilter, getTextureColorSpace } from '@gltf-transform/functions';
10
12
  // import { existsSync, mkdirSync } from 'fs';
11
13
  // import { tryGetFromCache, getKey, addToCache } from '../cache';
12
14
  // import { resizeTextureIfNecessary } from "./needle_texture_transform"
@@ -14,14 +16,6 @@ tmp.setGracefulCleanup();
14
16
  const NUM_CPUS = os.cpus().length || 1; // microsoft/vscode#112122
15
17
  const KTX_SOFTWARE_VERSION_MIN = '4.0.0-rc1';
16
18
  const KTX_SOFTWARE_VERSION_ACTIVE = '4.1.0-rc1';
17
- const { R, G } = TextureChannel;
18
- /**********************************************************************************************
19
- * Interfaces.
20
- */
21
- export const Mode = {
22
- ETC1S: 'etc1s',
23
- UASTC: 'uastc',
24
- };
25
19
  export const Filter = {
26
20
  BOX: 'box',
27
21
  TENT: 'tent',
@@ -41,128 +35,115 @@ export const Filter = {
41
35
  QUADRATIC_MIX: 'quadratic_mix',
42
36
  };
43
37
  const GLOBAL_DEFAULTS = {
38
+ resizeFilter: TextureResizeFilter.LANCZOS3,
44
39
  filter: Filter.LANCZOS4,
45
40
  filterScale: 1,
46
- powerOfTwo: false,
47
- slots: '*',
41
+ pattern: null,
42
+ slots: null,
48
43
  // See: https://github.com/donmccurdy/glTF-Transform/pull/389#issuecomment-1089842185
49
44
  jobs: 2 * NUM_CPUS,
45
+ cleanup: true,
46
+ limitInputPixels: true,
50
47
  };
51
- export const ETC1S_DEFAULTS = {
52
- quality: 128,
53
- compression: 1,
54
- ...GLOBAL_DEFAULTS,
55
- };
56
- export const UASTC_DEFAULTS = {
57
- level: 2,
58
- rdo: 0,
59
- rdoDictionarySize: 32768,
60
- rdoBlockScale: 10.0,
61
- rdoStdDev: 18.0,
62
- rdoMultithreading: true,
63
- zstd: 18,
64
- ...GLOBAL_DEFAULTS,
48
+ const { R, G, A } = TextureChannel;
49
+ /**********************************************************************************************
50
+ * Interfaces.
51
+ */
52
+ export const Mode = {
53
+ ETC1S: 'etc1s',
54
+ UASTC: 'uastc',
65
55
  };
66
56
  /**********************************************************************************************
67
57
  * Utilities.
68
58
  */
69
59
  /** Create CLI parameters from the given options. Attempts to write only non-default options. */
70
- export function createParams(slots, channels, size, logger, numTextures, options, version) {
71
- const params = [];
72
- params.push('--genmipmap');
73
- if (options.filter !== GLOBAL_DEFAULTS.filter)
74
- params.push('--filter', options.filter);
60
+ export function createParams(texture, slots, channels, size, logger, numTextures, options) {
61
+ const colorSpace = getTextureColorSpace(texture);
62
+ const params = ['--generate-mipmap'];
63
+ if (options.filter !== GLOBAL_DEFAULTS.filter) {
64
+ params.push('--mipmap-filter', options.filter);
65
+ }
75
66
  if (options.filterScale !== GLOBAL_DEFAULTS.filterScale) {
76
- params.push('--fscale', options.filterScale);
67
+ params.push('--mipmap-filter-scale', options.filterScale);
77
68
  }
69
+ // See: https://github.com/KhronosGroup/KTX-Software/issues/600
70
+ const isNormalMap = slots.find((slot) => micromatch.isMatch(slot, '*normal*', MICROMATCH_OPTIONS));
78
71
  if (options.mode === Mode.UASTC) {
79
72
  const _options = options;
80
- params.push('--uastc', _options.level);
81
- if (_options.rdo !== UASTC_DEFAULTS.rdo) {
82
- params.push('--uastc_rdo_l', _options.rdo);
83
- }
84
- if (_options.rdoDictionarySize !== UASTC_DEFAULTS.rdoDictionarySize) {
85
- params.push('--uastc_rdo_d', _options.rdoDictionarySize);
86
- }
87
- if (_options.rdoBlockScale !== UASTC_DEFAULTS.rdoBlockScale) {
88
- params.push('--uastc_rdo_b', _options.rdoBlockScale);
89
- }
90
- if (_options.rdoStdDev !== UASTC_DEFAULTS.rdoStdDev) {
91
- params.push('--uastc_rdo_s', _options.rdoStdDev);
73
+ params.push('--encode', 'uastc');
74
+ params.push('--uastc-quality', _options.level);
75
+ if (_options.rdo && !isNormalMap) {
76
+ params.push('--uastc-rdo');
77
+ if (_options.rdoLambda !== UASTC_DEFAULTS.rdoLambda) {
78
+ params.push('--uastc-rdo-l', _options.rdoLambda);
79
+ }
80
+ if (_options.rdoDictionarySize !== UASTC_DEFAULTS.rdoDictionarySize) {
81
+ params.push('--uastc-rdo-d', _options.rdoDictionarySize);
82
+ }
83
+ if (_options.rdoBlockScale !== UASTC_DEFAULTS.rdoBlockScale) {
84
+ params.push('--uastc-rdo-b', _options.rdoBlockScale);
85
+ }
86
+ if (_options.rdoStdDev !== UASTC_DEFAULTS.rdoStdDev) {
87
+ params.push('--uastc-rdo-s', _options.rdoStdDev);
88
+ }
89
+ if (!_options.rdoMultithreading) {
90
+ params.push('--uastc-rdo-m');
91
+ }
92
+ }
93
+ if (_options.zstd && _options.zstd > 0) {
94
+ params.push('--zstd', _options.zstd);
92
95
  }
93
- if (!_options.rdoMultithreading) {
94
- params.push('--uastc_rdo_m');
95
- }
96
- if (_options.zstd && _options.zstd > 0)
97
- params.push('--zcmp', _options.zstd);
98
96
  }
99
97
  else {
100
98
  const _options = options;
101
- params.push('--bcmp');
99
+ params.push('--encode', 'basis-lz');
102
100
  if (_options.quality !== ETC1S_DEFAULTS.quality) {
103
101
  params.push('--qlevel', _options.quality);
104
102
  }
105
103
  if (_options.compression !== ETC1S_DEFAULTS.compression) {
106
104
  params.push('--clevel', _options.compression);
107
105
  }
108
- if (_options.maxEndpoints)
109
- params.push('--max_endpoints', _options.maxEndpoints);
110
- if (_options.maxSelectors)
111
- params.push('--max_selectors', _options.maxSelectors);
112
- if (_options.rdoOff) {
113
- params.push('--no_endpoint_rdo', '--no_selector_rdo');
106
+ if (_options.rdo && !isNormalMap) {
107
+ if (_options.maxEndpoints !== ETC1S_DEFAULTS.maxEndpoints) {
108
+ params.push('--max-endpoints', _options.maxEndpoints);
109
+ }
110
+ if (_options.maxSelectors !== ETC1S_DEFAULTS.maxSelectors) {
111
+ params.push('--max-selectors', _options.maxSelectors);
112
+ }
113
+ if (_options.rdoThreshold !== ETC1S_DEFAULTS.rdoThreshold) {
114
+ params.push('--endpoint-rdo-threshold', _options.rdoThreshold);
115
+ params.push('--selector-rdo-threshold', _options.rdoThreshold);
116
+ }
114
117
  }
115
- else if (_options.rdoThreshold) {
116
- params.push('--endpoint_rdo_threshold', _options.rdoThreshold);
117
- params.push('--selector_rdo_threshold', _options.rdoThreshold);
118
+ else {
119
+ params.push('--no-endpoint-rdo', '--no-selector-rdo');
118
120
  }
119
121
  }
120
- if (slots.find((slot) => micromatch.isMatch(slot, '*normal*', MICROMATCH_OPTIONS))) {
121
- // See: https://github.com/KhronosGroup/KTX-Software/issues/600
122
- if (semver.gte(version, KTX_SOFTWARE_VERSION_ACTIVE)) {
123
- params.push('--normal_mode', '--input_swizzle', 'rgb1');
124
- }
125
- else if (options.mode === Mode.ETC1S) {
126
- params.push('--normal_map');
127
- }
122
+ // See: https://github.com/donmccurdy/glTF-Transform/issues/215
123
+ if (colorSpace === 'srgb') {
124
+ params.push('--assign-oetf', 'srgb', '--assign-primaries', 'bt709');
128
125
  }
129
- if (slots.length && !slots.find((slot) => micromatch.isMatch(slot, '*{color,emissive}*', MICROMATCH_OPTIONS))) {
130
- // See: https://github.com/donmccurdy/glTF-Transform/issues/215
131
- params.push('--assign_oetf', 'linear', '--assign_primaries', 'none');
126
+ else if (colorSpace === 'srgb-linear') {
127
+ params.push('--assign-oetf', 'linear', '--assign-primaries', 'bt709');
128
+ }
129
+ else if (slots.length && !colorSpace) {
130
+ params.push('--assign-oetf', 'linear', '--assign-primaries', 'none');
132
131
  }
133
132
  if (channels === R) {
134
- params.push('--target_type', 'R');
133
+ params.push('--format', 'R8_UNORM');
135
134
  }
136
135
  else if (channels === G || channels === (R | G)) {
137
- params.push('--target_type', 'RG');
136
+ params.push('--format', 'R8G8_UNORM');
138
137
  }
139
- // Minimum size on any dimension is 4px.
140
- // See: https://github.com/donmccurdy/glTF-Transform/issues/502
141
- let width;
142
- let height;
143
- if (options.powerOfTwo) {
144
- width = preferredPowerOfTwo(size[0]);
145
- height = preferredPowerOfTwo(size[1]);
138
+ else if (!(channels & A)) {
139
+ params.push('--format', colorSpace === 'srgb' ? 'R8G8B8_SRGB' : 'R8G8B8_UNORM');
146
140
  }
147
141
  else {
148
- if (!isPowerOfTwo(size[0]) || !isPowerOfTwo(size[1])) {
149
- logger.warn(`toktx: Texture dimensions ${size[0]}x${size[1]} are NPOT, and may` +
150
- ' fail in older APIs (including WebGL 1.0) on certain devices.');
151
- }
152
- width = isMultipleOfFour(size[0]) ? size[0] : ceilMultipleOfFour(size[0]);
153
- height = isMultipleOfFour(size[1]) ? size[1] : ceilMultipleOfFour(size[1]);
154
- }
155
- if (width !== size[0] || height !== size[1]) {
156
- if (width > 4096 || height > 4096) {
157
- logger.warn(`toktx: Resizing to nearest power of two, ${width}x${height}px. Texture dimensions` +
158
- ' greater than 4096px may not render on some mobile devices.' +
159
- ' Resize to a lower resolution before compressing, if needed.');
160
- }
161
- params.push('--resize', `${width}x${height}`);
142
+ params.push('--format', colorSpace === 'srgb' ? 'R8G8B8A8_SRGB' : 'R8G8B8A8_UNORM');
162
143
  }
163
144
  if (options.jobs && options.jobs > 1 && numTextures > 1) {
164
145
  // See: https://github.com/donmccurdy/glTF-Transform/pull/389#issuecomment-1089842185
165
- const threads = Math.max(2, Math.min(NUM_CPUS, (3 * NUM_CPUS) / numTextures));
146
+ const threads = Math.max(2, Math.min(NUM_CPUS, Math.round((3 * NUM_CPUS) / numTextures)));
166
147
  params.push('--threads', threads);
167
148
  }
168
149
  return params;
@@ -1,4 +1,5 @@
1
1
  export declare function getFileName(filepath: string): string;
2
+ export declare function getDirName(filepath: string): string;
2
3
  export declare type GLTFFileCallback = (file: string) => void | Promise<void>;
3
4
  export declare function foreachGLTF(args: string | string[], callback: GLTFFileCallback): Promise<void>;
4
5
  export declare function replaceExtension(filepath: string, newExtension: string): string;
@@ -4,6 +4,15 @@ export function getFileName(filepath) {
4
4
  const parts = filepath.replaceAll("\\", "/").split("/");
5
5
  return parts[parts.length - 1];
6
6
  }
7
+ export function getDirName(filepath) {
8
+ // should work for paths that end with "/" or not
9
+ const parts = filepath.replaceAll("\\", "/").split("/");
10
+ let res = parts.pop();
11
+ if (res === "") {
12
+ res = parts.pop();
13
+ }
14
+ return res;
15
+ }
7
16
  export async function foreachGLTF(args, callback) {
8
17
  // get original directory this run was invoked from
9
18
  const initDir = process.env.INIT_CWD;
@@ -48,7 +57,7 @@ export async function foreachGLTF(args, callback) {
48
57
  }
49
58
  }
50
59
  if (context.files.length <= 0) {
51
- console.log("WARN: No glTF files found. Make sure to invoke with a valid path to a glTF file or directory. This path may be relative to " + initDir);
60
+ console.log("WARN: No glTF files found. Make sure to invoke with a valid path to a glTF file or directory. This path may be relative to \"" + initDir + "\"");
52
61
  }
53
62
  else {
54
63
  for (const file of context.files) {
@@ -2,6 +2,7 @@ export * from "./compression_utils.js";
2
2
  export * from "./fileutils.js";
3
3
  export * from "./version.js";
4
4
  export * from "./mesh.js";
5
+ export * from "./texture.js";
5
6
  export * from "./guid.js";
6
7
  export * from "./nodeio.js";
7
8
  export * from "./stats.js";
@@ -2,6 +2,7 @@ export * from "./compression_utils.js";
2
2
  export * from "./fileutils.js";
3
3
  export * from "./version.js";
4
4
  export * from "./mesh.js";
5
+ export * from "./texture.js";
5
6
  export * from "./guid.js";
6
7
  export * from "./nodeio.js";
7
8
  export * from "./stats.js";
@@ -1,5 +1,6 @@
1
1
  import { Logger } from "@donmccurdy/caporal";
2
2
  import { Document } from "@gltf-transform/core";
3
+ import { Config } from "../config/index.js";
3
4
  export type Stats = {
4
5
  startTime: number;
5
6
  totalGPUMemoryInMB: number;
@@ -7,17 +8,22 @@ export type Stats = {
7
8
  totalFileSizeInMB: number;
8
9
  totalFileSizeInMBBefore: number;
9
10
  };
10
- export declare function printStats(stats: Stats, logger?: Logger): void;
11
+ export declare function printStats(stats: Stats, logger: Logger, config: Config): void;
11
12
  export type FileStats = {
12
13
  filename: string;
13
14
  /** Size in bytes */
14
15
  size: number;
16
+ /** Memory in bytes */
15
17
  gpu_memory: number;
16
- vertex_count: number;
17
18
  nodes: number;
18
19
  materials: number;
20
+ meshes: number;
21
+ textures: number;
22
+ vertex_count: number;
23
+ triangle_count: number;
19
24
  };
20
- export declare function createNewFilestats(file: string, document: Document, stats: {
21
- gpu_memory: number;
22
- }): FileStats;
23
- export declare function writeFileStatsToFile(filestats: FileStats[], output_path: string): void;
25
+ /**
26
+ * Create a new filestats object from a file and a document
27
+ */
28
+ export declare function createNewFilestats(file: string, document: Document, stats: Pick<FileStats, "gpu_memory">): FileStats;
29
+ export declare function writeFileStatsToFile(config: Config, filestats: FileStats[], output_path: string): void;
@@ -1,39 +1,45 @@
1
1
  import { getVersion } from "./version.js";
2
2
  import { getFileName } from "./fileutils.js";
3
3
  import { statSync, writeFileSync } from "fs";
4
- export function printStats(stats, logger) {
4
+ export function printStats(stats, logger, config) {
5
5
  const duration = Date.now() - stats.startTime;
6
6
  const durationInMinutes = duration / 1000 / 60;
7
- const msg = `[Needle Build Pipeline] v${getVersion()} — Finished packing ${stats.totalFilesProcessed} files in ${durationInMinutes.toFixed(1)} minutes; total size ${stats.totalFileSizeInMBBefore.toFixed(1)} MB → ${stats.totalFileSizeInMB.toFixed(1)} MB, total GPU memory: ${stats.totalGPUMemoryInMB.toFixed(1)} MB`;
7
+ const msg = `[Needle Build Pipeline] v${getVersion()} — Finished ${config?.usecase} compression ${stats.totalFilesProcessed} files in ${durationInMinutes.toFixed(1)} minutes; total size ${stats.totalFileSizeInMBBefore.toFixed(1)} MB → ${stats.totalFileSizeInMB.toFixed(1)} MB, total GPU memory: ${stats.totalGPUMemoryInMB.toFixed(1)} MB`;
8
8
  if (logger)
9
9
  logger.info(msg);
10
10
  else
11
11
  console.log(msg);
12
12
  }
13
+ /**
14
+ * Create a new filestats object from a file and a document
15
+ */
13
16
  export function createNewFilestats(file, document, stats) {
14
17
  const filename = getFileName(file);
15
18
  const root = document.getRoot();
16
19
  const filestats = {
17
20
  filename,
18
21
  size: statSync(file).size,
19
- gpu_memory: stats.gpu_memory,
22
+ gpu_memory: Math.round(stats.gpu_memory),
20
23
  nodes: root.listNodes().length,
21
24
  materials: root.listMaterials().length,
25
+ meshes: root.listMeshes().length,
26
+ textures: root.listTextures().length,
22
27
  vertex_count: 0,
28
+ triangle_count: 0,
23
29
  };
24
30
  // Count vertices
25
31
  for (const mesh of root.listMeshes()) {
26
32
  filestats.vertex_count += mesh.listPrimitives().reduce((acc, p) => acc + p.getAttribute('POSITION').getCount(), 0);
27
33
  }
28
- filestats.vertex_count = Math.round(filestats.vertex_count / 3);
34
+ filestats.triangle_count = filestats.vertex_count / 3;
29
35
  return filestats;
30
36
  }
31
- export function writeFileStatsToFile(filestats, output_path) {
37
+ export function writeFileStatsToFile(config, filestats, output_path) {
32
38
  if (output_path == undefined) {
33
39
  console.error("No stats output path provided");
34
40
  return;
35
41
  }
36
42
  console.log("Writing file stats to: " + output_path);
37
- const json = JSON.stringify(filestats, null, 2);
43
+ const json = JSON.stringify(filestats);
38
44
  writeFileSync(output_path, json);
39
45
  }
@@ -0,0 +1,2 @@
1
+ export declare function isMultipleOfFour(value: number): boolean;
2
+ export declare function ceilMultipleOfFour(value: number): number;
@@ -0,0 +1,8 @@
1
+ export function isMultipleOfFour(value) {
2
+ return value % 4 === 0;
3
+ }
4
+ export function ceilMultipleOfFour(value) {
5
+ if (value <= 4)
6
+ return 4;
7
+ return value % 4 ? value + 4 - (value % 4) : value;
8
+ }
package/package.json CHANGED
@@ -1,30 +1,51 @@
1
1
  {
2
2
  "name": "@needle-tools/gltf-build-pipeline",
3
- "version": "1.6.0-alpha.7",
3
+ "version": "2.1.0-alpha",
4
4
  "description": "Pipeline and tools for optimizing gltf files using gltf-transform and compression settings within glTF extensions",
5
5
  "main": "index.mjs",
6
6
  "type": "module",
7
7
  "readme": "README.md",
8
+ "author": {
9
+ "name": "Needle",
10
+ "email": "help@needle.tools",
11
+ "url": "https://needle.tools/"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/needle-tools/needle-gltf-extensions.git"
16
+ },
8
17
  "bin": {
9
- "gltf-build-pipeline": "./dist/src/cli/index.js"
18
+ "gltf-build-pipeline": "./dist/src/cli/index.js",
19
+ "needle-gltf": "./dist/src/cli/index.js"
10
20
  },
11
21
  "scripts": {
12
22
  "start": "node scripts/index.mjs",
13
23
  "dev": "npm-watch compile",
24
+ "compile": "tsc || exit 1",
25
+ "clear-caches": "node scripts/clear-caches.mjs",
26
+ "limit-caches": "node scripts/limit-caches.mjs",
14
27
  "transform": "node scripts/index.mjs",
15
28
  "transform:make-progressive": "node scripts/make-progressive.mjs",
16
29
  "transform:pack-gltf": "node --no-experimental-fetch scripts/pack-gltf.mjs",
17
30
  "pack-gltf": "node --no-experimental-fetch scripts/pack-gltf.mjs",
18
- "dev:pack-gltf": "npm run compile && node scripts/pack-gltf.mjs",
19
- "clear-caches": "node scripts/clear-caches.mjs",
20
- "limit-caches": "node scripts/limit-caches.mjs",
21
- "compile": "tsc || exit 1"
31
+ "dev:pack-gltf": "npm run compile && node scripts/pack-gltf.mjs"
32
+ },
33
+ "devDependencies": {
34
+ "@img/sharp-win32-x64": "^0.33.4",
35
+ "@types/node": "^18.7.23",
36
+ "npm-watch": "^0.13.0",
37
+ "typescript": "^4.9.5"
38
+ },
39
+ "optionalDependencies": {
40
+ "@img/sharp-linux-arm": "^0.33.4",
41
+ "@img/sharp-win32-x64": "^0.33.4"
22
42
  },
23
43
  "dependencies": {
24
44
  "@donmccurdy/caporal": "~0.0.10",
25
- "@gltf-transform/core": "^3.10.1",
26
- "@gltf-transform/extensions": "^3.10.1",
27
- "@gltf-transform/functions": "^3.10.1",
45
+ "@gltf-transform/cli": "^4.0.1",
46
+ "@gltf-transform/core": "^4.0.1",
47
+ "@gltf-transform/extensions": "^4.0.1",
48
+ "@gltf-transform/functions": "^4.0.1",
28
49
  "command-exists": "^1.2.9",
29
50
  "command-line-args": "^5.2.1",
30
51
  "draco3dgltf": "^1.5.3",
@@ -36,7 +57,7 @@
36
57
  "ndarray-pixels": "^2.0.1",
37
58
  "p-limit": "3.1.0",
38
59
  "semver": "^7.3.7",
39
- "sharp": "^0.32.6",
60
+ "sharp": "^0.33.4",
40
61
  "tmp": "^0.2.1",
41
62
  "uuid": "^9.0.1"
42
63
  },
@@ -48,20 +69,5 @@
48
69
  "extensions": "ts",
49
70
  "quiet": false
50
71
  }
51
- },
52
- "devDependencies": {
53
- "@types/node": "^18.7.23",
54
- "nodemon": "^3.1.2",
55
- "npm-watch": "^0.13.0",
56
- "typescript": "^4.9.5"
57
- },
58
- "author": {
59
- "name": "Needle",
60
- "email": "help@needle.tools",
61
- "url": "https://needle.tools/"
62
- },
63
- "repository": {
64
- "type": "git",
65
- "url": "git+https://github.com/needle-tools/needle-gltf-extensions.git"
66
72
  }
67
- }
73
+ }
@@ -59,7 +59,7 @@ if (noToktx)
59
59
  const packedFiles = new Set();
60
60
 
61
61
  /**
62
- * @type {import("../dist/index.js").Stats}
62
+ * @type {import("../dist/src/index.js").Stats}
63
63
  */
64
64
  const stats = {
65
65
  startTime: Date.now(),
package/tsconfig.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "outDir": "dist",
5
5
  "declaration": true,
6
6
  "moduleResolution": "NodeNext",
7
- "module": "ESNext",
7
+ "module": "NodeNext",
8
8
  "esModuleInterop": true,
9
9
  "skipLibCheck": true,
10
10
  "resolveJsonModule": true