shuishen
11 hours ago fbb068ec702338d609c1ca6eddbdb9f182d8f211
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
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, watch } from "vue";
import { BorderTopOutlined, ReloadOutlined } from "@ant-design/icons-vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
 
const props = defineProps<{ source: string }>();
 
type PropertyReader = { name: string; bytes: number; read: (view: DataView, offset: number) => number };
 
const host = ref<HTMLDivElement | null>(null);
const loading = ref(true);
const error = ref<string | null>(null);
const pointCount = ref(0);
const pointSize = ref(2.4);
 
let renderer: THREE.WebGLRenderer | null = null;
let scene: THREE.Scene | null = null;
let camera: THREE.PerspectiveCamera | null = null;
let controls: OrbitControls | null = null;
let points: THREE.Points<THREE.BufferGeometry, THREE.PointsMaterial> | null = null;
let resizeObserver: ResizeObserver | null = null;
let animationFrame = 0;
let requestId = 0;
 
const readers: Record<string, Omit<PropertyReader, "name">> = {
  char: { bytes: 1, read: (view, offset) => view.getInt8(offset) },
  int8: { bytes: 1, read: (view, offset) => view.getInt8(offset) },
  uchar: { bytes: 1, read: (view, offset) => view.getUint8(offset) },
  uint8: { bytes: 1, read: (view, offset) => view.getUint8(offset) },
  short: { bytes: 2, read: (view, offset) => view.getInt16(offset, true) },
  int16: { bytes: 2, read: (view, offset) => view.getInt16(offset, true) },
  ushort: { bytes: 2, read: (view, offset) => view.getUint16(offset, true) },
  uint16: { bytes: 2, read: (view, offset) => view.getUint16(offset, true) },
  int: { bytes: 4, read: (view, offset) => view.getInt32(offset, true) },
  int32: { bytes: 4, read: (view, offset) => view.getInt32(offset, true) },
  uint: { bytes: 4, read: (view, offset) => view.getUint32(offset, true) },
  uint32: { bytes: 4, read: (view, offset) => view.getUint32(offset, true) },
  float: { bytes: 4, read: (view, offset) => view.getFloat32(offset, true) },
  float32: { bytes: 4, read: (view, offset) => view.getFloat32(offset, true) },
  double: { bytes: 8, read: (view, offset) => view.getFloat64(offset, true) },
  float64: { bytes: 8, read: (view, offset) => view.getFloat64(offset, true) },
};
 
function headerEnd(bytes: Uint8Array): number {
  const marker = [101, 110, 100, 95, 104, 101, 97, 100, 101, 114]; // end_header
  for (let start = 0; start <= bytes.length - marker.length; start += 1) {
    if (marker.every((value, index) => bytes[start + index] === value)) {
      let end = start + marker.length;
      if (bytes[end] === 13) end += 1;
      if (bytes[end] === 10) return end + 1;
    }
  }
  throw new Error("PLY 文件缺少 end_header。");
}
 
