@margoengine/points 0.0.0-stage → 1.0.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 (62) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +876 -2
  4. package/dist/attributes-DNc-1pdr.js +256 -0
  5. package/dist/attributes.d.ts +48 -0
  6. package/dist/clip.d.ts +55 -0
  7. package/dist/clip.js +122 -0
  8. package/dist/cloud-B4O_G-Df.js +545 -0
  9. package/dist/cloud.d.ts +155 -0
  10. package/dist/color.d.ts +1 -0
  11. package/dist/copc-write.d.ts +95 -0
  12. package/dist/copc-write.js +318 -0
  13. package/dist/copc.d.ts +55 -0
  14. package/dist/copc.js +127 -0
  15. package/dist/depth-video.d.ts +98 -0
  16. package/dist/depth-video.js +164 -0
  17. package/dist/e57.d.ts +163 -0
  18. package/dist/e57.js +624 -0
  19. package/dist/frame.d.ts +14 -0
  20. package/dist/index.d.ts +16 -0
  21. package/dist/index.js +1246 -0
  22. package/dist/las.d.ts +213 -0
  23. package/dist/las.js +500 -0
  24. package/dist/laz-encode-CHXgHra_.js +446 -0
  25. package/dist/laz-encode.d.ts +14 -0
  26. package/dist/laz-model-DCphHLqH.js +385 -0
  27. package/dist/laz-model.d.ts +47 -0
  28. package/dist/laz-write.d.ts +46 -0
  29. package/dist/laz-write.js +75 -0
  30. package/dist/laz.d.ts +50 -0
  31. package/dist/laz.js +645 -0
  32. package/dist/material.d.ts +167 -0
  33. package/dist/math.d.ts +103 -0
  34. package/dist/octree.d.ts +182 -0
  35. package/dist/octree.js +360 -0
  36. package/dist/pick.d.ts +76 -0
  37. package/dist/pick.js +192 -0
  38. package/dist/plugin.d.ts +235 -0
  39. package/dist/potree-las-RC8sjbYU.js +1 -0
  40. package/dist/potree-las.d.ts +1 -0
  41. package/dist/potree.d.ts +70 -0
  42. package/dist/potree.js +451 -0
  43. package/dist/range-BQuJAjUM.js +23 -0
  44. package/dist/range.d.ts +4 -0
  45. package/dist/screen-door-CALlYs39.js +7 -0
  46. package/dist/shaders-DCnbvb0-.js +282 -0
  47. package/dist/shaders.d.ts +52 -0
  48. package/dist/shared/fog.d.ts +33 -0
  49. package/dist/shared/pass.d.ts +53 -0
  50. package/dist/shared/selection-mask.d.ts +52 -0
  51. package/dist/shared/style-expression.d.ts +18 -0
  52. package/dist/sprites.d.ts +78 -0
  53. package/dist/storage-limit.d.ts +6 -0
  54. package/dist/style.d.ts +124 -0
  55. package/dist/style.js +709 -0
  56. package/dist/surfels.d.ts +95 -0
  57. package/dist/surfels.js +538 -0
  58. package/dist/survey-DToZwkJv.js +46 -0
  59. package/dist/survey.d.ts +10 -0
  60. package/dist/tier-BcFbLPVT.js +91 -0
  61. package/dist/tier.d.ts +6 -0
  62. package/package.json +102 -4
