@speridlabs/visus 0.1.0 → 0.3.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/README.md CHANGED
@@ -1,155 +1,123 @@
1
- # Visus - Gaussian Splatting for Three.js
1
+ # Visus
2
2
 
3
- Visus is a high-performance WebGL library designed to seamlessly integrate real-time 3D Gaussian Splatting (3DGS) rendering into [Three.js](https://threejs.org/) applications. It focuses on speed and optimization to deliver smooth rendering experiences directly within your existing Three.js scenes.
3
+ ![Visus Demo](./public/demo.png)
4
4
 
5
- ## Installation
5
+ **High‑performance Gaussian Splatting** (3DGS) for [Three.js](https://threejs.org/) and React‑Three‑Fiber.
6
+ Drop in a `SplatMesh` or `<Splat>` component, feed it a `.ply`, and render millions of splats with correct transparency and minimal overhead.
7
+
8
+ ---
9
+
10
+ ## 🚀 Installation
6
11
 
7
12
  ```bash
8
- # Using npm
9
- npm install visus
13
+ # npm
14
+ npm install @speridlabs/visus three
10
15
 
11
- # Using yarn
12
- yarn add visus
16
+ # yarn
17
+ yarn add @speridlabs/visus three
18
+
19
+ # pnpm
20
+ pnpm add @speridlabs/visus three
13
21
 
14
- # Using pnpm
15
- pnpm add visus
16
22
  ```
17
23
 
18
- ## Key Features
24
+ > Visus treats Three.js as a peer dependency—make sure it's installed alongside.
25
+
26
+ ---
19
27
 
20
- - **Three.js Integration:** Designed as a `THREE.Mesh`-like object (`SplatMesh`) for easy addition to Three.js scenes.
21
- - **Customizable Material:** Offers options for controlling rendering appearance.
22
- - **Optimized Performance:** Leverages several techniques for speed:
23
- - **GPU Sorting:** Performs view-dependent sorting in a Web Worker to avoid blocking the main thread, ensuring correct transparency.
24
- - **Instanced Rendering:** Draws multiple splats per draw call using GPU instancing.
25
- - **Efficient Texture Packing:** Packs rotation and scale data tightly into GPU textures.
26
- - **Optimized Shaders:** Includes early discards and efficient math operations in GLSL shaders.
28
+ ## 🔑 Key Features
27
29
 
28
- ## Basic Usage
30
+ * **Mesh‑like API**: `new SplatMesh(data, options)` behaves like a `THREE.Mesh`.
31
+ * **React wrapper**: `<Splat plyUrl="..." splatOptions={{…}} />` for R3F apps.
32
+ * **Web Worker sorting**: non‑blocking depth sort for correct transparency.
33
+ * **GPU instancing**: draw hundreds of splats in a single call.
34
+ * **Packed textures**: compact quaternion & scale storage.
35
+ * **Shader culling**: early discards, premultiplied alpha.
29
36
 
30
- ```typescript
31
- // main.ts
37
+ ---
38
+
39
+ ## 🎯 Quickstart
40
+
41
+ ### Plain Three.js
42
+
43
+ ```js
32
44
  import * as THREE from 'three';
33
45
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
34
- import { PlyLoader, SplatMesh, SplatData } from 'visus'; // Import from visus
35
-
36
- // 1. Basic Three.js Scene Setup
37
- const scene = new THREE.Scene();
38
- const camera = new THREE.PerspectiveCamera(
39
- 75,
40
- window.innerWidth / window.innerHeight,
41
- 0.1,
42
- 1000,
43
- );
46
+ import { PlyLoader, SplatMesh } from '@speridlabs/visus';
47
+
48
+ const scene = new THREE.Scene();
49
+ const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 100);
44
50
  camera.position.set(0, 1, 3);
45
51
 
46
52
  const renderer = new THREE.WebGLRenderer({ antialias: true });
47
53
  renderer.setSize(window.innerWidth, window.innerHeight);
48
- renderer.setAnimationLoop(animate);
49
54
  document.body.appendChild(renderer.domElement);
50
55
 
51
56
  const controls = new OrbitControls(camera, renderer.domElement);
52
- controls.enableDamping = true;
53
-
54
- // 2. Load the Splat File
55
- // IMPORTANT: Place your PLY file (e.g., sample.ply) in your project's `public/` directory
56
- // or serve it from a location accessible by the browser.
57
- const loader = new PlyLoader();
58
- const plyUrl = '/sample.ply'; // Adjust path as needed
59
-
60
- async function loadAndDisplaySplat() {
61
- try {
62
- console.log(`Loading splat from ${plyUrl}...`);
63
- const splatData: SplatData = await loader.loadAsync(plyUrl);
64
- console.log(`Loaded ${splatData.numSplats} splats.`);
65
-
66
- // 3. Create the SplatMesh
67
- // autoSort: true enables automatic sorting based on camera view (recommended)
68
- const splatMesh = new SplatMesh(splatData, { autoSort: true });
69
-
70
- // Optional: Apply transformations if needed (e.g., correct orientation)
71
- // splatMesh.rotation.set(0, 0, Math.PI);
72
-
73
- // 4. Add to Scene
74
- scene.add(splatMesh);
75
- console.log('SplatMesh added to scene.');
76
-
77
- // Optional: Focus camera on the splat
78
- if (splatMesh.geometry.boundingBox) {
79
- const center = new THREE.Vector3();
80
- splatMesh.geometry.boundingBox.getCenter(center);
81
- controls.target.copy(center);
82
-
83
- const sphere = new THREE.Sphere();
84
- splatMesh.geometry.boundingBox.getBoundingSphere(sphere);
85
- camera.position
86
- .copy(center)
87
- .add(new THREE.Vector3(0, 0, sphere.radius * 2));
88
- camera.lookAt(center);
89
- controls.update();
90
- }
91
- } catch (error) {
92
- console.error('Error loading splat:', error);
93
- // Display error to user
94
- }
95
- }
96
-
97
- loadAndDisplaySplat(); // Start loading
98
57
 
99
- // 5. Animation Loop
100
- function animate() {
101
- controls.update(); // Required if damping is enabled
102
- renderer.render(scene, camera);
103
- }
58
+ (async () => {
59
+ const data = await new PlyLoader().loadAsync('/sample.ply');
60
+ const mesh = new SplatMesh(data, { autoSort: true });
61
+ scene.add(mesh);
62
+ })();
104
63
 
105
- // Handle window resize
106
- window.addEventListener('resize', () => {
107
- camera.aspect = window.innerWidth / window.innerHeight;
108
- camera.updateProjectionMatrix();
109
- renderer.setSize(window.innerWidth, window.innerHeight);
64
+ renderer.setAnimationLoop(() => {
65
+ controls.update();
66
+ renderer.render(scene, camera);
110
67
  });
111
68
  ```
112
69
 
113
- _(See `examples/main.ts` for a more complete example setup)_
70
+ ### React‑Three‑Fiber (R3F)
71
+
72
+ ```tsx
73
+ import React from 'react';
74
+ import { Canvas } from '@react-three/fiber';
75
+ import { Splat } from '@speridlabs/visus/react';
76
+
77
+ export default function App() {
78
+ return (
79
+ <Canvas camera={{ position: [0, 1, 3] }}>
80
+ <ambientLight />
81
+ <Splat plyUrl="/sample.ply" splatOptions={{ autoSort: true }} />
82
+ </Canvas>
83
+ );
84
+ }
85
+ ```
114
86
 
115
- ## API Overview
87
+ ---
116
88
 
117
- - **`PlyLoader`**: Loads `.ply` files containing Gaussian Splat data. Use `loadAsync` for Promise-based loading.
118
- - **`SplatData`**: Internal representation holding the raw data (positions, rotations, scales, colors, opacities) for all splats.
119
- - **`SplatMesh`**: The main renderable object. Add this to your `THREE.Scene`. It manages the geometry, material, and sorting. Takes `SplatData` and optional `SplatMeshOptions` in its constructor.
120
- - `options.autoSort` (default `true`): Automatically triggers sorting based on camera movement.
121
- - **`SplatMaterial`**: The `THREE.ShaderMaterial` used internally by `SplatMesh`. Handles the actual splat rendering logic. Can be customized via `SplatMaterialOptions`.
122
- - **`SplatSorter`**: Manages the Web Worker responsible for view-dependent sorting. Generally used internally by `SplatMesh`.
123
- - **`TextureManager`**: Handles packing splat data into GPU textures. Used internally.
89
+ ## 📦 API Overview
124
90
 
125
- ## Performance Optimizations
91
+ | Export | Description |
92
+ | -------------- | -------------------------------------------------------------- |
93
+ | `PlyLoader` | `.loadAsync(url): Promise<SplatData>` |
94
+ | `SplatData` | Raw buffers of positions, rotations, scales, colors, opacities |
95
+ | `SplatMesh` | `new SplatMesh(data, options?)` → a `THREE.Mesh` |
96
+ | `SplatOptions` | `{ autoSort?: boolean; /* … */ }` |
97
+ | `Splat` | React component wrapping `SplatMesh` |
98
+ | `VERSION` | Library version string |
126
99
 
127
- Visus employs several techniques documented in `Optimizations.md` to achieve real-time performance:
100
+ ---
128
101
 
129
- - **GPU Sorting via Web Worker:** Sorts splats by depth off the main thread using a distance-based counting sort, preventing stutter and ensuring correct alpha blending.
130
- - **Instanced Rendering:** Renders many splats (typically 128) in a single draw call, reducing CPU overhead.
131
- - **Packed Data Textures:** Stores rotation and scale data efficiently in textures, minimizing GPU memory bandwidth. Rotation quaternions are packed, reconstructing the `w` component in the shader. Scale is stored logarithmically.
132
- - **Shader Optimizations:** Uses early checks in vertex and fragment shaders to discard splats/fragments that won't be visible (behind near plane, too small, fully transparent, outside ellipse), reducing GPU workload.
133
- - **Premultiplied Alpha Blending:** Uses standard premultiplied alpha for correct transparency compositing.
102
+ ## 🔧 Performance Highlights
134
103
 
135
- ## Future Development / Roadmap
104
+ * **Off‑thread sorting** via Web Worker
105
+ * **Instanced draw calls** for minimal CPU overhead
106
+ * **Packed data textures** reduce memory bandwidth
107
+ * **Shader‑level early exit** for invisible splats
136
108
 
137
- Based on the analysis in `Optimizations.md`, potential future enhancements include:
109
+ ---
138
110
 
139
- - Support for Spherical Harmonics (SH) for view-dependent color effects.
140
- - Implementing spatial data reordering (e.g., Morton order) before GPU upload for improved cache coherency.
141
- - Exploring more advanced texture compression or lower-precision formats (like half-floats or uint8) for attributes like color and scale to further reduce GPU memory usage.
142
- - Adding streamed loading capabilities to handle very large `.ply` files more efficiently in terms of RAM.
143
- - Investigating multi-chunk based sorting optimizations for better key distribution with non-uniform datasets.
144
- - Adding optional dithering techniques as an alternative to alpha blending.
145
- - Implementing more sophisticated culling methods.
111
+ ## 🤝 Contributing
146
112
 
147
- ## Contributing
113
+ 1. Fork & clone
114
+ 2. `pnpm install`
115
+ 3. `pnpm lint && pnpm build`
116
+ 4. Open a PR!
148
117
 
149
- Contributions are welcome! If you find a bug or have a feature request, please open an issue on the GitHub repository.
118
+ ---
150
119
 
151
- For pull requests, please ensure your code adheres to the project's linting (`pnpm lint`) and formatting (`pnpm format`) standards.
120
+ ## 📄 License
152
121
 
153
- ## License
122
+ Apache 2.0 © Sperid Labs
154
123
 
155
- Visus is licensed under the [Apache License 2.0](LICENSE).
package/dist/main.d.ts ADDED
@@ -0,0 +1,320 @@
1
+ import * as THREE from 'three';
2
+
3
+ /**
4
+ * Simplified bounding box class that tracks min/max points
5
+ */
6
+ export declare class BoundingBox {
7
+ min: THREE.Vector3;
8
+ max: THREE.Vector3;
9
+ center: THREE.Vector3;
10
+ /** Half extents (size/2) */
11
+ halfExtents: THREE.Vector3;
12
+ /**
13
+ * Reset the bounding box to its initial state
14
+ */
15
+ reset(): void;
16
+ /**
17
+ * Expand the bounding box to include the given point
18
+ * @param point Point to include in the bounding box
19
+ */
20
+ expandByPoint(point: THREE.Vector3): void;
21
+ /**
22
+ * Expand this bounding box to include another bounding box
23
+ * @param box Bounding box to include
24
+ */
25
+ expandByBox(box: BoundingBox): void;
26
+ /**
27
+ * Update the center and half extents based on min/max
28
+ */
29
+ private updateDerived;
30
+ /**
31
+ * Check if this box contains a point
32
+ * @param point Point to check
33
+ * @returns True if the point is inside the box
34
+ */
35
+ containsPoint(point: THREE.Vector3): boolean;
36
+ /**
37
+ * Create a Three.js Box3 from this bounding box
38
+ * @returns THREE.Box3 representation
39
+ */
40
+ toBox3(): THREE.Box3;
41
+ /**
42
+ * Create a clone of this bounding box
43
+ * @returns New bounding box with the same values
44
+ */
45
+ clone(): BoundingBox;
46
+ }
47
+
48
+ /**
49
+ * Class for loading PLY files with Gaussian Splat data
50
+ */
51
+ export declare class PlyLoader extends THREE.Loader {
52
+ /**
53
+ * Load a PLY file with Gaussian Splat data
54
+ * @param url URL of the PLY file
55
+ * @param onLoad Optional callback when loading is complete
56
+ * @param onProgress Optional progress callback
57
+ * @param onError Optional error callback
58
+ */
59
+ load(url: string, onLoad?: (data: SplatData) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void;
60
+ /**
61
+ * Load a PLY file asynchronously and return a Promise
62
+ * @param url URL of the PLY file
63
+ * @param onProgress Optional progress callback
64
+ * @returns A Promise that resolves with the parsed SplatData
65
+ */
66
+ loadAsync(url: string, onProgress?: (event: ProgressEvent) => void): Promise<SplatData>;
67
+ /**
68
+ * Parse PLY buffer data into SplatData
69
+ * @param buffer ArrayBuffer containing PLY data
70
+ * @returns Parsed SplatData
71
+ */
72
+ parse(buffer: ArrayBuffer): SplatData;
73
+ }
74
+
75
+ export declare class SplatData {
76
+ numSplats: number;
77
+ positions: Float32Array;
78
+ rotations: Float32Array;
79
+ scales: Float32Array;
80
+ colors: Float32Array;
81
+ opacities: Float32Array;
82
+ centers: Float32Array;
83
+ boundingBox: BoundingBox;
84
+ constructor(numSplats?: number);
85
+ private allocateBuffers;
86
+ /**
87
+ * Set data for a specific splat
88
+ * @param index Splat index
89
+ * @param position Position vector
90
+ * @param rotation Quaternion
91
+ * @param scale Scale vector (expects LOG SCALE)
92
+ * @param color Color
93
+ * @param opacity Opacity value
94
+ */
95
+ setSplat(index: number, position: THREE.Vector3, rotation: THREE.Quaternion, scale: THREE.Vector3, color: THREE.Color, opacity: number): void;
96
+ /**
97
+ * Get a splat's data
98
+ * @param index Splat index
99
+ * @returns Object containing splat data (linear scale)
100
+ */
101
+ getSplat(index: number): {
102
+ position: THREE.Vector3;
103
+ rotation: THREE.Quaternion;
104
+ scale: THREE.Vector3;
105
+ color: THREE.Color;
106
+ opacity: number;
107
+ };
108
+ /**
109
+ * Calculate the bounding box for all splats
110
+ * NOTE: Currently it only uses positions, not the actual splat bounds
111
+ */
112
+ calculateBoundingBox(): BoundingBox;
113
+ /**
114
+ * Create a Three.js BufferGeometry from this splat data
115
+ * This is for visualization/debugging purposes only, not for rendering
116
+ */
117
+ createDebugGeometry(): THREE.BufferGeometry;
118
+ }
119
+
120
+ export declare class SplatMaterial extends THREE.ShaderMaterial {
121
+ constructor(options?: SplatMaterialOptions);
122
+ /**
123
+ * Update the viewport size
124
+ * @param width Viewport width
125
+ * @param height Viewport height
126
+ */
127
+ updateViewport(width: number, height: number): void;
128
+ /**
129
+ * Set transform texture A (positions)
130
+ * @param texture Texture containing positions
131
+ */
132
+ setTransformA(texture: THREE.Texture): void;
133
+ /**
134
+ * Set transform texture B (rotation, scale)
135
+ * @param texture Texture containing rotation and scale data
136
+ */
137
+ setTransformB(texture: THREE.Texture): void;
138
+ /**
139
+ * Set color texture
140
+ * @param texture Texture containing colors
141
+ */
142
+ setColorTexture(texture: THREE.Texture): void;
143
+ /**
144
+ * Set order texture
145
+ * @param texture Texture containing sort order
146
+ */
147
+ setOrderTexture(texture: THREE.Texture): void;
148
+ /**
149
+ * Set number of splats to render
150
+ * @param count Number of splats
151
+ */
152
+ setNumSplats(count: number): void;
153
+ }
154
+
155
+ export declare interface SplatMaterialOptions {
156
+ alphaTest?: number;
157
+ alphaHash?: boolean;
158
+ toneMapped?: boolean;
159
+ }
160
+
161
+ /**
162
+ * A mesh that renders Gaussian splats
163
+ * Not a real MESH, but a custom geometry with instancing
164
+ */
165
+ export declare class SplatMesh extends THREE.Mesh {
166
+ sorter: SplatSorter;
167
+ splatData: SplatData;
168
+ options: SplatMeshOptions;
169
+ textureManager: TextureManager;
170
+ material: SplatMaterial;
171
+ geometry: THREE.InstancedBufferGeometry;
172
+ private lastCameraPositionLocal;
173
+ private lastCameraDirectionLocal;
174
+ private invModelMatrix;
175
+ /** Number of splats combined into a single instanced draw call. */
176
+ private static INSTANCE_SIZE;
177
+ /**
178
+ * Create a new SplatMesh for rendering Gaussian splats
179
+ * @param splatData The splat data to render
180
+ * @param options Rendering options
181
+ */
182
+ constructor(splatData: SplatData, options?: SplatMeshOptions);
183
+ /**
184
+ * Creates the instanced geometry for rendering splats.
185
+ * @param totalSplats Total number of splats in the data.
186
+ * @param instanceSize Number of splats per instance.
187
+ * @returns InstancedBufferGeometry
188
+ */
189
+ private static createInstancedGeometry;
190
+ /**
191
+ * Create chunks data (bounding box min/max) for the sorter.
192
+ * @returns Float32Array containing chunk data [minX, minY, minZ, maxX, maxY, maxZ] or null.
193
+ */
194
+ private createChunks;
195
+ /**
196
+ * Update the viewport size
197
+ * @param width Viewport width
198
+ * @param height Viewport height
199
+ */
200
+ updateViewport(width: number, height: number): void;
201
+ /**
202
+ * Sorts splats based on camera position and direction.
203
+ * @param camera The camera to sort against.
204
+ */
205
+ sort(camera: THREE.Camera): void;
206
+ /**
207
+ * THREE.js hook called before rendering the object.
208
+ * Used here to trigger sorting and update viewport.
209
+ * @param renderer The renderer
210
+ * @param scene The scene
211
+ * @param camera The camera
212
+ */
213
+ onBeforeRender(renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.Camera): void;
214
+ /**
215
+ * Dispose of resources
216
+ */
217
+ dispose(): void;
218
+ }
219
+
220
+ export declare interface SplatMeshOptions extends SplatMaterialOptions {
221
+ autoSort?: boolean;
222
+ }
223
+
224
+ /**
225
+ * Manages sorting of splats based on camera view using a Web Worker.
226
+ */
227
+ export declare class SplatSorter extends THREE.EventDispatcher<{
228
+ updated: SplatSortUpdateEvent;
229
+ }> {
230
+ private worker;
231
+ private centers;
232
+ private orderTexture;
233
+ /** Bounding box data for optimization */
234
+ private chunks;
235
+ private lastCameraPosition;
236
+ private lastCameraDirection;
237
+ constructor();
238
+ /**
239
+ * Handles messages received from the sorting worker.
240
+ * @param event The message event from the worker.
241
+ */
242
+ private onWorkerMessage;
243
+ /**
244
+ * Initializes the sorter with necessary data and textures.
245
+ * @param orderTexture The THREE.DataTexture (R32UI) to store the sorted splat indices.
246
+ * @param centers A Float32Array containing the center position (x, y, z) for each splat.
247
+ * @param chunks Optional: A Float32Array containing bounding box chunk data [minX, minY, minZ, maxX, maxY, maxZ, ...] for optimization.
248
+ */
249
+ init(orderTexture: THREE.DataTexture, centers: Float32Array, chunks?: Float32Array): void;
250
+ /**
251
+ * Applies an optional mapping to filter or reorder splats before sorting.
252
+ * The sorter will only consider splats whose original indices are present in the mapping.
253
+ * @param mapping A Uint32Array where each element is the *original* index of a splat to include, or null to reset mapping.
254
+ */
255
+ setMapping(mapping: Uint32Array | null): void;
256
+ /**
257
+ * Updates the camera parameters used for sorting.
258
+ * @param position The camera's position in the sorter's local coordinate space.
259
+ * @param direction The camera's forward direction in the sorter's local coordinate space.
260
+ */
261
+ setCamera(position: THREE.Vector3, direction: THREE.Vector3): void;
262
+ /**
263
+ * Terminates the Web Worker and cleans up resources.
264
+ */
265
+ dispose(): void;
266
+ /**
267
+ * Creates the self-contained code for the sorting Web Worker.
268
+ * @returns A string containing the JavaScript code for the worker.
269
+ */
270
+ private createWorkerCode;
271
+ }
272
+
273
+ /** Event dispatched when the sort is updated */
274
+ declare interface SplatSortUpdateEvent extends THREE.Event {
275
+ type: 'updated';
276
+ count: number;
277
+ }
278
+
279
+ export declare class TextureManager {
280
+ transformA: THREE.DataTexture;
281
+ transformB: THREE.DataTexture;
282
+ colorTexture: THREE.DataTexture;
283
+ orderTexture: THREE.DataTexture;
284
+ textureWidth: number;
285
+ textureHeight: number;
286
+ /**
287
+ * Create a new TextureManager for a set of splats
288
+ * @param splatData The splat data to manage textures for
289
+ */
290
+ constructor(splatData: SplatData);
291
+ /**
292
+ * Create the transform A texture (positions and quaternion w component)
293
+ * @param splatData The splat data
294
+ * @returns DataTexture containing position data
295
+ */
296
+ private createTransformATexture;
297
+ /**
298
+ * Create the transform B texture (scale and rotation xyz)
299
+ * @param splatData The splat data
300
+ * @returns DataTexture containing scale and rotation data
301
+ */
302
+ private createTransformBTexture;
303
+ /**
304
+ * Create the color texture (RGB and opacity)
305
+ * @param splatData The splat data
306
+ * @returns DataTexture containing color data
307
+ */
308
+ private createColorTexture;
309
+ /**
310
+ * Create the order texture for sorting
311
+ * @param numSplats Number of splats
312
+ * @returns DataTexture for storing order indices
313
+ */
314
+ private createOrderTexture;
315
+ dispose(): void;
316
+ }
317
+
318
+ export declare const VERSION = "0.2.0";
319
+
320
+ export { }