function parsePly(buffer: ArrayBuffer): { positions: Float32Array; colors: Float32Array } {
  const bytes = new Uint8Array(buffer, 0, Math.min(buffer.byteLength, 64 * 1024));
  const end = headerEnd(bytes);
  const header = new TextDecoder("ascii").decode(new Uint8Array(buffer, 0, end));
  const lines = header.split(/\r?\n/);
  if (!lines.some((line) => line.trim() === "format binary_little_endian 1.0")) {
    throw new Error("当前仅支持 binary_little_endian PLY。");
  }
  const vertexLine = lines.find((line) => line.startsWith("element vertex "));
  const count = Number(vertexLine?.split(/\s+/)[2]);
  if (!Number.isSafeInteger(count) || count < 1) throw new Error("PLY 顶点数量无效。");
  const properties: PropertyReader[] = [];
  let inVertex = false;
  for (const line of lines) {
    if (line.startsWith("element ")) {
      inVertex = line.startsWith("element vertex ");
      continue;
    }
    if (!inVertex || !line.startsWith("property ")) continue;
    const [, type, name] = line.trim().split(/\s+/);
    const reader = readers[type];
    if (!reader || !name) throw new Error(`不支持的顶点属性类型:${type ?? "未知"}。`);
    properties.push({ name, ...reader });
  }
  const stride = properties.reduce((total, property) => total + property.bytes, 0);
  if (end + stride * count > buffer.byteLength) throw new Error("PLY 顶点数据不完整。");
  const offsets = Object.fromEntries(properties.reduce<[string, number][]>((items, property) => {
    const offset = items.length ? items[items.length - 1][1] + properties[items.length - 1].bytes : 0;
    items.push([property.name, offset]);
    return items;
  }, []));
  const required = ["x", "y", "z"];
  if (required.some((name) => offsets[name] === undefined)) throw new Error("PLY 缺少 x/y/z 顶点坐标。");
  const propertyByName = Object.fromEntries(properties.map((property) => [property.name, property]));
  const view = new DataView(buffer, end);
  const positions = new Float32Array(count * 3);
  const colors = new Float32Array(count * 3);
  const hasColor = ["red", "green", "blue"].every((name) => offsets[name] !== undefined);
  for (let index = 0; index < count; index += 1) {
    const base = index * stride;
    for (const [axis, offset] of [["x", 0], ["y", 1], ["z", 2]] as const) {
      positions[index * 3 + offset] = propertyByName[axis].read(view, base + offsets[axis]);
    }
    for (const [channel, offset] of [["red", 0], ["green", 1], ["blue", 2]] as const) {
      colors[index * 3 + offset] = hasColor ? propertyByName[channel].read(view, base + offsets[channel]) / 255 : 0.72;
    }
  }
  return { positions, colors };
}
 
function resize() {
  if (!host.value || !renderer || !camera) return;
  const width = Math.max(host.value.clientWidth, 1);
  const height = Math.max(host.value.clientHeight, 1);
  renderer.setSize(width, height, false);
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
}
 
function frame() {
  if (renderer && scene && camera && controls) {
    controls.update();
    renderer.render(scene, camera);
  }
  animationFrame = requestAnimationFrame(frame);
}
 
function resetView() {
  if (!camera || !controls || !points) return;
  const sphere = new THREE.Sphere();
  points.geometry.computeBoundingSphere();
  if (!points.geometry.boundingSphere) return;
  sphere.copy(points.geometry.boundingSphere);
  const radius = Math.max(sphere.radius, 0.01);
  controls.target.copy(sphere.center);
  camera.position.copy(sphere.center).add(new THREE.Vector3(radius * 1.25, radius * 0.85, radius * 1.65));
  camera.near = radius / 100;
  camera.far = radius * 100;
  camera.updateProjectionMatrix();
  controls.update();
}
 
function topDownView() {
  if (!camera || !controls || !points) return;
  points.geometry.computeBoundingSphere();
  if (!points.geometry.boundingSphere) return;
  const sphere = points.geometry.boundingSphere;
  const radius = Math.max(sphere.radius, 0.01);
  const distance = Math.max(camera.position.distanceTo(controls.target), radius * 1.5);
  controls.target.copy(sphere.center);
  camera.up.set(0, 1, 0);
  camera.position.copy(sphere.center).add(new THREE.Vector3(0, 0, distance));
  camera.near = radius / 100;
  camera.far = radius * 100;
  camera.updateProjectionMatrix();
  controls.update();
}
 
function applyPointSize() {
  if (points) points.material.size = pointSize.value;
}
 
