@aura3d/assets 1.4.0 → 1.4.1

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.
Files changed (69) hide show
  1. package/package.json +38 -5
  2. package/AGENTS.md +0 -46
  3. package/src/AdvancedAssetCorpus.ts +0 -454
  4. package/src/AssetBundleCacheFixtures.ts +0 -290
  5. package/src/AssetCache.ts +0 -76
  6. package/src/AssetCompatibility.ts +0 -224
  7. package/src/AssetCorpus.ts +0 -329
  8. package/src/AssetDependencyGraph.ts +0 -83
  9. package/src/AssetHandle.ts +0 -74
  10. package/src/AssetImportPreflight.ts +0 -179
  11. package/src/AssetInspection.ts +0 -706
  12. package/src/AssetLoader.ts +0 -36
  13. package/src/AssetManager.ts +0 -211
  14. package/src/AssetRegistry.ts +0 -44
  15. package/src/AssetRenderDefaults.ts +0 -36
  16. package/src/AudioLoader.ts +0 -41
  17. package/src/BlenderExportValidation.ts +0 -227
  18. package/src/CarConceptMaterialStability.ts +0 -1405
  19. package/src/EXRLoader.ts +0 -1
  20. package/src/ExternalParityGLTFCorpus.ts +0 -65
  21. package/src/GLTFAnimationRuntime.ts +0 -1416
  22. package/src/GLTFAutoFit.ts +0 -133
  23. package/src/GLTFCompressionDecoders.ts +0 -190
  24. package/src/GLTFExtensionSupport.ts +0 -138
  25. package/src/GLTFLoader.ts +0 -4060
  26. package/src/GLTFRenderResources.ts +0 -2270
  27. package/src/HDRLoader.ts +0 -1
  28. package/src/ImageLoader.ts +0 -52
  29. package/src/ImportPipeline.ts +0 -148
  30. package/src/KTX2BasisTextureTranscoder.ts +0 -225
  31. package/src/LoadContext.ts +0 -60
  32. package/src/MaterialLoader.ts +0 -166
  33. package/src/MeshOptimization.ts +0 -93
  34. package/src/OBJLoader.ts +0 -551
  35. package/src/SceneAnalysisFixtures.ts +0 -438
  36. package/src/SceneLoader.ts +0 -62
  37. package/src/ShaderLoader.ts +0 -30
  38. package/src/TextureLoader.ts +0 -30
  39. package/src/TexturePipeline.ts +0 -96
  40. package/src/TextureStreaming.ts +0 -20
  41. package/src/WorkerAssetJobs.ts +0 -56
  42. package/src/advanced-gallery/index.ts +0 -18
  43. package/src/asset-corpus/GLTFSceneLoader.ts +0 -9
  44. package/src/asset-corpus/ProductionAssetCorpus.ts +0 -230
  45. package/src/asset-corpus/ProductionAssetPipeline.ts +0 -5
  46. package/src/asset-corpus/ProductionGLTFRenderPipeline.ts +0 -182
  47. package/src/asset-corpus/ProductionHDRTextureLoader.ts +0 -2
  48. package/src/asset-corpus/ProductionKTX2TextureLoader.ts +0 -2
  49. package/src/asset-corpus/ProductionTextureLoader.ts +0 -2
  50. package/src/asset-corpus/index.ts +0 -29
  51. package/src/browser-index.ts +0 -229
  52. package/src/createRenderableScene.ts +0 -128
  53. package/src/index.ts +0 -325
  54. package/src/loadRenderableAsset.ts +0 -67
  55. package/src/loaders/CubeTextureLoader.ts +0 -8
  56. package/src/loaders/EXRLoader.ts +0 -10
  57. package/src/loaders/HDRLoader.ts +0 -7
  58. package/src/loaders/KTX2Loader.ts +0 -7
  59. package/src/loaders/LoaderDiagnostics.ts +0 -36
  60. package/src/loaders/MTLLoader.ts +0 -20
  61. package/src/loaders/OBJLoader.ts +0 -24
  62. package/src/loaders/TextureLoader.ts +0 -14
  63. package/src/loaders/ThreeCompatGLTFLoader.ts +0 -19
  64. package/src/loaders/index.ts +0 -14
  65. package/src/threejs-compatibility/ThreeCompatAssetProvenance.ts +0 -51
  66. package/src/threejs-compatibility/ThreeCompatAssetRegistry.ts +0 -61
  67. package/src/threejs-example-parity/index.ts +0 -262
  68. package/tests/assets.test.ts +0 -393
  69. package/tsconfig.json +0 -7
