Finish slicing box and UI

This commit is contained in:
Fuhrmann 2025-03-07 10:09:38 +01:00
parent 8227b4141a
commit 213537508c
19 changed files with 965 additions and 1361 deletions

View file

@ -1,13 +1,13 @@
import { AxesHelper, Group, Scene } from "three";
import { AxesHelper, Group, Mesh, MeshStandardMaterial, Scene } from "three";
import { buildMeshes } from "./utils/build-meshes";
import { Extent, buildScene } from "./utils/build-scene";
import { getMetadata } from "./utils/utils";
import { MODEL_ID, SERVICE_URL } from "./config";
import { buildClippingplanes } from "./utils/build-clipping-planes";
import { buildGrid } from "./utils/build-grid";
import { buildCoordinateGrid } from "./utils/build-coordinate-grid";
import { DragControls } from "three/examples/jsm/Addons.js";
export class MapScene {
export class SceneView {
private _scene: Scene;
private _dragControls: DragControls;
private _model: Group;
@ -20,7 +20,7 @@ export class MapScene {
static async create(container: HTMLElement, modelId: string) {
const { scene, model, dragControls } = await init(container, modelId);
return new MapScene(scene, model, dragControls);
return new SceneView(scene, model, dragControls);
}
get scene() {
@ -51,6 +51,21 @@ export class MapScene {
mesh.visible = !mesh.visible;
}
}
toggleCoordinateGrid() {
const group = this._scene.getObjectByName("coordinate-grid");
if (group) {
group.visible = !group.visible;
}
}
toggleWireFrame() {
const model = this._model;
model.children.forEach((child) => {
const material = (child as Mesh).material as MeshStandardMaterial;
material.wireframe = !material.wireframe;
});
}
}
async function init(container: HTMLElement, modelId = MODEL_ID) {
@ -92,11 +107,11 @@ async function init(container: HTMLElement, modelId = MODEL_ID) {
}
// Add a coordinate grid to the scene
const { gridHelper, annotations } = buildGrid(extent);
const { gridHelper, annotations } = buildCoordinateGrid(extent);
const annotationsGroup = new Group();
annotationsGroup.name = "coordinate-grid";
annotationsGroup.add(...annotations);
scene.add(gridHelper, annotationsGroup);
annotationsGroup.add(...annotations, gridHelper);
scene.add(annotationsGroup);
//const axesHelper = new AxesHelper(5);
//scene.add(axesHelper);

View file

@ -166,6 +166,7 @@ export function buildClippingplanes(
const clippingBox = new Group();
clippingBox.add(planeMeshGroup, edgeMeshGroup);
clippingBox.name = "clipping-box";
clippingBox.visible = false;
scene.add(clippingBox);
// Enable DragControls for the clipping planes
@ -175,18 +176,11 @@ export function buildClippingplanes(
renderer.domElement
);
dragControls.addEventListener("dragstart", (event) => {
const object = event.object as PlaneMesh;
dragControls.enabled = false;
dragControls.addEventListener("dragstart", () => {
// Disable OrbitControls when dragging starts
orbitControls.enabled = false;
// Remove existing cap meshes
const capMeshGroupName = `cap-mesh-group-${object.name}`;
let capMeshGroup = scene.getObjectByName(capMeshGroupName);
while (capMeshGroup) {
scene.remove(capMeshGroup);
capMeshGroup = scene.getObjectByName(capMeshGroupName);
}
});
dragControls.addEventListener("dragend", () => {
@ -468,77 +462,94 @@ function generateCapMeshes(
// Iterate over the list of geologic meshes
for (let mesh of meshes) {
const position = mesh.geometry.attributes.position.array;
const indices = mesh.geometry.index ? mesh.geometry.index.array : null;
const edges: Array<[Vector3, Vector3]> = [];
// Slice visible meshes only
if (mesh.visible) {
const position = mesh.geometry.attributes.position.array;
const indices = mesh.geometry.index ? mesh.geometry.index.array : null;
const edges: Array<[Vector3, Vector3]> = [];
for (
let i = 0;
i < (indices ? indices.length : position.length / 3);
i += 3
) {
const i1 = indices ? indices[i] * 3 : i * 3;
const i2 = indices ? indices[i + 1] * 3 : (i + 1) * 3;
const i3 = indices ? indices[i + 2] * 3 : (i + 2) * 3;
for (
let i = 0;
i < (indices ? indices.length : position.length / 3);
i += 3
) {
const i1 = indices ? indices[i] * 3 : i * 3;
const i2 = indices ? indices[i + 1] * 3 : (i + 1) * 3;
const i3 = indices ? indices[i + 2] * 3 : (i + 2) * 3;
const v1 = new Vector3(position[i1], position[i1 + 1], position[i1 + 2]);
const v2 = new Vector3(position[i2], position[i2 + 1], position[i2 + 2]);
const v3 = new Vector3(position[i3], position[i3 + 1], position[i3 + 2]);
const v1 = new Vector3(
position[i1],
position[i1 + 1],
position[i1 + 2]
);
const v2 = new Vector3(
position[i2],
position[i2 + 1],
position[i2 + 2]
);
const v3 = new Vector3(
position[i3],
position[i3 + 1],
position[i3 + 2]
);
// Check if the triangle is cut by the plane
const d1 = plane.distanceToPoint(v1);
const d2 = plane.distanceToPoint(v2);
const d3 = plane.distanceToPoint(v3);
// Check if the triangle is cut by the plane
const d1 = plane.distanceToPoint(v1);
const d2 = plane.distanceToPoint(v2);
const d3 = plane.distanceToPoint(v3);
// Compute intersection points
const intersections = [];
// Compute intersection points
const intersections = [];
if (d1 * d2 < 0) intersections.push(intersectEdge(v1, v2, d1, d2));
if (d2 * d3 < 0) intersections.push(intersectEdge(v2, v3, d2, d3));
if (d3 * d1 < 0) intersections.push(intersectEdge(v3, v1, d3, d1));
if (d1 * d2 < 0) intersections.push(intersectEdge(v1, v2, d1, d2));
if (d2 * d3 < 0) intersections.push(intersectEdge(v2, v3, d2, d3));
if (d3 * d1 < 0) intersections.push(intersectEdge(v3, v1, d3, d1));
if (intersections.length === 2) {
edges.push([intersections[0], intersections[1]]);
if (intersections.length === 2) {
edges.push([intersections[0], intersections[1]]);
}
}
// Intersection surface can be a multipolygon consisting of disconnected polygons
const polygons: Vector3[][] = buildPolygons(edges);
// Clip cap surfaces with clipping planes
const clippingPlanes = planes.filter(
(p) => !p.normal.equals(plane.normal)
);
const offset = orientation === Orientation.Z ? 1 : -1;
const material = new MeshStandardMaterial({
color: (mesh.material as MeshStandardMaterial).color,
side: DoubleSide,
polygonOffset: true,
polygonOffsetFactor: offset,
polygonOffsetUnits: offset,
clippingPlanes,
});
const localMeshes = polygons.map((polygon) => {
const geometry = triangulatePolygon(polygon, plane);
const capMesh = new Mesh(geometry, material);
// Offset mesh to avoid flickering
const normal = plane.normal.clone().multiplyScalar(offset);
const positionAttr = capMesh.geometry.attributes.position;
for (let i = 0; i < positionAttr.count; i++) {
const x = positionAttr.getX(i) + normal.x;
const y = positionAttr.getY(i) + normal.y;
const z = positionAttr.getZ(i) + normal.z;
positionAttr.setXYZ(i, x, y, z);
}
positionAttr.needsUpdate = true;
return capMesh;
});
capMeshes.push(...localMeshes);
}
// Intersection surface can be a multipolygon consisting of disconnected polygons
const polygons: Vector3[][] = buildPolygons(edges);
// Clip cap surfaces with clipping planes
const clippingPlanes = planes.filter((p) => !p.normal.equals(plane.normal));
const offset = orientation === Orientation.Z ? 1 : -1;
const material = new MeshStandardMaterial({
color: (mesh.material as MeshStandardMaterial).color,
side: DoubleSide,
polygonOffset: true,
polygonOffsetFactor: offset,
polygonOffsetUnits: offset,
clippingPlanes,
});
const localMeshes = polygons.map((polygon) => {
const geometry = triangulatePolygon(polygon, plane);
const capMesh = new Mesh(geometry, material);
// Offset mesh to avoid flickering
const normal = plane.normal.clone().multiplyScalar(offset);
const positionAttr = capMesh.geometry.attributes.position;
for (let i = 0; i < positionAttr.count; i++) {
const x = positionAttr.getX(i) + normal.x;
const y = positionAttr.getY(i) + normal.y;
const z = positionAttr.getZ(i) + normal.z;
positionAttr.setXYZ(i, x, y, z);
}
positionAttr.needsUpdate = true;
return capMesh;
});
capMeshes.push(...localMeshes);
}
return capMeshes;

View file

@ -13,7 +13,7 @@ enum Orientation {
Vertical,
}
export function buildGrid(extent: Extent) {
export function buildCoordinateGrid(extent: Extent) {
const center = getCenter3D(extent);
// Calculate the width and height of the grid
const gridWidth = extent.xmax - extent.xmin;
@ -26,10 +26,10 @@ export function buildGrid(extent: Extent) {
const gridHelper = new GridHelper(Math.max(gridWidth, gridHeight), divisions);
// Position the grid in the scene to match the given extent
gridHelper.position.set(center.x, center.y, 0); // Center the grid at the midpoint
gridHelper.position.set(center.x, center.y, 0);
// Rotate the grid if needed to align with the world coordinates
gridHelper.rotation.x = Math.PI / 2; // Rotate to align with the XY plane
// Rotate the grid to align with the XY-plane
gridHelper.rotation.x = Math.PI / 2;
// Retrieve the geometry of the grid helper
const geometry = gridHelper.geometry;

View file

@ -1,29 +0,0 @@
import { AmbientLight, DirectionalLight, Scene } from "three";
const DEG2RAD = Math.PI / 180;
export function buildDefaultLights(scene: Scene) {
// ambient light
scene.add(new AmbientLight(0x999999));
// directional lights
const opt = {
azimuth: 220,
altitude: 45,
};
const lambda = (90 - opt.azimuth) * DEG2RAD;
const phi = opt.altitude * DEG2RAD;
const x = Math.cos(phi) * Math.cos(lambda);
const y = Math.cos(phi) * Math.sin(lambda);
const z = Math.sin(phi);
const light1 = new DirectionalLight(0xffffff, 0.5);
light1.position.set(x, y, z);
scene.add(light1);
// thin light from the opposite direction
const light2 = new DirectionalLight(0xffffff, 0.1);
light2.position.set(-x, -y, -z);
scene.add(light2);
}

View file

@ -6,8 +6,7 @@ import {
MeshStandardMaterial,
} from "three";
import { fetchTriangleIndices } from "./fetch-triangle-indices";
import { fetchVertices } from "./fetch-vertices";
import { fetchVertices, fetchTriangleIndices } from "./utils";
import { TRIANGLE_INDICES_URL, VERTICES_URL } from "../config";
interface MappedFeature {
@ -22,6 +21,9 @@ export async function buildMeshes(mappedFeatures: MappedFeature[]) {
for (let i = 0; i < mappedFeatures.length; i++) {
const layerData = mappedFeatures[i];
const mesh = await buildMesh(layerData);
if (layerData.name === "Topography") {
mesh.visible = false;
}
meshes.push(mesh);
}

View file

@ -1,9 +1,42 @@
import { Color, PerspectiveCamera, Scene, Vector3, WebGLRenderer } from "three";
import {
PerspectiveCamera,
Scene,
WebGLRenderer,
AmbientLight,
DirectionalLight,
} from "three";
import { buildDefaultLights } from "./build-default-lights";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { getCenter3D, getMaxSize } from "./utils";
const DEG2RAD = Math.PI / 180;
function buildDefaultLights() {
// Ambient light
scene.add(new AmbientLight(0xaaaaaa));
// Directional lights
const opt = {
azimuth: 220,
altitude: 45,
};
const lambda = (90 - opt.azimuth) * DEG2RAD;
const phi = opt.altitude * DEG2RAD;
const x = Math.cos(phi) * Math.cos(lambda);
const y = Math.cos(phi) * Math.sin(lambda);
const z = Math.sin(phi);
const light1 = new DirectionalLight(0xffffff, 0.5);
light1.position.set(x, y, z);
scene.add(light1);
// Thin light from the opposite direction
const light2 = new DirectionalLight(0xffffff, 0.1);
light2.position.set(-x, -y, -z);
return light2;
}
export interface Extent {
xmin: number;
ymin: number;
@ -34,6 +67,7 @@ export function buildScene(container: HTMLElement, extent: Extent) {
camera.position.set(center.x, center.y - 125000, extent.zmax + 100000);
camera.lookAt(center);
// Initialize the renderer
renderer = new WebGLRenderer({
alpha: true,
logarithmicDepthBuffer: true,
@ -43,6 +77,8 @@ export function buildScene(container: HTMLElement, extent: Extent) {
renderer.setSize(width, height);
renderer.localClippingEnabled = true;
renderer.setAnimationLoop(animate);
// Handle window resize event to adapt the aspect ratio
window.addEventListener("resize", () => onWindowResize(container));
container.appendChild(renderer.domElement);
@ -55,16 +91,18 @@ export function buildScene(container: HTMLElement, extent: Extent) {
// Scene will hold all our elements such as objects, cameras and lights
scene = new Scene();
scene.background = new Color(0xdddddd);
buildDefaultLights(scene);
// Add lights to the scene
const lights = buildDefaultLights();
lights.name = "lights";
scene.add(lights);
return { renderer, scene, camera, controls };
}
function onWindowResize(container: HTMLElement) {
// Update the camera's aspect ratio and the renderer's size to reflect
// the new screen dimensions upon a browser window resize.
// the new screen dimensions upon a browser window resize
camera.aspect = container.clientWidth / container.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);

View file

@ -1,8 +0,0 @@
import { request } from "./request";
import { unpackEdges } from "./parsers";
export async function fetchTriangleIndices(edgeUrl: string, geomId: string) {
const url = edgeUrl + geomId;
const buffer = await request(url);
return unpackEdges(buffer);
}

View file

@ -1,8 +0,0 @@
import { unpackVertices } from "./parsers";
import { request } from "./request";
export async function fetchVertices(pointUrl: string, geomId: string) {
const url = pointUrl + geomId;
const buffer = await request(url);
return unpackVertices(buffer);
}

View file

@ -1,8 +0,0 @@
export async function request(url: string) {
const response = await fetch(url);
if (response.ok) {
return response.arrayBuffer();
} else {
throw new Error("HTTP error status: " + response.status);
}
}

View file

@ -1,5 +1,6 @@
import { Vector3 } from "three";
import { Extent } from "./build-scene";
import { unpackEdges, unpackVertices } from "./parsers";
export function getMaxSize(extent: Extent) {
return Math.max(
@ -32,3 +33,24 @@ export async function getMetadata(serviceUrl: string) {
throw new Error("HTTP error status: " + response.status);
}
}
export async function request(url: string) {
const response = await fetch(url);
if (response.ok) {
return response.arrayBuffer();
} else {
throw new Error("HTTP error status: " + response.status);
}
}
export async function fetchTriangleIndices(edgeUrl: string, geomId: string) {
const url = edgeUrl + geomId;
const buffer = await request(url);
return unpackEdges(buffer);
}
export async function fetchVertices(pointUrl: string, geomId: string) {
const url = pointUrl + geomId;
const buffer = await request(url);
return unpackVertices(buffer);
}