@drawcall/lod 0.3.0 → 0.4.0

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 (204) hide show
  1. package/README.md +5 -8
  2. package/dist/bake.d.ts +16 -2
  3. package/dist/bake.js +92 -4
  4. package/dist/bake.js.map +1 -1
  5. package/dist/baked/index.d.ts +2 -2
  6. package/dist/baked/index.js +2 -2
  7. package/dist/baked/interior/faces.js +4 -2
  8. package/dist/baked/interior/faces.js.map +1 -1
  9. package/dist/baked/interior/material.js +1 -1
  10. package/dist/baked/interior/material.js.map +1 -1
  11. package/dist/baked/interior/rooms.d.ts +1 -1
  12. package/dist/baked/interior/rooms.js +1 -1
  13. package/dist/dispose.d.ts +3 -3
  14. package/dist/dispose.js +6 -6
  15. package/dist/dispose.js.map +1 -1
  16. package/dist/foliage.d.ts +32 -0
  17. package/dist/foliage.js +137 -0
  18. package/dist/foliage.js.map +1 -0
  19. package/dist/impostor/bake/index.d.ts +3 -3
  20. package/dist/impostor/bake/index.js +12 -3
  21. package/dist/impostor/bake/index.js.map +1 -1
  22. package/dist/impostor/bake/source.d.ts +2 -1
  23. package/dist/impostor/bake/source.js +2 -2
  24. package/dist/impostor/bake/source.js.map +1 -1
  25. package/dist/impostor/impostor.d.ts +1 -1
  26. package/dist/impostor/impostor.js +1 -1
  27. package/dist/impostor/ktx2/encode.js +5 -2
  28. package/dist/impostor/ktx2/encode.js.map +1 -1
  29. package/dist/impostor/ktx2/uastc.js +3 -2
  30. package/dist/impostor/ktx2/uastc.js.map +1 -1
  31. package/dist/impostor/ktx2/worker.js +0 -2
  32. package/dist/impostor/ktx2/worker.js.map +1 -1
  33. package/dist/impostor/mesh/card.d.ts +1 -1
  34. package/dist/impostor/mesh/index.d.ts +2 -2
  35. package/dist/impostor/mesh/index.js +3 -3
  36. package/dist/impostor/mesh/index.js.map +1 -1
  37. package/dist/index.d.ts +3 -6
  38. package/dist/index.js +3 -6
  39. package/dist/index.js.map +1 -1
  40. package/dist/instanced/camera.d.ts +13 -25
  41. package/dist/instanced/camera.js +17 -42
  42. package/dist/instanced/camera.js.map +1 -1
  43. package/dist/instanced/clusters.d.ts +54 -0
  44. package/dist/instanced/clusters.js +151 -0
  45. package/dist/instanced/clusters.js.map +1 -0
  46. package/dist/instanced/cull.d.ts +3 -3
  47. package/dist/instanced/cull.js +2 -2
  48. package/dist/instanced/cull.js.map +1 -1
  49. package/dist/instanced/instances.d.ts +39 -0
  50. package/dist/instanced/instances.js +104 -0
  51. package/dist/instanced/instances.js.map +1 -0
  52. package/dist/instanced/key.d.ts +1 -1
  53. package/dist/instanced/key.js +1 -1
  54. package/dist/instanced/key.js.map +1 -1
  55. package/dist/instanced/levels.d.ts +9 -9
  56. package/dist/instanced/levels.js +7 -6
  57. package/dist/instanced/levels.js.map +1 -1
  58. package/dist/instanced/lists.d.ts +26 -39
  59. package/dist/instanced/lists.js +42 -61
  60. package/dist/instanced/lists.js.map +1 -1
  61. package/dist/instanced/measure.d.ts +2 -2
  62. package/dist/instanced/measure.js +2 -2
  63. package/dist/instanced/meshes.d.ts +11 -9
  64. package/dist/instanced/meshes.js +26 -16
  65. package/dist/instanced/meshes.js.map +1 -1
  66. package/dist/instanced/mirror.d.ts +16 -12
  67. package/dist/instanced/mirror.js +51 -12
  68. package/dist/instanced/mirror.js.map +1 -1
  69. package/dist/instanced/raycast.d.ts +6 -9
  70. package/dist/instanced/raycast.js +15 -18
  71. package/dist/instanced/raycast.js.map +1 -1
  72. package/dist/instanced/rows.d.ts +15 -73
  73. package/dist/instanced/rows.js +16 -189
  74. package/dist/instanced/rows.js.map +1 -1
  75. package/dist/instanced/shape.d.ts +3 -1
  76. package/dist/instanced/shape.js +6 -3
  77. package/dist/instanced/shape.js.map +1 -1
  78. package/dist/instanced/sort.d.ts +32 -34
  79. package/dist/instanced/sort.js +162 -132
  80. package/dist/instanced/sort.js.map +1 -1
  81. package/dist/instanced/update.d.ts +16 -12
  82. package/dist/instanced/update.js +57 -84
  83. package/dist/instanced/update.js.map +1 -1
  84. package/dist/levels/compile/index.d.ts +4 -2
  85. package/dist/levels/compile/index.js +10 -2
  86. package/dist/levels/compile/index.js.map +1 -1
  87. package/dist/levels/compile/pipelines.d.ts +1 -1
  88. package/dist/levels/compile/pipelines.js +1 -6
  89. package/dist/levels/compile/pipelines.js.map +1 -1
  90. package/dist/levels/draw.d.ts +1 -1
  91. package/dist/levels/draw.js +3 -3
  92. package/dist/levels/fade.d.ts +13 -22
  93. package/dist/levels/fade.js +17 -38
  94. package/dist/levels/fade.js.map +1 -1
  95. package/dist/levels/index.d.ts +7 -7
  96. package/dist/levels/index.js +1 -1
  97. package/dist/levels/item.d.ts +10 -10
  98. package/dist/levels/item.js +15 -23
  99. package/dist/levels/item.js.map +1 -1
  100. package/dist/levels/load.d.ts +1 -1
  101. package/dist/levels/load.js +5 -3
  102. package/dist/levels/load.js.map +1 -1
  103. package/dist/levels/manager.d.ts +30 -31
  104. package/dist/levels/manager.js +75 -62
  105. package/dist/levels/manager.js.map +1 -1
  106. package/dist/levels/material.d.ts +2 -2
  107. package/dist/levels/material.js +2 -2
  108. package/dist/levels/renderer.d.ts +8 -5
  109. package/dist/levels/renderer.js +20 -4
  110. package/dist/levels/renderer.js.map +1 -1
  111. package/dist/levels/requests.d.ts +4 -1
  112. package/dist/levels/requests.js +3 -1
  113. package/dist/levels/requests.js.map +1 -1
  114. package/dist/loader/context.d.ts +9 -11
  115. package/dist/loader/context.js +12 -7
  116. package/dist/loader/context.js.map +1 -1
  117. package/dist/loader/entry.d.ts +4 -0
  118. package/dist/loader/entry.js +43 -0
  119. package/dist/loader/entry.js.map +1 -0
  120. package/dist/loader/index.d.ts +49 -35
  121. package/dist/loader/index.js +123 -135
  122. package/dist/loader/index.js.map +1 -1
  123. package/dist/loader/level.js +5 -5
  124. package/dist/loader/level.js.map +1 -1
  125. package/dist/loader/node.d.ts +26 -0
  126. package/dist/loader/node.js +199 -0
  127. package/dist/loader/node.js.map +1 -0
  128. package/dist/loader/request.d.ts +11 -44
  129. package/dist/loader/request.js +7 -47
  130. package/dist/loader/request.js.map +1 -1
  131. package/dist/loader/url.d.ts +10 -9
  132. package/dist/loader/url.js +21 -17
  133. package/dist/loader/url.js.map +1 -1
  134. package/dist/lod.d.ts +122 -62
  135. package/dist/lod.js +331 -187
  136. package/dist/lod.js.map +1 -1
  137. package/dist/meshopt.d.ts +1 -1
  138. package/dist/meshopt.js +3 -2
  139. package/dist/meshopt.js.map +1 -1
  140. package/dist/node-process.d.ts +5 -0
  141. package/dist/node-process.js +6 -0
  142. package/dist/node-process.js.map +1 -0
  143. package/dist/node.d.ts +2 -0
  144. package/dist/node.js +5 -0
  145. package/dist/node.js.map +1 -0
  146. package/dist/simplify/index.d.ts +2 -2
  147. package/dist/simplify/index.js +7 -7
  148. package/dist/simplify/index.js.map +1 -1
  149. package/dist/source/detail.d.ts +7 -2
  150. package/dist/source/detail.js +24 -22
  151. package/dist/source/detail.js.map +1 -1
  152. package/dist/source/sampler.js +5 -2
  153. package/dist/source/sampler.js.map +1 -1
  154. package/dist/three.d.ts +7 -7
  155. package/dist/three.js +4 -4
  156. package/dist/three.js.map +1 -1
  157. package/dist/wind/bounds.js +1 -1
  158. package/dist/wind/bounds.js.map +1 -1
  159. package/dist/wind/hooks.d.ts +1 -1
  160. package/dist/wind/hooks.js +1 -1
  161. package/dist/wind/index.d.ts +3 -3
  162. package/dist/wind/index.js +11 -9
  163. package/dist/wind/index.js.map +1 -1
  164. package/package.json +10 -6
  165. package/skills/lod/SKILL.md +65 -54
  166. package/dist/gpu.d.ts +0 -39
  167. package/dist/gpu.js +0 -41
  168. package/dist/gpu.js.map +0 -1
  169. package/dist/instanced/chunk.d.ts +0 -97
  170. package/dist/instanced/chunk.js +0 -156
  171. package/dist/instanced/chunk.js.map +0 -1
  172. package/dist/instanced/chunks.d.ts +0 -60
  173. package/dist/instanced/chunks.js +0 -208
  174. package/dist/instanced/chunks.js.map +0 -1
  175. package/dist/instanced/index.d.ts +0 -120
  176. package/dist/instanced/index.js +0 -290
  177. package/dist/instanced/index.js.map +0 -1
  178. package/dist/instanced/pages/buffers.d.ts +0 -37
  179. package/dist/instanced/pages/buffers.js +0 -15
  180. package/dist/instanced/pages/buffers.js.map +0 -1
  181. package/dist/instanced/pages/chunk.d.ts +0 -51
  182. package/dist/instanced/pages/chunk.js +0 -81
  183. package/dist/instanced/pages/chunk.js.map +0 -1
  184. package/dist/instanced/pages/index.d.ts +0 -74
  185. package/dist/instanced/pages/index.js +0 -269
  186. package/dist/instanced/pages/index.js.map +0 -1
  187. package/dist/instanced/pages/passes.d.ts +0 -21
  188. package/dist/instanced/pages/passes.js +0 -52
  189. package/dist/instanced/pages/passes.js.map +0 -1
  190. package/dist/instanced/pages/slots.d.ts +0 -11
  191. package/dist/instanced/pages/slots.js +0 -90
  192. package/dist/instanced/pages/slots.js.map +0 -1
  193. package/dist/instanced/pages/workgroup.d.ts +0 -14
  194. package/dist/instanced/pages/workgroup.js +0 -38
  195. package/dist/instanced/pages/workgroup.js.map +0 -1
  196. package/dist/levels/wait.d.ts +0 -27
  197. package/dist/levels/wait.js +0 -61
  198. package/dist/levels/wait.js.map +0 -1
  199. package/dist/loader/cache.d.ts +0 -12
  200. package/dist/loader/cache.js +0 -68
  201. package/dist/loader/cache.js.map +0 -1
  202. package/dist/loader/dependencies.d.ts +0 -32
  203. package/dist/loader/dependencies.js +0 -113
  204. package/dist/loader/dependencies.js.map +0 -1
