@null3d/splats 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/LICENSE-APACHE +176 -0
- package/LICENSE-MIT +21 -0
- package/README.md +55 -2
- package/THIRD-PARTY-NOTICES.txt +63 -0
- package/dist/splats.wasm +0 -0
- package/lib/chunks.d.ts +74 -0
- package/lib/chunks.js +170 -0
- package/lib/coverage.d.ts +18 -0
- package/lib/coverage.js +208 -0
- package/lib/feature.d.ts +10 -0
- package/lib/feature.js +39 -0
- package/lib/format.d.ts +35 -0
- package/lib/format.js +53 -0
- package/lib/gltf.d.ts +9 -0
- package/lib/gltf.js +174 -0
- package/lib/index.d.ts +11 -0
- package/lib/index.js +10 -0
- package/lib/pack.d.ts +34 -0
- package/lib/pack.js +60 -0
- package/lib/select-reference.d.ts +12 -0
- package/lib/select-reference.js +103 -0
- package/lib/select-task.d.ts +65 -0
- package/lib/select-task.js +200 -0
- package/lib/select.d.ts +41 -0
- package/lib/select.js +145 -0
- package/lib/splats-mesh.wgsl-material-glsl-0-01097b38ab28a3d5.js +24 -0
- package/lib/splats-mesh.wgsl-material-glsl-1-3f27ff0f14b7cdd2.js +24 -0
- package/lib/splats-mesh.wgsl-material-glsl-2-d471bfaf3a580318.js +24 -0
- package/lib/splats-mesh.wgsl-material-glsl-3-e048b0d077060953.js +24 -0
- package/lib/splats-mesh.wgsl-material-wgsl-0-c529a49353714424.js +24 -0
- package/lib/splats-mesh.wgsl-material-wgsl-2-ec594872c7d3fbf6.js +24 -0
- package/lib/splats-mesh.wgsl.d.ts +6 -0
- package/lib/splats-mesh.wgsl.js +36 -0
- package/lib/splats.wgsl-material-glsl-0-32dc5311875620e4.js +24 -0
- package/lib/splats.wgsl-material-glsl-1-da80dc94627cf770.js +24 -0
- package/lib/splats.wgsl-material-glsl-2-fb7895ef8b78d665.js +24 -0
- package/lib/splats.wgsl-material-glsl-3-b8800106bf9b5770.js +24 -0
- package/lib/splats.wgsl-material-glsl-64-9f7d0841d0ac147d.js +24 -0
- package/lib/splats.wgsl-material-glsl-65-fbc638499588c846.js +24 -0
- package/lib/splats.wgsl-material-glsl-66-3c49fd84ca72bada.js +24 -0
- package/lib/splats.wgsl-material-glsl-67-5aabadfe22c2f13c.js +24 -0
- package/lib/splats.wgsl-material-wgsl-0-eef591a67552ad7e.js +24 -0
- package/lib/splats.wgsl-material-wgsl-2-15569422a33203f4.js +24 -0
- package/lib/splats.wgsl-material-wgsl-64-769cd6ac619835c2.js +24 -0
- package/lib/splats.wgsl-material-wgsl-66-f1515cd808e3a573.js +24 -0
- package/lib/splats.wgsl.d.ts +14 -0
- package/lib/splats.wgsl.js +42 -0
- package/lib/spz-write.d.ts +9 -0
- package/lib/spz-write.js +133 -0
- package/lib/spz.d.ts +9 -0
- package/lib/spz.js +240 -0
- package/lib/stream.d.ts +126 -0
- package/lib/stream.js +304 -0
- package/lib/system.d.ts +110 -0
- package/lib/system.js +498 -0
- package/lib/version.d.ts +1 -0
- package/lib/version.js +3 -0
- package/package.json +56 -5
package/lib/spz.js
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// The reader of SPZ files, Niantic's packed form of a Gaussian-splat cloud. A legacy file is one
|
|
2
|
+
// gzip stream whose contents are a header and the attribute arrays; a version 4 file is a plain
|
|
3
|
+
// header, a table of contents and one zstd stream for each attribute array.
|
|
4
|
+
//
|
|
5
|
+
// The reader reconstructs the cloud that the writer packed: 24-bit fixed-point centers, log spreads
|
|
6
|
+
// that become the standard deviations, unit quaternions, an opacity from each alpha's sigmoid, and
|
|
7
|
+
// the first spherical-harmonic band's color. Higher bands make a splat's color change with the
|
|
8
|
+
// view; this reader drops them, which the glTF extension allows.
|
|
9
|
+
import { colorOfSh, splatsError } from './format.js';
|
|
10
|
+
/** The magic value of every SPZ container, which reads "NGSP" in little-endian bytes. */
|
|
11
|
+
const MAGIC = 0x5053474e;
|
|
12
|
+
/** The first version whose file is a zstd container with a table of contents. */
|
|
13
|
+
const ZSTD_VERSION = 4;
|
|
14
|
+
/** The point count above which a file is refused, so a broken header cannot allocate the heap. */
|
|
15
|
+
const MAX_POINTS = 16_777_216;
|
|
16
|
+
/** The number of colored coefficients in each spherical-harmonic band. */
|
|
17
|
+
const DIM_FOR_DEGREE = { 0: 0, 1: 3, 2: 8, 3: 15, 4: 24 };
|
|
18
|
+
/** The scale that turns a byte into a first-band coefficient. */
|
|
19
|
+
const COLOR_SCALE = 0.15;
|
|
20
|
+
/**
|
|
21
|
+
* Reads an SPZ file into a cloud of splats. `file` holds the file's bytes as the browser delivers
|
|
22
|
+
* them. Throws when the file is not an SPZ file this reader knows, when its sizes do not fit, and
|
|
23
|
+
* when a zstd stream needs a browser without the zstd decompressor.
|
|
24
|
+
*
|
|
25
|
+
* @category api/splats
|
|
26
|
+
*/
|
|
27
|
+
export async function decodeSpz(file) {
|
|
28
|
+
const bytes = file instanceof Uint8Array ? file : new Uint8Array(file);
|
|
29
|
+
const raw = await contain(bytes);
|
|
30
|
+
const header = readHeader(raw);
|
|
31
|
+
if (header.count > MAX_POINTS)
|
|
32
|
+
throw splatsError(2102, `the SPZ file holds ${header.count} splats, and this reader takes up to ${MAX_POINTS}. Split the cloud across several files.`);
|
|
33
|
+
return header.version >= ZSTD_VERSION ? decodeZstd(raw, header) : decodeLegacy(raw, header);
|
|
34
|
+
}
|
|
35
|
+
/** The plain bytes of a legacy gzip file, or the bytes of a zstd container as they are. */
|
|
36
|
+
async function contain(bytes) {
|
|
37
|
+
if (bytes[0] === 0x1f && bytes[1] === 0x8b)
|
|
38
|
+
return inflate('gzip', bytes);
|
|
39
|
+
if (bytes.length >= 4 && view(bytes).getUint32(0, true) === MAGIC)
|
|
40
|
+
return bytes;
|
|
41
|
+
if (bytes[0] === 0x28 && bytes[1] === 0xb5 && bytes[2] === 0x2f && bytes[3] === 0xfd)
|
|
42
|
+
return inflate('zstd', bytes);
|
|
43
|
+
throw splatsError(2103, 'the file is not an SPZ file: it starts with neither the SPZ header, a gzip stream, nor a zstd stream.');
|
|
44
|
+
}
|
|
45
|
+
/** The file's header, read from the plain bytes that start it. */
|
|
46
|
+
function readHeader(raw) {
|
|
47
|
+
if (raw.length < 16)
|
|
48
|
+
throw splatsError(2103, 'the SPZ file is too short to hold its header.');
|
|
49
|
+
const data = view(raw);
|
|
50
|
+
if (data.getUint32(0, true) !== MAGIC)
|
|
51
|
+
throw splatsError(2103, 'the SPZ file does not start with the SPZ magic value.');
|
|
52
|
+
const version = data.getUint32(4, true);
|
|
53
|
+
if (version < 1 || version > ZSTD_VERSION)
|
|
54
|
+
throw splatsError(2103, `the SPZ file is version ${version}, and this reader reads versions 1 to ${ZSTD_VERSION}.`);
|
|
55
|
+
const count = data.getUint32(8, true);
|
|
56
|
+
const shDegree = raw[12];
|
|
57
|
+
if (DIM_FOR_DEGREE[shDegree] === undefined)
|
|
58
|
+
throw splatsError(2103, `the SPZ file gives the spherical-harmonic degree ${shDegree}, and a degree runs from 0 to 4.`);
|
|
59
|
+
return {
|
|
60
|
+
version,
|
|
61
|
+
count,
|
|
62
|
+
shDegree,
|
|
63
|
+
fractionalBits: raw[13],
|
|
64
|
+
flags: raw[14],
|
|
65
|
+
at: version >= ZSTD_VERSION ? 32 : 16,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** A legacy file's arrays, laid end to end after its header. */
|
|
69
|
+
function decodeLegacy(raw, header) {
|
|
70
|
+
const { count, version } = header;
|
|
71
|
+
const floats = version === 1 ? 2 : 3;
|
|
72
|
+
const rotations = version >= 3 ? 4 : 3;
|
|
73
|
+
const shBytes = DIM_FOR_DEGREE[header.shDegree] * 3;
|
|
74
|
+
const expected = header.at + count * (floats * 3 + 1 + 3 + 3 + rotations + shBytes);
|
|
75
|
+
if (raw.length < expected)
|
|
76
|
+
throw splatsError(2104, `the SPZ file holds ${raw.length} bytes, and its ${count} splats and their header need ${expected}. The file is cut short.`);
|
|
77
|
+
let at = header.at;
|
|
78
|
+
const take = (bytes) => {
|
|
79
|
+
const part = raw.subarray(at, at + bytes);
|
|
80
|
+
at += bytes;
|
|
81
|
+
return part;
|
|
82
|
+
};
|
|
83
|
+
const positions = take(count * floats * 3);
|
|
84
|
+
const alphas = take(count);
|
|
85
|
+
const colors = take(count * 3);
|
|
86
|
+
const scales = take(count * 3);
|
|
87
|
+
const quaternions = take(count * rotations);
|
|
88
|
+
return assemble(count, positions, alphas, colors, scales, quaternions, header);
|
|
89
|
+
}
|
|
90
|
+
/** A zstd container's streams, each decompressed on its own. */
|
|
91
|
+
async function decodeZstd(raw, header) {
|
|
92
|
+
const { count, version } = header;
|
|
93
|
+
if (raw.length < 32)
|
|
94
|
+
throw splatsError(2103, 'the SPZ file is too short to hold its header.');
|
|
95
|
+
const data = view(raw);
|
|
96
|
+
const streamCount = raw[15];
|
|
97
|
+
const toc = data.getUint32(16, true);
|
|
98
|
+
if (streamCount < 1 || streamCount > 6)
|
|
99
|
+
throw splatsError(2103, `the SPZ file names ${streamCount} streams, and it takes 1 to 6.`);
|
|
100
|
+
if (toc < header.at || toc + streamCount * 16 > raw.length)
|
|
101
|
+
throw splatsError(2103, 'the SPZ file points its table of contents outside the file.');
|
|
102
|
+
// The streams run positions, alphas, colors, scales, rotations and spherical harmonics, and a
|
|
103
|
+
// stream that the file leaves out is missing from the end of the table.
|
|
104
|
+
const tables = [];
|
|
105
|
+
let compressed = toc + streamCount * 16;
|
|
106
|
+
for (let i = 0; i < 6; i++) {
|
|
107
|
+
if (i >= streamCount) {
|
|
108
|
+
tables.push({ compressed: 0, size: 0 });
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const row = toc + i * 16;
|
|
112
|
+
const sizes = {
|
|
113
|
+
compressed: Number(data.getBigUint64(row, true)),
|
|
114
|
+
size: Number(data.getBigUint64(row + 8, true)),
|
|
115
|
+
};
|
|
116
|
+
tables.push(sizes);
|
|
117
|
+
compressed += sizes.compressed;
|
|
118
|
+
}
|
|
119
|
+
if (compressed !== raw.length)
|
|
120
|
+
throw splatsError(2103, `the SPZ file's streams end at ${compressed}, and the file holds ${raw.length} bytes.`);
|
|
121
|
+
const rotations = version >= 3 ? 4 : 3;
|
|
122
|
+
const shBytes = DIM_FOR_DEGREE[header.shDegree] * 3;
|
|
123
|
+
const want = [count * 3 * 3, count, count * 3, count * 3, count * rotations, count * shBytes];
|
|
124
|
+
const names = ['positions', 'alpha', 'colors', 'scales', 'rotations', 'spherical harmonics'];
|
|
125
|
+
const parts = [];
|
|
126
|
+
let at = toc + streamCount * 16;
|
|
127
|
+
for (let i = 0; i < 6; i++) {
|
|
128
|
+
const table = tables[i];
|
|
129
|
+
const slice = raw.subarray(at, at + table.compressed);
|
|
130
|
+
at += table.compressed;
|
|
131
|
+
const part = table.compressed === 0 ? new Uint8Array(0) : await inflate('zstd', slice);
|
|
132
|
+
if (part.length !== want[i])
|
|
133
|
+
throw splatsError(2104, `the SPZ file's ${names[i]} stream holds ${part.length} bytes, and its ${count} splats need ${want[i]}.`);
|
|
134
|
+
parts.push(part);
|
|
135
|
+
}
|
|
136
|
+
const [positions, alphas, colors, scales, quaternions] = parts;
|
|
137
|
+
return assemble(count, positions, alphas, colors, scales, quaternions, header);
|
|
138
|
+
}
|
|
139
|
+
/** The cloud that the arrays hold, in the form that the draw takes. */
|
|
140
|
+
function assemble(count, positions, alphas, colors, scales, quaternions, header) {
|
|
141
|
+
const out = {
|
|
142
|
+
count,
|
|
143
|
+
positions: new Float32Array(count * 3),
|
|
144
|
+
scales: new Float32Array(count * 3),
|
|
145
|
+
rotations: new Float32Array(count * 4),
|
|
146
|
+
colors: new Float32Array(count * 4),
|
|
147
|
+
};
|
|
148
|
+
const fixed = 1 / 2 ** header.fractionalBits;
|
|
149
|
+
const half = header.version === 1;
|
|
150
|
+
const smallestThree = header.version >= 3;
|
|
151
|
+
for (let i = 0; i < count; i++) {
|
|
152
|
+
for (let k = 0; k < 3; k++) {
|
|
153
|
+
const at = (i * 3 + k) * (half ? 2 : 3);
|
|
154
|
+
out.positions[i * 3 + k] = half
|
|
155
|
+
? halfToFloat(positions[at] | (positions[at + 1] << 8))
|
|
156
|
+
: signed24(positions, at) * fixed;
|
|
157
|
+
}
|
|
158
|
+
for (let k = 0; k < 3; k++)
|
|
159
|
+
out.scales[i * 3 + k] = Math.exp(scales[i * 3 + k] / 16 - 10);
|
|
160
|
+
if (smallestThree)
|
|
161
|
+
smallestThreeQuaternion(out.rotations, i * 4, quaternions, i * 4);
|
|
162
|
+
else
|
|
163
|
+
firstThreeQuaternion(out.rotations, i * 4, quaternions, i * 3);
|
|
164
|
+
const alpha = alphas[i] / 255;
|
|
165
|
+
const dc = [0, 1, 2].map((k) => (colors[i * 3 + k] / 255 - 0.5) / COLOR_SCALE);
|
|
166
|
+
colorOfSh(dc, true, out.colors.subarray(i * 4, i * 4 + 3));
|
|
167
|
+
out.colors[i * 4 + 3] = alpha;
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
/** A three-byte fixed-point value, sign-extended from its 24th bit. */
|
|
172
|
+
function signed24(bytes, at) {
|
|
173
|
+
let value = bytes[at] | (bytes[at + 1] << 8) | (bytes[at + 2] << 16);
|
|
174
|
+
if ((value & 0x800000) !== 0)
|
|
175
|
+
value |= 0xff000000;
|
|
176
|
+
return value;
|
|
177
|
+
}
|
|
178
|
+
/** A half-precision float, as the first version of the format stores centers. */
|
|
179
|
+
function halfToFloat(bits) {
|
|
180
|
+
const sign = bits & 0x8000 ? -1 : 1;
|
|
181
|
+
const exponent = (bits >> 10) & 0x1f;
|
|
182
|
+
const fraction = bits & 0x3ff;
|
|
183
|
+
if (exponent === 0)
|
|
184
|
+
return sign * fraction * 2 ** -24;
|
|
185
|
+
if (exponent === 0x1f)
|
|
186
|
+
return fraction === 0 ? sign * Infinity : Number.NaN;
|
|
187
|
+
return sign * (1 + fraction / 1024) * 2 ** (exponent - 15);
|
|
188
|
+
}
|
|
189
|
+
/** A quaternion that stores its first three components, with `w` from the unit length. */
|
|
190
|
+
function firstThreeQuaternion(out, to, bytes, at) {
|
|
191
|
+
let sum = 0;
|
|
192
|
+
for (let k = 0; k < 3; k++) {
|
|
193
|
+
const value = bytes[at + k] / 127.5 - 1;
|
|
194
|
+
out[to + k] = value;
|
|
195
|
+
sum += value * value;
|
|
196
|
+
}
|
|
197
|
+
out[to + 3] = Math.sqrt(Math.max(0, 1 - sum));
|
|
198
|
+
}
|
|
199
|
+
/** A quaternion in the smallest-three form: two bits name the largest, three signed 10-bit values hold the rest. */
|
|
200
|
+
function smallestThreeQuaternion(out, to, bytes, at) {
|
|
201
|
+
const word = (bytes[at] |
|
|
202
|
+
(bytes[at + 1] << 8) |
|
|
203
|
+
(bytes[at + 2] << 16) |
|
|
204
|
+
(bytes[at + 3] << 24)) >>>
|
|
205
|
+
0;
|
|
206
|
+
const largest = word >>> 30;
|
|
207
|
+
let rest = word & 0x3fffffff;
|
|
208
|
+
let sum = 0;
|
|
209
|
+
// The three stored components come in the order w, z, y, x, with the largest left out.
|
|
210
|
+
for (let k = 3; k >= 0; k--) {
|
|
211
|
+
if (k === largest)
|
|
212
|
+
continue;
|
|
213
|
+
const magnitude = rest & 0x1ff;
|
|
214
|
+
const negative = (rest >>> 9) & 1;
|
|
215
|
+
rest >>>= 10;
|
|
216
|
+
const value = ((negative === 1 ? -1 : 1) * Math.SQRT1_2 * magnitude) / 0x1ff;
|
|
217
|
+
out[to + k] = value;
|
|
218
|
+
sum += value * value;
|
|
219
|
+
}
|
|
220
|
+
out[to + largest] = Math.sqrt(Math.max(0, 1 - sum));
|
|
221
|
+
}
|
|
222
|
+
/** Decompresses a stream with the browser's own decompressor. */
|
|
223
|
+
async function inflate(format, bytes) {
|
|
224
|
+
if (typeof DecompressionStream === 'undefined')
|
|
225
|
+
throw splatsError(2105, `this browser has no decompressor, so it cannot read the SPZ file's ${format} stream. Use a browser that supports DecompressionStream.`);
|
|
226
|
+
let stream;
|
|
227
|
+
try {
|
|
228
|
+
stream = new Blob([bytes])
|
|
229
|
+
.stream()
|
|
230
|
+
.pipeThrough(new DecompressionStream(format));
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
throw splatsError(2105, `this browser cannot decompress ${format}, which this SPZ file needs. Use a browser that supports ${format} in DecompressionStream.`);
|
|
234
|
+
}
|
|
235
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
236
|
+
}
|
|
237
|
+
/** A view of the same bytes, for the header's whole numbers. */
|
|
238
|
+
function view(bytes) {
|
|
239
|
+
return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
240
|
+
}
|
package/lib/stream.d.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { type SplatChunk } from './chunks.js';
|
|
2
|
+
import { type SplatData } from './format.js';
|
|
3
|
+
/** The format name that a stream index gives. */
|
|
4
|
+
export declare const STREAM_FORMAT = "null3d.splats.stream";
|
|
5
|
+
/** The index version that this reader takes. */
|
|
6
|
+
export declare const STREAM_VERSION = 1;
|
|
7
|
+
/**
|
|
8
|
+
* One chunk of a splat stream: where its file lies, how many splats it holds, and the bounds that
|
|
9
|
+
* the selection needs before it loads.
|
|
10
|
+
*
|
|
11
|
+
* @category api/splats
|
|
12
|
+
*/
|
|
13
|
+
export interface StreamChunk {
|
|
14
|
+
/** The chunk's address, resolved against the index's own address. */
|
|
15
|
+
readonly url: string;
|
|
16
|
+
/** The number of splats in the chunk's file. */
|
|
17
|
+
readonly count: number;
|
|
18
|
+
/** The center of the chunk's bounds, in meters. */
|
|
19
|
+
readonly center: readonly [number, number, number];
|
|
20
|
+
/** The distance from the center to the farthest splat, in meters. */
|
|
21
|
+
readonly radius: number;
|
|
22
|
+
/** The size of the chunk's file in bytes, or 0 when the index does not give it. */
|
|
23
|
+
readonly bytes: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A splat stream's index: the cloud's count and the chunks that it is cut into.
|
|
27
|
+
*
|
|
28
|
+
* @category api/splats
|
|
29
|
+
*/
|
|
30
|
+
export interface SplatStream {
|
|
31
|
+
/** The number of splats in the whole cloud. */
|
|
32
|
+
readonly count: number;
|
|
33
|
+
/** The chunks, in the index's order. */
|
|
34
|
+
readonly chunks: readonly StreamChunk[];
|
|
35
|
+
/** The bytes that every chunk file takes together, as far as the index gives them. */
|
|
36
|
+
readonly bytes: number;
|
|
37
|
+
}
|
|
38
|
+
/** True when the bytes that a page downloaded start a stream index rather than a splat file. */
|
|
39
|
+
export declare function startsStreamIndex(bytes: Uint8Array): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Reads a stream index. `base` resolves each chunk's address, which a relative one needs. Throws
|
|
42
|
+
* E2112 for a text that is not a stream index of this version, and for a cloud whose chunks do not
|
|
43
|
+
* hold the number of splats that it names.
|
|
44
|
+
*
|
|
45
|
+
* @category api/splats
|
|
46
|
+
*/
|
|
47
|
+
export declare function parseStreamIndex(text: string, base: string | URL | undefined, what?: string): SplatStream;
|
|
48
|
+
/**
|
|
49
|
+
* The bytes of chunk files that a stream waits for before it draws its first view. A cloud that is
|
|
50
|
+
* larger than this keeps loading behind the frames that draw.
|
|
51
|
+
*/
|
|
52
|
+
export declare const FIRST_VIEW_BYTES = 1000000;
|
|
53
|
+
/**
|
|
54
|
+
* The number of chunks at the start of a nearest-first list that a stream's first view waits for:
|
|
55
|
+
* the chunks whose files fit in `limit` bytes, and at least the nearest one. A chunk whose size the
|
|
56
|
+
* index does not give makes the first view the nearest chunk alone, because nothing says how long
|
|
57
|
+
* the rest would take.
|
|
58
|
+
*/
|
|
59
|
+
export declare function firstViewCount(nearestFirst: ArrayLike<number>, bytes: ArrayLike<number>, limit?: number): number;
|
|
60
|
+
/** The calls that the loader makes, which a test replaces. */
|
|
61
|
+
export type FetchLike = (url: string, init?: RequestInit) => Promise<Response>;
|
|
62
|
+
/** How the stream loader behaves, and where its answers go. */
|
|
63
|
+
export interface StreamLoaderOptions {
|
|
64
|
+
/** Downloads a chunk. The default is the page's `fetch`. */
|
|
65
|
+
readonly fetch?: FetchLike;
|
|
66
|
+
/** Reads a chunk file. */
|
|
67
|
+
readonly decode: (bytes: Uint8Array) => Promise<SplatData>;
|
|
68
|
+
/** The most requests in flight at once. The default is 4. */
|
|
69
|
+
readonly concurrency?: number;
|
|
70
|
+
/** How many times a chunk is fetched again after a failure. The default is 2. */
|
|
71
|
+
readonly retries?: number;
|
|
72
|
+
/** The wait before the first retry, in milliseconds. The default is 250, and each retry doubles it. */
|
|
73
|
+
readonly retryDelayMs?: number;
|
|
74
|
+
/** The time after which one request is given up, in milliseconds. The default is 30000. */
|
|
75
|
+
readonly timeoutMs?: number;
|
|
76
|
+
/** Sees a chunk once its data is decoded. */
|
|
77
|
+
readonly onChunk: (index: number, chunk: SplatChunk) => void;
|
|
78
|
+
/** Sees a chunk that stays unreachable, once. */
|
|
79
|
+
readonly onFailed: (index: number, error: Error) => void;
|
|
80
|
+
/** Runs when no request is in flight and no wanted chunk waits. */
|
|
81
|
+
readonly onIdle: () => void;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Loads the chunks of a splat stream that the view asks for. Call `load` with the wanted chunks,
|
|
85
|
+
* nearest first, each time the selection changes. A chunk loads once: its request stays in flight
|
|
86
|
+
* if the view moves away, and its data stays for a later look.
|
|
87
|
+
*/
|
|
88
|
+
export declare class SplatStreamLoader {
|
|
89
|
+
readonly stream: SplatStream;
|
|
90
|
+
private readonly fetchImpl;
|
|
91
|
+
private readonly decode;
|
|
92
|
+
private readonly concurrency;
|
|
93
|
+
private readonly retries;
|
|
94
|
+
private readonly retryDelayMs;
|
|
95
|
+
private readonly timeoutMs;
|
|
96
|
+
private readonly states;
|
|
97
|
+
private readonly queue;
|
|
98
|
+
private readonly controllers;
|
|
99
|
+
private readonly options;
|
|
100
|
+
private inFlight;
|
|
101
|
+
private stopped;
|
|
102
|
+
private loadedCount;
|
|
103
|
+
private failedCount;
|
|
104
|
+
private received;
|
|
105
|
+
constructor(stream: SplatStream, options: StreamLoaderOptions);
|
|
106
|
+
/** The chunks whose data is loaded. */
|
|
107
|
+
get loaded(): number;
|
|
108
|
+
/** The chunks that stayed unreachable. */
|
|
109
|
+
get failed(): number;
|
|
110
|
+
/** The bytes of the chunk files that have arrived. */
|
|
111
|
+
get receivedBytes(): number;
|
|
112
|
+
/** True when no request is in flight and no wanted chunk waits. */
|
|
113
|
+
get idle(): boolean;
|
|
114
|
+
/** True when a chunk has loaded or stayed unreachable, so no answer about it waits. */
|
|
115
|
+
settled(index: number): boolean;
|
|
116
|
+
/**
|
|
117
|
+
* Wants the chunks that `order` names, nearest first, and starts the requests that fit. A chunk
|
|
118
|
+
* that is already loaded, failed or in flight is left alone.
|
|
119
|
+
*/
|
|
120
|
+
load(order: ArrayLike<number>): void;
|
|
121
|
+
/** Stops every request, and reports nothing more. */
|
|
122
|
+
abort(): void;
|
|
123
|
+
private pump;
|
|
124
|
+
private loadChunk;
|
|
125
|
+
private fetchChunk;
|
|
126
|
+
}
|
package/lib/stream.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// A splat stream: an index that names a cloud's chunks, and the loader that fetches the chunks that
|
|
2
|
+
// the view asks for. The index is small, so a page reads it first and then downloads only the
|
|
3
|
+
// chunks whose splats draw. Each chunk is an SPZ file of its own, so a large cloud appears a piece
|
|
4
|
+
// at a time instead of after its whole file arrives.
|
|
5
|
+
//
|
|
6
|
+
// The loader keeps a few requests in flight, retries a chunk that a lost connection or a cut-short
|
|
7
|
+
// body spoiled, and reports a chunk that stays unreachable. A chunk that arrives after the view
|
|
8
|
+
// moved away stays loaded but takes no row: the selection's counts decide which chunks draw.
|
|
9
|
+
import { chunkFrom } from './chunks.js';
|
|
10
|
+
import { checkSplats, splatsError } from './format.js';
|
|
11
|
+
/** The format name that a stream index gives. */
|
|
12
|
+
export const STREAM_FORMAT = 'null3d.splats.stream';
|
|
13
|
+
/** The index version that this reader takes. */
|
|
14
|
+
export const STREAM_VERSION = 1;
|
|
15
|
+
/** True when the bytes that a page downloaded start a stream index rather than a splat file. */
|
|
16
|
+
export function startsStreamIndex(bytes) {
|
|
17
|
+
// Skip a byte-order mark and whitespace, which a JSON file may start with.
|
|
18
|
+
let at = bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf ? 3 : 0;
|
|
19
|
+
while (at < bytes.length) {
|
|
20
|
+
const byte = bytes[at];
|
|
21
|
+
if (byte !== 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d)
|
|
22
|
+
return byte === 0x7b;
|
|
23
|
+
at++;
|
|
24
|
+
}
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Reads a stream index. `base` resolves each chunk's address, which a relative one needs. Throws
|
|
29
|
+
* E2112 for a text that is not a stream index of this version, and for a cloud whose chunks do not
|
|
30
|
+
* hold the number of splats that it names.
|
|
31
|
+
*
|
|
32
|
+
* @category api/splats
|
|
33
|
+
*/
|
|
34
|
+
export function parseStreamIndex(text, base, what = 'the splat stream index') {
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = JSON.parse(text);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
throw splatsError(2112, `${what} is not JSON, so it is not a splat stream index: ${error.message}. Give the address of an index that a stream writer made.`);
|
|
41
|
+
}
|
|
42
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
|
|
43
|
+
throw splatsError(2112, `${what} holds no JSON object, so it is not a splat stream index.`);
|
|
44
|
+
const index = parsed;
|
|
45
|
+
if (index.format !== STREAM_FORMAT)
|
|
46
|
+
throw splatsError(2112, `${what} names the format ${JSON.stringify(index.format)}, and a splat stream index names ${JSON.stringify(STREAM_FORMAT)}.`);
|
|
47
|
+
if (index['version'] !== STREAM_VERSION)
|
|
48
|
+
throw splatsError(2112, `${what} is version ${JSON.stringify(index['version'])}, and this reader reads version ${STREAM_VERSION}.`);
|
|
49
|
+
const count = index['count'];
|
|
50
|
+
if (typeof count !== 'number' || !Number.isInteger(count) || count < 0)
|
|
51
|
+
throw splatsError(2112, `${what} gives the count ${JSON.stringify(count)}, and a stream index takes a whole number of splats, 0 or more.`);
|
|
52
|
+
const rows = index['chunks'];
|
|
53
|
+
if (!Array.isArray(rows))
|
|
54
|
+
throw splatsError(2112, `${what} gives no list of chunks. Give a "chunks" array.`);
|
|
55
|
+
const chunks = [];
|
|
56
|
+
let total = 0;
|
|
57
|
+
let bytes = 0;
|
|
58
|
+
for (let i = 0; i < rows.length; i++) {
|
|
59
|
+
const row = rows[i];
|
|
60
|
+
if (typeof row !== 'object' || row === null || Array.isArray(row))
|
|
61
|
+
throw splatsError(2112, `chunk ${i} of ${what} is not an object.`);
|
|
62
|
+
const entry = row;
|
|
63
|
+
const url = entry['url'];
|
|
64
|
+
if (typeof url !== 'string' || url.length === 0)
|
|
65
|
+
throw splatsError(2112, `chunk ${i} of ${what} gives no address. Give a "url".`);
|
|
66
|
+
const chunkCount = entry['count'];
|
|
67
|
+
if (typeof chunkCount !== 'number' || !Number.isInteger(chunkCount) || chunkCount < 0)
|
|
68
|
+
throw splatsError(2112, `chunk ${i} of ${what} gives the count ${JSON.stringify(chunkCount)}, and a chunk takes a whole number of splats, 0 or more.`);
|
|
69
|
+
const center = entry['center'];
|
|
70
|
+
if (!isVector(center))
|
|
71
|
+
throw splatsError(2112, `chunk ${i} of ${what} gives no center of three finite numbers. Give a "center" array.`);
|
|
72
|
+
const radius = entry['radius'];
|
|
73
|
+
if (typeof radius !== 'number' || !Number.isFinite(radius) || radius < 0)
|
|
74
|
+
throw splatsError(2112, `chunk ${i} of ${what} gives the radius ${JSON.stringify(radius)}, and a chunk takes a finite radius, 0 or more.`);
|
|
75
|
+
const size = entry['bytes'] ?? 0;
|
|
76
|
+
if (typeof size !== 'number' || !Number.isInteger(size) || size < 0)
|
|
77
|
+
throw splatsError(2112, `chunk ${i} of ${what} gives the size ${JSON.stringify(size)}, and a chunk takes a whole number of bytes, 0 or more.`);
|
|
78
|
+
let address;
|
|
79
|
+
try {
|
|
80
|
+
address =
|
|
81
|
+
base === undefined ? new URL(url, 'http://localhost/').href : new URL(url, base).href;
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
throw splatsError(2112, `chunk ${i} of ${what} gives the address ${url}, which is not a URL.`);
|
|
85
|
+
}
|
|
86
|
+
chunks.push({
|
|
87
|
+
url: address,
|
|
88
|
+
count: chunkCount,
|
|
89
|
+
center: [center[0], center[1], center[2]],
|
|
90
|
+
radius,
|
|
91
|
+
bytes: size,
|
|
92
|
+
});
|
|
93
|
+
total += chunkCount;
|
|
94
|
+
bytes += size;
|
|
95
|
+
}
|
|
96
|
+
if (total !== count)
|
|
97
|
+
throw splatsError(2112, `${what} names ${count} splats, and its chunks hold ${total}. Give every splat one chunk.`);
|
|
98
|
+
return { count, chunks, bytes };
|
|
99
|
+
}
|
|
100
|
+
/** True for three finite numbers. */
|
|
101
|
+
function isVector(value) {
|
|
102
|
+
return (Array.isArray(value) &&
|
|
103
|
+
value.length === 3 &&
|
|
104
|
+
value.every((item) => typeof item === 'number' && Number.isFinite(item)));
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The bytes of chunk files that a stream waits for before it draws its first view. A cloud that is
|
|
108
|
+
* larger than this keeps loading behind the frames that draw.
|
|
109
|
+
*/
|
|
110
|
+
export const FIRST_VIEW_BYTES = 1_000_000;
|
|
111
|
+
/**
|
|
112
|
+
* The number of chunks at the start of a nearest-first list that a stream's first view waits for:
|
|
113
|
+
* the chunks whose files fit in `limit` bytes, and at least the nearest one. A chunk whose size the
|
|
114
|
+
* index does not give makes the first view the nearest chunk alone, because nothing says how long
|
|
115
|
+
* the rest would take.
|
|
116
|
+
*/
|
|
117
|
+
export function firstViewCount(nearestFirst, bytes, limit = FIRST_VIEW_BYTES) {
|
|
118
|
+
const total = nearestFirst.length;
|
|
119
|
+
let taken = 0;
|
|
120
|
+
let count = 0;
|
|
121
|
+
while (count < total) {
|
|
122
|
+
const size = bytes[nearestFirst[count]] ?? 0;
|
|
123
|
+
if (count > 0 && (size === 0 || taken + size > limit))
|
|
124
|
+
break;
|
|
125
|
+
taken += size;
|
|
126
|
+
count++;
|
|
127
|
+
}
|
|
128
|
+
return count;
|
|
129
|
+
}
|
|
130
|
+
/** The chunk states of the loader. */
|
|
131
|
+
const IDLE = 0;
|
|
132
|
+
const QUEUED = 1;
|
|
133
|
+
const LOADED = 2;
|
|
134
|
+
const FAILED = 3;
|
|
135
|
+
const IN_FLIGHT = 4;
|
|
136
|
+
/**
|
|
137
|
+
* Loads the chunks of a splat stream that the view asks for. Call `load` with the wanted chunks,
|
|
138
|
+
* nearest first, each time the selection changes. A chunk loads once: its request stays in flight
|
|
139
|
+
* if the view moves away, and its data stays for a later look.
|
|
140
|
+
*/
|
|
141
|
+
export class SplatStreamLoader {
|
|
142
|
+
stream;
|
|
143
|
+
fetchImpl;
|
|
144
|
+
decode;
|
|
145
|
+
concurrency;
|
|
146
|
+
retries;
|
|
147
|
+
retryDelayMs;
|
|
148
|
+
timeoutMs;
|
|
149
|
+
states;
|
|
150
|
+
queue = [];
|
|
151
|
+
controllers = new Set();
|
|
152
|
+
options;
|
|
153
|
+
inFlight = 0;
|
|
154
|
+
stopped = false;
|
|
155
|
+
loadedCount = 0;
|
|
156
|
+
failedCount = 0;
|
|
157
|
+
received = 0;
|
|
158
|
+
constructor(stream, options) {
|
|
159
|
+
this.stream = stream;
|
|
160
|
+
this.options = options;
|
|
161
|
+
this.fetchImpl = options.fetch ?? defaultFetch;
|
|
162
|
+
this.decode = options.decode;
|
|
163
|
+
this.concurrency = Math.max(1, Math.floor(options.concurrency ?? 4));
|
|
164
|
+
this.retries = Math.max(0, Math.floor(options.retries ?? 2));
|
|
165
|
+
this.retryDelayMs = Math.max(0, options.retryDelayMs ?? 250);
|
|
166
|
+
this.timeoutMs = Math.max(1, options.timeoutMs ?? 30_000);
|
|
167
|
+
this.states = new Uint8Array(stream.chunks.length);
|
|
168
|
+
}
|
|
169
|
+
/** The chunks whose data is loaded. */
|
|
170
|
+
get loaded() {
|
|
171
|
+
return this.loadedCount;
|
|
172
|
+
}
|
|
173
|
+
/** The chunks that stayed unreachable. */
|
|
174
|
+
get failed() {
|
|
175
|
+
return this.failedCount;
|
|
176
|
+
}
|
|
177
|
+
/** The bytes of the chunk files that have arrived. */
|
|
178
|
+
get receivedBytes() {
|
|
179
|
+
return this.received;
|
|
180
|
+
}
|
|
181
|
+
/** True when no request is in flight and no wanted chunk waits. */
|
|
182
|
+
get idle() {
|
|
183
|
+
return this.inFlight === 0 && this.queue.length === 0;
|
|
184
|
+
}
|
|
185
|
+
/** True when a chunk has loaded or stayed unreachable, so no answer about it waits. */
|
|
186
|
+
settled(index) {
|
|
187
|
+
const state = this.states[index];
|
|
188
|
+
return state === LOADED || state === FAILED;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Wants the chunks that `order` names, nearest first, and starts the requests that fit. A chunk
|
|
192
|
+
* that is already loaded, failed or in flight is left alone.
|
|
193
|
+
*/
|
|
194
|
+
load(order) {
|
|
195
|
+
if (this.stopped)
|
|
196
|
+
return;
|
|
197
|
+
// A chunk that waited for a look that has passed gives its place to the new order.
|
|
198
|
+
for (let i = 0; i < this.states.length; i++)
|
|
199
|
+
if (this.states[i] === QUEUED)
|
|
200
|
+
this.states[i] = IDLE;
|
|
201
|
+
this.queue.length = 0;
|
|
202
|
+
for (let k = 0; k < order.length; k++) {
|
|
203
|
+
const i = order[k];
|
|
204
|
+
if (this.states[i] === IDLE) {
|
|
205
|
+
this.states[i] = QUEUED;
|
|
206
|
+
this.queue.push(i);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
this.pump();
|
|
210
|
+
}
|
|
211
|
+
/** Stops every request, and reports nothing more. */
|
|
212
|
+
abort() {
|
|
213
|
+
this.stopped = true;
|
|
214
|
+
this.queue.length = 0;
|
|
215
|
+
for (const controller of this.controllers)
|
|
216
|
+
controller.abort();
|
|
217
|
+
this.controllers.clear();
|
|
218
|
+
this.inFlight = 0;
|
|
219
|
+
}
|
|
220
|
+
pump() {
|
|
221
|
+
if (this.stopped)
|
|
222
|
+
return;
|
|
223
|
+
while (this.inFlight < this.concurrency && this.queue.length > 0) {
|
|
224
|
+
const index = this.queue.shift();
|
|
225
|
+
this.states[index] = IN_FLIGHT;
|
|
226
|
+
this.inFlight++;
|
|
227
|
+
void this.loadChunk(index);
|
|
228
|
+
}
|
|
229
|
+
if (this.idle)
|
|
230
|
+
this.options.onIdle();
|
|
231
|
+
}
|
|
232
|
+
async loadChunk(index) {
|
|
233
|
+
try {
|
|
234
|
+
await this.fetchChunk(index);
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
// The chunk settles once, whether it loaded, failed, stopped or found no retry left.
|
|
238
|
+
this.inFlight = Math.max(0, this.inFlight - 1);
|
|
239
|
+
this.pump();
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
async fetchChunk(index) {
|
|
243
|
+
const chunk = this.stream.chunks[index];
|
|
244
|
+
let attempt = 0;
|
|
245
|
+
for (;;) {
|
|
246
|
+
const controller = new AbortController();
|
|
247
|
+
this.controllers.add(controller);
|
|
248
|
+
let timer;
|
|
249
|
+
try {
|
|
250
|
+
const request = this.fetchImpl(chunk.url, { signal: controller.signal });
|
|
251
|
+
timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
252
|
+
const response = await request;
|
|
253
|
+
if (!response.ok) {
|
|
254
|
+
// A server that lacks the file cannot answer it on a retry either.
|
|
255
|
+
throw permanent(splatsError(2114, `chunk ${index} of the splat stream answered ${response.status} at ${chunk.url}. Give an index whose chunk files the page may read.`));
|
|
256
|
+
}
|
|
257
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
258
|
+
const data = checkSplats(await this.decode(bytes), `chunk ${index} of the splat stream`);
|
|
259
|
+
if (data.count !== chunk.count)
|
|
260
|
+
throw permanent(splatsError(2113, `chunk ${index} of the splat stream holds ${data.count} splats at ${chunk.url}, and the index says ${chunk.count}. Check that the index and its chunk files belong together.`));
|
|
261
|
+
if (this.stopped)
|
|
262
|
+
return;
|
|
263
|
+
this.states[index] = LOADED;
|
|
264
|
+
this.loadedCount++;
|
|
265
|
+
this.received += bytes.byteLength;
|
|
266
|
+
this.options.onChunk(index, chunkFrom(data, chunk.center, chunk.radius));
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (this.stopped)
|
|
271
|
+
return;
|
|
272
|
+
if (isPermanent(error) || attempt >= this.retries) {
|
|
273
|
+
this.states[index] = FAILED;
|
|
274
|
+
this.failedCount++;
|
|
275
|
+
this.options.onFailed(index, asError(error));
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
attempt++;
|
|
279
|
+
await delay(this.retryDelayMs * 2 ** (attempt - 1));
|
|
280
|
+
if (this.stopped)
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
clearTimeout(timer);
|
|
285
|
+
this.controllers.delete(controller);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
function permanent(error) {
|
|
291
|
+
return Object.assign(error, { permanent: true });
|
|
292
|
+
}
|
|
293
|
+
function isPermanent(error) {
|
|
294
|
+
return (typeof error === 'object' &&
|
|
295
|
+
error !== null &&
|
|
296
|
+
error.permanent === true);
|
|
297
|
+
}
|
|
298
|
+
function asError(error) {
|
|
299
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
300
|
+
}
|
|
301
|
+
function delay(ms) {
|
|
302
|
+
return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
|
|
303
|
+
}
|
|
304
|
+
const defaultFetch = (url, init) => fetch(url, init);
|