Files
Aislo/B04_wf1_Surface/B04_wf1_Surface_UI_Camera.ts
T
eomsangdon c970812cf3 feat(3D): 휠 방향 반전·회전점 표시 + 3D/등고선 브라우저 보관함
- 휠 위 = 축소로 반전, 커서 지점을 축으로 한 dolly를 공용 유틸에서 직접 처리
- 회전 중심을 작은 구로 표시(돌리는 동안만, 화면상 크기 일정, 항상 위에 그림)
- 등고선 렌더 비용 감소: 폴리라인을 주곡선·보조곡선 2덩어리로 병합(드로우콜 424 → 2),
  라벨은 카메라가 움직였을 때만 재배치
- common_util_http_cache: 파일 mtime+크기 ETag, If-None-Match 일치 시 304
  (preview·contour 적용, 파일이 바뀌면 자동 무효화)
- A00_Common/b_asset_cache: IndexedDB 보관함(키 = projectId|url, 값 = 바이트+ETag).
  보관본 즉시 사용 후 백그라운드 재검증, 3D는 보관 바이트를 직접 파싱
- 프로젝트 전환 시 타 프로젝트 보관분 삭제, 대시보드→B그룹 이동 시 확정 모델의
  3D 프리뷰·등고선(1.0m) 미리 받기(포인트클라우드 제외)
2026-08-01 09:58:44 +09:00

287 lines
12 KiB
TypeScript

