@meimu/mutracer 0.1.2 → 0.1.4

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 (125) hide show
  1. package/dist/assets/bvh.worker.js +1 -1
  2. package/dist/mutracer.umd.js +4475 -4337
  3. package/docs/api.md +11 -9
  4. package/docs/threejs.md +30 -4
  5. package/lib/Engine.js +18 -1
  6. package/lib/Engine.js.map +1 -1
  7. package/lib/main.d.ts +1 -1
  8. package/lib/main.js.map +1 -1
  9. package/lib/oidn.d.ts +1 -1
  10. package/lib/oidnBundledWeights.cdn.d.ts +2 -2
  11. package/lib/renderer/MaterialTable.d.ts +1 -0
  12. package/lib/renderer/MaterialTable.js +10 -4
  13. package/lib/renderer/MaterialTable.js.map +1 -1
  14. package/lib/renderer/WGPUBloomPass.js +18 -18
  15. package/lib/renderer/WGPUFullQuadPass.js +6 -6
  16. package/lib/renderer/WGPUJNLMDenoiser.js +68 -68
  17. package/lib/renderer/WGPURayTraceOutput.js +16 -14
  18. package/lib/renderer/WGPURayTraceOutput.js.map +1 -1
  19. package/lib/renderer/WGPURayTracePass.d.ts +2 -0
  20. package/lib/renderer/WGPURayTracePass.js +13 -7
  21. package/lib/renderer/WGPURayTracePass.js.map +1 -1
  22. package/lib/renderer/WGPURenderingPipeline.js +24 -22
  23. package/lib/renderer/WGPURenderingPipeline.js.map +1 -1
  24. package/lib/renderer/WebGLJNLMDenoiser.js +68 -68
  25. package/lib/renderer/WebGLRayTraceOutputPass.js +4 -4
  26. package/lib/renderer/WebGLRayTracePass.d.ts +1 -0
  27. package/lib/renderer/WebGLRayTracePass.js +7 -1
  28. package/lib/renderer/WebGLRayTracePass.js.map +1 -1
  29. package/lib/renderer/envMapCreation.d.ts +5 -1
  30. package/lib/renderer/envMapCreation.js +42 -5
  31. package/lib/renderer/envMapCreation.js.map +1 -1
  32. package/lib/renderer/geometryUpdates.js +1 -1
  33. package/lib/renderer/geometryUpdates.js.map +1 -1
  34. package/lib/renderer/glsl/chunks/cameraRay.glsl.js +12 -12
  35. package/lib/renderer/glsl/chunks/envMap.glsl.js +69 -57
  36. package/lib/renderer/glsl/chunks/envMap.glsl.js.map +1 -1
  37. package/lib/renderer/glsl/chunks/intersect.glsl.js +316 -310
  38. package/lib/renderer/glsl/chunks/intersect.glsl.js.map +1 -1
  39. package/lib/renderer/glsl/chunks/materialBuffer.glsl.js +153 -121
  40. package/lib/renderer/glsl/chunks/materialBuffer.glsl.js.map +1 -1
  41. package/lib/renderer/glsl/chunks/openPbrBsdf.glsl.js +540 -540
  42. package/lib/renderer/glsl/chunks/rand.glsl.js +3 -3
  43. package/lib/renderer/glsl/chunks/random.glsl.js +4 -4
  44. package/lib/renderer/glsl/chunks/rayTraceCore.glsl.js +40 -39
  45. package/lib/renderer/glsl/chunks/rayTraceCore.glsl.js.map +1 -1
  46. package/lib/renderer/glsl/chunks/sampleLight.glsl.js +71 -71
  47. package/lib/renderer/glsl/chunks/sampleMaterial.glsl.js +84 -84
  48. package/lib/renderer/glsl/chunks/sampleShadowCatcher.glsl.js +13 -13
  49. package/lib/renderer/glsl/chunks/sampling.glsl.js +77 -77
  50. package/lib/renderer/glsl/chunks/sobol.glsl.js +65 -65
  51. package/lib/renderer/glsl/chunks/textureLinear.glsl.js +5 -5
  52. package/lib/renderer/glsl/chunks/uvProjection.glsl.js +11 -11
  53. package/lib/renderer/glsl/depthQuery.frag.js +5 -5
  54. package/lib/renderer/glsl/depthQuery.frag.js.map +1 -1
  55. package/lib/renderer/glsl/normalizeRayTraceOutput.frag.js +8 -8
  56. package/lib/renderer/glsl/rayTrace.frag.js +165 -165
  57. package/lib/renderer/glsl/rayTrace.frag.js.map +1 -1
  58. package/lib/renderer/glsl/shadowCatcher.frag.js +14 -14
  59. package/lib/renderer/glsl/shadowCatcher.frag.js.map +1 -1
  60. package/lib/renderer/glsl/webglPipeline.frag.js +56 -56
  61. package/lib/renderer/lightsUtil.js +7 -5
  62. package/lib/renderer/lightsUtil.js.map +1 -1
  63. package/lib/renderer/materialChanges.js +1 -1
  64. package/lib/renderer/materialChanges.js.map +1 -1
  65. package/lib/renderer/materialComparison.generated.js +36 -18
  66. package/lib/renderer/materialComparison.generated.js.map +1 -1
  67. package/lib/renderer/prepareMeshBVH.js +2 -2
  68. package/lib/renderer/prepareMeshBVH.js.map +1 -1
  69. package/lib/renderer/sceneChangeDetector.js +4 -1
  70. package/lib/renderer/sceneChangeDetector.js.map +1 -1
  71. package/lib/renderer/sceneLightChanges.js +3 -2
  72. package/lib/renderer/sceneLightChanges.js.map +1 -1
  73. package/lib/renderer/scratchSampling.js +18 -18
  74. package/lib/renderer/wgsl/chunks/common.wgsl.js +4 -4
  75. package/lib/renderer/wgsl/chunks/envMap.wgsl.d.ts +1 -1
  76. package/lib/renderer/wgsl/chunks/envMap.wgsl.js +39 -31
  77. package/lib/renderer/wgsl/chunks/envMap.wgsl.js.map +1 -1
  78. package/lib/renderer/wgsl/chunks/intersect.wgsl.js +475 -469
  79. package/lib/renderer/wgsl/chunks/intersect.wgsl.js.map +1 -1
  80. package/lib/renderer/wgsl/chunks/intersectionAlpha.wgsl.js +8 -8
  81. package/lib/renderer/wgsl/chunks/materialBuffer.wgsl.js +95 -61
  82. package/lib/renderer/wgsl/chunks/materialBuffer.wgsl.js.map +1 -1
  83. package/lib/renderer/wgsl/chunks/openPbrBsdf.wgsl.js +562 -562
  84. package/lib/renderer/wgsl/chunks/pdm_displacement.wgsl.d.ts +1 -1
  85. package/lib/renderer/wgsl/chunks/pdm_displacement.wgsl.js +117 -120
  86. package/lib/renderer/wgsl/chunks/pdm_displacement.wgsl.js.map +1 -1
  87. package/lib/renderer/wgsl/chunks/rand.wgsl.js +3 -3
  88. package/lib/renderer/wgsl/chunks/rayTraceCore.wgsl.js +25 -22
  89. package/lib/renderer/wgsl/chunks/rayTraceCore.wgsl.js.map +1 -1
  90. package/lib/renderer/wgsl/chunks/sampleLight.wgsl.js +128 -128
  91. package/lib/renderer/wgsl/chunks/sampleMaterial.wgsl.js +143 -143
  92. package/lib/renderer/wgsl/chunks/sampleShadowCatcher.wgsl.js +6 -6
  93. package/lib/renderer/wgsl/chunks/sampling.wgsl.js +75 -75
  94. package/lib/renderer/wgsl/chunks/shadowCatcherAccumulation.wgsl.d.ts +3 -3
  95. package/lib/renderer/wgsl/chunks/shadowCatcherAccumulation.wgsl.js +2 -2
  96. package/lib/renderer/wgsl/chunks/shadowCatcherAccumulation.wgsl.js.map +1 -1
  97. package/lib/renderer/wgsl/chunks/sobol.wgsl.js +69 -69
  98. package/lib/renderer/wgsl/chunks/uvProjection.wgsl.js +11 -11
  99. package/lib/renderer/wgsl/compose.frag.wgsl.d.ts +2 -2
  100. package/lib/renderer/wgsl/compose.frag.wgsl.js +130 -102
  101. package/lib/renderer/wgsl/compose.frag.wgsl.js.map +1 -1
  102. package/lib/renderer/wgsl/customDenoise.wgsl.js +10 -10
  103. package/lib/renderer/wgsl/depthQuery.wgsl.d.ts +1 -1
  104. package/lib/renderer/wgsl/depthQuery.wgsl.js +5 -5
  105. package/lib/renderer/wgsl/depthQuery.wgsl.js.map +1 -1
  106. package/lib/renderer/wgsl/offlineAdaptive.compute.js +28 -28
  107. package/lib/renderer/wgsl/rayTrace.compute.js +289 -277
  108. package/lib/renderer/wgsl/rayTrace.compute.js.map +1 -1
  109. package/lib/scene/EnvironmentLight.d.ts +9 -3
  110. package/lib/scene/EnvironmentLight.js +9 -2
  111. package/lib/scene/EnvironmentLight.js.map +1 -1
  112. package/lib/scene/Scene.d.ts +4 -0
  113. package/lib/scene/Scene.js.map +1 -1
  114. package/lib/scene/SpotLight.d.ts +2 -2
  115. package/lib/scene/SpotLight.js +1 -1
  116. package/lib/scene/SpotLight.js.map +1 -1
  117. package/lib/scene/Texture.d.ts +17 -6
  118. package/lib/scene/Texture.js +13 -4
  119. package/lib/scene/Texture.js.map +1 -1
  120. package/lib/util/fromTHREE.js +151 -29
  121. package/lib/util/fromTHREE.js.map +1 -1
  122. package/lib/version.d.ts +1 -1
  123. package/lib/version.js +1 -1
  124. package/lib/version.js.map +1 -1
  125. package/package.json +5 -4
