threePipeEnhancement.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /** Three.js adapter for a selected object and its bounded local underground context. */
  2. import * as THREE from 'three'
  3. import { enhancementLabel } from '../domain/pipeEnhancement.js'
  4. import { displayPipeDiameter, PIPE_PALETTE } from '../domain/pipeVisual.js'
  5. import { manholeModelMetrics } from '../domain/manholeModel.js'
  6. import { attachSceneFocus } from './sceneInputFocus.js'
  7. import { addDetailedPipeSegment } from './pipeDetailGeometry.js'
  8. import { attachPointPick } from './pointPick.js'
  9. import { pipeSurfaceMaterial, outlineSelectedPipe } from './pipeSurfaceMaterial.js'
  10. import { sourceDiameterM, pipeSurface } from '../domain/pipePhysical.js'
  11. import { planMarker } from '../domain/markerPlan.js'
  12. import { deviceVisualForStatus } from '../domain/deviceStatus.js'
  13. import { renderMarker } from './markerAssets.js'
  14. /**
  15. * 状态色键兜底表(与 `mapService.toneColors()` 同值、与 `styles/tokens.css` 同值)。
  16. * 色值真源仍是 tokens.css;本表只在读不到计算样式时兜底(脱浏览器回归、样式未挂载)。
  17. * 刻意不与 mapService 共享常量:那两个文件带有其它在制品改动,本票不触碰它们。
  18. */
  19. /** 设备图标相对设备主体的世界高度偏移(不受 group 缩放影响)。 */
  20. const ICON_OFFSET_ABOVE_DEVICE = 0.62
  21. const TONE_FALLBACK = Object.freeze({
  22. lv1: '#ff3b52',
  23. lv2: '#ffb020',
  24. lv3: '#01abea',
  25. lv4: '#27d17a',
  26. neutral: '#5680b0',
  27. 'point-offline': '#94a3b8',
  28. 'point-unknown': '#a970ff',
  29. 'point-unassociated': '#a3e635',
  30. })
  31. /**
  32. * 状态色键 → 十六进制。与 `mapService` 的 `toneColors()` 同一口径:
  33. * 色值唯一真源是 `styles/tokens.css`,这里从 `.cockpit-shell` 计算样式读,
  34. * 脱浏览器(Node 回归)读不到时用 `markerPlan.TONE_FALLBACK` 同值兜底。
  35. */
  36. function toneHex(tone) {
  37. const fallback = TONE_FALLBACK[tone] || TONE_FALLBACK.neutral
  38. if (typeof document === 'undefined' || !document.querySelector || typeof getComputedStyle !== 'function') return fallback
  39. const shell = document.querySelector('.cockpit-shell')
  40. if (!shell) return fallback
  41. const value = getComputedStyle(shell).getPropertyValue(`--${tone}`)
  42. return value && value.trim() ? value.trim() : fallback
  43. }
  44. /**
  45. * 设备 → 主图 marker 合成计划(**语义同步的唯一裁决点**)。
  46. *
  47. * 维护者 2026-10-22:「已确认使用了场景同款设备图标,但是颜色状态及中间的类型图标还是没有同步。」
  48. * 两处不一致的根因都在这里,必须与主图**逐项对齐**:
  49. *
  50. * 1. **颜色**:主图给 `planMarker` 传的是**设备状态表**的色键
  51. * (`deviceVisualForStatus()`:ALARM→lv1 / WARNING→lv2 / WORK_ORDER→lv3 /
  52. * NORMAL→lv4 / OFFLINE→`point-offline` / 未知→`point-unknown`)。
  53. * 不传 tone 会落到 `markerPlan` 的**点位聚合态**默认表 —— 那里 OFFLINE/UNKNOWN
  54. * 是 `neutral`,于是场景里的离线设备与主图不同色。所以必须显式传 `tone`。
  55. * 2. **类型图标**:内层图标按 `industry` 选(gas/water/drainage/manhole)。
  56. * 设备卡本身常无 `industry`,主图的规则是**继承所属点位行业**;设备侧已在
  57. * `domain/enhancementDevices.js` 按同一规则落好(`device.industry || point.industry`),
  58. * 这里直接消费,不再二次推导。
  59. * 3. **未关联设备**:主图对「没有监测点归属」的设备走镂空母版(业务异常时不降饱和)。
  60. * 判据就是有没有 `pointCode` —— 与主图 `unassociated` 同一含义。
  61. */
  62. export function deviceMarkerPlan(device) {
  63. const visual = deviceVisualForStatus(device.status)
  64. return planMarker({
  65. kind: 'monitoring-device',
  66. status: device.status,
  67. industry: device.industry || '',
  68. tone: visual.tone,
  69. unassociated: !device.pointCode,
  70. })
  71. }
  72. /**
  73. * 设备图标的**唯一来源**:复用主图 marker 的合成链路(`planMarker` + `renderMarker`),
  74. * 因此地下管线详情视图里的设备图标与一张图上的**同款**,不是另画一套。
  75. * 母版形状、状态色、内层行业图标、白描边、尺寸全部由 `deviceMarkerPlan` 决定。
  76. */
  77. async function defaultDeviceIcon(device) {
  78. const plan = deviceMarkerPlan(device)
  79. const url = await renderMarker(plan, { tintHex: toneHex(plan.tint) })
  80. return { url, width: plan.draw.width, height: plan.draw.height, tone: plan.tint }
  81. }
  82. function defaultRendererFactory({ canvas }) {
  83. return new THREE.WebGLRenderer({ canvas, alpha: true, antialias: true })
  84. }
  85. function project([lon, lat], center, scale) {
  86. const cosLat = Math.cos((center[1] * Math.PI) / 180)
  87. return new THREE.Vector3(
  88. (lon - center[0]) * 111320 * cosLat * scale,
  89. 0,
  90. -(lat - center[1]) * 111320 * scale,
  91. )
  92. }
  93. function disposeObject(root) {
  94. const resources = new Set()
  95. root.traverse((node) => {
  96. if (node.geometry) resources.add(node.geometry)
  97. if (node.material) for (const value of [].concat(node.material)) {
  98. resources.add(value)
  99. if (value.map) resources.add(value.map)
  100. }
  101. })
  102. for (const resource of resources) resource.dispose()
  103. }
  104. function material(color, opacity = 1) {
  105. return new THREE.MeshStandardMaterial({ color, roughness: 0.62, metalness: 0.18, transparent: opacity < 1, opacity })
  106. }
  107. function buildObject(plan, frame = null) {
  108. const object = plan.object
  109. const root = new THREE.Group()
  110. root.name = `pipe-enhancement:${object.code}`
  111. const center = object.renderKind === 'pipe'
  112. ? [0, 1].map((axis) => {
  113. const [min, max] = object.path.reduce(([lo, hi], point) =>
  114. [Math.min(lo, point[axis]), Math.max(hi, point[axis])], [Infinity, -Infinity])
  115. return (min + max) / 2
  116. })
  117. : object.position || object.path[0]
  118. const scale = 1
  119. const points = object.path.map((point) => project(point, frame?.center || center, scale))
  120. const color = (PIPE_PALETTE[object.colorKey] || PIPE_PALETTE.UNKNOWN).color
  121. if (object.renderKind === 'pipe') {
  122. const diameterM = object.displayDiameterM ?? displayPipeDiameter(object.diameterM ?? sourceDiameterM(object.diameter))
  123. const surface = object.surface || pipeSurface(object.material)
  124. if (diameterM === null) {
  125. const guide = new THREE.Line(new THREE.BufferGeometry().setFromPoints(points), new THREE.LineDashedMaterial({ color, dashSize: 1, gapSize: 0.6 }))
  126. guide.name = 'missing-diameter-guide'
  127. guide.computeLineDistances()
  128. root.add(guide)
  129. }
  130. for (let i = 1; diameterM !== null && i < points.length; i += 1) {
  131. if (object.primary === false) {
  132. const delta = new THREE.Vector3().subVectors(points[i], points[i - 1])
  133. const length = delta.length()
  134. if (length < 0.000001) continue
  135. const mesh = new THREE.Mesh(new THREE.CylinderGeometry(diameterM / 2, diameterM / 2, length, 16, 1, true), pipeSurfaceMaterial(color, surface))
  136. mesh.name = 'neighbor-pipe-wall'
  137. mesh.position.copy(points[i - 1]).add(points[i]).multiplyScalar(0.5)
  138. mesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), delta.normalize())
  139. root.add(mesh)
  140. } else addDetailedPipeSegment(root, points[i - 1], points[i], color, {
  141. startFlange: i === 1,
  142. endFlange: i === points.length - 1,
  143. radius: diameterM / 2,
  144. surface,
  145. })
  146. }
  147. } else if (object.renderKind === 'manhole') {
  148. // 票 04:尺寸与 Y 偏移全部来自 domain/manholeModel.js 的单源,
  149. // 并与管线共用同一个显示倍率(PIPE_DISPLAY.diameterScale),不再手写第二组米数。
  150. const model = manholeModelMetrics()
  151. 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),
  152. new THREE.MeshStandardMaterial({ color: '#718093', roughness: 0.9, side: THREE.DoubleSide }))
  153. shell.name = 'manhole-shaft'
  154. shell.position.copy(points[0])
  155. shell.position.y = model.shaft.centerY
  156. root.add(shell)
  157. const base = new THREE.Mesh(new THREE.CylinderGeometry(model.base.radius, model.base.radius, model.base.height, 32), material('#53616f'))
  158. base.position.copy(points[0]); base.position.y = model.base.centerY
  159. root.add(base)
  160. const cover = new THREE.Mesh(new THREE.CylinderGeometry(model.cover.radius, model.cover.radius, model.cover.height, 32), material(color))
  161. cover.name = 'manhole-cover'
  162. cover.position.copy(points[0]); cover.position.y = model.cover.centerY
  163. cover.rotation.x = model.cover.tilt
  164. root.add(cover)
  165. } else {
  166. const shape = object.renderKind === 'valve'
  167. ? new THREE.CylinderGeometry(0.48, 0.48, 0.16, 24)
  168. : object.renderKind === 'elbow'
  169. ? new THREE.TorusGeometry(0.48, 0.15, 12, 24, Math.PI)
  170. : object.renderKind === 'branch' || object.renderKind === 'cross'
  171. ? new THREE.ConeGeometry(0.55, 0.72, object.renderKind === 'cross' ? 4 : 8)
  172. : new THREE.BoxGeometry(0.72, 0.72, 0.72)
  173. const mesh = new THREE.Mesh(shape, material(color))
  174. mesh.position.copy(points[0])
  175. if (object.renderKind === 'elbow') mesh.rotation.y = Math.PI / 2
  176. root.add(mesh)
  177. }
  178. if (object.primary !== false) outlineSelectedPipe(root)
  179. root.position.y = frame ? ((frame.depthM || 0) - (object.depthM || 0)) * scale : 0
  180. root.userData = { code: object.code, sourceKind: object.sourceKind, primary: object.primary !== false, clipped: object.clipped === true }
  181. return root
  182. }
  183. function buildNeighborhood(plan) {
  184. if ((!plan.objects || plan.objects.length <= 1) && !plan.devices?.length) return buildObject(plan)
  185. const objects = plan.objects || [{ ...plan.object, primary: true, depthM: 0 }]
  186. const path = plan.object.path
  187. const center = [0, 1].map((axis) => {
  188. const [min, max] = path.reduce(([lo, hi], p) => [Math.min(lo, p[axis]), Math.max(hi, p[axis])], [Infinity, -Infinity])
  189. return (min + max) / 2
  190. })
  191. const frame = { center, scale: 1, depthM: objects[0].depthM }
  192. const root = new THREE.Group()
  193. root.name = `pipe-enhancement:${plan.object.code}`
  194. for (const object of objects) root.add(buildObject({ object }, frame))
  195. for (const device of plan.devices || []) {
  196. const group = new THREE.Group()
  197. group.name = `device:${device.code}`
  198. group.userData.device = device
  199. group.position.copy(project(device.position, center, frame.scale))
  200. const radius = device.pipeDisplayRadiusM || 0
  201. const deviceScale = Math.max(3.5, Math.min(7, radius * 2))
  202. group.scale.setScalar(deviceScale)
  203. group.renderOrder = 20
  204. group.position.y = ((frame.depthM || 0) - device.depthM) * frame.scale + Math.max(radius * 1.06, device.mountHeightM || 0) + deviceScale * 0.35
  205. const stem = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.035, 0.25, 8), material('#b9c5d0'))
  206. stem.position.y = -0.16
  207. stem.renderOrder = 21
  208. stem.material.depthTest = false
  209. stem.material.depthWrite = false
  210. group.add(stem)
  211. const color = (PIPE_PALETTE[device.colorKey] || PIPE_PALETTE.UNKNOWN).color
  212. const shape = device.industry === 'GAS' ? new THREE.BoxGeometry(0.22, 0.32, 0.18)
  213. : device.industry === 'WATER_SUPPLY' ? new THREE.CylinderGeometry(0.15, 0.15, 0.28, 12)
  214. : device.industry === 'MANHOLE' ? new THREE.BoxGeometry(0.3, 0.1, 0.22)
  215. : new THREE.ConeGeometry(0.17, 0.3, 12)
  216. const body = new THREE.Mesh(shape, new THREE.MeshStandardMaterial({ color, metalness: 0.25, roughness: 0.3,
  217. emissive: color, emissiveIntensity: 0.28, depthTest: false, depthWrite: false }))
  218. body.name = 'device-body'
  219. group.add(body)
  220. // 图标:贴图来自主图同款合成(异步到达后替换);尖端锚点 = Sprite 底部中心。
  221. const icon = new THREE.Sprite(new THREE.SpriteMaterial({ transparent: true, depthTest: false, depthWrite: false, sizeAttenuation: true }))
  222. icon.name = 'device-icon'
  223. icon.center.set(0.5, 0)
  224. // 图标挂在设备正上方一个**稳定的世界距离**,必须除掉 group.scale:
  225. // 否则 group 的 3.5~7 倍缩放会把它顶到设备上方 3~5 个世界单位处
  226. // (实测 NDC y 达 1.63~1.80,整个图标落在画面上沿之外,拉多远都看不全)。
  227. icon.position.set(0, ICON_OFFSET_ABOVE_DEVICE / deviceScale, 0)
  228. icon.renderOrder = 30
  229. icon.userData.device = device
  230. icon.visible = false
  231. group.add(icon)
  232. // 点击代理:与图标同尺寸的透明平面,专供射线命中。
  233. // 不用 Sprite 自身做拾取——Sprite 在嵌套缩放下的 raycast 不稳定(实测同一图标
  234. // 最小用例能命中、放进场景就 miss);代理平面只承担命中,视觉仍由 Sprite 提供。
  235. const hit = new THREE.Mesh(
  236. new THREE.PlaneGeometry(1, 1.2566),
  237. new THREE.MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false, depthTest: false }),
  238. )
  239. hit.name = 'device-icon-hit'
  240. hit.position.copy(icon.position)
  241. hit.renderOrder = 29
  242. hit.userData.device = device
  243. group.add(hit)
  244. root.add(group)
  245. }
  246. return root
  247. }
  248. /**
  249. * Mount a bounded local viewer. The optional rendererFactory is a system-boundary seam
  250. * for offline tests; production uses WebGLRenderer.
  251. */
  252. export function mountPipeEnhancement(host, plan, { rendererFactory = defaultRendererFactory, pixelRatio = 1, onDevicePick = () => {}, onObjectPick = () => {}, iconResolver = defaultDeviceIcon, loadTexture = null, scheduleFrame = null, now = null } = {}) {
  253. if (!host || !plan || plan.visible !== true || !plan.object) {
  254. return { status: 'unavailable', sync: () => {}, destroy: () => {}, getState: () => ({ status: 'unavailable' }) }
  255. }
  256. const scene = new THREE.Scene()
  257. scene.background = new THREE.Color(0x031226)
  258. const camera = new THREE.PerspectiveCamera(36, 1, 0.1, 100)
  259. camera.position.set(0, 3.8, 7.2)
  260. camera.lookAt(0, 0, 0)
  261. scene.add(new THREE.HemisphereLight(0xbde8ff, 0x061127, 2.2))
  262. const key = new THREE.DirectionalLight(0xffffff, 2.4)
  263. key.position.set(3, 6, 4)
  264. scene.add(key)
  265. const fill = new THREE.DirectionalLight(0x89baff, 1.8)
  266. fill.position.set(-4, 2, -3)
  267. scene.add(fill)
  268. const rim = new THREE.DirectionalLight(0xffe2bb, 2)
  269. rim.position.set(1, -1, -4)
  270. scene.add(rim)
  271. let renderer
  272. try {
  273. renderer = rendererFactory({ canvas: host.ownerDocument?.createElement?.('canvas') || null })
  274. renderer.setPixelRatio?.(pixelRatio)
  275. renderer.setSize?.(host.clientWidth || 320, host.clientHeight || 220, false)
  276. if (renderer.domElement && !renderer.domElement.parentNode) host.appendChild(renderer.domElement)
  277. } catch (error) {
  278. return { status: 'failed', reason: String(error?.message || error), sync: () => {}, destroy: () => {}, getState: () => ({ status: 'failed', reason: String(error?.message || error) }) }
  279. }
  280. let root = null
  281. let current = plan
  282. const target = new THREE.Vector3()
  283. let yaw = 0
  284. let pitch = Math.atan2(3.8, 7.2)
  285. let distance = Math.hypot(3.8, 7.2)
  286. let sceneRadius = 1
  287. let drag = null
  288. const canvas = renderer.domElement || host
  289. let destroyed = false
  290. const resize = () => {
  291. if (destroyed) return
  292. const width = host.clientWidth || 320
  293. const height = host.clientHeight || 220
  294. camera.aspect = width / Math.max(1, height)
  295. camera.updateProjectionMatrix()
  296. renderer.setSize?.(width, height, false)
  297. render()
  298. }
  299. /**
  300. * 镜头定位飞行(维护者 2026-10-22:「点击点位后的镜头定位运动效果也需要实现。」)
  301. *
  302. * 点击设备时不再瞬移:从当前 `target`/`distance` 在 `FLIGHT_MS` 内缓动到目标,
  303. * 每帧重绘。缓动用 ease-in-out cubic(两端慢、中间快),与主图相机飞行的观感一致。
  304. *
  305. * 两个可注入接缝(`scheduleFrame` / `now`)让脱浏览器回归能逐帧断言「起步不是终点」
  306. * 与「到期精确到位」,而不是只能验证终态。
  307. */
  308. const FLIGHT_MS = 620
  309. /** 定位构图:图标顶端不超过这个 NDC 高度(1=画面上沿),留出上方空间。 */
  310. const FOCUS_ICON_TOP_NDC = 0.4
  311. /** 设备底端不越过这个 NDC 高度(负值=画面下沿),保证设备完整。 */
  312. const FOCUS_BODY_BOTTOM_NDC = 0.9
  313. /** 解析距离的安全系数:再多留一点上下文,避免刚好贴边。 */
  314. const FOCUS_SAFETY = 1.18
  315. const nowImpl = typeof now === 'function'
  316. ? now
  317. : () => (typeof performance !== 'undefined' && typeof performance.now === 'function' ? performance.now() : Date.now())
  318. const scheduleFrameImpl = typeof scheduleFrame === 'function'
  319. ? scheduleFrame
  320. : (fn) => (typeof requestAnimationFrame === 'function' ? requestAnimationFrame(fn) : setTimeout(fn, 16))
  321. let flight = null
  322. const easeInOutCubic = (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2)
  323. const cancelFlight = () => { flight = null }
  324. const stepFlight = () => {
  325. if (!flight || destroyed) return
  326. const elapsed = nowImpl() - flight.startedAt
  327. const progress = Math.min(1, Math.max(0, elapsed / flight.duration))
  328. const eased = easeInOutCubic(progress)
  329. target.lerpVectors(flight.fromTarget, flight.toTarget, eased)
  330. distance = flight.fromDistance + (flight.toDistance - flight.fromDistance) * eased
  331. render()
  332. if (progress >= 1) { flight = null; return }
  333. scheduleFrameImpl(stepFlight)
  334. }
  335. const startFlight = (toTarget, toDistance, duration = FLIGHT_MS) => {
  336. flight = {
  337. fromTarget: target.clone(),
  338. fromDistance: distance,
  339. toTarget: toTarget.clone(),
  340. toDistance,
  341. startedAt: nowImpl(),
  342. duration: Math.max(1, duration),
  343. }
  344. scheduleFrameImpl(stepFlight)
  345. }
  346. const render = () => {
  347. const horizontal = Math.cos(pitch) * distance
  348. camera.position.set(
  349. target.x + Math.sin(yaw) * horizontal,
  350. target.y + Math.sin(pitch) * distance,
  351. target.z + Math.cos(yaw) * horizontal,
  352. )
  353. root?.traverse((node) => {
  354. if (node.name === 'selected-pipe-outline') node.material.uniforms.resolution.value.set(host.clientWidth || 320, host.clientHeight || 220)
  355. if (node.name === 'device-icon') {
  356. root.updateMatrixWorld(true)
  357. // 尺寸 = 主图 marker 的 draw 像素(含描边余量),按视距换算成固定屏显尺寸,
  358. // 与主图 billboard 的视觉重量一致;高度按图标自身宽高比。
  359. const iconWidth = node.userData.iconWidth || 26.7
  360. const aspect = node.userData.iconAspect || 1.2566
  361. const world = 2 * camera.position.distanceTo(node.getWorldPosition(new THREE.Vector3()))
  362. * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * iconWidth / (host.clientHeight || 220)
  363. const parentScale = Math.max(0.0001, node.parent.getWorldScale(new THREE.Vector3()).x)
  364. node.scale.set(world / parentScale, (world * aspect) / parentScale, 1)
  365. // 点击代理跟随图标尺寸,并把自身中心抬到图标可见区域中心(图标锚点在底部)。
  366. const hit = node.parent.getObjectByName('device-icon-hit')
  367. if (hit) {
  368. hit.scale.set(node.scale.x, node.scale.y, 1)
  369. hit.position.y = node.position.y + node.scale.y / 2
  370. }
  371. }
  372. })
  373. camera.near = Math.max(0.0001, distance > sceneRadius * 1.05 ? distance - sceneRadius * 1.05 : distance / 1000)
  374. camera.far = Math.max(camera.near + 1, distance + sceneRadius * 2)
  375. camera.updateProjectionMatrix()
  376. camera.lookAt(target)
  377. renderer.render?.(scene, camera)
  378. }
  379. /**
  380. * 设备图标异步装配:贴图来自主图同款合成(`iconResolver`)。
  381. * 图标未到达前 Sprite 保持 `visible=false`,避免出现白色占位方块;
  382. * 到达后写入 `userData.iconWidth/iconAspect` 供 `render` 按屏显尺寸缩放。
  383. * 场景已销毁/换选(`root` 变化)时丢弃迟到结果。
  384. */
  385. let iconEpoch = 0
  386. const textureLoader = new THREE.TextureLoader()
  387. /**
  388. * 贴图加载 seam:生产用 `THREE.TextureLoader`(需要浏览器 Image),
  389. * 脱浏览器回归可注入同步假加载器,从而离线断言「用的是主图同款图标产物」。
  390. * 回调签名 `(texture) => void`,失败时调用 `onError()`。
  391. */
  392. const loadTextureImpl = typeof loadTexture === 'function'
  393. ? loadTexture
  394. : (url, onLoad, onError) => textureLoader.load(url, onLoad, undefined, onError)
  395. const loadDeviceIcons = () => {
  396. const epoch = ++iconEpoch
  397. const sceneRoot = root
  398. if (!sceneRoot) return
  399. sceneRoot.traverse((node) => {
  400. if (node.name !== 'device-icon' || node.material.map) return
  401. const device = node.userData.device
  402. if (!device) return
  403. Promise.resolve()
  404. .then(() => iconResolver(device))
  405. .then((icon) => {
  406. if (destroyed || epoch !== iconEpoch || sceneRoot !== root || !icon?.url) return
  407. node.userData.iconWidth = Number.isFinite(icon.width) ? icon.width : undefined
  408. node.userData.iconAspect = Number.isFinite(icon.height) && Number.isFinite(icon.width) && icon.width > 0
  409. ? icon.height / icon.width
  410. : undefined
  411. loadTextureImpl(icon.url, (texture) => {
  412. if (destroyed || epoch !== iconEpoch || sceneRoot !== root) { texture.dispose?.(); return }
  413. texture.colorSpace = THREE.SRGBColorSpace
  414. node.material.map = texture
  415. node.material.color.set('#ffffff')
  416. node.material.needsUpdate = true
  417. node.visible = true
  418. render()
  419. }, () => { /* 贴图失败:保持不可见,不画自绘替代品。 */ })
  420. })
  421. .catch(() => { /* 合成失败:保持不可见,不画自绘替代品。 */ })
  422. })
  423. }
  424. const sync = (next) => {
  425. const preserveView = root && current.object.code === next.object.code && current.object.sourceKind === next.object.sourceKind
  426. current = next
  427. if (root) {
  428. scene.remove(root)
  429. disposeObject(root)
  430. }
  431. root = buildNeighborhood(next)
  432. scene.add(root)
  433. root.updateMatrixWorld(true)
  434. const box = new THREE.Box3().setFromObject(root)
  435. const sphere = box.getBoundingSphere(new THREE.Sphere())
  436. if (!box.isEmpty()) {
  437. sceneRadius = Math.max(0.01, sphere.radius)
  438. if (!preserveView) {
  439. target.copy(sphere.center)
  440. const halfFov = Math.atan(Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) * Math.min(1, camera.aspect))
  441. distance = sceneRadius / Math.sin(halfFov) * 1.12
  442. }
  443. camera.near = Math.max(0.0001, sceneRadius / 10000)
  444. camera.far = Math.max(100, sceneRadius * 100)
  445. camera.updateProjectionMatrix()
  446. }
  447. loadDeviceIcons()
  448. render()
  449. }
  450. const detachFocus = attachSceneFocus(host)
  451. const raycaster = new THREE.Raycaster()
  452. const hitAt = (x, y) => {
  453. if (!root || !canvas.getBoundingClientRect || !Number.isFinite(x) || !Number.isFinite(y)) return null
  454. const rect = canvas.getBoundingClientRect()
  455. if (!rect.width || !rect.height || x < rect.left || x > rect.left + rect.width || y < rect.top || y > rect.top + rect.height) return null
  456. camera.updateMatrixWorld()
  457. root.updateMatrixWorld(true)
  458. raycaster.setFromCamera(new THREE.Vector2((x - rect.left) / rect.width * 2 - 1, 1 - (y - rect.top) / rect.height * 2), camera)
  459. return raycaster.intersectObject(root, true)[0] || null
  460. }
  461. const detachPick = attachPointPick(canvas, ({ x, y }) => {
  462. // 必须在本次点击坐标上重新投射射线:不能复用 `onDown` 留下的 raycaster 状态,
  463. // 否则 pointerdown 未进入画布(或未触发)时拾取会落在上一次的射线上。
  464. if (!root || !canvas.getBoundingClientRect) return
  465. const rect = canvas.getBoundingClientRect()
  466. if (!rect.width || !rect.height) return
  467. camera.updateMatrixWorld()
  468. root.updateMatrixWorld(true)
  469. raycaster.setFromCamera(new THREE.Vector2((x - rect.left) / rect.width * 2 - 1, 1 - (y - rect.top) / rect.height * 2), camera)
  470. const intersections = raycaster.intersectObject(root, true)
  471. // 图标点击优先:命中可见图标即派发设备,即使放大后的管壁在它前方
  472. // (图标是屏幕可见交互层,用户点的是看得见的东西)。
  473. const iconHit = intersections.find((item) => item.object.name === 'device-icon-hit')
  474. const hit = iconHit || intersections[0]
  475. let node = hit?.object
  476. while (node) {
  477. if (node.userData.device) { onDevicePick(node.userData.device); return }
  478. if (node.userData.sourceKind) { onObjectPick({ objectKind: node.userData.sourceKind, code: node.userData.code }); return }
  479. node = node.parent
  480. }
  481. })
  482. const onDown = (event) => {
  483. if (drag || (event.button !== 0 && event.button !== 2)) return
  484. cancelFlight()
  485. const panDistance = Math.max(0.02, Math.min(distance, hitAt(event.clientX, event.clientY)?.distance ?? distance))
  486. drag = { button: event.button, id: event.pointerId, x: event.clientX, y: event.clientY, panDistance }
  487. event.preventDefault?.()
  488. try { canvas.setPointerCapture?.(event.pointerId) } catch { /* 合成事件可能没有可捕获指针。 */ }
  489. }
  490. const onMove = (event) => {
  491. if (!drag || event.pointerId !== drag.id) return
  492. const dx = event.clientX - drag.x
  493. const dy = event.clientY - drag.y
  494. if (drag.button === 0) {
  495. // 将像素位移换算为目标平面距离,保持“抓住场景拖动”的方向和速度。
  496. const unitsPerPixel = 2 * Math.min(distance, drag.panDistance) * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) / (host.clientHeight || 220)
  497. const right = new THREE.Vector3(1, 0, 0).applyQuaternion(camera.quaternion)
  498. const up = new THREE.Vector3(0, 1, 0).applyQuaternion(camera.quaternion)
  499. target.addScaledVector(right, -dx * unitsPerPixel).addScaledVector(up, dy * unitsPerPixel)
  500. } else {
  501. yaw -= dx * 0.01
  502. pitch = Math.max(-1.4, Math.min(1.4, pitch + dy * 0.008))
  503. }
  504. drag.x = event.clientX
  505. drag.y = event.clientY
  506. render()
  507. }
  508. const onUp = (event) => {
  509. if (!drag || (event?.pointerId !== undefined && event.pointerId !== drag.id)) return
  510. const id = drag.id
  511. drag = null
  512. try { canvas.releasePointerCapture?.(id) } catch { /* 指针可能已由浏览器释放。 */ }
  513. }
  514. const onLeave = (event) => {
  515. if (!canvas.hasPointerCapture?.(event.pointerId)) onUp(event)
  516. }
  517. const onWheel = (event) => {
  518. event.preventDefault?.()
  519. cancelFlight()
  520. const hit = hitAt(event.clientX, event.clientY)
  521. const factor = Math.exp(Math.max(-1000, Math.min(1000, event.deltaY)) * 0.001)
  522. const limit = Math.max(sceneRadius * 50, 10)
  523. if (hit) {
  524. const forward = camera.getWorldDirection(new THREE.Vector3())
  525. const nextDistance = Math.max(0.02, Math.min(limit, hit.distance * factor))
  526. const nextPosition = camera.position.clone().addScaledVector(raycaster.ray.direction, hit.distance - nextDistance)
  527. distance = nextDistance
  528. target.copy(nextPosition).addScaledVector(forward, distance)
  529. } else distance = Math.max(0.02, Math.min(limit, distance * factor))
  530. render()
  531. }
  532. canvas.addEventListener?.('pointerdown', onDown)
  533. canvas.addEventListener?.('pointermove', onMove)
  534. canvas.addEventListener?.('pointerup', onUp)
  535. canvas.addEventListener?.('pointercancel', onUp)
  536. canvas.addEventListener?.('lostpointercapture', onUp)
  537. canvas.addEventListener?.('pointerleave', onLeave)
  538. canvas.addEventListener?.('wheel', onWheel, { passive: false })
  539. resize()
  540. sync(plan)
  541. const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null
  542. observer?.observe(host)
  543. return {
  544. status: 'ready',
  545. title: enhancementLabel(plan.object.sourceKind),
  546. sync(next) { if (!destroyed && next?.visible && next.object) sync(next) },
  547. resize,
  548. focusDevice(code) {
  549. if (destroyed) return false
  550. const device = root?.getObjectByName(`device:${code}`)
  551. if (!device) return false
  552. // 定位目标取**稳定几何**(设备主体/支杆),不能用含图标的整体包围盒:
  553. // 图标按屏幕像素恒定尺寸缩放,飞行途中会变大变小,用整体盒算中心会让镜头「飘」。
  554. const anchor = device.getObjectByName('device-body') || device
  555. const bounds = new THREE.Box3().setFromObject(anchor).getBoundingSphere(new THREE.Sphere())
  556. /**
  557. * 终点距离按「**设备与图标都要完整可见**」解析求出,不再用固定倍率猜。
  558. *
  559. * 维护者 2026-10-23:「还需要拉远一点,需要能展示设备及点位图标的全貌。」
  560. * 图标是**屏幕恒定像素**的(约 33px 高),头顶在设备上方 `ICON_OFFSET_ABOVE_DEVICE`;
  561. * 只按设备包围球算距离会让图标顶出画面上沿(实测 NDC y 曾达 1.63~1.80)。
  562. *
  563. * 设 tanHalf=tan(fov/2)、H=视口高、iconPx=图标屏显高、o=图标偏移、r=设备半径:
  564. * 图标顶端 NDC ≈ (o + 2·d·tanHalf·iconPx/H) / (d·tanHalf) ≤ ICON_TOP_NDC
  565. * → d ≥ o / (tanHalf · (ICON_TOP_NDC − 2·iconPx/H))
  566. * 设备底端 NDC ≈ r / (d·tanHalf) ≤ BODY_BOTTOM_NDC → d ≥ r / (BODY_BOTTOM_NDC · tanHalf)
  567. * 取两者较大值再乘安全系数。这样任意视口尺寸都能适配,不是写死的倍数。
  568. */
  569. const tanHalf = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2))
  570. const viewHeight = host.clientHeight || 220
  571. const iconNode = device.getObjectByName('device-icon')
  572. const iconWidthPx = iconNode?.userData?.iconWidth || 26.7
  573. const iconAspect = iconNode?.userData?.iconAspect || 1.2566
  574. const iconPx = iconWidthPx * iconAspect
  575. const iconSpan = 2 * iconPx / viewHeight
  576. const distanceForIcon = ICON_OFFSET_ABOVE_DEVICE / Math.max(0.01, tanHalf * (FOCUS_ICON_TOP_NDC - iconSpan))
  577. const distanceForBody = bounds.radius / (FOCUS_BODY_BOTTOM_NDC * tanHalf)
  578. const toDistance = Math.max(0.8, Math.max(distanceForIcon, distanceForBody) * FOCUS_SAFETY)
  579. // 平滑飞行定位(不再瞬移);返回 true 表示已受理,飞行在后续帧推进。
  580. startFlight(bounds.center, toDistance)
  581. return true
  582. },
  583. getState: () => ({ status: destroyed ? 'destroyed' : 'ready', code: current.object.code, title: enhancementLabel(current.object.sourceKind) }),
  584. destroy() {
  585. if (destroyed) return
  586. destroyed = true
  587. cancelFlight()
  588. onUp()
  589. observer?.disconnect()
  590. detachFocus()
  591. detachPick()
  592. canvas.removeEventListener?.('pointerdown', onDown)
  593. canvas.removeEventListener?.('pointermove', onMove)
  594. canvas.removeEventListener?.('pointerup', onUp)
  595. canvas.removeEventListener?.('pointercancel', onUp)
  596. canvas.removeEventListener?.('lostpointercapture', onUp)
  597. canvas.removeEventListener?.('pointerleave', onLeave)
  598. canvas.removeEventListener?.('wheel', onWheel)
  599. if (root) disposeObject(root)
  600. renderer.dispose?.()
  601. if (renderer.domElement?.parentNode === host) host.removeChild(renderer.domElement)
  602. },
  603. }
  604. }