phoria2 1.2.0 → 1.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 (69) hide show
  1. package/README.md +11 -9
  2. package/dist/bloom.js +4 -4
  3. package/dist/bloom.js.map +1 -1
  4. package/dist/charts.js +527 -510
  5. package/dist/charts.js.map +1 -1
  6. package/dist/core.js +1760 -1170
  7. package/dist/core.js.map +1 -1
  8. package/dist/debug.js +297 -0
  9. package/dist/debug.js.map +1 -0
  10. package/dist/edit.js +60 -60
  11. package/dist/edit.js.map +1 -1
  12. package/dist/explain.js +32 -13
  13. package/dist/explain.js.map +1 -1
  14. package/dist/gltf.js +155 -155
  15. package/dist/gltf.js.map +1 -1
  16. package/dist/keyboard.js +188 -0
  17. package/dist/keyboard.js.map +1 -0
  18. package/dist/motion.js +35 -35
  19. package/dist/motion.js.map +1 -1
  20. package/dist/particles.js +187 -114
  21. package/dist/particles.js.map +1 -1
  22. package/dist/passes.js +116 -104
  23. package/dist/passes.js.map +1 -1
  24. package/dist/phoria2.js +1 -1
  25. package/dist/picking.js +95 -62
  26. package/dist/picking.js.map +1 -1
  27. package/dist/snapshot.js +1 -1
  28. package/dist/tooltip.js +1 -1
  29. package/dist/types/View.d.ts +27 -0
  30. package/dist/types/area.d.ts +18 -0
  31. package/dist/types/debug.d.ts +74 -0
  32. package/dist/types/explain.d.ts +4 -0
  33. package/dist/types/frame.d.ts +5 -0
  34. package/dist/types/geometry/Geometry.d.ts +16 -0
  35. package/dist/types/index.d.ts +2 -0
  36. package/dist/types/material/Material.d.ts +67 -0
  37. package/dist/types/material/Texture.d.ts +18 -2
  38. package/dist/types/particles/Emitter.d.ts +39 -2
  39. package/dist/types/scene/drawables.d.ts +23 -2
  40. package/dist/types/watch.d.ts +8 -1
  41. package/dist/types/webgl/hooks.d.ts +48 -0
  42. package/dist/types/webgl/passes.d.ts +4 -0
  43. package/dist/types/webgl/programs.d.ts +15 -5
  44. package/dist/types/webgl/resources.d.ts +12 -2
  45. package/dist/types/webgl/shaders.d.ts +41 -5
  46. package/llms-full.txt +275 -1
  47. package/llms.txt +1 -1
  48. package/package.json +1 -1
  49. package/schema/scene.schema.json +75 -0
  50. package/src/View.js +121 -7
  51. package/src/area.js +131 -0
  52. package/src/charts/marks.js +29 -2
  53. package/src/debug.js +283 -0
  54. package/src/explain.js +19 -0
  55. package/src/frame.js +7 -2
  56. package/src/geometry/Geometry.js +16 -1
  57. package/src/index.js +1 -0
  58. package/src/material/Material.js +130 -4
  59. package/src/material/Texture.js +55 -2
  60. package/src/particles/Emitter.js +121 -10
  61. package/src/scene/drawables.js +89 -8
  62. package/src/watch.js +26 -3
  63. package/src/webgl/WebGLRenderer.js +55 -7
  64. package/src/webgl/hooks.js +121 -0
  65. package/src/webgl/passes.js +17 -2
  66. package/src/webgl/picking.js +45 -3
  67. package/src/webgl/programs.js +20 -9
  68. package/src/webgl/resources.js +169 -15
  69. package/src/webgl/shaders.js +545 -38
@@ -43,9 +43,18 @@ const HINTS = {
43
43
  scale: "use 'repeat' - [u, v] times across",
44
44
  }
45
45
 
46
+ /**
47
+ * Part of an image, in its pixels from the top left, as needsUpdate() takes it.
48
+ * @typedef {{ x: number, y: number, width: number, height: number }} TextureRegion
49
+ */
50
+
51
+ // how many updates a texture remembers the region of, for a renderer catching up on several - a
52
+ // frame of paint can make a hundred or so
53
+ const CHANGES_KEPT = 256
54
+
46
55
  /**
47
56
  * An image for a material map. A video's frames upload by themselves as it plays; after drawing on
48
- * a canvas, call `needsUpdate()`.
57
+ * a canvas, call `needsUpdate()` - with the rectangle drawn in, to send only that.
49
58
  */