import * as THREE from "three";
import type { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import type { SurfaceBounds } from "./B04_wf1_Surface_Api_Fetch";
export const SURFACE_CAMERA_FOV = 50;
const LIGHT_VIEWER_BACKGROUND = 0xf5f7f9;
const DARK_VIEWER_BACKGROUND = 0x251f38;
export interface SurfaceCameraState {
direction: [number, number, number];
distanceMeters: number;
targetMeters: [number, number, number];
}
export function getReferenceCenter(bounds: SurfaceBounds): [number, number, number] {
return [
(bounds.x_min + bounds.x_max) / 2,
(bounds.y_min + bounds.y_max) / 2,
(bounds.z_min + bounds.z_max) / 2,
];
}
export function getTopFitDistance(bounds: SurfaceBounds, aspect: number): number {
const width = Math.max(bounds.x_max - bounds.x_min, 1);
const depth = Math.max(bounds.y_max - bounds.y_min, 1);
const verticalFov = (SURFACE_CAMERA_FOV * Math.PI) / 180;
const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * Math.max(aspect, 0.1));
const verticalDistance = depth / (2 * Math.tan(verticalFov / 2));
const horizontalDistance = width / (2 * Math.tan(horizontalFov / 2));
return Math.max(verticalDistance, horizontalDistance, 1) * 1.12;
}
export function targetPlaneMetersPerPixel(distanceMeters: number, viewportHeight: number): number {
const verticalFov = (SURFACE_CAMERA_FOV * Math.PI) / 180;
return (
(2 * Math.tan(verticalFov / 2) * Math.max(distanceMeters, 0.001)) / Math.max(viewportHeight, 1)
);
}
export function niceScaleDistance(roughMeters: number): number {
const exponent = Math.floor(Math.log10(Math.max(roughMeters, 0.001)));
const base = 10 ** exponent;
const normalized = roughMeters / base;
const step = normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10;
return step * base;
}
/* -----------------------------------------------------------------------------
* 커서 기준 회전·줌 (B04 포인트클라우드/지형, B05 노선 뷰어 공용)
*
* OrbitControls 기본값은 화면 중앙(target)을 축으로 돌아서, 커서로 보고 있는 봉우리가
* 화면 밖으로 밀려난다. 여기서는 커서 아래 지형 지점을 축으로 삼아 카메라와 target을
* 함께 돌린다 — 축이 화면에 고정되므로 시점이 튀지 않는다.
* 줌은 OrbitControls의 zoomToCursor로 같은 기준을 쓴다.
* -------------------------------------------------------------------------- */
/** 극점을 넘어 화면이 뒤집히지 않도록 남기는 여유각(rad). */
const POLAR_EPSILON = 0.02;
/** 포인트클라우드 클릭 허용 반경 — 카메라 거리에 비례(멀수록 점이 성기게 보인다). */
const POINT_PICK_RATIO = 0.01;
/** 휠 한 칸당 배율. 휠을 위로 올리면 이 값의 역수만큼 멀어진다(2026-08-01 사용자 지시). */
const ZOOM_STEP = 0.9;
/** 회전 중심 구슬의 화면상 크기 비율(카메라 거리 대비). 멀어져도 같은 크기로 보인다. */
const PIVOT_MARKER_RATIO = 0.012;
const PIVOT_MARKER_COLOR = 0xf59e0b;
export interface CursorPivotOptions {
camera: THREE.PerspectiveCamera;
controls: OrbitControls;
/** 포인터 이벤트를 받는 캔버스. */
element: HTMLElement;
/** 커서 아래에서 찾을 대상(지형 메시·포인트클라우드). 없으면 기존 축을 유지한다. */
pickables: () => THREE.Object3D[];
/** 마커 드래그 등 다른 조작이 잡고 있으면 회전을 넘긴다. */
blocked?: () => boolean;
/** 회전 중심 구슬을 띄울 장면. 주지 않으면 구슬을 만들지 않는다. */
scene?: THREE.Scene;
}
/** 커서 기준 회전·줌을 붙이고, 해제 함수를 돌려준다. */
export function bindCursorPivotControls(options: CursorPivotOptions): () => void {
const { camera, controls, element } = options;
// 회전·줌 모두 여기서 직접 처리한다(OrbitControls에는 휠 방향을 뒤집는 설정이 없다).
controls.enableRotate = false;
controls.enableZoom = false;
// 가운데 버튼 드래그 = 화면 이동(전역 공통). 기본값(DOLLY)은 휠 줌과 겹쳐 쓸모가 없다.
controls.mouseButtons.MIDDLE = THREE.MOUSE.PAN;
// 회전 중심 구슬 — 돌리는 동안에만 보인다. 화면상 크기는 거리와 무관하게 일정하다.
const pivotMarker = options.scene
? new THREE.Mesh(
new THREE.SphereGeometry(1, 16, 12),
new THREE.MeshBasicMaterial({
color: PIVOT_MARKER_COLOR,
// 지형에 묻혀 안 보이면 축을 확인할 수 없으므로 항상 위에 그린다.
depthTest: false,
transparent: true,
opacity: 0.9,
}),
)
: null;
if (pivotMarker && options.scene) {
pivotMarker.visible = false;
pivotMarker.renderOrder = 999;
options.scene.add(pivotMarker);
}
/** 구슬을 현재 축 위치·크기로 맞춘다. */
function syncPivotMarker(): void {
if (!pivotMarker || !pivotMarker.visible) return;
pivotMarker.position.copy(pivot);
const distance = camera.position.distanceTo(pivot);
pivotMarker.scale.setScalar(Math.max(distance * PIVOT_MARKER_RATIO, 0.01));
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pivot = new THREE.Vector3();
const viewDirection = new THREE.Vector3();
const fallbackPlane = new THREE.Plane();
let pointerId: number | null = null;
let lastX = 0;
let lastY = 0;
/** 커서가 가리키는 지형 위 지점을 회전축으로 잡는다.
*
* 지형을 맞히면 그 점을 쓰고, 하늘·구멍이라 못 맞히면 시선에 수직이고 현재 target을
* 지나는 평면과 광선을 만나게 해 **커서 방향**의 점을 쓴다(화면 중앙으로 돌아가지 않는다). */
function pickPivot(event: { clientX: number; clientY: number }): void {
pivot.copy(controls.target);
const rect = element.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
pointer.set(
((event.clientX - rect.left) / rect.width) * 2 - 1,
-((event.clientY - rect.top) / rect.height) * 2 + 1,
);
raycaster.setFromCamera(pointer, camera);
// 포인트클라우드는 점 사이가 비어 있어 정확히 맞히기 어렵다 — 거리에 비례한 허용 반경을 준다.
raycaster.params.Points.threshold =
camera.position.distanceTo(controls.target) * POINT_PICK_RATIO;
const hit = raycaster.intersectObjects(options.pickables(), true)[0];
if (hit) {
pivot.copy(hit.point);
return;
}
camera.getWorldDirection(viewDirection);
fallbackPlane.setFromNormalAndCoplanarPoint(viewDirection, controls.target);
raycaster.ray.intersectPlane(fallbackPlane, pivot);
}
function onPointerDown(event: PointerEvent): void {
// 가운데 버튼은 브라우저 기본 동작(페이지 자동 스크롤)이 화면 이동과 겹치므로 막는다.
if (event.button === 1) event.preventDefault();
if (event.button !== 0 || pointerId !== null) return;
if (options.blocked?.() || !controls.enabled) return;
pickPivot(event);
pointerId = event.pointerId;
lastX = event.clientX;
lastY = event.clientY;
if (pivotMarker) {
pivotMarker.visible = true;
syncPivotMarker();
}
}
/** 휠 줌 — 커서가 가리키는 지점을 축으로 삼아 그 점이 화면에 고정된 채 멀어지고 가까워진다.
* 휠을 위로 올리면 멀어진다(사용자 지시). */
function onWheel(event: WheelEvent): void {
if (!controls.enabled || options.blocked?.()) return;
event.preventDefault();
pickPivot(event);
const factor = event.deltaY < 0 ? 1 / ZOOM_STEP : ZOOM_STEP;
const cameraOffset = camera.position.clone().sub(pivot).multiplyScalar(factor);
const targetOffset = controls.target.clone().sub(pivot).multiplyScalar(factor);
// 축에 너무 가까워지면 시점이 뒤집히므로 최소 거리를 남긴다.
if (cameraOffset.length() < 0.5 && factor < 1) return;
camera.position.copy(pivot).add(cameraOffset);
controls.target.copy(pivot).add(targetOffset);
camera.lookAt(controls.target);
controls.update();
syncPivotMarker();
}
function onPointerMove(event: PointerEvent): void {
if (pointerId !== event.pointerId) return;
if (options.blocked?.()) {
stop();
return;
}
const height = Math.max(element.clientHeight, 1);
// OrbitControls와 같은 감도: 화면 높이만큼 끌면 한 바퀴.
const yaw = (2 * Math.PI * (event.clientX - lastX)) / height;
const pitch = (2 * Math.PI * (event.clientY - lastY)) / height;
lastX = event.clientX;
lastY = event.clientY;
if (yaw === 0 && pitch === 0) return;
const up = camera.up.clone().normalize();
const cameraOffset = camera.position.clone().sub(pivot);
const targetOffset = controls.target.clone().sub(pivot);
// 수평 회전 — 화면 상하축(카메라 up) 기준.
cameraOffset.applyAxisAngle(up, -yaw);
targetOffset.applyAxisAngle(up, -yaw);
// 수직 회전 — 시선의 오른쪽 축 기준. 마우스를 내리면 위에서 내려다보는 방향(2026-08-01
// 사용자 지시로 상하 반전). 극점을 넘으면 상하 성분만 버린다.
const eyeDirection = cameraOffset.clone().sub(targetOffset);
const right = eyeDirection.clone().cross(up);
if (right.lengthSq() > 1e-8) {
right.normalize();
const rotated = eyeDirection.clone().applyAxisAngle(right, pitch);
const polar = rotated.angleTo(up);
if (polar > POLAR_EPSILON && polar < Math.PI - POLAR_EPSILON) {
cameraOffset.applyAxisAngle(right, pitch);
targetOffset.applyAxisAngle(right, pitch);
}
}
camera.position.copy(pivot).add(cameraOffset);
controls.target.copy(pivot).add(targetOffset);
camera.lookAt(controls.target);
controls.update();
syncPivotMarker();
}
function stop(): void {
pointerId = null;
if (pivotMarker) pivotMarker.visible = false;
}
function onPointerEnd(event: PointerEvent): void {
if (pointerId === event.pointerId) stop();
}
element.addEventListener("pointerdown", onPointerDown);
element.addEventListener("pointermove", onPointerMove);
element.addEventListener("pointerup", onPointerEnd);
element.addEventListener("pointercancel", onPointerEnd);
element.addEventListener("pointerleave", onPointerEnd);
element.addEventListener("wheel", onWheel, { passive: false });
return () => {
element.removeEventListener("pointerdown", onPointerDown);
element.removeEventListener("pointermove", onPointerMove);
element.removeEventListener("pointerup", onPointerEnd);
element.removeEventListener("pointercancel", onPointerEnd);
element.removeEventListener("pointerleave", onPointerEnd);
element.removeEventListener("wheel", onWheel);
if (pivotMarker) {
pivotMarker.removeFromParent();
pivotMarker.geometry.dispose();
(pivotMarker.material as THREE.Material).dispose();
}
};
}
export function bindSurfaceViewerTheme(
applyBackground: (color: string | number) => void,
): () => void {
const systemDarkTheme = window.matchMedia("(prefers-color-scheme: dark)");
const update = (): void => {
const theme = document.documentElement.getAttribute("data-theme");
const dark = theme === "dark" || (theme !== "light" && systemDarkTheme.matches);
if (!dark) {
applyBackground(LIGHT_VIEWER_BACKGROUND);
return;
}
const surfaceRaised = getComputedStyle(document.documentElement)
.getPropertyValue("--color-surface-raised")
.trim();
applyBackground(
surfaceRaised && CSS.supports("color", surfaceRaised)
? surfaceRaised
: DARK_VIEWER_BACKGROUND,
);
};
const observer = new MutationObserver(update);
observer.observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme"],
});
systemDarkTheme.addEventListener("change", update);
update();
return () => {
observer.disconnect();
systemDarkTheme.removeEventListener("change", update);
};
}