package/docs/api.md CHANGED
@@ -310,11 +310,12 @@ Public spatial values use `Vec2` (`[number, number] | Float32Array`), `Vec3` (`[
310
310
  | `InstancedMesh`, `InstancedMeshOptions` | `new InstancedMesh(geometry, material \| material[], {count, transforms?, colors?})`; local Float32 column-major matrices default to identity, multiplied by inherited transform; count selects the active prefix; `colors` defaults to undefined (white linear RGB); `markUpdated(): this` notifies both matrices and colors; `markTransformsUpdated(start = 0, count = this.count - start): this` and `markColorsUpdated(start = 0, count = this.count - start): this` notify each separately. Each advances version once, initially 0. See [updates and costs](./updates.md#instanced-meshes) |
311
311
  | `Geometry`, `GeometryAttribute` | Triangle data: required `position`; optional `normal` and `indices` are generated at construction; `vertexCount` / `triangleCount` getters; optional `uv`, `uv1`, `tangent`, `color`, `materialIndex` (raw per-vertex indices, itemSize 1; all three corners of each triangle must match; invalid indices fall back to material 0 with one warning); `dynamic` (default `false`) for [deforming geometry](./updates.md#dynamic-geometry) |
312
312
  | `OpenPBRMaterial` | `new OpenPBRMaterial(params?)`; see [materials](./materials.md) |
313
- | `Texture` | HTMLImageElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas or `{ data, width, height }`; `Uint8Array`/`Uint8ClampedArray` color is sRGB; `Float32Array`/`Int32Array` color is linear |
313
+ | `Texture` | HTMLImageElement, HTMLCanvasElement, ImageBitmap, OffscreenCanvas or `{ data, width, height }`; `colorSpace`: `'srgb'` or `'linear'`; default undefined uses sRGB for images/bytes and linear for `Float32Array`/`Int32Array`; independent `wrapS` / `wrapT`: `'repeat'` (default), `'clamp-to-edge'`, `'mirrored-repeat'`, applied after UV scale/offset for material textures |
314
314
  | `Camera` | `new Camera({ projection: 'perspective', ... })` or orthographic; `position`, `lookAt()`, `copy(source)`, `clone()`; aspect defaults to automatic; depth of field with `fStop`, `focusDistance`, `sensorHeight`, `metersPerUnit` ([details](./getting-started.md#depth-of-field)) |
315
315
  | `RectLight`, `SphereLight`, `SpotLight`, `DirectionalLight`, `EnvironmentLight`, `AmbientLight` | Parameter-object constructors; analytic lights use `transform`, `position`, `lookAt()` and rigid axes. See [lights](./getting-started.md#lights) |
316
+ | `EnvironmentLight` | `new EnvironmentLight({map, intensity?})`; `intensity` defaults to `1`, scales environment radiance, and accepts `0` to disable lighting. Ambient lights and explicit background textures retain their own brightness. `transform` rotates the environment from local to world space (identity by default); translation and positive axis scale are ignored. An explicit background texture keeps its own orientation |
316
317
  | `IESProfile`, `parseIESProfile(text)` | Photometric profiles for `SpotLight` |
317
- | `SceneBackground` | `[r, g, b, a]`, `Texture` or `GroundedSkyboxBackground` |
318
+ | `SceneBackground` | `[r, g, b, a]`, `Texture` or `GroundedSkyboxBackground`; grounded backgrounds accept `rotation` around +Y in radians (default `0`) and `intensity` (default `1`). These affect only the background; the ground stays level and alpha is preserved |
318
319
 
319
320
  `OpenPBRMaterial` accepts canonical `specularRoughnessAnisotropy` (default `0`),
320
321
  `coatRoughnessAnisotropy` (`0`), `subsurfaceScatterAnisotropy` (`0`),
@@ -336,21 +337,22 @@ They follow the existing material/texture update mechanism.
336
337
 
337
338
  Raw texture sources contain exactly `width * height * 4` RGBA values, with
338
339
  rows ordered from top to bottom. `Uint8Array` and `Uint8ClampedArray` store
339
- 8-bit values: color slots decode RGB from sRGB, while data slots (roughness,
340
- normal, coat weight, etc.) read normalized channels directly. `Float32Array`
341
- (and `Int32Array` with linear integer values) supplies linear color and data
342
- channels, including HDR colors above 1. These sources can share a material
340
+ 8-bit values; color slots decode RGB from sRGB by default. `Float32Array`
341
+ (and `Int32Array` with integer HDR values) defaults to linear color, including
342
+ values above 1. Set `texture.colorSpace` to `'srgb'` or `'linear'` to override
343
+ color decoding. Data slots (roughness, normal, coat weight, etc.) always read
344
+ channels directly, normalizing bytes to [0, 1]. These sources can share a material
343
345
  texture array with Canvas images and other image sources on both backends.
344
346
 
345
- Material arrays containing linear raw sources use half-float storage (finite
347
+ Material arrays containing float/integer HDR sources use half-float storage (finite
346
348
  range up to 65504, rounded to half-float precision) and twice the bytes per
347
349
  pixel of an 8-bit array. Raw sources retain straight alpha and their original
348
350
  RGB even at zero alpha; Canvas composition can discard transparent RGB and
349
351
  round partially transparent colors. When the atlas budget requires resizing,
350
352
  raw sources use nearest-neighbor downsampling; image sources use Canvas
351
353
  resampling. Equal dimensions and opaque pixels allow exact byte/image
352
- comparisons. Float colors interpolate in linear space, while 8-bit color
353
- samples interpolate before sRGB decoding; gradients can therefore differ even
354
+ comparisons. Linear color samples interpolate in linear space, while sRGB color
355
+ samples interpolate before decoding; gradients can therefore differ even
354
356
  when their endpoint colors agree. Half-float and 8-bit filtering also have
355
357
  different precision.
356
358
 
package/docs/threejs.md CHANGED
@@ -62,12 +62,13 @@ then call `loop.tick()`. With first-layer frame control, call `sync.update()`,
62
62
  | `SkinnedMesh` / mesh with morph targets | CPU-deformed dynamic geometry |
63
63
  | `InstancedMesh` | One InstancedMesh per material group, with native colors, sharing geometry and BLAS |
64
64
  | Multi-material groups | One MuTracer mesh per group |
65
+ | Geometry `color` with `material.vertexColors = true` | Linear RGB colors modulate base color and unlit output, including base-color textures and instance colors; RGBA inputs use RGB only (vertex alpha is unsupported) |
65
66
  | `DirectionalLight` | `DirectionalLight` |
66
67
  | `PointLight` | `SphereLight` (radius `userData.mutracerRadius`, default 0.25) |
67
- | `SpotLight` | `SpotLight` (radius `userData.mutracerRadius`, default 0.01; `penumbra` sets the inner angle) |
68
+ | `SpotLight` | `SpotLight` (radius `userData.mutracerRadius`, default 0.01; `penumbra` sets the inner angle, with the same smooth falloff as Three.js) |
68
69
  | `RectAreaLight` | `RectLight` |
69
70
  | `AmbientLight` | `AmbientLight` |
70
- | `scene.environment` (equirectangular float `DataTexture`, e.g. from `HDRLoader`/`RGBELoader`) | `EnvironmentLight` |
71
+ | `scene.environment` (equirectangular float `DataTexture`, e.g. from `HDRLoader`/`RGBELoader`) | `EnvironmentLight`; orientation follows Three.js, so a `DataTexture` with `flipY = false` has its first row at the bottom |
71
72
  | `scene.background` color / texture | Background; the environment itself when `background === environment` |
72
73
 
73
74
  Three.js `opacity` maps to `geometryOpacity`; thin-shell choices map to
@@ -77,6 +78,28 @@ or conflict rule. These overrides apply after standard conversion; alpha mode
77
78
  still follows the source material flags and resolved coverage. Naming does not
78
79
  change transmission, volume or anisotropy conversion semantics.
79
80
 
81
+ Material `DataTexture` inputs support Red, RG, RGB and RGBA layouts, including
82
+ half-float data. Missing color channels become zero and missing alpha becomes
83
+ one. Decoded images use additional CPU memory and are reused until the source
84
+ texture is updated; set `texture.needsUpdate = true` after pixel edits.
85
+
86
+ `FrontSide`, `BackSide` and `DoubleSide` preserve the rendered face and normal
87
+ orientation. Later `material.side` edits synchronize automatically. Using both
88
+ front and back sides of shared geometry requires additional geometry memory.
89
+
90
+ Material color textures honor `LinearSRGBColorSpace` and `SRGBColorSpace`;
91
+ `NoColorSpace` reads color channels as linear. Data-map channels are always
92
+ linear. Color-space edits synchronize automatically.
93
+
94
+ Material textures preserve independent `wrapS` and `wrapT`: repeat,
95
+ clamp-to-edge and mirrored repeat. UV repeat and offset apply before wrapping;
96
+ later wrap edits synchronize automatically. Displacement uses the same modes.
97
+
98
+ `scene.environmentIntensity` controls environment lighting, including zero;
99
+ `scene.environmentRotation` rotates it using the source Euler order. Both
100
+ synchronize automatically. They do not change ambient lights or an explicitly
101
+ assigned `scene.background` texture.
102
+
80
103
  Thin-film ranges keep their endpoint order, including minimum greater than
81
104
  maximum, and retain the converter's 0–20 µm endpoint clamp. The converter uses
82
105
  Three.js's actual range defaults. `mutracerOpenPBR` may explicitly override the
@@ -93,7 +116,10 @@ copying pixels. General `KHR_texture_transform` rotation remains unsupported.
93
116
  Clearcoat normals are deferred to the independent coat-frame implementation.
94
117
  Anisotropy direction and source-model mapping are described [below](#anisotropy-source-conversion). The conversion preserves OpenPBR layering: glTF sheen
95
118
  layer order differs, and specular weight/color also affect metals in OpenPBR;
96
- these imports do not imply identical glTF BRDFs.
119
+ these imports do not imply identical glTF BRDFs. A fully metallic material
120
+ (`metalness` 1 without `metalnessMap`) ignores `specularIntensity`,
121
+ `specularColor` and their maps, as in glTF. Partially metallic or
122
+ metalness-mapped materials keep them, so their metal lobe is scaled too.
97
123
 
98
124
  Invisible objects are skipped. Other material types are skipped with a console
99
125
  warning unless `convertMaterial` supplies an OpenPBR material. `BatchedMesh`, instanced morph targets (`morphTexture`) and skinned
@@ -179,7 +205,7 @@ Renderer-specific settings without a Three.js equivalent:
179
205
  | `mutracerThinFilmMap` | material | Native R thickness texture with minimum 0; takes precedence over `iridescenceThicknessMap` |
180
206
  | `mutracerRadius` | point / spot light | Emitter radius |
181
207
  | `mutracerIesProfile`, `mutracerIesRotation` | spot light | `IESProfile` instance; rotation becomes local-Z transform rotation |
182
- | `mutracerGroundedSkybox: { texture, height, radius, groundHeight?, center? }` | scene | Grounded skybox background |
208
+ | `mutracerGroundedSkybox: { texture, height, radius, groundHeight?, center?, rotation?, intensity? }` | scene | Grounded skybox background; rotation/intensity options follow [SceneBackground](./api.md#scene-types) |
183
209
  | `mutracerHiddenBackground: true` | scene | Transparent background while keeping environment lighting |
184
210
 
185
211
  Directional and spot lights use their world position and target to build a
package/lib/Engine.js CHANGED
@@ -541,6 +541,8 @@ export default class Engine {
541
541
  return;
542
542
  this._disposed = true;
543
543
  this._bvhPreparationRevision++;
544
+ this._lossController?.abort(new Error('Engine is disposed.'));
545
+ this._lossController = undefined;
544
546
  this._contextRestore?.reject(new Error('Engine is disposed.'));
545
547
  this._contextRestore = undefined;
546
548
  if (this._webglListening) {
@@ -673,7 +675,22 @@ export default class Engine {
673
675
  this._customPrepared.set(denoiser, { device, width, height });
674
676
  }
675
677
  /** @internal */ _enqueueDenoise(work) {
676
- const task = this._denoiseTail.then(work);
678
+ const task = this._denoiseTail.then(async () => {
679
+ const device = this._gpuDevice, generation = this._deviceRevision;
680
+ try {
681
+ return await work();
682
+ }
683
+ finally {
684
+ // Cancelling tiled OIDN stops future tiles, not the commands already
685
+ // submitted. Keep the shared scratch lease until those commands finish
686
+ // so rapid edits cannot pile up inference or resize its inputs in flight.
687
+ // A lost/disposed device must release the lease without waiting for a
688
+ // queue that may never complete.
689
+ if (device && device === this._gpuDevice && generation === this._deviceRevision && !this._disposed) {
690
+ await this._awaitDevice(device.queue.onSubmittedWorkDone()).catch(() => { });
691
+ }
692
+ }
693
+ });
677
694
  this._denoiseTail = task.catch(() => { });
678
695
  return task;
679
696
  }
package/lib/Engine.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Engine.js","sourceRoot":"","sources":["../src/Engine.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAChG,OAAO,EAAC,YAAY,EAAC,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAC,8BAA8B,EAAE,cAAc,EAAC,MAAM,kCAAkC,CAAC;AAChG,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAI9D,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,mCAAmC,CAAC;AACxG,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAC/D,OAAO,EAAE,4BAA4B,EAAE,kBAAkB,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACzH,OAAO,EAAE,cAAc,EAAuB,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AACtG,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA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G,CAAC;CACF","sourcesContent":["import InstancedMesh from './scene/InstancedMesh.js';\nimport { bvhConfig, engineSettingsKey, workerCount, textureBudget } from './settings/engine.js';\nimport {createCanvas} from './util/canvas.js';\nimport Camera from './scene/Camera.js';\nimport {getRecommendedDeviceDescriptor, validateDevice} from './renderer/deviceRequirements.js';\nimport { cameraSnapshot } from './renderer/cameraSnapshot.js';\nimport type { Scene } from './scene/Scene.js';\nimport type Mesh from './scene/Mesh.js';\nimport type Geometry from './scene/Geometry.js';\nimport Display from './Display.js';\nimport type Render from './Render.js';\nimport { Events } from './util/events.js';\nimport { SceneChangeDetector, snapshotFields, snapshotsEqual } from './renderer/sceneChangeDetector.js';\nimport { CommittedScene } from './renderer/committedScene.js';\nimport { validateSceneLights } from './renderer/lightsUtil.js';\nimport { ensureMeshGeometryAttributes, meshNeedsStaticBvh, getPreparedMeshGeometry } from './renderer/prepareMeshBVH.js';\nimport { getGeometryBvh, type BvhBuildConfig } from './renderer/geometryBvh.js';\nimport { prepareStaticBvhs } from './renderer/staticBvhPreparation.js';\nimport { canUseBvhWorker, BvhWorkerPool, resolveBvhWorkerCount } from './renderer/bvhWorkerClient.js';\nimport { DEFAULT_MAX_TEXTURE_ARRAY_BYTES } from './renderer/MaterialTable.js';\nimport { packDepthSampleArea, type DepthSampleArea } from './renderer/depthQuery.js';\nimport { makeWGPURenderTargets } from './renderer/WGPURenderingPipeline.js';\nimport { makeWebGLRenderTargets } from './renderer/WebGLRenderingPipeline.js';\nimport { WebGLDevice as WebGLRenderer } from './renderer/webgl.js';\nimport type { RenderPipeline, RenderTarget } from './renderer/renderPipeline.js';\nimport type { RenderingDiagnostics } from './renderer/RenderingPipeline.js';\nimport type { TinyBvhLayout } from './tinybvh/TinyBvhBuilder.js';\nimport type {OwnedDenoiser} from './renderer/denoiser.js';\nimport type {Denoiser} from './Render.js';\nexport type { DepthSampleArea } from './renderer/depthQuery.js';\n\n/** BLAS implementation; default builtin. */\nexport type BVHBuilder = 'tinybvh' | 'builtin';\n/** Optional CPU preparation settings. */\nexport interface PrepareOptions {\n /** Completed BLAS fraction 0–1. Default undefined. */ onProgress?: (progress: number) => void;\n /** Cancels preparation. Default undefined. */ signal?: AbortSignal;\n}\n/** Engine construction settings. */\nexport interface EngineParams {\n /** Default display canvas. Default a new HTML canvas, or OffscreenCanvas without document. */ canvas?: HTMLCanvasElement | OffscreenCanvas;\n /** Backend selection. Default auto, with WebGL fallback. webgpu requires WebGPU. */ backend?: 'auto' | 'webgpu' | 'webgl';\n /** Caller-owned WebGPU device. Default undefined uses a shared device. Implies webgpu; incompatible with webgl. */ device?: GPUDevice;\n}\n/** Material-atlas device limits. */\nexport interface TextureAtlasLimits { maxTextureArrayLayers: number; maxTextureDimension2D: number; }\n/** Initialization result. */\nexport interface EngineInfo {\n backend: 'webgpu' | 'webgl'; adapterName: string; webgpuFallbackReason?: string; limits: TextureAtlasLimits;\n}\n/** Device and target diagnostics; Per-target GPU bytes exclude shared scene, temporary passes and driver costs. */\nexport interface EngineDiagnostics extends RenderingDiagnostics {\n backend: 'webgpu' | 'webgl' | undefined; adapterName: string;\n width: number; height: number; lastError?: string; webgpuFallbackReason?: string;\n}\ninterface EngineEvents {\n progress: { stage: 'device' | 'bvh' | 'shaders'; progress: number };\n error: Error;\n devicelost: { reason: string; recovering: boolean };\n}\nlet globalGPUDevice: GPUDevice | null = null;\nlet globalGPUAdapterInfo: GPUAdapterInfo | null = null;\nlet globalGPURequest: Promise<GPUDevice> | undefined;\nasync function sharedDevice(gpu: GPU): Promise<GPUDevice> {\n if (globalGPUDevice) return globalGPUDevice;\n if (!globalGPURequest) {\n const request = (async () => {\n const adapter = await gpu.requestAdapter({powerPreference: 'high-performance'}) ?? await gpu.requestAdapter();\n if (!adapter) throw new Error('No WebGPU adapter is available');\n const device = await adapter.requestDevice(getRecommendedDeviceDescriptor(adapter));\n globalGPUAdapterInfo = (adapter as GPUAdapter & {info?: GPUAdapterInfo}).info ?? null;\n globalGPUDevice = device;\n void device.lost.then(() => { if (globalGPUDevice === device) globalGPUDevice = null; });\n return device;\n })();\n globalGPURequest = request;\n void request.finally(() => { if (globalGPURequest === request) globalGPURequest = undefined; }).catch(() => {});\n }\n return globalGPURequest;\n}\n\n/** Shared device, committed scene/camera, CPU preparation and denoiser ownership. */\nexport default class Engine {\n /** Source scene, accepted only by update(). Default undefined. */ scene: Scene | undefined;\n /** Source camera, accepted only by update(). Default undefined. */ camera: Camera | undefined;\n /** Default canvas and display settings. */ readonly display: Display;\n /** Static BLAS builder. Default builtin. */ bvhBuilder: BVHBuilder = 'builtin';\n /** Static BLAS layout. Default bvh2; dynamic geometry uses bvh2. */ bvhLayout: TinyBvhLayout = 'bvh2';\n /** Enable TinyBVH spatial splits. Default false. */ bvhSpatialSplits = false;\n /** Material texture budget in bytes. Default 384 MiB. */ textureAtlasBudgetBytes = DEFAULT_MAX_TEXTURE_ARRAY_BYTES;\n /** Maximum CPU BVH workers. Default auto (hardware concurrency minus one, clamped 1–4). */\n get bvhWorkerCount(): number | 'auto' { return this._bvhWorkerCount; }\n set bvhWorkerCount(count: number | 'auto') { resolveBvhWorkerCount(count); this._bvhWorkerCount = count; }\n private _bvhWorkerCount: number | 'auto' = 'auto';\n private _bvhWorkerPool?: BvhWorkerPool;\n private _bvhPreparationRevision = 0;\n private _bvhPreparation?: Promise<void>;\n private _bvhPreparationTail: Promise<unknown> = Promise.resolve();\n private _tinyBvhUnavailable = false;\n private _bvhWorkerUnavailable = false;\n private _bvhPreparedGeometry = new WeakMap<Mesh, [Geometry, number]>();\n private _lastBvhBuild?: { geometryCount: number; bvhTimeMs: number };\n private _lastBvhSettings = '';\n private _lastBudget = -1;\n private _shaderProgress = '';\n private _events = new Events<EngineEvents>();\n private _pipeline?: RenderPipeline;\n private _webglRenderer?: WebGLRenderer;\n private _gpuDevice?: GPUDevice;\n private _suppliedDevice?: GPUDevice;\n private readonly _ownsDeviceSelection: boolean;\n private _deviceRevision = 0;\n private _lossController?: AbortController;\n private _deviceLossError?: Error;\n private _webglListening = false;\n private _webglLost = false;\n private _recoverWebGL = false;\n private _contextRestore?: {promise: Promise<void>; resolve: () => void; reject: (error: Error) => void};\n private _gpuAdapterInfo?: GPUAdapterInfo;\n private _backendChoice: NonNullable<EngineParams['backend']>;\n private _initPromise?: Promise<EngineInfo>;\n private _info?: EngineInfo;\n private _pipelineInitError?: Error;\n private _webgpuFallbackReason?: string;\n private _reportedErrors = new WeakSet<Error>();\n private _loggedErrorMessages = new Set<string>();\n private _sceneChangeDetector: SceneChangeDetector;\n private _snapshot = new CommittedScene();\n private _sourceScene?: Scene;\n private _committedScene?: Scene;\n private _sourceCamera?: Camera;\n private _committedCamera?: Camera;\n private _cameraFields: unknown[] = [];\n private _sceneRevision = 0;\n private _cameraRevision = 0;\n private _uploadedRevision = -1;\n private _pendingMeshes: 'none' | 'incremental' | 'full' = 'full';\n private _pendingTransforms = new Set<Mesh>();\n private _pendingColors = new Set<InstancedMesh>();\n private _pendingGeometries = new Set<Geometry>();\n private _pendingMaterials = new Set<import('./scene/OpenPBRMaterial.js').default>();\n private _pendingLights = true;\n private _pendingBackground = true;\n private _disposed = false;\n private _readingDepth = false;\n private _renders = new Set<Render>();\n private _targetCounter = 0;\n private _presented?: RenderTarget;\n private _denoisers = new Set<OwnedDenoiser>();\n private _denoiserCache = new Map<string, {references: number; value?: OwnedDenoiser; pending?: Promise<OwnedDenoiser>}>();\n private _denoiserEntries = new WeakMap<OwnedDenoiser, {key: string; references: number; value?: OwnedDenoiser; pending?: Promise<OwnedDenoiser>}>();\n private _weights = new Map<string, Promise<ArrayBuffer>>();\n private _customPrepared = new WeakMap<Denoiser, {device: GPUDevice; width: number; height: number}>();\n private _denoiseTail: Promise<unknown> = Promise.resolve();\n private _lastError: Error | undefined;\n /** Most recent synchronous engine/render failure. Default undefined. */\n get lastError() { return this._lastError; }\n /** @internal */ _setRenderError(error?: Error) { this._lastError = error ?? this._pipelineInitError; }\n\n constructor(params: EngineParams = {}) {\n if (params.device && params.backend === 'webgl') throw new Error('A supplied GPUDevice cannot use the webgl backend.');\n this._suppliedDevice = params.device;\n this._ownsDeviceSelection = !params.device;\n this._backendChoice = params.device ? 'webgpu' : params.backend ?? 'auto';\n this._sceneChangeDetector = new SceneChangeDetector();\n this.display = Display._create(this, params.canvas ?? createCanvas());\n }\n /** Initializes once; concurrent/repeated calls share the result. */\n init(): Promise<EngineInfo> {\n return this._initPromise ??= (async () => {\n if (this._disposed) throw new Error('Engine is disposed.');\n if (this._pipelineInitError && !this._ownsDeviceSelection) throw this._pipelineInitError;\n const revision = this._deviceRevision;\n if (this._contextRestore) await this._contextRestore.promise;\n if (this._disposed) throw new Error('Engine is disposed.');\n await this._initPipeline(this._backendChoice !== 'webgl' && !this._recoverWebGL);\n if (revision !== this._deviceRevision) throw this._deviceLossError;\n if (this._pipelineInitError) throw this._pipelineInitError;\n if (this._disposed) { this._pipeline?.dispose(); throw new Error('Engine is disposed.'); }\n const gl = this._webglRenderer?.gl, limits = this._gpuDevice?.limits;\n this._info = { backend: this._gpuDevice ? 'webgpu' : 'webgl', adapterName: this._adapterName(), webgpuFallbackReason: this._webgpuFallbackReason,\n limits: { maxTextureArrayLayers: limits?.maxTextureArrayLayers ?? gl?.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS), maxTextureDimension2D: limits?.maxTextureDimension2D ?? gl?.getParameter(gl.MAX_TEXTURE_SIZE) } };\n this._upload();\n return this._info;\n })();\n }\n /** Initialization info. Default undefined until init resolves. */ get info() { return this._info; }\n /** Active backend. Default undefined until initialization completes. */ get backend() { return this._info?.backend; }\n /** GPU device. Default undefined before initialization and on WebGL. */ get device() { return this._gpuDevice; }\n /** Subscribes to shared progress/errors/device loss; returns unsubscribe. */\n on<K extends keyof EngineEvents>(event: K, listener: (value: EngineEvents[K]) => void): () => void { return this._events.on(event, listener); }\n\n /** The sole external edit detection/commit point. Returns whether inputs changed. */\n update(): boolean {\n if (this._disposed) throw new Error('Engine is disposed.');\n this._lastError = this._pipelineInitError;\n let changed = false, resetTiming = false;\n const cameraFields = this.camera ? snapshotFields(this.camera) : [];\n if (this.camera !== this._sourceCamera || !snapshotsEqual(cameraFields, this._cameraFields)) {\n this._sourceCamera = this.camera; this._cameraFields = cameraFields;\n this._committedCamera = this.camera ? cameraSnapshot(this.camera) : undefined; this._cameraRevision++; changed = true;\n }\n const bvhSettings = engineSettingsKey(this, 'bvh');\n const force = bvhSettings !== this._lastBvhSettings || textureBudget(this) !== this._lastBudget;\n if (this.scene !== this._sourceScene || force) this._sceneChangeDetector.reset();\n if (this.scene) {\n validateSceneLights(this.scene.lights, error => this._notifyError(error));\n ensureMeshGeometryAttributes(this.scene.meshes);\n const changes = this._sceneChangeDetector.detect(this.scene);\n resetTiming = changes.meshes === 'full' || this.scene !== this._sourceScene || force;\n if (changes.meshes !== 'none' || changes.lights || changes.background || this.scene !== this._sourceScene || force) {\n this._committedScene = this._snapshot.capture(this.scene, changes);\n if (changes.meshes === 'full' || force || this.scene !== this._sourceScene) this._pendingMeshes = 'full';\n else if (changes.meshes === 'incremental' && this._pendingMeshes !== 'full') this._pendingMeshes = 'incremental';\n for (const mesh of changes.transforms) this._pendingTransforms.add(this._snapshot.mirror(mesh));\n for (const mesh of changes.colors) this._pendingColors.add(this._snapshot.mirror(mesh));\n for (const geometry of changes.geometries) this._pendingGeometries.add(this._snapshot.mirror(geometry));\n for (const material of changes.materials) this._pendingMaterials.add(this._snapshot.mirror(material));\n this._pendingLights ||= changes.lights;\n this._pendingBackground ||= changes.background;\n this._sceneRevision++; changed = true;\n }\n this._sceneChangeDetector.commit();\n } else if (this._sourceScene) { this._committedScene = undefined; this._pendingMeshes = 'full'; this._pendingLights = true; this._pendingBackground = true; this._sceneRevision++; changed = true; }\n this._sourceScene = this.scene; this._lastBvhSettings = bvhSettings; this._lastBudget = textureBudget(this);\n if (!this._pipeline) void this.init().catch(() => {});\n if (changed) for (const render of this._renders) render._inputsChanged(resetTiming);\n this._upload();\n return changed;\n }\n private _upload() {\n const pipeline = this._pipeline;\n if (!pipeline || this._disposed || this._bvhPreparation || this._uploadedRevision === this._sceneRevision) return;\n const scene = this._committedScene ?? { meshes: [], lights: [] };\n if (this._needsBVHPreparation(scene.meshes)) {\n const task = this.prepare(scene); this._bvhPreparation = task;\n void task.then(() => { if (this._bvhPreparation === task) this._bvhPreparation = undefined; this._upload(); }, error => { if (this._bvhPreparation === task) this._bvhPreparation = undefined; this._notifyError(error); });\n return;\n }\n const budgetChanged = pipeline.setTextureAtlasBudget(this._lastBudget >= 0 ? this._lastBudget : textureBudget(this));\n if (this._pendingMeshes !== 'none' || budgetChanged) pipeline.setMeshes(scene.meshes, this._pendingMeshes === 'full' || budgetChanged ? undefined : {\n transforms: [...this._pendingTransforms], colors: [...this._pendingColors], geometries: [...this._pendingGeometries], materials: [...this._pendingMaterials]\n });\n if (this._pendingLights) pipeline.setLights(scene.lights);\n if (this._pendingBackground) pipeline.setBackground(scene.background);\n this._pendingMeshes = 'none'; this._pendingLights = false; this._pendingBackground = false;\n this._pendingTransforms.clear(); this._pendingColors.clear(); this._pendingGeometries.clear(); this._pendingMaterials.clear();\n this._uploadedRevision = this._sceneRevision;\n }\n private _bvhConfig(): BvhBuildConfig { return bvhConfig(this); }\n /** Builds static CPU BVHs for this scene without replacing GPU inputs. Options default undefined. */\n prepare(scene: Scene, options: PrepareOptions = {}): Promise<void> {\n const revision = this._bvhPreparationRevision;\n const preparation = this._bvhPreparationTail.then(async () => {\n const isCancelled = () => revision !== this._bvhPreparationRevision || options.signal?.aborted === true;\n if (isCancelled()) return;\n const meshes = scene.meshes;\n const useWorker = canUseBvhWorker() && !this._bvhWorkerUnavailable;\n if (useWorker) {\n const count = workerCount(this);\n if (this._bvhWorkerPool?.size !== count) {\n this._bvhWorkerPool?.dispose();\n this._bvhWorkerPool = new BvhWorkerPool(count);\n }\n }\n const config = this._bvhConfig();\n const result = await prepareStaticBvhs(meshes, {\n config,\n ...config,\n builder: this.bvhBuilder === 'tinybvh' && !this._tinyBvhUnavailable ? 'tinybvh' : 'builtin',\n useWorker, workerPool: this._bvhWorkerPool, isCancelled,\n rebuild: false, onProgress: progress => {\n if (this._bvhPreparation === preparation) this._events.emit('progress', {stage: 'bvh', progress});\n options.onProgress?.(progress);\n }\n });\n if (isCancelled()) return;\n if (result.workerUnavailable && !this._bvhWorkerUnavailable) {\n this._bvhWorkerUnavailable = true;\n this._bvhWorkerPool?.dispose();\n this._bvhWorkerPool = undefined;\n console.warn('BVH preparation failed; falling back to the calling-thread BVH builder.');\n }\n if (result.tinyBvhUnavailable && !this._tinyBvhUnavailable) {\n this._tinyBvhUnavailable = true;\n console.warn('BVH preparation failed; falling back to the built-in BVH builder.');\n }\n result.failedMeshes.forEach(mesh => {\n this._bvhPreparedGeometry.set(mesh, [mesh.geometry, mesh.geometry.version]);\n });\n\n this._lastBvhBuild = { geometryCount: result.geometryCount, bvhTimeMs: result.bvhTimeMs };\n });\n this._bvhPreparationTail = preparation.catch(() => undefined);\n const signal = options.signal;\n if (!signal) return preparation;\n return new Promise<void>((resolve, reject) => {\n const aborted = () => reject(signal.reason ?? new DOMException('BVH preparation aborted', 'AbortError'));\n if (signal.aborted) { aborted(); return; }\n signal.addEventListener('abort', aborted, { once: true });\n preparation.then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted));\n });\n }\n\n private _needsBVHPreparation(meshes: Mesh[]) {\n if (this._bvhPreparation) return true;\n if ((this.bvhBuilder !== 'tinybvh' || this._tinyBvhUnavailable) &&\n (!canUseBvhWorker() || this._bvhWorkerUnavailable)) {\n return meshes.some(mesh => !!getGeometryBvh(getPreparedMeshGeometry(mesh)) && meshNeedsStaticBvh(mesh, this._bvhConfig()));\n }\n return meshes.some((mesh) => {\n const prepared = this._bvhPreparedGeometry.get(mesh);\n const attempted = prepared?.[0] === mesh.geometry &&\n prepared[1] === mesh.geometry.version;\n return !attempted && meshNeedsStaticBvh(mesh, this._bvhConfig());\n });\n }\n\n private async _initPipeline(preferWebGPU: boolean) {\n let gpuCreated = false;\n try {\n\n this._events.emit('progress', {stage: 'device', progress: 0});\n this._pipelineInitError = undefined;\n if (preferWebGPU && (this._suppliedDevice || (typeof navigator !== 'undefined' && navigator.gpu))) {\n try {\n const gpu = typeof navigator !== 'undefined' ? navigator.gpu : undefined;\n const gpuDevice = this._suppliedDevice ?? await sharedDevice(gpu!);\n const gpuAdapterInfo = this._suppliedDevice\n ? (gpuDevice as GPUDevice & {adapterInfo?: GPUAdapterInfo}).adapterInfo : globalGPUAdapterInfo;\n if (this._disposed) return;\n validateDevice(gpuDevice);\n this._gpuAdapterInfo = gpuAdapterInfo ?? undefined;\n this._gpuDevice = gpuDevice;\n this._pipeline = makeWGPURenderTargets(this.display.canvas, gpuDevice, {\n presentationFormat: gpu?.getPreferredCanvasFormat() ?? 'bgra8unorm'\n });\n this._watchDevice(gpuDevice);\n gpuCreated = true;\n } catch (e) {\n if (this._backendChoice === 'webgpu') throw e;\n this._webgpuFallbackReason = e instanceof Error ? e.message : String(e);\n this._gpuDevice = undefined;\n this._gpuAdapterInfo = undefined;\n }\n }\n if (!gpuCreated) {\n if (this._backendChoice === 'webgpu') throw new Error('WebGPU is not available in this environment');\n if (preferWebGPU && !this._webgpuFallbackReason) {\n this._webgpuFallbackReason = 'WebGPU is not available in this environment';\n }\n this._webglRenderer = new WebGLRenderer({\n canvas: this.display.canvas,\n alpha: true,\n depth: true,\n stencil: false,\n antialias: false,\n pixelRatio: 1,\n preserveDrawingBuffer: true,\n // PENDING\n premultipliedAlpha: false,\n parallelShaderCompile: true,\n powerPreference: 'high-performance'\n });\n\n this._pipeline = makeWebGLRenderTargets(this._webglRenderer);\n if (!this._webglListening) {\n this._webglListening = true;\n this.display.canvas.addEventListener('webglcontextlost', this._onContextLost);\n this.display.canvas.addEventListener('webglcontextrestored', this._onContextRestored);\n }\n this._recoverWebGL = false;\n }\n\n\n } catch (error) {\n this._pipelineInitError = error instanceof Error ? error : new Error(String(error));\n this._lastError = this._pipelineInitError;\n this._notifyError(this._pipelineInitError);\n } finally {\n\n this._events.emit('progress', {stage: 'device', progress: 1});\n }\n }\n\n private _onContextLost = (event: Event) => {\n event.preventDefault();\n if (this._disposed || this._webglLost) return;\n this._webglLost = true; this._recoverWebGL = true;\n let resolve!: () => void, reject!: (error: Error) => void;\n const promise = new Promise<void>((done, fail) => {resolve = done; reject = fail;});\n void promise.catch(() => {});\n this._contextRestore = {promise, resolve, reject};\n const error = new Error(`WebGL context lost: ${(event as WebGLContextEvent).statusMessage || 'context is unavailable'}`);\n this._invalidateDevice(error, true);\n this._events.emit('devicelost', {reason: 'webglcontextlost', recovering: true});\n };\n private _onContextRestored = () => {\n if (this._disposed || !this._webglLost) return;\n this._webglLost = false;\n const restore = this._contextRestore; this._contextRestore = undefined; restore?.resolve();\n };\n private _watchDevice(device: GPUDevice) {\n void device.lost.then(info => {\n if (this._disposed || this._gpuDevice !== device) return;\n if (globalGPUDevice === device) globalGPUDevice = null;\n const recovering = this._ownsDeviceSelection;\n const error = new Error(`WebGPU device lost (${info.reason}): ${info.message || 'device is unavailable'}`);\n this._invalidateDevice(error, recovering);\n this._events.emit('devicelost', {reason: info.reason, recovering});\n if (!recovering) this._notifyError(error);\n });\n }\n private _invalidateDevice(error: Error, recovering: boolean) {\n this._deviceLossError = error; this._deviceRevision++;\n this._lossController?.abort(error); this._lossController = undefined;\n for (const render of this._renders) render._deviceLost(recovering);\n this._pipeline?.dispose(); this._pipeline = undefined;\n this._webglRenderer?.dispose(); this._webglRenderer = undefined;\n this._gpuDevice = undefined; this._gpuAdapterInfo = undefined;\n this._info = undefined; this._initPromise = undefined;\n this._pipelineInitError = recovering ? undefined : error; this._lastError = error;\n this._presented = undefined; this._shaderProgress = '';\n this._uploadedRevision = -1; this._pendingMeshes = 'full'; this._pendingLights = true; this._pendingBackground = true;\n this._sceneRevision++;\n this._customPrepared = new WeakMap();\n for (const filter of [...this._denoisers]) {\n const entry = this._denoiserEntries.get(filter); if (entry) entry.references = 1;\n this._releaseDenoiser(filter);\n }\n this._denoiserCache.clear();\n }\n /** Replaces a caller-owned device after validation. Only available on engines\n * constructed with device; the next update/refine uploads the committed scene.\n */\n async setDevice(device: GPUDevice): Promise<void> {\n if (this._disposed) throw new Error('Engine is disposed.');\n if (this._ownsDeviceSelection) throw new Error('setDevice requires an engine constructed with device.');\n try { validateDevice(device); }\n catch (error) {this._lastError = this._notifyError(error); throw error;}\n if (this._gpuDevice === device && !this._pipelineInitError) return;\n this._invalidateDevice(new Error('WebGPU device replaced during converge.'), true);\n this._suppliedDevice = device;\n }\n /** @internal Device loss rejects pending waits without relying on driver completion. */\n _awaitDevice<T>(work: Promise<T>): Promise<T> {\n const signal = (this._lossController ??= new AbortController()).signal;\n return new Promise((resolve, reject) => {\n const lost = () => reject(signal.reason);\n signal.addEventListener('abort', lost, {once: true});\n work.then(resolve, reject).finally(() => signal.removeEventListener('abort', lost));\n });\n }\n /** @internal */ get _deviceGeneration() { return this._deviceRevision; }\n /** @internal */ get _lostError() { return this._deviceLossError; }\n\n private _adapterName() {\n if (this._gpuAdapterInfo) return this._gpuAdapterInfo.description || this._gpuAdapterInfo.vendor || 'WebGPU';\n const gl = this._webglRenderer?.gl, extension = gl?.getExtension('WEBGL_debug_renderer_info');\n return extension && gl ? gl.getParameter(extension.UNMASKED_RENDERER_WEBGL) : this._webglRenderer ? 'WebGL 2' : this._gpuDevice ? 'WebGPU' : '';\n }\n /** @internal */ _reportShaderProgress() {\n const compilation = this._pipeline?.getDiagnostics().shaderCompilation;\n if (!compilation) return;\n const key = `${compilation.status}/${compilation.completedPipelineCount}/${compilation.pipelineCount}`;\n if (key === this._shaderProgress) return;\n this._shaderProgress = key;\n this._events.emit('progress', {stage: 'shaders', progress: compilation.pipelineCount ? compilation.completedPipelineCount / compilation.pipelineCount : 1});\n }\n /** Current shared preparation and resident target statistics. Default undefined before any work. */\n getDiagnostics(): EngineDiagnostics | undefined {\n if (!this._pipeline && !this._lastBvhBuild) return;\n const values = this._pipeline?.getDiagnostics();\n return { ...values, bvh: {...values?.bvh, lastBuild: this._lastBvhBuild}, backend: this.backend, adapterName: this._adapterName(), width: this.display.canvas.width, height: this.display.canvas.height,\n lastError: this.lastError?.message, webgpuFallbackReason: this._webgpuFallbackReason,\n presentedTarget: this._presented?.label, presentedComplete: this._presented?.presentationComplete ?? false };\n }\n /** Queries a 7×7 depth grid using the committed engine camera. Default undefined until GPU data is ready. */\n async readDepthSamples(area: DepthSampleArea): Promise<Float32Array | undefined> {\n packDepthSampleArea(area, 1);\n if (!this._ready || !this._committedCamera || this._readingDepth) return;\n this._readingDepth = true;\n try {\n const camera = cameraSnapshot(this._committedCamera);\n camera.aspect ??= this.display.canvas.width / this.display.canvas.height;\n const result = await this._pipeline!.readDepthSamples(camera, area);\n return this._disposed ? undefined : result;\n }\n finally { this._readingDepth = false; }\n }\n /** Releases all renders, shared resources, CPU workers and owned denoisers. */\n dispose() {\n if (this._disposed) return;\n this._disposed = true; this._bvhPreparationRevision++;\n this._contextRestore?.reject(new Error('Engine is disposed.')); this._contextRestore = undefined;\n if (this._webglListening) {\n this.display.canvas.removeEventListener('webglcontextlost', this._onContextLost);\n this.display.canvas.removeEventListener('webglcontextrestored', this._onContextRestored);\n }\n for (const render of [...this._renders]) render.dispose();\n this._pipeline?.dispose(); this._pipeline = undefined; this._webglRenderer?.dispose(); this._bvhWorkerPool?.dispose();\n for (const denoiser of [...this._denoisers]) { const entry = this._denoiserEntries.get(denoiser); if (entry) entry.references = 1; this._releaseDenoiser(denoiser); }\n this._denoiserCache.clear();\n this._weights.clear(); this._events.clear();\n }\n /** @internal */ get _initializationError() { return this._pipelineInitError; }\n /** @internal */ get _ready() { return !!this._pipeline && this._uploadedRevision === this._sceneRevision && !!this._committedScene && !!this._committedCamera && !this._disposed; }\n /** @internal */ get _inputs() { return {scene: this._sceneRevision, camera: this._cameraRevision, value: this._committedCamera}; }\n /** @internal */ _register(render: Render) { if (this._disposed) throw new Error('Engine is disposed.'); this._renders.add(render); }\n /** @internal */ _unregister(render: Render) { this._renders.delete(render); }\n /** @internal */ _createTarget() { return this._pipeline?.createTarget(`render-${++this._targetCounter}`); }\n /** @internal */ _releaseTarget(target: RenderTarget) { if (this._presented === target) this._presented = undefined; this._pipeline?.releaseTarget(target); }\n /** @internal */ _present(target: RenderTarget) { target.activate(); target.present(); this._presented = target; }\n /** @internal */ _notifyError(value: unknown): Error {\n const error = value instanceof Error ? value : new Error(String(value));\n if (!this._loggedErrorMessages.has(error.message)) { this._loggedErrorMessages.add(error.message); console.error(`Path tracing failed: ${error.message}`, error); }\n if (!this._reportedErrors.has(error)) { this._reportedErrors.add(error); this._events.emit('error', error); }\n return error;\n }\n /** @internal */ _getWeights(url: string, load: () => Promise<ArrayBuffer>) {\n let pending = this._weights.get(url);\n if (!pending) { pending = load(); this._weights.set(url, pending); void pending.catch(() => { if (this._weights.get(url) === pending) this._weights.delete(url); }); }\n return pending;\n }\n /** @internal */ _retainDenoiser<T extends OwnedDenoiser>(key: string, create: () => T): T {\n let entry = this._denoiserCache.get(key);\n if (!entry?.value) {\n const value = this._ownDenoiser(create());\n const next = {key, references: 0, value};\n this._denoiserCache.set(key, next); this._denoiserEntries.set(value, next); entry = next;\n }\n entry.references++; return entry.value as T;\n }\n /** @internal */ async _acquireDenoiser(key: string, create: () => Promise<Extract<OwnedDenoiser, {kind: 'oidn'}>>): Promise<Extract<OwnedDenoiser, {kind: 'oidn'}>> {\n let entry = this._denoiserCache.get(key);\n if (!entry) {\n const next: {key: string; references: number; value?: OwnedDenoiser; pending?: Promise<OwnedDenoiser>} = {key, references: 0};\n const revision = this._deviceRevision;\n next.pending = create().then(filter => {\n if (revision !== this._deviceRevision) { this._disposeDenoiser(filter); throw this._deviceLossError; }\n next.value = this._ownDenoiser(filter); this._denoiserEntries.set(filter, next); return filter; });\n this._denoiserCache.set(key, next); entry = next;\n }\n entry.references++;\n try { return (entry.value ?? await entry.pending!) as Extract<OwnedDenoiser, {kind: 'oidn'}>; }\n catch (error) { entry.references--; if (this._denoiserCache.get(key) === entry) this._denoiserCache.delete(key); throw error; }\n }\n /** @internal */ _ownDenoiser<T extends OwnedDenoiser>(denoiser: T): T {\n if (this._disposed) { this._disposeDenoiser(denoiser); throw new Error('Engine is disposed.'); }\n this._denoisers.add(denoiser); return denoiser;\n }\n /** @internal */ _releaseDenoiser(denoiser: OwnedDenoiser) {\n const entry = this._denoiserEntries.get(denoiser);\n if (entry && --entry.references > 0) return;\n if (entry && this._denoiserCache.get(entry.key) === entry) this._denoiserCache.delete(entry.key);\n this._denoiserEntries.delete(denoiser);\n if (!this._denoisers.delete(denoiser)) return;\n this._disposeDenoiser(denoiser);\n }\n private _disposeDenoiser(denoiser: OwnedDenoiser) {\n if (denoiser.kind === 'oidn') { denoiser.denoiser.auxiliaryDenoisers?.albedo.dispose(); denoiser.denoiser.auxiliaryDenoisers?.normal.dispose(); }\n denoiser.denoiser.dispose();\n }\n /** @internal Called only while holding the shared inference lease. */\n async _prepareCustomDenoiser(denoiser: Denoiser, width: number, height: number) {\n const device = this.device;\n if (!device) throw new Error('Custom denoising requires WebGPU.');\n const previous = this._customPrepared.get(denoiser);\n if (previous?.device === device && previous.width === width && previous.height === height) return;\n await denoiser.prepare?.({device, width, height});\n this._customPrepared.set(denoiser, {device, width, height});\n }\n /** @internal */ _enqueueDenoise<T>(work: () => Promise<T>): Promise<T> {\n const task = this._denoiseTail.then(work); this._denoiseTail = task.catch(() => {}); return task;\n }\n}\n"]}
1
+ {"version":3,"file":"Engine.js","sourceRoot":"","sources":["../src/Engine.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAChG,OAAO,EAAC,YAAY,EAAC,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAC,8BAA8B,EAAE,cAAc,EAAC,MAAM,kCAAkC,CAAC;AAChG,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAI9D,OAAO,OAAO,MAAM,cAAc,CA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IACxD,CAAC;CACF","sourcesContent":["import InstancedMesh from './scene/InstancedMesh.js';\nimport { bvhConfig, engineSettingsKey, workerCount, textureBudget } from './settings/engine.js';\nimport {createCanvas} from './util/canvas.js';\nimport Camera from './scene/Camera.js';\nimport {getRecommendedDeviceDescriptor, validateDevice} from './renderer/deviceRequirements.js';\nimport { cameraSnapshot } from './renderer/cameraSnapshot.js';\nimport type { Scene } from './scene/Scene.js';\nimport type Mesh from './scene/Mesh.js';\nimport type Geometry from './scene/Geometry.js';\nimport Display from './Display.js';\nimport type Render from './Render.js';\nimport { Events } from './util/events.js';\nimport { SceneChangeDetector, snapshotFields, snapshotsEqual } from './renderer/sceneChangeDetector.js';\nimport { CommittedScene } from './renderer/committedScene.js';\nimport { validateSceneLights } from './renderer/lightsUtil.js';\nimport { ensureMeshGeometryAttributes, meshNeedsStaticBvh, getPreparedMeshGeometry } from './renderer/prepareMeshBVH.js';\nimport { getGeometryBvh, type BvhBuildConfig } from './renderer/geometryBvh.js';\nimport { prepareStaticBvhs } from './renderer/staticBvhPreparation.js';\nimport { canUseBvhWorker, BvhWorkerPool, resolveBvhWorkerCount } from './renderer/bvhWorkerClient.js';\nimport { DEFAULT_MAX_TEXTURE_ARRAY_BYTES } from './renderer/MaterialTable.js';\nimport { packDepthSampleArea, type DepthSampleArea } from './renderer/depthQuery.js';\nimport { makeWGPURenderTargets } from './renderer/WGPURenderingPipeline.js';\nimport { makeWebGLRenderTargets } from './renderer/WebGLRenderingPipeline.js';\nimport { WebGLDevice as WebGLRenderer } from './renderer/webgl.js';\nimport type { RenderPipeline, RenderTarget } from './renderer/renderPipeline.js';\nimport type { RenderingDiagnostics } from './renderer/RenderingPipeline.js';\nimport type { TinyBvhLayout } from './tinybvh/TinyBvhBuilder.js';\nimport type {OwnedDenoiser} from './renderer/denoiser.js';\nimport type {Denoiser} from './Render.js';\nexport type { DepthSampleArea } from './renderer/depthQuery.js';\n\n/** BLAS implementation; default builtin. */\nexport type BVHBuilder = 'tinybvh' | 'builtin';\n/** Optional CPU preparation settings. */\nexport interface PrepareOptions {\n /** Completed BLAS fraction 0–1. Default undefined. */ onProgress?: (progress: number) => void;\n /** Cancels preparation. Default undefined. */ signal?: AbortSignal;\n}\n/** Engine construction settings. */\nexport interface EngineParams {\n /** Default display canvas. Default a new HTML canvas, or OffscreenCanvas without document. */ canvas?: HTMLCanvasElement | OffscreenCanvas;\n /** Backend selection. Default auto, with WebGL fallback. webgpu requires WebGPU. */ backend?: 'auto' | 'webgpu' | 'webgl';\n /** Caller-owned WebGPU device. Default undefined uses a shared device. Implies webgpu; incompatible with webgl. */ device?: GPUDevice;\n}\n/** Material-atlas device limits. */\nexport interface TextureAtlasLimits { maxTextureArrayLayers: number; maxTextureDimension2D: number; }\n/** Initialization result. */\nexport interface EngineInfo {\n backend: 'webgpu' | 'webgl'; adapterName: string; webgpuFallbackReason?: string; limits: TextureAtlasLimits;\n}\n/** Device and target diagnostics; Per-target GPU bytes exclude shared scene, temporary passes and driver costs. */\nexport interface EngineDiagnostics extends RenderingDiagnostics {\n backend: 'webgpu' | 'webgl' | undefined; adapterName: string;\n width: number; height: number; lastError?: string; webgpuFallbackReason?: string;\n}\ninterface EngineEvents {\n progress: { stage: 'device' | 'bvh' | 'shaders'; progress: number };\n error: Error;\n devicelost: { reason: string; recovering: boolean };\n}\nlet globalGPUDevice: GPUDevice | null = null;\nlet globalGPUAdapterInfo: GPUAdapterInfo | null = null;\nlet globalGPURequest: Promise<GPUDevice> | undefined;\nasync function sharedDevice(gpu: GPU): Promise<GPUDevice> {\n if (globalGPUDevice) return globalGPUDevice;\n if (!globalGPURequest) {\n const request = (async () => {\n const adapter = await gpu.requestAdapter({powerPreference: 'high-performance'}) ?? await gpu.requestAdapter();\n if (!adapter) throw new Error('No WebGPU adapter is available');\n const device = await adapter.requestDevice(getRecommendedDeviceDescriptor(adapter));\n globalGPUAdapterInfo = (adapter as GPUAdapter & {info?: GPUAdapterInfo}).info ?? null;\n globalGPUDevice = device;\n void device.lost.then(() => { if (globalGPUDevice === device) globalGPUDevice = null; });\n return device;\n })();\n globalGPURequest = request;\n void request.finally(() => { if (globalGPURequest === request) globalGPURequest = undefined; }).catch(() => {});\n }\n return globalGPURequest;\n}\n\n/** Shared device, committed scene/camera, CPU preparation and denoiser ownership. */\nexport default class Engine {\n /** Source scene, accepted only by update(). Default undefined. */ scene: Scene | undefined;\n /** Source camera, accepted only by update(). Default undefined. */ camera: Camera | undefined;\n /** Default canvas and display settings. */ readonly display: Display;\n /** Static BLAS builder. Default builtin. */ bvhBuilder: BVHBuilder = 'builtin';\n /** Static BLAS layout. Default bvh2; dynamic geometry uses bvh2. */ bvhLayout: TinyBvhLayout = 'bvh2';\n /** Enable TinyBVH spatial splits. Default false. */ bvhSpatialSplits = false;\n /** Material texture budget in bytes. Default 384 MiB. */ textureAtlasBudgetBytes = DEFAULT_MAX_TEXTURE_ARRAY_BYTES;\n /** Maximum CPU BVH workers. Default auto (hardware concurrency minus one, clamped 1–4). */\n get bvhWorkerCount(): number | 'auto' { return this._bvhWorkerCount; }\n set bvhWorkerCount(count: number | 'auto') { resolveBvhWorkerCount(count); this._bvhWorkerCount = count; }\n private _bvhWorkerCount: number | 'auto' = 'auto';\n private _bvhWorkerPool?: BvhWorkerPool;\n private _bvhPreparationRevision = 0;\n private _bvhPreparation?: Promise<void>;\n private _bvhPreparationTail: Promise<unknown> = Promise.resolve();\n private _tinyBvhUnavailable = false;\n private _bvhWorkerUnavailable = false;\n private _bvhPreparedGeometry = new WeakMap<Mesh, [Geometry, number]>();\n private _lastBvhBuild?: { geometryCount: number; bvhTimeMs: number };\n private _lastBvhSettings = '';\n private _lastBudget = -1;\n private _shaderProgress = '';\n private _events = new Events<EngineEvents>();\n private _pipeline?: RenderPipeline;\n private _webglRenderer?: WebGLRenderer;\n private _gpuDevice?: GPUDevice;\n private _suppliedDevice?: GPUDevice;\n private readonly _ownsDeviceSelection: boolean;\n private _deviceRevision = 0;\n private _lossController?: AbortController;\n private _deviceLossError?: Error;\n private _webglListening = false;\n private _webglLost = false;\n private _recoverWebGL = false;\n private _contextRestore?: {promise: Promise<void>; resolve: () => void; reject: (error: Error) => void};\n private _gpuAdapterInfo?: GPUAdapterInfo;\n private _backendChoice: NonNullable<EngineParams['backend']>;\n private _initPromise?: Promise<EngineInfo>;\n private _info?: EngineInfo;\n private _pipelineInitError?: Error;\n private _webgpuFallbackReason?: string;\n private _reportedErrors = new WeakSet<Error>();\n private _loggedErrorMessages = new Set<string>();\n private _sceneChangeDetector: SceneChangeDetector;\n private _snapshot = new CommittedScene();\n private _sourceScene?: Scene;\n private _committedScene?: Scene;\n private _sourceCamera?: Camera;\n private _committedCamera?: Camera;\n private _cameraFields: unknown[] = [];\n private _sceneRevision = 0;\n private _cameraRevision = 0;\n private _uploadedRevision = -1;\n private _pendingMeshes: 'none' | 'incremental' | 'full' = 'full';\n private _pendingTransforms = new Set<Mesh>();\n private _pendingColors = new Set<InstancedMesh>();\n private _pendingGeometries = new Set<Geometry>();\n private _pendingMaterials = new Set<import('./scene/OpenPBRMaterial.js').default>();\n private _pendingLights = true;\n private _pendingBackground = true;\n private _disposed = false;\n private _readingDepth = false;\n private _renders = new Set<Render>();\n private _targetCounter = 0;\n private _presented?: RenderTarget;\n private _denoisers = new Set<OwnedDenoiser>();\n private _denoiserCache = new Map<string, {references: number; value?: OwnedDenoiser; pending?: Promise<OwnedDenoiser>}>();\n private _denoiserEntries = new WeakMap<OwnedDenoiser, {key: string; references: number; value?: OwnedDenoiser; pending?: Promise<OwnedDenoiser>}>();\n private _weights = new Map<string, Promise<ArrayBuffer>>();\n private _customPrepared = new WeakMap<Denoiser, {device: GPUDevice; width: number; height: number}>();\n private _denoiseTail: Promise<unknown> = Promise.resolve();\n private _lastError: Error | undefined;\n /** Most recent synchronous engine/render failure. Default undefined. */\n get lastError() { return this._lastError; }\n /** @internal */ _setRenderError(error?: Error) { this._lastError = error ?? this._pipelineInitError; }\n\n constructor(params: EngineParams = {}) {\n if (params.device && params.backend === 'webgl') throw new Error('A supplied GPUDevice cannot use the webgl backend.');\n this._suppliedDevice = params.device;\n this._ownsDeviceSelection = !params.device;\n this._backendChoice = params.device ? 'webgpu' : params.backend ?? 'auto';\n this._sceneChangeDetector = new SceneChangeDetector();\n this.display = Display._create(this, params.canvas ?? createCanvas());\n }\n /** Initializes once; concurrent/repeated calls share the result. */\n init(): Promise<EngineInfo> {\n return this._initPromise ??= (async () => {\n if (this._disposed) throw new Error('Engine is disposed.');\n if (this._pipelineInitError && !this._ownsDeviceSelection) throw this._pipelineInitError;\n const revision = this._deviceRevision;\n if (this._contextRestore) await this._contextRestore.promise;\n if (this._disposed) throw new Error('Engine is disposed.');\n await this._initPipeline(this._backendChoice !== 'webgl' && !this._recoverWebGL);\n if (revision !== this._deviceRevision) throw this._deviceLossError;\n if (this._pipelineInitError) throw this._pipelineInitError;\n if (this._disposed) { this._pipeline?.dispose(); throw new Error('Engine is disposed.'); }\n const gl = this._webglRenderer?.gl, limits = this._gpuDevice?.limits;\n this._info = { backend: this._gpuDevice ? 'webgpu' : 'webgl', adapterName: this._adapterName(), webgpuFallbackReason: this._webgpuFallbackReason,\n limits: { maxTextureArrayLayers: limits?.maxTextureArrayLayers ?? gl?.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS), maxTextureDimension2D: limits?.maxTextureDimension2D ?? gl?.getParameter(gl.MAX_TEXTURE_SIZE) } };\n this._upload();\n return this._info;\n })();\n }\n /** Initialization info. Default undefined until init resolves. */ get info() { return this._info; }\n /** Active backend. Default undefined until initialization completes. */ get backend() { return this._info?.backend; }\n /** GPU device. Default undefined before initialization and on WebGL. */ get device() { return this._gpuDevice; }\n /** Subscribes to shared progress/errors/device loss; returns unsubscribe. */\n on<K extends keyof EngineEvents>(event: K, listener: (value: EngineEvents[K]) => void): () => void { return this._events.on(event, listener); }\n\n /** The sole external edit detection/commit point. Returns whether inputs changed. */\n update(): boolean {\n if (this._disposed) throw new Error('Engine is disposed.');\n this._lastError = this._pipelineInitError;\n let changed = false, resetTiming = false;\n const cameraFields = this.camera ? snapshotFields(this.camera) : [];\n if (this.camera !== this._sourceCamera || !snapshotsEqual(cameraFields, this._cameraFields)) {\n this._sourceCamera = this.camera; this._cameraFields = cameraFields;\n this._committedCamera = this.camera ? cameraSnapshot(this.camera) : undefined; this._cameraRevision++; changed = true;\n }\n const bvhSettings = engineSettingsKey(this, 'bvh');\n const force = bvhSettings !== this._lastBvhSettings || textureBudget(this) !== this._lastBudget;\n if (this.scene !== this._sourceScene || force) this._sceneChangeDetector.reset();\n if (this.scene) {\n validateSceneLights(this.scene.lights, error => this._notifyError(error));\n ensureMeshGeometryAttributes(this.scene.meshes);\n const changes = this._sceneChangeDetector.detect(this.scene);\n resetTiming = changes.meshes === 'full' || this.scene !== this._sourceScene || force;\n if (changes.meshes !== 'none' || changes.lights || changes.background || this.scene !== this._sourceScene || force) {\n this._committedScene = this._snapshot.capture(this.scene, changes);\n if (changes.meshes === 'full' || force || this.scene !== this._sourceScene) this._pendingMeshes = 'full';\n else if (changes.meshes === 'incremental' && this._pendingMeshes !== 'full') this._pendingMeshes = 'incremental';\n for (const mesh of changes.transforms) this._pendingTransforms.add(this._snapshot.mirror(mesh));\n for (const mesh of changes.colors) this._pendingColors.add(this._snapshot.mirror(mesh));\n for (const geometry of changes.geometries) this._pendingGeometries.add(this._snapshot.mirror(geometry));\n for (const material of changes.materials) this._pendingMaterials.add(this._snapshot.mirror(material));\n this._pendingLights ||= changes.lights;\n this._pendingBackground ||= changes.background;\n this._sceneRevision++; changed = true;\n }\n this._sceneChangeDetector.commit();\n } else if (this._sourceScene) { this._committedScene = undefined; this._pendingMeshes = 'full'; this._pendingLights = true; this._pendingBackground = true; this._sceneRevision++; changed = true; }\n this._sourceScene = this.scene; this._lastBvhSettings = bvhSettings; this._lastBudget = textureBudget(this);\n if (!this._pipeline) void this.init().catch(() => {});\n if (changed) for (const render of this._renders) render._inputsChanged(resetTiming);\n this._upload();\n return changed;\n }\n private _upload() {\n const pipeline = this._pipeline;\n if (!pipeline || this._disposed || this._bvhPreparation || this._uploadedRevision === this._sceneRevision) return;\n const scene = this._committedScene ?? { meshes: [], lights: [] };\n if (this._needsBVHPreparation(scene.meshes)) {\n const task = this.prepare(scene); this._bvhPreparation = task;\n void task.then(() => { if (this._bvhPreparation === task) this._bvhPreparation = undefined; this._upload(); }, error => { if (this._bvhPreparation === task) this._bvhPreparation = undefined; this._notifyError(error); });\n return;\n }\n const budgetChanged = pipeline.setTextureAtlasBudget(this._lastBudget >= 0 ? this._lastBudget : textureBudget(this));\n if (this._pendingMeshes !== 'none' || budgetChanged) pipeline.setMeshes(scene.meshes, this._pendingMeshes === 'full' || budgetChanged ? undefined : {\n transforms: [...this._pendingTransforms], colors: [...this._pendingColors], geometries: [...this._pendingGeometries], materials: [...this._pendingMaterials]\n });\n if (this._pendingLights) pipeline.setLights(scene.lights);\n if (this._pendingBackground) pipeline.setBackground(scene.background);\n this._pendingMeshes = 'none'; this._pendingLights = false; this._pendingBackground = false;\n this._pendingTransforms.clear(); this._pendingColors.clear(); this._pendingGeometries.clear(); this._pendingMaterials.clear();\n this._uploadedRevision = this._sceneRevision;\n }\n private _bvhConfig(): BvhBuildConfig { return bvhConfig(this); }\n /** Builds static CPU BVHs for this scene without replacing GPU inputs. Options default undefined. */\n prepare(scene: Scene, options: PrepareOptions = {}): Promise<void> {\n const revision = this._bvhPreparationRevision;\n const preparation = this._bvhPreparationTail.then(async () => {\n const isCancelled = () => revision !== this._bvhPreparationRevision || options.signal?.aborted === true;\n if (isCancelled()) return;\n const meshes = scene.meshes;\n const useWorker = canUseBvhWorker() && !this._bvhWorkerUnavailable;\n if (useWorker) {\n const count = workerCount(this);\n if (this._bvhWorkerPool?.size !== count) {\n this._bvhWorkerPool?.dispose();\n this._bvhWorkerPool = new BvhWorkerPool(count);\n }\n }\n const config = this._bvhConfig();\n const result = await prepareStaticBvhs(meshes, {\n config,\n ...config,\n builder: this.bvhBuilder === 'tinybvh' && !this._tinyBvhUnavailable ? 'tinybvh' : 'builtin',\n useWorker, workerPool: this._bvhWorkerPool, isCancelled,\n rebuild: false, onProgress: progress => {\n if (this._bvhPreparation === preparation) this._events.emit('progress', {stage: 'bvh', progress});\n options.onProgress?.(progress);\n }\n });\n if (isCancelled()) return;\n if (result.workerUnavailable && !this._bvhWorkerUnavailable) {\n this._bvhWorkerUnavailable = true;\n this._bvhWorkerPool?.dispose();\n this._bvhWorkerPool = undefined;\n console.warn('BVH preparation failed; falling back to the calling-thread BVH builder.');\n }\n if (result.tinyBvhUnavailable && !this._tinyBvhUnavailable) {\n this._tinyBvhUnavailable = true;\n console.warn('BVH preparation failed; falling back to the built-in BVH builder.');\n }\n result.failedMeshes.forEach(mesh => {\n this._bvhPreparedGeometry.set(mesh, [mesh.geometry, mesh.geometry.version]);\n });\n\n this._lastBvhBuild = { geometryCount: result.geometryCount, bvhTimeMs: result.bvhTimeMs };\n });\n this._bvhPreparationTail = preparation.catch(() => undefined);\n const signal = options.signal;\n if (!signal) return preparation;\n return new Promise<void>((resolve, reject) => {\n const aborted = () => reject(signal.reason ?? new DOMException('BVH preparation aborted', 'AbortError'));\n if (signal.aborted) { aborted(); return; }\n signal.addEventListener('abort', aborted, { once: true });\n preparation.then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted));\n });\n }\n\n private _needsBVHPreparation(meshes: Mesh[]) {\n if (this._bvhPreparation) return true;\n if ((this.bvhBuilder !== 'tinybvh' || this._tinyBvhUnavailable) &&\n (!canUseBvhWorker() || this._bvhWorkerUnavailable)) {\n return meshes.some(mesh => !!getGeometryBvh(getPreparedMeshGeometry(mesh)) && meshNeedsStaticBvh(mesh, this._bvhConfig()));\n }\n return meshes.some((mesh) => {\n const prepared = this._bvhPreparedGeometry.get(mesh);\n const attempted = prepared?.[0] === mesh.geometry &&\n prepared[1] === mesh.geometry.version;\n return !attempted && meshNeedsStaticBvh(mesh, this._bvhConfig());\n });\n }\n\n private async _initPipeline(preferWebGPU: boolean) {\n let gpuCreated = false;\n try {\n\n this._events.emit('progress', {stage: 'device', progress: 0});\n this._pipelineInitError = undefined;\n if (preferWebGPU && (this._suppliedDevice || (typeof navigator !== 'undefined' && navigator.gpu))) {\n try {\n const gpu = typeof navigator !== 'undefined' ? navigator.gpu : undefined;\n const gpuDevice = this._suppliedDevice ?? await sharedDevice(gpu!);\n const gpuAdapterInfo = this._suppliedDevice\n ? (gpuDevice as GPUDevice & {adapterInfo?: GPUAdapterInfo}).adapterInfo : globalGPUAdapterInfo;\n if (this._disposed) return;\n validateDevice(gpuDevice);\n this._gpuAdapterInfo = gpuAdapterInfo ?? undefined;\n this._gpuDevice = gpuDevice;\n this._pipeline = makeWGPURenderTargets(this.display.canvas, gpuDevice, {\n presentationFormat: gpu?.getPreferredCanvasFormat() ?? 'bgra8unorm'\n });\n this._watchDevice(gpuDevice);\n gpuCreated = true;\n } catch (e) {\n if (this._backendChoice === 'webgpu') throw e;\n this._webgpuFallbackReason = e instanceof Error ? e.message : String(e);\n this._gpuDevice = undefined;\n this._gpuAdapterInfo = undefined;\n }\n }\n if (!gpuCreated) {\n if (this._backendChoice === 'webgpu') throw new Error('WebGPU is not available in this environment');\n if (preferWebGPU && !this._webgpuFallbackReason) {\n this._webgpuFallbackReason = 'WebGPU is not available in this environment';\n }\n this._webglRenderer = new WebGLRenderer({\n canvas: this.display.canvas,\n alpha: true,\n depth: true,\n stencil: false,\n antialias: false,\n pixelRatio: 1,\n preserveDrawingBuffer: true,\n // PENDING\n premultipliedAlpha: false,\n parallelShaderCompile: true,\n powerPreference: 'high-performance'\n });\n\n this._pipeline = makeWebGLRenderTargets(this._webglRenderer);\n if (!this._webglListening) {\n this._webglListening = true;\n this.display.canvas.addEventListener('webglcontextlost', this._onContextLost);\n this.display.canvas.addEventListener('webglcontextrestored', this._onContextRestored);\n }\n this._recoverWebGL = false;\n }\n\n\n } catch (error) {\n this._pipelineInitError = error instanceof Error ? error : new Error(String(error));\n this._lastError = this._pipelineInitError;\n this._notifyError(this._pipelineInitError);\n } finally {\n\n this._events.emit('progress', {stage: 'device', progress: 1});\n }\n }\n\n private _onContextLost = (event: Event) => {\n event.preventDefault();\n if (this._disposed || this._webglLost) return;\n this._webglLost = true; this._recoverWebGL = true;\n let resolve!: () => void, reject!: (error: Error) => void;\n const promise = new Promise<void>((done, fail) => {resolve = done; reject = fail;});\n void promise.catch(() => {});\n this._contextRestore = {promise, resolve, reject};\n const error = new Error(`WebGL context lost: ${(event as WebGLContextEvent).statusMessage || 'context is unavailable'}`);\n this._invalidateDevice(error, true);\n this._events.emit('devicelost', {reason: 'webglcontextlost', recovering: true});\n };\n private _onContextRestored = () => {\n if (this._disposed || !this._webglLost) return;\n this._webglLost = false;\n const restore = this._contextRestore; this._contextRestore = undefined; restore?.resolve();\n };\n private _watchDevice(device: GPUDevice) {\n void device.lost.then(info => {\n if (this._disposed || this._gpuDevice !== device) return;\n if (globalGPUDevice === device) globalGPUDevice = null;\n const recovering = this._ownsDeviceSelection;\n const error = new Error(`WebGPU device lost (${info.reason}): ${info.message || 'device is unavailable'}`);\n this._invalidateDevice(error, recovering);\n this._events.emit('devicelost', {reason: info.reason, recovering});\n if (!recovering) this._notifyError(error);\n });\n }\n private _invalidateDevice(error: Error, recovering: boolean) {\n this._deviceLossError = error; this._deviceRevision++;\n this._lossController?.abort(error); this._lossController = undefined;\n for (const render of this._renders) render._deviceLost(recovering);\n this._pipeline?.dispose(); this._pipeline = undefined;\n this._webglRenderer?.dispose(); this._webglRenderer = undefined;\n this._gpuDevice = undefined; this._gpuAdapterInfo = undefined;\n this._info = undefined; this._initPromise = undefined;\n this._pipelineInitError = recovering ? undefined : error; this._lastError = error;\n this._presented = undefined; this._shaderProgress = '';\n this._uploadedRevision = -1; this._pendingMeshes = 'full'; this._pendingLights = true; this._pendingBackground = true;\n this._sceneRevision++;\n this._customPrepared = new WeakMap();\n for (const filter of [...this._denoisers]) {\n const entry = this._denoiserEntries.get(filter); if (entry) entry.references = 1;\n this._releaseDenoiser(filter);\n }\n this._denoiserCache.clear();\n }\n /** Replaces a caller-owned device after validation. Only available on engines\n * constructed with device; the next update/refine uploads the committed scene.\n */\n async setDevice(device: GPUDevice): Promise<void> {\n if (this._disposed) throw new Error('Engine is disposed.');\n if (this._ownsDeviceSelection) throw new Error('setDevice requires an engine constructed with device.');\n try { validateDevice(device); }\n catch (error) {this._lastError = this._notifyError(error); throw error;}\n if (this._gpuDevice === device && !this._pipelineInitError) return;\n this._invalidateDevice(new Error('WebGPU device replaced during converge.'), true);\n this._suppliedDevice = device;\n }\n /** @internal Device loss rejects pending waits without relying on driver completion. */\n _awaitDevice<T>(work: Promise<T>): Promise<T> {\n const signal = (this._lossController ??= new AbortController()).signal;\n return new Promise((resolve, reject) => {\n const lost = () => reject(signal.reason);\n signal.addEventListener('abort', lost, {once: true});\n work.then(resolve, reject).finally(() => signal.removeEventListener('abort', lost));\n });\n }\n /** @internal */ get _deviceGeneration() { return this._deviceRevision; }\n /** @internal */ get _lostError() { return this._deviceLossError; }\n\n private _adapterName() {\n if (this._gpuAdapterInfo) return this._gpuAdapterInfo.description || this._gpuAdapterInfo.vendor || 'WebGPU';\n const gl = this._webglRenderer?.gl, extension = gl?.getExtension('WEBGL_debug_renderer_info');\n return extension && gl ? gl.getParameter(extension.UNMASKED_RENDERER_WEBGL) : this._webglRenderer ? 'WebGL 2' : this._gpuDevice ? 'WebGPU' : '';\n }\n /** @internal */ _reportShaderProgress() {\n const compilation = this._pipeline?.getDiagnostics().shaderCompilation;\n if (!compilation) return;\n const key = `${compilation.status}/${compilation.completedPipelineCount}/${compilation.pipelineCount}`;\n if (key === this._shaderProgress) return;\n this._shaderProgress = key;\n this._events.emit('progress', {stage: 'shaders', progress: compilation.pipelineCount ? compilation.completedPipelineCount / compilation.pipelineCount : 1});\n }\n /** Current shared preparation and resident target statistics. Default undefined before any work. */\n getDiagnostics(): EngineDiagnostics | undefined {\n if (!this._pipeline && !this._lastBvhBuild) return;\n const values = this._pipeline?.getDiagnostics();\n return { ...values, bvh: {...values?.bvh, lastBuild: this._lastBvhBuild}, backend: this.backend, adapterName: this._adapterName(), width: this.display.canvas.width, height: this.display.canvas.height,\n lastError: this.lastError?.message, webgpuFallbackReason: this._webgpuFallbackReason,\n presentedTarget: this._presented?.label, presentedComplete: this._presented?.presentationComplete ?? false };\n }\n /** Queries a 7×7 depth grid using the committed engine camera. Default undefined until GPU data is ready. */\n async readDepthSamples(area: DepthSampleArea): Promise<Float32Array | undefined> {\n packDepthSampleArea(area, 1);\n if (!this._ready || !this._committedCamera || this._readingDepth) return;\n this._readingDepth = true;\n try {\n const camera = cameraSnapshot(this._committedCamera);\n camera.aspect ??= this.display.canvas.width / this.display.canvas.height;\n const result = await this._pipeline!.readDepthSamples(camera, area);\n return this._disposed ? undefined : result;\n }\n finally { this._readingDepth = false; }\n }\n /** Releases all renders, shared resources, CPU workers and owned denoisers. */\n dispose() {\n if (this._disposed) return;\n this._disposed = true; this._bvhPreparationRevision++;\n this._lossController?.abort(new Error('Engine is disposed.')); this._lossController = undefined;\n this._contextRestore?.reject(new Error('Engine is disposed.')); this._contextRestore = undefined;\n if (this._webglListening) {\n this.display.canvas.removeEventListener('webglcontextlost', this._onContextLost);\n this.display.canvas.removeEventListener('webglcontextrestored', this._onContextRestored);\n }\n for (const render of [...this._renders]) render.dispose();\n this._pipeline?.dispose(); this._pipeline = undefined; this._webglRenderer?.dispose(); this._bvhWorkerPool?.dispose();\n for (const denoiser of [...this._denoisers]) { const entry = this._denoiserEntries.get(denoiser); if (entry) entry.references = 1; this._releaseDenoiser(denoiser); }\n this._denoiserCache.clear();\n this._weights.clear(); this._events.clear();\n }\n /** @internal */ get _initializationError() { return this._pipelineInitError; }\n /** @internal */ get _ready() { return !!this._pipeline && this._uploadedRevision === this._sceneRevision && !!this._committedScene && !!this._committedCamera && !this._disposed; }\n /** @internal */ get _inputs() { return {scene: this._sceneRevision, camera: this._cameraRevision, value: this._committedCamera}; }\n /** @internal */ _register(render: Render) { if (this._disposed) throw new Error('Engine is disposed.'); this._renders.add(render); }\n /** @internal */ _unregister(render: Render) { this._renders.delete(render); }\n /** @internal */ _createTarget() { return this._pipeline?.createTarget(`render-${++this._targetCounter}`); }\n /** @internal */ _releaseTarget(target: RenderTarget) { if (this._presented === target) this._presented = undefined; this._pipeline?.releaseTarget(target); }\n /** @internal */ _present(target: RenderTarget) { target.activate(); target.present(); this._presented = target; }\n /** @internal */ _notifyError(value: unknown): Error {\n const error = value instanceof Error ? value : new Error(String(value));\n if (!this._loggedErrorMessages.has(error.message)) { this._loggedErrorMessages.add(error.message); console.error(`Path tracing failed: ${error.message}`, error); }\n if (!this._reportedErrors.has(error)) { this._reportedErrors.add(error); this._events.emit('error', error); }\n return error;\n }\n /** @internal */ _getWeights(url: string, load: () => Promise<ArrayBuffer>) {\n let pending = this._weights.get(url);\n if (!pending) { pending = load(); this._weights.set(url, pending); void pending.catch(() => { if (this._weights.get(url) === pending) this._weights.delete(url); }); }\n return pending;\n }\n /** @internal */ _retainDenoiser<T extends OwnedDenoiser>(key: string, create: () => T): T {\n let entry = this._denoiserCache.get(key);\n if (!entry?.value) {\n const value = this._ownDenoiser(create());\n const next = {key, references: 0, value};\n this._denoiserCache.set(key, next); this._denoiserEntries.set(value, next); entry = next;\n }\n entry.references++; return entry.value as T;\n }\n /** @internal */ async _acquireDenoiser(key: string, create: () => Promise<Extract<OwnedDenoiser, {kind: 'oidn'}>>): Promise<Extract<OwnedDenoiser, {kind: 'oidn'}>> {\n let entry = this._denoiserCache.get(key);\n if (!entry) {\n const next: {key: string; references: number; value?: OwnedDenoiser; pending?: Promise<OwnedDenoiser>} = {key, references: 0};\n const revision = this._deviceRevision;\n next.pending = create().then(filter => {\n if (revision !== this._deviceRevision) { this._disposeDenoiser(filter); throw this._deviceLossError; }\n next.value = this._ownDenoiser(filter); this._denoiserEntries.set(filter, next); return filter; });\n this._denoiserCache.set(key, next); entry = next;\n }\n entry.references++;\n try { return (entry.value ?? await entry.pending!) as Extract<OwnedDenoiser, {kind: 'oidn'}>; }\n catch (error) { entry.references--; if (this._denoiserCache.get(key) === entry) this._denoiserCache.delete(key); throw error; }\n }\n /** @internal */ _ownDenoiser<T extends OwnedDenoiser>(denoiser: T): T {\n if (this._disposed) { this._disposeDenoiser(denoiser); throw new Error('Engine is disposed.'); }\n this._denoisers.add(denoiser); return denoiser;\n }\n /** @internal */ _releaseDenoiser(denoiser: OwnedDenoiser) {\n const entry = this._denoiserEntries.get(denoiser);\n if (entry && --entry.references > 0) return;\n if (entry && this._denoiserCache.get(entry.key) === entry) this._denoiserCache.delete(entry.key);\n this._denoiserEntries.delete(denoiser);\n if (!this._denoisers.delete(denoiser)) return;\n this._disposeDenoiser(denoiser);\n }\n private _disposeDenoiser(denoiser: OwnedDenoiser) {\n if (denoiser.kind === 'oidn') { denoiser.denoiser.auxiliaryDenoisers?.albedo.dispose(); denoiser.denoiser.auxiliaryDenoisers?.normal.dispose(); }\n denoiser.denoiser.dispose();\n }\n /** @internal Called only while holding the shared inference lease. */\n async _prepareCustomDenoiser(denoiser: Denoiser, width: number, height: number) {\n const device = this.device;\n if (!device) throw new Error('Custom denoising requires WebGPU.');\n const previous = this._customPrepared.get(denoiser);\n if (previous?.device === device && previous.width === width && previous.height === height) return;\n await denoiser.prepare?.({device, width, height});\n this._customPrepared.set(denoiser, {device, width, height});\n }\n /** @internal */ _enqueueDenoise<T>(work: () => Promise<T>): Promise<T> {\n const task = this._denoiseTail.then(async () => {\n const device = this._gpuDevice, generation = this._deviceRevision;\n try { return await work(); }\n finally {\n // Cancelling tiled OIDN stops future tiles, not the commands already\n // submitted. Keep the shared scratch lease until those commands finish\n // so rapid edits cannot pile up inference or resize its inputs in flight.\n // A lost/disposed device must release the lease without waiting for a\n // queue that may never complete.\n if (device && device === this._gpuDevice && generation === this._deviceRevision && !this._disposed) {\n await this._awaitDevice(device.queue.onSubmittedWorkDone()).catch(() => {});\n }\n }\n });\n this._denoiseTail = task.catch(() => {}); return task;\n }\n}\n"]}
package/lib/main.d.ts CHANGED
@@ -27,7 +27,7 @@ export type { OpenPBRMaterialParams } from './scene/OpenPBRMaterial.js';
27
27
  export { default as OpenPBRMaterial } from './scene/OpenPBRMaterial.js';
28
28
  export type { MaterialAlphaMode, UVProjection } from './scene/OpenPBRMaterial.js';
29
29
  export { default as Texture } from './scene/Texture.js';
30
- export type { TextureDataSource } from './scene/Texture.js';
30
+ export type { TextureDataSource, TextureWrapMode, TextureColorSpace } from './scene/Texture.js';
31
31
  export type { ColorRGB, ColorRGBA, Vec2, Vec3, Mat4 } from './types.js';
32
32
  export { default as AmbientLight } from './scene/AmbientLight.js';
33
33
  export { default as DirectionalLight } from './scene/DirectionalLight.js';
package/lib/main.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD;;;;;;;;;GASG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAYvC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAW1D,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAEpE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EACL,OAAO,IAAI,QAAQ,EACnB,SAAS,IAAI,iBAAiB,EAC/B,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAKxE,OAAO,EAAE,OAAO,IAAI,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAIxD,SAAS;AACT,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,EACL,OAAO,IAAI,UAAU,EACrB,aAAa,EACb,eAAe,EAChB,MAAM,uBAAuB,CAAC;AAE/B,2BAA2B;AAC3B,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAOjF,mBAAmB;AACnB,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,mBAAmB,EACnB,oBAAoB,EACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAO1D,oCAAoC;AACpC,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAEhD,OAAO,EAAE,OAAO,IAAI,OAAO,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAGhD,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAGxD,OAAO,EAAC,8BAA8B,EAAC,MAAM,kCAAkC,CAAC","sourcesContent":["/// <reference types=\"@webgpu/types\" preserve=\"true\" />\n\n/**\n * MuTracer: a physically based WebGPU path tracer with a\n * WebGL 2 fallback.\n *\n * Build a {@link Scene} from {@link Mesh}es and lights (or convert a Three.js\n * scene with {@link fromTHREEScene}), then call {@link Engine.update} and {@link Render.refine} once\n * per animation frame.\n *\n * @packageDocumentation\n */\nexport { VERSION } from './version.js';\n\nexport type {\n AlphaBlendStrategy,\n ShaderCompilationDiagnostics,\n ToneMapping\n} from './renderer/RenderingPipeline.js';\nexport type {\n OfflineAdaptiveSamplingOptions,\n OfflineVarianceHistory\n} from './renderer/OfflineAdaptiveSampling.js';\nexport type { OIDNModel, OIDNEngine, OIDNPrecision, OIDNHDRTransfer, OIDNDynamicTileOptions, OIDNDynamicTileSetting, OIDNAuxiliaryModelUrls } from './oidn.js';\nexport { DEFAULT_JNLM_OPTIONS } from './renderer/jnlm.js';\nexport type { JNLMOptions } from './renderer/jnlm.js';\n\n// Scene description\nexport type {\n AnalyticLight,\n GroundedSkyboxBackground,\n Scene,\n SceneBackground,\n SceneLight\n} from './scene/Scene.js';\nexport { default as Camera } from './scene/Camera.js';\nexport { default as Mesh } from './scene/Mesh.js';\nexport { default as InstancedMesh } from './scene/InstancedMesh.js';\nexport type { InstancedMeshOptions } from './scene/InstancedMesh.js';\nexport { default as SceneNode } from './scene/SceneNode.js';\nexport {\n default as Geometry,\n Attribute as GeometryAttribute\n} from './scene/Geometry.js';\nexport type { GeometryInit } from './scene/Geometry.js';\nexport type { OpenPBRMaterialParams } from './scene/OpenPBRMaterial.js';\nexport { default as OpenPBRMaterial } from './scene/OpenPBRMaterial.js';\nexport type {\n MaterialAlphaMode,\n UVProjection\n} from './scene/OpenPBRMaterial.js';\nexport { default as Texture } from './scene/Texture.js';\nexport type { TextureDataSource } from './scene/Texture.js';\nexport type { ColorRGB, ColorRGBA, Vec2, Vec3, Mat4 } from './types.js';\n\n// Lights\nexport { default as AmbientLight } from './scene/AmbientLight.js';\nexport { default as DirectionalLight } from './scene/DirectionalLight.js';\nexport { default as RectLight } from './scene/RectLight.js';\nexport { default as SphereLight } from './scene/SphereLight.js';\nexport { default as SpotLight } from './scene/SpotLight.js';\nexport { default as EnvironmentLight } from './scene/EnvironmentLight.js';\nexport {\n default as IESProfile,\n IESParseError,\n parseIESProfile\n} from './scene/IESProfile.js';\n\n// Loaders and integrations\nexport { loadRGBE, parseRGBE } from './util/loadRGBE.js';\nexport { fromTHREECamera, fromTHREEScene, THREESync } from './util/fromTHREE.js';\nexport type {\n FromTHREESceneOptions,\n THREESyncOptions, THREEControls,\n FromTHREECameraOptions\n} from './util/fromTHREE.js';\n\n// Geometry helpers\nexport {\n createCubeGeometry,\n createCurvePlaneGeometry,\n createPlaneGeometry,\n createSphereGeometry\n} from './util/commonGeometry.js';\nexport {\n generateVertexNormals,\n generateVertexTangents\n} from './util/geometry.js';\nexport { computeMeshesBoundingBox } from './util/mesh.js';\n\n// BVH\nexport type { TinyBvhLayout } from './tinybvh/TinyBvhBuilder.js';\n\nexport type { SamplingPattern } from './renderer/sampling.js';\n\n// Independent rendering mechanisms.\nexport { default as Engine } from './Engine.js';\nexport type { EngineParams, EngineInfo, EngineDiagnostics, PrepareOptions, BVHBuilder, DepthSampleArea, TextureAtlasLimits } from './Engine.js';\nexport { default as Display } from './Display.js';\nexport type { BlobOptions, DisplayChannel, DisplaySettings, PostProcess, PostProcessContext } from './Display.js';\nexport { default as Render } from './Render.js';\nexport type { RenderOptions, RenderSettings, ConvergeOptions, ConvergeResult, DenoiserOptions, Denoiser, DenoiseInput, CustomDenoiserOptions, DenoiseSchedule, JNLMDenoiserOptions, OIDNDenoiserOptions, RenderStatus, SampleEvent } from './Render.js';\n\nexport { default as Sync } from './Sync.js';\nexport { default as RenderLoop } from './RenderLoop.js';\nexport type { RenderLoopOptions, RenderLoopStatus } from './RenderLoop.js';\n\nexport {getRecommendedDeviceDescriptor} from './renderer/deviceRequirements.js';\n"]}
1
+ {"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD;;;;;;;;;GASG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,cA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,mBAAmB,EACnB,oBAAoB,EACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAO1D,oCAAoC;AACpC,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAEhD,OAAO,EAAE,OAAO,IAAI,OAAO,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,aAAa,CAAC;AAGhD,OAAO,EAAE,OAAO,IAAI,IAAI,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAGxD,OAAO,EAAC,8BAA8B,EAAC,MAAM,kCAAkC,CAAC","sourcesContent":["/// <reference types=\"@webgpu/types\" preserve=\"true\" />\n\n/**\n * MuTracer: a physically based WebGPU path tracer with a\n * WebGL 2 fallback.\n *\n * Build a {@link Scene} from {@link Mesh}es and lights (or convert a Three.js\n * scene with {@link fromTHREEScene}), then call {@link Engine.update} and {@link Render.refine} once\n * per animation frame.\n *\n * @packageDocumentation\n */\nexport { VERSION } from './version.js';\n\nexport type {\n AlphaBlendStrategy,\n ShaderCompilationDiagnostics,\n ToneMapping\n} from './renderer/RenderingPipeline.js';\nexport type {\n OfflineAdaptiveSamplingOptions,\n OfflineVarianceHistory\n} from './renderer/OfflineAdaptiveSampling.js';\nexport type { OIDNModel, OIDNEngine, OIDNPrecision, OIDNHDRTransfer, OIDNDynamicTileOptions, OIDNDynamicTileSetting, OIDNAuxiliaryModelUrls } from './oidn.js';\nexport { DEFAULT_JNLM_OPTIONS } from './renderer/jnlm.js';\nexport type { JNLMOptions } from './renderer/jnlm.js';\n\n// Scene description\nexport type {\n AnalyticLight,\n GroundedSkyboxBackground,\n Scene,\n SceneBackground,\n SceneLight\n} from './scene/Scene.js';\nexport { default as Camera } from './scene/Camera.js';\nexport { default as Mesh } from './scene/Mesh.js';\nexport { default as InstancedMesh } from './scene/InstancedMesh.js';\nexport type { InstancedMeshOptions } from './scene/InstancedMesh.js';\nexport { default as SceneNode } from './scene/SceneNode.js';\nexport {\n default as Geometry,\n Attribute as GeometryAttribute\n} from './scene/Geometry.js';\nexport type { GeometryInit } from './scene/Geometry.js';\nexport type { OpenPBRMaterialParams } from './scene/OpenPBRMaterial.js';\nexport { default as OpenPBRMaterial } from './scene/OpenPBRMaterial.js';\nexport type {\n MaterialAlphaMode,\n UVProjection\n} from './scene/OpenPBRMaterial.js';\nexport { default as Texture } from './scene/Texture.js';\nexport type { TextureDataSource, TextureWrapMode, TextureColorSpace } from './scene/Texture.js';\nexport type { ColorRGB, ColorRGBA, Vec2, Vec3, Mat4 } from './types.js';\n\n// Lights\nexport { default as AmbientLight } from './scene/AmbientLight.js';\nexport { default as DirectionalLight } from './scene/DirectionalLight.js';\nexport { default as RectLight } from './scene/RectLight.js';\nexport { default as SphereLight } from './scene/SphereLight.js';\nexport { default as SpotLight } from './scene/SpotLight.js';\nexport { default as EnvironmentLight } from './scene/EnvironmentLight.js';\nexport {\n default as IESProfile,\n IESParseError,\n parseIESProfile\n} from './scene/IESProfile.js';\n\n// Loaders and integrations\nexport { loadRGBE, parseRGBE } from './util/loadRGBE.js';\nexport { fromTHREECamera, fromTHREEScene, THREESync } from './util/fromTHREE.js';\nexport type {\n FromTHREESceneOptions,\n THREESyncOptions, THREEControls,\n FromTHREECameraOptions\n} from './util/fromTHREE.js';\n\n// Geometry helpers\nexport {\n createCubeGeometry,\n createCurvePlaneGeometry,\n createPlaneGeometry,\n createSphereGeometry\n} from './util/commonGeometry.js';\nexport {\n generateVertexNormals,\n generateVertexTangents\n} from './util/geometry.js';\nexport { computeMeshesBoundingBox } from './util/mesh.js';\n\n// BVH\nexport type { TinyBvhLayout } from './tinybvh/TinyBvhBuilder.js';\n\nexport type { SamplingPattern } from './renderer/sampling.js';\n\n// Independent rendering mechanisms.\nexport { default as Engine } from './Engine.js';\nexport type { EngineParams, EngineInfo, EngineDiagnostics, PrepareOptions, BVHBuilder, DepthSampleArea, TextureAtlasLimits } from './Engine.js';\nexport { default as Display } from './Display.js';\nexport type { BlobOptions, DisplayChannel, DisplaySettings, PostProcess, PostProcessContext } from './Display.js';\nexport { default as Render } from './Render.js';\nexport type { RenderOptions, RenderSettings, ConvergeOptions, ConvergeResult, DenoiserOptions, Denoiser, DenoiseInput, CustomDenoiserOptions, DenoiseSchedule, JNLMDenoiserOptions, OIDNDenoiserOptions, RenderStatus, SampleEvent } from './Render.js';\n\nexport { default as Sync } from './Sync.js';\nexport { default as RenderLoop } from './RenderLoop.js';\nexport type { RenderLoopOptions, RenderLoopStatus } from './RenderLoop.js';\n\nexport {getRecommendedDeviceDescriptor} from './renderer/deviceRequirements.js';\n"]}
package/lib/oidn.d.ts CHANGED
@@ -40,6 +40,6 @@ export declare const DEFAULT_OIDN_WEIGHTS_PACKAGE_BASE_URL = "https://cdn.jsdeli
40
40
  * Fallback for bundled standard/small weights when application assets fail.
41
41
  * Defaults to jsDelivr's `@meimu/mutracer@VERSION/oidn/weights/` directory.
42
42
  */
43
- export declare const DEFAULT_OIDN_WEIGHTS_BASE_URL = "https://cdn.jsdelivr.net/npm/@meimu/mutracer@0.1.2/oidn/weights/";
43
+ export declare const DEFAULT_OIDN_WEIGHTS_BASE_URL = "https://cdn.jsdelivr.net/npm/@meimu/mutracer@0.1.4/oidn/weights/";
44
44
  export declare function resolveOIDNModelUrl(model: OIDNModel, weightsBaseUrl?: string | URL): string;
45
45
  export declare function resolveOIDNAuxiliaryModelUrls(weightsBaseUrl?: string | URL): OIDNAuxiliaryModelUrls;
@@ -1,2 +1,2 @@
1
- export declare const standardWeightsUrl = "https://cdn.jsdelivr.net/npm/@meimu/mutracer@0.1.2/oidn/weights/rt_hdr_alb_nrm.tza";
2
- export declare const smallWeightsUrl = "https://cdn.jsdelivr.net/npm/@meimu/mutracer@0.1.2/oidn/weights/rt_hdr_alb_nrm_small.tza";
1
+ export declare const standardWeightsUrl = "https://cdn.jsdelivr.net/npm/@meimu/mutracer@0.1.4/oidn/weights/rt_hdr_alb_nrm.tza";
2
+ export declare const smallWeightsUrl = "https://cdn.jsdelivr.net/npm/@meimu/mutracer@0.1.4/oidn/weights/rt_hdr_alb_nrm_small.tza";
@@ -50,6 +50,7 @@ export interface BufferData extends Record<MaterialTextureIndex, number[]> {
50
50
  type: (typeof ShadowCatcherMaterial | typeof UnlitMaterial | 0)[];
51
51
  mapInfo: number[];
52
52
  mapTransform: number[];
53
+ mapWrap: number[];
53
54
  mapUvChannel: number[];
54
55
  mapColorLinear: number[];
55
56
  mediumType: number[];
@@ -13,7 +13,7 @@ import { materialEmission } from './materialEmission.js';
13
13
  import { Texture2DArray as WebGLTexture2DArray, constants, Texture2D } from './webgl.js';
14
14
  import { materialAlphaModeConstants, resolveMaterialAlphaMode } from '../scene/OpenPBRMaterial.js';
15
15
  import { mergeTexturesFromMaterials } from './texturesFromMaterials.js';
16
- import { isTextureDataSource } from '../scene/Texture.js';
16
+ import { isTextureDataSource, textureWrapIndex } from '../scene/Texture.js';
17
17
  import { commonNearestFloatProps, setDataTexture } from './dataTextureUtil.js';
18
18
  export const DEFAULT_MAX_TEXTURE_ARRAY_BYTES = 384 * 1024 * 1024;
19
19
  export function materialUsesMedium(material) {
@@ -169,6 +169,7 @@ function makeTextureArray(textures, sRGB = false, options = {}) {
169
169
  mapTransform: [],
170
170
  mapUvChannel: [],
171
171
  mapColorLinear: [],
172
+ mapWrap: [],
172
173
  stats: {
173
174
  estimatedBytes: 0,
174
175
  height: 1,
@@ -194,10 +195,12 @@ function makeTextureArray(textures, sRGB = false, options = {}) {
194
195
  const dataBacked = textures.some((texture) => isTextureDataSource(texture.image));
195
196
  const mapColorLinear = textures.map(texture => {
196
197
  const image = texture.image;
197
- return Number(isTextureDataSource(image) &&
198
+ return Number(texture.colorSpace ? texture.colorSpace === 'linear' : isTextureDataSource(image) &&
198
199
  !(image.data instanceof Uint8Array) && !(image.data instanceof Uint8ClampedArray));
199
200
  });
200
- const floatStorage = mapColorLinear.some(Boolean);
201
+ // Storage precision depends on the pixels, independently of their transfer function.
202
+ const floatStorage = textures.some(({ image }) => isTextureDataSource(image) &&
203
+ !(image.data instanceof Uint8Array) && !(image.data instanceof Uint8ClampedArray));
201
204
  const bytesPerPixel = floatStorage ? 8 : 4;
202
205
  const maxTextureArrayLayers = options.maxTextureArrayLayers ?? Infinity;
203
206
  const maxTextureDimension2D = options.maxTextureDimension2D ?? Infinity;
@@ -288,6 +291,7 @@ function makeTextureArray(textures, sRGB = false, options = {}) {
288
291
  texture.uvOffset[1]
289
292
  ]),
290
293
  mapUvChannel: textures.map((texture) => texture.uvChannel),
294
+ mapWrap: textures.flatMap(texture => [textureWrapIndex(texture.wrapS), textureWrapIndex(texture.wrapT)]),
291
295
  mapColorLinear,
292
296
  stats: {
293
297
  estimatedBytes: atlasWidth * atlasHeight * pages.length * bytesPerPixel,
@@ -416,11 +420,12 @@ class MaterialTable {
416
420
  lightTexturesIndices.push(-1);
417
421
  }
418
422
  }
419
- const { mapInfo, mapTransform, mapUvChannel, mapColorLinear, stats, texture } = makeTextureArray(allTextures, false, options);
423
+ const { mapInfo, mapTransform, mapUvChannel, mapColorLinear, mapWrap, stats, texture } = makeTextureArray(allTextures, false, options);
420
424
  this.texture = texture;
421
425
  this.textureAtlasStats = stats;
422
426
  bufferData.mapInfo = mapInfo;
423
427
  bufferData.mapTransform = mapTransform;
428
+ bufferData.mapWrap = mapWrap;
424
429
  bufferData.mapUvChannel = mapUvChannel;
425
430
  bufferData.mapColorLinear = mapColorLinear;
426
431
  for (const slot of MATERIAL_TEXTURE_SLOTS) {
@@ -535,6 +540,7 @@ class MaterialTable {
535
540
  pass.setUniform('map', this.texture || null);
536
541
  pass.setUniform('mapInfo', this.bufferData.mapInfo);
537
542
  pass.setUniform('mapTransform', this.bufferData.mapTransform);
543
+ pass.setUniform('mapWrap', this.bufferData.mapWrap);
538
544
  pass.setUniform('mapUvChannel', this.bufferData.mapUvChannel);
539
545
  pass.setUniform('mapColorLinear', this.bufferData.mapColorLinear);
540
546
  pass.setUniforms({