@@ -1,2270 +0,0 @@
1
- import {
2
- Geometry,
3
- IndexBuffer,
4
- InstancedPBRMaterial,
5
- InstancedUnlitMaterial,
6
- Material,
7
- PBRMaterial,
8
- Sampler,
9
- SkinnedLitMaterial,
10
- Texture,
11
- TextureBinding,
12
- TexturedPBRMaterial,
13
- TexturedUnlitMaterial,
14
- UnlitMaterial,
15
- VertexBuffer,
16
- createExternalParityEnvironmentLighting,
17
- computePerspectiveCameraFrame,
18
- computeSkinnedMorphTargetEnvelopeBounds,
19
- type CameraFrameBounds,
20
- type CameraFrameViewport,
21
- type CameraLike,
22
- type CollectedLight,
23
- type EnvironmentLightingOptions,
24
- type ForwardShadowMapOptions,
25
- type PerspectiveCameraFrame,
26
- type PerspectiveCameraFrameOptions,
27
- type VertexAttributeDescriptor,
28
- VertexFormat,
29
- DEFAULT_PBR_ENVIRONMENT_INTENSITY,
30
- type MorphTargetDelta,
31
- type RenderItem,
32
- type RendererCameraPolicy,
33
- type RendererInput,
34
- type RendererPostProcessOptions,
35
- type RendererShadowOptions,
36
- type RenderSource,
37
- type RenderState,
38
- type SamplerDescriptor,
39
- type TextureFormat,
40
- type TextureMipLevelDescriptor,
41
- type TexturePixelData,
42
- type TexturedPBRMaterialOptions,
43
- type TexturedPBRTextureSlot,
44
- isTexturedPbrTextureSlotShaderActive,
45
- DEFAULT_TEXTURED_PBR_SHADER_NAME
46
- } from "@aura3d/rendering";
47
- import { Bounds3 as SceneBounds3, multiplyMat4, type Mat4 } from "@aura3d/scene";
48
- import {
49
- parseGLTFRuntimeMaterialKey,
50
- type GLTFAsset,
51
- type GLTFImageAsset,
52
- type GLTFMaterialAsset,
53
- type GLTFMaterialVariantMappingAsset,
54
- type GLTFMeshAsset,
55
- type GLTFResolvedTextureInfo,
56
- type GLTFSceneCreateOptions,
57
- type GLTFTextureAsset
58
- } from "./GLTFLoader";
59
- import { transcodeKTX2BasisTexture, type KTX2BasisTargetFormat, type KTX2BasisTextureTranscoderOptions } from "./KTX2BasisTextureTranscoder";
60
-
61
- export interface DecodedGLTFImage {
62
- readonly width: number;
63
- readonly height: number;
64
- readonly format?: TextureFormat;
65
- readonly colorSpace?: "srgb" | "linear";
66
- readonly data?: TexturePixelData;
67
- readonly mipLevels?: readonly TextureMipLevelDescriptor[];
68
- readonly source?: TexImageSource;
69
- readonly fallbackData?: Uint8Array | Uint8ClampedArray;
70
- readonly fallbackMipLevels?: readonly TextureMipLevelDescriptor[];
71
- }
72
-
73
- export type GLTFImageDecoder = (image: GLTFImageAsset, imageIndex: number, asset: GLTFAsset) => DecodedGLTFImage | Promise<DecodedGLTFImage>;
74
-
75
- export interface GLTFRenderResourceOptions {
76
- readonly imageDecoder?: GLTFImageDecoder;
77
- readonly ktx2BasisTargetFormat?: KTX2BasisTargetFormat;
78
- readonly ktx2BasisTranscoderOptions?: KTX2BasisTextureTranscoderOptions;
79
- readonly materialVariant?: GLTFSceneCreateOptions["materialVariant"];
80
- readonly sceneIndex?: GLTFSceneCreateOptions["sceneIndex"];
81
- readonly sceneName?: GLTFSceneCreateOptions["sceneName"];
82
- readonly materialRenderStateOverrides?: readonly GLTFMaterialRenderStateOverride[];
83
- /**
84
- * When `true`, a texture that fails to fetch/decode aborts the whole asset load
85
- * (legacy behavior). When omitted/`false` (default), the loader logs a warning
86
- * and substitutes a neutral 1x1 texture so the material falls back to its
87
- * `baseColorFactor` and the rest of the asset still loads.
88
- */
89
- readonly failOnMissingTexture?: boolean;
90
- }
91
-
92
- export interface GLTFMaterialRenderStateOverride {
93
- readonly materialName: string | RegExp;
94
- readonly renderState: Partial<RenderState>;
95
- readonly reason?: string;
96
- }
97
-
98
- export interface GLTFRenderResources {
99
- readonly scene: ReturnType<GLTFAsset["createScene"]>;
100
- readonly geometryLibrary: ReadonlyMap<string, Geometry>;
101
- readonly materialLibrary: ReadonlyMap<string, Material>;
102
- readonly renderableBindings: readonly GLTFRenderableBinding[];
103
- readonly materialFidelityDiagnostics: readonly GLTFRenderResourceMaterialFidelityDiagnostic[];
104
- readonly morphTargetLibrary: ReadonlyMap<string, readonly MorphTargetDelta[]>;
105
- readonly textureLibrary: ReadonlyMap<string, Texture>;
106
- readonly bounds: CameraFrameBounds;
107
- collectMaterialOverrideTargets(query?: GLTFMaterialOverrideQuery): readonly GLTFMaterialOverrideTarget[];
108
- createCameraFrame(viewport: CameraFrameViewport, options?: PerspectiveCameraFrameOptions): PerspectiveCameraFrame;
109
- toRenderSource(options?: GLTFRenderSourceOptions): RenderSource;
110
- toRendererInput(viewport: CameraFrameViewport, options?: GLTFRendererInputOptions): GLTFRendererInput;
111
- dispose(): void;
112
- }
113
-
114
- export interface GLTFRenderableBinding {
115
- readonly nodeName: string;
116
- readonly geometryKey: string;
117
- readonly materialKey: string;
118
- readonly sourceMaterialName: string;
119
- readonly sourceMaterialIndex?: number;
120
- readonly sourceMeshIndex?: number;
121
- readonly primitiveIndex?: number;
122
- readonly materialVariants: readonly GLTFMaterialVariantMappingAsset[];
123
- readonly skinned: boolean;
124
- readonly instanced: boolean;
125
- }
126
-
127
- export type GLTFRenderResourceMaterialFidelityIssue =
128
- | "unsupported-texcoord-set"
129
- | "generated-tangent-uv-mismatch";
130
-
131
- export interface GLTFRenderResourceMaterialFidelityDiagnostic {
132
- readonly issue: GLTFRenderResourceMaterialFidelityIssue;
133
- readonly slot: TexturedPBRTextureSlot;
134
- readonly texCoord: number;
135
- readonly renderedTexCoord: number;
136
- readonly nodeName: string;
137
- readonly geometryKey: string;
138
- readonly materialKey: string;
139
- readonly sourceMaterialName: string;
140
- readonly sourceMaterialIndex?: number;
141
- readonly sourceMeshIndex?: number;
142
- readonly primitiveIndex?: number;
143
- readonly detail: string;
144
- }
145
-
146
- export interface GLTFMaterialOverrideQuery {
147
- readonly nodeName?: string | RegExp;
148
- readonly sourceMaterialName?: string | RegExp;
149
- readonly materialKey?: string | RegExp;
150
- readonly variant?: string;
151
- readonly uniqueMaterials?: boolean;
152
- }
153
-
154
- export interface GLTFMaterialOverrideTarget extends GLTFRenderableBinding {
155
- readonly material: Material;
156
- }
157
-
158
- export interface GLTFRendererInput extends RendererInput {
159
- readonly source: RenderSource;
160
- readonly camera: CameraLike;
161
- readonly frame: PerspectiveCameraFrame;
162
- readonly bounds: CameraFrameBounds;
163
- }
164
-
165
- export interface GLTFRendererInputOptions extends GLTFRenderSourceOptions {
166
- readonly frame?: PerspectiveCameraFrameOptions;
167
- }
168
-
169
- export type GLTFRenderQualityPreset = "default" | "studio-preview" | "hdr-studio-preview";
170
-
171
- export interface GLTFRenderSourceOptions {
172
- readonly qualityPreset?: GLTFRenderQualityPreset;
173
- readonly environmentLighting?: EnvironmentLightingOptions | false;
174
- readonly shadowMap?: ForwardShadowMapOptions;
175
- readonly shadow?: RendererShadowOptions | boolean;
176
- readonly collectedLights?: Iterable<CollectedLight>;
177
- readonly postprocess?: RendererPostProcessOptions | boolean;
178
- readonly renderItems?: Iterable<RenderItem>;
179
- readonly cameraPolicy?: RendererCameraPolicy;
180
- readonly cameraFrameBounds?: CameraFrameBounds;
181
- readonly cameraFrameOptions?: PerspectiveCameraFrameOptions;
182
- readonly cameraPosition?: readonly [number, number, number];
183
- readonly frustumCulling?: boolean;
184
- }
185
-
186
- export interface GLTFRenderResourceDiagnosticsOptions {
187
- readonly label?: string;
188
- readonly suspectStaticNodePattern?: RegExp;
189
- }
190
-
191
- export interface GLTFRenderResourceDiagnostics {
192
- readonly label: string;
193
- readonly drawItems: number;
194
- readonly skinnedDrawItems: number;
195
- readonly texturedDrawItems: number;
196
- readonly baseColorTextureDrawItems: number;
197
- readonly colorBearingTextureDrawItems: number;
198
- readonly surfaceDetailTextureDrawItems: number;
199
- readonly effectiveTextureBackedDrawItems: number;
200
- readonly unsupportedTexCoordDrawItems: number;
201
- readonly generatedTangentUvMismatchDrawItems: number;
202
- readonly texturedSkinnedDrawItems: number;
203
- readonly untexturedSkinnedDrawItems: number;
204
- readonly fallbackWhiteDrawItems: number;
205
- readonly missingGeometryDrawItems: number;
206
- readonly missingMaterialDrawItems: number;
207
- readonly materialCount: number;
208
- readonly textureCount: number;
209
- readonly textureBackedMaterialNames: readonly string[];
210
- readonly textureSlotDiagnostics: readonly GLTFRenderResourceTextureSlotDiagnostic[];
211
- readonly textureContributionDiagnostics: readonly GLTFRenderResourceTextureContributionDiagnostic[];
212
- readonly suppressedTextureSlotDiagnostics: readonly GLTFRenderResourceTextureContributionDiagnostic[];
213
- readonly materialFidelityDiagnostics: readonly GLTFRenderResourceMaterialFidelityDiagnostic[];
214
- readonly shaderActiveTextureSlotDiagnostics: readonly GLTFRenderResourceTextureSlotDiagnostic[];
215
- readonly shaderInactiveTextureSlotDiagnostics: readonly GLTFRenderResourceTextureSlotDiagnostic[];
216
- readonly fallbackWhiteMaterialNames: readonly string[];
217
- readonly skinnedLabels: readonly string[];
218
- readonly untexturedSkinnedLabels: readonly string[];
219
- readonly fallbackWhiteLabels: readonly string[];
220
- readonly missingGeometryLabels: readonly string[];
221
- readonly missingMaterialLabels: readonly string[];
222
- readonly suspectStaticLabels: readonly string[];
223
- }
224
-
225
- export interface GLTFRenderResourceTextureSlotDiagnostic {
226
- readonly slot: TexturedPBRTextureSlot;
227
- readonly drawItems: number;
228
- readonly materialNames: readonly string[];
229
- readonly labels: readonly string[];
230
- }
231
-
232
- export type GLTFRenderResourceTextureContribution = "color-bearing" | "surface-detail" | "suppressed";
233
-
234
- export interface GLTFRenderResourceTextureContributionDiagnostic extends GLTFRenderResourceTextureSlotDiagnostic {
235
- readonly contribution: GLTFRenderResourceTextureContribution;
236
- }
237
-
238
- type GLTFTextureColorSpace = "srgb" | "linear";
239
-
240
- const GLTF_DIAGNOSTIC_TEXTURE_BINDINGS: readonly (readonly [slot: TexturedPBRTextureSlot, textureParameter: string, enabledParameter: string])[] = [
241
- ["baseColor", "u_baseColorTexture", "u_baseColorTextureEnabled"],
242
- ["normal", "u_normalTexture", "u_normalTextureEnabled"],
243
- ["metallicRoughness", "u_metallicRoughnessTexture", "u_metallicRoughnessTextureEnabled"],
244
- ["occlusion", "u_occlusionTexture", "u_occlusionTextureEnabled"],
245
- ["emissive", "u_emissiveTexture", "u_emissiveTextureEnabled"],
246
- ["clearcoat", "u_clearcoatTexture", "u_clearcoatTextureEnabled"],
247
- ["clearcoatRoughness", "u_clearcoatRoughnessTexture", "u_clearcoatRoughnessTextureEnabled"],
248
- ["clearcoatNormal", "u_clearcoatNormalTexture", "u_clearcoatNormalTextureEnabled"],
249
- ["transmission", "u_transmissionTexture", "u_transmissionTextureEnabled"],
250
- ["diffuseTransmission", "u_diffuseTransmissionTexture", "u_diffuseTransmissionTextureEnabled"],
251
- ["diffuseTransmissionColor", "u_diffuseTransmissionColorTexture", "u_diffuseTransmissionColorTextureEnabled"],
252
- ["volumeThickness", "u_volumeThicknessTexture", "u_volumeThicknessTextureEnabled"],
253
- ["specular", "u_specularTexture", "u_specularTextureEnabled"],
254
- ["specularColor", "u_specularColorTexture", "u_specularColorTextureEnabled"],
255
- ["sheenColor", "u_sheenColorTexture", "u_sheenColorTextureEnabled"],
256
- ["sheenRoughness", "u_sheenRoughnessTexture", "u_sheenRoughnessTextureEnabled"],
257
- ["anisotropy", "u_anisotropyTexture", "u_anisotropyTextureEnabled"],
258
- ["iridescence", "u_iridescenceTexture", "u_iridescenceTextureEnabled"],
259
- ["iridescenceThickness", "u_iridescenceThicknessTexture", "u_iridescenceThicknessTextureEnabled"]
260
- ];
261
-
262
- export const DEFAULT_GLTF_RENDER_ENVIRONMENT_LIGHTING: EnvironmentLightingOptions = {
263
- color: [0.72, 0.74, 0.78],
264
- intensity: 0.38,
265
- proceduralMap: {
266
- skyColor: [0.62, 0.72, 0.9],
267
- horizonColor: [0.9, 0.82, 0.66],
268
- groundColor: [0.16, 0.16, 0.18],
269
- specularColor: [1, 0.92, 0.78],
270
- intensity: 0.42,
271
- specularIntensity: 0.7
272
- }
273
- };
274
-
275
- export const DEFAULT_GLTF_STUDIO_PREVIEW_ENVIRONMENT_LIGHTING: EnvironmentLightingOptions = {
276
- color: [0.82, 0.84, 0.88],
277
- intensity: 0.5,
278
- proceduralMap: {
279
- skyColor: [0.72, 0.82, 0.95],
280
- horizonColor: [1, 0.9, 0.72],
281
- groundColor: [0.12, 0.13, 0.15],
282
- specularColor: [1, 0.95, 0.82],
283
- intensity: 0.62,
284
- specularIntensity: 1.15
285
- }
286
- };
287
-
288
- export function createDefaultGLTFHdrStudioPreviewEnvironmentLighting(): EnvironmentLightingOptions {
289
- return createExternalParityEnvironmentLighting("studio").lighting;
290
- }
291
-
292
- export const DEFAULT_GLTF_STUDIO_PREVIEW_POSTPROCESS: RendererPostProcessOptions = {
293
- targetFormat: "rgba8",
294
- toneMapping: {
295
- exposure: 1.18,
296
- operator: "filmic",
297
- inputColorSpace: "linear",
298
- outputColorSpace: "srgb"
299
- },
300
- colorGrade: {
301
- contrast: 1.08,
302
- saturation: 1.06,
303
- vibrance: 0.1,
304
- vignette: 0.18,
305
- sharpening: 0.28
306
- },
307
- bloom: {
308
- threshold: 0.82,
309
- intensity: 0.08,
310
- radius: 1
311
- },
312
- fxaa: {
313
- edgeThreshold: 0.08,
314
- subpixelBlend: 0.55
315
- }
316
- };
317
-
318
- export const DEFAULT_GLTF_HDR_STUDIO_PREVIEW_POSTPROCESS: RendererPostProcessOptions = {
319
- targetFormat: "rgba16f",
320
- toneMapping: {
321
- exposure: 1.12,
322
- whitePoint: 1.25,
323
- operator: "filmic",
324
- inputColorSpace: "linear",
325
- outputColorSpace: "srgb"
326
- },
327
- colorGrade: {
328
- contrast: 1.1,
329
- saturation: 1.06,
330
- vibrance: 0.12,
331
- vignette: 0.16,
332
- sharpening: 0.32
333
- },
334
- bloom: {
335
- threshold: 0.9,
336
- intensity: 0.12,
337
- radius: 1
338
- },
339
- fxaa: {
340
- edgeThreshold: 0.08,
341
- subpixelBlend: 0.55
342
- }
343
- };
344
-
345
- export const DEFAULT_GLTF_STUDIO_PREVIEW_FRAME: PerspectiveCameraFrameOptions = {
346
- paddingRatio: 0.16,
347
- yawRadians: -0.38,
348
- pitchRadians: -0.16,
349
- nearPadding: 0.18,
350
- farPadding: 2.4
351
- };
352
-
353
- export async function createGLTFRenderResources(
354
- asset: GLTFAsset,
355
- options: GLTFRenderResourceOptions = {}
356
- ): Promise<GLTFRenderResources> {
357
- const geometryLibrary = new Map<string, Geometry>();
358
- const materialLibrary = new Map<string, Material>();
359
- const morphTargetLibrary = new Map<string, readonly MorphTargetDelta[]>();
360
- const textureLibrary = new Map<string, Texture>();
361
- const textureByImage = new Map<string, Promise<Texture>>();
362
- const scene = asset.createScene({
363
- ...(options.materialVariant ? { materialVariant: options.materialVariant } : {}),
364
- ...(options.sceneIndex !== undefined ? { sceneIndex: options.sceneIndex } : {}),
365
- ...(options.sceneName !== undefined ? { sceneName: options.sceneName } : {})
366
- });
367
-
368
- const getTexture = async (info: GLTFResolvedTextureInfo, colorSpace: GLTFTextureColorSpace): Promise<Texture> => {
369
- const textureAsset = asset.textures[info.texture];
370
- const image = asset.images[info.image];
371
- if (!textureAsset || !image) {
372
- throw new Error(`glTF material texture ${info.texture} references missing image ${info.image}`);
373
- }
374
- const cacheKey = textureCacheKey(info.image, colorSpace);
375
- const existing = textureByImage.get(cacheKey);
376
- if (existing) {
377
- const texture = await existing;
378
- setTextureLibraryEntry(textureLibrary, textureAsset.name, colorSpace, texture);
379
- return texture;
380
- }
381
- const decoder = options.imageDecoder ?? ((sourceImage, imageIndex, sourceAsset) => decodeImageInBrowser(sourceImage, imageIndex, sourceAsset, options));
382
- const texturePromise = (async () => {
383
- const decoded = await decoder(image, info.image, asset);
384
- return new Texture({
385
- width: decoded.width,
386
- height: decoded.height,
387
- ...(decoded.format ? { format: decoded.format } : {}),
388
- colorSpace,
389
- label: textureAsset.name,
390
- ...(decoded.mipLevels ? { mipLevels: decoded.mipLevels } : decoded.data ? { data: decoded.data } : { source: decoded.source }),
391
- ...(decoded.fallbackData ? { fallbackData: decoded.fallbackData } : {}),
392
- ...(decoded.fallbackMipLevels ? { fallbackMipLevels: decoded.fallbackMipLevels } : {})
393
- });
394
- })();
395
- textureByImage.set(cacheKey, texturePromise);
396
- try {
397
- const texture = await texturePromise;
398
- setTextureLibraryEntry(textureLibrary, textureAsset.name, colorSpace, texture);
399
- return texture;
400
- } catch (error) {
401
- textureByImage.delete(cacheKey);
402
- if (options.failOnMissingTexture) {
403
- throw error;
404
- }
405
- const reason = error instanceof Error ? error.message : String(error);
406
- warnMissingGLTFTexture(textureAsset.name, image.uri, reason);
407
- const fallback = createFallbackTexture(textureAsset.name, colorSpace);
408
- const fallbackPromise = Promise.resolve(fallback);
409
- textureByImage.set(cacheKey, fallbackPromise);
410
- setTextureLibraryEntry(textureLibrary, textureAsset.name, colorSpace, fallback);
411
- return fallback;
412
- }
413
- };
414
-
415
- try {
416
- for (const mesh of asset.meshes) {
417
- geometryLibrary.set(mesh.name, createGeometry(mesh, materialForMesh(asset, mesh, options.materialVariant)));
418
- if (mesh.morphTargets.length > 0) {
419
- morphTargetLibrary.set(mesh.name, mesh.morphTargets.map((target) => ({
420
- ...(target.name ? { name: target.name } : {}),
421
- positions: target.positions,
422
- normals: target.normals,
423
- tangents: target.tangents
424
- })));
425
- }
426
- }
427
-
428
- const runtimeMaterialContracts = new Map<string, ReturnType<typeof parseGLTFRuntimeMaterialKey>>();
429
- for (const { renderable } of scene.collectRenderables()) {
430
- const parsed = parseGLTFRuntimeMaterialKey(renderable.material);
431
- runtimeMaterialContracts.set(renderable.material, {
432
- material: parsed.material,
433
- contract: {
434
- ...parsed.contract,
435
- ...(renderable.skinning ? { skinned: true } : {}),
436
- ...(renderable.instanceTransforms ? { instanced: true } : {})
437
- }
438
- });
439
- }
440
- const materialTasks: Promise<void>[] = [];
441
- for (const material of asset.materials) {
442
- const runtimeKeys = [...runtimeMaterialContracts.entries()].filter(([, runtime]) => runtime.material === material.name);
443
- if (runtimeKeys.length === 0) {
444
- materialTasks.push(createMaterial(asset, material, getTexture, {}, options.materialRenderStateOverrides).then((runtimeMaterial) => {
445
- materialLibrary.set(material.name, runtimeMaterial);
446
- }));
447
- continue;
448
- }
449
- for (const [key, runtime] of runtimeKeys) {
450
- materialTasks.push(createMaterial(asset, material, getTexture, runtime.contract, options.materialRenderStateOverrides).then((runtimeMaterial) => {
451
- materialLibrary.set(key, runtimeMaterial);
452
- }));
453
- }
454
- }
455
- await Promise.all(materialTasks);
456
-
457
- for (const mesh of asset.meshes) {
458
- for (const [key, runtime] of runtimeMaterialContracts) {
459
- if (runtime.material === mesh.material && !materialLibrary.has(key)) {
460
- materialLibrary.set(key, createDefaultGLTFMaterial(mesh, runtime.contract));
461
- }
462
- }
463
- if (!materialLibrary.has(mesh.material)) {
464
- materialLibrary.set(mesh.material, createDefaultGLTFMaterial(mesh));
465
- }
466
- }
467
- } catch (error) {
468
- disposeGLTFRenderResourceMaps(geometryLibrary, textureLibrary);
469
- throw error;
470
- }
471
- const bounds = computeGLTFRenderResourceBounds(scene, geometryLibrary, morphTargetLibrary);
472
- const renderableBindings = createGLTFRenderableBindings(asset, scene);
473
- const materialFidelityDiagnostics = createGLTFMaterialFidelityDiagnostics(asset, renderableBindings, options.materialVariant);
474
-
475
- return {
476
- scene,
477
- geometryLibrary,
478
- materialLibrary,
479
- renderableBindings,
480
- materialFidelityDiagnostics,
481
- morphTargetLibrary,
482
- textureLibrary,
483
- bounds,
484
- collectMaterialOverrideTargets: (query = {}) => collectGLTFMaterialOverrideTargets(renderableBindings, materialLibrary, query),
485
- createCameraFrame: (viewport, frameOptions = {}) => computePerspectiveCameraFrame(bounds, viewport, defaultGLTFCameraFrameOptions(bounds, frameOptions)),
486
- toRenderSource: (sourceOptions = {}) => createGLTFRenderSource({
487
- scene,
488
- geometryLibrary,
489
- materialLibrary,
490
- morphTargetLibrary,
491
- bounds
492
- }, sourceOptions),
493
- toRendererInput: (viewport, inputOptions = {}) => {
494
- const { frame: frameOptions, ...sourceOptions } = inputOptions;
495
- const qualityPreset = sourceOptions.qualityPreset ?? "studio-preview";
496
- const frame = computePerspectiveCameraFrame(bounds, viewport, defaultGLTFCameraFrameOptions(bounds, frameOptions));
497
- return {
498
- source: createGLTFRenderSource({
499
- scene,
500
- geometryLibrary,
501
- materialLibrary,
502
- morphTargetLibrary,
503
- bounds
504
- }, {
505
- ...sourceOptions,
506
- qualityPreset,
507
- cameraPosition: sourceOptions.cameraPosition ?? frame.cameraPosition,
508
- cameraPolicy: sourceOptions.cameraPolicy ?? "require"
509
- }),
510
- camera: {
511
- viewProjectionMatrix: frame.viewProjectionMatrix,
512
- viewMatrix: frame.viewMatrix,
513
- projectionMatrix: frame.projectionMatrix
514
- },
515
- frame,
516
- bounds
517
- };
518
- },
519
- dispose: () => disposeGLTFRenderResourceMaps(geometryLibrary, textureLibrary)
520
- };
521
- }
522
-
523
- function createGLTFRenderableBindings(
524
- asset: GLTFAsset,
525
- scene: ReturnType<GLTFAsset["createScene"]>
526
- ): readonly GLTFRenderableBinding[] {
527
- const meshByGeometry = new Map(asset.meshes.map((mesh) => [mesh.name, mesh]));
528
- return scene.collectRenderables().map(({ node, renderable }) => {
529
- const mesh = meshByGeometry.get(renderable.geometry);
530
- const materialKey = renderable.material;
531
- const parsedMaterial = parseGLTFRuntimeMaterialKey(materialKey);
532
- return {
533
- nodeName: node.name,
534
- geometryKey: renderable.geometry,
535
- materialKey,
536
- sourceMaterialName: parsedMaterial.material,
537
- ...(mesh?.materialIndex !== undefined ? { sourceMaterialIndex: mesh.materialIndex } : {}),
538
- ...(mesh?.sourceMeshIndex !== undefined ? { sourceMeshIndex: mesh.sourceMeshIndex } : {}),
539
- ...(mesh?.primitiveIndex !== undefined ? { primitiveIndex: mesh.primitiveIndex } : {}),
540
- materialVariants: mesh?.materialVariants ?? [],
541
- skinned: Boolean(renderable.skinning),
542
- instanced: Boolean(renderable.instanceTransforms)
543
- };
544
- });
545
- }
546
-
547
- function createGLTFMaterialFidelityDiagnostics(
548
- asset: GLTFAsset,
549
- bindings: readonly GLTFRenderableBinding[],
550
- materialVariant: string | undefined
551
- ): readonly GLTFRenderResourceMaterialFidelityDiagnostic[] {
552
- const diagnostics: GLTFRenderResourceMaterialFidelityDiagnostic[] = [];
553
- const meshByGeometry = new Map(asset.meshes.map((mesh) => [mesh.name, mesh]));
554
- for (const binding of bindings) {
555
- const mesh = meshByGeometry.get(binding.geometryKey);
556
- if (!mesh) continue;
557
- const material = materialForMesh(asset, mesh, materialVariant);
558
- if (!material) continue;
559
- for (const { slot, info, tangentSpace } of materialTextureInfosBySlot(material)) {
560
- const renderedTexCoord = renderTexCoord(info.texCoord);
561
- if (info.texCoord > 1) {
562
- diagnostics.push({
563
- issue: "unsupported-texcoord-set",
564
- slot,
565
- texCoord: info.texCoord,
566
- renderedTexCoord,
567
- ...materialFidelityBindingFields(binding),
568
- detail: `glTF ${slot} texture requests TEXCOORD_${info.texCoord}, but current WebGL render resources only bind TEXCOORD_0 and TEXCOORD_1; the shader samples TEXCOORD_${renderedTexCoord}.`
569
- });
570
- }
571
- if (tangentSpace && mesh.tangents.length === 0 && info.texCoord > 0) {
572
- diagnostics.push({
573
- issue: "generated-tangent-uv-mismatch",
574
- slot,
575
- texCoord: info.texCoord,
576
- renderedTexCoord,
577
- ...materialFidelityBindingFields(binding),
578
- detail: `glTF ${slot} texture samples TEXCOORD_${info.texCoord}, but generated tangents are derived from TEXCOORD_0 when source tangents are absent.`
579
- });
580
- }
581
- }
582
- }
583
- return diagnostics;
584
- }
585
-
586
- function materialFidelityBindingFields(binding: GLTFRenderableBinding): Omit<GLTFRenderResourceMaterialFidelityDiagnostic, "issue" | "slot" | "texCoord" | "renderedTexCoord" | "detail"> {
587
- return {
588
- nodeName: binding.nodeName,
589
- geometryKey: binding.geometryKey,
590
- materialKey: binding.materialKey,
591
- sourceMaterialName: binding.sourceMaterialName,
592
- ...(binding.sourceMaterialIndex !== undefined ? { sourceMaterialIndex: binding.sourceMaterialIndex } : {}),
593
- ...(binding.sourceMeshIndex !== undefined ? { sourceMeshIndex: binding.sourceMeshIndex } : {}),
594
- ...(binding.primitiveIndex !== undefined ? { primitiveIndex: binding.primitiveIndex } : {})
595
- };
596
- }
597
-
598
- function collectGLTFMaterialOverrideTargets(
599
- bindings: readonly GLTFRenderableBinding[],
600
- materialLibrary: ReadonlyMap<string, Material>,
601
- query: GLTFMaterialOverrideQuery
602
- ): readonly GLTFMaterialOverrideTarget[] {
603
- const uniqueMaterials = query.uniqueMaterials ?? true;
604
- const seen = new Set<string>();
605
- const targets: GLTFMaterialOverrideTarget[] = [];
606
- for (const binding of bindings) {
607
- if (!matchesGLTFMaterialOverrideQuery(binding, query)) continue;
608
- if (uniqueMaterials && seen.has(binding.materialKey)) continue;
609
- const material = materialLibrary.get(binding.materialKey);
610
- if (!material) continue;
611
- seen.add(binding.materialKey);
612
- targets.push({ ...binding, material });
613
- }
614
- return targets;
615
- }
616
-
617
- function matchesGLTFMaterialOverrideQuery(binding: GLTFRenderableBinding, query: GLTFMaterialOverrideQuery): boolean {
618
- if (query.nodeName && !matchesTextOrPattern(binding.nodeName, query.nodeName)) return false;
619
- if (query.sourceMaterialName && !matchesTextOrPattern(binding.sourceMaterialName, query.sourceMaterialName)) return false;
620
- if (query.materialKey && !matchesTextOrPattern(binding.materialKey, query.materialKey)) return false;
621
- if (query.variant && !binding.materialVariants.some((variant) => variant.variant === query.variant)) return false;
622
- return true;
623
- }
624
-
625
- function matchesTextOrPattern(value: string, matcher: string | RegExp): boolean {
626
- return typeof matcher === "string" ? value === matcher : matcher.test(value);
627
- }
628
-
629
- export function createGLTFRenderSource(
630
- resources: Pick<GLTFRenderResources, "scene" | "geometryLibrary" | "materialLibrary" | "morphTargetLibrary" | "bounds">,
631
- options: GLTFRenderSourceOptions = {}
632
- ): RenderSource {
633
- const qualityPreset = options.qualityPreset ?? "studio-preview";
634
- const environmentLighting = options.environmentLighting === false
635
- ? false
636
- : options.environmentLighting ?? cloneEnvironmentLighting(defaultEnvironmentLightingForPreset(qualityPreset));
637
- const postprocess = options.postprocess !== undefined
638
- ? options.postprocess
639
- : qualityPreset !== "default"
640
- ? cloneRendererPostprocess(defaultPostprocessForPreset(qualityPreset))
641
- : undefined;
642
- return {
643
- scene: resources.scene,
644
- geometryLibrary: resources.geometryLibrary,
645
- materialLibrary: resources.materialLibrary,
646
- morphTargetLibrary: resources.morphTargetLibrary,
647
- ...(options.renderItems ? { renderItems: options.renderItems } : {}),
648
- ...(environmentLighting !== undefined ? { environmentLighting } : {}),
649
- ...(options.shadowMap ? { shadowMap: options.shadowMap } : {}),
650
- ...(options.shadow !== undefined ? { shadow: options.shadow } : {}),
651
- ...(options.collectedLights ? { collectedLights: options.collectedLights } : {}),
652
- ...(postprocess !== undefined ? { postprocess } : {}),
653
- ...(options.cameraPolicy ? { cameraPolicy: options.cameraPolicy } : {}),
654
- ...(options.cameraFrameBounds ? { cameraFrameBounds: options.cameraFrameBounds } : { cameraFrameBounds: resources.bounds }),
655
- ...(options.cameraFrameOptions ? { cameraFrameOptions: options.cameraFrameOptions } : {}),
656
- ...(options.cameraPosition ? { cameraPosition: options.cameraPosition } : {}),
657
- ...(options.frustumCulling !== undefined ? { frustumCulling: options.frustumCulling } : {})
658
- };
659
- }
660
-
661
- export function createGLTFRenderResourceDiagnostics(
662
- resources: Pick<GLTFRenderResources, "scene" | "geometryLibrary" | "materialLibrary"> & Partial<Pick<GLTFRenderResources, "textureLibrary" | "materialFidelityDiagnostics">>,
663
- options: GLTFRenderResourceDiagnosticsOptions = {}
664
- ): GLTFRenderResourceDiagnostics {
665
- const label = options.label ?? "gltf-render-resources";
666
- const textureBackedMaterialNames = new Set<string>();
667
- const textureSlotDiagnostics = new Map<string, { drawItems: number; materialNames: Set<string>; labels: string[] }>();
668
- const textureContributionDiagnostics = new Map<string, { drawItems: number; materialNames: Set<string>; labels: string[] }>();
669
- const suppressedTextureSlotDiagnostics = new Map<string, { drawItems: number; materialNames: Set<string>; labels: string[] }>();
670
- const shaderActiveTextureSlotDiagnostics = new Map<string, { drawItems: number; materialNames: Set<string>; labels: string[] }>();
671
- const shaderInactiveTextureSlotDiagnostics = new Map<string, { drawItems: number; materialNames: Set<string>; labels: string[] }>();
672
- const fallbackWhiteMaterialNames = new Set<string>();
673
- const skinnedLabels: string[] = [];
674
- const untexturedSkinnedLabels: string[] = [];
675
- const fallbackWhiteLabels: string[] = [];
676
- const missingGeometryLabels: string[] = [];
677
- const missingMaterialLabels: string[] = [];
678
- const suspectStaticLabels: string[] = [];
679
- let drawItems = 0;
680
- let skinnedDrawItems = 0;
681
- let texturedDrawItems = 0;
682
- let baseColorTextureDrawItems = 0;
683
- let colorBearingTextureDrawItems = 0;
684
- let surfaceDetailTextureDrawItems = 0;
685
- let effectiveTextureBackedDrawItems = 0;
686
- let texturedSkinnedDrawItems = 0;
687
- let missingGeometryDrawItems = 0;
688
- let missingMaterialDrawItems = 0;
689
-
690
- resources.scene.updateWorldTransforms();
691
- for (const { node, renderable } of resources.scene.collectRenderables()) {
692
- const itemLabel = `${node.name}:${renderable.geometry}`;
693
- const geometry = resources.geometryLibrary.get(renderable.geometry);
694
- const material = resources.materialLibrary.get(renderable.material);
695
- if (!geometry) {
696
- missingGeometryDrawItems += 1;
697
- missingGeometryLabels.push(itemLabel);
698
- }
699
- if (!material) {
700
- missingMaterialDrawItems += 1;
701
- missingMaterialLabels.push(itemLabel);
702
- }
703
- if (!geometry || !material) continue;
704
-
705
- drawItems += 1;
706
- const isSkinned = Boolean(renderable.skinning);
707
- const validTextureSlots = GLTF_DIAGNOSTIC_TEXTURE_BINDINGS.filter(([, textureParameter, enabledParameter]) =>
708
- materialHasValidTextureBinding(material, textureParameter, enabledParameter)
709
- );
710
- const hasAnyTexture = validTextureSlots.length > 0;
711
- const hasBaseColorTexture = materialHasValidTextureBinding(material, "u_baseColorTexture", "u_baseColorTextureEnabled");
712
- if (isSkinned) {
713
- skinnedDrawItems += 1;
714
- skinnedLabels.push(itemLabel);
715
- }
716
- if (hasAnyTexture) {
717
- texturedDrawItems += 1;
718
- textureBackedMaterialNames.add(material.name);
719
- }
720
- let hasEffectiveBaseColorTexture = false;
721
- let hasColorBearingTexture = false;
722
- let hasSurfaceDetailTexture = false;
723
- for (const [slot] of validTextureSlots) {
724
- addTextureSlotDiagnostic(textureSlotDiagnostics, slot, material.name, itemLabel);
725
- const shaderActive = materialSamplesTextureSlot(material, slot);
726
- const shaderSlotMap = shaderActive ? shaderActiveTextureSlotDiagnostics : shaderInactiveTextureSlotDiagnostics;
727
- addTextureSlotDiagnostic(shaderSlotMap, slot, material.name, itemLabel);
728
- const contribution = shaderActive ? textureContributionForSlot(material, slot) : "suppressed";
729
- if (contribution === "color-bearing") {
730
- hasColorBearingTexture = true;
731
- if (slot === "baseColor") hasEffectiveBaseColorTexture = true;
732
- addTextureContributionDiagnostic(textureContributionDiagnostics, contribution, slot, material.name, itemLabel);
733
- } else if (contribution === "surface-detail") {
734
- hasSurfaceDetailTexture = true;
735
- addTextureContributionDiagnostic(textureContributionDiagnostics, contribution, slot, material.name, itemLabel);
736
- } else {
737
- addTextureContributionDiagnostic(suppressedTextureSlotDiagnostics, contribution, slot, material.name, itemLabel);
738
- }
739
- }
740
- if (hasEffectiveBaseColorTexture) baseColorTextureDrawItems += 1;
741
- if (hasColorBearingTexture) colorBearingTextureDrawItems += 1;
742
- if (hasSurfaceDetailTexture) surfaceDetailTextureDrawItems += 1;
743
- if (hasColorBearingTexture || hasSurfaceDetailTexture) effectiveTextureBackedDrawItems += 1;
744
- if (isSkinned && hasBaseColorTexture) texturedSkinnedDrawItems += 1;
745
- if (isSkinned && !hasBaseColorTexture) untexturedSkinnedLabels.push(itemLabel);
746
- if (isFallbackWhiteRuntimeMaterial(material)) {
747
- fallbackWhiteLabels.push(itemLabel);
748
- fallbackWhiteMaterialNames.add(material.name);
749
- }
750
- if (!isSkinned && options.suspectStaticNodePattern?.test(node.name)) suspectStaticLabels.push(itemLabel);
751
- }
752
-
753
- return {
754
- label,
755
- drawItems,
756
- skinnedDrawItems,
757
- texturedDrawItems,
758
- baseColorTextureDrawItems,
759
- colorBearingTextureDrawItems,
760
- surfaceDetailTextureDrawItems,
761
- effectiveTextureBackedDrawItems,
762
- unsupportedTexCoordDrawItems: countDistinctMaterialFidelityDrawItems(resources.materialFidelityDiagnostics, "unsupported-texcoord-set"),
763
- generatedTangentUvMismatchDrawItems: countDistinctMaterialFidelityDrawItems(resources.materialFidelityDiagnostics, "generated-tangent-uv-mismatch"),
764
- texturedSkinnedDrawItems,
765
- untexturedSkinnedDrawItems: untexturedSkinnedLabels.length,
766
- fallbackWhiteDrawItems: fallbackWhiteLabels.length,
767
- missingGeometryDrawItems,
768
- missingMaterialDrawItems,
769
- materialCount: resources.materialLibrary.size,
770
- textureCount: resources.textureLibrary?.size ?? 0,
771
- textureBackedMaterialNames: [...textureBackedMaterialNames].sort(),
772
- textureSlotDiagnostics: [...textureSlotDiagnostics.entries()]
773
- .sort(([left], [right]) => left.localeCompare(right))
774
- .map(([slot, diagnostics]) => ({
775
- slot: slot as TexturedPBRTextureSlot,
776
- drawItems: diagnostics.drawItems,
777
- materialNames: [...diagnostics.materialNames].sort(),
778
- labels: [...diagnostics.labels].sort()
779
- })),
780
- textureContributionDiagnostics: mapTextureContributionDiagnostics(textureContributionDiagnostics),
781
- suppressedTextureSlotDiagnostics: mapTextureContributionDiagnostics(suppressedTextureSlotDiagnostics),
782
- materialFidelityDiagnostics: resources.materialFidelityDiagnostics ?? [],
783
- shaderActiveTextureSlotDiagnostics: [...shaderActiveTextureSlotDiagnostics.entries()]
784
- .sort(([left], [right]) => left.localeCompare(right))
785
- .map(([slot, diagnostics]) => ({
786
- slot: slot as TexturedPBRTextureSlot,
787
- drawItems: diagnostics.drawItems,
788
- materialNames: [...diagnostics.materialNames].sort(),
789
- labels: [...diagnostics.labels].sort()
790
- })),
791
- shaderInactiveTextureSlotDiagnostics: [...shaderInactiveTextureSlotDiagnostics.entries()]
792
- .sort(([left], [right]) => left.localeCompare(right))
793
- .map(([slot, diagnostics]) => ({
794
- slot: slot as TexturedPBRTextureSlot,
795
- drawItems: diagnostics.drawItems,
796
- materialNames: [...diagnostics.materialNames].sort(),
797
- labels: [...diagnostics.labels].sort()
798
- })),
799
- fallbackWhiteMaterialNames: [...fallbackWhiteMaterialNames].sort(),
800
- skinnedLabels,
801
- untexturedSkinnedLabels,
802
- fallbackWhiteLabels,
803
- missingGeometryLabels,
804
- missingMaterialLabels,
805
- suspectStaticLabels
806
- };
807
- }
808
-
809
- function defaultEnvironmentLightingForPreset(preset: GLTFRenderQualityPreset): EnvironmentLightingOptions {
810
- if (preset === "hdr-studio-preview") return createDefaultGLTFHdrStudioPreviewEnvironmentLighting();
811
- if (preset === "studio-preview") return DEFAULT_GLTF_STUDIO_PREVIEW_ENVIRONMENT_LIGHTING;
812
- return DEFAULT_GLTF_RENDER_ENVIRONMENT_LIGHTING;
813
- }
814
-
815
- function addTextureSlotDiagnostic(
816
- diagnosticsBySlot: Map<string, { drawItems: number; materialNames: Set<string>; labels: string[] }>,
817
- slot: TexturedPBRTextureSlot,
818
- materialName: string,
819
- itemLabel: string
820
- ): void {
821
- let diagnostics = diagnosticsBySlot.get(slot);
822
- if (!diagnostics) {
823
- diagnostics = { drawItems: 0, materialNames: new Set(), labels: [] };
824
- diagnosticsBySlot.set(slot, diagnostics);
825
- }
826
- diagnostics.drawItems += 1;
827
- diagnostics.materialNames.add(materialName);
828
- diagnostics.labels.push(itemLabel);
829
- }
830
-
831
- function addTextureContributionDiagnostic(
832
- diagnosticsByContributionSlot: Map<string, { drawItems: number; materialNames: Set<string>; labels: string[] }>,
833
- contribution: GLTFRenderResourceTextureContribution,
834
- slot: TexturedPBRTextureSlot,
835
- materialName: string,
836
- itemLabel: string
837
- ): void {
838
- addTextureSlotDiagnostic(diagnosticsByContributionSlot, `${contribution}:${slot}` as TexturedPBRTextureSlot, materialName, itemLabel);
839
- }
840
-
841
- function mapTextureContributionDiagnostics(
842
- diagnosticsByContributionSlot: Map<string, { drawItems: number; materialNames: Set<string>; labels: string[] }>
843
- ): readonly GLTFRenderResourceTextureContributionDiagnostic[] {
844
- return [...diagnosticsByContributionSlot.entries()]
845
- .sort(([left], [right]) => left.localeCompare(right))
846
- .map(([key, diagnostics]) => {
847
- const [contribution, slot] = key.split(":") as [GLTFRenderResourceTextureContribution, TexturedPBRTextureSlot];
848
- return {
849
- contribution,
850
- slot,
851
- drawItems: diagnostics.drawItems,
852
- materialNames: [...diagnostics.materialNames].sort(),
853
- labels: [...diagnostics.labels].sort()
854
- };
855
- });
856
- }
857
-
858
- function countDistinctMaterialFidelityDrawItems(
859
- diagnostics: readonly GLTFRenderResourceMaterialFidelityDiagnostic[] | undefined,
860
- issue: GLTFRenderResourceMaterialFidelityIssue
861
- ): number {
862
- if (!diagnostics) return 0;
863
- const labels = new Set<string>();
864
- for (const diagnostic of diagnostics) {
865
- if (diagnostic.issue !== issue) continue;
866
- labels.add(`${diagnostic.nodeName}:${diagnostic.geometryKey}:${diagnostic.materialKey}`);
867
- }
868
- return labels.size;
869
- }
870
-
871
- function textureContributionForSlot(
872
- material: Material,
873
- slot: TexturedPBRTextureSlot
874
- ): GLTFRenderResourceTextureContribution {
875
- switch (slot) {
876
- case "baseColor":
877
- case "diffuseTransmissionColor":
878
- case "specularColor":
879
- case "sheenColor":
880
- return "color-bearing";
881
- case "emissive":
882
- return materialHasEmissiveContribution(material) ? "color-bearing" : "suppressed";
883
- case "normal":
884
- return numericMaterialParameter(material, "u_normalScale", 1) > 0.001 ? "surface-detail" : "suppressed";
885
- case "occlusion":
886
- return numericMaterialParameter(material, "u_occlusionStrength", 1) > 0.001 ? "surface-detail" : "suppressed";
887
- default:
888
- return "surface-detail";
889
- }
890
- }
891
-
892
- function numericMaterialParameter(material: Material, name: string, fallback: number): number {
893
- const value = material.getParameter(name);
894
- return typeof value === "number" && Number.isFinite(value) ? value : fallback;
895
- }
896
-
897
- function materialHasEmissiveContribution(material: Material): boolean {
898
- const strength = numericMaterialParameter(material, "u_emissiveStrength", 1);
899
- const color = material.getParameter("u_emissiveColor");
900
- if (strength <= 0.001) return false;
901
- if ((Array.isArray(color) || ArrayBuffer.isView(color)) && color.length >= 3) {
902
- return Math.max(Number(color[0]) || 0, Number(color[1]) || 0, Number(color[2]) || 0) > 0.001;
903
- }
904
- return true;
905
- }
906
-
907
- function materialSamplesTextureSlot(material: Material, slot: TexturedPBRTextureSlot): boolean {
908
- if (material.shaderKey !== DEFAULT_TEXTURED_PBR_SHADER_NAME) return true;
909
- return isTexturedPbrTextureSlotShaderActive(slot, material.shaderVariant);
910
- }
911
-
912
- function materialHasValidTextureBinding(material: Material, textureParameter: string, enabledParameter: string): boolean {
913
- const enabled = material.getParameter(enabledParameter);
914
- const binding = material.getParameter(textureParameter);
915
- const enabledByMaterial = enabled === undefined || enabled === 1;
916
- return enabledByMaterial
917
- && binding instanceof TextureBinding
918
- && Boolean(binding.texture)
919
- && !isGeneratedFallbackTexture(binding.texture)
920
- && binding.validate().ok;
921
- }
922
-
923
- function isFallbackWhiteRuntimeMaterial(material: Material): boolean {
924
- const baseColor = material.getParameter("u_baseColor");
925
- const metallic = numericMaterialParameter(material, "u_metallic", 0);
926
- const roughness = numericMaterialParameter(material, "u_roughness", 1);
927
- const transmission = numericMaterialParameter(material, "u_transmissionFactor", 0)
928
- + numericMaterialParameter(material, "u_diffuseTransmissionFactor", 0);
929
- const hasTexture = materialHasValidTextureBinding(material, "u_baseColorTexture", "u_baseColorTextureEnabled")
930
- || materialHasValidTextureBinding(material, "u_texture", "u_textureEnabled");
931
- return !hasTexture
932
- && transmission <= 0.001
933
- && !(metallic >= 0.9 && roughness <= 0.25)
934
- && (Array.isArray(baseColor) || ArrayBuffer.isView(baseColor))
935
- && baseColor.length >= 4
936
- && baseColor[0] >= 0.98
937
- && baseColor[1] >= 0.98
938
- && baseColor[2] >= 0.98
939
- && baseColor[3] >= 0.98;
940
- }
941
-
942
- function isGeneratedFallbackTexture(texture: Texture | null | undefined): boolean {
943
- if (!texture) return true;
944
- return /^default-(?:white|linear-white|flat-normal|metallic-roughness|occlusion|emissive|clearcoat|transmission|diffuse-transmission|volume-thickness|specular|sheen|anisotropy|iridescence)/.test(texture.label);
945
- }
946
-
947
- function defaultPostprocessForPreset(preset: Exclude<GLTFRenderQualityPreset, "default">): RendererPostProcessOptions {
948
- return preset === "hdr-studio-preview"
949
- ? DEFAULT_GLTF_HDR_STUDIO_PREVIEW_POSTPROCESS
950
- : DEFAULT_GLTF_STUDIO_PREVIEW_POSTPROCESS;
951
- }
952
-
953
- function cloneEnvironmentLighting(environment: EnvironmentLightingOptions): EnvironmentLightingOptions {
954
- return {
955
- color: [...environment.color] as [number, number, number],
956
- intensity: environment.intensity,
957
- ...(environment.proceduralMap
958
- ? {
959
- proceduralMap: {
960
- skyColor: [...environment.proceduralMap.skyColor] as [number, number, number],
961
- horizonColor: [...environment.proceduralMap.horizonColor] as [number, number, number],
962
- groundColor: [...environment.proceduralMap.groundColor] as [number, number, number],
963
- specularColor: [...environment.proceduralMap.specularColor] as [number, number, number],
964
- intensity: environment.proceduralMap.intensity,
965
- specularIntensity: environment.proceduralMap.specularIntensity
966
- }
967
- }
968
- : {}),
969
- ...(environment.environmentMapTexture ? { environmentMapTexture: environment.environmentMapTexture } : {}),
970
- ...(environment.environmentCubeMapTexture ? { environmentCubeMapTexture: environment.environmentCubeMapTexture } : {}),
971
- ...(environment.environmentMapIntensity !== undefined ? { environmentMapIntensity: environment.environmentMapIntensity } : {}),
972
- ...(environment.environmentMapSpecularIntensity !== undefined ? { environmentMapSpecularIntensity: environment.environmentMapSpecularIntensity } : {}),
973
- ...(environment.environmentMapRotation !== undefined ? { environmentMapRotation: environment.environmentMapRotation } : {}),
974
- ...(environment.environmentMapMipCount !== undefined ? { environmentMapMipCount: environment.environmentMapMipCount } : {}),
975
- ...(environment.environmentMapEncoding ? { environmentMapEncoding: environment.environmentMapEncoding } : {}),
976
- ...(environment.environmentBrdfLutTexture ? { environmentBrdfLutTexture: environment.environmentBrdfLutTexture } : {})
977
- };
978
- }
979
-
980
- function cloneRendererPostprocess(postprocess: RendererPostProcessOptions): RendererPostProcessOptions {
981
- return {
982
- ...(postprocess.targetFormat ? { targetFormat: postprocess.targetFormat } : {}),
983
- ...(postprocess.toneMapping !== undefined
984
- ? { toneMapping: typeof postprocess.toneMapping === "object" ? { ...postprocess.toneMapping } : postprocess.toneMapping }
985
- : {}),
986
- ...(postprocess.colorGrade !== undefined
987
- ? { colorGrade: typeof postprocess.colorGrade === "object" ? { ...postprocess.colorGrade } : postprocess.colorGrade }
988
- : {}),
989
- ...(postprocess.bloom !== undefined
990
- ? { bloom: typeof postprocess.bloom === "object" ? { ...postprocess.bloom } : postprocess.bloom }
991
- : {}),
992
- ...(postprocess.chromaticAberration !== undefined
993
- ? { chromaticAberration: typeof postprocess.chromaticAberration === "object" ? { ...postprocess.chromaticAberration } : postprocess.chromaticAberration }
994
- : {}),
995
- ...(postprocess.filmGrain !== undefined
996
- ? { filmGrain: typeof postprocess.filmGrain === "object" ? { ...postprocess.filmGrain } : postprocess.filmGrain }
997
- : {}),
998
- ...(postprocess.depthOfField !== undefined
999
- ? { depthOfField: postprocess.depthOfField === false ? false : { ...postprocess.depthOfField } }
1000
- : {}),
1001
- ...(postprocess.motionBlur !== undefined
1002
- ? { motionBlur: postprocess.motionBlur === false ? false : { ...postprocess.motionBlur } }
1003
- : {}),
1004
- ...(postprocess.ssao !== undefined
1005
- ? { ssao: postprocess.ssao === false ? false : { ...postprocess.ssao } }
1006
- : {}),
1007
- ...(postprocess.ssr !== undefined
1008
- ? { ssr: postprocess.ssr === false ? false : { ...postprocess.ssr } }
1009
- : {}),
1010
- ...(postprocess.taa !== undefined
1011
- ? { taa: postprocess.taa === false ? false : { ...postprocess.taa } }
1012
- : {}),
1013
- ...(postprocess.outline !== undefined
1014
- ? { outline: typeof postprocess.outline === "object" ? { ...postprocess.outline } : postprocess.outline }
1015
- : {}),
1016
- ...(postprocess.fxaa !== undefined
1017
- ? { fxaa: typeof postprocess.fxaa === "object" ? { ...postprocess.fxaa } : postprocess.fxaa }
1018
- : {})
1019
- };
1020
- }
1021
-
1022
- function defaultGLTFCameraMinDistance(bounds: CameraFrameBounds): number {
1023
- const sizeX = Math.max(0, bounds.max[0] - bounds.min[0]);
1024
- const sizeY = Math.max(0, bounds.max[1] - bounds.min[1]);
1025
- const sizeZ = Math.max(0, bounds.max[2] - bounds.min[2]);
1026
- const diagonal = Math.hypot(sizeX, sizeY, sizeZ);
1027
- return Math.max(1.2, diagonal * 0.5);
1028
- }
1029
-
1030
- function defaultGLTFCameraFrameOptions(
1031
- bounds: CameraFrameBounds,
1032
- overrides: PerspectiveCameraFrameOptions = {}
1033
- ): PerspectiveCameraFrameOptions {
1034
- return {
1035
- ...DEFAULT_GLTF_STUDIO_PREVIEW_FRAME,
1036
- minDistance: defaultGLTFCameraMinDistance(bounds),
1037
- ...overrides
1038
- };
1039
- }
1040
-
1041
- function computeGLTFRenderResourceBounds(
1042
- scene: GLTFRenderResources["scene"],
1043
- geometryLibrary: ReadonlyMap<string, Geometry>,
1044
- morphTargetLibrary: ReadonlyMap<string, readonly MorphTargetDelta[]>
1045
- ): CameraFrameBounds {
1046
- scene.updateWorldTransforms();
1047
- let bounds: SceneBounds3 | undefined;
1048
- for (const { node, renderable } of scene.collectRenderables()) {
1049
- const geometry = geometryLibrary.get(renderable.geometry);
1050
- if (!geometry) continue;
1051
- const envelope = computeSkinnedMorphTargetEnvelopeBounds(geometry, renderable.skinning, morphTargetLibrary.get(renderable.geometry));
1052
- const local = new SceneBounds3(
1053
- [envelope.min[0], envelope.min[1], envelope.min[2]],
1054
- [envelope.max[0], envelope.max[1], envelope.max[2]]
1055
- );
1056
- const worldBounds = renderable.instanceTransforms
1057
- ? transformInstancedBounds(local, node.transform.worldMatrix, renderable.instanceTransforms)
1058
- : local.transform(node.transform.worldMatrix);
1059
- bounds = bounds ? bounds.union(worldBounds) : worldBounds;
1060
- }
1061
- if (!bounds || bounds.isEmpty()) {
1062
- return { min: [0, 0, 0], max: [0, 0, 0] };
1063
- }
1064
- return {
1065
- min: [bounds.min[0], bounds.min[1], bounds.min[2]],
1066
- max: [bounds.max[0], bounds.max[1], bounds.max[2]]
1067
- };
1068
- }
1069
-
1070
- function transformInstancedBounds(
1071
- local: SceneBounds3,
1072
- modelMatrix: Mat4,
1073
- instanceTransforms: Float32Array | readonly number[]
1074
- ): SceneBounds3 {
1075
- let bounds = new SceneBounds3();
1076
- for (let offset = 0; offset + 15 < instanceTransforms.length; offset += 16) {
1077
- bounds = bounds.union(local.transform(multiplyMat4(modelMatrix, toMat4(instanceTransforms.slice(offset, offset + 16)))));
1078
- }
1079
- return bounds;
1080
- }
1081
-
1082
- function toMat4(values: Float32Array | readonly number[]): Mat4 {
1083
- const array = Array.from(values);
1084
- if (array.length !== 16 || array.some((value) => !Number.isFinite(value))) {
1085
- throw new Error("glTF render resource instance transform must be a finite mat4.");
1086
- }
1087
- return array as Mat4;
1088
- }
1089
-
1090
- function disposeGLTFRenderResourceMaps(
1091
- geometryLibrary: ReadonlyMap<string, Geometry>,
1092
- textureLibrary: ReadonlyMap<string, Texture>
1093
- ): void {
1094
- for (const geometry of geometryLibrary.values()) geometry.dispose();
1095
- for (const texture of textureLibrary.values()) texture.dispose();
1096
- }
1097
-
1098
- function materialForMesh(
1099
- asset: GLTFAsset,
1100
- mesh: GLTFMeshAsset,
1101
- materialVariant: string | undefined
1102
- ): GLTFMaterialAsset | undefined {
1103
- const materialIndex = materialVariant
1104
- ? mesh.materialVariants.find((mapping) => mapping.variant === materialVariant)?.materialIndex ?? mesh.materialIndex
1105
- : mesh.materialIndex;
1106
- return materialIndex === undefined ? undefined : asset.materials[materialIndex];
1107
- }
1108
-
1109
- function createGeometry(mesh: GLTFMeshAsset, material: GLTFMaterialAsset | undefined): Geometry {
1110
- const usedTexCoordSets = usedRenderTexCoordSets(material);
1111
- const texcoords = selectRenderTexcoords(mesh, material, 0);
1112
- const texcoords1 = usedTexCoordSets.has(1) ? selectRenderTexcoords(mesh, material, 1) : [];
1113
- const needsUv = usedTexCoordSets.has(0) || texcoords.length > 0;
1114
- const needsUv1 = texcoords1.length > 0;
1115
- const needsNormal = mesh.normals.length > 0 || needsUv || materialNeedsNormals(material);
1116
- const needsTangent = mesh.tangents.length > 0 || (needsUv && (materialNeedsTangents(material) || (material !== undefined && !material.unlit)));
1117
- const needsColor = mesh.colors.length > 0;
1118
- const needsSkinning = mesh.skinIndex !== undefined || mesh.joints.length > 0 || mesh.weights.length > 0;
1119
- const format = vertexFormatForGLTFMesh(needsNormal, needsUv, needsTangent, needsUv1, needsColor, needsSkinning);
1120
- const renderNormals = needsNormal && mesh.normals.length === 0
1121
- ? generateMeshNormals(mesh.positions, mesh.indices, mesh.topology)
1122
- : mesh.normals;
1123
- const renderTangents = needsTangent && mesh.tangents.length === 0
1124
- ? generateMeshTangents(mesh.positions, texcoords, mesh.indices, mesh.topology, renderNormals)
1125
- : mesh.tangents;
1126
- const vertices = new VertexBuffer(format, mesh.positions.length);
1127
- for (let index = 0; index < mesh.positions.length; index += 1) {
1128
- vertices.setAttribute(index, "position", mesh.positions[index]!);
1129
- if (format.hasAttribute("normal")) {
1130
- vertices.setAttribute(index, "normal", renderNormals[index] ?? [0, 0, 1]);
1131
- }
1132
- if (format.hasAttribute("tangent")) {
1133
- vertices.setAttribute(index, "tangent", renderTangents[index] ?? fallbackTangent(renderNormals[index]));
1134
- }
1135
- if (format.hasAttribute("uv")) {
1136
- vertices.setAttribute(index, "uv", texcoords[index] ?? [0, 0]);
1137
- }
1138
- if (format.hasAttribute("uv1")) {
1139
- vertices.setAttribute(index, "uv1", texcoords1[index] ?? texcoords[index] ?? [0, 0]);
1140
- }
1141
- if (format.hasAttribute("color")) {
1142
- vertices.setAttribute(index, "color", mesh.colors[index] ?? [1, 1, 1, 1]);
1143
- }
1144
- if (format.hasAttribute("joints")) {
1145
- vertices.setAttribute(index, "joints", mesh.joints[index] ?? [0, 0, 0, 0]);
1146
- vertices.setAttribute(index, "weights", mesh.weights[index] ?? [0, 0, 0, 0]);
1147
- }
1148
- }
1149
- const indices = mesh.indices && mesh.indices.length > 0 ? new IndexBuffer(mesh.indices, mesh.positions.length) : null;
1150
- return new Geometry(vertices, indices, mesh.topology, mesh.geometry.bounds);
1151
- }
1152
-
1153
- function generateMeshNormals(
1154
- positions: readonly (readonly [number, number, number])[],
1155
- indices: readonly number[] | undefined,
1156
- topology: Geometry["topology"]
1157
- ): readonly (readonly [number, number, number])[] {
1158
- const normals = Array.from({ length: positions.length }, () => [0, 0, 0] as [number, number, number]);
1159
- if (topology !== "triangles") {
1160
- return normals.map(() => [0, 0, 1] as const);
1161
- }
1162
- const triangleIndices = indices && indices.length > 0 ? indices : positions.map((_, index) => index);
1163
- for (let offset = 0; offset + 2 < triangleIndices.length; offset += 3) {
1164
- const ia = triangleIndices[offset]!;
1165
- const ib = triangleIndices[offset + 1]!;
1166
- const ic = triangleIndices[offset + 2]!;
1167
- const a = positions[ia];
1168
- const b = positions[ib];
1169
- const c = positions[ic];
1170
- if (!a || !b || !c) continue;
1171
- const normal = cross3(subtract3(b, a), subtract3(c, a));
1172
- normals[ia] = add3(normals[ia]!, normal);
1173
- normals[ib] = add3(normals[ib]!, normal);
1174
- normals[ic] = add3(normals[ic]!, normal);
1175
- }
1176
- return normals.map((normal) => normalize3(normal));
1177
- }
1178
-
1179
- function generateMeshTangents(
1180
- positions: readonly (readonly [number, number, number])[],
1181
- texcoords: readonly (readonly [number, number])[],
1182
- indices: readonly number[] | undefined,
1183
- topology: Geometry["topology"],
1184
- normals: readonly (readonly [number, number, number])[]
1185
- ): readonly (readonly [number, number, number, number])[] {
1186
- const tangents = Array.from({ length: positions.length }, () => [0, 0, 0] as [number, number, number]);
1187
- const bitangents = Array.from({ length: positions.length }, () => [0, 0, 0] as [number, number, number]);
1188
- if (topology !== "triangles" || texcoords.length === 0) {
1189
- return normals.map((normal) => fallbackTangent(normal));
1190
- }
1191
- const triangleIndices = indices && indices.length > 0 ? indices : positions.map((_, index) => index);
1192
- for (let offset = 0; offset + 2 < triangleIndices.length; offset += 3) {
1193
- const ia = triangleIndices[offset]!;
1194
- const ib = triangleIndices[offset + 1]!;
1195
- const ic = triangleIndices[offset + 2]!;
1196
- const a = positions[ia];
1197
- const b = positions[ib];
1198
- const c = positions[ic];
1199
- const uva = texcoords[ia];
1200
- const uvb = texcoords[ib];
1201
- const uvc = texcoords[ic];
1202
- if (!a || !b || !c || !uva || !uvb || !uvc) continue;
1203
- const edge1 = subtract3(b, a);
1204
- const edge2 = subtract3(c, a);
1205
- const duv1: readonly [number, number] = [uvb[0] - uva[0], uvb[1] - uva[1]];
1206
- const duv2: readonly [number, number] = [uvc[0] - uva[0], uvc[1] - uva[1]];
1207
- const determinant = duv1[0] * duv2[1] - duv2[0] * duv1[1];
1208
- if (Math.abs(determinant) <= 1e-8) continue;
1209
- const scale = 1 / determinant;
1210
- const tangent = scale3(subtract3(scale3(edge1, duv2[1]), scale3(edge2, duv1[1])), scale);
1211
- const bitangent = scale3(subtract3(scale3(edge2, duv1[0]), scale3(edge1, duv2[0])), scale);
1212
- tangents[ia] = add3(tangents[ia]!, tangent);
1213
- tangents[ib] = add3(tangents[ib]!, tangent);
1214
- tangents[ic] = add3(tangents[ic]!, tangent);
1215
- bitangents[ia] = add3(bitangents[ia]!, bitangent);
1216
- bitangents[ib] = add3(bitangents[ib]!, bitangent);
1217
- bitangents[ic] = add3(bitangents[ic]!, bitangent);
1218
- }
1219
- return tangents.map((tangent, index) => {
1220
- const normal = normals[index] ?? [0, 0, 1];
1221
- const orthogonal = subtract3(tangent, scale3(normal, dot3(normal, tangent)));
1222
- if (length3(orthogonal) <= 1e-8) return fallbackTangent(normal);
1223
- const normalized = normalize3(orthogonal);
1224
- const handedness = dot3(cross3(normal, normalized), bitangents[index] ?? [0, 1, 0]) < 0 ? -1 : 1;
1225
- return [normalized[0], normalized[1], normalized[2], handedness] as const;
1226
- });
1227
- }
1228
-
1229
- function subtract3(left: readonly [number, number, number], right: readonly [number, number, number]): [number, number, number] {
1230
- return [left[0] - right[0], left[1] - right[1], left[2] - right[2]];
1231
- }
1232
-
1233
- function add3(left: readonly [number, number, number], right: readonly [number, number, number]): [number, number, number] {
1234
- return [left[0] + right[0], left[1] + right[1], left[2] + right[2]];
1235
- }
1236
-
1237
- function scale3(value: readonly [number, number, number], scalar: number): [number, number, number] {
1238
- return [value[0] * scalar, value[1] * scalar, value[2] * scalar];
1239
- }
1240
-
1241
- function dot3(left: readonly [number, number, number], right: readonly [number, number, number]): number {
1242
- return left[0] * right[0] + left[1] * right[1] + left[2] * right[2];
1243
- }
1244
-
1245
- function cross3(left: readonly [number, number, number], right: readonly [number, number, number]): [number, number, number] {
1246
- return [
1247
- left[1] * right[2] - left[2] * right[1],
1248
- left[2] * right[0] - left[0] * right[2],
1249
- left[0] * right[1] - left[1] * right[0]
1250
- ];
1251
- }
1252
-
1253
- function length3(value: readonly [number, number, number]): number {
1254
- return Math.hypot(value[0], value[1], value[2]);
1255
- }
1256
-
1257
- function normalize3(value: readonly [number, number, number]): readonly [number, number, number] {
1258
- const length = length3(value);
1259
- if (length <= 1e-8) return [0, 0, 1];
1260
- return [value[0] / length, value[1] / length, value[2] / length];
1261
- }
1262
-
1263
- function fallbackTangent(normal: readonly [number, number, number] | undefined): readonly [number, number, number, number] {
1264
- const n = normal ?? [0, 0, 1];
1265
- const reference: readonly [number, number, number] = Math.abs(n[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];
1266
- const tangent = normalize3(cross3(reference, n));
1267
- return [tangent[0], tangent[1], tangent[2], 1];
1268
- }
1269
-
1270
- function selectRenderTexcoords(
1271
- mesh: GLTFMeshAsset,
1272
- material: GLTFMaterialAsset | undefined,
1273
- setIndex: number
1274
- ): readonly (readonly [number, number])[] {
1275
- const selected = mesh.texcoordSets[setIndex];
1276
- if (selected && selected.length > 0) return selected;
1277
- if (setIndex > 0) {
1278
- throw new Error(`glTF mesh ${mesh.name} material ${mesh.material} references missing TEXCOORD_${setIndex}`);
1279
- }
1280
- return mesh.texcoords;
1281
- }
1282
-
1283
- function usedRenderTexCoordSets(material: GLTFMaterialAsset | undefined): ReadonlySet<number> {
1284
- const sets = new Set<number>();
1285
- const infos = material ? materialTextureInfos(material) : [];
1286
- for (const info of infos) {
1287
- if (info.texCoord <= 1) sets.add(info.texCoord);
1288
- }
1289
- if (sets.size === 0 && infos.length > 0) sets.add(0);
1290
- return sets;
1291
- }
1292
-
1293
- function materialTextureInfos(material: GLTFMaterialAsset): readonly GLTFResolvedTextureInfo[] {
1294
- return materialTextureInfosBySlot(material).map(({ info }) => info);
1295
- }
1296
-
1297
- function materialTextureInfosBySlot(material: GLTFMaterialAsset): readonly {
1298
- readonly slot: TexturedPBRTextureSlot;
1299
- readonly info: GLTFResolvedTextureInfo;
1300
- readonly tangentSpace: boolean;
1301
- }[] {
1302
- return [
1303
- material.baseColorTexture ? { slot: "baseColor", info: material.baseColorTexture, tangentSpace: false } : undefined,
1304
- material.metallicRoughnessTexture ? { slot: "metallicRoughness", info: material.metallicRoughnessTexture, tangentSpace: false } : undefined,
1305
- material.normalTexture ? { slot: "normal", info: material.normalTexture, tangentSpace: true } : undefined,
1306
- material.occlusionTexture ? { slot: "occlusion", info: material.occlusionTexture, tangentSpace: false } : undefined,
1307
- material.emissiveTexture ? { slot: "emissive", info: material.emissiveTexture, tangentSpace: false } : undefined,
1308
- material.clearcoat?.texture ? { slot: "clearcoat", info: material.clearcoat.texture, tangentSpace: false } : undefined,
1309
- material.clearcoat?.roughnessTexture ? { slot: "clearcoatRoughness", info: material.clearcoat.roughnessTexture, tangentSpace: false } : undefined,
1310
- material.clearcoat?.normalTexture ? { slot: "clearcoatNormal", info: material.clearcoat.normalTexture, tangentSpace: true } : undefined,
1311
- material.transmission?.texture ? { slot: "transmission", info: material.transmission.texture, tangentSpace: false } : undefined,
1312
- material.diffuseTransmission?.texture ? { slot: "diffuseTransmission", info: material.diffuseTransmission.texture, tangentSpace: false } : undefined,
1313
- material.diffuseTransmission?.colorTexture ? { slot: "diffuseTransmissionColor", info: material.diffuseTransmission.colorTexture, tangentSpace: false } : undefined,
1314
- material.volume?.thicknessTexture ? { slot: "volumeThickness", info: material.volume.thicknessTexture, tangentSpace: false } : undefined,
1315
- material.specular?.texture ? { slot: "specular", info: material.specular.texture, tangentSpace: false } : undefined,
1316
- material.specular?.colorTexture ? { slot: "specularColor", info: material.specular.colorTexture, tangentSpace: false } : undefined,
1317
- material.sheen?.colorTexture ? { slot: "sheenColor", info: material.sheen.colorTexture, tangentSpace: false } : undefined,
1318
- material.sheen?.roughnessTexture ? { slot: "sheenRoughness", info: material.sheen.roughnessTexture, tangentSpace: false } : undefined,
1319
- material.anisotropy?.texture ? { slot: "anisotropy", info: material.anisotropy.texture, tangentSpace: false } : undefined,
1320
- material.iridescence?.texture ? { slot: "iridescence", info: material.iridescence.texture, tangentSpace: false } : undefined,
1321
- material.iridescence?.thicknessTexture ? { slot: "iridescenceThickness", info: material.iridescence.thicknessTexture, tangentSpace: false } : undefined
1322
- ].filter((entry): entry is {
1323
- readonly slot: TexturedPBRTextureSlot;
1324
- readonly info: GLTFResolvedTextureInfo;
1325
- readonly tangentSpace: boolean;
1326
- } => entry !== undefined);
1327
- }
1328
-
1329
- function materialNeedsNormals(material: GLTFMaterialAsset | undefined): boolean {
1330
- return material === undefined || !material.unlit;
1331
- }
1332
-
1333
- function materialNeedsTangents(material: GLTFMaterialAsset | undefined): boolean {
1334
- return Boolean(material?.normalTexture || material?.clearcoat?.normalTexture);
1335
- }
1336
-
1337
- function vertexFormatForGLTFMesh(needsNormal: boolean, needsUv: boolean, needsTangent: boolean, needsUv1: boolean, needsColor: boolean, needsSkinning: boolean): VertexFormat {
1338
- if (!needsColor && !needsSkinning && !needsUv1) {
1339
- if (needsUv && needsTangent) return VertexFormat.P3N3T4T2;
1340
- if (needsUv) return needsNormal ? VertexFormat.P3N3T2 : new VertexFormat([
1341
- { semantic: "position", components: 3, offset: 0 },
1342
- { semantic: "uv", components: 2, offset: 12 }
1343
- ], 20);
1344
- return needsNormal ? VertexFormat.P3N3 : VertexFormat.P3;
1345
- }
1346
- if (!needsColor && needsSkinning && !needsUv) return needsNormal ? VertexFormat.P3N3J4W4 : VertexFormat.P3J4W4;
1347
- const attributes: VertexAttributeDescriptor[] = [{ semantic: "position", components: 3, offset: 0 }];
1348
- let offset = 12;
1349
- if (needsNormal) {
1350
- attributes.push({ semantic: "normal", components: 3, offset });
1351
- offset += 12;
1352
- }
1353
- if (needsTangent) {
1354
- attributes.push({ semantic: "tangent", components: 4, offset });
1355
- offset += 16;
1356
- }
1357
- if (needsUv) {
1358
- attributes.push({ semantic: "uv", components: 2, offset });
1359
- offset += 8;
1360
- }
1361
- if (needsUv1) {
1362
- attributes.push({ semantic: "uv1", components: 2, offset });
1363
- offset += 8;
1364
- }
1365
- if (needsColor) {
1366
- attributes.push({ semantic: "color", components: 4, offset });
1367
- offset += 16;
1368
- }
1369
- if (needsSkinning) {
1370
- attributes.push({ semantic: "joints", components: 4, offset });
1371
- offset += 16;
1372
- attributes.push({ semantic: "weights", components: 4, offset });
1373
- offset += 16;
1374
- }
1375
- return new VertexFormat(attributes, offset);
1376
- }
1377
-
1378
- async function createMaterial(
1379
- asset: GLTFAsset,
1380
- material: GLTFMaterialAsset,
1381
- getTexture: (info: GLTFResolvedTextureInfo, colorSpace: GLTFTextureColorSpace) => Promise<Texture>,
1382
- options: { readonly skinned?: boolean; readonly instanced?: boolean } = {},
1383
- renderStateOverrides: readonly GLTFMaterialRenderStateOverride[] = []
1384
- ): Promise<Material> {
1385
- const renderState = renderStateForGLTFMaterial(material, renderStateOverrides);
1386
- if (options.skinned && !material.unlit) {
1387
- const [
1388
- baseColorTexture,
1389
- normalTexture,
1390
- metallicRoughnessTexture,
1391
- occlusionTexture,
1392
- emissiveTexture,
1393
- clearcoatTexture,
1394
- clearcoatNormalTexture,
1395
- sheenColorTexture,
1396
- sheenRoughnessTexture,
1397
- transmissionTexture,
1398
- iridescenceTexture,
1399
- iridescenceThicknessTexture,
1400
- anisotropyTexture,
1401
- volumeThicknessTexture
1402
- ] = await Promise.all([
1403
- material.baseColorTexture
1404
- ? createTextureBinding(asset, material.baseColorTexture, "srgb", getTexture, "u_baseColorTexture")
1405
- : Promise.resolve(undefined),
1406
- material.normalTexture
1407
- ? createTextureBinding(asset, material.normalTexture, "linear", getTexture, "u_normalTexture", createNormalSampler(asset, material))
1408
- : Promise.resolve(undefined),
1409
- material.metallicRoughnessTexture
1410
- ? createTextureBinding(asset, material.metallicRoughnessTexture, "linear", getTexture, "u_metallicRoughnessTexture")
1411
- : Promise.resolve(undefined),
1412
- material.occlusionTexture
1413
- ? createTextureBinding(asset, material.occlusionTexture, "linear", getTexture, "u_occlusionTexture")
1414
- : Promise.resolve(undefined),
1415
- material.emissiveTexture
1416
- ? createTextureBinding(asset, material.emissiveTexture, "srgb", getTexture, "u_emissiveTexture")
1417
- : Promise.resolve(undefined),
1418
- material.clearcoat?.texture
1419
- ? createTextureBinding(asset, material.clearcoat.texture, "linear", getTexture, "u_clearcoatTexture")
1420
- : Promise.resolve(undefined),
1421
- material.clearcoat?.normalTexture
1422
- ? createTextureBinding(asset, material.clearcoat.normalTexture, "linear", getTexture, "u_clearcoatNormalTexture", createNormalSamplerForInfo(asset, material.clearcoat.normalTexture))
1423
- : Promise.resolve(undefined),
1424
- material.sheen?.colorTexture
1425
- ? createTextureBinding(asset, material.sheen.colorTexture, "srgb", getTexture, "u_sheenColorTexture")
1426
- : Promise.resolve(undefined),
1427
- material.sheen?.roughnessTexture
1428
- ? createTextureBinding(asset, material.sheen.roughnessTexture, "linear", getTexture, "u_sheenRoughnessTexture")
1429
- : Promise.resolve(undefined),
1430
- material.transmission?.texture
1431
- ? createTextureBinding(asset, material.transmission.texture, "linear", getTexture, "u_transmissionTexture")
1432
- : Promise.resolve(undefined),
1433
- material.iridescence?.texture
1434
- ? createTextureBinding(asset, material.iridescence.texture, "linear", getTexture, "u_iridescenceTexture")
1435
- : Promise.resolve(undefined),
1436
- material.iridescence?.thicknessTexture
1437
- ? createTextureBinding(asset, material.iridescence.thicknessTexture, "linear", getTexture, "u_iridescenceThicknessTexture")
1438
- : Promise.resolve(undefined),
1439
- material.anisotropy?.texture
1440
- ? createTextureBinding(asset, material.anisotropy.texture, "linear", getTexture, "u_anisotropyTexture")
1441
- : Promise.resolve(undefined),
1442
- material.volume?.thicknessTexture
1443
- ? createTextureBinding(asset, material.volume.thicknessTexture, "linear", getTexture, "u_volumeThicknessTexture")
1444
- : Promise.resolve(undefined)
1445
- ]);
1446
- const runtimeMaterial = new SkinnedLitMaterial({
1447
- name: material.name,
1448
- renderState,
1449
- baseColor: material.baseColorFactor,
1450
- baseColorTexture,
1451
- baseColorTextureOffset: material.baseColorTexture?.transform?.offset,
1452
- baseColorTextureScale: material.baseColorTexture?.transform?.scale,
1453
- baseColorTextureRotation: material.baseColorTexture?.transform?.rotation,
1454
- normalTexture,
1455
- normalScale: renderNormalScale(asset, material),
1456
- metallicRoughnessTexture,
1457
- occlusionTexture,
1458
- occlusionStrength: material.occlusionTexture?.strength,
1459
- emissiveTexture,
1460
- metallic: material.metallicFactor,
1461
- roughness: material.roughnessFactor,
1462
- emissiveColor: material.emissiveFactor,
1463
- emissiveStrength: material.emissiveStrength,
1464
- clearcoatTexture,
1465
- clearcoatNormalTexture,
1466
- sheenColorTexture,
1467
- sheenRoughnessTexture,
1468
- transmissionTexture,
1469
- iridescenceTexture,
1470
- iridescenceThicknessTexture,
1471
- anisotropyTexture,
1472
- volumeThicknessTexture,
1473
- ...pbrExtensionScalarOptions(material)
1474
- });
1475
- applyAlphaCutoff(runtimeMaterial, material);
1476
- await applyPBRExtensionParameters(asset, runtimeMaterial, material, getTexture);
1477
- return runtimeMaterial;
1478
- }
1479
- if (options.instanced && material.unlit && !material.baseColorTexture) {
1480
- const runtimeMaterial = new InstancedUnlitMaterial({
1481
- name: material.name,
1482
- color: material.baseColorFactor,
1483
- renderState
1484
- });
1485
- applyAlphaCutoff(runtimeMaterial, material);
1486
- await applyPBRExtensionParameters(asset, runtimeMaterial, material, getTexture);
1487
- return runtimeMaterial;
1488
- }
1489
- if (material.unlit) {
1490
- if (material.baseColorTexture) {
1491
- const texture = await getTexture(material.baseColorTexture, "srgb");
1492
- const runtimeMaterial = new TexturedUnlitMaterial({
1493
- name: material.name,
1494
- texture,
1495
- sampler: createSampler(asset.textures[material.baseColorTexture.texture]),
1496
- textureTransform: material.baseColorTexture.transform,
1497
- color: material.baseColorFactor,
1498
- renderState
1499
- });
1500
- applyAlphaCutoff(runtimeMaterial, material);
1501
- await applyPBRExtensionParameters(asset, runtimeMaterial, material, getTexture);
1502
- return runtimeMaterial;
1503
- }
1504
- const runtimeMaterial = new UnlitMaterial({
1505
- name: material.name,
1506
- color: material.baseColorFactor,
1507
- renderState
1508
- });
1509
- applyAlphaCutoff(runtimeMaterial, material);
1510
- await applyPBRExtensionParameters(asset, runtimeMaterial, material, getTexture);
1511
- return runtimeMaterial;
1512
- }
1513
- if (options.instanced && !requiresTexturedPBRMaterial(material) && !material.baseColorTexture) {
1514
- const runtimeMaterial = new InstancedPBRMaterial({
1515
- name: material.name,
1516
- renderState,
1517
- baseColor: material.baseColorFactor,
1518
- metallic: material.metallicFactor,
1519
- roughness: material.roughnessFactor,
1520
- emissiveColor: material.emissiveFactor,
1521
- emissiveStrength: material.emissiveStrength
1522
- });
1523
- applyAlphaCutoff(runtimeMaterial, material);
1524
- await applyPBRExtensionParameters(asset, runtimeMaterial, material, getTexture);
1525
- return runtimeMaterial;
1526
- }
1527
- if (requiresTexturedPBRMaterial(material)) {
1528
- const baseColorTexture = material.baseColorTexture ? await getTexture(material.baseColorTexture, "srgb") : undefined;
1529
- const normalTexture = material.normalTexture ? await getTexture(material.normalTexture, "linear") : undefined;
1530
- const metallicRoughnessTexture = material.metallicRoughnessTexture ? await getTexture(material.metallicRoughnessTexture, "linear") : undefined;
1531
- const occlusionTexture = material.occlusionTexture ? await getTexture(material.occlusionTexture, "linear") : undefined;
1532
- const emissiveTexture = material.emissiveTexture ? await getTexture(material.emissiveTexture, "srgb") : undefined;
1533
- const extensionTextureOptions = await pbrExtensionTextureOptions(asset, material, getTexture);
1534
- const runtimeMaterial = new TexturedPBRMaterial({
1535
- name: material.name,
1536
- renderState,
1537
- baseColor: renderPbrBaseColorFactor(material),
1538
- metallic: material.metallicFactor,
1539
- roughness: renderPbrRoughnessFactor(material),
1540
- emissiveColor: material.emissiveFactor,
1541
- emissiveStrength: material.emissiveStrength,
1542
- textureTexCoords: pbrTextureTexCoords(material),
1543
- ...pbrExtensionScalarOptions(material),
1544
- ...extensionTextureOptions,
1545
- baseColorTexture,
1546
- baseColorSampler: createSampler(material.baseColorTexture ? asset.textures[material.baseColorTexture.texture] : undefined),
1547
- baseColorTextureTransform: material.baseColorTexture?.transform,
1548
- normalTexture,
1549
- normalSampler: createNormalSampler(asset, material),
1550
- normalTextureTransform: material.normalTexture?.transform,
1551
- normalScale: renderNormalScale(asset, material),
1552
- metallicRoughnessTexture,
1553
- metallicRoughnessSampler: createSampler(material.metallicRoughnessTexture ? asset.textures[material.metallicRoughnessTexture.texture] : undefined),
1554
- metallicRoughnessTextureTransform: material.metallicRoughnessTexture?.transform,
1555
- occlusionTexture,
1556
- occlusionSampler: createSampler(material.occlusionTexture ? asset.textures[material.occlusionTexture.texture] : undefined),
1557
- occlusionTextureTransform: material.occlusionTexture?.transform,
1558
- occlusionStrength: material.occlusionTexture?.strength,
1559
- emissiveTexture,
1560
- emissiveSampler: createSampler(material.emissiveTexture ? asset.textures[material.emissiveTexture.texture] : undefined),
1561
- emissiveTextureTransform: material.emissiveTexture?.transform
1562
- });
1563
- applyAlphaCutoff(runtimeMaterial, material);
1564
- await applyPBRExtensionParameters(asset, runtimeMaterial, material, getTexture);
1565
- return runtimeMaterial;
1566
- }
1567
- if (material.baseColorTexture) {
1568
- const texture = await getTexture(material.baseColorTexture, "srgb");
1569
- const runtimeMaterial = new TexturedUnlitMaterial({
1570
- name: material.name,
1571
- texture,
1572
- sampler: createSampler(asset.textures[material.baseColorTexture.texture]),
1573
- textureTransform: material.baseColorTexture.transform,
1574
- color: material.baseColorFactor,
1575
- renderState
1576
- });
1577
- applyAlphaCutoff(runtimeMaterial, material);
1578
- await applyPBRExtensionParameters(asset, runtimeMaterial, material, getTexture);
1579
- return runtimeMaterial;
1580
- }
1581
- const runtimeMaterial = new PBRMaterial({
1582
- name: material.name,
1583
- renderState,
1584
- baseColor: renderPbrBaseColorFactor(material),
1585
- metallic: material.metallicFactor,
1586
- roughness: renderPbrRoughnessFactor(material),
1587
- emissiveColor: material.emissiveFactor,
1588
- emissiveStrength: material.emissiveStrength,
1589
- ...pbrExtensionScalarOptions(material)
1590
- });
1591
- applyAlphaCutoff(runtimeMaterial, material);
1592
- await applyPBRExtensionParameters(asset, runtimeMaterial, material, getTexture);
1593
- return runtimeMaterial;
1594
- }
1595
-
1596
- function createDefaultGLTFMaterial(mesh: GLTFMeshAsset, options: { readonly instanced?: boolean; readonly skinned?: boolean } = {}): Material {
1597
- // Use a neutral light-gray base color instead of glTF-spec white ([1,1,1,1])
1598
- // so missing-material fallbacks do not blow out as bright white artifacts.
1599
- const defaults = {
1600
- name: mesh.material,
1601
- baseColor: [0.76, 0.74, 0.72, 1] as const,
1602
- metallic: 0,
1603
- roughness: 0.85,
1604
- environmentIntensity: DEFAULT_PBR_ENVIRONMENT_INTENSITY
1605
- } as const;
1606
- if (options.skinned) {
1607
- return new SkinnedLitMaterial(defaults);
1608
- }
1609
- if (options.instanced) {
1610
- return new InstancedPBRMaterial(defaults);
1611
- }
1612
- return new PBRMaterial(defaults);
1613
- }
1614
-
1615
- /**
1616
- * baseColorFactor alpha at or above this value is treated as fully opaque when
1617
- * deciding whether a `BLEND` material is a spurious-blend (ghost) case. 8-bit
1618
- * authoring rounds 255/255 to 1.0 but tools occasionally emit 0.996 (254/255),
1619
- * so we allow a small epsilon while still catching genuine fades.
1620
- */
1621
- const BLEND_OPAQUE_ALPHA_THRESHOLD = 0.996;
1622
-
1623
- export function renderStateForGLTFMaterial(
1624
- material: GLTFMaterialAsset,
1625
- overrides: readonly GLTFMaterialRenderStateOverride[] = []
1626
- ): Partial<RenderState> {
1627
- const blend = requiresTransparentRenderState(material);
1628
- const cullBack = usesUnbackedScalarTransmission(material) || usesOpaqueDoubleSidedClearcoatShell(material);
1629
- const baseState: Partial<RenderState> = {
1630
- cullMode: cullBack ? "back" : material.doubleSided ? "none" : "back",
1631
- blend,
1632
- depthWrite: !blend
1633
- };
1634
- const override = overrides.find((entry) => matchesTextOrPattern(material.name, entry.materialName));
1635
- return override ? { ...baseState, ...override.renderState } : baseState;
1636
- }
1637
-
1638
- function requiresTransparentRenderState(material: GLTFMaterialAsset): boolean {
1639
- if (material.alphaMode === "BLEND") return !isEffectivelyOpaqueBlendMaterial(material);
1640
- if (material.alphaMode !== "OPAQUE") return false;
1641
- if (usesUnbackedScalarTransmission(material)) return false;
1642
- return materialHasTransmissionOrVolume(material);
1643
- }
1644
-
1645
- /**
1646
- * Many catalog GLBs (notably Sketchfab exports) spuriously tag fully opaque
1647
- * materials with `alphaMode: "BLEND"`. The standard glTF blend equation over a
1648
- * fully opaque surface (baseColorFactor alpha == 1, no texel alpha in use) is a
1649
- * no-op, but enabling blend disables depth writes — so those characters render
1650
- * as translucent "ghosts" with broken depth sorting.
1651
- *
1652
- * When a BLEND material is provably opaque we treat it as OPAQUE (blend off,
1653
- * depthWrite on). The check is deliberately conservative: anything that could
1654
- * carry real transparency — alpha factor < 1, transmission/volume, or a
1655
- * meaningful alphaCutoff — keeps blending.
1656
- *
1657
- * Known edge case: a baseColorTexture's own alpha channel cannot be inspected
1658
- * here (images are decoded asynchronously and channel-usage is not tracked on
1659
- * the material), so a BLEND material that relies purely on per-texel texture
1660
- * alpha while keeping baseColorFactor alpha == 1 would be flattened to opaque.
1661
- * That pattern is rare in the wild (such assets normally use MASK or set the
1662
- * factor alpha < 1), and the override path (renderStateOverrides /
1663
- * GLTFMaterialRenderStateOverride) remains available to force blend back on.
1664
- */
1665
- function isEffectivelyOpaqueBlendMaterial(material: GLTFMaterialAsset): boolean {
1666
- if (material.alphaMode !== "BLEND") return false;
1667
- if (material.baseColorFactor[3] < BLEND_OPAQUE_ALPHA_THRESHOLD) return false;
1668
- // Conservative: if a baseColorTexture is present, retain blending — the texture may
1669
- // carry per-texel alpha that we cannot inspect here. Flattening would depth-sort it
1670
- // as opaque and cause ghosting / overlay artifacts.
1671
- if (material.baseColorTexture) return false;
1672
- if (materialHasTransmissionOrVolume(material)) return false;
1673
- return true;
1674
- }
1675
-
1676
- function materialHasTransmissionOrVolume(material: GLTFMaterialAsset): boolean {
1677
- return (material.transmission?.factor ?? 0) > 0.001
1678
- || (material.diffuseTransmission?.factor ?? 0) > 0.001
1679
- || (material.volume?.thicknessFactor ?? 0) > 0.001
1680
- || material.volume?.thicknessTexture !== undefined;
1681
- }
1682
-
1683
- function usesUnbackedScalarTransmission(material: GLTFMaterialAsset): boolean {
1684
- return material.alphaMode === "OPAQUE"
1685
- && (material.transmission?.factor ?? 0) > 0.001
1686
- && material.transmission?.texture === undefined
1687
- && material.diffuseTransmission === undefined
1688
- && material.volume === undefined;
1689
- }
1690
-
1691
- function usesOpaqueDoubleSidedClearcoatShell(material: GLTFMaterialAsset): boolean {
1692
- return material.alphaMode === "OPAQUE"
1693
- && material.doubleSided
1694
- && (material.clearcoat?.factor ?? 0) > 0.001
1695
- && material.metallicFactor > 0.35
1696
- && material.roughnessFactor <= 0.42;
1697
- }
1698
-
1699
- function renderPbrBaseColorFactor(material: GLTFMaterialAsset): readonly [number, number, number, number] {
1700
- if (!usesUnbackedScalarTransmission(material)) return material.baseColorFactor;
1701
- const maxColor = Math.max(material.baseColorFactor[0], material.baseColorFactor[1], material.baseColorFactor[2]);
1702
- if (maxColor < 0.8) return material.baseColorFactor;
1703
- return [0.028, 0.036, 0.044, material.baseColorFactor[3]];
1704
- }
1705
-
1706
- function renderPbrRoughnessFactor(material: GLTFMaterialAsset): number {
1707
- if (!usesUnbackedScalarTransmission(material)) return material.roughnessFactor;
1708
- return Math.max(material.roughnessFactor, 0.72);
1709
- }
1710
-
1711
- function applyAlphaCutoff(runtimeMaterial: Material, material: GLTFMaterialAsset): void {
1712
- runtimeMaterial.setParameter("u_alphaCutoff", material.alphaMode === "MASK" ? material.alphaCutoff : 0);
1713
- }
1714
-
1715
- function renderNormalScale(asset: GLTFAsset, material: GLTFMaterialAsset): number | undefined {
1716
- return renderNormalMapScale(asset, material.normalTexture);
1717
- }
1718
-
1719
- function createNormalSampler(asset: GLTFAsset, material: GLTFMaterialAsset): Sampler {
1720
- const texture = material.normalTexture ? asset.textures[material.normalTexture.texture] : undefined;
1721
- return createNormalMapSampler(texture);
1722
- }
1723
-
1724
- function createNormalSamplerForInfo(asset: GLTFAsset, info: GLTFResolvedTextureInfo | undefined): Sampler {
1725
- const texture = info ? asset.textures[info.texture] : undefined;
1726
- return createNormalMapSampler(texture);
1727
- }
1728
-
1729
- function renderNormalMapScale(asset: GLTFAsset, info: (GLTFResolvedTextureInfo & { readonly scale: number }) | undefined): number | undefined {
1730
- if (!info) return undefined;
1731
- return info.scale;
1732
- }
1733
-
1734
- function createNormalMapSampler(texture: GLTFTextureAsset | undefined): Sampler {
1735
- const sampler = createSampler(texture);
1736
- if (!usesNearestSampler(texture)) return sampler;
1737
- return new Sampler({
1738
- minFilter: "linear-mipmap-linear",
1739
- magFilter: "linear",
1740
- addressU: sampler.addressU,
1741
- addressV: sampler.addressV,
1742
- maxAnisotropy: sampler.maxAnisotropy
1743
- });
1744
- }
1745
-
1746
- function usesNearestSampler(texture: GLTFTextureAsset | undefined): boolean {
1747
- const sampler = createSampler(texture);
1748
- return sampler.magFilter === "nearest" || sampler.minFilter.startsWith("nearest");
1749
- }
1750
-
1751
- function pbrExtensionScalarOptions(material: GLTFMaterialAsset): {
1752
- readonly clearcoatFactor?: number;
1753
- readonly clearcoatRoughnessFactor?: number;
1754
- readonly transmissionFactor?: number;
1755
- readonly diffuseTransmissionFactor?: number;
1756
- readonly diffuseTransmissionColorFactor?: readonly [number, number, number];
1757
- readonly transmissionFallbackEnergy?: number;
1758
- readonly volumeThicknessFactor?: number;
1759
- readonly volumeAttenuationDistance?: number;
1760
- readonly volumeAttenuationColor?: readonly [number, number, number];
1761
- readonly ior?: number;
1762
- readonly specularFactor?: number;
1763
- readonly specularColorFactor?: readonly [number, number, number];
1764
- readonly sheenColorFactor?: readonly [number, number, number];
1765
- readonly sheenRoughnessFactor?: number;
1766
- readonly anisotropyStrength?: number;
1767
- readonly anisotropyRotation?: number;
1768
- readonly iridescenceFactor?: number;
1769
- readonly iridescenceIor?: number;
1770
- readonly iridescenceThicknessMinimum?: number;
1771
- readonly iridescenceThicknessMaximum?: number;
1772
- readonly dispersion?: number;
1773
- } {
1774
- return {
1775
- ...(material.clearcoat ? {
1776
- clearcoatFactor: material.clearcoat.factor,
1777
- clearcoatRoughnessFactor: renderClearcoatRoughnessFactor(material)
1778
- } : {}),
1779
- ...(material.transmission ? {
1780
- transmissionFactor: usesUnbackedScalarTransmission(material) ? 0 : material.transmission.factor,
1781
- transmissionFallbackEnergy: renderTransmissionFallbackEnergy(material)
1782
- } : {}),
1783
- ...(material.diffuseTransmission ? {
1784
- diffuseTransmissionFactor: material.diffuseTransmission.factor,
1785
- diffuseTransmissionColorFactor: material.diffuseTransmission.colorFactor
1786
- } : {}),
1787
- ...(material.volume ? {
1788
- volumeThicknessFactor: material.volume.thicknessFactor,
1789
- volumeAttenuationDistance: renderVolumeAttenuationDistance(material.volume.attenuationDistance),
1790
- volumeAttenuationColor: material.volume.attenuationColor
1791
- } : {}),
1792
- ...(material.ior !== undefined ? { ior: material.ior } : {}),
1793
- ...(material.specular ? {
1794
- specularFactor: material.specular.factor,
1795
- specularColorFactor: renderSpecularColorFactor(material.specular.colorFactor)
1796
- } : {}),
1797
- ...(material.sheen ? {
1798
- sheenColorFactor: material.sheen.colorFactor,
1799
- sheenRoughnessFactor: material.sheen.roughnessFactor
1800
- } : {}),
1801
- ...(material.anisotropy ? {
1802
- anisotropyStrength: material.anisotropy.strength,
1803
- anisotropyRotation: material.anisotropy.rotation
1804
- } : {}),
1805
- ...(material.iridescence ? {
1806
- iridescenceFactor: material.iridescence.factor,
1807
- iridescenceIor: material.iridescence.ior,
1808
- iridescenceThicknessMinimum: material.iridescence.thicknessMinimum,
1809
- iridescenceThicknessMaximum: material.iridescence.thicknessMaximum
1810
- } : {}),
1811
- ...(material.dispersion !== undefined ? {
1812
- dispersion: material.dispersion
1813
- } : {})
1814
- };
1815
- }
1816
-
1817
- async function pbrExtensionTextureOptions(
1818
- asset: GLTFAsset,
1819
- material: GLTFMaterialAsset,
1820
- getTexture: (info: GLTFResolvedTextureInfo, colorSpace: GLTFTextureColorSpace) => Promise<Texture>
1821
- ): Promise<Partial<TexturedPBRMaterialOptions>> {
1822
- const clearcoatTexture = material.clearcoat?.texture;
1823
- const clearcoatRoughnessTexture = material.clearcoat?.roughnessTexture;
1824
- const clearcoatNormalTexture = material.clearcoat?.normalTexture;
1825
- const transmissionTexture = material.transmission?.texture;
1826
- const diffuseTransmissionTexture = material.diffuseTransmission?.texture;
1827
- const diffuseTransmissionColorTexture = material.diffuseTransmission?.colorTexture;
1828
- const volumeThicknessTexture = material.volume?.thicknessTexture;
1829
- const specularTexture = material.specular?.texture;
1830
- const specularColorTexture = material.specular?.colorTexture;
1831
- const sheenColorTexture = material.sheen?.colorTexture;
1832
- const sheenRoughnessTexture = material.sheen?.roughnessTexture;
1833
- const anisotropyTexture = material.anisotropy?.texture;
1834
- const iridescenceTexture = material.iridescence?.texture;
1835
- const iridescenceThicknessTexture = material.iridescence?.thicknessTexture;
1836
-
1837
- return {
1838
- ...(clearcoatTexture ? {
1839
- clearcoatTexture: await getTexture(clearcoatTexture, "linear"),
1840
- clearcoatSampler: createSamplerForInfo(asset, clearcoatTexture),
1841
- clearcoatTextureTransform: clearcoatTexture.transform
1842
- } : {}),
1843
- ...(clearcoatRoughnessTexture ? {
1844
- clearcoatRoughnessTexture: await getTexture(clearcoatRoughnessTexture, "linear"),
1845
- clearcoatRoughnessSampler: createSamplerForInfo(asset, clearcoatRoughnessTexture),
1846
- clearcoatRoughnessTextureTransform: clearcoatRoughnessTexture.transform
1847
- } : {}),
1848
- ...(clearcoatNormalTexture ? {
1849
- clearcoatNormalTexture: await getTexture(clearcoatNormalTexture, "linear"),
1850
- clearcoatNormalSampler: createNormalSamplerForInfo(asset, clearcoatNormalTexture),
1851
- clearcoatNormalTextureTransform: clearcoatNormalTexture.transform,
1852
- clearcoatNormalScale: renderNormalMapScale(asset, clearcoatNormalTexture)
1853
- } : {}),
1854
- ...(transmissionTexture ? {
1855
- transmissionTexture: await getTexture(transmissionTexture, "linear"),
1856
- transmissionSampler: createSamplerForInfo(asset, transmissionTexture),
1857
- transmissionTextureTransform: transmissionTexture.transform
1858
- } : {}),
1859
- ...(diffuseTransmissionTexture ? {
1860
- diffuseTransmissionTexture: await getTexture(diffuseTransmissionTexture, "linear"),
1861
- diffuseTransmissionSampler: createSamplerForInfo(asset, diffuseTransmissionTexture),
1862
- diffuseTransmissionTextureTransform: diffuseTransmissionTexture.transform
1863
- } : {}),
1864
- ...(diffuseTransmissionColorTexture ? {
1865
- diffuseTransmissionColorTexture: await getTexture(diffuseTransmissionColorTexture, "srgb"),
1866
- diffuseTransmissionColorSampler: createSamplerForInfo(asset, diffuseTransmissionColorTexture),
1867
- diffuseTransmissionColorTextureTransform: diffuseTransmissionColorTexture.transform
1868
- } : {}),
1869
- ...(volumeThicknessTexture ? {
1870
- volumeThicknessTexture: await getTexture(volumeThicknessTexture, "linear"),
1871
- volumeThicknessSampler: createSamplerForInfo(asset, volumeThicknessTexture),
1872
- volumeThicknessTextureTransform: volumeThicknessTexture.transform
1873
- } : {}),
1874
- ...(specularTexture ? {
1875
- specularTexture: await getTexture(specularTexture, "linear"),
1876
- specularSampler: createSamplerForInfo(asset, specularTexture),
1877
- specularTextureTransform: specularTexture.transform
1878
- } : {}),
1879
- ...(specularColorTexture ? {
1880
- specularColorTexture: await getTexture(specularColorTexture, "srgb"),
1881
- specularColorSampler: createSamplerForInfo(asset, specularColorTexture),
1882
- specularColorTextureTransform: specularColorTexture.transform
1883
- } : {}),
1884
- ...(sheenColorTexture ? {
1885
- sheenColorTexture: await getTexture(sheenColorTexture, "srgb"),
1886
- sheenColorSampler: createSamplerForInfo(asset, sheenColorTexture),
1887
- sheenColorTextureTransform: sheenColorTexture.transform
1888
- } : {}),
1889
- ...(sheenRoughnessTexture ? {
1890
- sheenRoughnessTexture: await getTexture(sheenRoughnessTexture, "linear"),
1891
- sheenRoughnessSampler: createSamplerForInfo(asset, sheenRoughnessTexture),
1892
- sheenRoughnessTextureTransform: sheenRoughnessTexture.transform
1893
- } : {}),
1894
- ...(anisotropyTexture ? {
1895
- anisotropyTexture: await getTexture(anisotropyTexture, "linear"),
1896
- anisotropySampler: createSamplerForInfo(asset, anisotropyTexture),
1897
- anisotropyTextureTransform: anisotropyTexture.transform
1898
- } : {}),
1899
- ...(iridescenceTexture ? {
1900
- iridescenceTexture: await getTexture(iridescenceTexture, "linear"),
1901
- iridescenceSampler: createSamplerForInfo(asset, iridescenceTexture),
1902
- iridescenceTextureTransform: iridescenceTexture.transform
1903
- } : {}),
1904
- ...(iridescenceThicknessTexture ? {
1905
- iridescenceThicknessTexture: await getTexture(iridescenceThicknessTexture, "linear"),
1906
- iridescenceThicknessSampler: createSamplerForInfo(asset, iridescenceThicknessTexture),
1907
- iridescenceThicknessTextureTransform: iridescenceThicknessTexture.transform
1908
- } : {})
1909
- };
1910
- }
1911
-
1912
- function renderTransmissionFallbackEnergy(material: GLTFMaterialAsset): number {
1913
- const usesUnbackedCutoutTransmission = material.alphaMode === "MASK" && material.transmission?.texture === undefined && material.volume === undefined;
1914
- return usesUnbackedCutoutTransmission || usesUnbackedScalarTransmission(material) ? 0 : 0.08;
1915
- }
1916
-
1917
- function pbrTextureTexCoords(material: GLTFMaterialAsset): Partial<Record<TexturedPBRTextureSlot, number>> {
1918
- return {
1919
- ...(material.baseColorTexture ? { baseColor: renderTexCoord(material.baseColorTexture.texCoord) } : {}),
1920
- ...(material.normalTexture ? { normal: renderTexCoord(material.normalTexture.texCoord) } : {}),
1921
- ...(material.metallicRoughnessTexture ? { metallicRoughness: renderTexCoord(material.metallicRoughnessTexture.texCoord) } : {}),
1922
- ...(material.occlusionTexture ? { occlusion: renderTexCoord(material.occlusionTexture.texCoord) } : {}),
1923
- ...(material.emissiveTexture ? { emissive: renderTexCoord(material.emissiveTexture.texCoord) } : {}),
1924
- ...(material.clearcoat?.texture ? { clearcoat: renderTexCoord(material.clearcoat.texture.texCoord) } : {}),
1925
- ...(material.clearcoat?.roughnessTexture ? { clearcoatRoughness: renderTexCoord(material.clearcoat.roughnessTexture.texCoord) } : {}),
1926
- ...(material.clearcoat?.normalTexture ? { clearcoatNormal: renderTexCoord(material.clearcoat.normalTexture.texCoord) } : {}),
1927
- ...(material.transmission?.texture ? { transmission: renderTexCoord(material.transmission.texture.texCoord) } : {}),
1928
- ...(material.diffuseTransmission?.texture ? { diffuseTransmission: renderTexCoord(material.diffuseTransmission.texture.texCoord) } : {}),
1929
- ...(material.diffuseTransmission?.colorTexture ? { diffuseTransmissionColor: renderTexCoord(material.diffuseTransmission.colorTexture.texCoord) } : {}),
1930
- ...(material.volume?.thicknessTexture ? { volumeThickness: renderTexCoord(material.volume.thicknessTexture.texCoord) } : {}),
1931
- ...(material.specular?.texture ? { specular: renderTexCoord(material.specular.texture.texCoord) } : {}),
1932
- ...(material.specular?.colorTexture ? { specularColor: renderTexCoord(material.specular.colorTexture.texCoord) } : {}),
1933
- ...(material.sheen?.colorTexture ? { sheenColor: renderTexCoord(material.sheen.colorTexture.texCoord) } : {}),
1934
- ...(material.sheen?.roughnessTexture ? { sheenRoughness: renderTexCoord(material.sheen.roughnessTexture.texCoord) } : {}),
1935
- ...(material.anisotropy?.texture ? { anisotropy: renderTexCoord(material.anisotropy.texture.texCoord) } : {}),
1936
- ...(material.iridescence?.texture ? { iridescence: renderTexCoord(material.iridescence.texture.texCoord) } : {}),
1937
- ...(material.iridescence?.thicknessTexture ? { iridescenceThickness: renderTexCoord(material.iridescence.thicknessTexture.texCoord) } : {})
1938
- };
1939
- }
1940
-
1941
- function renderTexCoord(texCoord: number): number {
1942
- return texCoord === 1 ? 1 : 0;
1943
- }
1944
-
1945
- async function applyPBRExtensionParameters(
1946
- asset: GLTFAsset,
1947
- runtimeMaterial: Material,
1948
- material: GLTFMaterialAsset,
1949
- getTexture: (info: GLTFResolvedTextureInfo, colorSpace: GLTFTextureColorSpace) => Promise<Texture>
1950
- ): Promise<void> {
1951
- if (material.clearcoat) {
1952
- runtimeMaterial.setParameter("u_clearcoatFactor", material.clearcoat.factor);
1953
- runtimeMaterial.setParameter("u_clearcoatRoughnessFactor", renderClearcoatRoughnessFactor(material));
1954
- if (material.clearcoat.texture) {
1955
- await setTextureParameter(asset, runtimeMaterial, "u_clearcoatTexture", material.clearcoat.texture, "linear", getTexture);
1956
- }
1957
- if (material.clearcoat.roughnessTexture) {
1958
- await setTextureParameter(asset, runtimeMaterial, "u_clearcoatRoughnessTexture", material.clearcoat.roughnessTexture, "linear", getTexture);
1959
- }
1960
- if (material.clearcoat.normalTexture) {
1961
- await setTextureParameter(asset, runtimeMaterial, "u_clearcoatNormalTexture", material.clearcoat.normalTexture, "linear", getTexture);
1962
- runtimeMaterial.setParameter("u_clearcoatNormalScale", renderNormalMapScale(asset, material.clearcoat.normalTexture) ?? material.clearcoat.normalTexture.scale);
1963
- }
1964
- }
1965
- if (material.transmission) {
1966
- runtimeMaterial.setParameter("u_transmissionFactor", usesUnbackedScalarTransmission(material) ? 0 : material.transmission.factor);
1967
- if (material.transmission.texture) {
1968
- await setTextureParameter(asset, runtimeMaterial, "u_transmissionTexture", material.transmission.texture, "linear", getTexture);
1969
- }
1970
- }
1971
- if (material.diffuseTransmission) {
1972
- runtimeMaterial.setParameter("u_diffuseTransmissionFactor", material.diffuseTransmission.factor);
1973
- runtimeMaterial.setParameter("u_diffuseTransmissionColorFactor", material.diffuseTransmission.colorFactor);
1974
- if (material.diffuseTransmission.texture) {
1975
- await setTextureParameter(asset, runtimeMaterial, "u_diffuseTransmissionTexture", material.diffuseTransmission.texture, "linear", getTexture);
1976
- }
1977
- if (material.diffuseTransmission.colorTexture) {
1978
- await setTextureParameter(asset, runtimeMaterial, "u_diffuseTransmissionColorTexture", material.diffuseTransmission.colorTexture, "srgb", getTexture);
1979
- }
1980
- }
1981
- if (material.volume) {
1982
- runtimeMaterial.setParameter("u_volumeThicknessFactor", material.volume.thicknessFactor);
1983
- runtimeMaterial.setParameter("u_volumeAttenuationDistance", renderVolumeAttenuationDistance(material.volume.attenuationDistance));
1984
- runtimeMaterial.setParameter("u_volumeAttenuationColor", material.volume.attenuationColor);
1985
- if (material.volume.thicknessTexture) {
1986
- await setTextureParameter(asset, runtimeMaterial, "u_volumeThicknessTexture", material.volume.thicknessTexture, "linear", getTexture);
1987
- }
1988
- }
1989
- if (material.ior !== undefined) {
1990
- runtimeMaterial.setParameter("u_ior", material.ior);
1991
- }
1992
- if (material.specular) {
1993
- runtimeMaterial.setParameter("u_specularFactor", material.specular.factor);
1994
- runtimeMaterial.setParameter("u_specularColorFactor", renderSpecularColorFactor(material.specular.colorFactor));
1995
- if (material.specular.texture) {
1996
- await setTextureParameter(asset, runtimeMaterial, "u_specularTexture", material.specular.texture, "linear", getTexture);
1997
- }
1998
- if (material.specular.colorTexture) {
1999
- await setTextureParameter(asset, runtimeMaterial, "u_specularColorTexture", material.specular.colorTexture, "srgb", getTexture);
2000
- }
2001
- }
2002
- if (material.sheen) {
2003
- runtimeMaterial.setParameter("u_sheenColorFactor", material.sheen.colorFactor);
2004
- runtimeMaterial.setParameter("u_sheenRoughnessFactor", material.sheen.roughnessFactor);
2005
- if (material.sheen.colorTexture) {
2006
- await setTextureParameter(asset, runtimeMaterial, "u_sheenColorTexture", material.sheen.colorTexture, "srgb", getTexture);
2007
- }
2008
- if (material.sheen.roughnessTexture) {
2009
- await setTextureParameter(asset, runtimeMaterial, "u_sheenRoughnessTexture", material.sheen.roughnessTexture, "linear", getTexture);
2010
- }
2011
- }
2012
- if (material.anisotropy) {
2013
- runtimeMaterial.setParameter("u_anisotropyStrength", material.anisotropy.strength);
2014
- runtimeMaterial.setParameter("u_anisotropyRotation", material.anisotropy.rotation);
2015
- if (material.anisotropy.texture) {
2016
- await setTextureParameter(asset, runtimeMaterial, "u_anisotropyTexture", material.anisotropy.texture, "linear", getTexture);
2017
- }
2018
- }
2019
- if (material.iridescence) {
2020
- runtimeMaterial.setParameter("u_iridescenceFactor", material.iridescence.factor);
2021
- runtimeMaterial.setParameter("u_iridescenceIor", material.iridescence.ior);
2022
- runtimeMaterial.setParameter("u_iridescenceThicknessMinimum", material.iridescence.thicknessMinimum);
2023
- runtimeMaterial.setParameter("u_iridescenceThicknessMaximum", material.iridescence.thicknessMaximum);
2024
- if (material.iridescence.texture) {
2025
- await setTextureParameter(asset, runtimeMaterial, "u_iridescenceTexture", material.iridescence.texture, "linear", getTexture);
2026
- }
2027
- if (material.iridescence.thicknessTexture) {
2028
- await setTextureParameter(asset, runtimeMaterial, "u_iridescenceThicknessTexture", material.iridescence.thicknessTexture, "linear", getTexture);
2029
- }
2030
- }
2031
- if (material.dispersion !== undefined) {
2032
- runtimeMaterial.setParameter("u_dispersion", material.dispersion);
2033
- }
2034
- }
2035
-
2036
- function renderClearcoatRoughnessFactor(material: GLTFMaterialAsset): number {
2037
- return material.clearcoat?.roughnessFactor ?? 0;
2038
- }
2039
-
2040
- async function setTextureParameter(
2041
- asset: GLTFAsset,
2042
- runtimeMaterial: Material,
2043
- uniformName: string,
2044
- info: GLTFResolvedTextureInfo,
2045
- colorSpace: GLTFTextureColorSpace,
2046
- getTexture: (info: GLTFResolvedTextureInfo, colorSpace: GLTFTextureColorSpace) => Promise<Texture>,
2047
- sampler?: Sampler
2048
- ): Promise<void> {
2049
- runtimeMaterial.setParameter(uniformName, await createTextureBinding(asset, info, colorSpace, getTexture, uniformName, sampler));
2050
- runtimeMaterial.setParameter(`${uniformName}Offset`, info.transform?.offset ?? [0, 0]);
2051
- runtimeMaterial.setParameter(`${uniformName}Scale`, info.transform?.scale ?? [1, 1]);
2052
- runtimeMaterial.setParameter(`${uniformName}Rotation`, info.transform?.rotation ?? 0);
2053
- runtimeMaterial.setParameter(`${uniformName}TexCoord`, renderTexCoord(info.texCoord));
2054
- }
2055
-
2056
- async function createTextureBinding(
2057
- asset: GLTFAsset,
2058
- info: GLTFResolvedTextureInfo,
2059
- colorSpace: GLTFTextureColorSpace,
2060
- getTexture: (info: GLTFResolvedTextureInfo, colorSpace: GLTFTextureColorSpace) => Promise<Texture>,
2061
- uniformName = `gltf-texture-${info.texture}`,
2062
- sampler?: Sampler
2063
- ): Promise<TextureBinding> {
2064
- return new TextureBinding({
2065
- name: uniformName,
2066
- texture: await getTexture(info, colorSpace),
2067
- sampler: sampler ?? createSampler(asset.textures[info.texture]),
2068
- required: true,
2069
- expectedColorSpace: colorSpace,
2070
- transform: info.transform
2071
- });
2072
- }
2073
-
2074
- function requiresTexturedPBRMaterial(material: GLTFMaterialAsset): boolean {
2075
- return Boolean(
2076
- material.baseColorTexture ||
2077
- material.normalTexture ||
2078
- material.metallicRoughnessTexture ||
2079
- material.occlusionTexture ||
2080
- material.emissiveTexture ||
2081
- material.clearcoat?.texture ||
2082
- material.clearcoat?.roughnessTexture ||
2083
- material.clearcoat?.normalTexture ||
2084
- material.transmission?.texture ||
2085
- material.diffuseTransmission?.texture ||
2086
- material.diffuseTransmission?.colorTexture ||
2087
- material.volume?.thicknessTexture ||
2088
- material.specular?.texture ||
2089
- material.specular?.colorTexture ||
2090
- material.sheen?.colorTexture ||
2091
- material.sheen?.roughnessTexture ||
2092
- material.anisotropy?.texture ||
2093
- material.iridescence?.texture ||
2094
- material.iridescence?.thicknessTexture
2095
- );
2096
- }
2097
-
2098
- function renderVolumeAttenuationDistance(distance: number): number {
2099
- return distance === Number.POSITIVE_INFINITY ? 1_000_000 : distance;
2100
- }
2101
-
2102
- function renderSpecularColorFactor(value: readonly [number, number, number]): readonly [number, number, number] {
2103
- return [clampNonNegative(value[0]), clampNonNegative(value[1]), clampNonNegative(value[2])];
2104
- }
2105
-
2106
- function clampUnit(value: number): number {
2107
- return Math.max(0, Math.min(1, value));
2108
- }
2109
-
2110
- function clampNonNegative(value: number): number {
2111
- return Math.max(0, value);
2112
- }
2113
-
2114
- function textureCacheKey(imageIndex: number, colorSpace: GLTFTextureColorSpace): string {
2115
- return `${imageIndex}:${colorSpace}`;
2116
- }
2117
-
2118
- function setTextureLibraryEntry(textureLibrary: Map<string, Texture>, textureName: string, colorSpace: GLTFTextureColorSpace, texture: Texture): void {
2119
- const existing = textureLibrary.get(textureName);
2120
- if (!existing) {
2121
- textureLibrary.set(textureName, texture);
2122
- return;
2123
- }
2124
- if (existing === texture) return;
2125
- const keyedName = textureLibraryKey(textureLibrary, textureName, colorSpace);
2126
- if (textureLibrary.get(keyedName) !== texture) {
2127
- textureLibrary.set(keyedName, texture);
2128
- }
2129
- }
2130
-
2131
- function textureLibraryKey(textureLibrary: ReadonlyMap<string, Texture>, textureName: string, colorSpace: GLTFTextureColorSpace): string {
2132
- if (!textureLibrary.has(textureName)) return textureName;
2133
- return `${textureName}:${colorSpace}`;
2134
- }
2135
-
2136
- function createSampler(texture: GLTFTextureAsset | undefined): Sampler {
2137
- const descriptor = texture?.samplerDescriptor;
2138
- const samplerDescriptor: SamplerDescriptor = descriptor
2139
- ? {
2140
- minFilter: descriptor.minFilter,
2141
- magFilter: descriptor.magFilter,
2142
- addressU: descriptor.addressU,
2143
- addressV: descriptor.addressV,
2144
- maxAnisotropy: 8
2145
- }
2146
- : {
2147
- minFilter: "linear-mipmap-linear",
2148
- magFilter: "linear",
2149
- addressU: "repeat",
2150
- addressV: "repeat",
2151
- maxAnisotropy: 8
2152
- };
2153
- return new Sampler(samplerDescriptor);
2154
- }
2155
-
2156
- async function decodeImageInBrowser(
2157
- image: GLTFImageAsset,
2158
- _imageIndex: number,
2159
- asset: GLTFAsset,
2160
- options: GLTFRenderResourceOptions = {}
2161
- ): Promise<DecodedGLTFImage> {
2162
- if (isKTX2BasisImage(image)) {
2163
- const bytes = await readImageBytes(asset, image);
2164
- return transcodeKTX2BasisTexture(bytes, {
2165
- ...options.ktx2BasisTranscoderOptions,
2166
- targetFormat: options.ktx2BasisTargetFormat ?? options.ktx2BasisTranscoderOptions?.targetFormat
2167
- });
2168
- }
2169
- if (typeof createImageBitmap === "function") {
2170
- const blob = image.data
2171
- ? new Blob([image.data], { type: image.mimeType ?? "application/octet-stream" })
2172
- : await fetchImageBlob(asset, image);
2173
- const bitmap = await createImageBitmap(blob, {
2174
- colorSpaceConversion: "none",
2175
- premultiplyAlpha: "none"
2176
- });
2177
- return { width: bitmap.width, height: bitmap.height, source: bitmap, colorSpace: "srgb" };
2178
- }
2179
- const ImageCtor = globalThis.Image;
2180
- if (!ImageCtor || !image.uri) {
2181
- throw new Error("glTF image decoding requires createImageBitmap, HTMLImageElement, or a custom imageDecoder");
2182
- }
2183
- const imageElement = new ImageCtor();
2184
- const url = resolveImageUrl(asset.url, image.uri);
2185
- return new Promise((resolve, reject) => {
2186
- imageElement.onload = () => resolve({ width: imageElement.width, height: imageElement.height, source: imageElement, colorSpace: "srgb" });
2187
- imageElement.onerror = () => reject(new Error(`glTF image decode failed for ${url}`));
2188
- imageElement.src = url;
2189
- });
2190
- }
2191
-
2192
- function createSamplerForInfo(asset: GLTFAsset, info: GLTFResolvedTextureInfo): Sampler {
2193
- return createSampler(asset.textures[info.texture]);
2194
- }
2195
-
2196
- async function readImageBytes(asset: GLTFAsset, image: GLTFImageAsset): Promise<ArrayBuffer> {
2197
- if (image.data) return image.data.slice(0);
2198
- const blob = await fetchImageBlob(asset, image);
2199
- return blob.arrayBuffer();
2200
- }
2201
-
2202
- async function fetchImageBlob(asset: GLTFAsset, image: GLTFImageAsset): Promise<Blob> {
2203
- if (!image.uri) {
2204
- throw new Error("glTF image has no uri or embedded data");
2205
- }
2206
- if (typeof fetch !== "function") {
2207
- throw new Error("glTF image fetch requires fetch or a custom imageDecoder");
2208
- }
2209
- const response = await fetch(resolveImageUrl(asset.url, image.uri));
2210
- if (!response.ok) {
2211
- throw new Error(`glTF image request failed with ${response.status}`);
2212
- }
2213
- return response.blob();
2214
- }
2215
-
2216
- function isKTX2BasisImage(image: GLTFImageAsset): boolean {
2217
- return image.mimeType === "image/ktx2" || /\.ktx2(?:[?#]|$)/i.test(image.uri ?? "");
2218
- }
2219
-
2220
- function createFallbackTexture(label: string, colorSpace: GLTFTextureColorSpace): Texture {
2221
- return new Texture({
2222
- width: 1,
2223
- height: 1,
2224
- colorSpace,
2225
- label: `${label} (missing-texture-fallback)`,
2226
- data: new Uint8Array([255, 255, 255, 255])
2227
- });
2228
- }
2229
-
2230
- function warnMissingGLTFTexture(textureName: string, imageUri: string | undefined, reason: string): void {
2231
- if (typeof console === "undefined" || typeof console.warn !== "function") return;
2232
- const source = imageUri ? ` (${imageUri})` : "";
2233
- console.warn(
2234
- `glTF texture "${textureName}"${source} could not be loaded; falling back to baseColorFactor. Reason: ${reason}`
2235
- );
2236
- }
2237
-
2238
- function resolveImageUrl(assetUrl: string, imageUri: string): string {
2239
- if (/^(?:data:|blob:|https?:|file:)/i.test(imageUri)) return imageUri;
2240
- if (assetUrl.startsWith("data:")) {
2241
- throw new Error(`Relative glTF image uri ${imageUri} cannot be resolved from a data URL asset`);
2242
- }
2243
- return new URL(imageUri, resolveAbsoluteAssetBase(assetUrl)).toString();
2244
- }
2245
-
2246
- /**
2247
- * Derive an absolute base URL for resolving relative texture URIs.
2248
- *
2249
- * Catalog assets are often loaded from root-relative paths (e.g.
2250
- * `/aura-assets/x.glb`). `new URL(uri, base)` requires `base` to be absolute, so
2251
- * a bare relative `assetUrl` throws `Failed to construct 'URL': Invalid base URL`.
2252
- * If the asset URL is already absolute we use it directly; otherwise we resolve it
2253
- * against the document/origin base when running in a browser, falling back to a
2254
- * synthetic `file:///` origin so resolution never throws in non-browser contexts.
2255
- */
2256
- function resolveAbsoluteAssetBase(assetUrl: string): string {
2257
- if (/^[a-z][a-z0-9+.-]*:/i.test(assetUrl)) return assetUrl;
2258
- const documentBase =
2259
- (typeof document !== "undefined" && document.baseURI) ||
2260
- (typeof location !== "undefined" && location.href) ||
2261
- undefined;
2262
- if (documentBase) {
2263
- try {
2264
- return new URL(assetUrl, documentBase).toString();
2265
- } catch {
2266
- // fall through to synthetic base below
2267
- }
2268
- }
2269
- return new URL(assetUrl, "file:///").toString();
2270
- }