| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622 |
- /** Three.js adapter for a selected object and its bounded local underground context. */
- import * as THREE from 'three'
- import { enhancementLabel } from '../domain/pipeEnhancement.js'
- import { displayPipeDiameter, PIPE_PALETTE } from '../domain/pipeVisual.js'
- import { manholeModelMetrics } from '../domain/manholeModel.js'
- import { attachSceneFocus } from './sceneInputFocus.js'
- import { addDetailedPipeSegment } from './pipeDetailGeometry.js'
- import { attachPointPick } from './pointPick.js'
- import { pipeSurfaceMaterial, outlineSelectedPipe } from './pipeSurfaceMaterial.js'
- import { sourceDiameterM, pipeSurface } from '../domain/pipePhysical.js'
- import { planMarker } from '../domain/markerPlan.js'
- import { deviceVisualForStatus } from '../domain/deviceStatus.js'
- import { renderMarker } from './markerAssets.js'
- /**
- * 状态色键兜底表(与 `mapService.toneColors()` 同值、与 `styles/tokens.css` 同值)。
- * 色值真源仍是 tokens.css;本表只在读不到计算样式时兜底(脱浏览器回归、样式未挂载)。
- * 刻意不与 mapService 共享常量:那两个文件带有其它在制品改动,本票不触碰它们。
- */
- /** 设备图标相对设备主体的世界高度偏移(不受 group 缩放影响)。 */
- const ICON_OFFSET_ABOVE_DEVICE = 0.62
- const TONE_FALLBACK = Object.freeze({
- lv1: '#ff3b52',
- lv2: '#ffb020',
- lv3: '#01abea',
- lv4: '#27d17a',
- neutral: '#5680b0',
- 'point-offline': '#94a3b8',
- 'point-unknown': '#a970ff',
- 'point-unassociated': '#a3e635',
- })
- /**
- * 状态色键 → 十六进制。与 `mapService` 的 `toneColors()` 同一口径:
- * 色值唯一真源是 `styles/tokens.css`,这里从 `.cockpit-shell` 计算样式读,
- * 脱浏览器(Node 回归)读不到时用 `markerPlan.TONE_FALLBACK` 同值兜底。
- */
- function toneHex(tone) {
- const fallback = TONE_FALLBACK[tone] || TONE_FALLBACK.neutral
- if (typeof document === 'undefined' || !document.querySelector || typeof getComputedStyle !== 'function') return fallback
- const shell = document.querySelector('.cockpit-shell')
- if (!shell) return fallback
- const value = getComputedStyle(shell).getPropertyValue(`--${tone}`)
- return value && value.trim() ? value.trim() : fallback
- }
- /**
- * 设备 → 主图 marker 合成计划(**语义同步的唯一裁决点**)。
- *
- * 维护者 2026-10-22:「已确认使用了场景同款设备图标,但是颜色状态及中间的类型图标还是没有同步。」
- * 两处不一致的根因都在这里,必须与主图**逐项对齐**:
- *
- * 1. **颜色**:主图给 `planMarker` 传的是**设备状态表**的色键
- * (`deviceVisualForStatus()`:ALARM→lv1 / WARNING→lv2 / WORK_ORDER→lv3 /
- * NORMAL→lv4 / OFFLINE→`point-offline` / 未知→`point-unknown`)。
- * 不传 tone 会落到 `markerPlan` 的**点位聚合态**默认表 —— 那里 OFFLINE/UNKNOWN
- * 是 `neutral`,于是场景里的离线设备与主图不同色。所以必须显式传 `tone`。
- * 2. **类型图标**:内层图标按 `industry` 选(gas/water/drainage/manhole)。
- * 设备卡本身常无 `industry`,主图的规则是**继承所属点位行业**;设备侧已在
- * `domain/enhancementDevices.js` 按同一规则落好(`device.industry || point.industry`),
- * 这里直接消费,不再二次推导。
- * 3. **未关联设备**:主图对「没有监测点归属」的设备走镂空母版(业务异常时不降饱和)。
- * 判据就是有没有 `pointCode` —— 与主图 `unassociated` 同一含义。
- */
- export function deviceMarkerPlan(device) {
- const visual = deviceVisualForStatus(device.status)
- return planMarker({
- kind: 'monitoring-device',
- status: device.status,
- industry: device.industry || '',
- tone: visual.tone,
- unassociated: !device.pointCode,
- })
- }
- /**
- * 设备图标的**唯一来源**:复用主图 marker 的合成链路(`planMarker` + `renderMarker`),
- * 因此地下管线详情视图里的设备图标与一张图上的**同款**,不是另画一套。
- * 母版形状、状态色、内层行业图标、白描边、尺寸全部由 `deviceMarkerPlan` 决定。
- */
- async function defaultDeviceIcon(device) {
- const plan = deviceMarkerPlan(device)
- const url = await renderMarker(plan, { tintHex: toneHex(plan.tint) })
- return { url, width: plan.draw.width, height: plan.draw.height, tone: plan.tint }
- }
- function defaultRendererFactory({ canvas }) {
- return new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true })
- }
- function project([lon, lat], center, scale) {
- const cosLat = Math.cos((center[1] * Math.PI) / 180)
- return new THREE.Vector3(
- (lon - center[0]) * 111320 * cosLat * scale,
- 0,
- -(lat - center[1]) * 111320 * scale,
- )
- }
- function disposeObject(root) {
- const resources = new Set()
- root.traverse((node) => {
- if (node.geometry) resources.add(node.geometry)
- if (node.material) for (const value of [].concat(node.material)) {
- resources.add(value)
- if (value.map) resources.add(value.map)
- }
- })
- for (const resource of resources) resource.dispose()
- }
- function material(color, opacity = 1) {
- return new THREE.MeshStandardMaterial({ color, roughness: 0.62, metalness: 0.18, transparent: opacity < 1, opacity })
- }
- function buildObject(plan, frame = null) {
- const object = plan.object
- const root = new THREE.Group()
- root.name = `pipe-enhancement:${object.code}`
- const center = object.renderKind === 'pipe'
- ? [0, 1].map((axis) => {
- const [min, max] = object.path.reduce(([lo, hi], point) =>
- [Math.min(lo, point[axis]), Math.max(hi, point[axis])], [Infinity, -Infinity])
- return (min + max) / 2
- })
- : object.position || object.path[0]
- const scale = 1
- const points = object.path.map((point) => project(point, frame?.center || center, scale))
- const color = (PIPE_PALETTE[object.colorKey] || PIPE_PALETTE.UNKNOWN).color
- if (object.renderKind === 'pipe') {
- const diameterM = object.displayDiameterM ?? displayPipeDiameter(object.diameterM ?? sourceDiameterM(object.diameter))
- const surface = object.surface || pipeSurface(object.material)
- if (diameterM === null) {
- const guide = new THREE.Line(new THREE.BufferGeometry().setFromPoints(points), new THREE.LineDashedMaterial({ color, dashSize: 1, gapSize: 0.6 }))
- guide.name = 'missing-diameter-guide'
- guide.computeLineDistances()
- root.add(guide)
- }
- for (let i = 1; diameterM !== null && i < points.length; i += 1) {
- if (object.primary === false) {
- const delta = new THREE.Vector3().subVectors(points[i], points[i - 1])
- const length = delta.length()
- if (length < 0.000001) continue
- const mesh = new THREE.Mesh(new THREE.CylinderGeometry(diameterM / 2, diameterM / 2, length, 16, 1, true), pipeSurfaceMaterial(color, surface))
- mesh.name = 'neighbor-pipe-wall'
- mesh.position.copy(points[i - 1]).add(points[i]).multiplyScalar(0.5)
- mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), delta.normalize())
- root.add(mesh)
- } else addDetailedPipeSegment(root, points[i - 1], points[i], color, {
- startFlange: i === 1,
- endFlange: i === points.length - 1,
- radius: diameterM / 2,
- surface,
- })
- }
- } else if (object.renderKind === 'manhole') {
- // 票 04:尺寸与 Y 偏移全部来自 domain/manholeModel.js 的单源,
- // 并与管线共用同一个显示倍率(PIPE_DISPLAY.diameterScale),不再手写第二组米数。
- const model = manholeModelMetrics()
- const shell = new THREE.Mesh(new THREE.CylinderGeometry(model.shaft.radius, model.shaft.radius, model.shaft.height, 32, 1, true, Math.PI * 0.25, Math.PI * 1.5),
- new THREE.MeshStandardMaterial({ color: '#718093', roughness: 0.9, side: THREE.DoubleSide }))
- shell.name = 'manhole-shaft'
- shell.position.copy(points[0])
- shell.position.y = model.shaft.centerY
- root.add(shell)
- const base = new THREE.Mesh(new THREE.CylinderGeometry(model.base.radius, model.base.radius, model.base.height, 32), material('#53616f'))
- base.position.copy(points[0]); base.position.y = model.base.centerY
- root.add(base)
- const cover = new THREE.Mesh(new THREE.CylinderGeometry(model.cover.radius, model.cover.radius, model.cover.height, 32), material(color))
- cover.name = 'manhole-cover'
- cover.position.copy(points[0]); cover.position.y = model.cover.centerY
- cover.rotation.x = model.cover.tilt
- root.add(cover)
- } else {
- const shape = object.renderKind === 'valve'
- ? new THREE.CylinderGeometry(0.48, 0.48, 0.16, 24)
- : object.renderKind === 'elbow'
- ? new THREE.TorusGeometry(0.48, 0.15, 12, 24, Math.PI)
- : object.renderKind === 'branch' || object.renderKind === 'cross'
- ? new THREE.ConeGeometry(0.55, 0.72, object.renderKind === 'cross' ? 4 : 8)
- : new THREE.BoxGeometry(0.72, 0.72, 0.72)
- const mesh = new THREE.Mesh(shape, material(color))
- mesh.position.copy(points[0])
- if (object.renderKind === 'elbow') mesh.rotation.y = Math.PI / 2
- root.add(mesh)
- }
- if (object.primary !== false) outlineSelectedPipe(root)
- root.position.y = frame ? ((frame.depthM || 0) - (object.depthM || 0)) * scale : 0
- root.userData = { code: object.code, sourceKind: object.sourceKind, primary: object.primary !== false, clipped: object.clipped === true }
- return root
- }
- function buildNeighborhood(plan) {
- if ((!plan.objects || plan.objects.length <= 1) && !plan.devices?.length) return buildObject(plan)
- const objects = plan.objects || [{ ...plan.object, primary: true, depthM: 0 }]
- const path = plan.object.path
- const center = [0, 1].map((axis) => {
- const [min, max] = path.reduce(([lo, hi], p) => [Math.min(lo, p[axis]), Math.max(hi, p[axis])], [Infinity, -Infinity])
- return (min + max) / 2
- })
- const frame = { center, scale: 1, depthM: objects[0].depthM }
- const root = new THREE.Group()
- root.name = `pipe-enhancement:${plan.object.code}`
- for (const object of objects) root.add(buildObject({ object }, frame))
- for (const device of plan.devices || []) {
- const group = new THREE.Group()
- group.name = `device:${device.code}`
- group.userData.device = device
- group.position.copy(project(device.position, center, frame.scale))
- const radius = device.pipeDisplayRadiusM || 0
- const deviceScale = Math.max(3.5, Math.min(7, radius * 2))
- group.scale.setScalar(deviceScale)
- group.renderOrder = 20
- group.position.y = ((frame.depthM || 0) - device.depthM) * frame.scale + Math.max(radius * 1.06, device.mountHeightM || 0) + deviceScale * 0.35
- const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.035, 0.25, 8), material('#b9c5d0'))
- stem.position.y = -0.16
- stem.renderOrder = 21
- stem.material.depthTest = false
- stem.material.depthWrite = false
- group.add(stem)
- const color = (PIPE_PALETTE[device.colorKey] || PIPE_PALETTE.UNKNOWN).color
- const shape = device.industry === 'GAS' ? new THREE.BoxGeometry(0.22, 0.32, 0.18)
- : device.industry === 'WATER_SUPPLY' ? new THREE.CylinderGeometry(0.15, 0.15, 0.28, 12)
- : device.industry === 'MANHOLE' ? new THREE.BoxGeometry(0.3, 0.1, 0.22)
- : new THREE.ConeGeometry(0.17, 0.3, 12)
- const body = new THREE.Mesh(shape, new THREE.MeshStandardMaterial({ color, metalness: 0.25, roughness: 0.3,
- emissive: color, emissiveIntensity: 0.28, depthTest: false, depthWrite: false }))
- body.name = 'device-body'
- group.add(body)
- // 图标:贴图来自主图同款合成(异步到达后替换);尖端锚点 = Sprite 底部中心。
- const icon = new THREE.Sprite(new THREE.SpriteMaterial({ transparent: true, depthTest: false, depthWrite: false, sizeAttenuation: true }))
- icon.name = 'device-icon'
- icon.center.set(0.5, 0)
- // 图标挂在设备正上方一个**稳定的世界距离**,必须除掉 group.scale:
- // 否则 group 的 3.5~7 倍缩放会把它顶到设备上方 3~5 个世界单位处
- // (实测 NDC y 达 1.63~1.80,整个图标落在画面上沿之外,拉多远都看不全)。
- icon.position.set(0, ICON_OFFSET_ABOVE_DEVICE / deviceScale, 0)
- icon.renderOrder = 30
- icon.userData.device = device
- icon.visible = false
- group.add(icon)
- // 点击代理:与图标同尺寸的透明平面,专供射线命中。
- // 不用 Sprite 自身做拾取——Sprite 在嵌套缩放下的 raycast 不稳定(实测同一图标
- // 最小用例能命中、放进场景就 miss);代理平面只承担命中,视觉仍由 Sprite 提供。
- const hit = new THREE.Mesh(
- new THREE.PlaneGeometry(1, 1.2566),
- new THREE.MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false, depthTest: false }),
- )
- hit.name = 'device-icon-hit'
- hit.position.copy(icon.position)
- hit.renderOrder = 29
- hit.userData.device = device
- group.add(hit)
- root.add(group)
- }
- return root
- }
- /**
- * Mount a bounded local viewer. The optional rendererFactory is a system-boundary seam
- * for offline tests; production uses WebGLRenderer.
- */
- export function mountPipeEnhancement(host, plan, { rendererFactory = defaultRendererFactory, pixelRatio = 1, onDevicePick = () => {}, onObjectPick = () => {}, iconResolver = defaultDeviceIcon, loadTexture = null, scheduleFrame = null, now = null } = {}) {
- if (!host || !plan || plan.visible !== true || !plan.object) {
- return { status: 'unavailable', sync: () => {}, destroy: () => {}, getState: () => ({ status: 'unavailable' }) }
- }
- const scene = new THREE.Scene()
- scene.background = new THREE.Color(0x031226)
- const camera = new THREE.PerspectiveCamera(36, 1, 0.1, 100)
- camera.position.set(0, 3.8, 7.2)
- camera.lookAt(0, 0, 0)
- scene.add(new THREE.HemisphereLight(0xbde8ff, 0x061127, 2.2))
- const key = new THREE.DirectionalLight(0xffffff, 2.4)
- key.position.set(3, 6, 4)
- scene.add(key)
- const fill = new THREE.DirectionalLight(0x89baff, 1.8)
- fill.position.set(-4, 2, -3)
- scene.add(fill)
- const rim = new THREE.DirectionalLight(0xffe2bb, 2)
- rim.position.set(1, -1, -4)
- scene.add(rim)
- let renderer
- try {
- renderer = rendererFactory({ canvas: host.ownerDocument?.createElement?.('canvas') || null })
- renderer.setPixelRatio?.(pixelRatio)
- renderer.setSize?.(host.clientWidth || 320, host.clientHeight || 220, false)
- if (renderer.domElement && !renderer.domElement.parentNode) host.appendChild(renderer.domElement)
- } catch (error) {
- return { status: 'failed', reason: String(error?.message || error), sync: () => {}, destroy: () => {}, getState: () => ({ status: 'failed', reason: String(error?.message || error) }) }
- }
- let root = null
- let current = plan
- const target = new THREE.Vector3()
- let yaw = 0
- let pitch = Math.atan2(3.8, 7.2)
- let distance = Math.hypot(3.8, 7.2)
- let sceneRadius = 1
- let drag = null
- const canvas = renderer.domElement || host
- let destroyed = false
- const resize = () => {
- if (destroyed) return
- const width = host.clientWidth || 320
- const height = host.clientHeight || 220
- camera.aspect = width / Math.max(1, height)
- camera.updateProjectionMatrix()
- renderer.setSize?.(width, height, false)
- render()
- }
- /**
- * 镜头定位飞行(维护者 2026-10-22:「点击点位后的镜头定位运动效果也需要实现。」)
- *
- * 点击设备时不再瞬移:从当前 `target`/`distance` 在 `FLIGHT_MS` 内缓动到目标,
- * 每帧重绘。缓动用 ease-in-out cubic(两端慢、中间快),与主图相机飞行的观感一致。
- *
- * 两个可注入接缝(`scheduleFrame` / `now`)让脱浏览器回归能逐帧断言「起步不是终点」
- * 与「到期精确到位」,而不是只能验证终态。
- */
- const FLIGHT_MS = 620
- /** 定位构图:图标顶端不超过这个 NDC 高度(1=画面上沿),留出上方空间。 */
- const FOCUS_ICON_TOP_NDC = 0.4
- /** 设备底端不越过这个 NDC 高度(负值=画面下沿),保证设备完整。 */
- const FOCUS_BODY_BOTTOM_NDC = 0.9
- /** 解析距离的安全系数:再多留一点上下文,避免刚好贴边。 */
- const FOCUS_SAFETY = 1.18
- const nowImpl = typeof now === 'function'
- ? now
- : () => (typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now())
- const scheduleFrameImpl = typeof scheduleFrame === 'function'
- ? scheduleFrame
- : (fn) => (typeof requestAnimationFrame === 'function' ? requestAnimationFrame(fn) : setTimeout(fn, 16))
- let flight = null
- const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2)
- const cancelFlight = () => { flight = null }
- const stepFlight = () => {
- if (!flight || destroyed) return
- const elapsed = nowImpl() - flight.startedAt
- const progress = Math.min(1, Math.max(0, elapsed / flight.duration))
- const eased = easeInOutCubic(progress)
- target.lerpVectors(flight.fromTarget, flight.toTarget, eased)
- distance = flight.fromDistance + (flight.toDistance - flight.fromDistance) * eased
- render()
- if (progress >= 1) { flight = null; return }
- scheduleFrameImpl(stepFlight)
- }
- const startFlight = (toTarget, toDistance, duration = FLIGHT_MS) => {
- flight = {
- fromTarget: target.clone(),
- fromDistance: distance,
- toTarget: toTarget.clone(),
- toDistance,
- startedAt: nowImpl(),
- duration: Math.max(1, duration),
- }
- scheduleFrameImpl(stepFlight)
- }
- const render = () => {
- const horizontal = Math.cos(pitch) * distance
- camera.position.set(
- target.x + Math.sin(yaw) * horizontal,
- target.y + Math.sin(pitch) * distance,
- target.z + Math.cos(yaw) * horizontal,
- )
- root?.traverse((node) => {
- if (node.name === 'selected-pipe-outline') node.material.uniforms.resolution.value.set(host.clientWidth || 320, host.clientHeight || 220)
- if (node.name === 'device-icon') {
- root.updateMatrixWorld(true)
- // 尺寸 = 主图 marker 的 draw 像素(含描边余量),按视距换算成固定屏显尺寸,
- // 与主图 billboard 的视觉重量一致;高度按图标自身宽高比。
- const iconWidth = node.userData.iconWidth || 26.7
- const aspect = node.userData.iconAspect || 1.2566
- const world = 2 * camera.position.distanceTo(node.getWorldPosition(new THREE.Vector3()))
- * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * iconWidth / (host.clientHeight || 220)
- const parentScale = Math.max(0.0001, node.parent.getWorldScale(new THREE.Vector3()).x)
- node.scale.set(world / parentScale, (world * aspect) / parentScale, 1)
- // 点击代理跟随图标尺寸,并把自身中心抬到图标可见区域中心(图标锚点在底部)。
- const hit = node.parent.getObjectByName('device-icon-hit')
- if (hit) {
- hit.scale.set(node.scale.x, node.scale.y, 1)
- hit.position.y = node.position.y + node.scale.y / 2
- }
- }
- })
- camera.near = Math.max(0.0001, distance > sceneRadius * 1.05 ? distance - sceneRadius * 1.05 : distance / 1000)
- camera.far = Math.max(camera.near + 1, distance + sceneRadius * 2)
- camera.updateProjectionMatrix()
- camera.lookAt(target)
- renderer.render?.(scene, camera)
- }
- /**
- * 设备图标异步装配:贴图来自主图同款合成(`iconResolver`)。
- * 图标未到达前 Sprite 保持 `visible=false`,避免出现白色占位方块;
- * 到达后写入 `userData.iconWidth/iconAspect` 供 `render` 按屏显尺寸缩放。
- * 场景已销毁/换选(`root` 变化)时丢弃迟到结果。
- */
- let iconEpoch = 0
- const textureLoader = new THREE.TextureLoader()
- /**
- * 贴图加载 seam:生产用 `THREE.TextureLoader`(需要浏览器 Image),
- * 脱浏览器回归可注入同步假加载器,从而离线断言「用的是主图同款图标产物」。
- * 回调签名 `(texture) => void`,失败时调用 `onError()`。
- */
- const loadTextureImpl = typeof loadTexture === 'function'
- ? loadTexture
- : (url, onLoad, onError) => textureLoader.load(url, onLoad, undefined, onError)
- const loadDeviceIcons = () => {
- const epoch = ++iconEpoch
- const sceneRoot = root
- if (!sceneRoot) return
- sceneRoot.traverse((node) => {
- if (node.name !== 'device-icon' || node.material.map) return
- const device = node.userData.device
- if (!device) return
- Promise.resolve()
- .then(() => iconResolver(device))
- .then((icon) => {
- if (destroyed || epoch !== iconEpoch || sceneRoot !== root || !icon?.url) return
- node.userData.iconWidth = Number.isFinite(icon.width) ? icon.width : undefined
- node.userData.iconAspect = Number.isFinite(icon.height) && Number.isFinite(icon.width) && icon.width > 0
- ? icon.height / icon.width
- : undefined
- loadTextureImpl(icon.url, (texture) => {
- if (destroyed || epoch !== iconEpoch || sceneRoot !== root) { texture.dispose?.(); return }
- texture.colorSpace = THREE.SRGBColorSpace
- node.material.map = texture
- node.material.color.set('#ffffff')
- node.material.needsUpdate = true
- node.visible = true
- render()
- }, () => { /* 贴图失败:保持不可见,不画自绘替代品。 */ })
- })
- .catch(() => { /* 合成失败:保持不可见,不画自绘替代品。 */ })
- })
- }
- const sync = (next) => {
- const preserveView = root && current.object.code === next.object.code && current.object.sourceKind === next.object.sourceKind
- current = next
- if (root) {
- scene.remove(root)
- disposeObject(root)
- }
- root = buildNeighborhood(next)
- scene.add(root)
- root.updateMatrixWorld(true)
- const box = new THREE.Box3().setFromObject(root)
- const sphere = box.getBoundingSphere(new THREE.Sphere())
- if (!box.isEmpty()) {
- sceneRadius = Math.max(0.01, sphere.radius)
- if (!preserveView) {
- target.copy(sphere.center)
- const halfFov = Math.atan(Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * Math.min(1, camera.aspect))
- distance = sceneRadius / Math.sin(halfFov) * 1.12
- }
- camera.near = Math.max(0.0001, sceneRadius / 10000)
- camera.far = Math.max(100, sceneRadius * 100)
- camera.updateProjectionMatrix()
- }
- loadDeviceIcons()
- render()
- }
- const detachFocus = attachSceneFocus(host)
- const raycaster = new THREE.Raycaster()
- const hitAt = (x, y) => {
- if (!root || !canvas.getBoundingClientRect || !Number.isFinite(x) || !Number.isFinite(y)) return null
- const rect = canvas.getBoundingClientRect()
- if (!rect.width || !rect.height || x < rect.left || x > rect.left + rect.width || y < rect.top || y > rect.top + rect.height) return null
- camera.updateMatrixWorld()
- root.updateMatrixWorld(true)
- raycaster.setFromCamera(new THREE.Vector2((x - rect.left) / rect.width * 2 - 1, 1 - (y - rect.top) / rect.height * 2), camera)
- return raycaster.intersectObject(root, true)[0] || null
- }
- const detachPick = attachPointPick(canvas, ({ x, y }) => {
- // 必须在本次点击坐标上重新投射射线:不能复用 `onDown` 留下的 raycaster 状态,
- // 否则 pointerdown 未进入画布(或未触发)时拾取会落在上一次的射线上。
- if (!root || !canvas.getBoundingClientRect) return
- const rect = canvas.getBoundingClientRect()
- if (!rect.width || !rect.height) return
- camera.updateMatrixWorld()
- root.updateMatrixWorld(true)
- raycaster.setFromCamera(new THREE.Vector2((x - rect.left) / rect.width * 2 - 1, 1 - (y - rect.top) / rect.height * 2), camera)
- const intersections = raycaster.intersectObject(root, true)
- // 图标点击优先:命中可见图标即派发设备,即使放大后的管壁在它前方
- // (图标是屏幕可见交互层,用户点的是看得见的东西)。
- const iconHit = intersections.find((item) => item.object.name === 'device-icon-hit')
- const hit = iconHit || intersections[0]
- let node = hit?.object
- while (node) {
- if (node.userData.device) { onDevicePick(node.userData.device); return }
- if (node.userData.sourceKind) { onObjectPick({ objectKind: node.userData.sourceKind, code: node.userData.code }); return }
- node = node.parent
- }
- })
- const onDown = (event) => {
- if (drag || (event.button !== 0 && event.button !== 2)) return
- cancelFlight()
- const panDistance = Math.max(0.02, Math.min(distance, hitAt(event.clientX, event.clientY)?.distance ?? distance))
- drag = { button: event.button, id: event.pointerId, x: event.clientX, y: event.clientY, panDistance }
- event.preventDefault?.()
- try { canvas.setPointerCapture?.(event.pointerId) } catch { /* 合成事件可能没有可捕获指针。 */ }
- }
- const onMove = (event) => {
- if (!drag || event.pointerId !== drag.id) return
- const dx = event.clientX - drag.x
- const dy = event.clientY - drag.y
- if (drag.button === 0) {
- // 将像素位移换算为目标平面距离,保持“抓住场景拖动”的方向和速度。
- const unitsPerPixel = 2 * Math.min(distance, drag.panDistance) * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) / (host.clientHeight || 220)
- const right = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion)
- const up = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion)
- target.addScaledVector(right, -dx * unitsPerPixel).addScaledVector(up, dy * unitsPerPixel)
- } else {
- yaw -= dx * 0.01
- pitch = Math.max(-1.4, Math.min(1.4, pitch + dy * 0.008))
- }
- drag.x = event.clientX
- drag.y = event.clientY
- render()
- }
- const onUp = (event) => {
- if (!drag || (event?.pointerId !== undefined && event.pointerId !== drag.id)) return
- const id = drag.id
- drag = null
- try { canvas.releasePointerCapture?.(id) } catch { /* 指针可能已由浏览器释放。 */ }
- }
- const onLeave = (event) => {
- if (!canvas.hasPointerCapture?.(event.pointerId)) onUp(event)
- }
- const onWheel = (event) => {
- event.preventDefault?.()
- cancelFlight()
- const hit = hitAt(event.clientX, event.clientY)
- const factor = Math.exp(Math.max(-1000, Math.min(1000, event.deltaY)) * 0.001)
- const limit = Math.max(sceneRadius * 50, 10)
- if (hit) {
- const forward = camera.getWorldDirection(new THREE.Vector3())
- const nextDistance = Math.max(0.02, Math.min(limit, hit.distance * factor))
- const nextPosition = camera.position.clone().addScaledVector(raycaster.ray.direction, hit.distance - nextDistance)
- distance = nextDistance
- target.copy(nextPosition).addScaledVector(forward, distance)
- } else distance = Math.max(0.02, Math.min(limit, distance * factor))
- render()
- }
- canvas.addEventListener?.('pointerdown', onDown)
- canvas.addEventListener?.('pointermove', onMove)
- canvas.addEventListener?.('pointerup', onUp)
- canvas.addEventListener?.('pointercancel', onUp)
- canvas.addEventListener?.('lostpointercapture', onUp)
- canvas.addEventListener?.('pointerleave', onLeave)
- canvas.addEventListener?.('wheel', onWheel, { passive: false })
- resize()
- sync(plan)
- const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null
- observer?.observe(host)
- return {
- status: 'ready',
- title: enhancementLabel(plan.object.sourceKind),
- sync(next) { if (!destroyed && next?.visible && next.object) sync(next) },
- resize,
- focusDevice(code) {
- if (destroyed) return false
- const device = root?.getObjectByName(`device:${code}`)
- if (!device) return false
- // 定位目标取**稳定几何**(设备主体/支杆),不能用含图标的整体包围盒:
- // 图标按屏幕像素恒定尺寸缩放,飞行途中会变大变小,用整体盒算中心会让镜头「飘」。
- const anchor = device.getObjectByName('device-body') || device
- const bounds = new THREE.Box3().setFromObject(anchor).getBoundingSphere(new THREE.Sphere())
- /**
- * 终点距离按「**设备与图标都要完整可见**」解析求出,不再用固定倍率猜。
- *
- * 维护者 2026-10-23:「还需要拉远一点,需要能展示设备及点位图标的全貌。」
- * 图标是**屏幕恒定像素**的(约 33px 高),头顶在设备上方 `ICON_OFFSET_ABOVE_DEVICE`;
- * 只按设备包围球算距离会让图标顶出画面上沿(实测 NDC y 曾达 1.63~1.80)。
- *
- * 设 tanHalf=tan(fov/2)、H=视口高、iconPx=图标屏显高、o=图标偏移、r=设备半径:
- * 图标顶端 NDC ≈ (o + 2·d·tanHalf·iconPx/H) / (d·tanHalf) ≤ ICON_TOP_NDC
- * → d ≥ o / (tanHalf · (ICON_TOP_NDC − 2·iconPx/H))
- * 设备底端 NDC ≈ r / (d·tanHalf) ≤ BODY_BOTTOM_NDC → d ≥ r / (BODY_BOTTOM_NDC · tanHalf)
- * 取两者较大值再乘安全系数。这样任意视口尺寸都能适配,不是写死的倍数。
- */
- const tanHalf = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2))
- const viewHeight = host.clientHeight || 220
- const iconNode = device.getObjectByName('device-icon')
- const iconWidthPx = iconNode?.userData?.iconWidth || 26.7
- const iconAspect = iconNode?.userData?.iconAspect || 1.2566
- const iconPx = iconWidthPx * iconAspect
- const iconSpan = 2 * iconPx / viewHeight
- const distanceForIcon = ICON_OFFSET_ABOVE_DEVICE / Math.max(0.01, tanHalf * (FOCUS_ICON_TOP_NDC - iconSpan))
- const distanceForBody = bounds.radius / (FOCUS_BODY_BOTTOM_NDC * tanHalf)
- const toDistance = Math.max(0.8, Math.max(distanceForIcon, distanceForBody) * FOCUS_SAFETY)
- // 平滑飞行定位(不再瞬移);返回 true 表示已受理,飞行在后续帧推进。
- startFlight(bounds.center, toDistance)
- return true
- },
- getState: () => ({ status: destroyed ? 'destroyed' : 'ready', code: current.object.code, title: enhancementLabel(current.object.sourceKind) }),
- destroy() {
- if (destroyed) return
- destroyed = true
- cancelFlight()
- onUp()
- observer?.disconnect()
- detachFocus()
- detachPick()
- canvas.removeEventListener?.('pointerdown', onDown)
- canvas.removeEventListener?.('pointermove', onMove)
- canvas.removeEventListener?.('pointerup', onUp)
- canvas.removeEventListener?.('pointercancel', onUp)
- canvas.removeEventListener?.('lostpointercapture', onUp)
- canvas.removeEventListener?.('pointerleave', onLeave)
- canvas.removeEventListener?.('wheel', onWheel)
- if (root) disposeObject(root)
- renderer.dispose?.()
- if (renderer.domElement?.parentNode === host) host.removeChild(renderer.domElement)
- },
- }
- }
|