| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458 |
- /**
- * T03 逻辑检查:三键相机契约、旋转中心规则与阻尼(票 03 / ADR 0008)。
- *
- * 仓库没有测试运行器,且项目约定不为验证引入新框架,所以这里用零依赖 Node 断言脚本:
- * 相机语义全在 `domain/camera.js`(纯数学)与 `services/cameraControl.js`(状态迁移,引擎依赖注入),
- * 因此可以用**假引擎**驱动整套交互,不需要浏览器、不需要 cesium。
- * 真机行为(Cesium 默认输入确实被替换、中心确实落在屏幕中心、阻尼真的在真机上生效)
- * 由 t03-camera-walkthrough.mjs 覆盖。
- *
- * 运行:node .scratch/cockpit-shell-panel-layout/verify/t03-camera-contract.mjs
- */
- import assert from 'node:assert/strict'
- import { DAMPING_TAU_MS, FOCUS_FLIGHT_MS, PITCH_LIMITS, RANGE_LIMITS } from '../../../src/modules/cockpit/domain/camera.js'
- import * as camera from '../../../src/modules/cockpit/domain/camera.js'
- import { attachCameraInput, createCameraControl } from '../../../src/modules/cockpit/services/cameraControl.js'
- const GROUND = { lon: 110.39, lat: 28.46, height: 0 }
- const XIANGLING = { lon: 110.396, lat: 28.455, height: 0 } // 沅陵某监测点
- const FRAME_MS = 1000 / 60
- function createFakeEngine({ viewport = { width: 1680, height: 900 }, fovY = Math.PI / 3, ground = GROUND } = {}) {
- const applied = []
- let clock = 1000
- let pendingFrame = null
- return {
- applied,
- engine: {
- applyView(pivot, hpr) {
- applied.push({ pivot: { ...pivot }, hpr: { ...hpr } })
- },
- readView() {
- return { heading: 0, pitch: -60, range: 10000 }
- },
- pickGroundAtCenter() {
- return { ...ground }
- },
- projectPivot() {
- return { x: viewport.width / 2, y: viewport.height / 2 }
- },
- inputTarget() {
- return null
- },
- viewport() {
- return { ...viewport }
- },
- fovY() {
- return fovY
- },
- now() {
- return clock
- },
- requestFrame(callback) {
- pendingFrame = callback
- },
- },
- get pendingFrame() {
- return pendingFrame
- },
- advance(ms) {
- clock += ms
- },
- /** 跑一帧:假的 rAF 不带时间戳,控制器会退回 `engine.now()`(真机用真时间戳)。 */
- runFrame(dtMs = FRAME_MS) {
- const callback = pendingFrame
- pendingFrame = null
- clock += dtMs
- if (callback) callback()
- }, last() {
- return applied[applied.length - 1]
- },
- }
- }
- function newControl(options) {
- const fake = createFakeEngine(options)
- const control = createCameraControl({ engine: fake.engine, ...(options && options.control) })
- control.syncFromEngine()
- fake.applied.length = 0
- return { fake, control }
- }
- /** 一直跑到停稳(阻尼 + 换中心飞行都收敛),返回跑过的帧数。 */
- function settle(fake, control, maxFrames = 400) {
- let frames = 0
- while (!control.getState().settled && frames < maxFrames) {
- fake.runFrame()
- frames += 1
- }
- assert.ok(frames < maxFrames, `阻尼/飞行应在有限帧内停稳(已跑 ${frames} 帧仍未 settled)`)
- return frames
- }
- /** 假元素:记录监听器,供 attachCameraInput 的绑定/解绑断言。 */
- function createFakeElement() {
- const handlers = new Map()
- return {
- handlers,
- defaultPrevented: 0,
- addEventListener(type, fn) {
- if (!handlers.has(type)) handlers.set(type, new Set())
- handlers.get(type).add(fn)
- },
- removeEventListener(type, fn) {
- if (handlers.has(type)) handlers.get(type).delete(fn)
- },
- setPointerCapture() {},
- releasePointerCapture() {},
- fire(type, payload = {}) {
- const set = handlers.get(type)
- if (!set) return
- const event = {
- preventDefault() {
- this.defaultPrevented = true
- },
- ...payload,
- }
- set.forEach((fn) => fn(event))
- return event
- },
- }
- }
- const near = (a, b, tolerance, message) =>
- assert.ok(Math.abs(a - b) <= tolerance, `${message}:期望 ≈${b}(±${tolerance}),实际 ${a}`)
- const round3 = (n) => Number(n.toFixed(3))
- const metersPerPxAt = (range) => camera.metersPerPixel({ range, fovYRad: Math.PI / 3, viewportHeight: 900 })
- const degreesLonFor = (meters, lat) => meters / (111320 * Math.cos((lat * Math.PI) / 180))
- // ---------- 1. 左键拖拽只平移 ----------
- {
- const { fake, control } = newControl()
- const before = control.getState()
- control.beginDrag({ button: 0, x: 0, y: 0 })
- control.moveDrag({ x: 100, y: 0 })
- const after = control.getState()
- assert.deepEqual(after.hpr, before.hpr, '平移不得改 heading / pitch / range')
- // 维护者 2026-09-17 裁定:**抓着地图拖** —— 拖右 → 相机左移、画面右移,所以中心往西(lon 减小)。
- const expectedLon = before.pivot.lon - degreesLonFor(100 * metersPerPxAt(before.hpr.range), GROUND.lat)
- near(after.pivot.lon, expectedLon, Math.abs(expectedLon - before.pivot.lon) * 0.02, '拖右应把中心按像素比例西移(相机左移)')
- near(after.pivot.lat, before.pivot.lat, 1e-6, 'heading=0 时右拖不应产生南北位移')
- settle(fake, control)
- near(fake.last().pivot.lon, expectedLon, 1e-9, '阻尼收敛后下发给相机的中心应等于目标')
- console.log('PASS 1 左键拖拽只平移(heading/pitch/range 原样,中心按像素比例随「抓地图」方向西移)')
- }
- // ---------- 2. 平移方向 = 抓着地图拖(维护者裁定的语义钉子) ----------
- {
- const { fake, control } = newControl()
- control.beginDrag({ button: 0, x: 0, y: 0 })
- control.moveDrag({ x: 0, y: 100 })
- const down = control.getState()
- assert.ok(
- down.pivot.lat > GROUND.lat,
- `heading=0 时下拖应把中心往北带(画面下移、相机上移):${JSON.stringify(down.pivot)}`,
- )
- const { fake: fake2, control: control2 } = newControl()
- control2.beginDrag({ button: 2, x: 0, y: 0 })
- control2.moveDrag({ x: 90 / camera.ORBIT_SENSITIVITY.heading, y: 0 }) // 先把 heading 拖到 90°(向东看)
- control2.endDrag()
- settle(fake2, control2)
- near(control2.getState().hpr.heading, 90, 1e-6, '轨道旋转应把 heading 拖到 90°')
- const beforePan = control2.getState()
- control2.beginDrag({ button: 0, x: 0, y: 0 })
- control2.moveDrag({ x: 100, y: 0 })
- const afterPan = control2.getState()
- assert.ok(
- afterPan.pivot.lat > beforePan.pivot.lat,
- `heading=90°(向东看)时拖右应把中心往北带(画面右移=相机往左=北):${JSON.stringify(afterPan.pivot)}`,
- )
- near(afterPan.pivot.lon, beforePan.pivot.lon, 1e-6, 'heading=90° 时右拖不应产生东西位移')
- console.log('PASS 2 平移方向 = 抓着地图拖(拖右→画面右移/相机左移,heading=0/90 两点验证)')
- }
- // ---------- 3. 右键拖拽只做轨道旋转 ----------
- {
- const { fake, control } = newControl()
- const before = control.getState()
- control.beginDrag({ button: 2, x: 0, y: 0 })
- control.moveDrag({ x: 100, y: 50 })
- const after = control.getState()
- near(after.hpr.heading, 28, 1e-6, 'heading 变化 = dx × 灵敏度')
- near(after.hpr.pitch, -60 - 50 * 0.22, 1e-6, 'pitch 变化 = -dy × 灵敏度')
- assert.equal(after.hpr.range, before.hpr.range, '轨道旋转不得改弹簧臂长度')
- assert.deepEqual(after.pivot, before.pivot, '轨道旋转不得移动中心')
- settle(fake, control)
- near(fake.last().hpr.range, before.hpr.range, 1e-9, '阻尼收敛后下发的 range 仍应原样')
- console.log('PASS 3 右键拖拽只做轨道旋转(heading/pitch 按像素变化,range 与中心不动)')
- }
- // ---------- 4. pitch 夹在上下限内 ----------
- {
- const { fake, control } = newControl()
- control.beginDrag({ button: 2, x: 0, y: 0 })
- control.moveDrag({ x: 0, y: 5000 })
- near(control.getState().hpr.pitch, PITCH_LIMITS.ground.min, 1e-9, '一直下拖应夹在下限')
- control.moveDrag({ x: 0, y: -10000 })
- near(control.getState().hpr.pitch, PITCH_LIMITS.ground.max, 1e-9, '一直上拖应夹在上限')
- settle(fake, control)
- near(fake.last().hpr.pitch, PITCH_LIMITS.ground.max, 1e-9, '阻尼收敛后下发的 pitch 也应在限内')
- console.log(`PASS 4 pitch 夹在 [${PITCH_LIMITS.ground.min}, ${PITCH_LIMITS.ground.max}](地面视图)`)
- }
- // ---------- 5. 右键按下锁定中心:拖拽中不重新拾取 ----------
- {
- const { fake, control } = newControl()
- const locked = control.getState().pivot
- control.beginDrag({ button: 2, x: 0, y: 0 })
- // 拖拽进行中来了「选中某对象」:中心不许被改,飞行也不许插进来。
- control.setFocus(XIANGLING)
- control.moveDrag({ x: 40, y: 0 })
- assert.deepEqual(control.getState().pivot, locked, '拖拽中下发的中心必须仍是按下时锁定的那个')
- control.endDrag()
- assert.equal(control.getState().flying, true, '松手后应开始平滑换中心')
- settle(fake, control)
- const final = control.getState().pivot
- near(final.lon, XIANGLING.lon, 1e-9, '飞行结束后中心应为选中对象')
- near(final.lat, XIANGLING.lat, 1e-9, '飞行结束后中心应为选中对象')
- console.log('PASS 5 右键按下锁定中心(拖拽中的选中不插队;松手后才开始换中心)')
- }
- // ---------- 6. 滚轮只改弹簧臂长度 ----------
- {
- const { fake, control } = newControl()
- const before = control.getState()
- const handled = control.wheel({ deltaY: -100 })
- const after = control.getState()
- assert.equal(handled, true, '滚轮应被相机契约接管(调用方据此 preventDefault)')
- near(after.hpr.range, 10000 * Math.exp(-100 * 0.0012), 1e-6, '上滚拉近:range 按指数缩')
- assert.equal(after.hpr.heading, before.hpr.heading, '滚轮不得转 heading')
- assert.equal(after.hpr.pitch, before.hpr.pitch, '滚轮不得改 pitch')
- assert.deepEqual(after.pivot, before.pivot, '滚轮不得移动中心')
- control.wheel({ deltaY: -1e6 })
- near(control.getState().hpr.range, RANGE_LIMITS.min, 1e-9, '拉近到极限应夹住下限')
- control.wheel({ deltaY: 1e6 })
- near(control.getState().hpr.range, RANGE_LIMITS.max, 1e-9, '推远到极限应夹住上限')
- settle(fake, control)
- near(fake.last().hpr.range, RANGE_LIMITS.max, 1e-9, '阻尼收敛后下发的 range 应等于目标')
- console.log(`PASS 6 滚轮只改弹簧臂长度(并夹在 [${RANGE_LIMITS.min}, ${RANGE_LIMITS.max}] 米)`)
- }
- // ---------- 7. 中心规则:选中优先 / 取消不回退 / 平移才回退 ----------
- {
- const { fake, control } = newControl()
- assert.deepEqual(control.getState().pivot, GROUND, '未选中时中心 = 屏幕中心的地面拾取点')
- control.setFocus(XIANGLING)
- settle(fake, control)
- assert.deepEqual(control.getState().pivot, XIANGLING, '选中后中心 = 对象地表点')
- control.setFocus(null)
- assert.deepEqual(control.getState().pivot, XIANGLING, '取消选中不得回退中心')
- assert.equal(control.getState().focus, null, '取消选中应清掉选中态')
- control.beginDrag({ button: 0, x: 0, y: 0 })
- control.moveDrag({ x: 10, y: 0 })
- control.endDrag()
- assert.deepEqual(control.getState().pivot, GROUND, '左键平移后中心回到地面拾取点')
- console.log('PASS 7 中心规则:选中优先 → 取消不回退 → 平移才更新为地面拾取点')
- }
- // ---------- 8. 换中心平滑、且全程保持 heading 与 range ----------
- {
- const { fake, control } = newControl()
- const before = control.getState()
- control.setFocus(XIANGLING)
- // 起手第一帧(elapsed = 0)必须仍停在原中心 —— 换中心不许瞬移。
- fake.runFrame(0)
- near(control.getState().pivot.lon, before.pivot.lon, 1e-12, '换中心第一帧应从原中心出发')
- const samples = []
- let frames = 0
- while (control.getState().flying && frames++ < 200) {
- fake.runFrame(FOCUS_FLIGHT_MS / 8)
- const now = control.getState()
- assert.equal(now.hpr.heading, before.hpr.heading, '换中心过程中 heading 必须保持')
- assert.equal(now.hpr.range, before.hpr.range, '换中心过程中 range 必须保持')
- samples.push(now.pivot.lon)
- }
- assert.ok(samples.length >= 4, `换中心应有多帧(实际 ${samples.length})`)
- assert.equal(
- samples.every((lon, i) => i === 0 || lon >= samples[i - 1] - 1e-12),
- true,
- `中心应朝目标单调推进:${samples.join(' → ')}`,
- )
- settle(fake, control)
- near(control.getState().pivot.lon, XIANGLING.lon, 1e-9, '末帧应到达目标中心')
- assert.equal(control.getState().flying, false, '到达后应结束飞行')
- console.log(`PASS 8 换中心平滑(${samples.length} 帧单调推进、heading/range 全程不变)`)
- }
- // ---------- 9. 阻尼:渐入、不超调、停稳、且与帧率无关 ----------
- {
- const { fake, control } = newControl()
- const before = control.getState()
- control.beginDrag({ button: 0, x: 0, y: 0 })
- control.moveDrag({ x: 400, y: 0 })
- const target = control.getState()
- // 目标立刻到位(输入不丢),实际态还在起点附近 —— 这就是「丝滑」的来源。
- assert.notDeepEqual(target.pivot, before.pivot, '目标态应当立刻跟上输入')
- assert.deepEqual(control.getState().shownPivot, before.pivot, '首个阻尼帧之前,实际态还在起点')
- const targetShift = target.pivot.lon - before.pivot.lon
- fake.runFrame(FRAME_MS)
- const oneFrame = control.getState()
- const oneFrameShift = oneFrame.shownPivot.lon - before.pivot.lon
- assert.ok(
- Math.abs(oneFrameShift) > 0 && Math.abs(oneFrameShift) < Math.abs(targetShift) * 0.6,
- `一帧内应只走一小部分(实际 ${oneFrameShift} / 目标 ${targetShift})`,
- )
- assert.equal(oneFrame.settled, false, '一帧后还没停稳')
- // 逼近过程不得超调(单调朝目标,不越过)。
- let previous = Math.abs(target.pivot.lon - oneFrame.shownPivot.lon)
- let frames = 1
- while (!control.getState().settled && frames < 400) {
- fake.runFrame(FRAME_MS)
- const gap = Math.abs(target.pivot.lon - control.getState().shownPivot.lon)
- assert.ok(gap <= previous + 1e-12, `阻尼不得超调:缺口从 ${previous} 变成 ${gap}`)
- previous = gap
- frames += 1
- }
- assert.equal(control.getState().settled, true, '有限帧内应停稳')
- assert.deepEqual(control.getState().shownPivot, target.pivot, '停稳后实际态应吸附到目标')
- console.log(`PASS 9a 阻尼渐入、不超调、${frames} 帧内停稳并吸附(τ=${DAMPING_TAU_MS}ms)`)
- // 帧率无关:同样的真实时长,60fps 与 120fps 收敛到同一个位置(±1%)。
- const walk = (dtMs, totalMs) => {
- const { fake: f, control: c } = newControl()
- const start = c.getState()
- c.beginDrag({ button: 0, x: 0, y: 0 })
- c.moveDrag({ x: 400, y: 0 })
- // 固定帧数,别用浮点累加判停:累加误差会多跑一帧,把「帧率无关」测成假的偏差。
- const frames = Math.round(totalMs / dtMs)
- for (let i = 0; i < frames; i += 1) f.runFrame(dtMs)
- const shift = c.getState().shownPivot.lon - start.pivot.lon
- const full = c.getState().pivot.lon - start.pivot.lon
- return shift / full
- }
- const at60 = walk(1000 / 60, 200)
- const at120 = walk(1000 / 120, 200)
- near(at60, at120, 0.01, '同样 200ms 内 60fps 与 120fps 的收敛比例应一致(±1%)')
- assert.ok(at60 > 0.6 && at60 < 0.95, `200ms(≈1.8τ)应走掉大半但未走完:实际 ${at60}`)
- console.log(`PASS 9b 阻尼与帧率无关(60fps ${(at60 * 100).toFixed(1)}% vs 120fps ${(at120 * 100).toFixed(1)}%)`)
- }
- // ---------- 10. 用户操作打断换中心飞行 ----------
- {
- const { fake, control } = newControl()
- control.setFocus(XIANGLING)
- assert.equal(control.getState().flying, true, '应处于换中心飞行中')
- control.beginDrag({ button: 0, x: 0, y: 0 })
- assert.equal(control.getState().flying, false, '一上手就应打断飞行(输入永远优先)')
- console.log('PASS 10 用户操作打断换中心飞行')
- }
- // ---------- 10b. 阻尼可现场拖调(手感是主观的,维护者要能在控制台试) ----------
- {
- const { fake, control } = newControl()
- assert.equal(control.getState().dampingTauMs, DAMPING_TAU_MS, '默认应取 domain 里的 τ')
- // 调大 τ:同样一帧走得更少(更飘)。
- const shiftWith = (tau) => {
- const { fake: f, control: c } = newControl()
- c.setDampingTau(tau)
- const start = c.getState().pivot.lon
- c.beginDrag({ button: 0, x: 0, y: 0 })
- c.moveDrag({ x: 400, y: 0 })
- f.runFrame(FRAME_MS)
- return Math.abs(c.getState().shownPivot.lon - start)
- }
- const loose = shiftWith(400)
- const tight = shiftWith(40)
- assert.ok(tight > loose * 1.5, `τ 越小越跟手:τ=40 走 ${tight},τ=400 只走 ${loose}`)
- // τ = 0:不做阻尼(一帧内直接贴到目标),给「要完全即时手感」的场合留的档。
- const { fake: f2, control: c2 } = newControl()
- c2.setDampingTau(0)
- c2.beginDrag({ button: 0, x: 0, y: 0 })
- c2.moveDrag({ x: 400, y: 0 })
- f2.runFrame(FRAME_MS)
- assert.deepEqual(c2.getState().shownPivot, c2.getState().pivot, 'τ=0 时一帧内实际态应贴到目标态')
- assert.equal(c2.getState().settled, true, 'τ=0 时下完指令一帧即停稳')
- assert.equal(f2.pendingFrame, null, 'τ=0 停稳后不应再排帧')
- // 非法值不生效(守住旋钮)。
- assert.equal(control.setDampingTau(-5), DAMPING_TAU_MS, '负数应被拒绝并保持原值')
- assert.equal(control.setDampingTau('abc'), DAMPING_TAU_MS, '非数字应被拒绝并保持原值')
- console.log(`PASS 10b 阻尼可拖调(τ=40 走 ${round3(tight)}° > τ=400 走 ${round3(loose)}°;τ=0 直接跟手)`)
- }
- // ---------- 11. DOM 绑定:三类输入都接上,右键菜单与滚轮默认行为被吃掉 ----------
- {
- const { fake, control } = newControl()
- const element = createFakeElement()
- const detach = attachCameraInput(element, control)
- assert.deepEqual(
- [...element.handlers.keys()].sort(),
- ['contextmenu', 'pointercancel', 'pointerdown', 'pointermove', 'pointerup', 'wheel'],
- '应绑定左右键拖拽与滚轮(并吃掉右键菜单)',
- )
- assert.equal(element.fire('contextmenu').defaultPrevented, true, '右键菜单必须被 preventDefault')
- element.fire('pointerdown', { button: 0, pointerId: 1, clientX: 500, clientY: 400 })
- element.fire('pointermove', { pointerId: 1, clientX: 560, clientY: 400 })
- assert.equal(control.getState().dragging, 'pan', '左键按下后应处于平移态')
- element.fire('pointerup', { pointerId: 1, clientX: 560, clientY: 400 })
- assert.equal(control.getState().dragging, null, '松手后应结束拖拽')
- element.fire('pointerdown', { button: 2, pointerId: 2, clientX: 500, clientY: 400 })
- element.fire('pointermove', { pointerId: 2, clientX: 540, clientY: 400 })
- assert.equal(control.getState().dragging, 'orbit', '右键按下后应处于轨道旋转态')
- element.fire('pointerup', { pointerId: 2, clientX: 540, clientY: 400 })
- assert.equal(element.fire('wheel', { deltaY: -120 }).defaultPrevented, true, '滚轮默认行为(页面滚动)必须被吃掉')
- detach()
- assert.equal(element.handlers.get('pointerdown').size, 0, 'detach 应摘掉监听器')
- assert.equal(element.handlers.get('wheel').size, 0, 'detach 应摘掉滚轮监听器')
- console.log('PASS 11 DOM 绑定:三类输入接上、右键菜单与滚轮默认行为被吃掉、可完整摘除')
- }
- // ---------- 12. 状态串(走查与人工排查读的那一行) ----------
- {
- const { control } = newControl()
- const text = camera.formatCameraState(control.getState())
- ;['h=', 'p=', 'r=', 'pivot=', 'focus=ground', 'drag=none', 'settled='].forEach((part) =>
- assert.ok(text.includes(part), `状态串应含 ${part}:${text}`),
- )
- assert.equal(
- camera.formatCameraState({ hpr: { heading: 0, pitch: -60, range: 1 }, pivot: null }),
- 'h=0.0 p=-60.0 r=1 pivot=none',
- )
- console.log(`PASS 12 状态串可读:${text}`)
- }
- console.log('\nT03 逻辑检查通过:三键契约、中心规则、换中心动画、阻尼(帧率无关)、DOM 绑定均符合契约与维护者裁定。')
|