Remove OpenSCAD from the web port
Web FreeCAD does not implement OpenSCAD. Drop the module end to end instead of keeping a blocked or placeholder shell: - delete the parity-matrix row and regenerate the module registry (31 modules, OpenSCAD absent) - remove the OpenSCAD-only frontend modules (worker, facades, slice, mesh backend, desktop/preferences tasks) and strip the OpenSCAD branches from the dispatchers, shells, storage and router - neutralise the two shared owners that outlived the module: openscad-desktop-view -> scene-viewport (SceneViewport) and openscad-desktop-adapter -> scene-document (SceneDocument), so Part, Mesh and the other consumers keep working - drop the FreeCADWebOpenSCADRuntimeProbe target and FREECAD_WEB_ENABLE_OPENSCAD option from the kernel CMake; BUILD_OPENSCAD stays in the forced-off list - delete web/openscad.html, its Vite input, the kernel artifacts and the 17 OpenSCAD tool entry points AGENTS.md records the removal rule. tsc --noEmit is clean and grep -ri openscad web/src is empty. Also carry the Boost pthread guard: under Emscripten a plain -lpthread implies -sUSE_PTHREADS=1 and therewith --shared-memory, which the non-atomics VTK archives cannot link against. Validation NOT_RUN / PARTIAL_FAILED, Acceptance NOT_CLAIMED. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
595
web/src/scene-viewport.tsx
Normal file
595
web/src/scene-viewport.tsx
Normal file
@@ -0,0 +1,595 @@
|
||||
import type { InspectionDisplayAttributes } from "./inspection-result-display.js";
|
||||
import { distanceAnnotation } from "./measure-annotation.js";
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import * as THREE from "three";
|
||||
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
|
||||
import type { SceneDocument } from "./scene-document.js";
|
||||
import { attachSceneCommands } from "./scene-command-host.js";
|
||||
import { SelectionDecoration } from "./selection-decoration.js";
|
||||
import type { PointsViewState } from "./points-document-facade.js";
|
||||
|
||||
export type ViewPolygon = { polygon: { x: number; y: number }[]; viewProjection: number[] };
|
||||
|
||||
export interface FacetInteraction {
|
||||
mode: "triangle" | "region" | "box" | "navigate";
|
||||
visibleOnly: boolean; frontOnly: boolean;
|
||||
components: Record<string, number[][]>; componentOnClick: boolean;
|
||||
selected: Record<string, number[]>;
|
||||
request?: { id: number; mode: "all" | "small"; maximum: number };
|
||||
onFacets: (facets: Record<string, number[]>, toggle?: boolean) => void;
|
||||
}
|
||||
|
||||
export type InspectionHit = { object: string; index?: number; facet?: number; point: [number, number, number] };
|
||||
|
||||
export function SceneViewport({ viewportHeight = 420, onReady, facetInteraction, polygonMode = false, onPolygon, onCancelPolygon, inspectionMode, onInspect, inspectionAnnotations = [], document, selected, onSelect, onPickMesh, meshInfoMode = false, onHoverMesh, onPickPoint, onPickVertex, onPickLocation, onCancelPick, onViewDirection, ariaLabel = "Geometry viewport", reserveControlsSpace = false, preserveCamera = false, onPickEdge }: {
|
||||
document: SceneDocument & { objects: Array<SceneDocument["objects"][number] & { lineSubelements?: string[]; directionEdges?: string[]; alphas?: number[]; vertices?: number[][]; curvature?: number[]; pointAttributes?: { Color?: number[][]; Normal?: number[][]; Intensity?: number[] }; pointDisplayMode?: string }> }; selected: string[]; onSelect: (name: string) => void; ariaLabel?: string; reserveControlsSpace?: boolean; preserveCamera?: boolean;
|
||||
meshInfoMode?: boolean;
|
||||
onHoverMesh?: (facet: number | null) => void;
|
||||
onPickEdge?: (object: string, subelement: string) => void;
|
||||
onReady?: () => void;
|
||||
viewportHeight?: number;
|
||||
facetInteraction?: FacetInteraction;
|
||||
polygonMode?: boolean;
|
||||
onPolygon?: (capture: ViewPolygon) => void;
|
||||
onCancelPolygon?: () => void;
|
||||
inspectionMode?: "inspect" | "navigate";
|
||||
onInspect?: (hit: InspectionHit) => void;
|
||||
inspectionAnnotations?: Array<{ text: string; point: [number, number, number] }>;
|
||||
onPickMesh?: (pick: { object: string; facet: number; point: [number, number, number]; direction: [number, number, number] }) => void;
|
||||
onPickPoint?: (point: [number, number, number]) => void;
|
||||
onPickVertex?: (point: [number, number, number]) => void;
|
||||
onPickLocation?: (point: [number, number, number], normal?: [number, number, number]) => void;
|
||||
onCancelPick?: () => void;
|
||||
onViewDirection?: (direction: [number, number, number]) => void;
|
||||
}) {
|
||||
const meshInfo = useRef({ active: meshInfoMode, hover: onHoverMesh });
|
||||
meshInfo.current = { active: meshInfoMode, hover: onHoverMesh };
|
||||
const pickEdge = useRef(onPickEdge); pickEdge.current = onPickEdge;
|
||||
const ready = useRef(onReady); ready.current = onReady;
|
||||
const facets = useRef(facetInteraction);
|
||||
facets.current = facetInteraction;
|
||||
const handledFacetRequest = useRef<number>();
|
||||
const polygonCallbacks = useRef({ onPolygon, onCancelPolygon });
|
||||
polygonCallbacks.current = { onPolygon, onCancelPolygon };
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const inspection = useRef({ mode: inspectionMode, pick: onInspect, annotations: inspectionAnnotations });
|
||||
inspection.current = { mode: inspectionMode, pick: onInspect, annotations: inspectionAnnotations };
|
||||
const savedCamera = useRef<{ documentId: string; position: THREE.Vector3; target: THREE.Vector3 }>();
|
||||
const select = useRef(onSelect);
|
||||
select.current = onSelect;
|
||||
const pickMesh = useRef(onPickMesh);
|
||||
pickMesh.current = onPickMesh;
|
||||
const pickPoint = useRef(onPickPoint);
|
||||
pickPoint.current = onPickPoint;
|
||||
const pickVertex = useRef(onPickVertex);
|
||||
pickVertex.current = onPickVertex;
|
||||
const pickLocation = useRef(onPickLocation);
|
||||
pickLocation.current = onPickLocation;
|
||||
const cancelPick = useRef(onCancelPick);
|
||||
cancelPick.current = onCancelPick;
|
||||
const viewDirection = useRef(onViewDirection);
|
||||
viewDirection.current = onViewDirection;
|
||||
useEffect(() => {
|
||||
if (!host.current) return;
|
||||
const container = host.current;
|
||||
const renderer = new THREE.WebGLRenderer({ antialias: true });
|
||||
renderer.setPixelRatio(window.devicePixelRatio);
|
||||
container.appendChild(renderer.domElement);
|
||||
const scene = new THREE.Scene();
|
||||
scene.background = new THREE.Color(0xf1f3f5);
|
||||
const camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1000000);
|
||||
camera.up.set(0, 0, 1);
|
||||
let controls: OrbitControls = new OrbitControls(camera, renderer.domElement);
|
||||
const content = new THREE.Group();
|
||||
scene.add(content, new THREE.HemisphereLight(0xffffff, 0x555555, 3));
|
||||
// Shared selection decoration: the local frame is anchored at the selected
|
||||
// object's bounding-box centre rather than at a scene origin.
|
||||
const decoration = new SelectionDecoration(scene);
|
||||
const publishDecoration = (value: SelectionDecoration) => {
|
||||
(window as unknown as { __freecadSceneDecorationState?: unknown }).__freecadSceneDecorationState = value.snapshot();
|
||||
};
|
||||
const sceneCommands = attachSceneCommands(scene, controls, container, () => document.documentId, () => {}, {
|
||||
canvas: renderer.domElement,
|
||||
objects: () => content.children.filter(object => !object.userData.pointsDecoration && object.userData.selectable !== false).map(object => ({
|
||||
id: String(object.userData.name),
|
||||
label: document.objects.find(entry => entry.name === object.userData.name)?.label || String(object.userData.name),
|
||||
object,
|
||||
})),
|
||||
select: id => { if (!meshInfo.current.active && !inspection.current.mode && (!facets.current || facets.current.mode === "navigate")) select.current(id); },
|
||||
}, next => { controls = next; });
|
||||
const geometries: THREE.BufferGeometry[] = [];
|
||||
const materials: THREE.Material[] = [];
|
||||
for (const object of document.objects) {
|
||||
if (object.visible === false) continue;
|
||||
const pointView = object as typeof object & Partial<PointsViewState>;
|
||||
const shapeSelection = selected.includes(object.name) && pointView.selectionStyle !== "Box";
|
||||
const color = shapeSelection ? new THREE.Color(0x16846b)
|
||||
: object.color ? new THREE.Color(object.color[0], object.color[1], object.color[2]) : new THREE.Color(0xa3abb6);
|
||||
if (object.points?.length && object.facets?.length) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute("position", new THREE.Float32BufferAttribute(object.points.flat(), 3));
|
||||
geometry.setIndex(object.facets.flat());
|
||||
geometry.computeVertexNormals();
|
||||
const vertexColors = object.colors?.length === object.points.length * 3;
|
||||
const vertexAlphas = vertexColors && object.alphas?.length === object.points.length;
|
||||
if (vertexColors) {
|
||||
const stride = vertexAlphas ? 4 : 3;
|
||||
const values = new Float32Array(object.points.length * stride);
|
||||
const value = new THREE.Color();
|
||||
for (let index = 0; index < object.points.length; ++index) {
|
||||
value.setRGB(object.colors![index * 3], object.colors![index * 3 + 1], object.colors![index * 3 + 2], THREE.SRGBColorSpace).toArray(values, index * stride);
|
||||
if (vertexAlphas) values[index * stride + 3] = object.alphas![index];
|
||||
}
|
||||
geometry.setAttribute("color", new THREE.BufferAttribute(values, stride));
|
||||
}
|
||||
const opacity = object.opacity ?? 1;
|
||||
const transparent = opacity < 1 || Boolean(vertexAlphas && object.alphas!.some(alpha => alpha < 1));
|
||||
const material = new THREE.MeshStandardMaterial({ color: vertexColors ? 0xffffff : color, vertexColors,
|
||||
opacity, transparent, depthWrite: !transparent,
|
||||
emissive: vertexColors && selected.includes(object.name) ? 0x16846b : 0, emissiveIntensity: 0.1, side: THREE.DoubleSide });
|
||||
const mesh = new THREE.Mesh(geometry, material);
|
||||
mesh.userData.name = object.name;
|
||||
content.add(mesh); geometries.push(geometry); materials.push(material);
|
||||
}
|
||||
if (object.pointMarkers?.length) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute("position", new THREE.Float32BufferAttribute(object.pointMarkers.flat(), 3));
|
||||
const requestedPointSize = (object as typeof object & InspectionDisplayAttributes).pointSize;
|
||||
const pointSize = typeof requestedPointSize === "number" && Number.isFinite(requestedPointSize)
|
||||
&& requestedPointSize > 0 ? requestedPointSize : 7;
|
||||
const attributes = object.pointAttributes;
|
||||
const mode = object.pointDisplayMode;
|
||||
const count = object.pointMarkers.length;
|
||||
const opacity = object.opacity ?? 1;
|
||||
let material: THREE.Material;
|
||||
if (mode === "Shaded" && attributes?.Normal?.length === count) {
|
||||
geometry.setAttribute("pointNormal", new THREE.Float32BufferAttribute(attributes.Normal.flat(), 3));
|
||||
material = new THREE.ShaderMaterial({
|
||||
transparent: opacity < 1, depthWrite: opacity >= 1,
|
||||
uniforms: { baseColor: { value: color }, opacity: { value: opacity }, pixelRatio: { value: renderer.getPixelRatio() }, pointSize: { value: pointSize } },
|
||||
vertexShader: `attribute vec3 pointNormal; varying float shade; uniform float pixelRatio; uniform float pointSize;
|
||||
void main() { vec3 n = normalMatrix * pointNormal;
|
||||
shade = 0.25 + 0.75 * abs(dot(normalize(n), normalize(vec3(0.3, 0.5, 1.0))));
|
||||
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); gl_PointSize = pointSize * pixelRatio; }`,
|
||||
fragmentShader: `uniform vec3 baseColor; uniform float opacity; varying float shade;
|
||||
void main() { gl_FragColor = vec4(baseColor * shade, opacity);
|
||||
#include <tonemapping_fragment>
|
||||
#include <colorspace_fragment>
|
||||
}`,
|
||||
});
|
||||
} else {
|
||||
const colors = mode === "Color" && attributes?.Color?.length === count ? attributes.Color : undefined;
|
||||
const intensities = mode === "Intensity" && attributes?.Intensity?.length === count ? attributes.Intensity
|
||||
: mode === "Intensity" && object.curvature?.length === count ? object.curvature : undefined;
|
||||
const alphas = colors && object.alphas?.length === count ? object.alphas : undefined;
|
||||
const stride = alphas ? 4 : 3;
|
||||
if (colors || intensities) {
|
||||
const values = new Float32Array(count * stride);
|
||||
for (let i = 0; i < count; ++i) {
|
||||
const rgb = colors?.[i];
|
||||
const grey = Math.max(0, Math.min(1, intensities?.[i] ?? 0));
|
||||
new THREE.Color().setRGB(rgb?.[0] ?? grey, rgb?.[1] ?? grey, rgb?.[2] ?? grey, THREE.SRGBColorSpace).toArray(values, i * stride);
|
||||
if (alphas) values[i * stride + 3] = alphas[i];
|
||||
}
|
||||
geometry.setAttribute("color", new THREE.BufferAttribute(values, stride));
|
||||
}
|
||||
material = new THREE.PointsMaterial({ color: shapeSelection ? color : colors || intensities ? 0xffffff : color,
|
||||
vertexColors: Boolean(colors || intensities), opacity, transparent: Boolean(alphas) || opacity < 1,
|
||||
depthWrite: !alphas && opacity >= 1, size: pointSize, sizeAttenuation: false });
|
||||
}
|
||||
const points = new THREE.Points(geometry, material);
|
||||
points.userData.name = object.name;
|
||||
points.userData.selectable = pointView.selectable;
|
||||
if (pointView.selectable === false) points.raycast = () => {};
|
||||
content.add(points); geometries.push(geometry); materials.push(material);
|
||||
if (pointView.boundingBox || (pointView.selectionStyle === "Box" && selected.includes(object.name))) {
|
||||
geometry.computeBoundingBox();
|
||||
if (geometry.boundingBox && !geometry.boundingBox.isEmpty()) {
|
||||
const box = new THREE.Box3Helper(geometry.boundingBox, selected.includes(object.name) ? 0x16846b : 0x42484f);
|
||||
box.userData.pointsDecoration = true;
|
||||
box.raycast = () => {};
|
||||
content.add(box); geometries.push(box.geometry); materials.push(box.material as THREE.Material);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (object.measurement) content.add(distanceAnnotation(object.measurement));
|
||||
const segments: number[] = [];
|
||||
const inspectionLines = object as typeof object & {
|
||||
inspectionLineIndices?: number[][];
|
||||
inspectionSampleColors?: number[][];
|
||||
inspectionSampleAlphas?: number[];
|
||||
};
|
||||
const segmentColors: number[] = [];
|
||||
const segmentEdges: Array<string | undefined> = [];
|
||||
for (const [index, line] of (object.lines ?? []).entries()) {
|
||||
const sub = object.lineSubelements?.[index];
|
||||
for (let i = 1; i < line.length; i++) {
|
||||
segments.push(...line[i - 1], ...line[i]);
|
||||
if (inspectionLines.inspectionLineIndices && inspectionLines.inspectionSampleColors) {
|
||||
for (const vertex of [i - 1, i]) {
|
||||
const sample = inspectionLines.inspectionLineIndices[index][vertex];
|
||||
const rgb = inspectionLines.inspectionSampleColors[sample];
|
||||
const color = new THREE.Color().setRGB(rgb[0], rgb[1], rgb[2], THREE.SRGBColorSpace);
|
||||
segmentColors.push(color.r, color.g, color.b, inspectionLines.inspectionSampleAlphas?.[sample] ?? 1);
|
||||
}
|
||||
}
|
||||
segmentEdges.push(sub && object.directionEdges?.includes(sub) ? sub : undefined);
|
||||
}
|
||||
}
|
||||
if (segments.length) {
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute("position", new THREE.Float32BufferAttribute(segments, 3));
|
||||
if (segmentColors.length) geometry.setAttribute("color", new THREE.Float32BufferAttribute(segmentColors, 4));
|
||||
const material = new THREE.LineBasicMaterial({ vertexColors: segmentColors.length > 0,
|
||||
transparent: segmentColors.length > 0, color: segmentColors.length ? 0xffffff : object.typeId === "Part::Section" && object.color
|
||||
? color : selected.includes(object.name) ? 0x16846b : 0x42484f });
|
||||
const lines = new THREE.LineSegments(geometry, material);
|
||||
lines.userData.name = object.name;
|
||||
lines.userData.segmentEdges = segmentEdges;
|
||||
lines.userData.inspectionLineIndices = inspectionLines.inspectionLineIndices;
|
||||
content.add(lines); geometries.push(geometry); materials.push(material);
|
||||
}
|
||||
}
|
||||
const highlight = new THREE.Group(); scene.add(highlight);
|
||||
let previousFacetSelection: Record<string, number[]> | undefined;
|
||||
const updateFacetHighlights = () => {
|
||||
if (previousFacetSelection === facets.current?.selected) return;
|
||||
previousFacetSelection = facets.current?.selected;
|
||||
for (const child of [...highlight.children]) {
|
||||
const mesh = child as THREE.Mesh; mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose(); highlight.remove(child);
|
||||
}
|
||||
for (const object of document.objects) {
|
||||
if (object.visible === false) continue;
|
||||
const indices = facets.current?.selected[object.name];
|
||||
if (!indices?.length || !object.points || !object.facets) continue;
|
||||
const positions = indices.flatMap(index => (object.facets![index] ?? []).flatMap(vertex => object.points![vertex]));
|
||||
const geometry = new THREE.BufferGeometry(); geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
|
||||
const material = new THREE.MeshBasicMaterial({ color: 0xff8c18, side: THREE.DoubleSide, transparent: true,
|
||||
opacity: 0.72, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1 });
|
||||
highlight.add(new THREE.Mesh(geometry, material));
|
||||
}
|
||||
};
|
||||
const bounds = new THREE.Box3().setFromObject(content);
|
||||
const center = bounds.isEmpty() ? new THREE.Vector3() : bounds.getCenter(new THREE.Vector3());
|
||||
const radius = bounds.isEmpty() ? 10 : Math.max(bounds.getSize(new THREE.Vector3()).length(), 0.01);
|
||||
controls.target.copy(center);
|
||||
camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7));
|
||||
if (preserveCamera && savedCamera.current?.documentId === document.documentId) {
|
||||
camera.position.copy(savedCamera.current.position); controls.target.copy(savedCamera.current.target);
|
||||
}
|
||||
camera.near = radius / 10000; camera.far = radius * 100;
|
||||
const toolbar = container.querySelector<HTMLElement>(".scene-display-tools");
|
||||
if (reserveControlsSpace) {
|
||||
renderer.domElement.style.position = "absolute"; renderer.domElement.style.bottom = "0";
|
||||
}
|
||||
const resize = () => {
|
||||
const reserved = reserveControlsSpace && toolbar ? toolbar.offsetTop + toolbar.offsetHeight + 8 : 0;
|
||||
const width = Math.max(container.clientWidth, 1), height = Math.max(container.clientHeight - reserved, 1);
|
||||
renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix();
|
||||
};
|
||||
const observer = new ResizeObserver(resize); observer.observe(container); if (toolbar && reserveControlsSpace) observer.observe(toolbar); resize();
|
||||
const facetMeshes = () => content.children.filter((object): object is THREE.Mesh => object instanceof THREE.Mesh);
|
||||
const eligibleFacet = (mesh: THREE.Mesh, index: number) => {
|
||||
const position = mesh.geometry.getAttribute("position"), indices = mesh.geometry.index!;
|
||||
const a = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3)).applyMatrix4(mesh.matrixWorld);
|
||||
const b = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3 + 1)).applyMatrix4(mesh.matrixWorld);
|
||||
const c = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3 + 2)).applyMatrix4(mesh.matrixWorld);
|
||||
const center = a.clone().add(b).add(c).multiplyScalar(1 / 3);
|
||||
if (facets.current?.frontOnly && b.clone().sub(a).cross(c.clone().sub(a)).dot(camera.position.clone().sub(center)) <= 0) return false;
|
||||
if (facets.current?.visibleOnly) {
|
||||
const samples = [center, a.clone().lerp(center, 0.001), b.clone().lerp(center, 0.001), c.clone().lerp(center, 0.001)];
|
||||
if (!samples.some(point => {
|
||||
const projected = point.project(camera);
|
||||
if (projected.z < -1 || projected.z > 1 || Math.abs(projected.x) > 1 || Math.abs(projected.y) > 1) return false;
|
||||
const ray = new THREE.Raycaster(); ray.setFromCamera(new THREE.Vector2(projected.x, projected.y), camera);
|
||||
const hit = ray.intersectObjects(facetMeshes())[0];
|
||||
return hit?.object === mesh && hit.faceIndex === index;
|
||||
})) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
const collectFacets = (polygon?: { x: number; y: number }[]) => {
|
||||
camera.updateMatrixWorld(true); content.updateMatrixWorld(true);
|
||||
const inside = (point: THREE.Vector3) => {
|
||||
if (!polygon) return true;
|
||||
const p = point.project(camera); if (p.z < -1 || p.z > 1) return false;
|
||||
const x = (p.x + 1) / 2, y = (p.y + 1) / 2;
|
||||
let hit = false;
|
||||
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
|
||||
const a = polygon[i], b = polygon[j];
|
||||
if ((a.y > y) !== (b.y > y) && x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x) hit = !hit;
|
||||
}
|
||||
return hit;
|
||||
};
|
||||
const result: Record<string, number[]> = {};
|
||||
for (const mesh of facetMeshes()) {
|
||||
const indices = mesh.geometry.index!, points = mesh.geometry.getAttribute("position");
|
||||
const selected: number[] = [];
|
||||
for (let index = 0; index < indices.count / 3; ++index) {
|
||||
if (!eligibleFacet(mesh, index)) continue;
|
||||
const corners = [0, 1, 2].map(offset => new THREE.Vector3().fromBufferAttribute(points, indices.getX(index * 3 + offset)).applyMatrix4(mesh.matrixWorld));
|
||||
if (corners.some(point => inside(point.clone())) || inside(corners[0].clone().add(corners[1]).add(corners[2]).multiplyScalar(1 / 3))) selected.push(index);
|
||||
}
|
||||
result[String(mesh.userData.name)] = selected;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const polygonLayer = window.document.createElement("div");
|
||||
if (polygonMode || (facetInteraction?.mode === "region" || facetInteraction?.mode === "box")) {
|
||||
controls.enabled = false;
|
||||
polygonLayer.style.cssText = "position:absolute;inset:0;z-index:10;cursor:crosshair;touch-action:none";
|
||||
const svg = window.document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("viewBox", "0 0 1 1"); svg.setAttribute("preserveAspectRatio", "none");
|
||||
svg.style.cssText = "position:absolute;width:100%;height:100%;pointer-events:none";
|
||||
const outline = window.document.createElementNS(svg.namespaceURI, "polygon");
|
||||
outline.setAttribute("fill", "#16846b33"); outline.setAttribute("stroke", "#16846b"); outline.setAttribute("stroke-width", "0.004");
|
||||
svg.appendChild(outline); polygonLayer.appendChild(svg);
|
||||
const vertices: { x: number; y: number }[] = [];
|
||||
const buttons = window.document.createElement("div"); buttons.style.cssText = "position:absolute;top:8px;left:8px";
|
||||
const complete = window.document.createElement("button"); complete.textContent = facetInteraction ? "Select region" : "Complete cut"; complete.disabled = true;
|
||||
const cancel = window.document.createElement("button"); cancel.textContent = "Cancel polygon";
|
||||
buttons.append(complete, cancel); polygonLayer.appendChild(buttons);
|
||||
let drawing = false;
|
||||
const add = (event: PointerEvent) => {
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
const x = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
|
||||
const y = Math.max(0, Math.min(1, 1 - (event.clientY - rect.top) / rect.height));
|
||||
if (facets.current?.mode === "box" && vertices.length) {
|
||||
const first = vertices[0];
|
||||
vertices.splice(1, vertices.length - 1, { x, y: first.y }, { x, y }, { x: first.x, y });
|
||||
outline.setAttribute("points", vertices.map(p => `${p.x},${1-p.y}`).join(" "));
|
||||
complete.disabled = x === first.x || y === first.y;
|
||||
return;
|
||||
}
|
||||
const last = vertices[vertices.length - 1];
|
||||
if (last && Math.hypot(x - last.x, y - last.y) < 0.003) return;
|
||||
vertices.push({ x, y });
|
||||
outline.setAttribute("points", vertices.map(p => `${p.x},${1-p.y}`).join(" "));
|
||||
const noncollinear = vertices.length >= 3 && vertices.slice(2).some(p => Math.abs((vertices[1].x-vertices[0].x)*(p.y-vertices[0].y) - (vertices[1].y-vertices[0].y)*(p.x-vertices[0].x)) > 1e-10);
|
||||
complete.disabled = !noncollinear;
|
||||
};
|
||||
polygonLayer.onpointerdown = event => {
|
||||
if (buttons.contains(event.target as Node) || event.button !== 0) return;
|
||||
if (facets.current?.mode === "box") vertices.length = 0;
|
||||
drawing = true; polygonLayer.setPointerCapture(event.pointerId); add(event);
|
||||
};
|
||||
polygonLayer.onpointermove = event => { if (drawing) add(event); };
|
||||
polygonLayer.onpointerup = () => { drawing = false; if (facets.current?.mode === "box" && !complete.disabled) facets.current.onFacets(collectFacets(vertices)); };
|
||||
polygonLayer.onpointercancel = () => { drawing = false; };
|
||||
complete.onclick = () => {
|
||||
if (complete.disabled) return;
|
||||
camera.updateMatrixWorld(true);
|
||||
if (facets.current) { facets.current.onFacets(collectFacets(vertices)); return; }
|
||||
polygonCallbacks.current.onPolygon?.({ polygon: vertices, viewProjection: new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).toArray() });
|
||||
};
|
||||
cancel.onclick = () => polygonCallbacks.current.onCancelPolygon?.();
|
||||
polygonLayer.tabIndex = 0;
|
||||
polygonLayer.onkeydown = event => { if (event.key === "Escape") polygonCallbacks.current.onCancelPolygon?.(); };
|
||||
container.appendChild(polygonLayer); polygonLayer.focus();
|
||||
}
|
||||
let downX = 0, downY = 0;
|
||||
const down = (event: PointerEvent) => { downX = event.clientX; downY = event.clientY; };
|
||||
const hover = (event: PointerEvent) => {
|
||||
if (!meshInfo.current.active || event.buttons) return;
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
camera.updateMatrixWorld(true); content.updateMatrixWorld(true);
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.Mesh))[0];
|
||||
meshInfo.current.hover?.(hit?.faceIndex ?? null);
|
||||
};
|
||||
const leave = () => meshInfo.current.hover?.(null);
|
||||
const pick = (event: PointerEvent) => {
|
||||
if (event.button === 2 && !meshInfo.current.active && (pickLocation.current || pickMesh.current)) { cancelPick.current?.(); return; }
|
||||
if (event.button !== 0 || Math.hypot(event.clientX - downX, event.clientY - downY) > 4) return;
|
||||
const rect = renderer.domElement.getBoundingClientRect();
|
||||
if (facets.current && facets.current.mode !== "navigate") {
|
||||
if (facets.current.mode !== "triangle") return;
|
||||
camera.updateMatrixWorld(true); content.updateMatrixWorld(true);
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
const hits = ray.intersectObjects(facetMeshes());
|
||||
const candidates = facets.current.visibleOnly ? hits.slice(0, 1) : hits;
|
||||
const hit = candidates.find(item => item.faceIndex != null && eligibleFacet(item.object as THREE.Mesh, item.faceIndex));
|
||||
if (hit?.faceIndex != null) {
|
||||
const name = String(hit.object.userData.name);
|
||||
const indices = facets.current.componentOnClick
|
||||
? facets.current.components[name]?.find(group => group.includes(hit.faceIndex!)) ?? [hit.faceIndex] : [hit.faceIndex];
|
||||
facets.current.onFacets({ [name]: indices.filter(index => eligibleFacet(hit.object as THREE.Mesh, index)) }, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (inspection.current.mode) {
|
||||
if (inspection.current.mode === "navigate") return;
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.params.Points.threshold = radius / 100;
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
const hit = ray.intersectObjects(content.children.filter(object =>
|
||||
document.objects.some(item => item.name === object.userData.name && item.typeId === "Inspection::Feature")))[0];
|
||||
if (hit?.object instanceof THREE.Points && hit.index !== undefined) {
|
||||
const point = hit.object.localToWorld(new THREE.Vector3().fromBufferAttribute(hit.object.geometry.getAttribute("position"), hit.index));
|
||||
inspection.current.pick?.({ object: hit.object.userData.name, index: hit.index, point: [point.x,point.y,point.z] });
|
||||
} else if (hit?.faceIndex != null) {
|
||||
inspection.current.pick?.({ object: hit.object.userData.name, facet: hit.faceIndex, point: [hit.point.x,hit.point.y,hit.point.z] });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (pickMesh.current) {
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.Mesh))[0];
|
||||
if (hit && hit.faceIndex != null) {
|
||||
const direction = camera.getWorldDirection(new THREE.Vector3());
|
||||
pickMesh.current({ object: hit.object.userData.name, facet: hit.faceIndex,
|
||||
point: [hit.point.x, hit.point.y, hit.point.z], direction: [direction.x, direction.y, direction.z] });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (pickVertex.current || pickLocation.current) {
|
||||
// Snap to native topology in screen space, independent of tessellation density.
|
||||
let nearest: { point: THREE.Vector3; pixels: number; depth: number; normal?: THREE.Vector3 } | undefined;
|
||||
const occlusion = new THREE.Raycaster();
|
||||
const meshes = content.children.filter(object => object instanceof THREE.Mesh);
|
||||
for (const object of document.objects) {
|
||||
if (object.visible === false) continue;
|
||||
for (const position of object.vertices ?? object.pointMarkers ?? []) {
|
||||
const point = new THREE.Vector3(...position);
|
||||
const projected = point.clone().project(camera);
|
||||
if (projected.z < -1 || projected.z > 1) continue;
|
||||
const pixels = Math.hypot((projected.x + 1) * rect.width / 2 + rect.left - event.clientX,
|
||||
(1 - projected.y) * rect.height / 2 + rect.top - event.clientY);
|
||||
if (pixels > 10) continue;
|
||||
occlusion.setFromCamera(new THREE.Vector2(projected.x, projected.y), camera);
|
||||
const obstruction = occlusion.intersectObjects(meshes)[0];
|
||||
const depth = point.distanceTo(occlusion.ray.origin);
|
||||
if (obstruction && obstruction.distance < depth - radius * 1e-6) continue;
|
||||
if (!nearest || pixels < nearest.pixels - 0.01 || Math.abs(pixels - nearest.pixels) <= 0.01 && depth < nearest.depth) {
|
||||
let normal: THREE.Vector3 | undefined;
|
||||
if (pickLocation.current) {
|
||||
const mesh = meshes.find(item => item.userData.name === object.name);
|
||||
if (mesh instanceof THREE.Mesh) {
|
||||
if (obstruction?.object === mesh && obstruction.face) {
|
||||
normal = obstruction.face.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld));
|
||||
} else {
|
||||
// A ray through a boundary vertex can miss every triangle by roundoff.
|
||||
// Use that vertex's displayed normal from the same native mesh.
|
||||
const positions = mesh.geometry.getAttribute("position"), normals = mesh.geometry.getAttribute("normal");
|
||||
const vertex = new THREE.Vector3();
|
||||
let facing = -Infinity;
|
||||
for (let index = 0; normals && index < positions.count; ++index) {
|
||||
vertex.fromBufferAttribute(positions, index).applyMatrix4(mesh.matrixWorld);
|
||||
if (vertex.distanceTo(point) > radius * 1e-6) continue;
|
||||
const candidate = new THREE.Vector3().fromBufferAttribute(normals, index)
|
||||
.applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld));
|
||||
const score = -candidate.dot(occlusion.ray.direction);
|
||||
if (score > facing) { normal = candidate; facing = score; }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
nearest = { point, pixels, depth, normal };
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nearest) {
|
||||
const point: [number, number, number] = [nearest.point.x, nearest.point.y, nearest.point.z];
|
||||
if (pickVertex.current) pickVertex.current(point);
|
||||
else pickLocation.current?.(point, nearest.normal ? [nearest.normal.x, nearest.normal.y, nearest.normal.z] : undefined);
|
||||
return;
|
||||
}
|
||||
if (pickVertex.current) return;
|
||||
}
|
||||
const ray = new THREE.Raycaster();
|
||||
ray.params.Line.threshold = radius / 200;
|
||||
ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1,
|
||||
1 - (event.clientY - rect.top) / rect.height * 2), camera);
|
||||
if (pickEdge.current) {
|
||||
const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.LineSegments))
|
||||
.find(hit => hit.index !== undefined && hit.object.userData.segmentEdges?.[Math.floor(hit.index / 2)]);
|
||||
if (hit) pickEdge.current(String(hit.object.userData.name), hit.object.userData.segmentEdges[Math.floor(hit.index! / 2)]);
|
||||
return;
|
||||
}
|
||||
const hit = ray.intersectObjects(content.children)[0];
|
||||
if (pickLocation.current) {
|
||||
if (hit?.face) {
|
||||
const normal = hit.face.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(hit.object.matrixWorld));
|
||||
pickLocation.current([hit.point.x, hit.point.y, hit.point.z], [normal.x, normal.y, normal.z]);
|
||||
} else if (hit?.object instanceof THREE.LineSegments) {
|
||||
pickLocation.current([hit.point.x, hit.point.y, hit.point.z]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (hit && pickPoint.current) {
|
||||
// Point raycasts report the closest point on the ray, not the vertex itself.
|
||||
const point = hit.object instanceof THREE.Points && hit.index !== undefined
|
||||
? hit.object.localToWorld(new THREE.Vector3().fromBufferAttribute(hit.object.geometry.getAttribute("position"), hit.index))
|
||||
: hit.point;
|
||||
pickPoint.current([point.x, point.y, point.z]);
|
||||
} else if (hit) select.current(hit.object.userData.name);
|
||||
};
|
||||
renderer.domElement.addEventListener("pointerdown", down);
|
||||
renderer.domElement.addEventListener("pointerup", pick);
|
||||
renderer.domElement.addEventListener("pointermove", hover);
|
||||
renderer.domElement.addEventListener("pointerleave", leave);
|
||||
const labels = window.document.createElement("div");
|
||||
labels.style.cssText = "position:absolute;inset:0;pointer-events:none;overflow:hidden";
|
||||
container.style.position = "relative"; container.appendChild(labels);
|
||||
let previousAnnotations: typeof inspectionAnnotations | undefined;
|
||||
let controlsBeforeInspection: boolean | undefined;
|
||||
const direction = new THREE.Vector3();
|
||||
let announcedReady = false;
|
||||
const syncDecoration = () => {
|
||||
const name = selected[0];
|
||||
const target = name ? content.children.find(child => child.userData.name === name) : undefined;
|
||||
if (!target) { publishDecoration(decoration); decoration.clear(); publishDecoration(decoration); return; }
|
||||
const box = new THREE.Box3().setFromObject(target);
|
||||
if (box.isEmpty()) { decoration.clear(); publishDecoration(decoration); return; }
|
||||
decoration.setTarget(box.getCenter(new THREE.Vector3()).toArray(), new THREE.Quaternion(), target);
|
||||
publishDecoration(decoration);
|
||||
};
|
||||
syncDecoration();
|
||||
renderer.setAnimationLoop(() => {
|
||||
decoration.updateFrame(camera);
|
||||
if (meshInfo.current.active || inspection.current.mode === "inspect") {
|
||||
controlsBeforeInspection ??= controls.enabled;
|
||||
controls.enabled = false; renderer.domElement.style.cursor = "crosshair";
|
||||
} else if (controlsBeforeInspection !== undefined) {
|
||||
controls.enabled = controlsBeforeInspection; controlsBeforeInspection = undefined;
|
||||
renderer.domElement.style.cursor = "";
|
||||
}
|
||||
const annotations = inspection.current.annotations;
|
||||
if (annotations !== previousAnnotations) {
|
||||
labels.replaceChildren(...annotations.map(annotation => {
|
||||
const label = window.document.createElement("span"); label.textContent = annotation.text;
|
||||
label.style.cssText = "position:absolute;background:#55007f;color:#ddd;padding:4px;white-space:nowrap";
|
||||
return label;
|
||||
})); previousAnnotations = annotations;
|
||||
}
|
||||
annotations.forEach((annotation, index) => {
|
||||
const p = new THREE.Vector3(...annotation.point).project(camera);
|
||||
const label = labels.children[index] as HTMLElement;
|
||||
label.style.display = p.z < -1 || p.z > 1 ? "none" : "block";
|
||||
label.style.left = `${(p.x+1)*renderer.domElement.clientWidth/2}px`;
|
||||
label.style.top = `${(1-p.y)*renderer.domElement.clientHeight/2}px`;
|
||||
});
|
||||
controls.update();
|
||||
updateFacetHighlights();
|
||||
const request = facets.current?.request;
|
||||
if (request && request.id !== handledFacetRequest.current) {
|
||||
handledFacetRequest.current = request.id;
|
||||
const picked = collectFacets();
|
||||
if (request.mode === "small") for (const name of Object.keys(picked)) {
|
||||
const small = new Set(facets.current?.components[name]?.filter(group => group.length <= request.maximum).flat() ?? []);
|
||||
picked[name] = picked[name].filter(index => small.has(index));
|
||||
}
|
||||
facets.current?.onFacets(picked);
|
||||
}
|
||||
if (viewDirection.current) {
|
||||
controls.object.getWorldDirection(direction);
|
||||
viewDirection.current([direction.x, direction.y, direction.z]);
|
||||
}
|
||||
renderer.render(scene, camera);
|
||||
if (!announcedReady) { announcedReady = true; ready.current?.(); }
|
||||
});
|
||||
return () => {
|
||||
if (preserveCamera) savedCamera.current = { documentId: document.documentId, position: camera.position.clone(), target: controls.target.clone() };
|
||||
for (const child of highlight.children) {
|
||||
const mesh = child as THREE.Mesh; mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose();
|
||||
}
|
||||
polygonLayer.remove();
|
||||
labels.remove();
|
||||
observer.disconnect(); renderer.setAnimationLoop(null); sceneCommands.dispose(); decoration.dispose(); controls.dispose();
|
||||
renderer.domElement.removeEventListener("pointerdown", down);
|
||||
renderer.domElement.removeEventListener("pointerup", pick);
|
||||
renderer.domElement.removeEventListener("pointermove", hover);
|
||||
renderer.domElement.removeEventListener("pointerleave", leave);
|
||||
geometries.forEach(item => item.dispose()); materials.forEach(item => item.dispose());
|
||||
content.children.forEach(child => child.userData.dispose?.()); renderer.dispose(); renderer.domElement.remove();
|
||||
};
|
||||
}, [document, selected.join("\0"), reserveControlsSpace, polygonMode, facetInteraction?.mode]);
|
||||
return <div ref={host} aria-label={ariaLabel} style={{ width: "100%", height: viewportHeight, maxHeight: "60vh" }} />;
|
||||
}
|
||||
Reference in New Issue
Block a user