@@ -0,0 +1,155 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Mesh } from '@margoengine/core';
3
+ import { type PointBlocks } from './math.js';
4
+ import { PointsMaterial, type PointsMaterialOptions } from './material.js';
5
+ import { SelectionMasked } from './shared/selection-mask.js';
6
+ import type { MaskStyle } from './shared/selection-mask.js';
7
+ /**
8
+ * Point data. This is also the point-cloud output of `@margoengine/loaders`
9
+ * (`{kind: 'points', positions, colors?, normals?}`), which can be passed straight in.
10
+ */
11
+ export interface PointCloudData {
12
+ /** xyz per point. A Float32Array is used in place (not copied); other arrays are copied. */
13
+ positions: Float32Array | ArrayLike<number>;
14
+ /** RGB or RGBA per point: floats in 0..1, or 0..255 in a Uint8Array/Uint8ClampedArray. Packed to RGBA8. */
15
+ colors?: Float32Array | Uint8Array | Uint8ClampedArray | ArrayLike<number> | null;
16
+ /** 3 or 4. Inferred from `colors.length / count` when omitted. */
17
+ colorComponents?: 3 | 4;
18
+ /** Per-point size multiplier of `material.size`. A Float32Array is used in place. */
19
+ sizes?: Float32Array | ArrayLike<number> | null;
20
+ /** Accepted for loader interop and kept on the cloud; `SurfelPlugin` lays each disc flat on its normal. */
21
+ normals?: Float32Array | null;
22
+ }
23
+ /**
24
+ * Options for `new PointCloud(...)`. Throws a TypeError without positions, and a RangeError when the
25
+ * positions length is not a multiple of 3 or an option is out of range.
26
+ */
27
+ export interface PointCloudOptions extends PointCloudData {
28
+ /** A shared material or options for a new one. Default a new `PointsMaterial`. */
29
+ material?: PointsMaterial | PointsMaterialOptions;
30
+ /** Maximum points per culling block; a positive integer. Default 16384. */
31
+ blockSize?: number;
32
+ /** Seed of the per-block shuffle used for level of detail. Default 1. */
33
+ seed?: number;
34
+ /**
35
+ * How per-point colors are stored: 'rgba8', 4 bytes a point, clamped to 0..1, or 'float', 16 bytes a point, so HDR and
36
+ * emissive colors keep values above 1. Default 'rgba8'.
37
+ */
38
+ colorFormat?: 'rgba8' | 'float';
39
+ /**
40
+ * Color space of per-point colors. Loader output and 8-bit scanner colors are sRGB. Default 'srgb', or 'linear' with
41
+ * `colorFormat: 'float'`.
42
+ */
43
+ colorSpace?: 'srgb' | 'linear';
44
+ /**
45
+ * Permute the arrays into block order once at construction so the GPU reads them sequentially (faster for
46
+ * huge, spatially scrambled inputs). Point indices then refer to the new order; `sourceIndex` maps back.
47
+ * Default false.
48
+ */
49
+ reorder?: boolean;
50
+ /** Column-major model matrix, 16 floats, used in place, so clouds can share one. Default a new identity. */
51
+ matrix?: Float32Array;
52
+ /** World-unit margin added to every frustum plane test, for large points at block edges. Default 0. */
53
+ cullMargin?: number;
54
+ /** Label for debugging. Default ''. */
55
+ name?: string;
56
+ }
57
+ /** A per-point data stream of a PointCloud that can be marked dirty. */
58
+ export type PointChannel = 'positions' | 'colors' | 'sizes';
59
+ /** Owner interface the plugin implements, so `dispose()` can detach the cloud. */
60
+ export interface PointOwner {
61
+ remove(item: unknown): void;
62
+ /** @internal Retained per-cloud allocation inventory, without shared renderer state. */
63
+ memoryFor?(cloud: PointCloud): {
64
+ cpu: readonly ArrayLike<number>[];
65
+ gpu: readonly GPUBuffer[];
66
+ };
67
+ }
68
+ /**
69
+ * A chunked, GPU-resident point cloud drawn with a `PointsMaterial`.
70
+ * Add it to a `PointsPlugin` to draw it.
71
+ */
72
+ export declare class PointCloud extends SelectionMasked {
73
+ /** @internal Allocation inventory consumed by optional diagnostic entries. */
74
+ get memoryResources(): {
75
+ cpu: readonly (ArrayLike<number> | null)[];
76
+ gpu: readonly GPUBuffer[];
77
+ };
78
+ name: string;
79
+ /** Hidden clouds are skipped entirely. */
80
+ visible: boolean;
81
+ /** Column-major model matrix, used when the cloud is not attached to a mesh. */
82
+ readonly matrix: Float32Array;
83
+ readonly material: PointsMaterial;
84
+ readonly count: number;
85
+ readonly positions: Float32Array;
86
+ /** Packed RGBA8 per point (r in the low byte), or null. With `colorFormat: 'float'`, the bits of `floatColors`. */
87
+ colors: Uint32Array | null;
88
+ /** Component count of the colors last given (3 or 4). */
89
+ colorComponents: 3 | 4;
90
+ sizes: Float32Array | null;
91
+ /** xyz per point, in the same order as `positions`, or null. */
92
+ readonly normals: Float32Array | null;
93
+ readonly colorFormat: 'rgba8' | 'float';
94
+ readonly colorSpace: 'srgb' | 'linear';
95
+ readonly blockSize: number;
96
+ readonly seed: number;
97
+ cullMargin: number;
98
+ /** True when `reorder` permuted the arrays; the GPU then reads slots directly. */
99
+ readonly direct: boolean;
100
+ /** With `reorder`, the original index of each stored point. */
101
+ readonly sourceIndex: Uint32Array | null;
102
+ /** Chunking result: blocks, bounds and the shuffled draw order. */
103
+ blocks: PointBlocks;
104
+ /** Points drawn and blocks visible in the latest frame. */
105
+ readonly stats: {
106
+ blocksVisible: number;
107
+ pointsVisible: number;
108
+ pointsDrawn: number;
109
+ };
110
+ /** Bumped when GPU buffers must be recreated (colors or sizes added or removed, rebuild). @internal */
111
+ structure: number;
112
+ /** Pending `[start, end)` point ranges per channel. @internal */
113
+ readonly dirty: Record<PointChannel, Array<[number, number]>>;
114
+ private mesh;
115
+ private owner?;
116
+ constructor(options: PointCloudOptions);
117
+ /** 32-bit words of `colors` per point: 1, or 4 with `colorFormat: 'float'`. */
118
+ get colorStride(): number;
119
+ /** With `colorFormat: 'float'` and colors, RGBA float32 per point (a view of `colors`); otherwise null. */
120
+ get floatColors(): Float32Array | null;
121
+ /** The mesh whose world matrix this cloud follows, or null. */
122
+ get attachedMesh(): Mesh | null;
123
+ /** Follow a core mesh's world matrix (and its visibility). Pass null to use `matrix` again. */
124
+ attach(mesh: Mesh | null): this;
125
+ /** Copies `values` (xyz per point) over points `start ..` and uploads only that range next frame. */
126
+ updatePositions(start: number, values: ArrayLike<number>): this;
127
+ /** Overwrites colors of points `start ..`. `components` defaults to the cloud's current component count. */
128
+ updateColors(start: number, values: ArrayLike<number>, components?: 3 | 4): this;
129
+ /** Overwrites per-point sizes of points `start ..`. */
130
+ updateSizes(start: number, values: ArrayLike<number>): this;
131
+ /**
132
+ * Marks points `start .. start + count` of a channel as changed after you wrote into `positions`, `colors`
133
+ * (packed, or `floatColors`) or `sizes` directly. Position edits also grow the block bounds.
134
+ */
135
+ markDirty(channel: PointChannel, start?: number, count?: number): this;
136
+ /** Replaces or removes all per-point colors (reallocates the GPU buffer). */
137
+ setColors(values: ArrayLike<number> | null, components?: 3 | 4, notify?: boolean): this;
138
+ /** Replaces or removes all per-point sizes (reallocates the GPU buffer). */
139
+ setSizes(values: ArrayLike<number> | null, notify?: boolean): this;
140
+ /**
141
+ * Replaces or removes the selection mask: one value a point (stored order), selected when true or above 0. Every
142
+ * draw style keeps working (shapes, sizes, sphere shading, EDL, fog, picking): the mask only fades, highlights or
143
+ * filters the points, as `style` (or the current `maskStyle`) says. Adding or removing it reallocates; `updateMask`
144
+ * and `setMaskStyle` do not.
145
+ */
146
+ setMask(values: ArrayLike<number | boolean> | null, style?: MaskStyle): this;
147
+ /** Re-chunks from the current positions: tight bounds again, and points that became finite join a block. */
148
+ rebuild(): this;
149
+ /** Detaches from its plugin, which frees the GPU buffers. The CPU arrays stay usable. */
150
+ dispose(): void;
151
+ [Symbol.dispose]: () => void;
152
+ /** @internal */
153
+ bind(owner: PointOwner | undefined): void;
154
+ private range;
155
+ }
@@ -0,0 +1 @@
1
+ export { parseColor, type ColorInput } from '@margoengine/math/color';
@@ -0,0 +1,95 @@
1
+ import { type LASWriteInput } from './las.js';
2
+ /** Points for the writer: what `writeLAS` takes, or the bytes of an uncompressed LAS file (versions 1.0 to 1.5). */
3
+ export type CopcBatch = LASWriteInput | Uint8Array;
4
+ /** One batch, or any number of them: an array, a generator, or an async stream such as tiles being read. */
5
+ export type CopcPoints = CopcBatch | Iterable<CopcBatch> | AsyncIterable<CopcBatch>;
6
+ /**
7
+ * Where the writer keeps points that wait for their node. The default holds them in memory; a store over files or the
8
+ * browser's file system keeps a cloud of any size out of it.
9
+ */
10
+ export interface CopcStore {
11
+ /** Adds bytes after those already under `key`. The writer does not touch `bytes` again. */
12
+ append(key: string, bytes: Uint8Array): void | Promise<void>;
13
+ /** The bytes under `key` in the order appended, in pieces of any length. */
14
+ read(key: string): Iterable<Uint8Array> | AsyncIterable<Uint8Array>;
15
+ /** Forgets `key`. */
16
+ delete(key: string): void | Promise<void>;
17
+ }
18
+ /** Options of {@link writeCOPC} and {@link writeCOPCTo}. */
19
+ export interface CopcWriteOptions {
20
+ /**
21
+ * Cells along each side of a node's sampling grid, 2 to 1024; a node keeps one point a cell, and the file's `spacing`
22
+ * is the cube's side over this. Default 128.
23
+ */
24
+ gridSize?: number;
25
+ /** A node with at most this many points left keeps them all and has no children. Default 100,000. */
26
+ leafPoints?: number;
27
+ /** Coordinate resolution. Default: that of the first batch. */
28
+ scale?: readonly [number, number, number];
29
+ /** OGC WKT of the CRS, in place of the first batch's. Needed when that batch states its CRS as GeoTIFF keys. */
30
+ wkt?: string;
31
+ /** Where waiting points go. Default: memory. */
32
+ store?: CopcStore;
33
+ /** Entries in one hierarchy page, 9 or more. Default 4,096: a reader loads a page at a time. */
34
+ pageEntries?: number;
35
+ /** Called after each node is written, with the points written so far and the points in all. */
36
+ onProgress?: (written: number, total: number) => void;
37
+ /** Stops the work; the store is emptied and the promise rejects with the signal's reason. */
38
+ signal?: AbortSignal;
39
+ }
40
+ /** What {@link writeCOPCTo} wrote. */
41
+ export interface CopcWritten {
42
+ points: number;
43
+ /** Octree nodes, one LAZ chunk each. */
44
+ nodes: number;
45
+ /** The deepest node's level; the root is 0. */
46
+ depth: number;
47
+ /** Length of the file. */
48
+ bytes: number;
49
+ }
50
+ /** Writes `bytes` at `position` of the file. Positions rise, but for the header, written last at 0. */
51
+ export type CopcSink = (bytes: Uint8Array, position: number) => void | Promise<void>;
52
+ /**
53
+ * Writes a Cloud Optimized Point Cloud through `sink`, holding only the nodes it is building in memory when
54
+ * `options.store` keeps waiting points elsewhere. Formats 0 to 3 become 6 or 7; every field and extra byte is kept.
55
+ *
56
+ * @param sink Writes bytes at a position: a file handle, a browser file stream.
57
+ * @param source The points: one batch, or an iterable or async iterable of batches with one record layout.
58
+ * @param options The octree's grid and leaf sizes, the coordinate scale and CRS, the store, progress and abort.
59
+ * @returns The points, nodes, depth and length written.
60
+ * @throws RangeError for no points, a bad option, batches of two layouts, waveform formats, a CRS held only as GeoTIFF
61
+ * keys, or a point too far for the scale; TypeError for a batch that is not uncompressed LAS; the signal's reason on an
62
+ * abort.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { open } from 'node:fs/promises';
67
+ * import { writeCOPCTo } from '@margoengine/points/copc-write';
68
+ *
69
+ * const file = await open('site.copc.laz', 'w');
70
+ * async function* tiles() {
71
+ * for (let x = 0; x < 4; x++) yield { positions: [x, 0, 0, x, 1, 0], intensity: [10, 20] };
72
+ * }
73
+ * const written = await writeCOPCTo((bytes, position) => file.write(bytes, 0, bytes.length, position).then(() => {}), tiles());
74
+ * await file.close();
75
+ * console.log(written.points, written.nodes);
76
+ * ```
77
+ */
78
+ export declare function writeCOPCTo(sink: CopcSink, source: CopcPoints, options?: CopcWriteOptions): Promise<CopcWritten>;
79
+ /**
80
+ * {@link writeCOPCTo} into one array, for clouds that fit in memory.
81
+ *
82
+ * @param source The points: one batch, or an iterable or async iterable of batches.
83
+ * @param options As {@link writeCOPCTo} takes them.
84
+ * @returns The file.
85
+ * @throws As {@link writeCOPCTo} does.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * import { writeCOPC } from '@margoengine/points/copc-write';
90
+ *
91
+ * const file = await writeCOPC({ positions: [0, 0, 0, 1, 2, 3], wkt: 'GEOGCS["WGS 84"]' });
92
+ * console.log(file.length);
93
+ * ```
94
+ */
95
+ export declare function writeCOPC(source: CopcPoints, options?: CopcWriteOptions): Promise<Uint8Array>;
@@ -0,0 +1,318 @@
1
+ import { LAS_RECORD_SIZES as e, readLASHeader as t, writeLAS as n } from "./las.js";
2
+ import { i as r, n as i, r as a, t as o } from "./laz-encode-CHXgHra_.js";
3
+ //#region ../shared/bytes.js
4
+ function s(e) {
5
+ let t = new Uint8Array(e.reduce((e, t) => e + t.length, 0)), n = 0;
6
+ for (let r of e) t.set(r, n), n += r.length;
7
+ return t;
8
+ }
9
+ //#endregion
10
+ //#region src/copc-write.ts
11
+ var c = 375, l = 160, u = 1 << 20, d = 30;
12
+ function f(e) {
13
+ if (e >= 6 && e <= 8) return e;
14
+ if (e <= 3) return e >= 2 ? 7 : 6;
15
+ throw RangeError(`COPC holds point formats 6, 7 and 8; format ${e} has waveform packets, which it cannot keep`);
16
+ }
17
+ function p(e, t, n, r, i) {
18
+ let a = e.getUint8(t + 14), o = e.getUint8(t + 15), s = (o & 31) == 12, c = n === 1 || n === 3;
19
+ if (r.setUint16(i + 12, e.getUint16(t + 12, !0), !0), r.setUint8(i + 14, a & 7 | (a >> 3 & 7) << 4), r.setUint8(i + 15, o >> 5 | (s ? 8 : 0) | a & 192), r.setUint8(i + 16, s ? 1 : o & 31), r.setUint8(i + 17, e.getUint8(t + 17)), r.setInt16(i + 18, Math.round(e.getInt8(t + 16) / .006), !0), r.setUint16(i + 20, e.getUint16(t + 18, !0), !0), c && r.setFloat64(i + 22, e.getFloat64(t + 20, !0), !0), n >= 2) {
20
+ let a = t + (n === 3 ? 28 : 20);
21
+ for (let t = 0; t < 3; t++) r.setUint16(i + 30 + t * 2, e.getUint16(a + t * 2, !0), !0);
22
+ }
23
+ }
24
+ var m = (e, t, ...n) => e.userId === t && n.includes(e.recordId);
25
+ function h(r, i, a) {
26
+ let o = r instanceof Uint8Array ? r : n({
27
+ ...r,
28
+ scale: i.scale ?? a?.scale ?? r.scale
29
+ }), { header: s, records: c } = t(o), { pointFormat: l, pointRecordLength: u, pointCount: d, pointDataOffset: h } = s;
30
+ if (o[104] & 192) throw TypeError("A batch is compressed; give uncompressed LAS bytes or decoded points to writeCOPC");
31
+ if (h + d * u > o.length) throw TypeError(`A LAS batch ends before its ${d} points of ${u} bytes; it is cut off`);
32
+ let g = new DataView(o.buffer, o.byteOffset, o.byteLength), _ = f(l), v = u - e[l], y = e[_] + v;
33
+ if (v < 0) throw TypeError(`A LAS batch's records are shorter than point format ${l} needs`);
34
+ if (!a) {
35
+ let e = (i.wkt === void 0 ? void 0 : new TextEncoder().encode(`${i.wkt}\0`)) ?? c.find((e) => m(e, "LASF_Projection", 2112))?.data.slice(), t = i.scale ?? s.scale;
36
+ if (!e && c.some((e) => m(e, "LASF_Projection", 34735))) throw RangeError("The points state their CRS as GeoTIFF keys, which COPC cannot hold; pass options.wkt");
37
+ if (!t.every((e) => e > 0 && Number.isFinite(e))) throw RangeError("COPC scale must be three numbers above 0");
38
+ a = {
39
+ format: _,
40
+ length: y,
41
+ scale: [...t],
42
+ offset: [...s.offset],
43
+ records: c.filter((e) => !m(e, "laszip encoded", 22204) && !m(e, "copc", 1, 1e3) && !m(e, "LASF_Projection", 2111, 2112, 34735, 34736, 34737)).map((e) => ({
44
+ ...e,
45
+ data: e.data.slice()
46
+ })),
47
+ wkt: e,
48
+ globalEncoding: g.getUint16(6, !0) & 9 | (e ? 16 : 0),
49
+ kept: o.slice(0, 94)
50
+ };
51
+ }
52
+ if (_ !== a.format || y !== a.length) throw RangeError(`Every batch needs one record layout: this one makes point format ${_} of ${y} bytes, the first made format ${a.format} of ${a.length}`);
53
+ let b = new Uint8Array(d * y), x = new DataView(b.buffer), { scale: S, offset: C } = a;
54
+ for (let t = 0; t < d; t++) {
55
+ let n = h + t * u, r = t * y;
56
+ l === _ ? b.set(o.subarray(n, n + u), r) : (p(g, n, l, x, r), b.set(o.subarray(n + e[l], n + u), r + e[_]));
57
+ for (let e = 0; e < 3; e++) {
58
+ let t = g.getInt32(n + e * 4, !0), i = s.scale[e] === S[e] && s.offset[e] === C[e] ? t : Math.round((t * s.scale[e] + s.offset[e] - C[e]) / S[e]);
59
+ if (!(i >= -2147483648 && i <= 2147483647)) throw RangeError("A point lies too far from the first batch's offset for this scale; pass a coarser scale");
60
+ x.setInt32(r + e * 4, i, !0);
61
+ }
62
+ }
63
+ return {
64
+ layout: a,
65
+ points: b
66
+ };
67
+ }
68
+ var g = ({ level: e, x: t, y: n, z: r }) => `copc-${e}-${t}-${n}-${r}`, _ = class {
69
+ constructor(e, t) {
70
+ this.length = e, this.full = t, this.used = 0, this.count = 0;
71
+ }
72
+ add(e, t) {
73
+ let n = this.length;
74
+ if (this.block ??= new Uint8Array(Math.max(1, Math.floor(u / n)) * n), this.block.set(e.subarray(t, t + n), this.used), this.used += n, this.count++, this.used === this.block.length) return this.flush();
75
+ }
76
+ flush() {
77
+ if (!this.used) return;
78
+ let e = this.block.subarray(0, this.used);
79
+ return this.block = void 0, this.used = 0, this.full(e);
80
+ }
81
+ };
82
+ function v() {
83
+ let e = /* @__PURE__ */ new Map();
84
+ return {
85
+ append(t, n) {
86
+ let r = e.get(t);
87
+ r ? r.push(n) : e.set(t, [n]);
88
+ },
89
+ read: (t) => e.get(t) ?? [],
90
+ delete(t) {
91
+ e.delete(t);
92
+ }
93
+ };
94
+ }
95
+ async function* y(e, t, n) {
96
+ let r = /* @__PURE__ */ new Uint8Array();
97
+ for await (let i of e.read(t)) {
98
+ let e = i;
99
+ r.length && (e = new Uint8Array(r.length + i.length), e.set(r), e.set(i, r.length));
100
+ let t = e.length - e.length % n;
101
+ t && (yield e.subarray(0, t)), r = new Uint8Array(e.subarray(t));
102
+ }
103
+ if (r.length) throw RangeError("The COPC store gave back part of a record; read must return what was appended");
104
+ }
105
+ function b(e, t, n, r = !1) {
106
+ let i = new Uint8Array(r ? 60 : 54), a = new DataView(i.buffer);
107
+ return i.set(new TextEncoder().encode(e).subarray(0, 16), 2), a.setUint16(18, t, !0), r ? a.setBigUint64(20, BigInt(n), !0) : a.setUint16(20, n, !0), i;
108
+ }
109
+ function x(e, t, n) {
110
+ let r = /* @__PURE__ */ new Map(), i = (e) => {
111
+ let t = e.children.reduce((e, t) => e + i(t), 1);
112
+ return r.set(e, t), t;
113
+ }, a = [];
114
+ i(e);
115
+ let o = n, s = (e) => {
116
+ let n = [], i = t, c = (e, t, r, a) => {
117
+ n.push([
118
+ e,
119
+ t,
120
+ r,
121
+ a
122
+ ]), i--;
123
+ }, l = (e) => {
124
+ c(e, e.offset, e.bytes, e.count), e.children.forEach(l);
125
+ };
126
+ c(e, e.offset, e.bytes, e.count), e.children.forEach((t, n) => {
127
+ if (r.get(t) <= i - (e.children.length - n - 1)) l(t);
128
+ else {
129
+ let [e, n] = s(t);
130
+ c(t, e, n, -1);
131
+ }
132
+ });
133
+ let u = new Uint8Array(n.length * 32), d = new DataView(u.buffer);
134
+ n.forEach(([e, t, n, r], i) => {
135
+ let a = i * 32;
136
+ d.setInt32(a, e.level, !0), d.setInt32(a + 4, e.x, !0), d.setInt32(a + 8, e.y, !0), d.setInt32(a + 12, e.z, !0), d.setBigUint64(a + 16, BigInt(t), !0), d.setInt32(a + 24, n, !0), d.setInt32(a + 28, r, !0);
137
+ }), a.push(u);
138
+ let f = [o, u.length];
139
+ return o += u.length, f;
140
+ };
141
+ return {
142
+ bytes: a,
143
+ root: s(e)
144
+ };
145
+ }
146
+ async function S(e, t, n) {
147
+ let { gridSize: u = 128, leafPoints: f = 1e5, pageEntries: p = 4096, signal: m, onProgress: S } = n, C = n.store ?? v();
148
+ if (!Number.isInteger(u) || u < 2 || u > 1024) throw RangeError("gridSize must be a whole number from 2 to 1024");
149
+ if (!Number.isInteger(f) || f < 1 || f > 2147483647) throw RangeError("leafPoints must be a whole number from 1 to 2147483647");
150
+ if (!Number.isInteger(p) || p < 9) throw RangeError("pageEntries must be 9 or more");
151
+ m?.throwIfAborted();
152
+ let w = /* @__PURE__ */ new Set(), ee = (e) => (t) => (w.add(e), C.append(e, t)), te = async (e) => {
153
+ w.delete(e), await C.delete(e);
154
+ };
155
+ try {
156
+ let v = {
157
+ level: 0,
158
+ x: 0,
159
+ y: 0,
160
+ z: 0,
161
+ count: 0
162
+ }, w = [
163
+ Infinity,
164
+ Infinity,
165
+ Infinity
166
+ ], T = [
167
+ -Infinity,
168
+ -Infinity,
169
+ -Infinity
170
+ ], E = /* @__PURE__ */ new Float64Array(15), D, O = Infinity, k = -Infinity, ne = t instanceof Uint8Array || "positions" in t ? [t] : t, A;
171
+ for await (let e of ne) {
172
+ m?.throwIfAborted();
173
+ let t = h(e, n, D);
174
+ D = t.layout;
175
+ let { points: r } = t, { length: i } = D, a = new DataView(r.buffer);
176
+ A ??= new _(i, ee(g(v)));
177
+ for (let e = 0; e < r.length; e += i) {
178
+ for (let t = 0; t < 3; t++) {
179
+ let n = a.getInt32(e + t * 4, !0);
180
+ n < w[t] && (w[t] = n), n > T[t] && (T[t] = n);
181
+ }
182
+ let t = a.getUint8(e + 14) & 15;
183
+ t && E[t - 1]++;
184
+ let n = a.getFloat64(e + 22, !0);
185
+ n < O && (O = n), n > k && (k = n), v.count++;
186
+ let i = A.add(r, e);
187
+ i && await i;
188
+ }
189
+ }
190
+ if (!D || !v.count) throw RangeError("writeCOPC needs at least one point");
191
+ await A.flush();
192
+ let { length: j, scale: M, offset: N, format: re } = D, P = v.count, F = w.map((e, t) => e * M[t] + N[t]), I = T.map((e, t) => e * M[t] + N[t]), L = F.map((e, t) => (e + I[t]) / 2), R = Math.max(...I.map((e, t) => (e - F[t]) / 2), ...M), z = R * 2, ie = L.map((e) => e - R), B = a(re, j), V = new Uint8Array(l), H = [...D.wkt ? [{
193
+ userId: "LASF_Projection",
194
+ recordId: 2112,
195
+ data: D.wkt
196
+ }] : [], ...D.records], U = H.filter((e) => e.data.length <= 65535), W = H.filter((e) => e.data.length > 65535), G = [
197
+ b("copc", 1, l),
198
+ V,
199
+ r(B, 4294967295),
200
+ ...U.flatMap((e) => [b(e.userId, e.recordId, e.data.length), e.data])
201
+ ], K = c + G.reduce((e, t) => e + t.length, 0), ae = [], oe = [], q = K + 8, se = 0, ce = 0, J = 0, Y = async (t) => {
202
+ await e(t, q), q += t.length;
203
+ }, le = async (e) => {
204
+ m?.throwIfAborted();
205
+ let t = g(e), n = e.count <= f || e.level >= d, r = z / 2 ** e.level / u, i = [
206
+ e.x,
207
+ e.y,
208
+ e.z
209
+ ].map((t, n) => ie[n] + t * (z / 2 ** e.level)), a = n ? void 0 : /* @__PURE__ */ new Set(), c = [], l = new _(j, (e) => {
210
+ c.push(e);
211
+ }), p = [];
212
+ for await (let n of y(C, t, j)) {
213
+ m?.throwIfAborted();
214
+ let t = new DataView(n.buffer, n.byteOffset, n.byteLength);
215
+ for (let o = 0; o < n.length; o += j) {
216
+ if (!a) {
217
+ l.add(n, o);
218
+ continue;
219
+ }
220
+ let s = 0, c = 0;
221
+ for (let e = 0; e < 3; e++) {
222
+ let n = (t.getInt32(o + e * 4, !0) * M[e] + N[e] - i[e]) / r, a = Math.min(u - 1, Math.max(0, Math.floor(n)));
223
+ s = s * u + a, n >= u / 2 && (c |= 1 << e);
224
+ }
225
+ if (!a.has(s)) {
226
+ a.add(s), l.add(n, o);
227
+ continue;
228
+ }
229
+ let d = p[c];
230
+ if (!d) {
231
+ let t = {
232
+ level: e.level + 1,
233
+ x: e.x * 2 + (c & 1),
234
+ y: e.y * 2 + (c >> 1 & 1),
235
+ z: e.z * 2 + (c >> 2 & 1),
236
+ count: 0
237
+ };
238
+ d = p[c] = {
239
+ node: t,
240
+ blocks: new _(j, ee(g(t)))
241
+ };
242
+ }
243
+ d.node.count++;
244
+ let f = d.blocks.add(n, o);
245
+ f && await f;
246
+ }
247
+ }
248
+ l.flush(), await te(t);
249
+ for (let e of p) await e?.blocks.flush();
250
+ let h = s(c), v = l.count, b = new Float64Array(v), x = new DataView(h.buffer);
251
+ c.length = 0;
252
+ for (let e = 0; e < v; e++) b[e] = x.getFloat64(e * j + 22, !0);
253
+ let w = Uint32Array.from({ length: v }, (e, t) => t).sort((e, t) => b[e] - b[t] || e - t), T = new Uint8Array(v * j);
254
+ for (let e = 0; e < v; e++) T.set(h.subarray(w[e] * j, (w[e] + 1) * j), e * j);
255
+ let E = q;
256
+ for (let e of o(T, new DataView(T.buffer), 0, v, j, B)) await Y(e);
257
+ let D = q - E;
258
+ ae.push(D), oe.push(v), se += v, ce++, J = Math.max(J, e.level), S?.(se, P);
259
+ let O = [];
260
+ for (let e of p) e && O.push(await le(e.node));
261
+ return {
262
+ level: e.level,
263
+ x: e.x,
264
+ y: e.y,
265
+ z: e.z,
266
+ count: v,
267
+ offset: E,
268
+ bytes: D,
269
+ children: O
270
+ };
271
+ }, ue = await le(v), de = q, fe = /* @__PURE__ */ new Uint8Array(8);
272
+ new DataView(fe.buffer).setBigUint64(0, BigInt(de), !0), await e(fe, K);
273
+ for (let e of i(ae, oe)) await Y(e);
274
+ let pe = q, X = x(ue, p, pe + 60), me = s(X.bytes);
275
+ await Y(b("copc", 1e3, me.length, !0)), await Y(me);
276
+ for (let e of W) await Y(b(e.userId, e.recordId, e.data.length, !0)), await Y(e.data);
277
+ let Z = new DataView(V.buffer);
278
+ [
279
+ ...L,
280
+ R,
281
+ z / u
282
+ ].forEach((e, t) => Z.setFloat64(t * 8, e, !0)), Z.setBigUint64(40, BigInt(X.root[0]), !0), Z.setBigUint64(48, BigInt(X.root[1]), !0), Z.setFloat64(56, O, !0), Z.setFloat64(64, k, !0);
283
+ let Q = new Uint8Array(c), $ = new DataView(Q.buffer);
284
+ Q.set([
285
+ 76,
286
+ 65,
287
+ 83,
288
+ 70
289
+ ]), Q.set(D.kept.subarray(4, 6), 4), $.setUint16(6, D.globalEncoding, !0), Q.set(D.kept.subarray(8, 24), 8), $.setUint8(24, 1), $.setUint8(25, 4), Q.set(D.kept.subarray(26, 58), 26), Q.set(new TextEncoder().encode("Margo Engine"), 58), Q.set(D.kept.subarray(90, 94), 90), $.setUint16(94, c, !0), $.setUint32(96, K, !0), $.setUint32(100, 2 + U.length, !0), $.setUint8(104, re | 128), $.setUint16(105, j, !0);
290
+ for (let e = 0; e < 3; e++) $.setFloat64(131 + e * 8, M[e], !0), $.setFloat64(155 + e * 8, N[e], !0), $.setFloat64(179 + e * 16, I[e], !0), $.setFloat64(187 + e * 16, F[e], !0);
291
+ $.setBigUint64(235, BigInt(pe), !0), $.setUint32(243, 1 + W.length, !0), $.setBigUint64(247, BigInt(P), !0);
292
+ for (let e = 0; e < 15; e++) $.setBigUint64(255 + e * 8, BigInt(E[e]), !0);
293
+ return await e(s([Q, ...G]), 0), {
294
+ points: P,
295
+ nodes: ce,
296
+ depth: J,
297
+ bytes: q
298
+ };
299
+ } finally {
300
+ for (let e of w) await C.delete(e);
301
+ }
302
+ }
303
+ function C(e, t, n = {}) {
304
+ return S(e, t, n);
305
+ }
306
+ async function w(e, t = {}) {
307
+ let n = /* @__PURE__ */ new Uint8Array(65536), r = 0;
308
+ return await S((e, t) => {
309
+ let i = t + e.length;
310
+ if (i > n.length) {
311
+ let e = new Uint8Array(Math.max(i, n.length * 2));
312
+ e.set(n), n = e;
313
+ }
314
+ n.set(e, t), i > r && (r = i);
315
+ }, e, t), n.slice(0, r);
316
+ }
317
+ //#endregion
318
+ export { w as writeCOPC, C as writeCOPCTo };
package/dist/copc.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { type LASHeader, type LASRecord } from './las.js';
2
+ import type { OctreeNode, OctreeNodeData, OctreeSource } from './octree.js';
3
+ /** Options of `CopcSource.open`. */
4
+ export interface CopcOptions {
5
+ /** Used for every range request. Default `globalThis.fetch`. */
6
+ fetch?: typeof fetch;
7
+ /** Cancels the header and hierarchy reads. */
8
+ signal?: AbortSignal;
9
+ }
10
+ /** The file's info record (user id `copc`, record id 1). */
11
+ export interface CopcInfo {
12
+ /** Centre of the octree's cube, world units. */
13
+ readonly center: readonly [number, number, number];
14
+ /** Half of the cube's side. */
15
+ readonly halfSize: number;
16
+ /** Distance between the root node's points. */
17
+ readonly spacing: number;
18
+ readonly rootHierarchyOffset: number;
19
+ readonly rootHierarchySize: number;
20
+ /** Smallest and largest GPS time in the file. */
21
+ readonly gpsTime: readonly [number, number];
22
+ }
23
+ /** Parses the 160-byte COPC info record. Throws a TypeError when the file has none. */
24
+ export declare function copcInfo(records: readonly LASRecord[]): CopcInfo;
25
+ /**
26
+ * An `OctreeSource` over a COPC file on any server that answers range requests: `CopcSource.open(url)`, then
27
+ * `OctreeCloud.attach(engine, points, source)`. The hierarchy pages are read at open, a node's points when it is
28
+ * shown. Positions and bounds are relative to `origin` (the cube's centre), so place the cloud there. A server that
29
+ * ignores `Range` sends the whole file, which works and costs that download per request.
30
+ */
31
+ export declare class CopcSource implements OctreeSource {
32
+ private readonly url;
33
+ private readonly fetcher;
34
+ readonly header: LASHeader;
35
+ readonly records: readonly LASRecord[];
36
+ readonly info: CopcInfo;
37
+ readonly root: OctreeNode;
38
+ /** World position of local [0, 0, 0]: the cube's centre. */
39
+ readonly origin: readonly [number, number, number];
40
+ private constructor();
41
+ /**
42
+ * Whether the file's colours are 16-bit (the specification) or 8-bit values stored as they are, decided once from the
43
+ * first node loaded with colour, the root when `OctreeCloud` draws it: deciding per node would brighten a dark node of
44
+ * a 16-bit file 256 times.
45
+ */
46
+ private wideColors?;
47
+ /**
48
+ * Reads the header, the records and every hierarchy page.
49
+ * @throws MargoError `'failed'` when the server answers an error; TypeError when the file is not COPC; RangeError for
50
+ * a hierarchy that is corrupt; the `signal`'s reason when it aborts.
51
+ */
52
+ static open(url: string | URL, options?: CopcOptions): Promise<CopcSource>;
53
+ /** Fetches and decodes one node's chunk. An empty node gives no points without a request. */
54
+ load(node: OctreeNode, signal: AbortSignal): Promise<OctreeNodeData>;
55
+ }