@threenative/three-native 0.0.0-stage → 0.3.6
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.
- package/LICENSE +21 -0
- package/README.md +24 -2
- package/package.json +42 -3
- package/src/addons/buffer-geometry-utils.ts +14 -0
- package/src/addons/data-utils.ts +63 -0
- package/src/addons/decal-geometry.ts +25 -0
- package/src/addons/decal.ts +218 -0
- package/src/addons/gltf-loader-web.ts +323 -0
- package/src/addons/hdr-loader.ts +71 -0
- package/src/addons/hdr.ts +139 -0
- package/src/addons/lut-cube-loader-web.ts +17 -0
- package/src/addons/lut-cube-loader.ts +149 -0
- package/src/addons/merge-geometries.ts +374 -0
- package/src/addons/mesh-bvh-webgpu.ts +13 -0
- package/src/addons/mesh-bvh.ts +50 -0
- package/src/addons/post-effects-web.ts +22 -0
- package/src/addons/post-effects.ts +173 -0
- package/src/audio.ts +564 -0
- package/src/blend-mode.ts +33 -0
- package/src/browser-backend.ts +2156 -0
- package/src/browser-entry.ts +305 -0
- package/src/browser-math.ts +448 -0
- package/src/browser-renderer.ts +527 -0
- package/src/browser-tsl.ts +650 -0
- package/src/catalog.ts +497 -0
- package/src/fixture-format.ts +721 -0
- package/src/fixture-native.ts +426 -0
- package/src/fixture-protocol.ts +315 -0
- package/src/math-utils.ts +65 -0
- package/src/object-surface.ts +250 -0
- package/src/pass-node.ts +286 -0
- package/src/property-binding.ts +93 -0
- package/src/quad-mesh.ts +54 -0
- package/src/reflector.ts +89 -0
- package/src/refused.ts +27 -0
- package/src/render-target.ts +107 -0
- package/src/rtt.ts +158 -0
- package/src/shadow-map.ts +21 -0
- package/src/storage.ts +206 -0
- package/src/texture-sources.ts +252 -0
- package/src/tsl-extras.ts +51 -0
- package/src/tsl-struct.ts +20 -0
- package/src/tsl-uniforms.ts +234 -0
- package/src/update-ranges.ts +109 -0
- package/src/wgsl-fn.ts +55 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* three's GLTFLoader under `engine: "threenative"` on the web (PRD-540): the bytes go to the engine's own
|
|
3
|
+
* glTF loader in Wasm (`tnw_web_load_gltf`), the same C++ the V8 player's loadAsset runs, and the
|
|
4
|
+
* result comes back in GLTFLoader's shape. Upstream GLTFLoader over engine classes never settles,
|
|
5
|
+
* so it is never bundled. The web build cooks models decoder-free for the native engine, so a codec
|
|
6
|
+
* or plugin the engine loader lacks is refused by name instead of being skipped.
|
|
7
|
+
*
|
|
8
|
+
* One plugin path is hosted: `TN_discrete_lod`, the LOD chain the asset pipeline bakes (PRD-617).
|
|
9
|
+
* `register` takes core's DiscreteLodPlugin and runs its `afterRoot` over a small parser: the file's
|
|
10
|
+
* JSON, its index accessors, and the engine's meshes keyed to the glTF mesh and primitive they came from.
|
|
11
|
+
*/
|
|
12
|
+
// quality-allow: the symbol exists only in the web engine module the bundler resolves "three" to, so no declaration can type it.
|
|
13
|
+
// @ts-expect-error -- `__tnLoadGltf` exists only in the web engine module "three" resolves to.
|
|
14
|
+
import { __tnLoadGltf } from "three";
|
|
15
|
+
|
|
16
|
+
interface IEngineModel {
|
|
17
|
+
readonly scene: object;
|
|
18
|
+
readonly animations: readonly object[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** GLTFLoader's result: one default scene, its clips, and the members three's callers read. */
|
|
22
|
+
export interface IGltfResult {
|
|
23
|
+
readonly scene: object;
|
|
24
|
+
readonly scenes: readonly object[];
|
|
25
|
+
readonly animations: readonly object[];
|
|
26
|
+
readonly cameras: readonly object[];
|
|
27
|
+
readonly asset: { readonly version: string };
|
|
28
|
+
readonly parser: undefined;
|
|
29
|
+
readonly userData: Record<string, unknown>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const load = __tnLoadGltf as
|
|
33
|
+
| ((bytes: Uint8Array, files: ReadonlyMap<string, Uint8Array>) => IEngineModel)
|
|
34
|
+
| undefined;
|
|
35
|
+
|
|
36
|
+
interface IGltfJson {
|
|
37
|
+
accessors?: {
|
|
38
|
+
bufferView?: number;
|
|
39
|
+
byteOffset?: number;
|
|
40
|
+
componentType?: number;
|
|
41
|
+
count?: number;
|
|
42
|
+
sparse?: unknown;
|
|
43
|
+
type?: string;
|
|
44
|
+
}[];
|
|
45
|
+
bufferViews?: { byteLength?: number; byteOffset?: number; byteStride?: number }[];
|
|
46
|
+
images?: { uri?: unknown }[];
|
|
47
|
+
meshes?: { primitives?: unknown[] }[];
|
|
48
|
+
nodes?: { children?: number[]; mesh?: number }[];
|
|
49
|
+
scene?: number;
|
|
50
|
+
scenes?: { nodes?: number[] }[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The JSON and, for a GLB, the binary chunk. Throws on a file that is neither. */
|
|
54
|
+
function readGltf(data: ArrayBuffer | string): { json: IGltfJson; bin: Uint8Array | undefined } {
|
|
55
|
+
if (typeof data === "string") return { bin: undefined, json: JSON.parse(data) as IGltfJson };
|
|
56
|
+
const bytes = new Uint8Array(data);
|
|
57
|
+
if (bytes.byteLength < 20 || bytes[0] !== 0x67 || bytes[1] !== 0x6c)
|
|
58
|
+
return { bin: undefined, json: JSON.parse(new TextDecoder().decode(bytes)) as IGltfJson };
|
|
59
|
+
const view = new DataView(data);
|
|
60
|
+
const jsonEnd = 20 + view.getUint32(12, true);
|
|
61
|
+
const json = JSON.parse(new TextDecoder().decode(bytes.subarray(20, jsonEnd))) as IGltfJson;
|
|
62
|
+
const hasBin =
|
|
63
|
+
jsonEnd + 8 <= bytes.byteLength && view.getUint32(jsonEnd + 4, true) === 0x004e4942;
|
|
64
|
+
return {
|
|
65
|
+
bin: hasBin
|
|
66
|
+
? bytes.subarray(jsonEnd + 8, jsonEnd + 8 + view.getUint32(jsonEnd, true))
|
|
67
|
+
: undefined,
|
|
68
|
+
json,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The files a glTF names by relative uri for its images (the asset cook writes shared images beside
|
|
74
|
+
* the model), which the engine loader cannot fetch itself. Data URIs and GLB-embedded images are not.
|
|
75
|
+
*/
|
|
76
|
+
export function externalImageUris(data: ArrayBuffer | string): string[] {
|
|
77
|
+
let json: IGltfJson;
|
|
78
|
+
try {
|
|
79
|
+
json = readGltf(data).json;
|
|
80
|
+
} catch {
|
|
81
|
+
return []; // a malformed file is refused by name when the engine loader parses it
|
|
82
|
+
}
|
|
83
|
+
const uris = (json.images ?? []).flatMap(({ uri }) =>
|
|
84
|
+
typeof uri === "string" && !uri.startsWith("data:") ? [uri] : [],
|
|
85
|
+
);
|
|
86
|
+
return [...new Set(uris)];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function refuse(what: string): never {
|
|
90
|
+
throw new Error(`TN_NATIVE_GLTF_${what}_UNSUPPORTED: the engine glTF loader does not take this`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const HOSTED_PLUGIN = "TN_discrete_lod";
|
|
94
|
+
|
|
95
|
+
/** The part of three's GLTFParser that DiscreteLodPlugin reads. */
|
|
96
|
+
interface IEngineParser {
|
|
97
|
+
readonly associations: Map<object, { meshes: number; nodes: number; primitives: number }>;
|
|
98
|
+
readonly json: IGltfJson;
|
|
99
|
+
getDependency(type: string, index: number): Promise<unknown>;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface IHostedPlugin {
|
|
103
|
+
readonly name: string;
|
|
104
|
+
afterRoot?(result: IGltfResult): Promise<void> | void;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
type PluginFactory = (parser: IEngineParser) => IHostedPlugin;
|
|
108
|
+
|
|
109
|
+
const ELEMENTS = { 5121: Uint8Array, 5123: Uint16Array, 5125: Uint32Array } as const;
|
|
110
|
+
|
|
111
|
+
/** An index accessor's values, copied out of the GLB's binary chunk. */
|
|
112
|
+
function readIndices(
|
|
113
|
+
json: IGltfJson,
|
|
114
|
+
bin: Uint8Array | undefined,
|
|
115
|
+
index: number,
|
|
116
|
+
): { array: ArrayLike<number> } {
|
|
117
|
+
const accessor = json.accessors?.[index];
|
|
118
|
+
const view = json.bufferViews?.[accessor?.bufferView ?? -1];
|
|
119
|
+
const Element = ELEMENTS[accessor?.componentType as keyof typeof ELEMENTS];
|
|
120
|
+
if (
|
|
121
|
+
accessor === undefined ||
|
|
122
|
+
view === undefined ||
|
|
123
|
+
Element === undefined ||
|
|
124
|
+
accessor.type !== "SCALAR" ||
|
|
125
|
+
accessor.sparse !== undefined ||
|
|
126
|
+
typeof accessor.count !== "number" ||
|
|
127
|
+
(view.byteStride ?? 0) !== 0
|
|
128
|
+
)
|
|
129
|
+
throw new Error(
|
|
130
|
+
`TN_WASM_GLTF_LOD_ACCESSOR: accessor ${String(index)} is not a plain index accessor`,
|
|
131
|
+
);
|
|
132
|
+
if (bin === undefined)
|
|
133
|
+
throw new Error("TN_WASM_GLTF_LOD_ACCESSOR: only a GLB's binary chunk is read for a LOD chain");
|
|
134
|
+
const start = (view.byteOffset ?? 0) + (accessor.byteOffset ?? 0);
|
|
135
|
+
const end = start + accessor.count * Element.BYTES_PER_ELEMENT;
|
|
136
|
+
if (!Number.isInteger(start) || end > bin.byteLength)
|
|
137
|
+
throw new Error(
|
|
138
|
+
`TN_WASM_GLTF_LOD_ACCESSOR: accessor ${String(index)} reads past the binary chunk`,
|
|
139
|
+
);
|
|
140
|
+
return { array: new Element(bin.slice(start, end).buffer) };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Keys each engine mesh to the glTF mesh and primitive it came from. The engine loader builds
|
|
145
|
+
* GLTFLoader's hierarchy, so meshes come in one order on both sides: node by node, depth first, a
|
|
146
|
+
* node's own primitives before its children. A count that differs is a scene this walk does not
|
|
147
|
+
* describe, and refuses the load rather than chain the wrong geometry.
|
|
148
|
+
*/
|
|
149
|
+
function associate(json: IGltfJson, scene: object, into: IEngineParser["associations"]): void {
|
|
150
|
+
const expected: { meshes: number; nodes: number; primitives: number }[] = [];
|
|
151
|
+
const visit = (node: number): void => {
|
|
152
|
+
const def = json.nodes?.[node];
|
|
153
|
+
if (def === undefined)
|
|
154
|
+
throw new Error(`TN_WASM_GLTF_LOD_MISMATCH: node ${String(node)} is missing`);
|
|
155
|
+
if (def.mesh !== undefined)
|
|
156
|
+
for (
|
|
157
|
+
let primitives = 0;
|
|
158
|
+
primitives < (json.meshes?.[def.mesh]?.primitives?.length ?? 0);
|
|
159
|
+
primitives += 1
|
|
160
|
+
)
|
|
161
|
+
expected.push({ meshes: def.mesh, nodes: node, primitives });
|
|
162
|
+
for (const child of def.children ?? []) visit(child);
|
|
163
|
+
};
|
|
164
|
+
for (const node of json.scenes?.[json.scene ?? 0]?.nodes ?? []) visit(node);
|
|
165
|
+
const meshes: object[] = [];
|
|
166
|
+
const walk = (object: { isMesh?: boolean; children: object[] }): void => {
|
|
167
|
+
if (object.isMesh === true) meshes.push(object);
|
|
168
|
+
for (const child of object.children) walk(child as never);
|
|
169
|
+
};
|
|
170
|
+
walk(scene as never);
|
|
171
|
+
if (meshes.length !== expected.length)
|
|
172
|
+
throw new Error(
|
|
173
|
+
`TN_WASM_GLTF_LOD_MISMATCH: the file has ${String(expected.length)} primitive(s) and the engine scene ${String(meshes.length)} mesh(es)`,
|
|
174
|
+
);
|
|
175
|
+
for (const [i, mesh] of meshes.entries()) into.set(mesh, expected[i] as never);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Builds the registered plugins over the file's parser; any plugin but the one hosted is refused by name. */
|
|
179
|
+
function hostPlugins(
|
|
180
|
+
factories: readonly PluginFactory[],
|
|
181
|
+
data: ArrayBuffer | string,
|
|
182
|
+
): { parser: IEngineParser; plugins: IHostedPlugin[] } | undefined {
|
|
183
|
+
if (factories.length === 0) return undefined;
|
|
184
|
+
const { bin, json } = readGltf(data);
|
|
185
|
+
const parser: IEngineParser = {
|
|
186
|
+
associations: new Map(),
|
|
187
|
+
getDependency: async (type, index) => {
|
|
188
|
+
if (type === "accessor") return readIndices(json, bin, index);
|
|
189
|
+
throw new Error(
|
|
190
|
+
`TN_WASM_GLTF_DEPENDENCY_UNSUPPORTED: the engine glTF loader returns no '${type}'`,
|
|
191
|
+
);
|
|
192
|
+
},
|
|
193
|
+
json,
|
|
194
|
+
};
|
|
195
|
+
const plugins = factories.map((factory) => factory(parser));
|
|
196
|
+
for (const plugin of plugins) if (plugin.name !== HOSTED_PLUGIN) refuse("PLUGIN");
|
|
197
|
+
return { parser, plugins };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export class GLTFLoader {
|
|
201
|
+
path = "";
|
|
202
|
+
/** A plugin defect (a chain the file declares and cannot deliver) rejects the load; core's plugin logs it on stock three. */
|
|
203
|
+
readonly failClosed = true;
|
|
204
|
+
readonly #factories: PluginFactory[] = [];
|
|
205
|
+
|
|
206
|
+
setPath(path: string): this {
|
|
207
|
+
this.path = path;
|
|
208
|
+
return this;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
setResourcePath(): this {
|
|
212
|
+
return this;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
setCrossOrigin(): this {
|
|
216
|
+
return this;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
setRequestHeader(): this {
|
|
220
|
+
return this;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
setKTX2Loader(): never {
|
|
224
|
+
return refuse("KTX2");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
setMeshoptDecoder(): never {
|
|
228
|
+
return refuse("MESHOPT");
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
setDRACOLoader(): never {
|
|
232
|
+
return refuse("DRACO");
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Takes a plugin factory; only `TN_discrete_lod` is hosted, any other is refused by name when parsing. */
|
|
236
|
+
register(factory: PluginFactory): this {
|
|
237
|
+
this.#factories.push(factory);
|
|
238
|
+
return this;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** `onLoad` or `onError` runs once, as three's does; images named by uri are fetched first. */
|
|
242
|
+
parse(
|
|
243
|
+
data: ArrayBuffer | string,
|
|
244
|
+
path: string,
|
|
245
|
+
onLoad: (gltf: IGltfResult) => void,
|
|
246
|
+
onError?: (error: unknown) => void,
|
|
247
|
+
): void {
|
|
248
|
+
const settle = async (files: ReadonlyMap<string, Uint8Array>): Promise<void> => {
|
|
249
|
+
let result: IGltfResult;
|
|
250
|
+
try {
|
|
251
|
+
if (load === undefined)
|
|
252
|
+
throw new Error("TN_WASM_GLTF_UNAVAILABLE: this web engine has no glTF loader");
|
|
253
|
+
const bytes =
|
|
254
|
+
typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
|
|
255
|
+
const hosted = hostPlugins(this.#factories, data);
|
|
256
|
+
const model = load(bytes, files);
|
|
257
|
+
result = {
|
|
258
|
+
scene: model.scene,
|
|
259
|
+
scenes: [model.scene],
|
|
260
|
+
animations: [...model.animations],
|
|
261
|
+
cameras: [],
|
|
262
|
+
asset: { version: "2.0" },
|
|
263
|
+
parser: undefined,
|
|
264
|
+
userData: {},
|
|
265
|
+
};
|
|
266
|
+
if (hosted !== undefined) {
|
|
267
|
+
associate(hosted.parser.json, model.scene, hosted.parser.associations);
|
|
268
|
+
for (const plugin of hosted.plugins) await plugin.afterRoot?.(result);
|
|
269
|
+
}
|
|
270
|
+
} catch (error) {
|
|
271
|
+
if (onError === undefined) throw error;
|
|
272
|
+
onError(error);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
onLoad(result);
|
|
276
|
+
};
|
|
277
|
+
const uris = externalImageUris(data);
|
|
278
|
+
if (uris.length === 0) {
|
|
279
|
+
void settle(new Map());
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
Promise.all(
|
|
283
|
+
uris.map(async (uri) => {
|
|
284
|
+
const response = await fetch(path + uri);
|
|
285
|
+
if (!response.ok) throw new Error(`TN_WASM_GLTF_FETCH: ${response.status} ${path + uri}`);
|
|
286
|
+
// The engine loader asks for the uri with its percent escapes decoded.
|
|
287
|
+
return [decodeURIComponent(uri), new Uint8Array(await response.arrayBuffer())] as const;
|
|
288
|
+
}),
|
|
289
|
+
).then(
|
|
290
|
+
(files) => settle(new Map(files)),
|
|
291
|
+
(error: unknown) => {
|
|
292
|
+
if (onError === undefined) throw error;
|
|
293
|
+
onError(error);
|
|
294
|
+
},
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
parseAsync(data: ArrayBuffer | string, path: string): Promise<IGltfResult> {
|
|
299
|
+
return new Promise((resolve, reject) => this.parse(data, path, resolve, reject));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async loadAsync(url: string): Promise<IGltfResult> {
|
|
303
|
+
const response = await fetch(this.path + url);
|
|
304
|
+
if (!response.ok) throw new Error(`TN_WASM_GLTF_FETCH: ${response.status} ${url}`);
|
|
305
|
+
const resolved = this.path + url;
|
|
306
|
+
return this.parseAsync(
|
|
307
|
+
await response.arrayBuffer(),
|
|
308
|
+
resolved.slice(0, resolved.lastIndexOf("/") + 1),
|
|
309
|
+
);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
load(
|
|
313
|
+
url: string,
|
|
314
|
+
onLoad: (gltf: IGltfResult) => void,
|
|
315
|
+
_onProgress?: unknown,
|
|
316
|
+
onError?: (error: unknown) => void,
|
|
317
|
+
): void {
|
|
318
|
+
this.loadAsync(url).then(onLoad, (error: unknown) => {
|
|
319
|
+
if (onError === undefined) throw error;
|
|
320
|
+
onError(error);
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* three's `HDRLoader` (three/addons/loaders/HDRLoader.js) for the browser back end: fetch the file,
|
|
3
|
+
* decode it with the shared `parseHDR`, and build the engine `DataTexture` with the settings three's
|
|
4
|
+
* `DataTextureLoader` applies. `three` here is the engine binding the web build aliases it to.
|
|
5
|
+
* The V8 player's equivalent reads the cooked package instead (runtime-native core-hdr.mjs).
|
|
6
|
+
*/
|
|
7
|
+
import { DataTexture, LinearFilter, LinearSRGBColorSpace, RGBAFormat } from "three";
|
|
8
|
+
|
|
9
|
+
import { HALF_FLOAT_TYPE, parseHDR } from "./hdr.js";
|
|
10
|
+
|
|
11
|
+
type EngineDataTexture = {
|
|
12
|
+
colorSpace: string;
|
|
13
|
+
flipY: boolean;
|
|
14
|
+
magFilter: number;
|
|
15
|
+
minFilter: number;
|
|
16
|
+
needsUpdate: boolean;
|
|
17
|
+
};
|
|
18
|
+
// quality-allow: the engine DataTexture is constructed with an argument list upstream's declaration does not carry.
|
|
19
|
+
const EngineDataTexture = DataTexture as unknown as new (
|
|
20
|
+
data: ArrayLike<number>,
|
|
21
|
+
width: number,
|
|
22
|
+
height: number,
|
|
23
|
+
format: number,
|
|
24
|
+
type: number,
|
|
25
|
+
) => EngineDataTexture;
|
|
26
|
+
|
|
27
|
+
export class HDRLoader {
|
|
28
|
+
type: number = HALF_FLOAT_TYPE;
|
|
29
|
+
path = "";
|
|
30
|
+
|
|
31
|
+
setDataType(type: number): this {
|
|
32
|
+
this.type = type;
|
|
33
|
+
return this;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
setPath(path: string): this {
|
|
37
|
+
this.path = path;
|
|
38
|
+
return this;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
load(
|
|
42
|
+
url: string,
|
|
43
|
+
onLoad?: (texture: EngineDataTexture) => void,
|
|
44
|
+
_onProgress?: unknown,
|
|
45
|
+
onError?: (error: unknown) => void,
|
|
46
|
+
): void {
|
|
47
|
+
this.loadAsync(url).then(onLoad, (error) => {
|
|
48
|
+
if (onError === undefined) throw error;
|
|
49
|
+
onError(error);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async loadAsync(url: string): Promise<EngineDataTexture> {
|
|
54
|
+
const response = await fetch(this.path + url);
|
|
55
|
+
if (!response.ok)
|
|
56
|
+
throw new Error(`TN_HDR_FETCH: ${this.path + url} answered ${String(response.status)}`);
|
|
57
|
+
const image = parseHDR(await response.arrayBuffer(), this.type);
|
|
58
|
+
const texture = new EngineDataTexture(
|
|
59
|
+
image.data,
|
|
60
|
+
image.width,
|
|
61
|
+
image.height,
|
|
62
|
+
RGBAFormat,
|
|
63
|
+
image.type,
|
|
64
|
+
);
|
|
65
|
+
texture.colorSpace = LinearSRGBColorSpace;
|
|
66
|
+
texture.minFilter = texture.magFilter = LinearFilter;
|
|
67
|
+
texture.flipY = true;
|
|
68
|
+
texture.needsUpdate = true;
|
|
69
|
+
return texture;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* three's `HDRLoader.parse` (r185, MIT) as plain JS: Radiance RGBE bytes to the RGBA texels three
|
|
3
|
+
* uploads, shared by both engine back ends. Only the byte source differs per target, so each back
|
|
4
|
+
* end's `HDRLoader` reads the file and hands the bytes here.
|
|
5
|
+
*
|
|
6
|
+
* The decode is three's: `2^(e-128)/255` per channel, alpha 1, rows as stored (three sets `flipY`),
|
|
7
|
+
* and `HalfFloatType` (the default) through three's own truncating binary16 conversion.
|
|
8
|
+
*/
|
|
9
|
+
import { toHalfFloat } from "./data-utils.js";
|
|
10
|
+
|
|
11
|
+
export const FLOAT_TYPE = 1015;
|
|
12
|
+
export const HALF_FLOAT_TYPE = 1016;
|
|
13
|
+
|
|
14
|
+
export interface IHDRImage {
|
|
15
|
+
readonly width: number;
|
|
16
|
+
readonly height: number;
|
|
17
|
+
/** RGBA: binary16 bits for HalfFloatType, float32 for FloatType. */
|
|
18
|
+
readonly data: Uint16Array | Float32Array;
|
|
19
|
+
readonly type: typeof FLOAT_TYPE | typeof HALF_FLOAT_TYPE;
|
|
20
|
+
readonly gamma: number;
|
|
21
|
+
readonly exposure: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function fail(message: string): never {
|
|
25
|
+
throw new Error(`TN_HDR_INVALID: ${message}`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The header lines, as three's `RGBE_ReadHeader` reads them; returns the pixel offset. */
|
|
29
|
+
function readHeader(bytes: Uint8Array) {
|
|
30
|
+
let pos = 0;
|
|
31
|
+
const line = (): string | undefined => {
|
|
32
|
+
const end = bytes.indexOf(0x0a, pos);
|
|
33
|
+
if (end < 0 || end - pos > 1024) return undefined;
|
|
34
|
+
const text = String.fromCharCode(...bytes.subarray(pos, end));
|
|
35
|
+
pos = end + 1;
|
|
36
|
+
return text;
|
|
37
|
+
};
|
|
38
|
+
if (!/^#\?(\S+)/.test(line() ?? "")) fail("bad initial token");
|
|
39
|
+
let format = false;
|
|
40
|
+
let width = 0;
|
|
41
|
+
let height = 0;
|
|
42
|
+
let gamma = 1;
|
|
43
|
+
let exposure = 1;
|
|
44
|
+
for (let text = line(); text !== undefined; text = line()) {
|
|
45
|
+
if (text.startsWith("#")) continue;
|
|
46
|
+
let match = /^\s*GAMMA\s*=\s*(\d+(\.\d+)?)\s*$/.exec(text);
|
|
47
|
+
if (match) gamma = Number.parseFloat(match[1] ?? "1");
|
|
48
|
+
match = /^\s*EXPOSURE\s*=\s*(\d+(\.\d+)?)\s*$/.exec(text);
|
|
49
|
+
if (match) exposure = Number.parseFloat(match[1] ?? "1");
|
|
50
|
+
if (/^\s*FORMAT=(\S+)\s*$/.test(text)) format = true;
|
|
51
|
+
match = /^\s*-Y\s+(\d+)\s+\+X\s+(\d+)\s*$/.exec(text);
|
|
52
|
+
if (match) {
|
|
53
|
+
height = Number.parseInt(match[1] ?? "0", 10);
|
|
54
|
+
width = Number.parseInt(match[2] ?? "0", 10);
|
|
55
|
+
}
|
|
56
|
+
if (format && width > 0) break;
|
|
57
|
+
}
|
|
58
|
+
if (!format) fail("missing format specifier");
|
|
59
|
+
if (!(width > 0 && height > 0)) fail("missing image size specifier");
|
|
60
|
+
return { pos, width, height, gamma, exposure };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** RGBE pixels, run-length decoded per scanline (three's `RGBE_ReadPixels_RLE`). */
|
|
64
|
+
function readPixels(bytes: Uint8Array, width: number, height: number): Uint8Array {
|
|
65
|
+
if (
|
|
66
|
+
width < 8 ||
|
|
67
|
+
width > 0x7fff ||
|
|
68
|
+
bytes[0] !== 2 ||
|
|
69
|
+
bytes[1] !== 2 ||
|
|
70
|
+
((bytes[2] ?? 0) & 0x80) !== 0
|
|
71
|
+
)
|
|
72
|
+
return bytes;
|
|
73
|
+
if (width !== (((bytes[2] ?? 0) << 8) | (bytes[3] ?? 0))) fail("wrong scanline width");
|
|
74
|
+
const rgba = new Uint8Array(4 * width * height);
|
|
75
|
+
const scanline = new Uint8Array(4 * width);
|
|
76
|
+
let offset = 0;
|
|
77
|
+
let pos = 0;
|
|
78
|
+
for (let row = 0; row < height && pos < bytes.length; ++row) {
|
|
79
|
+
if (pos + 4 > bytes.length) fail("read error");
|
|
80
|
+
if (
|
|
81
|
+
bytes[pos] !== 2 ||
|
|
82
|
+
bytes[pos + 1] !== 2 ||
|
|
83
|
+
(((bytes[pos + 2] ?? 0) << 8) | (bytes[pos + 3] ?? 0)) !== width
|
|
84
|
+
)
|
|
85
|
+
fail("bad rgbe scanline format");
|
|
86
|
+
pos += 4;
|
|
87
|
+
let ptr = 0;
|
|
88
|
+
while (ptr < scanline.length && pos < bytes.length) {
|
|
89
|
+
let count = bytes[pos++] ?? 0;
|
|
90
|
+
const run = count > 128;
|
|
91
|
+
if (run) count -= 128;
|
|
92
|
+
if (count === 0 || ptr + count > scanline.length) fail("bad scanline data");
|
|
93
|
+
if (run) {
|
|
94
|
+
scanline.fill(bytes[pos++] ?? 0, ptr, ptr + count);
|
|
95
|
+
} else {
|
|
96
|
+
scanline.set(bytes.subarray(pos, pos + count), ptr);
|
|
97
|
+
pos += count;
|
|
98
|
+
}
|
|
99
|
+
ptr += count;
|
|
100
|
+
}
|
|
101
|
+
for (let i = 0; i < width; ++i, offset += 4) {
|
|
102
|
+
rgba[offset] = scanline[i] ?? 0;
|
|
103
|
+
rgba[offset + 1] = scanline[i + width] ?? 0;
|
|
104
|
+
rgba[offset + 2] = scanline[i + 2 * width] ?? 0;
|
|
105
|
+
rgba[offset + 3] = scanline[i + 3 * width] ?? 0;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return rgba;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Decodes a Radiance `.hdr` file to the texels three's HDRLoader produces for `type`. */
|
|
112
|
+
export function parseHDR(buffer: ArrayBuffer, type: number = HALF_FLOAT_TYPE): IHDRImage {
|
|
113
|
+
if (type !== HALF_FLOAT_TYPE && type !== FLOAT_TYPE) fail(`unsupported type ${type}`);
|
|
114
|
+
const bytes = new Uint8Array(buffer);
|
|
115
|
+
const header = readHeader(bytes);
|
|
116
|
+
const rgbe = readPixels(bytes.subarray(header.pos), header.width, header.height);
|
|
117
|
+
// three keeps whatever length a flat file has; the engine needs exactly width * height texels.
|
|
118
|
+
if (rgbe.length !== 4 * header.width * header.height)
|
|
119
|
+
fail("pixel data does not match the image size");
|
|
120
|
+
const texels = header.width * header.height;
|
|
121
|
+
const data = type === FLOAT_TYPE ? new Float32Array(texels * 4) : new Uint16Array(texels * 4);
|
|
122
|
+
const one = type === FLOAT_TYPE ? 1 : toHalfFloat(1);
|
|
123
|
+
for (let j = 0; j < texels * 4; j += 4) {
|
|
124
|
+
const scale = 2 ** ((rgbe[j + 3] ?? 0) - 128) / 255;
|
|
125
|
+
for (let c = 0; c < 3; ++c) {
|
|
126
|
+
const value = (rgbe[j + c] ?? 0) * scale;
|
|
127
|
+
data[j + c] = type === FLOAT_TYPE ? value : toHalfFloat(Math.min(value, 65504));
|
|
128
|
+
}
|
|
129
|
+
data[j + 3] = one;
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
width: header.width,
|
|
133
|
+
height: header.height,
|
|
134
|
+
data,
|
|
135
|
+
type: type as IHDRImage["type"],
|
|
136
|
+
gamma: header.gamma,
|
|
137
|
+
exposure: header.exposure,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Data3DTexture, Vector3 } from "three";
|
|
2
|
+
import { defineLUTCubeLoader } from "./lut-cube-loader.js";
|
|
3
|
+
|
|
4
|
+
export const LUTCubeLoader = defineLUTCubeLoader(
|
|
5
|
+
{
|
|
6
|
+
// quality-allow: generated engine declarations omit the Data3DTexture source constructor and image record.
|
|
7
|
+
textureClass: Data3DTexture as unknown as Parameters<
|
|
8
|
+
typeof defineLUTCubeLoader
|
|
9
|
+
>[0]["textureClass"],
|
|
10
|
+
vectorClass: Vector3,
|
|
11
|
+
},
|
|
12
|
+
async (url) => {
|
|
13
|
+
const response = await fetch(url);
|
|
14
|
+
if (!response.ok) throw new Error(`TN_LUT_FETCH: ${response.status} ${url}`);
|
|
15
|
+
return response.text();
|
|
16
|
+
},
|
|
17
|
+
);
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/** Cube LUT loading shared by the native player and the Wasm engine. */
|
|
2
|
+
interface ITexture {
|
|
3
|
+
image: { data: Uint8Array | Float32Array; width: number; height: number; depth: number };
|
|
4
|
+
type: number;
|
|
5
|
+
minFilter: number;
|
|
6
|
+
magFilter: number;
|
|
7
|
+
wrapS: number;
|
|
8
|
+
wrapT: number;
|
|
9
|
+
wrapR: number;
|
|
10
|
+
generateMipmaps: boolean;
|
|
11
|
+
needsUpdate: boolean;
|
|
12
|
+
}
|
|
13
|
+
interface IVector {
|
|
14
|
+
x: number;
|
|
15
|
+
y: number;
|
|
16
|
+
z: number;
|
|
17
|
+
}
|
|
18
|
+
interface IManager {
|
|
19
|
+
itemStart?(url: string): void;
|
|
20
|
+
itemEnd?(url: string): void;
|
|
21
|
+
itemError?(url: string): void;
|
|
22
|
+
}
|
|
23
|
+
interface ICubeClasses {
|
|
24
|
+
textureClass: new (
|
|
25
|
+
data: Uint8Array | Float32Array,
|
|
26
|
+
width: number,
|
|
27
|
+
height: number,
|
|
28
|
+
depth: number,
|
|
29
|
+
) => ITexture;
|
|
30
|
+
vectorClass: new (x: number, y: number, z: number) => IVector;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface ICubeData {
|
|
34
|
+
title: string | null;
|
|
35
|
+
size: number;
|
|
36
|
+
min: number[];
|
|
37
|
+
max: number[];
|
|
38
|
+
samples: number[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function cubeSize(words: string[], previous: number): number {
|
|
42
|
+
if (previous || words.length !== 2) throw new Error("TN_LUT_SIZE: expected one LUT_3D_SIZE");
|
|
43
|
+
const size = Number(words[1]);
|
|
44
|
+
if (!Number.isInteger(size) || size < 2 || size > 256)
|
|
45
|
+
throw new Error("TN_LUT_SIZE: expected 2 through 256");
|
|
46
|
+
return size;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function cubeRow(line: string, cube: ICubeData): void {
|
|
50
|
+
if (!line || line.startsWith("#")) return;
|
|
51
|
+
const heading = /^TITLE\s+"([^"]*)"\s*(?:#.*)?$/u.exec(line);
|
|
52
|
+
if (heading) {
|
|
53
|
+
cube.title = heading[1] ?? "";
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const words = line.split("#")[0]?.trim().split(/\s+/u) ?? [];
|
|
57
|
+
const key = words[0];
|
|
58
|
+
if (key === "LUT_3D_SIZE") {
|
|
59
|
+
cube.size = cubeSize(words, cube.size);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
const target = key === "DOMAIN_MIN" ? cube.min : key === "DOMAIN_MAX" ? cube.max : undefined;
|
|
63
|
+
const values = (target ? words.slice(1) : words).map(Number);
|
|
64
|
+
if (values.length !== 3 || !values.every(Number.isFinite)) throw new Error(`TN_LUT_ROW: ${line}`);
|
|
65
|
+
if (target) {
|
|
66
|
+
target.splice(0, 3, ...values);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (!cube.size || cube.samples.length >= cube.size ** 3 * 4)
|
|
70
|
+
throw new Error("TN_LUT_DATA: missing size or excess samples");
|
|
71
|
+
cube.samples.push(...values, 1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function parseCube(input: string): ICubeData {
|
|
75
|
+
const cube: ICubeData = { title: null, size: 0, min: [0, 0, 0], max: [1, 1, 1], samples: [] };
|
|
76
|
+
for (const raw of input.split(/\r?\n/u)) cubeRow(raw.trim(), cube);
|
|
77
|
+
if (!cube.size || cube.samples.length !== cube.size ** 3 * 4)
|
|
78
|
+
throw new Error("TN_LUT_DATA: expected size cubed RGB samples");
|
|
79
|
+
if (cube.min.some((value, index) => value > (cube.max[index] ?? 0)))
|
|
80
|
+
throw new Error("TN_LUT_DOMAIN: minimum exceeds maximum");
|
|
81
|
+
return cube;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function defineLUTCubeLoader(classes: ICubeClasses, read: (url: string) => Promise<string>) {
|
|
85
|
+
return class LUTCubeLoader {
|
|
86
|
+
type = 1009;
|
|
87
|
+
path = "";
|
|
88
|
+
constructor(readonly manager?: IManager) {}
|
|
89
|
+
setType(type: number): this {
|
|
90
|
+
if (type !== 1009 && type !== 1015)
|
|
91
|
+
throw new Error("TN_LUT_TYPE: expected UnsignedByteType or FloatType");
|
|
92
|
+
this.type = type;
|
|
93
|
+
return this;
|
|
94
|
+
}
|
|
95
|
+
setPath(path: string): this {
|
|
96
|
+
this.path = path;
|
|
97
|
+
return this;
|
|
98
|
+
}
|
|
99
|
+
load(
|
|
100
|
+
url: string,
|
|
101
|
+
onLoad?: (result: ReturnType<LUTCubeLoader["parse"]>) => void,
|
|
102
|
+
_onProgress?: unknown,
|
|
103
|
+
onError?: (error: unknown) => void,
|
|
104
|
+
): void {
|
|
105
|
+
this.loadAsync(url).then(onLoad, (error) => {
|
|
106
|
+
if (onError === undefined) throw error;
|
|
107
|
+
onError(error);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
async loadAsync(url: string) {
|
|
111
|
+
const resolved = this.path + url;
|
|
112
|
+
this.manager?.itemStart?.(resolved);
|
|
113
|
+
try {
|
|
114
|
+
return this.parse(await read(resolved));
|
|
115
|
+
} catch (error) {
|
|
116
|
+
this.manager?.itemError?.(resolved);
|
|
117
|
+
throw error;
|
|
118
|
+
} finally {
|
|
119
|
+
this.manager?.itemEnd?.(resolved);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
parse(input: string) {
|
|
123
|
+
this.setType(this.type);
|
|
124
|
+
const { title, size, min, max, samples } = parseCube(input);
|
|
125
|
+
const data =
|
|
126
|
+
this.type === 1009
|
|
127
|
+
? Uint8Array.from(samples, (value) => value * 255)
|
|
128
|
+
: Float32Array.from(samples);
|
|
129
|
+
const texture3D = new classes.textureClass(data, size, size, size);
|
|
130
|
+
Object.assign(texture3D, {
|
|
131
|
+
type: this.type,
|
|
132
|
+
magFilter: 1006,
|
|
133
|
+
minFilter: 1006,
|
|
134
|
+
wrapS: 1001,
|
|
135
|
+
wrapT: 1001,
|
|
136
|
+
wrapR: 1001,
|
|
137
|
+
generateMipmaps: false,
|
|
138
|
+
needsUpdate: true,
|
|
139
|
+
});
|
|
140
|
+
return {
|
|
141
|
+
title,
|
|
142
|
+
size,
|
|
143
|
+
domainMin: new classes.vectorClass(min[0] ?? 0, min[1] ?? 0, min[2] ?? 0),
|
|
144
|
+
domainMax: new classes.vectorClass(max[0] ?? 1, max[1] ?? 1, max[2] ?? 1),
|
|
145
|
+
texture3D,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
}
|