three-las 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aidan Newsome
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # three-las
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A three.js loader for lidar point clouds: LAS, LAZ and COPC.
4
+
5
+ **[Demo](https://aidannewsome.github.io/three-las/)**
6
+
7
+ ## Install
8
+
9
+ npm install three-las
10
+
11
+ ## Use
12
+
13
+ ```js
14
+ import { LASLoader } from 'three-las'
15
+
16
+ const loader = new LASLoader().setDecoderPath('/decoders/')
17
+ const points = await loader.loadAsync('survey.copc.laz')
18
+ scene.add(points)
19
+ ```
20
+
21
+ For LAZ and COPC, copy `laz-perf.wasm` from `node_modules/laz-perf/lib/web/` into the decoder path.
22
+
23
+ You get one `THREE.Points` with `position`, `color`, `intensity` and `classification`, placed at the file's offset, Z up.
24
+ A COPC file loads its coarsest levels first, up to `maxPoints` (2,000,000).
25
+
26
+ ## License
27
+
28
+ MIT
@@ -0,0 +1,24 @@
1
+ import { Loader, Points, type LoadingManager } from 'three';
2
+ /**
3
+ * Loads a LAS, LAZ or COPC point cloud as one `THREE.Points`, as `PCDLoader` does a PCD.
4
+ *
5
+ * A COPC file is read from its coarsest level down, a level at a time, until the next would pass `maxPoints` (the
6
+ * coarsest is always read), so a large survey loads as an even sample of the whole area; over HTTP, only those levels'
7
+ * bytes are fetched.
8
+ *
9
+ * Positions are stored from the file's offset, small enough for 32-bit floats, and the `Points` is placed at that
10
+ * offset. Coordinates are the file's own, Z up.
11
+ */
12
+ export declare class LASLoader extends Loader<Points> {
13
+ #private;
14
+ /** The most points a COPC file loads, its coarsest levels first, though never fewer than its coarsest level. */
15
+ maxPoints: number;
16
+ /** The folder `laz-perf.wasm` is served from, for LAZ and COPC. Unset, laz-perf looks beside its own script. */
17
+ decoderPath: string;
18
+ constructor(manager?: LoadingManager);
19
+ setDecoderPath(path: string): this;
20
+ setMaxPoints(maxPoints: number): this;
21
+ load(url: string, onLoad: (points: Points) => void, onProgress?: (event: ProgressEvent) => void, onError?: (error: unknown) => void): void;
22
+ /** A whole LAS, LAZ or COPC file already in memory. */
23
+ parse(data: ArrayBuffer): Promise<Points>;
24
+ }
@@ -0,0 +1,156 @@
1
+ import { Copc, Las } from 'copc';
2
+ import { BufferGeometry, Color, SRGBColorSpace, Float32BufferAttribute, Loader, Points, PointsMaterial, Uint8BufferAttribute, } from 'three';
3
+ // A COPC file says so in its first 589 bytes: the LAS header, then the COPC VLR's header and body.
4
+ const COPC_HEAD = 375 + 54 + 160;
5
+ const FIELDS = ['X', 'Y', 'Z', 'Intensity', 'Classification', 'Red', 'Green', 'Blue'];
6
+ /**
7
+ * Loads a LAS, LAZ or COPC point cloud as one `THREE.Points`, as `PCDLoader` does a PCD.
8
+ *
9
+ * A COPC file is read from its coarsest level down, a level at a time, until the next would pass `maxPoints` (the
10
+ * coarsest is always read), so a large survey loads as an even sample of the whole area; over HTTP, only those levels'
11
+ * bytes are fetched.
12
+ *
13
+ * Positions are stored from the file's offset, small enough for 32-bit floats, and the `Points` is placed at that
14
+ * offset. Coordinates are the file's own, Z up.
15
+ */
16
+ export class LASLoader extends Loader {
17
+ /** The most points a COPC file loads, its coarsest levels first, though never fewer than its coarsest level. */
18
+ maxPoints = 2_000_000;
19
+ /** The folder `laz-perf.wasm` is served from, for LAZ and COPC. Unset, laz-perf looks beside its own script. */
20
+ decoderPath = '';
21
+ #lazPerf;
22
+ constructor(manager) {
23
+ super(manager);
24
+ }
25
+ setDecoderPath(path) {
26
+ this.decoderPath = path;
27
+ return this;
28
+ }
29
+ setMaxPoints(maxPoints) {
30
+ this.maxPoints = maxPoints;
31
+ return this;
32
+ }
33
+ load(url, onLoad, onProgress, onError) {
34
+ const resolved = this.manager.resolveURL(this.path + url);
35
+ this.manager.itemStart(resolved);
36
+ this.#fetch(resolved)
37
+ .then(onLoad)
38
+ .catch((error) => {
39
+ if (onError)
40
+ onError(error);
41
+ else
42
+ console.error(error);
43
+ this.manager.itemError(resolved);
44
+ })
45
+ .finally(() => this.manager.itemEnd(resolved));
46
+ }
47
+ /** A whole LAS, LAZ or COPC file already in memory. */
48
+ async parse(data) {
49
+ const file = new Uint8Array(data);
50
+ if (isCopc(file))
51
+ return this.#readCopc(async (begin, end) => file.subarray(begin, end));
52
+ const header = Las.Header.parse(file);
53
+ const records = isCompressed(file)
54
+ ? await Las.PointData.decompressFile(file, await this.#decoder())
55
+ : file.subarray(header.pointDataOffset, header.pointDataOffset + header.pointCount * header.pointDataRecordLength);
56
+ return toPoints([Las.View.create(records, header, [], FIELDS)], header.offset);
57
+ }
58
+ // Over HTTP, its head first: a COPC is then read by ranges, anything else whole.
59
+ async #fetch(url) {
60
+ const get = (begin, end) => fetch(url, {
61
+ headers: { ...this.requestHeader, ...(begin === undefined ? {} : { Range: `bytes=${begin}-${end - 1}` }) },
62
+ credentials: this.withCredentials ? 'include' : 'same-origin',
63
+ }).then((response) => {
64
+ if (!response.ok)
65
+ throw new Error(`${url}: ${response.status} ${response.statusText}`);
66
+ return response;
67
+ });
68
+ const head = await get(0, COPC_HEAD);
69
+ // a server that ignores ranges sends the whole file
70
+ if (head.status !== 206)
71
+ return this.parse(await head.arrayBuffer());
72
+ if (!isCopc(new Uint8Array(await head.arrayBuffer())))
73
+ return this.parse(await (await get()).arrayBuffer());
74
+ return this.#readCopc(async (begin, end) => new Uint8Array(await (await get(begin, end)).arrayBuffer()));
75
+ }
76
+ async #readCopc(getter) {
77
+ const copc = await Copc.create(getter);
78
+ let { nodes, pages } = await Copc.loadHierarchyPage(getter, copc.info.rootHierarchyPage);
79
+ const chosen = [];
80
+ for (let level = 0, total = 0;; level++) {
81
+ // deeper levels' hierarchy pages, loaded only once the levels above them are in
82
+ for (const [key, page] of Object.entries(pages)) {
83
+ if (!page || levelOf(key) !== level)
84
+ continue;
85
+ const subtree = await Copc.loadHierarchyPage(getter, page);
86
+ nodes = { ...nodes, ...subtree.nodes };
87
+ pages = { ...pages, ...subtree.pages, [key]: undefined };
88
+ }
89
+ const here = Object.entries(nodes).flatMap(([key, node]) => (node && levelOf(key) === level ? [node] : []));
90
+ const count = here.reduce((sum, node) => sum + node.pointCount, 0);
91
+ if (here.length === 0 || (total > 0 && total + count > this.maxPoints))
92
+ break;
93
+ chosen.push(...here);
94
+ total += count;
95
+ }
96
+ const lazPerf = await this.#decoder();
97
+ const views = await Promise.all(chosen.map((node) => Copc.loadPointDataView(getter, copc, node, { lazPerf, include: FIELDS })));
98
+ return toPoints(views, copc.header.offset);
99
+ }
100
+ #decoder() {
101
+ const lazPerf = this.#lazPerf ??
102
+ Las.PointData.createLazPerf(this.decoderPath ? { locateFile: (file) => this.decoderPath + file } : {});
103
+ this.#lazPerf = lazPerf;
104
+ return lazPerf;
105
+ }
106
+ }
107
+ const isCopc = (file) => file.length >= COPC_HEAD && String.fromCharCode(...file.subarray(377, 381)) === 'copc';
108
+ // LAZ marks its point format with the top bit
109
+ const isCompressed = (file) => (file[104] & 0x80) !== 0;
110
+ // a COPC node's key: level-x-y-z
111
+ const levelOf = (key) => Number(key.split('-')[0]);
112
+ function toPoints(views, offset) {
113
+ const count = views.reduce((sum, view) => sum + view.pointCount, 0);
114
+ const position = new Float32Array(count * 3);
115
+ const intensity = new Float32Array(count);
116
+ const classification = new Uint8Array(count);
117
+ const hasColor = views.length > 0 && 'Red' in views[0].dimensions;
118
+ const color = hasColor ? new Float32Array(count * 3) : undefined;
119
+ // LAS colour is 16-bit, though many files hold 8-bit values in it
120
+ const deepest = hasColor ? Math.max(...views.map((view) => maxOf(view, 'Red', 'Green', 'Blue'))) : 0;
121
+ const full = deepest > 255 ? 65535 : 255;
122
+ const srgb = new Color();
123
+ let at = 0;
124
+ for (const view of views) {
125
+ const [x, y, z, i, c] = ['X', 'Y', 'Z', 'Intensity', 'Classification'].map((name) => view.getter(name));
126
+ const [r, g, b] = hasColor ? ['Red', 'Green', 'Blue'].map((name) => view.getter(name)) : [];
127
+ for (let n = 0; n < view.pointCount; n++, at++) {
128
+ position[at * 3] = x(n) - offset[0];
129
+ position[at * 3 + 1] = y(n) - offset[1];
130
+ position[at * 3 + 2] = z(n) - offset[2];
131
+ intensity[at] = i(n);
132
+ classification[at] = c(n);
133
+ if (color)
134
+ srgb.setRGB(r(n) / full, g(n) / full, b(n) / full, SRGBColorSpace).toArray(color, at * 3);
135
+ }
136
+ }
137
+ const geometry = new BufferGeometry();
138
+ geometry.setAttribute('position', new Float32BufferAttribute(position, 3));
139
+ if (color)
140
+ geometry.setAttribute('color', new Float32BufferAttribute(color, 3));
141
+ geometry.setAttribute('intensity', new Float32BufferAttribute(intensity, 1));
142
+ geometry.setAttribute('classification', new Uint8BufferAttribute(classification, 1));
143
+ geometry.computeBoundingSphere();
144
+ const points = new Points(geometry, new PointsMaterial({ vertexColors: hasColor }));
145
+ points.position.set(...offset);
146
+ return points;
147
+ }
148
+ function maxOf(view, ...names) {
149
+ let max = 0;
150
+ for (const name of names) {
151
+ const get = view.getter(name);
152
+ for (let n = 0; n < view.pointCount; n++)
153
+ max = Math.max(max, get(n));
154
+ }
155
+ return max;
156
+ }
@@ -0,0 +1 @@
1
+ export { LASLoader } from './LASLoader.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { LASLoader } from './LASLoader.js';
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "three-las",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A three.js loader for lidar point clouds: LAS, LAZ and COPC.",
5
+ "keywords": [
6
+ "copc",
7
+ "las",
8
+ "laz",
9
+ "lidar",
10
+ "loader",
11
+ "point cloud",
12
+ "three",
13
+ "three.js",
14
+ "threejs"
15
+ ],
16
+ "homepage": "https://aidannewsome.github.io/three-las/",
17
+ "bugs": "https://github.com/aidannewsome/three-las/issues",
18
+ "license": "MIT",
19
+ "author": "Aidan Newsome",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/aidannewsome/three-las.git"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ }
34
+ },
35
+ "dependencies": {
36
+ "copc": "^0.0.9"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^24.19.4",
40
+ "@types/three": "^0.187.0",
41
+ "oxfmt": "^0.80.0",
42
+ "oxlint": "^1.95.0",
43
+ "oxlint-tsgolint": "^7.0.2009",
44
+ "three": "^0.187.0",
45
+ "typescript": "~7.0",
46
+ "vite": "^8.4.0",
47
+ "vitest": "^5.1.2"
48
+ },
49
+ "peerDependencies": {
50
+ "three": ">=0.170.0"
51
+ }
52
+ }