File size: 9,931 Bytes
6ce4ca6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
<script lang="ts">
	import { T } from "@threlte/core";
	import { Align, OrbitControls } from "@threlte/extras";
	import { BufferGeometry, Vector3, Color, BufferAttribute, Euler, Matrix4 } from "three";

	// Props for external data input
	interface Props {
		// External RGBD data input (optional)
		inputRGBData?: Uint8Array;
		inputDepthData?: Float32Array;
		inputWidth?: number;
		inputHeight?: number;
		inputCameraIntrinsics?: {
			fx: number;
			fy: number;
			cx: number;
			cy: number;
		};
		// Visual settings (optional)
		initialColorMode?: ColorMode;
		initialPointSize?: number;
		initialScale?: number;
		useMockData?: boolean;
		cameraPositionX?: number;
		cameraPositionY?: number;
		cameraPositionZ?: number;
		cameraRotationX?: number;
		cameraRotationY?: number;
		cameraRotationZ?: number;
	}

	let {
		inputRGBData,
		inputDepthData,
		inputWidth,
		inputHeight,
		inputCameraIntrinsics,
		initialColorMode = "mixed",
		initialPointSize = 0.1,
		initialScale = 2.0,
		useMockData = true,
		cameraPositionX = $bindable(0),
		cameraPositionY = $bindable(0),
		cameraPositionZ = $bindable(5),
		cameraRotationX = $bindable(0),
		cameraRotationY = $bindable(0),
		cameraRotationZ = $bindable(0)
	}: Props = $props();

	// Camera system with Svelte 5 runes
	let pointSize = $state(initialPointSize);
	let maxDepth = $state(3.0);
	let minDepth = $state(0.1);
	let pointCloudScale = $state(initialScale); // Scale factor to spread out the point cloud
	let colorMode = $state<ColorMode>(initialColorMode);
	let pointStyle = $state<PointStyle>("circle");
	let brightness = $state(1.0);
	let contrast = $state(1.0);

	// Color mode types
	type ColorMode = "depth" | "rgb" | "mixed" | "grayscale" | "height";
	type PointStyle = "square" | "circle" | "shader";

	// RGBD Data structure
	interface RGBDData {
		width: number;
		height: number;
		rgbData: Uint8Array; // RGB channels (width * height * 3)
		depthData: Float32Array; // Depth values in meters (width * height)
		cameraIntrinsics: {
			fx: number;
			fy: number; // Focal lengths
			cx: number;
			cy: number; // Principal point
		};
	}

	// Generate mock 64x64 RGBD data
	function generateMockRGBD(): RGBDData {
		const width = 64;
		const height = 64;
		const rgbData = new Uint8Array(width * height * 3);
		const depthData = new Float32Array(width * height);

		// Generate some interesting depth patterns and colors
		for (let y = 0; y < height; y++) {
			for (let x = 0; x < width; x++) {
				const idx = y * width + x;
				const rgbIdx = idx * 3;

				// Create a wave pattern for depth
				const centerX = width / 2;
				const centerY = height / 2;
				const distFromCenter = Math.sqrt((x - centerX) ** 2 + (y - centerY) ** 2);
				const waveDepth = 1.5 + 0.8 * Math.sin(distFromCenter * 0.3) * Math.cos(x * 0.2);

				// Add some noise
				const noise = (Math.random() - 0.5) * 0.2;
				depthData[idx] = Math.max(0.1, waveDepth + noise);

				// Generate more interesting RGB patterns
				const r = Math.floor(128 + 127 * Math.sin(x * 0.1) * Math.cos(y * 0.1));
				const g = Math.floor(128 + 127 * Math.sin((x + y) * 0.05));
				const b = Math.floor(128 + 127 * Math.cos(distFromCenter * 0.1));

				rgbData[rgbIdx] = Math.max(0, Math.min(255, r)); // R
				rgbData[rgbIdx + 1] = Math.max(0, Math.min(255, g)); // G
				rgbData[rgbIdx + 2] = Math.max(0, Math.min(255, b)); // B
			}
		}

		return {
			width,
			height,
			rgbData,
			depthData,
			cameraIntrinsics: {
				fx: 50.0,
				fy: 50.0,
				cx: width / 2,
				cy: height / 2
			}
		};
	}

	// Create RGBD data from external input or mock data
	function createRGBDData(): RGBDData {
		// Use external data if provided
		if (!useMockData && inputRGBData && inputDepthData && inputWidth && inputHeight) {
			return {
				width: inputWidth,
				height: inputHeight,
				rgbData: inputRGBData,
				depthData: inputDepthData,
				cameraIntrinsics: inputCameraIntrinsics || {
					fx: 50.0,
					fy: 50.0,
					cx: inputWidth / 2,
					cy: inputHeight / 2
				}
			};
		}

		// Fallback to mock data
		return generateMockRGBD();
	}

	// Convert depth value to color (rainbow mapping)
	function depthToColor(depth: number, minDepth: number, maxDepth: number): Color {
		// Normalize depth to 0-1 range
		const normalizedDepth = Math.max(0, Math.min(1, (depth - minDepth) / (maxDepth - minDepth)));

		// Rainbow color mapping: Red (near) -> Green -> Blue (far)
		const hue = ((1 - normalizedDepth) * 240) / 360; // 240° = blue, 0° = red
		const saturation = 1.0;
		const lightness = 0.5;

		return new Color().setHSL(hue, saturation, lightness);
	}

	// Get color based on selected mode
	function getPointColor(
		x: number,
		y: number,
		depth: number,
		rgbData: Uint8Array,
		rgbdData: RGBDData
	): Color {
		const idx = y * rgbdData.width + x;
		const rgbIdx = idx * 3;

		switch (colorMode) {
			case "depth":
				return depthToColor(depth, minDepth, maxDepth);

			case "rgb":
				const r = rgbData[rgbIdx] / 255;
				const g = rgbData[rgbIdx + 1] / 255;
				const b = rgbData[rgbIdx + 2] / 255;
				return new Color(r * brightness, g * brightness, b * brightness);

			case "mixed":
				const rgbColor = new Color(
					rgbData[rgbIdx] / 255,
					rgbData[rgbIdx + 1] / 255,
					rgbData[rgbIdx + 2] / 255
				);
				const depthColor = depthToColor(depth, minDepth, maxDepth);
				// Mix RGB with depth-based intensity
				const depthIntensity = 1 - (depth - minDepth) / (maxDepth - minDepth);
				return rgbColor.multiplyScalar(depthIntensity * brightness + 0.3);

			case "grayscale":
				const normalizedDepth = (depth - minDepth) / (maxDepth - minDepth);
				const intensity = (1 - normalizedDepth) * brightness;
				return new Color(intensity, intensity, intensity);

			case "height":
				// Color based on Y position (height)
				const worldY = (-(y - rgbdData.cameraIntrinsics.cy) * depth) / rgbdData.cameraIntrinsics.fy;
				const normalizedHeight = (worldY + 2) / 4; // Assuming height range -2 to 2
				const heightHue = (normalizedHeight * 120) / 360; // Green to red
				return new Color().setHSL(heightHue, 0.8, 0.5);

			default:
				return depthToColor(depth, minDepth, maxDepth);
		}
	}

	// Convert pixel coordinates + depth to 3D world coordinates
	function pixelTo3D(
		x: number,
		y: number,
		depth: number,
		intrinsics: RGBDData["cameraIntrinsics"]
	): Vector3 {
		const worldX = ((x - intrinsics.cx) * depth) / intrinsics.fx;
		const worldY = (-(y - intrinsics.cy) * depth) / intrinsics.fy; // Flip Y for correct orientation
		const worldZ = -depth; // Negative Z for forward direction

		// Apply scaling factor to spread out the point cloud
		return new Vector3(worldX * pointCloudScale, worldY * pointCloudScale, worldZ);
	}

	// Generate point cloud geometry from RGBD data
	function generatePointCloudGeometry(rgbdData: RGBDData): BufferGeometry {
		const positions: number[] = [];
		const colors: number[] = [];

		for (let y = 0; y < rgbdData.height; y++) {
			for (let x = 0; x < rgbdData.width; x++) {
				const idx = y * rgbdData.width + x;
				const depth = rgbdData.depthData[idx];

				// Skip invalid depth values
				if (depth <= 0 || depth > maxDepth) continue;

				// Convert to 3D coordinates (in camera space)
				const point3D = pixelTo3D(x, y, depth, rgbdData.cameraIntrinsics);

				// Use the points directly in camera space - parent will handle transformations
				positions.push(point3D.x, point3D.y, point3D.z);

				// Get color based on selected mode
				const color = getPointColor(x, y, depth, rgbdData.rgbData, rgbdData);
				colors.push(color.r, color.g, color.b);
			}
		}

		const geometry = new BufferGeometry();
		geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
		geometry.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3));

		return geometry;
	}

	// Initialize RGBD data
	let rgbdData = $state(createRGBDData());
	let pointCloudGeometry = $state<BufferGeometry>();

	// Reactive geometry updates
	$effect(() => {
		// React to changes in rgbd data, depth range, scale, or visual settings
		rgbdData;
		maxDepth;
		minDepth;
		pointCloudScale;
		colorMode;
		brightness;
		contrast;

		pointCloudGeometry = generatePointCloudGeometry(rgbdData);
	});

	// Watch for external data changes
	$effect(() => {
		// React to external input changes
		inputRGBData;
		inputDepthData;
		inputWidth;
		inputHeight;
		inputCameraIntrinsics;
		useMockData;

		rgbdData = createRGBDData();
	});