package/dist/lod.js CHANGED
@@ -1,37 +1,60 @@
1
- import { Object3D, Sphere } from "three/webgpu";
1
+ import { Box3, Color, Float32BufferAttribute, InstancedBufferAttribute, InstancedBufferGeometry, Matrix4, Mesh, MeshBasicNodeMaterial, Object3D, Sphere, } from "three/webgpu";
2
2
  import { at } from "./at.js";
3
- import { measureLevels, prepareBounds } from "./levels/bounds.js";
4
3
  import { disposeCopies } from "./dispose.js";
5
- import { EncodedLevels, emptyLevels, levelsFrom, tintOf } from "./levels/index.js";
6
- import { FADE, drawnLevel, levelsToDraw } from "./levels/draw.js";
7
- import { setFadeSource } from "./levels/fade.js";
4
+ import { EncodedLevels, emptyLevels, levelsFrom } from "./levels/index.js";
5
+ import { FADE } from "./levels/draw.js";
6
+ import { fadeSourceOf } from "./levels/fade.js";
8
7
  import { levelsToLoad } from "./levels/load.js";
9
8
  import { LodLevelLoadManager } from "./levels/manager.js";
10
- import { levelMaterial } from "./levels/material.js";
11
- import { screenHeight, screenOf } from "./levels/screen.js";
12
- import { inShadowMap } from "./levels/renderer.js";
13
- import { isImpostorMesh, isLOD, isLine, isMesh, isPoints, rejectSkinned, sameClass } from "./three.js";
9
+ import { inShadowMap, maxStorageBinding } from "./levels/renderer.js";
10
+ import { isRenderer, isStorageInstanced, sameClass } from "./three.js";
14
11
  import { WIND } from "./wind/hooks.js";