async function loadSource(source: string) {
  const activeId = ++requestId;
  loading.value = true;
  error.value = null;
  try {
    const response = await fetch(source, { cache: "no-store" });
    if (!response.ok) throw new Error(`点云读取失败 (${response.status})。`);
    const parsed = parsePly(await response.arrayBuffer());
    if (activeId !== requestId || !scene) return;
    points?.geometry.dispose();
    points?.material.dispose();
    const geometry = new THREE.BufferGeometry();
    geometry.setAttribute("position", new THREE.BufferAttribute(parsed.positions, 3));
    geometry.setAttribute("color", new THREE.BufferAttribute(parsed.colors, 3));
    const material = new THREE.PointsMaterial({ size: pointSize.value, vertexColors: true, sizeAttenuation: false });
    points = new THREE.Points(geometry, material);
    scene.add(points);
    pointCount.value = parsed.positions.length / 3;
    resetView();
  } catch (caught) {
    if (activeId === requestId) error.value = caught instanceof Error ? caught.message : "点云无法读取。";
  } finally {
    if (activeId === requestId) loading.value = false;
  }
}
 
onMounted(() => {
  if (!host.value) return;
  scene = new THREE.Scene();
  scene.background = new THREE.Color("#101821");
  camera = new THREE.PerspectiveCamera(42, 1, 0.01, 1_000);
  renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
  renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
  host.value.appendChild(renderer.domElement);
  controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.08;
  controls.screenSpacePanning = true;
  resizeObserver = new ResizeObserver(resize);
  resizeObserver.observe(host.value);
  resize();
  frame();
  void loadSource(props.source);
});
 
watch(() => props.source, (source) => { void loadSource(source); });
watch(pointSize, applyPointSize);
 
onBeforeUnmount(() => {
  cancelAnimationFrame(animationFrame);
  resizeObserver?.disconnect();
  controls?.dispose();
  points?.geometry.dispose();
  points?.material.dispose();
  renderer?.dispose();
  renderer?.domElement.remove();
});
</script>
 
<template>
  <div class="sparse-point-viewer">
    <div ref="host" class="canvas-host" aria-label="稀疏点云交互视图" />
    <div class="viewer-toolbar">
      <span>{{ pointCount.toLocaleString() }} 点</span>
      <label>点大小 <a-slider v-model:value="pointSize" :min="1" :max="8" :step="0.2" /></label>
      <a-tooltip title="俯视模型(沿本地 Z 轴)"><a-button type="text" aria-label="俯视模型" @click="topDownView"><BorderTopOutlined /></a-button></a-tooltip>
      <a-tooltip title="复位视角"><a-button type="text" aria-label="复位视角" @click="resetView"><ReloadOutlined /></a-button></a-tooltip>
    </div>
    <div v-if="loading || error" class="viewer-state"><a-spin v-if="loading" /><span v-else>{{ error }}</span></div>
  </div>
</template>
 
<style scoped>
.sparse-point-viewer { position: relative; height: 560px; overflow: hidden; background: #101821; border: 1px solid #273543; }
.canvas-host { width: 100%; height: 100%; }
.canvas-host :deep(canvas) { display: block; width: 100%; height: 100%; }
.viewer-toolbar { position: absolute; right: 12px; bottom: 12px; display: flex; align-items: center; gap: 12px; padding: 8px 10px; color: #e8f1f5; background: rgba(12, 20, 29, 0.84); font-size: 13px; }
.viewer-toolbar label { display: flex; align-items: center; gap: 8px; white-space: nowrap; }
.viewer-toolbar :deep(.ant-slider) { width: 100px; margin: 0; }
.viewer-toolbar :deep(.ant-btn) { color: #e8f1f5; }
.viewer-state { position: absolute; inset: 0; display: grid; place-items: center; color: #e8f1f5; background: rgba(12, 20, 29, 0.65); }
@media (max-width: 767px) { .sparse-point-viewer { height: 420px; } .viewer-toolbar { left: 8px; right: 8px; bottom: 8px; gap: 8px; } .viewer-toolbar :deep(.ant-slider) { width: min(92px, 24vw); } }
</style>