@aura3d/assets 1.0.6

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