15
- import { copyWind, refreshWind } from "./wind/index.js";
12
+ import { copyWind } from "./wind/index.js";
13
+ import { localCamera, shownBy } from "./instanced/camera.js";
14
+ import { ClusterView, boundClusters, checkClusters, measuredBox } from "./instanced/clusters.js";
15
+ import { cullIn, emptyCull } from "./instanced/cull.js";
16
+ import { Instances, measure } from "./instanced/instances.js";
17
+ import { MeshesByLevel } from "./instanced/levels.js";
18
+ import { InstanceLists, frustumIn, listedOf } from "./instanced/lists.js";
19
+ import { MAX_SURVIVOR_SCALE, instanceLevel } from "./instanced/measure.js";
20
+ import { drawInstances } from "./instanced/meshes.js";
21
+ import { raycastInstances } from "./instanced/raycast.js";
22
+ import { InstanceShape } from "./instanced/shape.js";
16
23
  /**
17
- * One object's levels, switched by on-screen height with dithered fades. three's renderer calls `update` with each
18
- * camera before it draws, shadow maps' included; each camera measures at the height it draws at, measured in each
19
- * render (outside one, the canvas's). Orthographic cameras switch without fading. Shadows follow what the camera draws
20
- * and omit casters smaller than a shadow texel; levels cast into three's shadow maps, not into a light whose shadow
21
- * map a custom shadow node replaces. Nothing draws until the coarsest level that draws something has loaded, which
22
- * loads first; a deferred level loads when a camera first needs it, once that one has loaded, and meanwhile the
23
- * nearest loaded coarser level draws in its place.
24
+ * Copies of one object at levels of detail, driven like a three InstancedMesh: `instanceMatrix`, `instanceColor`,
25
+ * `count` and `boundingBox`, and `clusters` to cull and choose levels by. Each copy draws the level levelsToDraw gives
26
+ * for its height on screen, switching with dithered fades; each camera's instances are sorted into indirect draws on
27
+ * the GPU. `new Lod(levels)` is one object at the Lod's own transform.
24
28
  *
25
- * Arriving levels' texture uploads are paced to about one uncompressed 2048² RGBA texture's bytes per frame. Levels
26
- * are cloned into the Lod. A nested Lod switches and fades its own levels. Lines, points and sprites draw without
27
- * fading. Raycasts hit the source only. A Lod draws with its LodGpu's renderer only.
29
+ * The attributes are assignable. A CPU attribute's edits draw once its `needsUpdate` is set (within its update ranges,
30
+ * which the Lod takes and clears), as an InstancedMesh's do. A StorageInstancedBufferAttribute, such as one the app's
31
+ * compute pass writes, is read in place, every frame; a storage colour holds four floats per instance. A matrix of
32
+ * scale 0 draws nothing. Instance matrices may scale arbitrarily; the Lod's own transform and its parents should scale
33
+ * uniformly.
28
34
  *
29
- * Build a new Lod after adding or moving meshes within a level: geometry is measured and hooked at construction or
30
- * arrival. Skinned meshes and ShaderMaterials are refused; use static meshes with node materials or supported built-in
31
- * materials.
35
+ * Which levels load and which level meshes draw for a camera follow from the instances' bounds: per cluster, its box
36
+ * and scales; without clusters, `boundingBox` around the first `count` instances, else what the CPU measures of a CPU
37
+ * instanceMatrix. With clusters, only their instances draw. A storage instanceMatrix with neither loads every level
38
+ * (it warns once). Each camera draws only the instances in its frustum, and each shadow map is a camera of its own: it
39
+ * draws the casters in its frustum, each at the level its texels resolve, as an orthographic camera would (an instance
40
+ * smaller than a texel casts nothing). Thresholds, fades and loading follow `LodLevel`; `cullDistance` thins the
41
+ * instances out with distance. Nothing draws until the coarsest level that draws something has loaded, which loads
42
+ * first; a deferred level loads when a camera first needs it, and meanwhile the nearest loaded coarser level draws in
43
+ * its place. Arriving levels' texture uploads are paced to about one uncompressed 2048² RGBA texture's bytes per frame.
44
+ *
45
+ * It draws with WebGPU only (three's WebGPURenderer on its WebGPU backend, with `indirect-first-instance`), with the
46
+ * first renderer that draws it: it learns of it in that renderer's first frame, which draws nothing of it, and another
47
+ * renderer drawing it is its error. Sequential cameras are supported; a nested render with a camera that the outer
48
+ * render also draws with replaces that camera's instance lists, so exclude the Lod from it with camera layers.
49
+ *
50
+ * Level templates are cloned, then their meshes are instanced, as children of the Lod on its layers; it sets each
51
+ * one's `visible` per camera, so hide the Lod itself, never its level meshes. Skinned meshes, InstancedMeshes (except ImpostorMesh),
52
+ * lines, points, sprites and LODs in levels are refused, as are ShaderMaterials; use static meshes with node materials
53
+ * or supported built-in materials. Build a new Lod after adding or moving meshes within a level: geometry is measured
54
+ * at construction or arrival. For external detail, leave level 0 empty and draw the instances that `getLevelAt`
55
+ * reports there.
32
56
  */