50
59
  export class Texture {
51
60
  /** The options it takes, and hints for names people reach for instead. */
@@ -77,6 +86,8 @@ export class Texture {
77
86
  flipY = false
78
87
  /** @internal Bumped by needsUpdate() so renderers re-upload. */
79
88
  version = 0
89
+ /** What each recent update changed - its region, or null for all of it. @type {{ version: number, region: TextureRegion | null }[]} */
90
+ #changes = []
80
91
  /** Resolves when the image is available (immediately when one was given). @type {Promise<Texture>} */
81
92
  ready
82
93
 
@@ -180,11 +191,53 @@ export class Texture {
180
191
  /** @internal Whether the app chose the colour space, rather than leaving the default. @returns {boolean} */
181
192
  get colorSpaceSet() { return this.#colorSpaceSet }
182
193
 
183
- needsUpdate() {
194
+ /**
195
+ * Upload the image again, after drawing on it (a canvas) or changing its pixels. Give the
196
+ * rectangle that changed - in the image's pixels, from its top left - and only that is sent: for a
197
+ * big canvas drawn on a little at a time, far less to send each frame.
198
+ *
199
+ * ctx.fillRect(x, y, 20, 20)
200
+ * texture.needsUpdate({ x, y, width: 20, height: 20 })
201
+ * @param {TextureRegion} [region]
202
+ * @returns {this}
203
+ */
204
+ needsUpdate(region) {
205
+ /** @type {TextureRegion | null} */
206
+ let changed = null
207
+ if (region !== undefined) {
208
+ const { x, y, width, height } = region ?? /** @type {any} */ ({})
209
+ if (![x, y, width, height].every((v) => typeof v === 'number' && Number.isFinite(v)) || width < 0 || height < 0) {
210
+ fail('Texture', `needsUpdate() takes the region changed, { x, y, width, height } in the image's pixels, got ${describe(region)}`)
211
+ }
212
+ // whole pixels, covering every one the region touches
213
+ const x0 = Math.floor(x), y0 = Math.floor(y)
214
+ changed = { x: x0, y: y0, width: Math.ceil(x + width) - x0, height: Math.ceil(y + height) - y0 }
215
+ }
184
216
  this.version++
217
+ this.#changes.push({ version: this.version, region: changed })
218
+ if (this.#changes.length > CHANGES_KEPT) this.#changes.shift()
185
219
  return this
186
220
  }
187
221
 
222
+ /**
223
+ * @internal What changed since a version a renderer uploaded: each update's region since, or null
224
+ * when that's all of it - an update without a region, or one too long ago to know.
225
+ * @param {number} version
226
+ * @returns {TextureRegion[] | null}
227
+ */
228
+ changedSince(version) {
229
+ const first = this.#changes[0]
230
+ if (!first || first.version > version + 1) return null
231
+ /** @type {TextureRegion[]} */
232
+ const regions = []
233
+ for (const { version: v, region } of this.#changes) {
234
+ if (v <= version) continue
235
+ if (!region) return null
236
+ regions.push(region)
237
+ }
238
+ return regions.length ? regions : null
239
+ }
240
+
188
241
  /** Release the GPU copy. @returns {void} */
189
242
  dispose() {
190
243
  for (const fn of this.#onDispose) fn()
@@ -1,7 +1,8 @@
1
1
  // A particle system as one Points node: particles are born at the emitter's origin, move under
2
2
  // velocity, gravity and drag, fade through a list of colours and die. The simulation runs in the
3
3
  // emitter's own update handler, so it follows the scene clock (frame-rate independent) and its
4
- // arrays go to the GPU as one buffer refill per frame.
4
+ // arrays go to the GPU as one buffer refill per frame. Particles that grow, fade or turn give the
5
+ // geometry per-point sizes, opacities or angles, and are drawn as squares.
5
6
  import * as mat4 from '../math/mat4.js'
6
7
  import { Geometry } from '../geometry/Geometry.js'
7
8
  import { Material } from '../material/Material.js'
@@ -48,17 +49,32 @@ import { checkNumber, describe, fail } from '../validate.js'
48
49
  * frustumCulled?: boolean,
49
50
  * renderOrder?: number,
50
51
  * onParticle?: ((p: Particle) => boolean | void) | null,
51
- * }} EmitterOptions
52
+ * sort?: boolean,
53
+ * } & LookOptions} EmitterOptions
52
54
  * max: most live particles at once (default 1000). rate: particles born per second (default 100).
53
55
  * gravity: acceleration, e.g. [0, -9.8, 0] (default none). drag: share of velocity lost per second
54
56
  * (default 0). follow: a node whose position becomes the origin each frame - a trail that stays
55
57
  * behind it. onParticle: called for every live particle each frame after it moves; return false to
56
- * remove it (a particle hitting something).
58
+ * remove it (a particle hitting something). sort: draw furthest first, for soft particles with
59
+ * blending 'normal' (smoke) that would otherwise layer wrongly.
60
+ */
61
+
62
+ /**
63
+ * How particles look over their lives, beyond colour.
64
+ * @typedef {object} LookOptions
65
+ * @property {number | number[]} [size] a multiple of the material's size, or several each particle goes
66
+ * through over its life - [0.5, 3] for smoke that billows out (default 1)
67
+ * @property {number} [sizeSpread] each particle's size varies by up to this share either way, 0-1 (default 0)
68
+ * @property {number | number[]} [opacity] 0-1, or several each particle goes through - [0, 1, 0] fades in
69
+ * and out (default 1)
70
+ * @property {number | [number, number]} [spin] radians per second: a number turns each particle up to that
71
+ * fast either way, [min, max] a range. Spinning particles start at a random angle (default 0)
57
72
  */
58
73
 
59
74
  const SPAWN_OPTIONS = ['origin', 'originSpread', 'velocity', 'velocitySpread', 'lifetime', 'color']
60
- const OPTIONS = [...Points.OPTIONS, ...SPAWN_OPTIONS,
61
- 'max', 'rate', 'gravity', 'drag', 'follow', 'onParticle']
75
+ const LOOK_OPTIONS = ['size', 'sizeSpread', 'opacity', 'spin']
76
+ const BEHAVIOUR_OPTIONS = ['rate', 'gravity', 'drag', 'follow', 'onParticle', ...LOOK_OPTIONS]
77
+ const OPTIONS = [...Points.OPTIONS, ...SPAWN_OPTIONS, 'max', ...BEHAVIOUR_OPTIONS]
62
78
  const HINTS = {
63
79
  count: "use 'max' for the most particles alive at once, 'rate' for how many are born per second",
64
80
  lifetimeRnd: "give 'lifetime' a [min, max] range",
@@ -111,6 +127,13 @@ export class Emitter extends Points {
111
127
  /** @type {Map<string, number>} */ #paletteIds = new Map()
112
128
  /** @type {Uint8Array} */ #palette
113
129
  #spawnPalette = 0
130
+ // the looks: stops over each particle's life, and each one's own size factor and turn rate
131
+ /** @type {number[]} */ #size = [1]
132
+ #sizeSpread = 0
133
+ /** @type {number[]} */ #opacity = [1]
134
+ /** @type {[number, number]} */ #spin = [0, 0]
135
+ /** @type {Float32Array | null} */ #sizeFactors = null
136
+ /** @type {Float32Array | null} */ #spins = null
114
137
  /** Last frame's origin, so a moving source leaves an even trail rather than clumps. */
115
138
  #lastOrigin = /** @type {Vec3 | null} */ (null)
116
139
  #particle = /** @type {Particle} */ ({ position: new Vec3(), velocity: new Vec3(), age: 0, lifetime: 0 })
@@ -144,12 +167,12 @@ export class Emitter extends Points {
144
167
  /**
145
168
  * Change several settings at once - a preset, say. Vectors are copied into the emitter's own,
146
169
  * so anything bound to `emitter.gravity` and friends stays bound. Live particles carry on.
147
- * @param {SpawnOptions & { rate?: number, gravity?: Vec3Input, drag?: number, follow?: Node | null,
170
+ * @param {SpawnOptions & LookOptions & { rate?: number, gravity?: Vec3Input, drag?: number, follow?: Node | null,
148
171
  * onParticle?: ((p: Particle) => boolean | void) | null }} options
149
172
  * @returns {this}
150
173
  */
151
174
  set(options) {
152
- const known = [...SPAWN_OPTIONS, 'rate', 'gravity', 'drag', 'follow', 'onParticle']
175
+ const known = [...SPAWN_OPTIONS, ...BEHAVIOUR_OPTIONS]
153
176
  for (const key of Object.keys(options ?? {})) {
154
177
  if (!known.includes(key)) fail('Emitter', `set() doesn't take '${key}' - it takes ${known.join(', ')}`)
155
178
  }
@@ -169,6 +192,22 @@ export class Emitter extends Points {
169
192
  /** @returns {[number, number, number][]} */
170
193
  get color() { return /** @type {[number, number, number][]} */ (this.#palettes[0].map((s) => [...s])) }
171
194
 
195
+ /** Each particle's size over its life, as multiples of the material's. @param {number | number[]} v */
196
+ set size(v) { this.#setLooks({ size: v }) }
197
+ /** @returns {number[]} */
198
+ get size() { return [...this.#size] }
199
+ /** How much each particle's size varies, 0-1 either way. @param {number} v */
200
+ set sizeSpread(v) { this.#setLooks({ sizeSpread: v }) }
201
+ get sizeSpread() { return this.#sizeSpread }
202
+ /** Each particle's opacity over its life. @param {number | number[]} v */
203
+ set opacity(v) { this.#setLooks({ opacity: v }) }
204
+ /** @returns {number[]} */
205
+ get opacity() { return [...this.#opacity] }
206
+ /** How fast particles turn, radians per second, as a [min, max] range. @param {number | [number, number]} v */
207
+ set spin(v) { this.#setLooks({ spin: v }) }
208
+ /** @returns {[number, number]} */
209
+ get spin() { return [...this.#spin] }
210
+
172
211
  /**
173
212
  * Birth `count` particles at once - explosions, splashes. Options override the emitter's own
174
213
  * spawn settings for this burst only.
@@ -211,6 +250,7 @@ export class Emitter extends Points {
211
250
  const v = this.#velocities, ages = this.#ages, lives = this.#lifetimes
212
251
  const g = this.gravity, keep = Math.exp(-this.drag * dt)
213
252
  const hook = this.onParticle, particle = this.#particle
253
+ const angles = this.geometry.angles, spins = this.#spins
214
254
 
215
255
  for (let i = 0; i < this.#alive;) {
216
256
  const age = ages[i] += dt
@@ -223,6 +263,7 @@ export class Emitter extends Points {
223
263
  v[i3 + k] = (v[i3 + k] + g[k] * dt) * keep
224
264
  p[i3 + k] += v[i3 + k] * dt
225
265
  }
266
+ if (angles && spins) angles[i] += spins[i] * dt
226
267
  this.#paint(i, age / lives[i])
227
268
  if (hook) {
228
269
  particle.position.set(p[i3], p[i3 + 1], p[i3 + 2])
@@ -256,7 +297,7 @@ export class Emitter extends Points {
256
297
  const rest = super.cloneOptions()
257
298
  delete rest.geometry
258
299
  return { ...rest, ...this.#saveSpawn(), max: this.#max, rate: this.rate, gravity: this.gravity.clone(),
259
- drag: this.drag, follow: this.follow, onParticle: this.onParticle, color: this.color }
300
+ drag: this.drag, follow: this.follow, onParticle: this.onParticle, color: this.color, ...this.#looks() }
260
301
  }
261
302
 
262
303
  /** @internal @returns {Record<string, unknown>} */
@@ -266,7 +307,8 @@ export class Emitter extends Points {
266
307
  return { ...rest, max: this.#max, rate: this.rate, gravity: this.gravity.toArray(), drag: this.drag,
267
308
  origin: this.origin.toArray(), originSpread: this.originSpread, velocity: this.velocity.toArray(),
268
309
  velocitySpread: typeof this.velocitySpread === 'number' ? this.velocitySpread : this.velocitySpread.toArray(),
269
- lifetime: [...this.lifetime], color: this.#palettes[0].map((s) => new Color().setSRGB(s[0], s[1], s[2]).toJSON()) }
310
+ lifetime: [...this.lifetime], color: this.#palettes[0].map((s) => new Color().setSRGB(s[0], s[1], s[2]).toJSON()),
311
+ ...this.#looks() }
270
312
  }
271
313
 
272
314
  // birth one particle somewhere between a and b, already `head` seconds into its life
@@ -287,6 +329,12 @@ export class Emitter extends Points {
287
329
  this.#lifetimes[i] = min + Math.random() * (max - min)
288
330
  this.#ages[i] = head
289
331
  this.#palette[i] = this.#spawnPalette
332
+ if (this.#sizeFactors) this.#sizeFactors[i] = 1 + (Math.random() * 2 - 1) * this.#sizeSpread
333
+ const angles = this.geometry.angles, spins = this.#spins
334
+ if (angles && spins) {
335
+ spins[i] = this.#spin[0] + Math.random() * (this.#spin[1] - this.#spin[0])
336
+ angles[i] = Math.random() * Math.PI * 2 + spins[i] * head
337
+ }
290
338
  this.#paint(i, head / this.#lifetimes[i])
291
339
  }
292
340
 
@@ -302,10 +350,16 @@ export class Emitter extends Points {
302
350
  this.#ages[i] = this.#ages[last]
303
351
  this.#lifetimes[i] = this.#lifetimes[last]
304
352
  this.#palette[i] = this.#palette[last]
353
+ for (const a of [this.geometry.sizes, this.geometry.opacities, this.geometry.angles, this.#sizeFactors, this.#spins]) {
354
+ if (a) a[i] = a[last]
355
+ }
305
356
  }
306
357
 
307
358
  /** @param {number} i @param {number} t 0-1 through its life */
308
359
  #paint(i, t) {
360
+ const { sizes, opacities } = this.geometry
361
+ if (sizes) sizes[i] = along(this.#size, t) * (this.#sizeFactors ? this.#sizeFactors[i] : 1)
362
+ if (opacities) opacities[i] = along(this.#opacity, t)
309
363
  const c = /** @type {Float32Array} */ (this.geometry.colors), stops = this.#palettes[this.#palette[i]]
310
364
  if (stops.length === 1) {
311
365
  c.set(stops[0], i * 3)
@@ -349,8 +403,9 @@ export class Emitter extends Points {
349
403
  if (o.color !== undefined) this.#palettes[0] = colorStops(o.color)
350
404
  }
351
405
 
352
- /** @param {{ rate?: number, gravity?: Vec3Input, drag?: number, follow?: Node | null, onParticle?: ((p: Particle) => boolean | void) | null }} o */
406
+ /** @param {LookOptions & { rate?: number, gravity?: Vec3Input, drag?: number, follow?: Node | null, onParticle?: ((p: Particle) => boolean | void) | null }} o */
353
407
  #setBehaviour(o) {
408
+ this.#setLooks(o)
354
409
  const owner = 'Emitter'
355
410
  if (o.rate !== undefined) this.rate = Math.max(0, checkNumber(owner, 'rate', o.rate))
356
411
  if (o.gravity !== undefined) this.gravity.copy(o.gravity, owner)
@@ -359,6 +414,31 @@ export class Emitter extends Points {
359
414
  if (o.onParticle !== undefined) this.onParticle = o.onParticle
360
415
  }
361
416
 
417
+ // Sizes, opacities and angles go on the geometry when first wanted (the points are then drawn as
418
+ // squares) and stay; live particles get the plain values until they are next painted.
419
+ /** @param {LookOptions} o */
420
+ #setLooks(o) {
421
+ const owner = 'Emitter', g = this.geometry, max = this.#max
422
+ if (o.size !== undefined) this.#size = lookStops('size', o.size, Infinity)
423
+ if (o.sizeSpread !== undefined) this.#sizeSpread = Math.min(Math.max(checkNumber(owner, 'sizeSpread', o.sizeSpread), 0), 1)
424
+ if (o.opacity !== undefined) this.#opacity = lookStops('opacity', o.opacity, 1)
425
+ if (o.spin !== undefined) this.#spin = spinRange(o.spin)
426
+ const plain = (/** @type {number[]} */ stops) => stops.length === 1 && stops[0] === 1
427
+ if (!g.sizes && (!plain(this.#size) || this.#sizeSpread)) g.sizes = new Float32Array(max).fill(1)
428
+ if (!this.#sizeFactors && this.#sizeSpread) this.#sizeFactors = new Float32Array(max).fill(1)
429
+ if (!g.opacities && !plain(this.#opacity)) g.opacities = new Float32Array(max).fill(1)
430
+ if (!g.angles && (this.#spin[0] || this.#spin[1])) {
431
+ g.angles = new Float32Array(max)
432
+ this.#spins = new Float32Array(max)
433
+ }
434
+ }
435
+
436
+ /** The looks, as options. @returns {LookOptions} */
437
+ #looks() {
438
+ return { size: unstop(this.#size), sizeSpread: this.#sizeSpread, opacity: unstop(this.#opacity),
439
+ spin: /** @type {[number, number]} */ ([...this.#spin]) }
440
+ }
441
+
362
442
  /** The spawn settings other than colour, as options. @returns {SpawnOptions} */
363
443
  #saveSpawn() {
364
444
  return { origin: this.origin.clone(), originSpread: this.originSpread, velocity: this.velocity.clone(),
@@ -397,6 +477,37 @@ function lifetimeRange(v) {
397
477
  return [Math.min(range[0], range[1]), Math.max(range[0], range[1])]
398
478
  }
399
479
 
480
+ /** @param {string} name @param {number | number[]} v @param {number} most @returns {number[]} */
481
+ function lookStops(name, v, most) {
482
+ const list = Array.isArray(v) ? v : [v]
483
+ if (!list.length || !list.every((n) => typeof n === 'number' && Number.isFinite(n) && n >= 0)) {
484
+ fail('Emitter', `'${name}' must be a number of 0 or more, or a list of them a particle goes through, got ${describe(v)}`)
485
+ }
486
+ return list.map((n) => Math.min(n, most))
487
+ }
488
+
489
+ /** One stop as a number, several as a list. @param {number[]} stops @returns {number | number[]} */
490
+ function unstop(stops) {
491
+ return stops.length === 1 ? stops[0] : [...stops]
492
+ }
493
+
494
+ /** The value t (0-1) of the way through evenly spaced stops. @param {number[]} stops @param {number} t */
495
+ function along(stops, t) {
496
+ if (stops.length === 1) return stops[0]
497
+ const x = Math.min(Math.max(t, 0), 1) * (stops.length - 1)
498
+ const s = Math.min(Math.floor(x), stops.length - 2)
499
+ return stops[s] + (stops[s + 1] - stops[s]) * (x - s)
500
+ }
501
+
502
+ /** @param {number | [number, number]} v @returns {[number, number]} */
503
+ function spinRange(v) {
504
+ const range = typeof v === 'number' ? [-Math.abs(v), Math.abs(v)] : v
505
+ if (!Array.isArray(range) || range.length !== 2 || !range.every((n) => typeof n === 'number' && Number.isFinite(n))) {
506
+ fail('Emitter', `'spin' must be radians per second, or a [min, max] range, got ${describe(v)}`)
507
+ }
508
+ return [Math.min(range[0], range[1]), Math.max(range[0], range[1])]
509
+ }
510
+
400
511
  /** @param {ColorInput | ColorInput[]} v @returns {number[][]} */
401
512
  function colorStops(v) {
402
513
  // a single [r, g, b] array is one colour, not three
@@ -215,7 +215,9 @@ export class Drawable extends Node {
215
215
 
216
216
  /** @internal @param {Box3} box */
217
217
  expandBounds(box) {
218
- if (this.geometry.vertexCount) box.union(this.geometry.bounds.clone().applyMatrix4(this.worldMatrix))
218
+ if (!this.geometry.vertexCount) return box
219
+ const own = this.geometry.bounds.clone().applyMatrix4(this.worldMatrix)
220
+ box.union(padForHooks(own, this.material))
219
221
  return box
220
222
  }
221
223
 
@@ -249,7 +251,7 @@ export class Drawable extends Node {
249
251
  dispose() {
250
252
  this.geometry.dispose()
251
253
  this.material.dispose()
252
- for (const [, t] of this.material.textures) t.dispose()
254
+ for (const [, t] of this.material.allTextures) t.dispose()
253
255
  super.dispose()
254
256
  }
255
257
  }
@@ -411,9 +413,11 @@ export class InstancedMesh extends Mesh {
411
413
 
412
414
  /** @internal @param {Box3} box */
413
415
  expandBounds(box) {
416
+ // as far as a shader hook can move a vertex, round each copy
417
+ const pad = this.material.shader?.vertex ? this.material.shader.bounds ?? 0 : 0
414
418
  this.eachInstanceBox((x0, y0, z0, x1, y1, z1) => {
415
- box.expandByXYZ(x0, y0, z0)
416
- box.expandByXYZ(x1, y1, z1)
419
+ box.expandByXYZ(x0 - pad, y0 - pad, z0 - pad)
420
+ box.expandByXYZ(x1 + pad, y1 + pad, z1 + pad)
417
421
  })
418
422
  return box
419
423
  }
@@ -466,20 +470,44 @@ export class InstancedMesh extends Mesh {
466
470
  /** Each vertex drawn as a square point sprite: star fields, particles, scatter plots. */
467
471
  export class Points extends Drawable {
468
472
  static type = 'points'
469
- static get OPTIONS() { return [...DRAWABLE_OPTIONS, 'labels'] }
473
+ static get OPTIONS() { return [...DRAWABLE_OPTIONS, 'labels', 'sort'] }
470
474
 
471
475
  /** A label per point from its row of data - or a list of them, several per point. @type {ReturnType<typeof instanceLabels>} */
472
476
  labels = null
477
+ /**
478
+ * Draw the points back to front, furthest first, each frame - for soft points that cover what is
479
+ * behind them (smoke, with blending 'normal'), which then layer the right way round. Drawn as squares.
480
+ */
481
+ sort = false
473
482
 
474
- /** @param {DrawableOptions & { labels?: InstanceLabels | InstanceLabels[] | null }} options */
483
+ /** @param {DrawableOptions & { labels?: InstanceLabels | InstanceLabels[] | null, sort?: boolean }} options */
475
484
  constructor(options) {
476
485
  super(options)
477
486
  this.labels = instanceLabels(this.constructor.name, options?.labels)
487
+ if (options?.sort !== undefined) {
488
+ if (typeof options.sort !== 'boolean') fail(this.constructor.name, `'sort' is true or false, got ${describe(options.sort)}`)
489
+ this.sort = options.sort
490
+ }
491
+ }
492
+
493
+ /**
494
+ * @internal Drawn as squares, one a point, rather than as GL points: when the geometry gives each
495
+ * point its own size, opacity or angle, or the points are sorted. Squares can be any size and stay
496
+ * whole at the edge of the view.
497
+ */
498
+ get drawsSprites() {
499
+ const g = this.geometry
500
+ return this.sort || !!(g.sizes || g.opacities || g.angles)
478
501
  }
479
502
 
480
503
  /** @internal @returns {Record<string, unknown>} */
481
504
  cloneOptions() {
482
- return { ...super.cloneOptions(), labels: this.labels }
505
+ return { ...super.cloneOptions(), labels: this.labels, sort: this.sort }
506
+ }
507
+
508
+ /** @internal @returns {Record<string, unknown>} */
509
+ jsonOptions() {
510
+ return { ...super.jsonOptions(), ...(this.sort ? { sort: true } : {}) }
483
511
  }
484
512
 
485
513
  /** @returns {'points'} */
@@ -488,12 +516,52 @@ export class Points extends Drawable {
488
516
  }
489
517
  }
490
518
 
519
+ const ARROWS = ['none', 'start', 'end', 'both']
520
+
521
+ /**
522
+ * @typedef {DrawableOptions & { arrows?: 'none' | 'start' | 'end' | 'both', arrowSize?: number }} LinesOptions
523
+ */
524
+
491
525
  /**
492
526
  * Line segments: indices (or consecutive vertices) in pairs. Width is in pixels and works on
493
- * every platform. edges(geometry) makes a wireframe of any geometry.
527
+ * every platform. edges(geometry) makes a wireframe of any geometry. Segments each starting where
528
+ * the one before ended make a chain - a polyline - which dashes run on along and arrowheads finish.
494
529
  */
495
530
  export class Lines extends Drawable {
496
531
  static type = 'lines'
532
+ static get OPTIONS() { return [...DRAWABLE_OPTIONS, 'arrows', 'arrowSize'] }
533
+
534
+ /** Arrowheads at the ends of each chain: at its 'start', its 'end', 'both' or 'none'. @type {'none' | 'start' | 'end' | 'both'} */
535
+ arrows = 'none'
536
+ /** Arrowhead length in pixels; 0 sizes them from the material's width. */
537
+ arrowSize = 0
538
+
539
+ /** @param {LinesOptions} options */
540
+ constructor(options) {
541
+ super(options)
542
+ if (options?.arrows !== undefined) this.arrows = /** @type {any} */ (checkOneOf('Lines', 'arrows', options.arrows, ARROWS))
543
+ if (options?.arrowSize !== undefined) this.arrowSize = Math.max(0, checkNumber('Lines', 'arrowSize', options.arrowSize))
544
+ }
545
+
546
+ /** @internal Which ends get arrowheads, for the shader: 1 the start, 2 the end. */
547
+ get arrowBits() {
548
+ return ARROWS.indexOf(this.arrows)
549
+ }
550
+
551
+ /** @internal An arrowhead's length in pixels, before the pixel ratio. @param {number} width */
552
+ arrowPixels(width) {
553
+ return this.arrowSize || 6 + width * 3
554
+ }
555
+
556
+ /** @internal @returns {Record<string, unknown>} */
557
+ cloneOptions() {
558
+ return { ...super.cloneOptions(), arrows: this.arrows, arrowSize: this.arrowSize }
559
+ }
560
+
561
+ /** @internal @returns {Record<string, unknown>} */
562
+ jsonOptions() {
563
+ return { ...super.jsonOptions(), ...(this.arrows !== 'none' ? { arrows: this.arrows } : {}), ...(this.arrowSize ? { arrowSize: this.arrowSize } : {}) }
564
+ }
497
565
 
498
566
  /** @returns {'lines'} */
499
567
  get drawMode() {
@@ -583,3 +651,16 @@ export class Label extends Node {
583
651
  return json
584
652
  }
585
653
  }
654
+
655
+ /**
656
+ * A drawable's world box, grown by as far as its shader's vertex hook says it can move a vertex.
657
+ * @param {import('../value/Box3.js').Box3} box @param {import('../material/Material.js').Material} material
658
+ */
659
+ function padForHooks(box, material) {
660
+ const pad = material.shader?.vertex ? material.shader.bounds ?? 0 : 0
661
+ if (pad > 0 && !box.isEmpty()) {
662
+ box.min.set(box.min[0] - pad, box.min[1] - pad, box.min[2] - pad)
663
+ box.max.set(box.max[0] + pad, box.max[1] + pad, box.max[2] + pad)
664
+ }
665
+ return box
666
+ }
package/src/watch.js CHANGED
@@ -10,6 +10,8 @@
10
10
  /** @type {WeakMap<object, number>} */
11
11
  const ids = new WeakMap()
12
12
  let nextId = 1
13
+ /** Does a material's shader hook read the clock? @param {{ vertex: string, fragment: string, lit: string }} h */
14
+ export const usesTime = (h) => /\buTime\b/.test(h.vertex + h.fragment + h.lit)
13
15
  /** @param {object} o */
14
16
  const idOf = (o) => {
15
17
  let id = ids.get(o)
@@ -24,14 +26,17 @@ export class ChangeWatch {
24
26
  #previousCount = -1
25
27
  /** @type {string[]} */ #strings = []
26
28
  /** @type {string[]} */ #previousStrings = []
29
+ #time = 0
27
30
 
28
31
  /**
29
32
  * Has anything that affects the picture changed since the last call? The first call says yes.
30
33
  * @param {Scene} scene
31
34
  * @param {Camera} camera
35
+ * @param {number} [time] the View's clock, which shader hooks reading uTime follow
32
36
  * @returns {boolean}
33
37
  */
34
- changed(scene, camera) {
38
+ changed(scene, camera, time = 0) {
39
+ this.#time = time
35
40
  this.#count = 0
36
41
  this.#strings = []
37
42
  this.#camera(camera)
@@ -147,7 +152,11 @@ export class ChangeWatch {
147
152
  this.#push(g.version)
148
153
  this.#push(g.drawCount ?? -1)
149
154
  this.#push(node.renderOrder)
150
- this.#push((node.castShadow ? 1 : 0) | (node.receiveShadow ? 2 : 0))
155
+ this.#push((node.castShadow ? 1 : 0) | (node.receiveShadow ? 2 : 0) | (node.sort ? 4 : 0))
156
+ if ('arrowBits' in node) {
157
+ this.#push(node.arrowBits)
158
+ this.#push(node.arrowSize)
159
+ }
151
160
  // per-instance labels come from these, so swapping either redraws
152
161
  this.#push(node.labels ? idOf(node.labels) : 0)
153
162
  this.#push(node.data && typeof node.data === 'object' ? idOf(node.data) : 0)
@@ -164,6 +173,9 @@ export class ChangeWatch {
164
173
  this.#push(m.metalness)
165
174
  this.#push(m.size)
166
175
  this.#push(m.width)
176
+ this.#push(m.dash)
177
+ this.#push(m.gap)
178
+ this.#push(m.dashOffset)
167
179
  this.#push(m.alphaTest)
168
180
  this.#push(m.normalScale)
169
181
  this.#push(m.aoMapIntensity)
@@ -187,7 +199,18 @@ export class ChangeWatch {
187
199
  this.#pushAll(m.translucencyColor)
188
200
  this.#push((m.unlit ? 1 : 0) | (m.flatShading ? 2 : 0) | (m.doubleSided ? 4 : 0) | (m.vertexColors ? 8 : 0) |
189
201
  (m.depthWrite ? 16 : 0) | (m.depthTest ? 32 : 0) | (m.sizeAttenuation ? 64 : 0) | (m.blending === 'additive' ? 128 : m.blending === 'multiply' ? 1024 : 0) | (m.transparent ? 256 : 0) | (m.fog ? 512 : 0))
190
- for (const [, texture] of m.textures) this.#texture(texture)
202
+ for (const [, texture] of m.allTextures) this.#texture(texture)
203
+ const hooks = m.shader
204
+ if (hooks) {
205
+ this.#push(idOf(hooks))
206
+ for (const v of Object.values(hooks.uniforms)) {
207
+ if (typeof v === 'number') this.#push(v)
208
+ // numbers and colours - textures count through their versions, above
209
+ else if (Array.isArray(v) || ArrayBuffer.isView(v)) this.#pushAll(/** @type {ArrayLike<number>} */ (v))
210
+ }
211
+ // a hook that reads the clock moves on its own while time runs
212
+ if (usesTime(hooks)) this.#push(this.#time)
213
+ }
191
214
  }
192
215
 
193
216
  /** @param {any} texture */