roamwright 0.0.0-stage → 0.1.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.
- package/CONTRIBUTING.md +12 -0
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/examples/index.html +19 -0
- package/examples/island.js +62 -0
- package/geometry/builder.js +546 -0
- package/geometry/instances.js +76 -0
- package/geometry/placement.js +65 -0
- package/geometry/primitives.js +172 -0
- package/index.js +8 -0
- package/licenses/baking-lab.txt +21 -0
- package/licenses/fidelityfx-fsr.txt +19 -0
- package/licenses/three.txt +21 -0
- package/math/curve.js +94 -0
- package/math/noise.js +80 -0
- package/math/random.js +27 -0
- package/math/scalar.js +12 -0
- package/motion/player.js +248 -0
- package/motion/spaces.js +206 -0
- package/package.json +50 -4
- package/rendering/context.js +20 -0
- package/rendering/dof.js +59 -0
- package/rendering/eye-adapt.js +119 -0
- package/rendering/piece-batch.js +411 -0
- package/rendering/post-shaders.js +236 -0
- package/rendering/post.js +520 -0
- package/rendering/still-casters.js +37 -0
- package/rendering/taa.js +171 -0
- package/rendering/textures.js +63 -0
- package/rendering/world-matrices.js +77 -0
- package/runtime/first-use.js +60 -0
- package/runtime/gpu-timing.js +75 -0
- package/runtime/hand-over.js +102 -0
- package/runtime/pool.js +153 -0
- package/runtime/quality-fit.js +194 -0
- package/runtime/quality-store.js +58 -0
- package/runtime/seen.js +36 -0
- package/runtime/worker.js +53 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
import { QUAD_VS } from './post-shaders.js';
|
|
3
|
+
|
|
4
|
+
// ════════════════════════════════════════════════════════════════════════
|
|
5
|
+
// The eye's adaptation: how bright the picture is, metered on the card each frame (centre-weighted, as a camera meters) and
|
|
6
|
+
// followed slowly, so that stepping from the street into a dark room opens the eye over a second or two, and facing a bright
|
|
7
|
+
// sky closes it. The meter never leaves the card (no reading back, which would stall the frame): the scene is boiled down to
|
|
8
|
+
// one texel of mean log brightness, and a second texel follows it over time; the final pass reads that one (tEye).
|
|
9
|
+
// The eye adapts only round what the hour leads one to expect (ref, from the sun's height), and by a part of the difference,
|
|
10
|
+
// held within a stop or so: night stays night and noon noon, as they were graded; what changes is a dark room, a bright sky.
|
|
11
|
+
// ════════════════════════════════════════════════════════════════════════
|
|
12
|
+
const METER = { w: 64, h: 36 }, // the first boiled-down picture, in texels: each takes 16 samples of the scene
|
|
13
|
+
REDUCED = { w: 16, h: 9 }, // then 4 x 4 of those to a texel, then all of these to one
|
|
14
|
+
SPEED = { brighter: 2.4, darker: 0.9 }; // how fast the eye follows, a share a second: it closes on light faster than it opens in the dark
|
|
15
|
+
|
|
16
|
+
const LUM = `/* glsl */ float logLum(vec3 c){ return log2(max(dot(c, vec3(0.2126, 0.7152, 0.0722)), 1e-4)); }`;
|
|
17
|
+
// The scene to METER: the log brightness of 4 x 4 samples in each texel's span, weighted toward the middle of the picture, as (sum of
|
|
18
|
+
// weighted values, sum of weights) so later steps may average both and divide at the end.
|
|
19
|
+
const METER_FS = `/* glsl */ uniform sampler2D tSrc; uniform vec2 uSpan; varying vec2 vUv; ${LUM}
|
|
20
|
+
void main(){
|
|
21
|
+
float w = 1.0 - 0.75 * smoothstep(0.1, 0.75, length((vUv - 0.5) * vec2(1.6, 1.0)));
|
|
22
|
+
float s = 0.0;
|
|
23
|
+
for (int j = 0; j < 4; j++) for (int i = 0; i < 4; i++) {
|
|
24
|
+
vec3 c = texture2D(tSrc, vUv + (vec2(float(i), float(j)) - 1.5) * 0.25 * uSpan).rgb;
|
|
25
|
+
s += logLum(clamp(c, 0.0, 64.0)); // an invalid or blinding pixel counts as bright, never as infinite
|
|
26
|
+
}
|
|
27
|
+
gl_FragColor = vec4(s / 16.0 * w, w, 0.0, 1.0);
|
|
28
|
+
}`;
|
|
29
|
+
// Averages uN.x x uN.y texels of the source into one, keeping the two sums: one program for both steps, its loops running to the
|
|
30
|
+
// larger block and stopping at uN, so each step sums the same texels in the same order as loops of its own length did.
|
|
31
|
+
const REDUCE_FS = `/* glsl */ uniform sampler2D tSrc; uniform vec2 uPx; uniform ivec2 uN; varying vec2 vUv;
|
|
32
|
+
void main(){
|
|
33
|
+
vec2 s = vec2(0.0);
|
|
34
|
+
vec2 o = vUv - (vec2(uN) * 0.5 - 0.5) * uPx;
|
|
35
|
+
for (int j = 0; j < ${REDUCED.h}; j++) {
|
|
36
|
+
if (j >= uN.y) break;
|
|
37
|
+
for (int i = 0; i < ${REDUCED.w}; i++) { if (i >= uN.x) break; s += texture2D(tSrc, o + vec2(float(i), float(j)) * uPx).rg; }
|
|
38
|
+
}
|
|
39
|
+
gl_FragColor = vec4(s / float(uN.x * uN.y), 0.0, 1.0);
|
|
40
|
+
}`;
|
|
41
|
+
// The eye: last frame's level moved toward this frame's mean by its share of the time passed.
|
|
42
|
+
const ADAPT_FS = `/* glsl */ uniform sampler2D tMean, tPrev; uniform float uDt, uFirst; varying vec2 vUv;
|
|
43
|
+
void main(){
|
|
44
|
+
vec2 m = texture2D(tMean, vec2(0.5)).rg;
|
|
45
|
+
float now = m.r / max(m.g, 1e-4), prev = texture2D(tPrev, vec2(0.5)).r;
|
|
46
|
+
float k = 1.0 - exp(-uDt * (now > prev ? ${SPEED.brighter.toFixed(2)} : ${SPEED.darker.toFixed(2)}));
|
|
47
|
+
gl_FragColor = vec4(uFirst > 0.5 ? now : prev + (now - prev) * k, 0.0, 0.0, 1.0);
|
|
48
|
+
}`;
|
|
49
|
+
|
|
50
|
+
const target = (w, h, format) =>
|
|
51
|
+
new THREE.WebGLRenderTarget(w, h, {
|
|
52
|
+
type: THREE.HalfFloatType,
|
|
53
|
+
format,
|
|
54
|
+
depthBuffer: false,
|
|
55
|
+
minFilter: THREE.NearestFilter,
|
|
56
|
+
magFilter: THREE.NearestFilter,
|
|
57
|
+
});
|
|
58
|
+
const pass = (fragmentShader, uniforms) =>
|
|
59
|
+
new THREE.ShaderMaterial({ depthTest: false, depthWrite: false, vertexShader: QUAD_VS, fragmentShader, uniforms });
|
|
60
|
+
|
|
61
|
+
export function createEyeAdaptation() {
|
|
62
|
+
// The meter's targets and passes, made once for the page; eye.level is the texture the final pass reads.
|
|
63
|
+
const meter = target(METER.w, METER.h, THREE.RGFormat),
|
|
64
|
+
reduced = target(REDUCED.w, REDUCED.h, THREE.RGFormat),
|
|
65
|
+
mean = target(1, 1, THREE.RGFormat),
|
|
66
|
+
levels = [target(1, 1, THREE.RedFormat), target(1, 1, THREE.RedFormat)],
|
|
67
|
+
meterMat = pass(METER_FS, { tSrc: { value: null }, uSpan: { value: new THREE.Vector2(1 / METER.w, 1 / METER.h) } }),
|
|
68
|
+
reduceMat = pass(REDUCE_FS, {
|
|
69
|
+
tSrc: { value: meter.texture },
|
|
70
|
+
uPx: { value: new THREE.Vector2(1 / METER.w, 1 / METER.h) },
|
|
71
|
+
uN: { value: new THREE.Vector2(METER.w / REDUCED.w, METER.h / REDUCED.h) },
|
|
72
|
+
}),
|
|
73
|
+
meanMat = pass(REDUCE_FS, {
|
|
74
|
+
tSrc: { value: reduced.texture },
|
|
75
|
+
uPx: { value: new THREE.Vector2(1 / REDUCED.w, 1 / REDUCED.h) },
|
|
76
|
+
uN: { value: new THREE.Vector2(REDUCED.w, REDUCED.h) },
|
|
77
|
+
}),
|
|
78
|
+
adaptMat = pass(ADAPT_FS, { tMean: { value: mean.texture }, tPrev: { value: null }, uDt: { value: 0 }, uFirst: { value: 1 } }),
|
|
79
|
+
quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), meterMat),
|
|
80
|
+
quadScene = new THREE.Scene(),
|
|
81
|
+
quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
|
|
82
|
+
quad.frustumCulled = false;
|
|
83
|
+
quadScene.add(quad);
|
|
84
|
+
const eye = { level: levels[0].texture, flip: 0, last: 0 };
|
|
85
|
+
|
|
86
|
+
function draw(rn, material, into) {
|
|
87
|
+
quad.material = material;
|
|
88
|
+
rn.setRenderTarget(into);
|
|
89
|
+
rn.render(quadScene, quadCam);
|
|
90
|
+
}
|
|
91
|
+
// Meters the scene's picture (a texture of light before tone mapping) and moves the eye on; a pause of more than a second (a
|
|
92
|
+
// crossing, a page that was hidden) starts the eye afresh where it looks.
|
|
93
|
+
function adaptEye(rn, sceneTexture) {
|
|
94
|
+
const now = performance.now(),
|
|
95
|
+
dt = (now - eye.last) / 1000;
|
|
96
|
+
eye.last = now;
|
|
97
|
+
meterMat.uniforms.tSrc.value = sceneTexture;
|
|
98
|
+
draw(rn, meterMat, meter);
|
|
99
|
+
draw(rn, reduceMat, reduced);
|
|
100
|
+
draw(rn, meanMat, mean);
|
|
101
|
+
const from = levels[eye.flip],
|
|
102
|
+
into = levels[1 - eye.flip];
|
|
103
|
+
adaptMat.uniforms.tPrev.value = from.texture;
|
|
104
|
+
adaptMat.uniforms.uDt.value = Math.min(dt, 0.1);
|
|
105
|
+
adaptMat.uniforms.uFirst.value = dt > 1 ? 1 : 0;
|
|
106
|
+
draw(rn, adaptMat, into);
|
|
107
|
+
eye.flip = 1 - eye.flip;
|
|
108
|
+
eye.level = into.texture;
|
|
109
|
+
}
|
|
110
|
+
// The meter's materials with the targets they draw into, for warming their programs before the first frame.
|
|
111
|
+
const eyeMaterials = () => [
|
|
112
|
+
[meterMat, meter],
|
|
113
|
+
[reduceMat, reduced],
|
|
114
|
+
[meanMat, mean],
|
|
115
|
+
[adaptMat, levels[0]],
|
|
116
|
+
];
|
|
117
|
+
|
|
118
|
+
return { adaptEye, eye, eyeMaterials };
|
|
119
|
+
}
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import * as THREE from 'three';
|
|
2
|
+
|
|
3
|
+
const GL_TYPE = new Map([
|
|
4
|
+
[Float32Array, 5126],
|
|
5
|
+
[Int8Array, 5120],
|
|
6
|
+
[Uint8Array, 5121],
|
|
7
|
+
]);
|
|
8
|
+
const GL_UNSIGNED_INT = 5125,
|
|
9
|
+
INDEX_BYTES = 4,
|
|
10
|
+
PACK_LEAST = 65536; // a batch is packed only if it has room for at least this many vertices
|
|
11
|
+
// How a batch's buffers fit its pieces: `growth`, how much larger they are made when they are full; `use`, the share of them its
|
|
12
|
+
// pieces must fill for it not to be packed (pack); `room`, how much larger than its pieces the buffers it is packed into are.
|
|
13
|
+
// TIGHT trades more frequent GPU copies for less unused buffer capacity.
|
|
14
|
+
const LOOSE = { growth: 1.5, use: 2 / 3, room: 1.2 },
|
|
15
|
+
TIGHT = { growth: 1.2, use: 0.8, room: 1.1 };
|
|
16
|
+
// Runs of items in a buffer: a new run takes the first gap it fits, or goes at the end
|
|
17
|
+
class Runs {
|
|
18
|
+
constructor(end = 0) {
|
|
19
|
+
this.end = end; // the first item after the last run
|
|
20
|
+
this.gaps = []; // [start, count] of let-go runs before `end`, in order
|
|
21
|
+
}
|
|
22
|
+
claim(count) {
|
|
23
|
+
for (let i = 0; i < this.gaps.length; i++) {
|
|
24
|
+
const gap = this.gaps[i];
|
|
25
|
+
if (gap[1] < count) continue;
|
|
26
|
+
const start = gap[0];
|
|
27
|
+
if (gap[1] === count) this.gaps.splice(i, 1);
|
|
28
|
+
else this.gaps[i] = [start + count, gap[1] - count];
|
|
29
|
+
return start;
|
|
30
|
+
}
|
|
31
|
+
const start = this.end;
|
|
32
|
+
this.end += count;
|
|
33
|
+
return start;
|
|
34
|
+
}
|
|
35
|
+
release(start, count) {
|
|
36
|
+
if (start + count === this.end) {
|
|
37
|
+
this.end = start;
|
|
38
|
+
const last = this.gaps[this.gaps.length - 1];
|
|
39
|
+
if (last && last[0] + last[1] === this.end) this.end = this.gaps.pop()[0];
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
let i = 0;
|
|
43
|
+
while (i < this.gaps.length && this.gaps[i][0] < start) i++;
|
|
44
|
+
this.gaps.splice(i, 0, [start, count]);
|
|
45
|
+
for (const at of [i, i - 1]) {
|
|
46
|
+
const a = this.gaps[at],
|
|
47
|
+
b = this.gaps[at + 1];
|
|
48
|
+
if (a && b && a[0] + a[1] === b[0]) this.gaps.splice(at, 2, [a[0], a[1] + b[1]]);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Create a mesh class bound to a renderer and its main camera. All instances
|
|
55
|
+
* share sorting scratch space and the WebGL multi-draw extension for that
|
|
56
|
+
* context. Shadow hooks optionally integrate a cache of static point shadows.
|
|
57
|
+
* Supply static triangle geometry with matching layouts and indexing to each
|
|
58
|
+
* batch. Attributes use contiguous Float32Array, Int8Array or Uint8Array data.
|
|
59
|
+
*/
|
|
60
|
+
export function createPieceBatch({ renderer, camera, markStill = () => {}, isStill = () => false, keptAway = () => false }) {
|
|
61
|
+
const _clip = new THREE.Matrix4(),
|
|
62
|
+
_view = new THREE.Frustum(),
|
|
63
|
+
_seen = []; // the pieces a camera sees, by their place in _keys (kept from frame to frame: never emptied, only written over)
|
|
64
|
+
// The pieces are put in order by one number each, sorted in place by the typed array's own sort, which makes nothing: an array's
|
|
65
|
+
// sort copied the list each time, and a comparator's result was a new number (hundreds of batches a frame). A key is the piece's
|
|
66
|
+
// depth in steps of DEPTH_STEP metres, from DEPTH_FROM, times PIECES_MOST, plus its place in _seen.
|
|
67
|
+
const DEPTH_STEP = 1 / 16,
|
|
68
|
+
DEPTH_FROM = -1024,
|
|
69
|
+
PIECES_MOST = 65536;
|
|
70
|
+
let _keys = new Float64Array(64);
|
|
71
|
+
// The i-th of `seen` pieces in order, nearest first (farthest first, from the end of the keys, where `far`)
|
|
72
|
+
const nthSeen = (i, seen, far) => _seen[_keys[far ? seen - 1 - i : i] % PIECES_MOST];
|
|
73
|
+
let multi; // the multi-draw extension, or null where the browser has none (the pieces are then drawn one by one)
|
|
74
|
+
|
|
75
|
+
return class PieceBatch extends THREE.Mesh {
|
|
76
|
+
// vertices, indices: how many to make room for at first (a batch that is filled once says exactly how many); fit: LOOSE or TIGHT
|
|
77
|
+
constructor(material, vertices = 0, indices = 0, fit = LOOSE) {
|
|
78
|
+
super(new THREE.BufferGeometry(), material);
|
|
79
|
+
this.room = { vertices, indices };
|
|
80
|
+
this.fit = fit;
|
|
81
|
+
this.held = { vertices: 0, indices: 0 }; // what the buffers have room for
|
|
82
|
+
this.used = { vertices: 0, indices: 0 }; // and what the pieces fill
|
|
83
|
+
this.vertexRuns = new Runs();
|
|
84
|
+
this.indexRuns = new Runs();
|
|
85
|
+
this.layout = null; // [name, array type, item size, normalized] of each attribute, from the first piece
|
|
86
|
+
this.indices = null; // an indexed batch keeps its indices here as well, to fill a larger buffer from when it grows
|
|
87
|
+
this.pieces = []; // by id: { vertexStart, vertexCount, start, count, sphere, shown, depth }, or null where one was removed
|
|
88
|
+
this.spare = []; // ids to give out again
|
|
89
|
+
this.starts = new Int32Array(16); // the pieces after the first that the pass being drawn sees: where each begins (in bytes, if indexed)
|
|
90
|
+
this.counts = new Int32Array(16);
|
|
91
|
+
this.rest = 0;
|
|
92
|
+
this.restTriangles = 0;
|
|
93
|
+
this.pointShadow = true; // whether it casts in a point light's shadow as well as directional shadows
|
|
94
|
+
this.changes = 0; // how many times a piece was added, let go, shown or hidden: a cached point shadow tracks this revision
|
|
95
|
+
markStill(this); // a batch never moves
|
|
96
|
+
this.matrixAutoUpdate = false;
|
|
97
|
+
this.bound();
|
|
98
|
+
}
|
|
99
|
+
// Writes a geometry's vertices (and indices) to the card and returns the piece's id. The geometry itself is not kept and never uploaded.
|
|
100
|
+
// first, count: the part of an indexed geometry's indices that makes the piece (one of its groups); all of them if not given.
|
|
101
|
+
add(geometry, first = 0, count = geometry.index ? geometry.index.count : geometry.attributes.position.count) {
|
|
102
|
+
const vertexCount = geometry.attributes.position.count,
|
|
103
|
+
index = geometry.index,
|
|
104
|
+
gl = renderer.getContext();
|
|
105
|
+
if (!this.layout) {
|
|
106
|
+
this.layout = Object.entries(geometry.attributes).map(([name, a]) => [name, a.array.constructor, a.itemSize, a.normalized]);
|
|
107
|
+
if (index) this.indices = new Uint32Array(0);
|
|
108
|
+
}
|
|
109
|
+
const { vertexStart, start } = this.claim(vertexCount, count);
|
|
110
|
+
for (const [name, , itemSize] of this.layout) {
|
|
111
|
+
const array = geometry.attributes[name].array;
|
|
112
|
+
gl.bindBuffer(gl.COPY_WRITE_BUFFER, this.geometry.attributes[name].buffer);
|
|
113
|
+
gl.bufferSubData(gl.COPY_WRITE_BUFFER, vertexStart * itemSize * array.BYTES_PER_ELEMENT, array);
|
|
114
|
+
}
|
|
115
|
+
if (index) this.writeIndices(start, count, i => index.array[first + i] + vertexStart);
|
|
116
|
+
gl.bindBuffer(gl.COPY_WRITE_BUFFER, null);
|
|
117
|
+
if (!geometry.boundingSphere) geometry.computeBoundingSphere();
|
|
118
|
+
return this.record({ vertexStart, vertexCount, start, count, sphere: geometry.boundingSphere.clone() });
|
|
119
|
+
}
|
|
120
|
+
// Moves a piece into another batch of the same layout (one drawn in another material), copied from buffer to buffer on the card;
|
|
121
|
+
// returns its id there
|
|
122
|
+
move(id, to) {
|
|
123
|
+
const piece = this.pieces[id],
|
|
124
|
+
gl = renderer.getContext();
|
|
125
|
+
if (!to.layout) {
|
|
126
|
+
to.layout = this.layout;
|
|
127
|
+
if (this.indices) to.indices = new Uint32Array(0);
|
|
128
|
+
}
|
|
129
|
+
const { vertexStart, start } = to.claim(piece.vertexCount, piece.count);
|
|
130
|
+
for (const [name, type, itemSize] of this.layout) {
|
|
131
|
+
const bytes = itemSize * type.BYTES_PER_ELEMENT;
|
|
132
|
+
gl.bindBuffer(gl.COPY_READ_BUFFER, this.geometry.attributes[name].buffer);
|
|
133
|
+
gl.bindBuffer(gl.COPY_WRITE_BUFFER, to.geometry.attributes[name].buffer);
|
|
134
|
+
gl.copyBufferSubData(
|
|
135
|
+
gl.COPY_READ_BUFFER,
|
|
136
|
+
gl.COPY_WRITE_BUFFER,
|
|
137
|
+
piece.vertexStart * bytes,
|
|
138
|
+
vertexStart * bytes,
|
|
139
|
+
piece.vertexCount * bytes,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
gl.bindBuffer(gl.COPY_READ_BUFFER, null);
|
|
143
|
+
if (this.indices) to.writeIndices(start, piece.count, i => this.indices[piece.start + i] - piece.vertexStart + vertexStart);
|
|
144
|
+
gl.bindBuffer(gl.COPY_WRITE_BUFFER, null);
|
|
145
|
+
const moved = to.record({ vertexStart, vertexCount: piece.vertexCount, start, count: piece.count, sphere: piece.sphere });
|
|
146
|
+
this.remove(id);
|
|
147
|
+
return moved;
|
|
148
|
+
}
|
|
149
|
+
// Room in the buffers for a piece of `vertexCount` vertices and `count` indices (if indexed), grown if need be
|
|
150
|
+
claim(vertexCount, count) {
|
|
151
|
+
const vertexStart = this.vertexRuns.claim(vertexCount),
|
|
152
|
+
start = this.indices ? this.indexRuns.claim(count) : vertexStart;
|
|
153
|
+
if (this.vertexRuns.end > this.held.vertices || this.indexRuns.end > this.held.indices) this.grow();
|
|
154
|
+
return { vertexStart, start };
|
|
155
|
+
}
|
|
156
|
+
// A piece's `count` indices from `start` on, index(i) each, kept here and written to the card
|
|
157
|
+
writeIndices(start, count, index) {
|
|
158
|
+
const gl = renderer.getContext(),
|
|
159
|
+
own = this.indices.subarray(start, start + count);
|
|
160
|
+
for (let i = 0; i < count; i++) own[i] = index(i);
|
|
161
|
+
gl.bindBuffer(gl.COPY_WRITE_BUFFER, this.geometry.index.buffer);
|
|
162
|
+
gl.bufferSubData(gl.COPY_WRITE_BUFFER, start * INDEX_BYTES, own);
|
|
163
|
+
}
|
|
164
|
+
// A piece whose vertices are in place: its id
|
|
165
|
+
record(piece) {
|
|
166
|
+
const id = this.spare.length ? this.spare.pop() : this.pieces.length;
|
|
167
|
+
this.pieces[id] = { ...piece, shown: true, depth: 0 };
|
|
168
|
+
this.changes++;
|
|
169
|
+
this.used.vertices += piece.vertexCount;
|
|
170
|
+
if (this.indices) this.used.indices += piece.count;
|
|
171
|
+
this.bound();
|
|
172
|
+
return id;
|
|
173
|
+
}
|
|
174
|
+
remove(id) {
|
|
175
|
+
const piece = this.pieces[id];
|
|
176
|
+
this.pieces[id] = null;
|
|
177
|
+
this.spare.push(id);
|
|
178
|
+
this.changes++;
|
|
179
|
+
this.vertexRuns.release(piece.vertexStart, piece.vertexCount);
|
|
180
|
+
this.used.vertices -= piece.vertexCount;
|
|
181
|
+
if (this.indices) {
|
|
182
|
+
this.indexRuns.release(piece.start, piece.count);
|
|
183
|
+
this.used.indices -= piece.count;
|
|
184
|
+
}
|
|
185
|
+
this.bound();
|
|
186
|
+
}
|
|
187
|
+
// Gives the card back the buffers' room once no piece is left; they grow again when asked
|
|
188
|
+
empty() {
|
|
189
|
+
if (this.pieces.some(Boolean) || !this.held.vertices) return;
|
|
190
|
+
this.discard(this.geometry);
|
|
191
|
+
this.geometry = new THREE.BufferGeometry();
|
|
192
|
+
this.held = { vertices: 0, indices: 0 };
|
|
193
|
+
this.used = { vertices: 0, indices: 0 };
|
|
194
|
+
this.vertexRuns = new Runs();
|
|
195
|
+
this.indexRuns = new Runs();
|
|
196
|
+
this.pieces = [];
|
|
197
|
+
this.spare = [];
|
|
198
|
+
this.changes++;
|
|
199
|
+
if (this.indices) this.indices = new Uint32Array(0);
|
|
200
|
+
this.bound();
|
|
201
|
+
}
|
|
202
|
+
show(id, shown) {
|
|
203
|
+
const piece = this.pieces[id];
|
|
204
|
+
if (piece.shown === shown) return;
|
|
205
|
+
piece.shown = shown;
|
|
206
|
+
this.changes++;
|
|
207
|
+
}
|
|
208
|
+
// The bounds of all pieces, by which Three decides whether the batch is in view at all; with no piece it never is
|
|
209
|
+
bound() {
|
|
210
|
+
const all = new THREE.Sphere(new THREE.Vector3(), -1);
|
|
211
|
+
for (const piece of this.pieces) if (piece) all.union(piece.sphere);
|
|
212
|
+
if (all.isEmpty()) all.radius = -Infinity;
|
|
213
|
+
this.geometry.boundingSphere = all;
|
|
214
|
+
this.boundingSphere = all.clone();
|
|
215
|
+
}
|
|
216
|
+
// Three sorts the opaque things of a pass nearest first by the centre of this sphere, so that what stands in front hides what is
|
|
217
|
+
// behind before it is shaded: the batch is placed where its nearest piece in the viewer's picture stands, as that piece's own mesh
|
|
218
|
+
// was, with a radius that still holds every piece (the sphere is also what Three culls the whole batch by)
|
|
219
|
+
sortBy(nearest) {
|
|
220
|
+
const all = this.geometry.boundingSphere,
|
|
221
|
+
at = this.boundingSphere;
|
|
222
|
+
at.center.copy(nearest.sphere.center);
|
|
223
|
+
at.radius = all.radius + at.center.distanceTo(all.center);
|
|
224
|
+
}
|
|
225
|
+
// Larger buffers: at least what is asked of them now and what was said at the start, and half as large again as the old ones. What
|
|
226
|
+
// the old vertex buffers held is copied across on the card; the indices are written again from the copy kept here.
|
|
227
|
+
grow() {
|
|
228
|
+
const size = (needed, room, held) => (needed > held ? Math.max(needed, room, Math.ceil(held * this.fit.growth)) : held),
|
|
229
|
+
vertices = size(this.vertexRuns.end, this.room.vertices, this.held.vertices),
|
|
230
|
+
indices = size(this.indexRuns.end, this.room.indices, this.held.indices),
|
|
231
|
+
kept = this.indices && new Uint32Array(indices),
|
|
232
|
+
length = this.held.vertices;
|
|
233
|
+
if (kept) kept.set(this.indices);
|
|
234
|
+
this.remake(vertices, kept, (gl, bytes) => gl.copyBufferSubData(gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, length * bytes));
|
|
235
|
+
this.held = { vertices, indices };
|
|
236
|
+
}
|
|
237
|
+
// Packs the pieces together, one after another, into buffers `room` times what they fill, once they fill less than `use`
|
|
238
|
+
// of the ones they are in (a buffer only ever grows, and pieces are let go): what each piece holds is copied across on the card,
|
|
239
|
+
// and its indices are written again from the copy kept here; a batch with no piece left gives its room back. Returns whether it did either.
|
|
240
|
+
pack() {
|
|
241
|
+
const { vertices: filled, indices: filledIndices } = this.used;
|
|
242
|
+
if (this.held.vertices < PACK_LEAST || filled >= this.held.vertices * this.fit.use) return false;
|
|
243
|
+
if (!filled) {
|
|
244
|
+
this.empty();
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
const vertices = Math.ceil(filled * this.fit.room),
|
|
248
|
+
indices = Math.ceil(filledIndices * this.fit.room),
|
|
249
|
+
kept = this.indices && new Uint32Array(indices);
|
|
250
|
+
let at = 0,
|
|
251
|
+
indexAt = 0;
|
|
252
|
+
if (kept)
|
|
253
|
+
for (const piece of this.pieces) {
|
|
254
|
+
if (!piece) continue;
|
|
255
|
+
for (let i = 0; i < piece.count; i++) kept[indexAt + i] = this.indices[piece.start + i] - piece.vertexStart + at;
|
|
256
|
+
at += piece.vertexCount;
|
|
257
|
+
indexAt += piece.count;
|
|
258
|
+
}
|
|
259
|
+
this.remake(vertices, kept, (gl, bytes) => {
|
|
260
|
+
let to = 0;
|
|
261
|
+
for (const piece of this.pieces) {
|
|
262
|
+
if (!piece) continue;
|
|
263
|
+
gl.copyBufferSubData(gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, piece.vertexStart * bytes, to * bytes, piece.vertexCount * bytes);
|
|
264
|
+
to += piece.vertexCount;
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
at = indexAt = 0;
|
|
268
|
+
for (const piece of this.pieces) {
|
|
269
|
+
if (!piece) continue;
|
|
270
|
+
piece.vertexStart = at;
|
|
271
|
+
at += piece.vertexCount;
|
|
272
|
+
if (kept) {
|
|
273
|
+
piece.start = indexAt;
|
|
274
|
+
indexAt += piece.count;
|
|
275
|
+
} else piece.start = piece.vertexStart;
|
|
276
|
+
}
|
|
277
|
+
this.held = { vertices, indices };
|
|
278
|
+
this.vertexRuns = new Runs(at);
|
|
279
|
+
this.indexRuns = new Runs(indexAt);
|
|
280
|
+
return true;
|
|
281
|
+
}
|
|
282
|
+
// New buffers on the card in place of the old ones: room for `vertices` in each attribute's, filled by copy(gl, bytes a vertex)
|
|
283
|
+
// from the old one while both are bound (the old as COPY_READ_BUFFER, the new as COPY_WRITE_BUFFER), and `kept`, the indices of an
|
|
284
|
+
// indexed batch, written whole.
|
|
285
|
+
remake(vertices, kept, copy) {
|
|
286
|
+
const gl = renderer.getContext(),
|
|
287
|
+
old = this.geometry;
|
|
288
|
+
this.geometry = new THREE.BufferGeometry();
|
|
289
|
+
for (const [name, type, itemSize, normalized] of this.layout) {
|
|
290
|
+
const bytes = itemSize * type.BYTES_PER_ELEMENT,
|
|
291
|
+
buffer = gl.createBuffer();
|
|
292
|
+
gl.bindBuffer(gl.COPY_WRITE_BUFFER, buffer);
|
|
293
|
+
gl.bufferData(gl.COPY_WRITE_BUFFER, vertices * bytes, gl.STATIC_DRAW);
|
|
294
|
+
if (this.held.vertices) {
|
|
295
|
+
gl.bindBuffer(gl.COPY_READ_BUFFER, old.attributes[name].buffer);
|
|
296
|
+
copy(gl, bytes);
|
|
297
|
+
gl.bindBuffer(gl.COPY_READ_BUFFER, null);
|
|
298
|
+
}
|
|
299
|
+
const attribute = new THREE.GLBufferAttribute(buffer, GL_TYPE.get(type), itemSize, type.BYTES_PER_ELEMENT, vertices);
|
|
300
|
+
attribute.normalized = normalized;
|
|
301
|
+
this.geometry.setAttribute(name, attribute);
|
|
302
|
+
}
|
|
303
|
+
if (kept) {
|
|
304
|
+
const buffer = gl.createBuffer();
|
|
305
|
+
this.indices = kept;
|
|
306
|
+
// a buffer of indices must be an index buffer from its first binding on, and that binding belongs to whichever vertex
|
|
307
|
+
// array Three bound last: it is given back what it had
|
|
308
|
+
const bound = gl.getParameter(gl.ELEMENT_ARRAY_BUFFER_BINDING);
|
|
309
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
|
|
310
|
+
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, kept, gl.STATIC_DRAW);
|
|
311
|
+
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, bound);
|
|
312
|
+
this.geometry.setIndex(new THREE.GLBufferAttribute(buffer, GL_UNSIGNED_INT, 1, INDEX_BYTES, kept.length));
|
|
313
|
+
}
|
|
314
|
+
gl.bindBuffer(gl.COPY_WRITE_BUFFER, null);
|
|
315
|
+
this.geometry.boundingSphere = old.boundingSphere;
|
|
316
|
+
this.discard(old);
|
|
317
|
+
}
|
|
318
|
+
// Frees the batch's buffers on the card, once it is let go
|
|
319
|
+
free() {
|
|
320
|
+
this.discard(this.geometry);
|
|
321
|
+
}
|
|
322
|
+
// Frees a geometry's buffers on the card, whether or not Three has drawn from them yet
|
|
323
|
+
discard(geometry) {
|
|
324
|
+
const gl = renderer.getContext();
|
|
325
|
+
for (const name in geometry.attributes) gl.deleteBuffer(geometry.attributes[name].buffer);
|
|
326
|
+
if (geometry.index) gl.deleteBuffer(geometry.index.buffer);
|
|
327
|
+
geometry.dispose();
|
|
328
|
+
}
|
|
329
|
+
// The pieces a camera sees, nearest first (farthest first in a see-through material): the first becomes the range Three draws,
|
|
330
|
+
// the others are listed for the multi-draw that follows it
|
|
331
|
+
choose(viewer) {
|
|
332
|
+
_view.setFromProjectionMatrix(_clip.multiplyMatrices(viewer.projectionMatrix, viewer.matrixWorldInverse).multiply(this.matrixWorld));
|
|
333
|
+
const e = _clip.elements;
|
|
334
|
+
let seen = 0;
|
|
335
|
+
for (const piece of this.pieces) {
|
|
336
|
+
if (!piece || !piece.shown || !_view.intersectsSphere(piece.sphere)) continue;
|
|
337
|
+
const c = piece.sphere.center;
|
|
338
|
+
piece.depth = e[2] * c.x + e[6] * c.y + e[10] * c.z + e[14];
|
|
339
|
+
_seen[seen++] = piece;
|
|
340
|
+
}
|
|
341
|
+
if (seen > _keys.length) _keys = new Float64Array(2 ** Math.ceil(Math.log2(seen)));
|
|
342
|
+
for (let i = 0; i < seen; i++) _keys[i] = Math.max(0, Math.floor((_seen[i].depth - DEPTH_FROM) / DEPTH_STEP)) * PIECES_MOST + i;
|
|
343
|
+
_keys.fill(Infinity, seen);
|
|
344
|
+
_keys.sort();
|
|
345
|
+
const far = this.material.transparent,
|
|
346
|
+
first = seen ? nthSeen(0, seen, far) : null;
|
|
347
|
+
if (first && camera === viewer && !this.material.transparent) this.sortBy(first);
|
|
348
|
+
if (first) this.geometry.setDrawRange(first.start, first.count);
|
|
349
|
+
else this.geometry.setDrawRange(0, -1); // a range Three takes for nothing to draw
|
|
350
|
+
this.rest = Math.max(0, seen - 1);
|
|
351
|
+
if (this.rest > this.starts.length) {
|
|
352
|
+
this.starts = new Int32Array(this.rest * 2);
|
|
353
|
+
this.counts = new Int32Array(this.rest * 2);
|
|
354
|
+
}
|
|
355
|
+
const unit = this.indices ? INDEX_BYTES : 1;
|
|
356
|
+
let drawn = 0;
|
|
357
|
+
for (let i = 0; i < this.rest; i++) {
|
|
358
|
+
const piece = nthSeen(i + 1, seen, far);
|
|
359
|
+
this.starts[i] = piece.start * unit;
|
|
360
|
+
this.counts[i] = piece.count;
|
|
361
|
+
drawn += piece.count;
|
|
362
|
+
}
|
|
363
|
+
this.restTriangles = drawn / 3;
|
|
364
|
+
}
|
|
365
|
+
// Hands over the pieces after the first, with everything Three bound for the first still in place
|
|
366
|
+
drawRest(material) {
|
|
367
|
+
if (!this.rest) return;
|
|
368
|
+
const gl = renderer.getContext(),
|
|
369
|
+
twoPasses = material.transparent && material.side === THREE.DoubleSide && !material.forceSinglePass;
|
|
370
|
+
// Three draws such a material's back faces and then its front faces, and has just drawn the fronts: so do the rest
|
|
371
|
+
if (twoPasses) {
|
|
372
|
+
gl.frontFace(gl.CW);
|
|
373
|
+
this.multiDraw(gl);
|
|
374
|
+
gl.frontFace(gl.CCW);
|
|
375
|
+
}
|
|
376
|
+
this.multiDraw(gl);
|
|
377
|
+
}
|
|
378
|
+
multiDraw(gl) {
|
|
379
|
+
const { starts, counts, rest } = this;
|
|
380
|
+
if (multi === undefined) multi = renderer.extensions.has('WEBGL_multi_draw') ? renderer.extensions.get('WEBGL_multi_draw') : null;
|
|
381
|
+
if (this.indices) {
|
|
382
|
+
if (multi) multi.multiDrawElementsWEBGL(gl.TRIANGLES, counts, 0, GL_UNSIGNED_INT, starts, 0, rest);
|
|
383
|
+
else for (let i = 0; i < rest; i++) gl.drawElements(gl.TRIANGLES, counts[i], GL_UNSIGNED_INT, starts[i]);
|
|
384
|
+
} else if (multi) multi.multiDrawArraysWEBGL(gl.TRIANGLES, starts, 0, counts, 0, rest);
|
|
385
|
+
else for (let i = 0; i < rest; i++) gl.drawArrays(gl.TRIANGLES, starts[i], counts[i]);
|
|
386
|
+
renderer.info.render.calls += multi ? 1 : rest;
|
|
387
|
+
renderer.info.render.triangles += this.restTriangles;
|
|
388
|
+
}
|
|
389
|
+
onBeforeRender(_renderer, _scene, viewer) {
|
|
390
|
+
this.choose(viewer);
|
|
391
|
+
}
|
|
392
|
+
onAfterRender(_renderer, _scene, _camera, _geometry, material) {
|
|
393
|
+
this.drawRest(material);
|
|
394
|
+
}
|
|
395
|
+
// In a point light's shadow it is drawn only where it casts there, and not where a cached point shadow already contains its current revision
|
|
396
|
+
onBeforeShadow(_renderer, _object, _camera, shadowCamera, _geometry, drawnWith) {
|
|
397
|
+
if (!drawnWith.isMeshDistanceMaterial || (this.pointShadow && !(isStill(this) && keptAway(this, this.changes))))
|
|
398
|
+
this.choose(shadowCamera);
|
|
399
|
+
else {
|
|
400
|
+
this.geometry.setDrawRange(0, -1);
|
|
401
|
+
this.rest = 0;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
onAfterShadow(_renderer, _object, _camera, _shadowCamera, _geometry, depthMaterial) {
|
|
405
|
+
this.drawRest(depthMaterial);
|
|
406
|
+
}
|
|
407
|
+
raycast() {} // the vertices are on the card only
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export { TIGHT };
|