33
57
  export class Lod extends Object3D {
34
- gpu;
35
58
  /** Multiplies every measured height: below 1, cheaper levels take over sooner. */
36
59
  static quality = 1;
37
60
  /** Tint every level by its index, to see which level draws where. */
@@ -39,229 +62,350 @@ export class Lod extends Object3D {
39
62
  /** Share of a level's range its fade spans: from `maxPixels × (1 - fade)` up to its `maxPixels`, the finer level draws too. */
40
63
  static fade = FADE;
41
64
  isLOD = true;
65
+ isLod = true;
42
66
  /** Let the renderer call `update` with its camera every frame. */
43
67
  autoUpdate = true;
44
68
  /** Draw only this level, without fades, once the coarsest level that draws something has loaded. */
45
69
  forceLevel = null;
46
- /** The levels, each `object` this Lod's own copy once there is one. Set `maxPixels` to move a switch. */
70
+ /** The levels, each `object` the template its level meshes are made from, once there is one (never in the scene). */
47
71
  levels = [];
72
+ /** Thins the instances out with distance from a camera, in every camera; null draws them at any distance. */
73
+ cullDistance = null;
74
+ /** 16 floats per instance: a CPU InstancedBufferAttribute (identities to start with) or a storage one. */
75
+ instanceMatrix;
76
+ /** RGB per instance, white without: three floats on the CPU, four in a storage attribute. */
77
+ instanceColor = null;
78
+ /** How many of `instanceMatrix`'s instances draw. */
79
+ count;
80
+ /** Bounds every instance at every level, in the Lod's space (see `computeBoundingBox`); measured when null. */
81
+ boundingBox = null;
82
+ /** Disjoint ranges of instances, each inside its box, which cull and choose levels apart; clipped to `count`. */
83
+ clusters = undefined;
48
84
  /** The levels as they were given, which a copy is made from. */
49
85
  inputs = [];
50
- /** Per level, where its meshes' fade comes from. */
51
- fades = [];
52
- /** Per level, whether its object is a Lod, which fades its own levels. */
53
- nested = [];
54
- /**
55
- * Per loaded level, what in it may cast (see `shadowCasters`): found when it is built or joins, read every shadow
56
- * map.
57
- */
58
- casters = [];
59
- /** The levels as levelsToDraw reads them. */
60
- encoded;
61
- /** Bounding sphere of the source (see `measureLevels`) in the Lod's own space. */
62
- sphere = new Sphere();
63
- casterRadius = 0;
64
- loads;
86
+ /** What it is made of for its levels, which a copy makes anew. */
87
+ built;
65
88
  disposed = false;
89
+ instances = new Instances();
90
+ /** What the level meshes draw. */
91
+ drawn;
92
+ /** Around every instance, survivors grown: what every level mesh is culled and boxed by. */
93
+ bounds = { sphere: new Sphere(), box: new Box3() };
94
+ view = new ClusterView();
95
+ /** The cluster ranges last checked to be disjoint. */
96
+ checked = [];
97
+ /** What `cullIn` writes cullDistance into, in this Lod's space. */
98
+ cull = emptyCull();
66
99
  /**
67
- * `levels[0]` is the source. Empty only as the target of `copy`. A source that draws nothing (an empty Object3D, for
68
- * detail another system draws) is measured by the first level that draws something. `gpu` is what it shares with
69
- * every Lod drawing with its renderer.
100
+ * Drawn until a renderer has drawn the Lod, to learn which: three tells a mesh its renderer, but not a LOD. It bounds
101
+ * the instances for Box3.setFromObject, as the level meshes do once there are some.
70
102
  */
71
- constructor(levels, gpu, options = {}) {
103
+ sentinel;
104
+ warned = false;
105
+ /** `levels[0]` is the source; empty only as the target of `copy`. `count` instances, at the Lod's origin to start with. */
106
+ constructor(levels, count = 1, options = {}) {
72
107
  super();
73
- this.gpu = gpu;
74
- const { loads, encoded } = this.build(levels);
75
- this.loads = loads;
76
- this.encoded = encoded;
77
- this.loads.item.given = options.manager;
78
- }
79
- build(inputs) {
80
- this.inputs = inputs;
81
- if (inputs.length > 0) {
82
- const { own, placed } = measureLevels(inputs, "Lod");
83
- this.sphere = placed;
84
- this.casterRadius = placed.radius;
85
- this.levels.push(...levelsFrom(inputs, 2 * own.radius, "Lod"));
86
- }
87
- const encoded = new EncodedLevels(this.levels, emptyLevels(inputs), "Lod");
88
- this.levels.forEach(({ object }, i) => {
89
- const fade = { kind: "object", fade: 0, diameter: 0, tint: tintOf(i, false) };
90
- this.fades.push(fade);
91
- this.nested.push(object ? isLOD(object) : false);
92
- this.casters.push(object ? shadowCasters(object) : null);
93
- if (!object)
94
- return;
95
- rejectSkinned(object, "Lod");
96
- this.add(object);
97
- this.hook(object, fade, isLOD(object), object);
98
- });
99
- const loads = new LodLevelLoadManager(this, this.gpu, `Lod ${this.uuid}`, inputs, encoded.get(null, true), (level, loaded) => this.prepare(level, loaded), (level) => {
100
- const object = this.levels[level]?.object;
101
- return object ? [object] : [];
102
- }, null);
103
- return { loads, encoded };
104
- }
105
- /** Fade the meshes under `node` by `fade`; an inner Lod fades its own. */
106
- hook(node, fade, nested, level) {
107
- const inner = nested || (node !== level && isLOD(node));
108
- if (isMesh(node) && !inner) {
109
- setFadeSource(node, fade);
110
- // An ImpostorMesh reads its draw itself.
111
- if (!isImpostorMesh(node))
112
- node.material = Array.isArray(node.material) ? node.material.map((m) => levelMaterial(m)) : levelMaterial(node.material);
113
- }
114
- for (const child of node.children)
115
- this.hook(child, fade, inner, level);
116
- }
117
- /** A copy of `loaded`, level `index`'s object, parented hidden for world matrices and wind until it joins. */
118
- prepare(index, loaded) {
119
- const object = loaded.clone();
120
- const nested = isLOD(object);
121
- const level = at(this.levels, index);
122
- object.visible = false;
123
- rejectSkinned(object, "Lod");
124
- if (level.box)
125
- prepareBounds(object, level.box);
126
- this.hook(object, at(this.fades, index), nested, object);
127
- this.add(object);
128
- object.updateWorldMatrix(true, true);
129
- refreshWind(this, object);
130
- return {
131
- object,
132
- join: () => {
133
- level.object = object;
134
- this.nested[index] = nested;
135
- this.casters[index] = shadowCasters(object);
136
- },
137
- discard: () => {
138
- this.remove(object);
139
- disposeCopies(object);
140
- },
141
- };
108
+ if (!Number.isInteger(count) || count < 0)
109
+ throw new RangeError(`Lod: count must be a nonnegative integer, not ${count}`);
110
+ this.count = count;
111
+ this.instanceMatrix = identities(count);
112
+ this.instances.refresh(this);
113
+ this.drawn = { matrices: this.instances.matrixStorage, colors: this.instances.colorStorage };
114
+ this.sentinel = this.makeSentinel();
115
+ this.built = this.init(levels);
116
+ this.built.loads.item.given = options.manager;
117
+ this.refresh();
142
118
  }
143
119
  get pending() {
144
- return this.loads.pending;
120
+ return this.built.loads.pending;
145
121
  }
146
122
  get error() {
147
- return this.loads.error;
123
+ return this.built.loads.error;
148
124
  }
149
125
  /** Where the item of levels a camera misses goes (see `LodOptions.manager`). */
150
126
  get manager() {
151
- return this.loads.item.manager;
127
+ return this.built.loads.item.manager;
152
128
  }
153
129
  set manager(manager) {
154
- this.loads.item.given = manager;
130
+ this.built.loads.item.given = manager;
131
+ }
132
+ setMatrixAt(index, matrix) {
133
+ matrix.toArray(this.instanceMatrix.array, index * 16);
134
+ return this;
135
+ }
136
+ getMatrixAt(index, matrix) {
137
+ return matrix.fromArray(this.instanceMatrix.array, index * 16);
138
+ }
139
+ /** Write instance `index`'s colour, making a white `instanceColor` for every instance first if there is none. */
140
+ setColorAt(index, color) {
141
+ this.instanceColor ??= new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3);
142
+ color.toArray(this.instanceColor.array, index * this.instanceColor.itemSize);
143
+ return this;
144
+ }
145
+ /** Instance `index`'s colour: white without `instanceColor`. */
146
+ getColorAt(index, color) {
147
+ const colors = this.instanceColor;
148
+ return colors ? color.fromArray(colors.array, index * colors.itemSize) : color.setRGB(1, 1, 1);
149
+ }
150
+ /**
151
+ * Set `boundingBox` around the first `count` instances at every level and its sway, from a CPU instanceMatrix as it
152
+ * is now; the CPU cannot read a storage one.
153
+ */
154
+ computeBoundingBox() {
155
+ if (isStorageInstanced(this.instanceMatrix))
156
+ throw new Error("Lod.computeBoundingBox: the CPU cannot read a storage instanceMatrix: set boundingBox or clusters");
157
+ this.boundingBox = measuredBox(measure(this.instanceMatrix, this.count, null), this.built.shape, this.boundingBox ?? new Box3());
158
+ }
159
+ /** What this Lod is made of for `inputs`: its levels, their meshes and their loading. */
160
+ init(inputs) {
161
+ const shape = new InstanceShape(inputs);
162
+ const lists = new InstanceLists(listedOf(inputs));
163
+ const drawing = { shape, lists, drawn: this.drawn };
164
+ this.inputs = inputs;
165
+ if (inputs.length > 0)
166
+ this.levels.push(...levelsFrom(inputs, 2 * shape.ownRadius, "Lod"));
167
+ const encoded = new EncodedLevels(this.levels, emptyLevels(inputs), "Lod");
168
+ const drawFor = (renderer, camera) => this.built.loads.guard(() => {
169
+ this.built.lists.drawFor(this.see(renderer), camera, this.instances.matrixStorage);
170
+ });
171
+ const meshes = new MeshesByLevel(this, this.levels, drawing, this.bounds, drawFor);
172
+ // Its sorts show them.
173
+ meshes.show(0);
174
+ const loads = new LodLevelLoadManager(this, `Lod ${this.uuid}`, inputs, encoded.get(null, true), (level, loaded) => meshes.prepare(level, loaded), (level) => meshes.of(level));
175
+ return { ...drawing, meshes, loads, encoded };
155
176
  }
156
- /** Switch and fade the levels for `camera`, and load those it needs. What fails is reported (see `error`): three is rendering. */
177
+ /**
178
+ * The sentinel, drawn until a renderer has drawn the Lod (see `see`): no instances, on the Lod's layers, casting, and
179
+ * never hit by a raycast. Its box is the instances' bounds, and its vertices that box's corners (see `placeSentinel`),
180
+ * which precise Box3.setFromObject reads.
181
+ */
182
+ makeSentinel() {
183
+ const geometry = new InstancedBufferGeometry().setAttribute("position", new Float32BufferAttribute(new Float32Array(24), 3));
184
+ geometry.instanceCount = 0;
185
+ geometry.boundingBox = this.bounds.box;
186
+ geometry.boundingSphere = this.bounds.sphere;
187
+ const sentinel = new Mesh(geometry, SENTINEL_MATERIAL);
188
+ sentinel.frustumCulled = false;
189
+ sentinel.layers = this.layers;
190
+ sentinel.raycast = () => { };
191
+ // Shadow passes draw it too: a Lod that only casts learns its renderer there.
192
+ sentinel.castShadow = true;
193
+ sentinel.onBeforeRender = (renderer) => this.built.loads.guard(() => void this.see(renderer));
194
+ this.add(sentinel);
195
+ return sentinel;
196
+ }
197
+ /** `renderer`, which three hands a mesh's draw, draws the Lod (see `LodLevelLoadManager.see`): it, once checked. */
198
+ see(renderer) {
199
+ if (!isRenderer(renderer))
200
+ throw new Error("Lod: three drew a mesh of it with no renderer");
201
+ this.built.loads.see(renderer);
202
+ return renderer;
203
+ }
204
+ [WIND](padding, slope, baseY) {
205
+ if (this.built.loads.started)
206
+ throw new Error("Lod: apply wind before the first render");
207
+ this.built.shape.wind(padding, slope, baseY);
208
+ for (const mesh of this.built.meshes.all()) {
209
+ const source = fadeSourceOf(mesh);
210
+ if (source)
211
+ source.radius = this.built.shape.fadeRadius;
212
+ }
213
+ this.refresh();
214
+ }
215
+ /** Take in the instances as they are now, so that its level meshes bound them (see Box3.setFromObject), then update the world matrices. */
216
+ updateMatrixWorld(force) {
217
+ if (!this.disposed && this.levels.length > 0)
218
+ this.built.loads.guard(() => this.refresh());
219
+ super.updateMatrixWorld(force);
220
+ }
221
+ /** Sort the instances into level lists for `camera`, a camera's or a shadow map's, and load the levels they need. What fails is reported (see `error`). */
157
222
  update(camera) {
223
+ if (this.disposed || this.levels.length === 0)
224
+ return;
158
225
  // A shadow map draws nothing of a Lod whose levels cast nothing; one not loaded yet may.
159
226
  const shadow = inShadowMap(this);
160
- if (shadow && !this.casters.some((casters) => !casters || casters.some((node) => node.castShadow)))
161
- return;
162
- this.loads.guard(() => this.show(camera, shadow));
163
- }
164
- /** Show the levels for `camera`, a shadow map's when `shadow`. */
165
- show(camera, shadow) {
166
- if (this.disposed || this.levels.length === 0)
227
+ if (shadow && !this.levels.some(({ object }, i) => !object || this.built.meshes.of(i).some((mesh) => mesh.castShadow)))
167
228
  return;
168
- // A shadow map draws the levels its scene's camera chose.
169
- if (shadow)
170
- return void this.loads.request(camera, 0, true);
171
- const { height, levels } = this.measure(camera, false);
172
- const loaded = this.loads.request(camera, levelsToLoad([[height, height]], this.encoded.heights(levels)), false);
173
- let { level, finer, fade } = levelsToDraw(height, levels, loaded, this.loads.before, this.loads.progress);
174
- // A nested Lod fades its own levels: the switch to or from one is immediate.
175
- if (this.nested[level] || this.nested[finer])
176
- fade = 0;
177
- const diameter = 2 * this.casterRadius * this.matrixWorld.getMaxScaleOnAxis();
178
- this.levels.forEach(({ object }, i) => {
179
- const source = at(this.fades, i);
180
- source.fade = i === level ? fade : i === finer ? -fade : 0;
181
- source.diameter = diameter;
182
- source.tint = tintOf(i, Lod.debug);
183
- if (object)
184
- object.visible = i === level || (fade > 0 && i === finer);
229
+ this.built.loads.guard(() => {
230
+ const { renderer } = this.built.loads;
231
+ this.sentinel.visible = renderer === null;
232
+ if (renderer)
233
+ this.sort(renderer, camera, shadow);
185
234
  });
186
235
  }
187
- /** The source's height on `camera`'s screen, and the levels as levelsToDraw reads them there. */
188
- measure(camera, shadow) {
189
- const screen = screenOf(camera, this.loads.heightOf(camera, shadow));
190
- const height = screenHeight(this.sphere, this.matrixWorld, screen) * Lod.quality;
191
- return { height, levels: this.encoded.get(this.forceLevel, !screen.ortho) };
236
+ /** Take in the attributes, clusters and cullDistance as they are now, and bound the instances. */
237
+ refresh() {
238
+ const { lists, meshes, shape } = this.built;
239
+ if (this.clusters)
240
+ checkClusters(this.clusters, this.instanceMatrix.count, this.checked);
241
+ this.instances.refresh(this);
242
+ const survivors = this.cullDistance?.scaleSurvivors ?? false;
243
+ const matrices = survivors ? lists.scaledMatrices(this.instanceMatrix.count) : this.instances.matrixStorage;
244
+ const colors = this.instances.colorStorage;
245
+ if (matrices !== this.drawn.matrices || colors !== this.drawn.colors) {
246
+ this.drawn.matrices = matrices;
247
+ this.drawn.colors = colors;
248
+ drawInstances(meshes.all(), this.drawn);
249
+ }
250
+ boundClusters(this, this.instances.measured, shape, survivors ? MAX_SURVIVOR_SCALE : 1, this.bounds);
251
+ this.placeSentinel();
252
+ }
253
+ /** Put the sentinel's vertices at the corners of the instances' bounds; at the origin while nothing bounds them. */
254
+ placeSentinel() {
255
+ const { box } = this.bounds;
256
+ const position = this.sentinel.geometry.getAttribute("position");
257
+ const empty = box.isEmpty();
258
+ let moved = false;
259
+ for (let i = 0; i < 8; i++) {
260
+ const x = empty ? 0 : i & 1 ? box.max.x : box.min.x;
261
+ const y = empty ? 0 : i & 2 ? box.max.y : box.min.y;
262
+ const z = empty ? 0 : i & 4 ? box.max.z : box.min.z;
263
+ if (position.getX(i) === x && position.getY(i) === y && position.getZ(i) === z)
264
+ continue;
265
+ position.setXYZ(i, x, y, z);
266
+ moved = true;
267
+ }
268
+ if (moved)
269
+ position.needsUpdate = true;
270
+ }
271
+ /** Sort for `camera`, a shadow map's when `shadow`, drawn by `renderer`. */
272
+ sort(renderer, camera, shadow) {
273
+ const { loads, shape, lists, encoded, meshes } = this.built;
274
+ this.refresh();
275
+ const limit = maxStorageBinding(renderer);
276
+ const bytes = this.instanceMatrix.count * 64;
277
+ if (bytes > limit)
278
+ throw new RangeError(`Lod: its instanceMatrix of ${this.instanceMatrix.count} instances takes ${bytes} bytes, more than the device's storage binding of ${limit} bytes: split the instances across Lods, or raise maxStorageBufferBindingSize in the renderer's requiredLimits`);
279
+ const local = this.localCamera(camera, renderer, shadow);
280
+ const cull = cullIn(this.cullDistance, this.matrixWorld, this.cull);
281
+ const found = lists.of(camera);
282
+ const { view } = this;
283
+ view.see(this, this.instances.measured, shape, frustumIn(found, camera, this.matrixWorld), local, cull);
284
+ if (view.unbounded && !this.warned) {
285
+ this.warned = true;
286
+ console.warn(`Lod ${this.uuid}: nothing bounds its storage instanceMatrix, so every level loads and the CPU culls nothing; set boundingBox or clusters`);
287
+ }
288
+ const { levels } = local;
289
+ // A shadow map draws from the levels its scene's cameras loaded.
290
+ loads.request(camera, levelsToLoad(shadow ? [] : view.heights, encoded.heights(levels)), shadow);
291
+ meshes.tint(Lod.debug);
292
+ lists.prune(camera, (other) => loads.rendering(other));
293
+ const { loaded, before, progress } = loads;
294
+ // Three projects this Lod's children for the camera after this update.
295
+ const { shown, only } = shownBy(view.seen, levels, encoded, { loaded, before, progress });
296
+ lists.sort(camera, {
297
+ ...local,
298
+ cull,
299
+ loaded,
300
+ before,
301
+ progress,
302
+ source: shape.source,
303
+ reach: shape.reach,
304
+ ranges: view.ranges,
305
+ instances: view.instances,
306
+ inside: view.inside,
307
+ onlyLevel: cull === null ? only : 0,
308
+ version: this.instances.version,
309
+ }, limit);
310
+ // Nothing draws from the camera's indirect draws before a sort writes them, which a level mesh's draw runs first.
311
+ meshes.show(found.written ? shown : 0);
312
+ }
313
+ /** `camera` in this Lod's space, drawn by `renderer` (see `localCamera`). */
314
+ localCamera(camera, renderer, shadow) {
315
+ const { loads, encoded } = this.built;
316
+ return localCamera(camera, loads.heightOf(camera, renderer, shadow), this.matrixWorld, encoded, this.forceLevel, Lod.quality);
192
317
  }
193
318
  /**
194
- * The index of the level that draws most of the Lod's pixels for `camera` from where it is, with the levels loaded
195
- * now and no arrival under way (see `drawnLevel`); null while no level it could draw is loaded.
319
+ * The level that draws most of instance `index`'s pixels for `camera` from where it is now, with the levels loaded
320
+ * now and no arrival under way (see `drawnLevel`); null at scale 0, thinned out by `cullDistance`, or while no level
321
+ * it could draw is loaded. From the CPU instanceMatrix as it is, edits not yet drawn included; the CPU cannot read a
322
+ * storage one. It measures with the renderer drawing the Lod, so it throws before one has drawn it.
196
323
  */
197
- getLevel(camera) {
198
- if (this.levels.length === 0)
199
- return null;
200
- const { height, levels } = this.measure(camera, inShadowMap(this));
201
- return drawnLevel(levelsToDraw(height, levels, this.loads.loaded, this.loads.loaded, 1));
202
- }
203
- [WIND](padding) {
204
- if (this.loads.started)
205
- throw new Error("Lod: apply wind before the first render");
206
- this.casterRadius += padding;
324
+ getLevelAt(index, camera) {
325
+ const { renderer } = this.built.loads;
326
+ if (!renderer)
327
+ throw new Error("Lod.getLevelAt: render the Lod first: it measures with the renderer drawing it");
328
+ if (isStorageInstanced(this.instanceMatrix))
329
+ throw new Error("Lod.getLevelAt: the CPU cannot read a storage instanceMatrix");
330
+ if (!Number.isInteger(index) || index < 0 || index >= this.count)
331
+ throw new RangeError(`Lod.getLevelAt: ${index} is not one of its ${this.count} instances`);
332
+ const cull = cullIn(this.cullDistance, this.matrixWorld, this.cull);
333
+ const local = this.localCamera(camera, renderer, inShadowMap(this));
334
+ return instanceLevel(this.instanceMatrix.array, index * 16, cull, local, this.built.shape.source, this.built.loads.loaded);
207
335
  }
336
+ /**
337
+ * Hits the first `count` instances on the source level, with `instanceId` set as on an InstancedMesh's hits; `object`
338
+ * is this Lod. Instances of a storage instanceMatrix, which the CPU cannot read, are not hit. Its level meshes, on its
339
+ * layers, are never hit themselves.
340
+ */
208
341
  raycast(raycaster, intersects) {
209
- const source = this.levels[0]?.object;
210
- if (source)
211
- raycaster.intersectObject(source, true, intersects);
212
- // Stop the raycaster from descending into the other levels.
213
- return false;
342
+ if (!isStorageInstanced(this.instanceMatrix))
343
+ raycastInstances(this, { parts: this.built.meshes.source, rest: this.built.shape.rest }, this.instanceMatrix.array, this.count, raycaster, intersects);
214
344
  }
215
345
  /**
216
- * Copies `source`'s levels into this empty Lod (it throws otherwise). The copies share geometry, materials and
217
- * textures with `source`, as three's clone does; the settings, LoadingManager, wind and each level's `maxPixels`
218
- * come along.
346
+ * Copies `source`'s levels, instances and settings into this Lod without levels (it throws otherwise); the copy
347
+ * shares geometry and textures with `source`, and holds copies of its attributes and clusters. Storage attributes
348
+ * cannot be copied: their instances live on the GPU.
219
349
  */
220
350
  copy(source) {
221
351
  if (this.levels.length > 0)
222
- throw new Error("Lod.copy: copy into an empty Lod");
352
+ throw new Error("Lod.copy: copy into a Lod without levels");
353
+ const { instanceMatrix, instanceColor } = source;
354
+ if (isStorageInstanced(instanceMatrix) || (instanceColor && isStorageInstanced(instanceColor)))
355
+ throw new Error("Lod.copy: a storage attribute's instances live on the GPU and cannot be copied");
356
+ const inputs = source.inputs.map((input, i) => ({ ...input, maxPixels: at(source.levels, i).maxPixels }));
223
357
  super.copy(source, false);
224
- const { loads, encoded } = this.build(source.inputs.map((input, i) => ({ ...input, maxPixels: at(source.levels, i).maxPixels })));
225
- this.loads = loads;
226
- this.encoded = encoded;
227
- this.loads.item.given = source.loads.item.given;
358
+ this.instanceMatrix = new InstancedBufferAttribute(instanceMatrix.array.slice(), 16);
359
+ this.instanceColor = instanceColor && new InstancedBufferAttribute(instanceColor.array.slice(), 3);
360
+ this.count = source.count;
361
+ this.boundingBox = source.boundingBox?.clone() ?? null;
362
+ this.clusters = source.clusters?.map((cluster) => ({ ...cluster, boundingBox: cluster.boundingBox.clone() }));
363
+ this.cullDistance = source.cullDistance && { ...source.cullDistance };
228
364
  this.forceLevel = source.forceLevel;
229
365
  this.autoUpdate = source.autoUpdate;
366
+ this.built.lists.dispose();
367
+ this.built.loads.dispose(() => { });
368
+ this.built = this.init(inputs);
369
+ this.built.loads.item.given = source.built.loads.item.given;
230
370
  copyWind(source, this);
371
+ this.refresh();
231
372
  return this;
232
373
  }
233
374
  clone() {
234
- const clone = new Lod([], this.gpu).copy(this);
375
+ const clone = new Lod([], 0).copy(this);
235
376
  if (!sameClass(this, clone))
236
377
  throw new Error("Lod.clone: a subclass must override clone");
237
378
  return clone;
238
379
  }
239
380
  /**
240
- * Release what the Lod made of its levels, once nothing it prepares or compiles still uses them. Objects you give or
241
- * load are yours to dispose; LodLoader's are freed when the last Lod holding them is disposed (see `LodLevel.hold`).
381
+ * Release its buffers and what it made of its levels, once nothing it prepares or compiles still uses them. Objects
382
+ * you give or load, its attributes among them, are yours to dispose; CachedLodLoader's are freed when the last Lod
383
+ * holding them is disposed (see `LodLevel.hold`).
242
384
  */
243
385
  dispose() {
244
386
  if (this.disposed)
245
387
  return;
246
388
  this.disposed = true;
247
389
  super.dispose();
248
- this.loads.dispose(() => {
390
+ this.sentinel.removeFromParent();
391
+ this.sentinel.geometry.dispose();
392
+ this.built.loads.dispose(() => {
393
+ this.built.meshes.dispose();
394
+ this.built.lists.dispose();
395
+ this.instances.dispose();
249
396
  for (const { object } of this.levels)
250
397
  if (object)
251
398
  disposeCopies(object);
252
399
  });
253
400
  }
254
401
  }
255
- /**
256
- * What three's shadow pass may draw under `root`, itself included: its meshes, lines and points, cast if `castShadow`
257
- * is set.
258
- */
259
- function shadowCasters(root) {
260
- const found = [];
261
- root.traverse((node) => {
262
- if (isMesh(node) || isLine(node) || isPoints(node))
263
- found.push(node);
264
- });
265
- return found;
402
+ const SENTINEL_MATERIAL = new MeshBasicNodeMaterial();
403
+ /** A CPU instanceMatrix of `count` identities. */
404
+ function identities(count) {
405
+ const array = new Float32Array(count * 16);
406
+ for (let i = 0; i < count; i++)
407
+ array.set(IDENTITY, i * 16);
408
+ return new InstancedBufferAttribute(array, 16);
266
409
  }
410
+ const IDENTITY = new Matrix4().elements;
267
411
  //# sourceMappingURL=lod.js.map