</script>

{#if pointCloudGeometry}
	<T.Group
		position={[cameraPositionX, cameraPositionY, cameraPositionZ]}
		rotation={[cameraRotationX, cameraRotationY, cameraRotationZ]}
		onpointerenter={(e) => e.stopPropagation()}
		onpointerleave={(e) => e.stopPropagation()}
		onpointerdown={(e) => e.stopPropagation()}
		onpointerup={(e) => e.stopPropagation()}
		onpointermove={(e) => e.stopPropagation()}
		onclick={(e) => e.stopPropagation()}
	>
		<!-- Debug visualization: small cube at camera position -->
		<!-- <T.Mesh position={[0, 0, 0]}>
			<T.BoxGeometry args={[0.1, 0.1, 0.1]} />
			<T.MeshBasicMaterial color="red" />
		</T.Mesh> -->

		<!-- Debug visualization: cone pointing in camera direction -->
		<!-- <T.Mesh position={[0, 0, -0.2]} rotation={[Math.PI / 2, 0, 0]}>
			<T.ConeGeometry args={[0.05, 0.2, 8]} />
			<T.MeshBasicMaterial color="blue" />
		</T.Mesh> -->

		<!-- The actual pointcloud -->
		<T.Points
			geometry={pointCloudGeometry}
			onpointerenter={(e) => e.stopPropagation()}
			onpointerleave={(e) => e.stopPropagation()}
			onpointerdown={(e) => e.stopPropagation()}
			onpointerup={(e) => e.stopPropagation()}
			onpointermove={(e) => e.stopPropagation()}
			onclick={(e) => e.stopPropagation()}
		>
			<T.PointsMaterial
				size={pointSize}
				vertexColors={true}
				sizeAttenuation={true}
				transparent={true}
				opacity={0.9}
				alphaTest={0.1}
				map={pointStyle === "circle" ? undefined : undefined}
			/>
		</T.Points>
	</T.Group>
{/if}