// ==UserScript== // @name 车道线测距与中线生成 // @namespace http://58.144.139.12/pointcloud // @version 1.1.2 // @description 点云车道线标注辅助:点击测距/测宽、两条车道线生成中线 // @author swj // @match *://*/* // @grant none // @run-at document-idle // @noframes // ==/UserScript== /* * 本文件由 scripts/build.mjs 自动生成,请勿直接修改。 * 源码:src/core.mjs、src/platform.mjs、src/overlay.mjs、src/ui.mjs * 构建:node scripts/build.mjs */ (function () { 'use strict'; /* ==================== src/core.mjs ==================== */ const TOOL_VERSION = '1.1.2'; const EPS = 1e-9; function vec3(x = 0, y = 0, z = 0) { return { x: Number(x), y: Number(y), z: Number(z) }; } function clonePoint(p) { return { x: p.x, y: p.y, z: p.z }; } function isFinitePoint(p) { return !!p && typeof p === 'object' && Number.isFinite(p.x) && Number.isFinite(p.y) && Number.isFinite(p.z); } function addVec(a, b) { return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z }; } function subVec(a, b) { return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z }; } function scaleVec(a, s) { return { x: a.x * s, y: a.y * s, z: a.z * s }; } function dotVec(a, b) { return a.x * b.x + a.y * b.y + a.z * b.z; } function crossVec(a, b) { return { x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x, }; } function lenSqVec(a) { return dotVec(a, a); } function lenVec(a) { return Math.sqrt(lenSqVec(a)); } function distSqVec(a, b) { return lenSqVec(subVec(a, b)); } function distVec(a, b) { return Math.sqrt(distSqVec(a, b)); } function normalizeVec(a) { const l = lenVec(a); if (!(l > EPS)) return null; const k = 1 / l; return { x: a.x * k, y: a.y * k, z: a.z * k }; } function lerpVec(a, b, t) { return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t, z: a.z + (b.z - a.z) * t, }; } function averageVecs(list) { if (!Array.isArray(list) || list.length === 0) return null; let sx = 0, sy = 0, sz = 0; for (const p of list) { if (!isFinitePoint(p)) return null; sx += p.x; sy += p.y; sz += p.z; } const n = list.length; return { x: sx / n, y: sy / n, z: sz / n }; } function clamp(v, min, max) { return v < min ? min : (v > max ? max : v); } function mat4Identity() { return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; } function mat4FromElements(src) { if (!src) return null; const arr = Array.isArray(src) ? src : (src.elements && (Array.isArray(src.elements) || ArrayBuffer.isView(src.elements)) ? src.elements : null); if (!arr || arr.length < 16) return null; const out = new Array(16); for (let i = 0; i < 16; i++) { const v = Number(arr[i]); if (!Number.isFinite(v)) return null; out[i] = v; } return out; } function mat4Multiply(a, b) { const out = new Array(16); for (let c = 0; c < 4; c++) { for (let r = 0; r < 4; r++) { out[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3]; } } return out; } function mat4TransformPoint(m, p) { const x = p.x, y = p.y, z = p.z; const w = Number.isFinite(p.w) ? p.w : 1; const out = { x: m[0] * x + m[4] * y + m[8] * z + m[12] * w, y: m[1] * x + m[5] * y + m[9] * z + m[13] * w, z: m[2] * x + m[6] * y + m[10] * z + m[14] * w, w: m[3] * x + m[7] * y + m[11] * z + m[15] * w, }; if (!Number.isFinite(out.x) || !Number.isFinite(out.y) || !Number.isFinite(out.z) || !Number.isFinite(out.w)) { return null; } return out; } function mat4TransformDirection(m, v) { return { x: m[0] * v.x + m[4] * v.y + m[8] * v.z, y: m[1] * v.x + m[5] * v.y + m[9] * v.z, z: m[2] * v.x + m[6] * v.y + m[10] * v.z, }; } function mat4Invert(m) { if (!m || m.length < 16) return null; const rows = []; for (let r = 0; r < 4; r++) { rows.push([ m[r], m[4 + r], m[8 + r], m[12 + r], r === 0 ? 1 : 0, r === 1 ? 1 : 0, r === 2 ? 1 : 0, r === 3 ? 1 : 0, ]); } for (let col = 0; col < 4; col++) { let pivot = col; let pivotVal = Math.abs(rows[col][col]); for (let r = col + 1; r < 4; r++) { const v = Math.abs(rows[r][col]); if (v > pivotVal) { pivot = r; pivotVal = v; } } if (!(pivotVal > 1e-12)) return null; if (pivot !== col) { const tmp = rows[col]; rows[col] = rows[pivot]; rows[pivot] = tmp; } const pv = rows[col][col]; for (let c = 0; c < 8; c++) rows[col][c] /= pv; for (let r = 0; r < 4; r++) { if (r === col) continue; const f = rows[r][col]; if (f === 0) continue; for (let c = 0; c < 8; c++) rows[r][c] -= f * rows[col][c]; } } const out = new Array(16); for (let r = 0; r < 4; r++) { for (let c = 0; c < 4; c++) out[c * 4 + r] = rows[r][4 + c]; } for (let i = 0; i < 16; i++) if (!Number.isFinite(out[i])) return null; return out; } function mat4ApproximatelyEqual(a, b, eps = 1e-6) { if (!a || !b || a.length < 16 || b.length < 16) return false; for (let i = 0; i < 16; i++) if (Math.abs(a[i] - b[i]) > eps) return false; return true; } function createProjector(camera) { if (!camera || typeof camera !== 'object') return null; const matrixWorld = mat4FromElements(camera.matrixWorld); let view = mat4FromElements(camera.matrixWorldInverse); if (!view && matrixWorld) view = mat4Invert(matrixWorld); const projection = mat4FromElements(camera.projectionMatrix); if (!view || !projection) return null; const matrixWorldResolved = matrixWorld || mat4Invert(view); const projectionInverse = mat4FromElements(camera.projectionMatrixInverse) || mat4Invert(projection); if (!matrixWorldResolved || !projectionInverse) return null; return { view, matrixWorld: matrixWorldResolved, projection, projectionInverse, near: Number.isFinite(camera.near) ? camera.near : 0.1, far: Number.isFinite(camera.far) ? camera.far : 2000, isPerspective: !!camera.isPerspectiveCamera, isOrthographic: !!camera.isOrthographicCamera, }; } function projectWorld(projector, world) { if (!projector || !isFinitePoint(world)) return null; const viewP = mat4TransformPoint(projector.view, world); if (!viewP) return null; const clip = mat4TransformPoint(projector.projection, viewP); if (!clip) return null; if (Math.abs(clip.w) < 1e-12) return null; const inv = 1 / clip.w; const ndcX = clip.x * inv; const ndcY = clip.y * inv; const ndcZ = clip.z * inv; const behind = clip.w <= 0; return { ndcX, ndcY, ndcZ, w: clip.w, behind, visible: !behind && ndcZ >= -1 && ndcZ <= 1 }; } function ndcToLocal(ndcX, ndcY, width, height) { return { x: (ndcX * 0.5 + 0.5) * width, y: (-ndcY * 0.5 + 0.5) * height, }; } function localToNdc(x, y, width, height) { return { x: (x / width) * 2 - 1, y: -(y / height) * 2 + 1, }; } function projectWorldToLocal(projector, world, width, height) { if (!(width > 0) || !(height > 0)) return null; const proj = projectWorld(projector, world); if (!proj) return null; const local = ndcToLocal(proj.ndcX, proj.ndcY, width, height); return { x: local.x, y: local.y, ndcX: proj.ndcX, ndcY: proj.ndcY, ndcZ: proj.ndcZ, w: proj.w, behind: proj.behind, visible: proj.visible, onScreen: proj.visible && local.x >= 0 && local.x <= width && local.y >= 0 && local.y <= height, }; } function unprojectNdc(projector, nx, ny, nz) { if (!projector) return null; const clip = mat4TransformPoint(projector.projectionInverse, { x: nx, y: ny, z: nz, w: 1 }); if (!clip || Math.abs(clip.w) < 1e-12) return null; const viewP = { x: clip.x / clip.w, y: clip.y / clip.w, z: clip.z / clip.w }; const worldP = mat4TransformPoint(projector.matrixWorld, viewP); if (!worldP || Math.abs(worldP.w) < 1e-12) return null; return { x: worldP.x / worldP.w, y: worldP.y / worldP.w, z: worldP.z / worldP.w }; } function createRayFromLocal(projector, px, py, width, height) { if (!projector || !(width > 0) || !(height > 0)) return null; const ndc = localToNdc(px, py, width, height); const nearP = unprojectNdc(projector, ndc.x, ndc.y, -1); const farP = unprojectNdc(projector, ndc.x, ndc.y, 1); if (!nearP || !farP) return null; const direction = normalizeVec(subVec(farP, nearP)); if (!direction) return null; return { origin: nearP, far: farP, direction, ndc }; } function rayPlaneIntersect(ray, planePoint, planeNormal, options = {}) { if (!ray || !ray.origin || !ray.direction || !isFinitePoint(planePoint) || !isFinitePoint(planeNormal)) return null; const denom = dotVec(ray.direction, planeNormal); if (Math.abs(denom) < 1e-9) return null; const t = dotVec(subVec(planePoint, ray.origin), planeNormal) / denom; if (t < 0 && !options.allowNegative) return null; return { point: addVec(ray.origin, scaleVec(ray.direction, t)), t }; } function rayPointClosest(ray, p) { if (!ray || !ray.origin || !ray.direction || !isFinitePoint(p)) return null; const v = subVec(p, ray.origin); const s = dotVec(v, ray.direction); if (!(s > 0)) return null; const closest = addVec(ray.origin, scaleVec(ray.direction, s)); return { s, closest, dist: distVec(p, closest) }; } function pickNearestPoint(ray, points, options = {}) { if (!ray || !ray.origin || !ray.direction) return null; if (!points || typeof points.length !== 'number') return null; const threshold = Number.isFinite(options.threshold) ? options.threshold : Infinity; const stride = Math.max(1, Math.floor(Number(options.stride) || 1)); let best = null; for (let i = 0; i < points.length; i += stride) { const hit = rayPointClosest(ray, points[i]); if (!hit) continue; if (hit.dist > threshold) continue; if (!best || hit.dist < best.dist) { best = { index: i, point: clonePoint(points[i]), dist: hit.dist, s: hit.s, closest: hit.closest }; } } return best; } function closestPointOnSegment(a, b, p) { const ab = subVec(b, a); const d2 = lenSqVec(ab); let t = 0; if (d2 > EPS * EPS) t = clamp(dotVec(subVec(p, a), ab) / d2, 0, 1); const foot = addVec(a, scaleVec(ab, t)); return { foot, t, dist: distVec(p, foot) }; } function pointToPolyline(p, polyline) { const pts = polyline && Array.isArray(polyline.points) ? polyline.points : polyline; if (!p || !Array.isArray(pts) || pts.length === 0) return null; if (pts.length === 1) { return { dist: distVec(p, pts[0]), foot: clonePoint(pts[0]), segIndex: 0, t: 0 }; } let best = null; for (let i = 0; i + 1 < pts.length; i++) { const hit = closestPointOnSegment(pts[i], pts[i + 1], p); if (!best || hit.dist < best.dist) { best = { dist: hit.dist, foot: hit.foot, segIndex: i, t: hit.t }; } } return best; } function sideOfSegment(a, b, p) { const cz = (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x); if (Math.abs(cz) < 1e-9) return 0; return cz > 0 ? 1 : -1; } function sideText(side) { if (side > 0) return '左侧'; if (side < 0) return '右侧'; return '线上'; } function pointToPolylineXY(p, polyline) { const pts = polyline && Array.isArray(polyline.points) ? polyline.points : polyline; if (!p || !Array.isArray(pts) || pts.length === 0) return null; if (pts.length === 1) { const foot = clonePoint(pts[0]); return { distXY: Math.hypot(p.x - foot.x, p.y - foot.y), segIndex: 0, t: 0, foot, footXY: { x: foot.x, y: foot.y }, }; } let best = null; for (let i = 0; i + 1 < pts.length; i++) { const a = pts[i]; const b = pts[i + 1]; const dx = b.x - a.x; const dy = b.y - a.y; const d2 = dx * dx + dy * dy; let t = 0; if (d2 > EPS * EPS) t = clamp(((p.x - a.x) * dx + (p.y - a.y) * dy) / d2, 0, 1); const fx = a.x + dx * t; const fy = a.y + dy * t; const distXY = Math.hypot(p.x - fx, p.y - fy); if (!best || distXY < best.distXY - 1e-12) { best = { distXY, segIndex: i, t, foot: { x: fx, y: fy, z: a.z + (b.z - a.z) * t, }, footXY: { x: fx, y: fy }, }; } } return best; } function measureToPolyline(p, polyline) { const pts = polyline && Array.isArray(polyline.points) ? polyline.points : polyline; const hitXY = pointToPolylineXY(p, pts); if (!hitXY) return null; const hit3D = pointToPolyline(p, pts); let side = 0; if (Array.isArray(pts) && pts.length >= 2 && hitXY.segIndex + 1 < pts.length) { side = sideOfSegment(pts[hitXY.segIndex], pts[hitXY.segIndex + 1], p); } const foot = hitXY.foot; const foot3D = hit3D ? hit3D.foot : clonePoint(foot); const dist3D = hit3D ? hit3D.dist : distVec(p, foot3D); return { dist: hitXY.distXY, distXY: hitXY.distXY, foot, footXY: hitXY.footXY, segIndex: hitXY.segIndex, t: hitXY.t, side, sideText: sideText(side), foot3D, dist3D, seg3DIndex: hit3D ? hit3D.segIndex : hitXY.segIndex, t3D: hit3D ? hit3D.t : hitXY.t, dz: p.z - foot.z, }; } function summarizeMeasure(line, pointA, pointB) { const a = measureToPolyline(pointA, line); const b = measureToPolyline(pointB, line); if (!a || !b) return null; const opposite = (a.side === 0 || b.side === 0) ? true : (a.side !== b.side); const sum = a.distXY + b.distXY; const diff = Math.abs(a.distXY - b.distXY); const sum3d = a.dist3D + b.dist3D; const diff3d = Math.abs(a.dist3D - b.dist3D); return { a, b, opposite, width: opposite ? sum : diff, sum, diff, width3d: opposite ? sum3d : diff3d, sum3d, diff3d, }; } function polylineLength(points) { if (!Array.isArray(points) || points.length < 2) return 0; let total = 0; for (let i = 1; i < points.length; i++) total += distVec(points[i - 1], points[i]); return total; } function cumulativeLengths(points) { if (!Array.isArray(points) || points.length === 0) return []; const acc = new Array(points.length); acc[0] = 0; for (let i = 1; i < points.length; i++) acc[i] = acc[i - 1] + distVec(points[i - 1], points[i]); return acc; } function resamplePolyline(points, count) { const n = Array.isArray(points) ? points.length : 0; if (!Number.isInteger(count) || count < 2) throw new RangeError('resamplePolyline: 采样点数必须是 >= 2 的整数'); if (n === 0) return []; if (n === 1) { const out = []; for (let i = 0; i < count; i++) out.push(clonePoint(points[0])); return out; } const acc = cumulativeLengths(points); const total = acc[n - 1]; const out = []; if (!(total > EPS)) { for (let i = 0; i < count; i++) out.push(clonePoint(points[0])); return out; } let seg = 1; for (let i = 0; i < count; i++) { if (i === 0) { out.push(clonePoint(points[0])); continue; } if (i === count - 1) { out.push(clonePoint(points[n - 1])); continue; } const target = total * i / (count - 1); while (seg < n - 1 && acc[seg] < target) seg++; const d0 = acc[seg - 1]; const d1 = acc[seg]; const span = d1 - d0; const t = span > EPS ? (target - d0) / span : 0; out.push(lerpVec(points[seg - 1], points[seg], t)); } return out; } function orientLines(line1, line2) { if (!Array.isArray(line1) || !Array.isArray(line2) || line1.length < 2 || line2.length < 2) { return { reverse: false, forwardCost: Infinity, reverseCost: Infinity }; } const a1 = line1[0]; const a2 = line1[line1.length - 1]; const b1 = line2[0]; const b2 = line2[line2.length - 1]; const forwardCost = distSqVec(a1, b1) + distSqVec(a2, b2); const reverseCost = distSqVec(a1, b2) + distSqVec(a2, b1); return { reverse: reverseCost < forwardCost, forwardCost, reverseCost }; } function applyLineDirection(points, reverse) { if (!Array.isArray(points)) return []; return reverse ? points.slice().reverse() : points.slice(); } function buildCenterLine(line1, line2, options = {}) { const l1 = Array.isArray(line1) ? line1 : []; const l2 = Array.isArray(line2) ? line2 : []; if (l1.length < 2 || l2.length < 2) { return { ok: false, reason: '两条车道线都至少需要 2 个点' }; } if (!l1.every(isFinitePoint) || !l2.every(isFinitePoint)) { return { ok: false, reason: '车道线坐标包含无效数值' }; } const opts = (options && typeof options === 'object') ? options : {}; const minPoints = Math.max(2, Math.round(Number(opts.minPoints) || 2) || 2); const orient = orientLines(l1, l2); const l2o = orient.reverse ? l2.slice().reverse() : l2.slice(); const autoN = Math.max(l1.length, l2o.length); const rawRequested = opts.pointCount; const isAuto = rawRequested === undefined || rawRequested === null || rawRequested === '' || rawRequested === 'auto'; let requestedN = null; let effectiveN = autoN; let clamped = false; if (!isAuto) { const numeric = Number(rawRequested); if (Number.isFinite(numeric)) { requestedN = numeric; let n = Math.round(numeric); if (n < minPoints) { n = minPoints; clamped = true; } if (n > 500) { n = 500; clamped = true; } effectiveN = n; } else { requestedN = null; effectiveN = autoN; } } if (!Number.isInteger(effectiveN) || effectiveN < 2) effectiveN = Math.max(2, autoN); const needResample = l1.length !== effectiveN || l2o.length !== effectiveN; const a = l1.length === effectiveN ? l1 : resamplePolyline(l1, effectiveN); const b = l2o.length === effectiveN ? l2o : resamplePolyline(l2o, effectiveN); const points = new Array(effectiveN); for (let i = 0; i < effectiveN; i++) { points[i] = { x: (a[i].x + b[i].x) / 2, y: (a[i].y + b[i].y) / 2, z: (a[i].z + b[i].z) / 2, }; } return { ok: true, points, n: effectiveN, requestedN, effectiveN, clamped, resampled: needResample, reversed: orient.reverse, rawLengths: [polylineLength(l1), polylineLength(l2)], length: polylineLength(points), }; } function screenDistanceToSegment(px, py, ax, ay, bx, by) { const dx = bx - ax; const dy = by - ay; const d2 = dx * dx + dy * dy; let t = 0; if (d2 > 1e-12) t = ((px - ax) * dx + (py - ay) * dy) / d2; t = clamp(t, 0, 1); const x = ax + dx * t; const y = ay + dy * t; return { dist: Math.hypot(px - x, py - y), x, y, t }; } function pickPolylineByScreen(lines, clickX, clickY, projector, width, height, maxPx = 12) { if (!projector || !Array.isArray(lines) || !(width > 0) || !(height > 0)) return null; if (!Number.isFinite(clickX) || !Number.isFinite(clickY)) return null; let best = null; for (const line of lines) { const pts = line && Array.isArray(line.points) ? line.points : null; if (!pts || pts.length === 0) continue; const projected = new Array(pts.length); for (let i = 0; i < pts.length; i++) { const p = projectWorldToLocal(projector, pts[i], width, height); projected[i] = (p && !p.behind) ? p : null; } if (pts.length === 1) { const p = projected[0]; if (!p) continue; const distPx = Math.hypot(clickX - p.x, clickY - p.y); if (distPx <= maxPx && (!best || distPx < best.distPx)) { best = { line, distPx, segIndex: 0, t: 0, footX: p.x, footY: p.y }; } continue; } for (let i = 0; i + 1 < pts.length; i++) { const s0 = projected[i]; const s1 = projected[i + 1]; if (!s0 || !s1) continue; const hit = screenDistanceToSegment(clickX, clickY, s0.x, s0.y, s1.x, s1.y); if (hit.dist > maxPx) continue; if (!best || hit.dist < best.distPx) { best = { line, distPx: hit.dist, segIndex: i, t: hit.t, footX: hit.x, footY: hit.y }; } } } return best; } function screenDistance(ax, ay, bx, by) { return Math.hypot(ax - bx, ay - by); } function suggestTargetClass(classOptions, lineAClassId, lineBClassId, options = {}) { const list = Array.isArray(classOptions) ? classOptions.filter(Boolean) : []; const a = lineAClassId != null ? String(lineAClassId) : ''; const b = lineBClassId != null ? String(lineBClassId) : ''; const findById = (id) => list.find((o) => String(o.classId) === String(id)); const manualId = options.manualClassId != null && options.manualClassId !== '' ? String(options.manualClassId) : ''; if (manualId) { const found = findById(manualId); if (found) { return { classId: found.classId, label: found.label || String(found.classId), reason: 'manual', auto: false, crossSource: a !== '' && String(found.classId) !== a, }; } } const textOf = (o) => `${o.label || ''} ${o.classId || ''}`.toLowerCase(); const keywordMatchers = [ { reason: 'keyword-centerline', test: (text) => text.includes('中心线') }, { reason: 'keyword-midline', test: (text) => text.includes('中线') }, ]; for (const matcher of keywordMatchers) { const hit = list.find((o) => matcher.test(textOf(o))); if (hit) { return { classId: hit.classId, label: hit.label || String(hit.classId), reason: matcher.reason, auto: true, crossSource: a !== '' && String(hit.classId) !== a, }; } } const laneCandidates = list.filter((o) => { const text = textOf(o); return text.includes('车道线') || text.includes('车道'); }); if (laneCandidates.length > 0) { let preferred = null; if (a && b && a === b) preferred = laneCandidates.find((o) => String(o.classId) === a); if (!preferred && a) preferred = laneCandidates.find((o) => String(o.classId) === a); if (!preferred && b) preferred = laneCandidates.find((o) => String(o.classId) === b); if (!preferred) preferred = laneCandidates[0]; return { classId: preferred.classId, label: preferred.label || String(preferred.classId), reason: 'keyword-lane', auto: true, crossSource: a !== '' && String(preferred.classId) !== a, }; } const centerHit = list.find((o) => /centerline|center/.test(textOf(o))); if (centerHit) { return { classId: centerHit.classId, label: centerHit.label || String(centerHit.classId), reason: 'keyword-center', auto: true, crossSource: a !== '' && String(centerHit.classId) !== a, }; } if (a && b && a === b) { const hit = findById(a); return { classId: hit ? hit.classId : a, label: hit ? (hit.label || a) : a, reason: 'source-common', auto: true, crossSource: false, }; } const firstSource = a || b; if (firstSource) { const hit = findById(firstSource); return { classId: hit ? hit.classId : firstSource, label: hit ? (hit.label || firstSource) : firstSource, reason: 'source-first', auto: true, crossSource: a !== '' && String(hit ? hit.classId : firstSource) !== a, }; } if (list.length > 0) { const first = list[0]; return { classId: first.classId, label: first.label || String(first.classId), reason: 'fallback-first', auto: true, crossSource: false, }; } return { classId: '', label: '', reason: 'none', auto: true, crossSource: false }; } function normalizePoints(raw, options = {}) { const out = []; const maxDepth = Number.isInteger(options.maxDepth) ? options.maxDepth : 5; const visit = (value, depth) => { if (value == null || depth > maxDepth) return; if (!Array.isArray(value) && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0) { try { visit(Array.from(value), depth); } catch (_) { /* 忽略不可迭代对象 */ } return; } if (Array.isArray(value)) { if (value.length === 0) return; const first = value[0]; if (typeof first === 'number') { for (let i = 0; i + 2 < value.length; i += 3) { const p = vec3(value[i], value[i + 1], value[i + 2]); if (isFinitePoint(p)) out.push(p); } return; } if (Array.isArray(first)) { for (const item of value) { if (Array.isArray(item) && item.length >= 3) { const p = vec3(item[0], item[1], item[2]); if (isFinitePoint(p)) out.push(p); } } return; } if (first && typeof first === 'object') { for (const item of value) { if (!item || typeof item !== 'object') continue; const nested = item.points; if (nested && typeof nested === 'object') { visit(nested, depth + 1); continue; } const x = numberOrNaN(item.x); const y = numberOrNaN(item.y); if (Number.isNaN(x) || Number.isNaN(y)) continue; const p = vec3(x, y, Number.isFinite(Number(item.z)) ? Number(item.z) : 0); if (isFinitePoint(p)) out.push(p); } return; } return; } if (typeof value === 'object') { if (value.points && typeof value.points === 'object') { visit(value.points, depth + 1); return; } const x = numberOrNaN(value.x); const y = numberOrNaN(value.y); if (Number.isNaN(x) || Number.isNaN(y)) return; const p = vec3(x, y, Number.isFinite(Number(value.z)) ? Number(value.z) : 0); if (isFinitePoint(p)) out.push(p); } }; try { visit(raw, 0); } catch (_) { return []; } return out; } function numberOrNaN(v) { const n = Number(v); return Number.isFinite(n) ? n : NaN; } function fmt2(v) { const n = Number(v); if (!Number.isFinite(n)) return '--'; return n.toFixed(2); } function fmtMeters(v) { return `${fmt2(v)} 米`; } function safeText(v) { try { if (v == null) return ''; if (typeof v === 'string') return v; return String(v); } catch (_) { return ''; } } /* ==================== src/platform.mjs ==================== */ function createPlatform() { const LOG = '[车道线工具]'; const cache = { viewer: null, camera: null, storeManager: null, store: null, lineHandler: null, points: null, pickElement: null, lastDiscoverAt: 0, discoverCount: 0, lastSummary: '', rectsLogged: false, pickThreshold: 0.5, discovering: false, lastInfo: null, }; const errors = []; let marksCache = { at: 0, frameId: null, result: null }; function recordError(where, err) { const msg = `${where}:${err && err.message ? err.message : String(err)}`; const item = { at: Date.now(), msg }; errors.push(item); if (errors.length > 30) errors.shift(); try { console.warn(`${LOG} ${msg}`); } catch (_) { /* 忽略 */ } } function safe(fn, fallback, where) { try { return fn(); } catch (err) { if (where) recordError(where, err); return fallback; } } function num(v, fallback) { const n = Number(v); return Number.isFinite(n) ? n : fallback; } function getGlobalViewer() { try { if (window.viewer && typeof window.viewer === 'object') return window.viewer; } catch (_) { /* 忽略 */ } try { const inst = window.instance; if (inst && inst.viewer && typeof inst.viewer === 'object') return inst.viewer; } catch (_) { /* 忽略 */ } return null; } function getGlobalStoreManager() { try { const inst = window.instance; if (inst && inst.StoreManager && typeof inst.StoreManager === 'object') return inst.StoreManager; } catch (_) { /* 忽略 */ } try { if (window.StoreManager && typeof window.StoreManager === 'object') return window.StoreManager; } catch (_) { /* 忽略 */ } return null; } function getVuexStore() { const isValid = (s) => !!s && typeof s === 'object' && typeof s.commit === 'function'; const sm = cache.storeManager || getGlobalStoreManager(); if (sm && typeof sm.getStore === 'function') { const store = safe(() => sm.getStore(), null, 'StoreManager.getStore'); if (isValid(store)) return store; } const found = safe(() => { const app = document.querySelector('#app'); const vueApp = app && app.__vue_app__; const provides = vueApp && vueApp._context && vueApp._context.provides; const store = provides && provides.store; return isValid(store) ? store : null; }, null, '读取 Vuex store(provides)'); if (found) return found; const fromVnode = safe(() => { const el = document.querySelector('#app'); const comp = el && el._vnode && el._vnode.component; const store = comp && comp.provides && comp.provides.store; return isValid(store) ? store : null; }, null, '读取 Vuex store(vnode.component)'); if (fromVnode) return fromVnode; return null; } function findPointCloud() { if (cache.points && cache.points.geometry) return cache.points; const viewer = cache.viewer; if (!viewer) return null; let best = null; let bestCount = -1; const consider = (obj) => { if (!obj || obj.isPoints !== true) return; const count = safe(() => obj.geometry.attributes.position.count, 0); if (count > bestCount) { best = obj; bestCount = count; } }; consider(safe(() => viewer.points, null)); const seen = new Set(); const stack = []; safe(() => { if (viewer.scene && Array.isArray(viewer.scene.children)) stack.push(...viewer.scene.children); }, null); let guard = 0; while (stack.length && guard < 600) { guard++; const obj = stack.pop(); if (!obj || seen.has(obj)) continue; seen.add(obj); consider(obj); if (Array.isArray(obj.children)) { for (const child of obj.children) stack.push(child); } } cache.points = best; return best; } function getRendererObj() { const viewer = cache.viewer; if (!viewer) return null; const candidates = []; safe(() => { if (viewer.render && typeof viewer.render === 'object') candidates.push(viewer.render); }, null); safe(() => { if (viewer.renderer && typeof viewer.renderer === 'object') candidates.push(viewer.renderer); }, null); safe(() => { if (viewer.rendererMain && typeof viewer.rendererMain === 'object') candidates.push(viewer.rendererMain); }, null); for (const item of candidates) { if (item && item.domElement) return item; } return null; } function findPickElement() { if (cache.pickElement && document.contains(cache.pickElement)) return cache.pickElement; const viewer = cache.viewer; if (!viewer) return null; const candidates = []; safe(() => { if (viewer.lineHandler && viewer.lineHandler.domElement) candidates.push(viewer.lineHandler.domElement); }, null); safe(() => { if (viewer.canvasContainer) candidates.push(viewer.canvasContainer); }, null); safe(() => { if (viewer.domElement) candidates.push(viewer.domElement); }, null); safe(() => { const r = getRendererObj(); if (r && r.domElement) candidates.push(r.domElement); }, null); for (const el of candidates) { if (el && typeof el.getBoundingClientRect === 'function' && document.contains(el)) { cache.pickElement = el; return el; } } return null; } function discover(force) { if (cache.discovering) return cache.lastInfo; const now = Date.now(); if (!force && cache.lastDiscoverAt && now - cache.lastDiscoverAt < 800) { return cache.lastInfo || buildInfo(); } cache.discovering = true; cache.lastDiscoverAt = now; cache.discoverCount++; try { cache.points = null; cache.pickElement = null; cache.viewer = getGlobalViewer(); cache.camera = safe(() => (cache.viewer ? cache.viewer.camera : null), null); cache.storeManager = getGlobalStoreManager(); cache.store = getVuexStore(); cache.lineHandler = safe(() => (cache.viewer ? cache.viewer.lineHandler : null), null); cache.points = findPointCloud(); findPickElement(); const info = buildInfo(); cache.lastInfo = info; const summary = [ `viewer=${info.hasViewer ? '✓' : '✗'}`, `camera=${info.hasCamera ? '✓' : '✗'}`, `画布=${info.hasPickElement ? '✓' : '✗'}`, `StoreManager=${info.hasStoreManager ? '✓' : '✗'}`, `点云=${info.hasPointCloud ? '✓' : '✗'}`, `拾取handler=${info.hasLineHandler ? '✓' : '✗'}`, ].join(' '); if (force || summary !== cache.lastSummary) { cache.lastSummary = summary; console.log(`${LOG} 平台发现:${summary}(模式:${info.mode})`); if (!cache.rectsLogged) { cache.rectsLogged = true; safe(() => { const a = (cache.viewer && cache.viewer.domElement) || (cache.viewer && cache.viewer.canvasContainer) || (getRendererObj() && getRendererObj().domElement); const b = cache.viewer && cache.viewer.canvasContainer; const ra = a && a.getBoundingClientRect ? a.getBoundingClientRect() : null; const rb = b && b.getBoundingClientRect ? b.getBoundingClientRect() : null; if (ra && rb) { console.log(`${LOG} 画布 rect:canvas=${Math.round(ra.left)},${Math.round(ra.top)},${Math.round(ra.width)}x${Math.round(ra.height)};canvasContainer=${Math.round(rb.left)},${Math.round(rb.top)},${Math.round(rb.width)}x${Math.round(rb.height)}`); } else if (ra) { console.log(`${LOG} 画布 rect:${Math.round(ra.left)},${Math.round(ra.top)},${Math.round(ra.width)}x${Math.round(ra.height)}`); } }, null); } } return info; } finally { cache.discovering = false; } } function computeMode() { const hasViewer = !!cache.viewer; const hasCamera = !!cache.camera; const hasSM = !!cache.storeManager; if (hasViewer && hasCamera && hasSM) return 'full'; if (hasViewer && hasCamera) return 'viewer'; return 'overlay'; } function readDisplayFrameId() { const sm = cache.storeManager; if (!sm || typeof sm.getDisplayFrameId !== 'function') return null; return safe(() => sm.getDisplayFrameId(), null, '读取显示帧 ID'); } function getDisplayFrameId() { if (!cache.discovering) discover(); return readDisplayFrameId(); } function computeMergedFrameInfo() { const sm = cache.storeManager; const st = safe(() => (sm && typeof sm.statusState === 'function' ? sm.statusState() : null), null); const cfg = safe(() => (sm && typeof sm.configState === 'function' ? sm.configState() : null), null); const params = safe(() => (window.instance && window.instance.params) || null, null); const frames = cfg && (cfg.frames || (cfg.config && cfg.config.frames)); const frameIds = cfg && cfg.frameIds; const frameCount = Array.isArray(frames) ? frames.length : (frameIds && typeof frameIds === 'object' ? Object.keys(frameIds).length : null); const dataType = String((params && params.data_type) || (cfg && cfg.config && cfg.config.data_type) || ''); const flag = !!(st && (st.isMergedFrameMode === true || st.mergedFrameMode === true)); const fusion = /fusion/i.test(dataType); const isMergedFrame = flag || (fusion && frameCount != null && frameCount > 1); return { isMergedFrame, known: flag || (frameCount != null && frameCount > 0) || fusion, displayFrameId: readDisplayFrameId(), curFrameId: readFrameId(), frameCount: frameCount, dataType, source: flag ? 'statusState' : (fusion ? 'config+params' : 'none'), }; } function getMergedFrameInfo() { if (!cache.discovering) discover(); return computeMergedFrameInfo(); } function buildInfo() { const merged = computeMergedFrameInfo(); return { mode: computeMode(), projectKind: getProjectInfo().kind, projectLabel: getProjectInfo().label, mergedFrame: merged, isMergedFrame: merged.isMergedFrame, displayFrameId: merged.displayFrameId, dataType: merged.dataType, frameId: readFrameId(), discoverCount: cache.discoverCount, hasViewer: !!cache.viewer, hasCamera: !!cache.camera, hasRenderer: !!getRendererObj(), hasPickElement: !!getCanvasRect(), hasStoreManager: !!cache.storeManager, hasStore: !!getVuexStore(), hasLineHandler: !!(cache.lineHandler && typeof cache.lineHandler.getMousePositionByEvent === 'function'), hasPointCloud: !!findPointCloud(), groundHeight: getGroundHeight(), linePointSize: num(safe(() => cache.storeManager.statusState().linePointSize, NaN), null), lineMinPointsNum: getLineMinPointsNum(), labelType: getLabelType(), curMarkTool: getCurMarkTool(), multiFrame: getMultiFrame(), pcdLoaded: getPcdLoaded(), errorCount: errors.length, }; } function getInfo() { if (!cache.discovering) discover(); return cache.lastInfo || buildInfo(); } function getModeText() { const mode = computeMode(); if (mode === 'full') return '平台模式:已连接(可测量、可读写标注)'; if (mode === 'viewer') return '只读模式:已发现点云视图,无法读写平台标注(可测量)'; return '覆盖层模式:未发现平台接口(仅面板/覆盖层可用)'; } function getProjectInfo() { let pathname = ''; try { pathname = String((typeof location !== 'undefined' && location && location.pathname) || ''); } catch (_) { pathname = ''; } const isMapCenterline = /\/map-pointcloud\//i.test(pathname) || /map-pointcloud/i.test(pathname); return { kind: isMapCenterline ? 'map-centerline' : 'pointcloud', label: isMapCenterline ? '地图中心线项目' : '点云标注项目', pathname, isMapCenterline, }; } function getViewer() { discover(); return cache.viewer; } function getCamera() { discover(); if (cache.camera) return cache.camera; (cache.viewer) && (cache.camera = safe(() => cache.viewer.camera, null)); return cache.camera; } function getStoreManager() { discover(); return cache.storeManager; } function getPickElement() { discover(); return findPickElement(); } function getCanvasRect() { const el = findPickElement(); if (!el) return null; const rect = safe(() => el.getBoundingClientRect(), null, '读取画布 rect'); if (!rect || !(rect.width > 0) || !(rect.height > 0)) { const fallback = safe(() => { if (cache.viewer && cache.viewer.domElement) return cache.viewer.domElement; const r = getRendererObj(); return r && r.domElement ? r.domElement : null; }, null); if (fallback && fallback !== el) { const r2 = safe(() => fallback.getBoundingClientRect(), null); if (r2 && r2.width > 0 && r2.height > 0) { return { left: r2.left, top: r2.top, width: r2.width, height: r2.height }; } } return null; } return { left: rect.left, top: rect.top, width: rect.width, height: rect.height }; } function getProjector() { const camera = getCamera(); if (!camera) return null; return safe(() => createProjector(camera), null, '构建相机投影器'); } function eventToLocal(event) { if (!event || !Number.isFinite(Number(event.clientX)) || !Number.isFinite(Number(event.clientY))) return null; const rect = getCanvasRect(); if (!rect) return null; const x = Number(event.clientX) - rect.left; const y = Number(event.clientY) - rect.top; return { x, y, rect }; } function isEventInsideViewer(event) { const el = getPickElement(); if (!el || !event || !event.target) return false; const target = event.target; try { return target === el || (typeof el.contains === 'function' && el.contains(target)); } catch (_) { return false; } } function statusState() { return safe(() => { const sm = cache.storeManager; return sm && typeof sm.statusState === 'function' ? sm.statusState() : null; }, null); } function getGroundHeight() { if (!cache.discovering && !cache.storeManager) discover(); const st = statusState(); const v = num(st && st.groundHeight, 0); return v; } function getLabelType() { const st = statusState(); if (!st) return null; const v = st.selectLabelType; return typeof v === 'string' ? v : null; } function getCurMarkTool() { const st = statusState(); if (!st) return null; const v = st.curMarkTool; return typeof v === 'string' ? v : null; } function getChooseState() { const st = statusState(); if (!st || !st.modeStatus || typeof st.modeStatus !== 'object') return null; const v = st.modeStatus.choose; if (v === undefined || v === null) return null; return !!v; } function getPcdLoaded() { const st = statusState(); if (!st || st.pcdLoaded === undefined || st.pcdLoaded === null) return null; return !!st.pcdLoaded; } function getMultiFrame() { const st = statusState(); if (!st) return null; const mf = st.multiFrame; if (mf === undefined || mf === null) return null; if (typeof mf === 'boolean' || typeof mf === 'number') return !!mf; if (typeof mf === 'object') { if (Array.isArray(mf.frameIds)) return mf.frameIds.length > 1 && mf.isMulti !== false; if (mf.frameIds && typeof mf.frameIds === 'object') return Object.keys(mf.frameIds).length > 1 && mf.isMulti !== false; if (mf.isMulti !== undefined) return !!mf.isMulti; } return !!mf; } function getActivationIssues(options = {}) { discover(); const issues = []; if (!cache.viewer) issues.push('未发现点云视图(window.viewer 不存在,页面可能尚未加载完成,请稍后重试)'); if (!cache.camera) issues.push('未发现可用相机,无法做 3D 投影'); if (!getCanvasRect()) issues.push('未发现点云画布位置(#canvas-container),无法把点击换算到 3D'); const labelType = getLabelType(); if (labelType && labelType !== 'mark') issues.push('当前处于语义分割等非标线模式,请先切换到标注/编辑模式'); if (getPcdLoaded() === false) issues.push('点云尚未加载完毕,请等待加载完成后再试'); if (options.forCenter && getMultiFrame() === true) issues.push('当前为多帧合并模式,生成中线前请先退出多帧'); return issues; } function ensureChooseMode() { const before = getChooseState(); if (before === null) return { ok: true, choose: null, switched: false, unknown: true }; if (before === true) return { ok: true, choose: true, switched: false }; const sm = getStoreManager(); if (!sm || typeof sm.statusCommit !== 'function') { return { ok: false, choose: before, switched: false, reason: '未发现平台 statusCommit,无法切换到选择模式' }; } safe(() => sm.statusCommit('modeStatus', 'choose'), null, '切换平台选择模式'); const after = getChooseState(); if (after === true) return { ok: true, choose: true, switched: true }; return { ok: false, choose: after, switched: false, reason: '平台仍处于绘制模式,请先按空格切到选择模式' }; } function restoreMode(wasChoose) { if (wasChoose !== false) return { ok: true, restored: false }; const current = getChooseState(); if (current !== true) return { ok: true, restored: false }; const sm = getStoreManager(); if (!sm || typeof sm.statusCommit !== 'function') return { ok: false, restored: false, reason: '未发现平台 statusCommit' }; safe(() => sm.statusCommit('modeStatus', 'choose'), null, '恢复平台绘制模式'); return { ok: true, restored: true }; } function isLinePainting() { const handler = cache.lineHandler || safe(() => (cache.viewer ? cache.viewer.lineHandler : null), null); if (!handler) return null; if (typeof handler.isStartedPainting === 'function') { return safe(() => !!handler.isStartedPainting(), null, 'lineHandler.isStartedPainting'); } if (typeof handler.isPainting === 'boolean') return handler.isPainting; return null; } function cancelLinePainting() { const handler = cache.lineHandler || safe(() => (cache.viewer ? cache.viewer.lineHandler : null), null); if (!handler) return { ok: false, reason: '未发现平台画线处理器(lineHandler)' }; const candidates = ['cancel', 'cancelPaint', 'stopPaint', 'stop']; for (const name of candidates) { if (typeof handler[name] === 'function') { const ok = safe(() => { handler[name](); return true; }, false, `lineHandler.${name}()`); if (ok) return { ok: true, method: name }; } } return { ok: false, reason: 'lineHandler 没有可用的取消画线方法' }; } function hardenInteractionMode() { if (!cache.discovering) discover(); const result = { ok: false, choose: getChooseState(), curMarkTool: getCurMarkTool(), painting: isLinePainting(), switched: false, cancelledPainting: false, retried: false, reason: '', }; const checkOk = () => (result.choose === true || result.choose === null) && result.painting !== true && (result.curMarkTool === 'choose' || result.curMarkTool === null); const cancelIfPainting = () => { if (isLinePainting() !== true) return; const cancelled = cancelLinePainting(); if (cancelled.ok) result.cancelledPainting = true; }; const refresh = () => { result.choose = getChooseState(); result.curMarkTool = getCurMarkTool(); result.painting = isLinePainting(); }; cancelIfPainting(); const first = ensureChooseMode(); if (first.switched) result.switched = true; cancelIfPainting(); refresh(); if (!checkOk()) { result.retried = true; const second = ensureChooseMode(); if (second.switched) result.switched = true; cancelIfPainting(); refresh(); } result.ok = checkOk(); if (!result.ok) { result.reason = `平台仍处于绘制状态(curMarkTool=${result.curMarkTool || '未知'}${result.painting === true ? ',画线未完成' : ''}),请按空格切到选择模式后重试`; } return result; } function readFrameId() { const sm = cache.storeManager; if (!sm || typeof sm.getCurFrameId !== 'function') return null; return safe(() => sm.getCurFrameId(), null, '读取当前帧 ID'); } function getFrameId() { if (!cache.discovering) discover(); return readFrameId(); } function colorToCss(color) { if (color === undefined || color === null) return null; if (typeof color === 'string') return color; if (typeof color === 'number' && Number.isFinite(color)) { return `#${(color & 0xffffff).toString(16).padStart(6, '0')}`; } if (typeof color === 'object') { if (typeof color.getHexString === 'function') return safe(() => `#${color.getHexString()}`, null); if (Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b)) { const to = (v) => Math.round(Math.max(0, Math.min(1, v)) * 255).toString(16).padStart(2, '0'); return `#${to(color.r)}${to(color.g)}${to(color.b)}`; } } return null; } function marksGetter(name, args) { const sm = getStoreManager(); if (!sm || typeof sm.marksGetter !== 'function') return null; return safe(() => { const getter = sm.marksGetter(name); if (typeof getter === 'function') return getter.apply(sm, args || []); return getter; }, null, `marksGetter(${name})`); } function getClassIdOf(trackId) { const raw = marksGetter('classId', [trackId]); if (raw == null) return ''; if (typeof raw === 'string' || typeof raw === 'number') return String(raw); if (typeof raw === 'object') { for (const key of ['pname', 'class', 'classId', 'name', 'id', 'label']) { if (raw[key] != null && raw[key] !== '') return String(raw[key]); } } return ''; } function getClassInfo(classId, type) { if (!classId) return null; const store = getVuexStore(); if (store && store.getters && typeof store.getters['config/getClass'] === 'function') { const def = safe(() => store.getters['config/getClass'](classId, type || 'line_3d'), null, 'getters[config/getClass]'); if (def && typeof def === 'object') return def; } const sm = cache.storeManager; if (!sm || typeof sm.configGetter !== 'function') return null; const raw = safe(() => { const getter = sm.configGetter('getClass'); if (typeof getter === 'function') return getter(classId, type); return getter; }, null, 'configGetter(getClass)'); return raw && typeof raw === 'object' ? raw : null; } function getMarkRecord(trackId) { const sm = cache.storeManager; if (!sm) return null; const marks = safe(() => (typeof sm.marksState === 'function' ? sm.marksState().marks : null), null, 'marksState().marks'); if (!marks || typeof marks !== 'object') return null; if (marks[trackId]) return marks[trackId]; if (marks[String(trackId)]) return marks[String(trackId)]; return null; } function isLineMark(mark) { if (!mark || typeof mark !== 'object') return false; const type = mark.type; const toolType = mark.toolType; if (type === 'line_3d') return true; if (toolType === 'line_3d') return true; return false; } function isRealLineMark(mark) { if (!isLineMark(mark)) return false; const vt = mark.visual_type; if (vt === undefined || vt === null) return true; return Number(vt) === 0; } function normalizeMarkPoints(mark) { if (!mark || typeof mark !== 'object') return []; let points = normalizePoints(mark.points); if (points.length < 2) points = normalizePoints(mark); return points; } function readFromStore() { const sm = getStoreManager(); if (!sm) { return { ok: false, source: 'store', reason: '未发现平台 StoreManager(页面可能未加载完成或未登录)', marks: [], frameId: null }; } const frameId = getFrameId(); if (frameId === null || frameId === undefined) { return { ok: false, source: 'store', reason: '未获取到当前帧 ID', marks: [], frameId: null }; } const marks = []; const seen = new Set(); let rawCount = 0; const pushMark = (trackId, mark, extraClass) => { if (!isRealLineMark(mark)) return; const key = String(trackId); if (seen.has(key)) return; const points = normalizeMarkPoints(mark); if (points.length < 2) return; seen.add(key); const classId = getClassIdOf(trackId) || (extraClass != null && extraClass !== '' ? String(extraClass) : '') || (mark.class != null ? String(mark.class) : ''); const cls = classId ? getClassInfo(classId, mark.type) : null; const color = (cls && (colorToCss(cls.color) || colorToCss(cls.class_color))) || null; const label = (cls && (cls.ptitle || cls.label || cls.title || cls.pname || cls.name || cls.class_name || cls.cn_name)) || classId || '线段'; marks.push({ source: 'store', id: String(trackId), trackId, type: mark.type || 'line_3d', classId, color, label: String(label), points, raw: mark, }); }; const frame = safe(() => sm.frameMarks(frameId), null, '读取 frameMarks'); const m3 = frame && (frame['3d'] || frame['3D'] || null); if (m3 && typeof m3 === 'object') { for (const trackId of Object.keys(m3)) { rawCount++; const rec = getMarkRecord(trackId); pushMark(trackId, m3[trackId], rec && rec.class); } } else { const stateMarks = safe(() => (typeof sm.marksState === 'function' ? sm.marksState().marks : null), null, '读取 marksState().marks'); if (stateMarks && typeof stateMarks === 'object') { for (const trackId of Object.keys(stateMarks)) { rawCount++; const rec = stateMarks[trackId]; const rec3d = rec && rec['3d']; const mark = rec3d && (rec3d[frameId] || rec3d[String(frameId)]); pushMark(trackId, mark, rec && rec.class); } } else if (!frame) { return { ok: false, source: 'store', reason: `当前帧(${frameId})没有可读取的标注数据`, marks: [], frameId }; } } return { ok: true, source: 'store', frameId, marks, reason: marks.length === 0 ? '当前帧没有线段标注(请先用平台「线段」工具绘制车道线)' : '', rawCount, }; } function readFromScene() { const viewer = getViewer(); if (!viewer) return { ok: false, source: 'scene', reason: '未发现点云视图', marks: [] }; const marks = []; const seen = new Set(); const visited = new Set(); const queue = []; safe(() => { if (viewer.lineScene && Array.isArray(viewer.lineScene.children)) queue.push(...viewer.lineScene.children); }, null); const visit = (obj) => { safe(() => { const mark = obj.mark || (obj.userData && obj.userData.mark) || null; if (mark && !isRealLineMark(mark)) return; let points = []; if (typeof obj.getPositions === 'function') { points = normalizePoints(safe(() => obj.getPositions(), null)); } if (points.length < 2 && typeof obj.getSpheresAndLines === 'function') { const pair = safe(() => obj.getSpheresAndLines(), null); const spheres = pair && pair[0]; if (Array.isArray(spheres)) { const arr = []; for (const s of spheres) { const pos = (s && s.position) ? s.position : s; if (pos && Number.isFinite(pos.x) && Number.isFinite(pos.y)) { arr.push({ x: pos.x, y: pos.y, z: Number.isFinite(pos.z) ? pos.z : 0 }); } } points = arr; } } if (points.length < 2 && mark) points = normalizeMarkPoints(mark); if (points.length < 2) return; const trackId = obj.trackId != null ? obj.trackId : (mark && mark.trackId != null ? mark.trackId : obj.id); const key = trackId != null ? String(trackId) : `scene-${marks.length}`; if (seen.has(key)) return; seen.add(key); const classId = obj.classId != null ? String(obj.classId) : (mark && mark.class != null ? String(mark.class) : ''); const color = colorToCss(obj.color) || null; const label = obj.className || obj.label || classId || '线段'; marks.push({ source: 'scene', id: key, trackId: trackId != null ? trackId : key, type: 'line_3d', classId, color, label: String(label), points, raw: mark, }); }, null); }; let guard = 0; while (queue.length && guard < 800) { guard++; const obj = queue.shift(); if (!obj || visited.has(obj) || obj.isSprite || obj.isMesh) continue; visited.add(obj); visit(obj); safe(() => { const children = obj.children; if (Array.isArray(children) && children.length && queue.length < 500) { for (const child of children) queue.push(child); } }, null); } return { ok: marks.length > 0, source: 'scene', frameId: getFrameId(), marks, reason: marks.length > 0 ? '' : '未从平台 StoreManager / 3D 场景中读取到线段标注', }; } function readLineMarks(options = {}) { const now = Date.now(); const force = options.force === true; if (!force && marksCache.result && now - marksCache.at < 500 && marksCache.frameId === getFrameId()) { return marksCache.result; } let result = readFromStore(); if (!result.ok || result.marks.length === 0) { const scene = readFromScene(); if (scene.ok && scene.marks.length > 0) { result = { ...scene, storeReason: result.reason || '' }; } else if (!result.ok) { result = { ...result, reason: result.reason || scene.reason, sceneReason: scene.reason }; } } marksCache = { at: now, frameId: getFrameId(), result }; return result; } function invalidateMarks() { marksCache = { at: 0, frameId: null, result: null }; } function getClassListForType(toolType = 'line_3d') { const cfg = safe(() => cache.storeManager.configState(), null, '读取 configState'); const classes = cfg && cfg.classes; if (!classes || typeof classes !== 'object') return []; let node = classes[toolType] || classes['line_3d'] || null; const buildFromMap = (obj) => Object.keys(obj).map((key) => { const item = obj[key]; const base = (item && typeof item === 'object') ? item : {}; return { pname: base.pname || base.classId || key, ...base }; }); let list = []; if (node) { if (Array.isArray(node)) list = node; else if (Array.isArray(node.class)) list = node.class; else if (Array.isArray(node.list)) list = node.list; else if (node.listClass && typeof node.listClass === 'object') list = buildFromMap(node.listClass); else if (node.class && typeof node.class === 'object') list = buildFromMap(node.class); } else if (classes.listClass && typeof classes.listClass === 'object') { list = buildFromMap(classes.listClass); } const out = []; const seen = new Set(); for (const item of list) { if (!item) continue; const pname = item.pname || item.classId || item.id || item.name; if (!pname || seen.has(String(pname))) continue; seen.add(String(pname)); out.push({ classId: String(pname), label: item.ptitle || item.label || item.title || item.name || String(pname), color: colorToCss(item.color) || null, }); } return out; } function getLineMinPointsNum() { const sm = cache.storeManager || getStoreManager(); if (!sm || typeof sm.configGetter !== 'function') return 2; const raw = safe(() => { const v = sm.configGetter('getLineMinPointsNum'); return typeof v === 'function' ? v() : v; }, null, 'configGetter(getLineMinPointsNum)'); const n = Math.round(Number(raw)); return Number.isFinite(n) && n >= 2 ? n : 2; } function isClassValidForLine(classId) { if (!classId) return false; const list = getClassListForType('line_3d'); if (list.length > 0) return list.some((c) => c.classId === String(classId)); const store = getVuexStore(); const getter = store && store.getters && store.getters['config/getClass']; if (typeof getter === 'function') { const def = safe(() => getter(classId, 'line_3d'), null, 'config/getClass 校验'); if (def) return true; } const def2 = getClassInfo(classId, 'line_3d'); if (def2) return true; return null; } function getClassOptions(marks) { const list = Array.isArray(marks) ? marks : []; const map = new Map(); for (const m of list) { const key = m.classId || ''; if (!map.has(key)) { map.set(key, { classId: key, label: m.label || key || '默认类别', color: m.color || null, count: 0 }); } map.get(key).count++; } for (const c of getClassListForType('line_3d')) { if (!map.has(c.classId)) { map.set(c.classId, { classId: c.classId, label: c.label || c.classId, color: c.color || null, count: 0 }); } } return Array.from(map.values()); } function toPlainPoint(v) { if (!v) return null; const x = Number(v.x), y = Number(v.y), z = Number(v.z); if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z)) return { x, y, z }; if (v.position) return toPlainPoint(v.position); return null; } function getPickThreshold() { let size = num(safe(() => cache.storeManager.statusState().linePointSize, NaN), NaN); if (!Number.isFinite(size) || size <= 0) size = 0.2; const threshold = Math.max(0.1, size); cache.pickThreshold = threshold; return threshold; } function pickPointCloudByRay(local) { const pointsObj = findPointCloud(); if (!pointsObj) return { ok: false, reason: '未发现点云对象' }; const projector = getProjector(); const rect = getCanvasRect(); if (!projector || !rect) return { ok: false, reason: '未发现相机/画布' }; const ray = safe(() => createRayFromLocal(projector, local.x, local.y, rect.width, rect.height), null, '构建点击射线'); if (!ray) return { ok: false, reason: '射线构建失败' }; const attr = safe(() => pointsObj.geometry && pointsObj.geometry.attributes && pointsObj.geometry.attributes.position, null); if (!attr || !(attr.count > 0)) return { ok: false, reason: '点云没有位置数据' }; let origin = ray.origin; let direction = ray.direction; let matrixWorld = null; let toWorld = null; const mw = safe(() => mat4FromElements(pointsObj.matrixWorld), null); if (mw) { const inv = safe(() => mat4Invert(mw), null); if (inv) { const o2 = safe(() => mat4TransformPoint(inv, ray.origin), null); const d2 = safe(() => normalizeVec(mat4TransformDirection(inv, ray.direction)), null); if (o2 && d2) { matrixWorld = mw; toWorld = (p) => { const w = mat4TransformPoint(mw, p); if (!w) return null; const k = Math.abs(w.w) > 1e-12 ? 1 / w.w : 1; return { x: w.x * k, y: w.y * k, z: w.z * k }; }; origin = o2; direction = d2; } } } const count = attr.count; const maxSample = 400000; const stride = Math.max(1, Math.ceil(count / maxSample)); const threshold = getPickThreshold(); const thresholdSq = threshold * threshold; let bestSq = thresholdSq; let bestIndex = -1; let bestS = 0; const arr = attr.array || attr.data; const ox = origin.x, oy = origin.y, oz = origin.z; const dx = direction.x, dy = direction.y, dz = direction.z; if (arr && arr.length >= count * 3) { for (let i = 0; i < count; i += stride) { const ix = i * 3; const vx = arr[ix] - ox; const vy = arr[ix + 1] - oy; const vz = arr[ix + 2] - oz; const s = vx * dx + vy * dy + vz * dz; if (s <= 0) continue; const px = vx - dx * s; const py = vy - dy * s; const pz = vz - dz * s; const d2 = px * px + py * py + pz * pz; if (d2 < bestSq) { bestSq = d2; bestIndex = i; bestS = s; } } } else if (typeof attr.getX === 'function') { for (let i = 0; i < count; i += stride) { const vx = attr.getX(i) - ox; const vy = attr.getY(i) - oy; const vz = attr.getZ(i) - oz; const s = vx * dx + vy * dy + vz * dz; if (s <= 0) continue; const px = vx - dx * s; const py = vy - dy * s; const pz = vz - dz * s; const d2 = px * px + py * py + pz * pz; if (d2 < bestSq) { bestSq = d2; bestIndex = i; bestS = s; } } } else { return { ok: false, reason: '点云位置属性格式不支持' }; } if (bestIndex < 0) return { ok: false, reason: `射线附近 ${threshold.toFixed(2)} 米内没有点云点` }; let point; if (arr && arr.length >= count * 3) { point = { x: arr[bestIndex * 3], y: arr[bestIndex * 3 + 1], z: arr[bestIndex * 3 + 2] }; } else { point = { x: attr.getX(bestIndex), y: attr.getY(bestIndex), z: attr.getZ(bestIndex) }; } if (toWorld) { const w = toWorld(point); if (w) point = w; } return { ok: true, point, distance: Math.sqrt(bestSq), s: bestS, threshold }; } function pickPointByEvent(event) { discover(); const rect = getCanvasRect(); if (!rect) return { ok: false, reason: '未发现点云画布(#canvas-container),无法计算 3D 坐标' }; const local = eventToLocal(event); if (!local) return { ok: false, reason: '无法把鼠标事件换算到画布坐标' }; const handler = cache.lineHandler; const ndc = localToNdc(local.x, local.y, rect.width, rect.height); if (handler) { safe(() => { if (typeof handler.setupRaycaster === 'function') handler.setupRaycaster(); }, null, 'lineHandler.setupRaycaster'); if (typeof handler.getPointPosition === 'function') { const p = toPlainPoint(safe(() => handler.getPointPosition(ndc), null, 'lineHandler.getPointPosition')); if (p) return { ok: true, point: p, source: '平台拾取(点云)', handler: true }; } if (typeof handler.getGroundPosition === 'function') { const g = toPlainPoint(safe(() => handler.getGroundPosition(ndc), null, 'lineHandler.getGroundPosition')); if (g) return { ok: true, point: g, source: '平台拾取(地面)', handler: true }; } } if (handler && typeof handler.getMousePositionByEvent === 'function') { const attempts = [ [{ clientX: Number(event.clientX), clientY: Number(event.clientY) }, true], [{ clientX: Number(event.clientX), clientY: Number(event.clientY) }, undefined], [event, true], [event, undefined], ]; for (const [arg, second] of attempts) { try { const v = second === undefined ? handler.getMousePositionByEvent(arg) : handler.getMousePositionByEvent(arg, second); const p = toPlainPoint(v); if (p) return { ok: true, point: p, source: '平台拾取', handler: true }; } catch (err) { recordError('平台拾取 getMousePositionByEvent', err); } } } const cloud = safe(() => pickPointCloudByRay(local), { ok: false, reason: '点云拾取异常' }, '点云射线拾取'); if (cloud && cloud.ok) return { ok: true, point: cloud.point, source: '点云拾取', cloud }; const projector = getProjector(); const ray = projector ? safe(() => createRayFromLocal(projector, local.x, local.y, rect.width, rect.height), null) : null; if (ray) { const gh = getGroundHeight(); const hit = safe(() => rayPlaneIntersect(ray, { x: 0, y: 0, z: gh }, { x: 0, y: 0, z: 1 }), null); if (hit) return { ok: true, point: hit.point, source: `地面平面(z=${gh.toFixed(2)})` }; const hit0 = safe(() => rayPlaneIntersect(ray, { x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 1 }), null); if (hit0) return { ok: true, point: hit0.point, source: '地面平面(z=0)' }; } const why = cloud && cloud.reason ? `(${cloud.reason})` : ''; return { ok: false, reason: `无法计算点击处 3D 坐标${why}` }; } function deepClone(obj) { if (obj === undefined || obj === null) return {}; try { return JSON.parse(JSON.stringify(obj)); } catch (err) { recordError('深拷贝源标注 attrs', err); return {}; } } function findSourceLineEntry(frameId, sourceTrackIds) { const sm = getStoreManager(); if (!sm) return null; let entries = []; const frame = safe(() => sm.frameMarks(frameId), null, '读取 frameMarks(写标注)'); const m3 = frame && (frame['3d'] || frame['3D']); if (m3 && typeof m3 === 'object') { entries = Object.keys(m3) .map((key) => [key, m3[key]]) .filter(([, mark]) => isRealLineMark(mark)); } if (entries.length === 0) { const stateMarks = safe(() => (typeof sm.marksState === 'function' ? sm.marksState().marks : null), null, '读取 marksState(写标注)'); if (stateMarks && typeof stateMarks === 'object') { for (const trackId of Object.keys(stateMarks)) { const rec = stateMarks[trackId]; const rec3d = rec && rec['3d']; const mark = rec3d && (rec3d[frameId] || rec3d[String(frameId)]); if (isRealLineMark(mark)) entries.push([trackId, mark]); } } } if (entries.length === 0) return null; const wanted = Array.isArray(sourceTrackIds) ? sourceTrackIds.map(String) : []; for (const [key, mark] of entries) { if (wanted.length === 0) break; const markTrack = mark && mark.trackId != null ? String(mark.trackId) : ''; if (wanted.includes(String(key)) || (markTrack && wanted.includes(markTrack))) { return { key, mark }; } } return { key: entries[0][0], mark: entries[0][1] }; } function getMarksGetterFn() { const sm = getStoreManager(); if (!sm || typeof sm.marksGetter !== 'function') return null; return safe(() => { const getter = sm.marksGetter('getMarks'); return typeof getter === 'function' ? getter : null; }, null, 'marksGetter(getMarks)'); } function isMarkLike(value) { return !!(value && typeof value === 'object' && (value.type === 'line_3d' || (Array.isArray(value.points) && value.points.length >= 2))); } function verifyMarkInStore(trackId, frameId) { const keys = [trackId, String(trackId), Number(trackId)].filter((v) => v !== null && v !== undefined && v === v); const sm = getStoreManager(); if (!sm) return null; const frame = safe(() => sm.frameMarks(frameId), null, '校验新标注 frameMarks'); const m3 = frame && (frame['3d'] || frame['3D']); if (m3 && typeof m3 === 'object') { for (const key of keys) { if (Object.prototype.hasOwnProperty.call(m3, key) && isMarkLike(m3[key])) return true; } } const getMarks = getMarksGetterFn(); if (!getMarks) return m3 ? false : null; for (const key of keys) { const res = safe(() => getMarks(key, '3d', frameId), null, '校验新标注 getMarks'); if (!res || typeof res !== 'object') continue; if (isMarkLike(res)) return true; const direct = res[key] !== undefined ? res[key] : res[String(key)]; if (isMarkLike(direct)) return true; } return false; } function isMarkRendered(trackId) { return safe(() => { const viewer = cache.viewer; const children = viewer && viewer.lineScene && viewer.lineScene.children; if (!Array.isArray(children)) return false; return children.some((obj) => { if (!obj) return false; const tid = obj.trackId != null ? obj.trackId : (obj.mark && obj.mark.trackId != null ? obj.mark.trackId : null); return tid != null && String(tid) === String(trackId); }); }, false, '检查新标注渲染'); } function buildCenterMarkPayload(centerPoints, options = {}) { if (!Array.isArray(centerPoints) || centerPoints.length < 2) { return { ok: false, reason: '中线点不足 2 个' }; } const frameId = getFrameId(); if (frameId === null || frameId === undefined) return { ok: false, reason: '未获取到当前帧 ID' }; const source = findSourceLineEntry(frameId, options.sourceTrackIds); const explicitClassId = options.classId != null && options.classId !== '' ? String(options.classId) : ''; let classId = ''; let attrs = null; let attrsFrom = 'none'; let sourceTrackId = null; let sourceClassId = ''; if (source) { sourceClassId = getClassIdOf(source.key) || (source.mark.class != null ? String(source.mark.class) : ''); classId = explicitClassId || sourceClassId; sourceTrackId = source.key; } else if (explicitClassId) { classId = explicitClassId; } else { return { ok: false, reason: '当前帧未找到线段标注,无法继承类别/属性;请先在面板选择类别' }; } if (!classId) return { ok: false, reason: '无法确定新标注的类别 ID(classId)' }; const classValid = isClassValidForLine(classId); if (classValid === false) { return { ok: false, reason: `类别「${classId}」不在平台线段类别配置中,已拒绝写入;请选择源线相同类别或在面板重新选择` }; } const crossClass = !!(sourceClassId && String(classId) !== String(sourceClassId)); if (!crossClass && source) { attrs = source.mark && source.mark.attrs ? deepClone(source.mark.attrs) : null; attrsFrom = 'source'; } else { attrs = {}; attrsFrom = 'empty'; } const payload = { type: 'line_3d', visual_type: 0, classId, attrs, points: centerPoints.map((p) => [p.x, p.y, p.z]), }; return { ok: true, payload, attrs, classId, sourceClassId, crossClass, attrsFrom, frameId, sourceTrackId, sourceMark: source ? source.mark : null, centerPointCount: centerPoints.length, }; } function writeCenterLine(centerPoints, options = {}) { if (!Array.isArray(centerPoints) || centerPoints.length < 2) { return { ok: false, reason: '中线点不足 2 个,无法写入平台' }; } discover(); const sm = getStoreManager(); if (!sm) return { ok: false, reason: '未发现平台 StoreManager,无法写入平台标注(可复制 JSON 手动创建)' }; if (typeof sm.markCommit !== 'function') { return { ok: false, reason: '平台 StoreManager.markCommit 不可用,无法写入标注' }; } if (getMultiFrame() === true) { return { ok: false, reason: '当前为多帧合并模式,禁止生成标注,请先退出多帧' }; } const frameId = getFrameId(); if (frameId === null || frameId === undefined) return { ok: false, reason: '未获取到当前帧 ID' }; const built = buildCenterMarkPayload(centerPoints, options); if (!built.ok) return { ok: false, reason: built.reason }; let trackId = marksGetter('avaliableTrackId'); if (typeof trackId === 'function') { trackId = safe(() => trackId(), null, '获取 avaliableTrackId'); } if (trackId === null || trackId === undefined || trackId === '') { return { ok: false, reason: '未获取到可用 trackId(avaliableTrackId 不可用)' }; } const newMark = { id: null, type: 'line_3d', visual_type: 0, point_num: 0, is_computed: 0, no_maps: null, attrs: built.attrs, points: centerPoints.map((p) => [p.x, p.y, p.z]), }; const commitArgs = [0, newMark, trackId, built.classId, frameId, null]; let commitError = null; try { sm.markCommit('addOrReplaceMark3D', commitArgs); } catch (err) { commitError = err; recordError('markCommit(addOrReplaceMark3D)', err); } if (commitError) { return { ok: false, reason: `写入平台标注失败:${commitError.message || commitError}`, payload: built.payload, commitArgs }; } const verified = verifyMarkInStore(trackId, frameId); invalidateMarks(); if (verified === false) { return { ok: false, reason: '写入后未在平台数据中查到新标注(可能被类别/属性校验拦截),已降级为覆盖层预览', trackId, payload: built.payload, }; } const rendered = isMarkRendered(trackId); if (!rendered) { safe(() => { if (cache.viewer && typeof cache.viewer.addMark === 'function') cache.viewer.addMark(newMark, trackId); }, null, '手动补建新标注渲染'); } safe(() => sm.selectMarkInfo(trackId, built.classId, '3d'), null, '选中新标注'); safe(() => { if (cache.viewer && typeof cache.viewer.rendererMain === 'function') cache.viewer.rendererMain(); }, null, '触发平台渲染'); console.log(`${LOG} 已写入平台标注:trackId=${trackId}, classId=${built.classId}, 点数=${centerPoints.length},已渲染=${rendered},跨类别=${built.crossClass},attrs来源=${built.attrsFrom}`); return { ok: true, reason: '', trackId, classId: built.classId, sourceClassId: built.sourceClassId, crossClass: built.crossClass, attrsFrom: built.attrsFrom, method: 'markCommit(addOrReplaceMark3D)', verified, rendered, payload: built.payload, frameId, commitArgs, }; } function syncMarks() { discover(); const sm = getStoreManager(); if (!sm) return { ok: false, reason: '未发现平台 StoreManager,无法触发保存' }; if (getMultiFrame() === true) return { ok: false, reason: '当前为多帧合并模式,平台禁止保存,请先退出多帧' }; const store = safe(() => (typeof sm.getStore === 'function' ? sm.getStore() : null), null, '获取平台 store'); if (!store || typeof store.dispatch !== 'function') { return { ok: false, reason: '未发现平台 Vuex store,无法立即保存(请在平台内按 Ctrl+S 保存)' }; } const run = async () => { await new Promise((resolve) => setTimeout(resolve, 0)); if (typeof store.commit === 'function') { try { store.commit('marks/syncLabelMeta'); } catch (err) { recordError('commit(marks/syncLabelMeta)', err); } try { store.commit('marks/changeGlobalVersion'); } catch (err) { recordError('commit(marks/changeGlobalVersion)', err); } } await new Promise((resolve) => setTimeout(resolve, 0)); const ret = await store.dispatch('marks/syncMarks'); return { code: ret, noChange: ret === 'CODE_NO_SAVE' }; }; const promise = run(); return { ok: true, pending: true, promise }; } function triggerSaveHotkey() { try { const ev = new KeyboardEvent('keydown', { key: 's', code: 'KeyS', keyCode: 83, which: 83, ctrlKey: true, bubbles: true, cancelable: true, }); document.dispatchEvent(ev); return { ok: true, method: '模拟 Ctrl+S' }; } catch (err) { recordError('模拟 Ctrl+S', err); return { ok: false, reason: `模拟 Ctrl+S 失败:${err.message || err}` }; } } function getDiagnostics() { return { info: getInfo(), modeText: getModeText(), pickThreshold: cache.pickThreshold, sourceSummary: cache.lastSummary, errors: errors.slice(), }; } function refresh() { invalidateMarks(); return discover(true); } return { discover, refresh, getInfo, getModeText, getProjectInfo, getMergedFrameInfo, getDisplayFrameId, getDiagnostics, getViewer, getCamera, getStoreManager, getPickElement, getCanvasRect, getProjector, eventToLocal, isEventInsideViewer, getGroundHeight, getFrameId, getLabelType, getCurMarkTool, getChooseState, getPcdLoaded, getMultiFrame, getActivationIssues, ensureChooseMode, restoreMode, hardenInteractionMode, isLinePainting, cancelLinePainting, readLineMarks, getClassOptions, getClassListForType, getLineMinPointsNum, isClassValidForLine, pickPointByEvent, buildCenterMarkPayload, writeCenterLine, syncMarks, triggerSaveHotkey, invalidateMarks, recordError, isReady() { discover(); return !!(cache.viewer && cache.camera && getCanvasRect()); }, }; } /* ==================== src/overlay.mjs ==================== */ function createOverlay(options = {}) { const getCamera = typeof options.getCamera === 'function' ? options.getCamera : () => null; const getRect = typeof options.getRect === 'function' ? options.getRect : () => null; const getHost = typeof options.getHost === 'function' ? options.getHost : () => document.body; const Z_INDEX = 2147483000; const MAX_DPR = 2; const EMPTY_SCENE = { lines: [], points: [], labels: [] }; let mounted = false; let active = false; let visible = true; let dirty = true; let rafId = 0; let lastSignature = ''; let container = null; let canvas = null; let ctx = null; let labelLayer = null; const labelEls = new Map(); let scene = { lines: [], points: [], labels: [] }; let lastDrawInfo = { width: 0, height: 0, lines: 0, points: 0, labels: 0, drawCount: 0 }; function mount() { if (mounted) return true; try { if (!document.body) return false; container = document.createElement('div'); container.id = 'lane-tool-overlay'; container.setAttribute('data-lane-tool', 'overlay'); container.style.cssText = [ 'position:fixed', 'left:0', 'top:0', 'width:0', 'height:0', 'pointer-events:none', 'overflow:hidden', `z-index:${Z_INDEX}`, 'contain:layout style', ].join(';'); canvas = document.createElement('canvas'); canvas.style.cssText = 'position:absolute;left:0;top:0;pointer-events:none;display:block;'; ctx = canvas.getContext('2d'); labelLayer = document.createElement('div'); labelLayer.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none;overflow:hidden;'; container.appendChild(canvas); container.appendChild(labelLayer); getHost().appendChild(container); mounted = true; dirty = true; return true; } catch (err) { console.error('[车道线工具] 覆盖层挂载失败:', err); mounted = false; return false; } } function unmount() { stopLoop(); try { if (container && container.parentNode) container.parentNode.removeChild(container); } catch (err) { console.warn('[车道线工具] 覆盖层卸载异常:', err); } container = null; canvas = null; ctx = null; labelLayer = null; labelEls.clear(); mounted = false; lastSignature = ''; } function startLoop() { if (!mounted || rafId) return; rafId = requestAnimationFrame(tick); } function stopLoop() { if (rafId) { try { cancelAnimationFrame(rafId); } catch (_) { /* 忽略 */ } rafId = 0; } } function tick() { rafId = 0; if (!active || !mounted) return; rafId = requestAnimationFrame(tick); try { if (document.hidden) return; const signature = computeSignature(); if (!dirty && signature === lastSignature) return; lastSignature = signature; dirty = false; draw(); } catch (err) { console.warn('[车道线工具] 覆盖层绘制异常:', err); } } function computeSignature() { try { const rect = safeRect(); if (!rect) return 'no-rect'; const camera = getCamera(); let view = ''; let proj = ''; if (camera) { const mv = camera.matrixWorldInverse && camera.matrixWorldInverse.elements; const pm = camera.projectionMatrix && camera.projectionMatrix.elements; if (mv) view = Array.prototype.join.call(mv, ','); if (pm) proj = Array.prototype.join.call(pm, ','); const mw = camera.matrixWorld && camera.matrixWorld.elements; if (mw) proj += '|' + Array.prototype.join.call(mw, ','); } return `${rect.left.toFixed(2)},${rect.top.toFixed(2)},${rect.width.toFixed(2)},${rect.height.toFixed(2)},${view},${proj}`; } catch (_) { return 'sig-error'; } } function safeRect() { try { const rect = getRect(); if (!rect) return null; if (!(rect.width > 0) || !(rect.height > 0)) return null; if (!Number.isFinite(rect.left) || !Number.isFinite(rect.top)) return null; return rect; } catch (_) { return null; } } function safeCamera() { try { const camera = getCamera(); return (camera && typeof camera === 'object') ? camera : null; } catch (_) { return null; } } function getProjectorSafe() { const camera = safeCamera(); if (!camera) return null; try { return createProjector(camera); } catch (err) { console.warn('[车道线工具] 相机投影器构建失败:', err); return null; } } function syncCanvas(rect) { const dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR); container.style.left = `${rect.left}px`; container.style.top = `${rect.top}px`; container.style.width = `${rect.width}px`; container.style.height = `${rect.height}px`; const pxWidth = Math.max(1, Math.round(rect.width * dpr)); const pxHeight = Math.max(1, Math.round(rect.height * dpr)); if (canvas.width !== pxWidth || canvas.height !== pxHeight) { canvas.width = pxWidth; canvas.height = pxHeight; } canvas.style.width = `${rect.width}px`; canvas.style.height = `${rect.height}px`; if (ctx && typeof ctx.setTransform === 'function') ctx.setTransform(dpr, 0, 0, dpr, 0, 0); return dpr; } function draw() { if (!mounted || !ctx) return; const rect = safeRect(); if (!rect) { if (container) container.style.display = 'none'; hideAllLabels(); return; } if (container) container.style.display = visible ? '' : 'none'; if (!visible) { hideAllLabels(); return; } syncCanvas(rect); ctx.clearRect(0, 0, rect.width, rect.height); const projector = getProjectorSafe(); if (!projector) { hideAllLabels(); return; } let lineCount = 0; let pointCount = 0; let labelCount = 0; for (const line of scene.lines) { if (drawPolyline(line, projector, rect)) lineCount++; } for (const item of scene.points) { if (drawPoint(item, projector, rect)) pointCount++; } labelCount = renderLabels(scene.labels, projector, rect); lastDrawInfo = { width: rect.width, height: rect.height, lines: lineCount, points: pointCount, labels: labelCount, drawCount: lastDrawInfo.drawCount + 1, }; } function drawPolyline(line, projector, rect) { const pts = line && Array.isArray(line.points) ? line.points : null; if (!pts || pts.length === 0) return false; const screen = []; for (const p of pts) { const proj = projectWorldToLocal(projector, p, rect.width, rect.height); screen.push(proj && !proj.behind ? proj : null); } const segments = []; let current = []; for (const s of screen) { if (s) current.push(s); else if (current.length) { segments.push(current); current = []; } } if (current.length) segments.push(current); if (segments.length === 0) return false; const color = line.color || '#00e5ff'; const width = Number.isFinite(line.width) ? line.width : 2.5; const opacity = Number.isFinite(line.opacity) ? line.opacity : 1; const dash = Array.isArray(line.dash) && line.dash.length ? line.dash : null; const halo = line.halo !== false; const haloColor = typeof line.haloColor === 'string' && line.haloColor ? line.haloColor : 'rgba(0,0,0,0.72)'; ctx.save(); ctx.globalAlpha = opacity; ctx.lineCap = 'round'; ctx.lineJoin = 'round'; for (const seg of segments) { drawSegmentPath(seg, null); if (halo) { ctx.strokeStyle = haloColor; ctx.lineWidth = width + 3; ctx.setLineDash([]); ctx.stroke(); } drawSegmentPath(seg, dash); ctx.strokeStyle = color; ctx.lineWidth = width; ctx.stroke(); } for (const seg of segments) { if (seg.length === 1) { ctx.beginPath(); ctx.arc(seg[0].x, seg[0].y, width + 1, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); } } ctx.restore(); return true; } function drawSegmentPath(seg, dash) { ctx.beginPath(); if (seg.length === 1) return; ctx.moveTo(seg[0].x, seg[0].y); for (let i = 1; i < seg.length; i++) ctx.lineTo(seg[i].x, seg[i].y); ctx.setLineDash(dash || []); } function drawPoint(item, projector, rect) { if (!item || !item.point) return false; const proj = projectWorldToLocal(projector, item.point, rect.width, rect.height); if (!proj || proj.behind) return false; const color = item.color || '#4dd0e1'; const radius = Number.isFinite(item.radius) ? item.radius : 4; ctx.save(); if (item.halo !== false) { ctx.beginPath(); ctx.arc(proj.x, proj.y, radius + 2, 0, Math.PI * 2); ctx.fillStyle = 'rgba(0,0,0,0.75)'; ctx.fill(); } ctx.beginPath(); ctx.arc(proj.x, proj.y, radius, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.strokeStyle = 'rgba(255,255,255,0.85)'; ctx.lineWidth = 1; ctx.stroke(); ctx.restore(); return true; } function sanitizeCssColor(value) { if (typeof value !== 'string') return ''; const s = value.trim(); if (!s || s.length > 80) return ''; return /^[#a-zA-Z0-9(),.%\s-]+$/.test(s) ? s : ''; } function escapeLabelText(text) { return String(text == null ? '' : text) .replace(/&/g, '&') .replace(//g, '>'); } function renderLabels(labels, projector, rect) { if (!labelLayer) return 0; const list = Array.isArray(labels) ? labels : []; const seen = new Set(); let count = 0; for (let i = 0; i < list.length; i++) { const label = list[i]; if (!label || !label.text) continue; const key = label.id != null ? String(label.id) : `idx${i}`; seen.add(key); let el = labelEls.get(key); if (!el) { el = document.createElement('div'); el.setAttribute('data-lane-tool', 'label'); el.style.cssText = [ 'position:absolute', 'left:0', 'top:0', 'pointer-events:none', 'white-space:nowrap', 'font-size:12px', 'line-height:16px', 'font-family:"Microsoft YaHei",system-ui,-apple-system,sans-serif', 'padding:1px 6px', 'border-radius:4px', 'background:rgba(15,23,42,0.82)', 'color:#fff', 'border:1px solid rgba(255,255,255,0.28)', 'text-shadow:0 1px 2px rgba(0,0,0,0.8)', 'will-change:transform', 'box-shadow:0 1px 4px rgba(0,0,0,0.45)', ].join(';'); labelLayer.appendChild(el); labelEls.set(key, el); } const proj = label.point ? projectWorldToLocal(projector, label.point, rect.width, rect.height) : null; if (!proj || proj.behind) { el.style.display = 'none'; continue; } const offsetX = Number.isFinite(label.offsetX) ? label.offsetX : 0; const offsetY = Number.isFinite(label.offsetY) ? label.offsetY : 0; const x = proj.x + offsetX; const y = proj.y + offsetY; if (x < -120 || y < -60 || x > rect.width + 120 || y > rect.height + 60) { el.style.display = 'none'; continue; } const dotColor = sanitizeCssColor(label.dotColor); const contentKey = `${dotColor}|${label.text}`; if (el._laneContentKey !== contentKey) { el._laneContentKey = contentKey; if (dotColor) { el.innerHTML = '` + `${escapeLabelText(label.text)}`; } else { el.textContent = label.text; } } el.style.display = ''; if (label.color) el.style.color = label.color; if (label.bg) el.style.background = label.bg; if (label.border) el.style.borderColor = label.border; el.style.transform = `translate(-50%,-50%) translate(${x}px,${y}px)`; count++; } for (const [key, el] of labelEls) { if (!seen.has(key)) el.style.display = 'none'; } return count; } function hideAllLabels() { for (const el of labelEls.values()) el.style.display = 'none'; } function clearCanvas() { try { hideAllLabels(); if (ctx && canvas) { ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.restore(); } lastSignature = ''; dirty = true; lastDrawInfo = { ...lastDrawInfo, lines: 0, points: 0, labels: 0 }; } catch (err) { console.warn('[车道线工具] 覆盖层清屏异常:', err); } } function setScene(next) { if (next && typeof next === 'object') { scene = { lines: Array.isArray(next.lines) ? next.lines : [], points: Array.isArray(next.points) ? next.points : [], labels: Array.isArray(next.labels) ? next.labels : [], }; } else { scene = { lines: [], points: [], labels: [] }; } dirty = true; } function clearScene() { scene = { lines: [], points: [], labels: [] }; dirty = true; clearCanvas(); } function setActive(value) { const next = !!value; if (active === next) { if (next) { dirty = true; startLoop(); } return; } active = next; if (active) { mount(); startLoop(); } else { stopLoop(); clearCanvas(); } dirty = true; } function setVisible(value) { visible = !!value; dirty = true; if (container) container.style.display = visible ? '' : 'none'; if (!visible) { hideAllLabels(); clearCanvas(); } } function requestDraw() { dirty = true; } function getScreenPoint(world) { try { const rect = safeRect(); if (!rect) return null; const projector = getProjectorSafe(); if (!projector) return null; return projectWorldToLocal(projector, world, rect.width, rect.height); } catch (_) { return null; } } function getState() { return { mounted, active, visible, dirty, sceneCounts: { lines: scene.lines.length, points: scene.points.length, labels: scene.labels.length }, lastDrawInfo: { ...lastDrawInfo }, }; } function getScene() { return { lines: scene.lines.slice(), points: scene.points.slice(), labels: scene.labels.slice(), }; } return { mount, unmount, setScene, clearScene, setActive, setVisible, requestDraw, getScreenPoint, getState, getScene, clearCanvas, isMounted: () => mounted, isActive: () => active, }; } /* ==================== src/ui.mjs ==================== */ function bootstrapLaneTool() { const LOG = '[车道线工具]'; const VERSION = TOOL_VERSION; const STORAGE_KEY = 'lane-tool-ui-v1'; const PICK_PX = 14; const AUTO_PICK_PX = 320; const CLICK_MOVE_PX = 5; try { if (window.__LANE_TOOL__ && window.__LANE_TOOL__.ui) return; } catch (_) { /* 忽略 */ } if (!document.body) { setTimeout(() => { try { bootstrapLaneTool(); } catch (err) { console.error(`${LOG} 延迟初始化失败:`, err); } }, 300); return; } const platform = createPlatform(); const overlay = createOverlay({ getCamera: () => platform.getCamera(), getRect: () => platform.getCanvasRect(), }); const state = { tool: 'idle', phase: '', panelHidden: false, collapsed: false, overlayVisible: true, referenceLine: null, measurePair: [], measureResult: null, measureMode: 'horizontal', lines: [], centerResult: null, classOptions: [], centerClassId: '', classSuggestion: null, manualClassByProject: {}, classAttrNote: '', projectInfo: null, centerAutoCount: true, centerPointCount: 8, generated: null, writeError: '', saveState: 'idle', saveError: '', onlyPreview: false, autoSave: false, modeWasChoose: null, lastMarks: null, pickSource: '', lastActivationIssues: [], toastSeq: 0, settings: { left: null, top: null }, }; const dom = {}; function escapeHtml(text) { return String(text == null ? '' : text) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function loadSettings() { try { const raw = localStorage.getItem(STORAGE_KEY); if (!raw) return; const saved = JSON.parse(raw); if (!saved || typeof saved !== 'object') return; state.panelHidden = !!saved.panelHidden; state.collapsed = !!saved.collapsed; if (typeof saved.overlayVisible === 'boolean') state.overlayVisible = saved.overlayVisible; if (typeof saved.onlyPreview === 'boolean') state.onlyPreview = saved.onlyPreview; if (typeof saved.autoSave === 'boolean') state.autoSave = saved.autoSave; if (typeof saved.centerAutoCount === 'boolean') state.centerAutoCount = saved.centerAutoCount; if (Number.isFinite(saved.centerPointCount)) state.centerPointCount = saved.centerPointCount; if (saved.measureMode === '3d' || saved.measureMode === 'horizontal') state.measureMode = saved.measureMode; if (saved.centerClassManualByProject && typeof saved.centerClassManualByProject === 'object') { state.manualClassByProject = { ...saved.centerClassManualByProject }; } if (Number.isFinite(saved.left) && Number.isFinite(saved.top)) { state.settings.left = saved.left; state.settings.top = saved.top; } } catch (err) { console.warn(`${LOG} 读取面板设置失败:`, err); } } function saveSettings() { try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ panelHidden: state.panelHidden, collapsed: state.collapsed, overlayVisible: state.overlayVisible, onlyPreview: state.onlyPreview, autoSave: state.autoSave, centerAutoCount: state.centerAutoCount, centerPointCount: state.centerPointCount, measureMode: state.measureMode, centerClassManualByProject: state.manualClassByProject, left: state.settings.left, top: state.settings.top, })); } catch (err) { console.warn(`${LOG} 保存面板设置失败:`, err); } } function getProjectKind() { try { const info = platform.getProjectInfo(); return info && info.kind ? info.kind : 'pointcloud'; } catch (_) { return 'pointcloud'; } } function getManualClassId() { const kind = getProjectKind(); const v = state.manualClassByProject && state.manualClassByProject[kind]; return v != null && v !== '' ? String(v) : ''; } function setManualClassId(classId) { const kind = getProjectKind(); if (!state.manualClassByProject || typeof state.manualClassByProject !== 'object') state.manualClassByProject = {}; if (classId) state.manualClassByProject[kind] = String(classId); else delete state.manualClassByProject[kind]; saveSettings(); } function refreshProject() { try { const info = platform.getProjectInfo(); state.projectInfo = info; if (dom.project) { const extra = info.isMapCenterline ? '(生成目标类别通常为「车道中心线」)' : ''; dom.project.textContent = `当前项目:${info.label}${extra}`; } const merged = platform.getMergedFrameInfo(); if (dom.mergedHint) { if (merged && merged.isMergedFrame) { const display = merged.displayFrameId != null ? merged.displayFrameId : '与标注帧相同'; const count = merged.frameCount != null ? merged.frameCount : '?'; dom.mergedHint.style.display = ''; dom.mergedHint.textContent = `合并帧模式:写入帧键=当前标注帧(${merged.curFrameId}) · 显示帧=${display} · 帧数=${count}`; } else { dom.mergedHint.style.display = 'none'; dom.mergedHint.textContent = ''; } } } catch (err) { console.warn(`${LOG} 刷新项目信息失败:`, err); } } const CSS_TEXT = ` #lane-tool-panel{position:fixed;z-index:2147483001;right:16px;top:72px;width:330px;box-sizing:border-box; background:rgba(17,24,39,.95);color:#e5e7eb;border:1px solid rgba(148,163,184,.45);border-radius:10px; box-shadow:0 10px 30px rgba(0,0,0,.5);font-family:"Microsoft YaHei",system-ui,-apple-system,sans-serif; font-size:12px;line-height:1.55;user-select:none;-webkit-user-select:none;text-align:left} #lane-tool-panel *{box-sizing:border-box} #lane-tool-panel.lt-collapsed .lt-body{display:none} #lane-tool-panel.lt-hidden{display:none} #lane-tool-panel .lt-header{display:flex;align-items:center;justify-content:space-between;padding:7px 10px; cursor:move;border-bottom:1px solid rgba(148,163,184,.3);border-radius:10px 10px 0 0; background:linear-gradient(180deg,rgba(37,99,235,.4),rgba(37,99,235,.12))} #lane-tool-panel .lt-title{font-size:13px;font-weight:700;color:#f8fafc;letter-spacing:.4px} #lane-tool-panel .lt-header-btns{display:flex;gap:6px} #lane-tool-panel .lt-icon-btn{width:20px;height:20px;line-height:16px;text-align:center;padding:0; background:rgba(255,255,255,.08);color:#e5e7eb;border:1px solid rgba(255,255,255,.2);border-radius:4px; cursor:pointer;font-size:12px;font-family:inherit} #lane-tool-panel .lt-icon-btn:hover{background:rgba(255,255,255,.22)} #lane-tool-panel .lt-body{padding:9px 10px 8px;max-height:calc(100vh - 120px);overflow-y:auto} #lane-tool-panel .lt-status{padding:5px 8px;margin-bottom:8px;border-radius:6px;font-size:11px; background:rgba(15,23,42,.85);border:1px solid rgba(148,163,184,.35);color:#cbd5e1} #lane-tool-panel .lt-status.lt-good{border-color:rgba(74,222,128,.65);color:#86efac} #lane-tool-panel .lt-status.lt-warn{border-color:rgba(251,191,36,.7);color:#fcd34d} #lane-tool-panel .lt-row{display:flex;gap:6px;flex-wrap:wrap;align-items:center;margin-bottom:7px} #lane-tool-panel .lt-btn{flex:1 1 auto;min-width:64px;padding:5px 8px;background:rgba(255,255,255,.07); color:#e5e7eb;border:1px solid rgba(148,163,184,.45);border-radius:6px;cursor:pointer; font-size:12px;font-family:inherit;line-height:1.4} #lane-tool-panel .lt-btn:hover:not(:disabled){background:rgba(96,165,250,.22);border-color:#60a5fa} #lane-tool-panel .lt-btn.lt-active{background:rgba(37,99,235,.8);border-color:#93c5fd;color:#fff;font-weight:700} #lane-tool-panel .lt-btn.lt-primary{background:rgba(22,163,74,.85);border-color:#4ade80;color:#fff;font-weight:700} #lane-tool-panel .lt-btn.lt-primary:hover:not(:disabled){background:rgba(22,163,74,1)} #lane-tool-panel .lt-btn:disabled{opacity:.45;cursor:not-allowed} #lane-tool-panel .lt-section{border-top:1px dashed rgba(148,163,184,.3);padding-top:6px;margin-top:6px} #lane-tool-panel .lt-hint{margin:3px 0;color:#cbd5e1;min-height:16px} #lane-tool-panel .lt-hint.lt-hint-warn{color:#fca5a5} #lane-tool-panel .lt-result{margin:4px 0;padding:6px 8px;background:rgba(30,41,59,.75);border-radius:6px; border-left:3px solid #38bdf8} #lane-tool-panel .lt-result .lt-big{font-size:16px;font-weight:700;color:#67e8f9} #lane-tool-panel .lt-result .lt-sub{color:#94a3b8;font-size:11px;margin-top:1px} #lane-tool-panel .lt-row label{display:flex;align-items:center;gap:4px;color:#cbd5e1;cursor:pointer;font-size:11px} #lane-tool-panel input[type=checkbox]{accent-color:#3b82f6;margin:0;cursor:pointer} #lane-tool-panel .lt-select{flex:1;min-width:120px;background:#0f172a;color:#e5e7eb;border:1px solid rgba(148,163,184,.45); border-radius:5px;padding:3px 4px;font-size:11px;font-family:inherit} #lane-tool-panel .lt-num{width:72px;background:#0f172a;color:#e5e7eb;border:1px solid rgba(148,163,184,.45); border-radius:5px;padding:3px 4px;font-size:12px;font-family:inherit} #lane-tool-panel .lt-num:disabled{opacity:.45;cursor:not-allowed} #lane-tool-panel .lt-footer{margin-top:6px;padding-top:6px;border-top:1px solid rgba(148,163,184,.25); color:#94a3b8;font-size:10px;display:flex;justify-content:space-between;gap:6px} #lane-tool-panel .lt-kbd{color:#93c5fd} #lane-tool-toast{position:fixed;z-index:2147483002;left:50%;bottom:76px;transform:translateX(-50%); display:flex;flex-direction:column;gap:6px;align-items:center;pointer-events:none} #lane-tool-toast .lt-toast{max-width:560px;padding:7px 14px;border-radius:6px;background:rgba(15,23,42,.95); color:#f1f5f9;border:1px solid rgba(96,165,250,.75);box-shadow:0 6px 18px rgba(0,0,0,.5); font-family:"Microsoft YaHei",system-ui,-apple-system,sans-serif;font-size:12px;line-height:1.5; transition:opacity .25s;text-align:left} #lane-tool-toast .lt-toast.lt-toast-error{border-color:#f87171;color:#fecaca} #lane-tool-toast .lt-toast.lt-toast-ok{border-color:#4ade80;color:#bbf7d0} `; const PANEL_HTML = `
车道线测距与中线生成
正在检测平台接口…
当前项目:检测中…
工具一:点「测距」后,点击一条车道线作为基准线。
测量方式:
工具二:点「中线」后,依次点击两条车道线;或在两线中间点一下自动取两侧最近两条。
类别:
生成点数: 点
快捷键:Alt+M 测距 · Alt+N 中线 · Esc 取消 · Alt+H 面板
`; function injectStyle() { if (document.getElementById('lane-tool-style')) return; try { const style = document.createElement('style'); style.id = 'lane-tool-style'; style.textContent = CSS_TEXT; (document.head || document.documentElement).appendChild(style); } catch (err) { console.warn(`${LOG} 注入样式失败:`, err); } } function mountPanel() { injectStyle(); if (document.getElementById('lane-tool-panel')) return; try { const panel = document.createElement('div'); panel.id = 'lane-tool-panel'; panel.setAttribute('data-lane-tool', 'panel'); panel.innerHTML = PANEL_HTML; document.body.appendChild(panel); dom.panel = panel; dom.status = panel.querySelector('#lt-status'); dom.project = panel.querySelector('#lt-project'); dom.mergedHint = panel.querySelector('#lt-merged'); dom.modeShort = panel.querySelector('#lt-mode-short'); dom.btnMeasure = panel.querySelector('#lt-btn-measure'); dom.btnCenter = panel.querySelector('#lt-btn-center'); dom.btnClear = panel.querySelector('#lt-btn-clear'); dom.btnCancel = panel.querySelector('#lt-btn-cancel'); dom.chkOverlay = panel.querySelector('#lt-chk-overlay'); dom.pickSource = panel.querySelector('#lt-pick-source'); dom.measureHint = panel.querySelector('#lt-measure-hint'); dom.measureResult = panel.querySelector('#lt-measure-result'); dom.measureMode = panel.querySelector('#lt-measure-mode'); dom.centerHint = panel.querySelector('#lt-center-hint'); dom.centerInfo = panel.querySelector('#lt-center-info'); dom.centerClass = panel.querySelector('#lt-center-class'); dom.chkAutoCount = panel.querySelector('#lt-chk-auto-count'); dom.numCount = panel.querySelector('#lt-center-count'); dom.countHint = panel.querySelector('#lt-count-hint'); dom.chkPreview = panel.querySelector('#lt-chk-preview'); dom.chkAutoSave = panel.querySelector('#lt-chk-autosave'); dom.btnGenerate = panel.querySelector('#lt-btn-generate'); dom.btnSave = panel.querySelector('#lt-btn-save'); dom.btnCopy = panel.querySelector('#lt-btn-copy'); dom.centerStatus = panel.querySelector('#lt-center-status'); dom.chkOverlay.checked = state.overlayVisible; dom.measureMode.value = state.measureMode; dom.chkAutoCount.checked = state.centerAutoCount; dom.numCount.value = String(state.centerPointCount); dom.numCount.disabled = state.centerAutoCount; dom.chkPreview.checked = state.onlyPreview; dom.chkAutoSave.checked = state.autoSave; if (state.panelHidden) panel.classList.add('lt-hidden'); if (state.collapsed) { panel.classList.add('lt-collapsed'); const btn = panel.querySelector('[data-act="collapse"]'); if (btn) btn.textContent = '▸'; } applySavedPosition(); bindPanelEvents(); bindDrag(); } catch (err) { console.error(`${LOG} 面板挂载失败:`, err); } } function applySavedPosition() { if (!dom.panel) return; if (Number.isFinite(state.settings.left) && Number.isFinite(state.settings.top)) { dom.panel.style.left = `${state.settings.left}px`; dom.panel.style.top = `${state.settings.top}px`; dom.panel.style.right = 'auto'; } } function mountToastLayer() { if (document.getElementById('lane-tool-toast')) return; try { const layer = document.createElement('div'); layer.id = 'lane-tool-toast'; layer.setAttribute('data-lane-tool', 'toast'); document.body.appendChild(layer); dom.toastLayer = layer; } catch (err) { console.warn(`${LOG} 提示层挂载失败:`, err); } } function toast(message, type = 'info', duration = 2800) { try { if (!dom.toastLayer) mountToastLayer(); if (!dom.toastLayer) return; const item = document.createElement('div'); item.className = `lt-toast${type === 'error' ? ' lt-toast-error' : (type === 'ok' ? ' lt-toast-ok' : '')}`; item.textContent = String(message); item.setAttribute('data-lane-tool', 'toast-item'); dom.toastLayer.appendChild(item); state.toastSeq++; while (dom.toastLayer.children.length > 4) dom.toastLayer.removeChild(dom.toastLayer.firstChild); setTimeout(() => { try { item.style.opacity = '0'; setTimeout(() => { try { if (item.parentNode) item.parentNode.removeChild(item); } catch (_) { /* 忽略 */ } }, 260); } catch (_) { /* 忽略 */ } }, Math.max(1200, duration)); } catch (err) { console.warn(`${LOG} 提示显示失败:`, err); } } function bindPanelEvents() { try { dom.btnMeasure.addEventListener('click', (ev) => { ev.stopPropagation(); toggleTool('measure'); }); dom.btnCenter.addEventListener('click', (ev) => { ev.stopPropagation(); toggleTool('center'); }); dom.btnClear.addEventListener('click', (ev) => { ev.stopPropagation(); clearAll(true); }); dom.btnCancel.addEventListener('click', (ev) => { ev.stopPropagation(); exitTool(); }); dom.btnGenerate.addEventListener('click', (ev) => { ev.stopPropagation(); generateCenter(); }); dom.btnSave.addEventListener('click', (ev) => { ev.stopPropagation(); doSyncSave(false); }); dom.btnCopy.addEventListener('click', (ev) => { ev.stopPropagation(); copyCenterJson(); }); dom.chkOverlay.addEventListener('change', () => { state.overlayVisible = !!dom.chkOverlay.checked; applyOverlayState(); saveSettings(); }); dom.chkPreview.addEventListener('change', () => { state.onlyPreview = !!dom.chkPreview.checked; saveSettings(); refreshPanel(); }); dom.chkAutoSave.addEventListener('change', () => { state.autoSave = !!dom.chkAutoSave.checked; saveSettings(); }); dom.measureMode.addEventListener('change', () => { state.measureMode = dom.measureMode.value === '3d' ? '3d' : 'horizontal'; saveSettings(); refreshAll(); const tip = state.measureMode === '3d' ? '测量方式:三维最短距离(含高度差)' : '测量方式:水平投影(车道宽度,忽略高度差)'; toast(tip, 'info', 2600); }); dom.centerClass.addEventListener('change', () => { state.centerClassId = dom.centerClass.value || ''; setManualClassId(state.centerClassId); const opt = (state.classOptions || []).find((o) => String(o.classId) === String(state.centerClassId)); state.classSuggestion = { classId: state.centerClassId, label: opt ? (opt.label || state.centerClassId) : state.centerClassId, reason: 'manual', auto: false, crossSource: !!(state.lines[0] && state.lines[0].classId && String(state.lines[0].classId) !== String(state.centerClassId)), }; toast(`目标类别已手动选择:${state.classSuggestion.label}`, 'info', 2600); refreshPanel(); }); dom.chkAutoCount.addEventListener('change', () => { state.centerAutoCount = !!dom.chkAutoCount.checked; dom.numCount.disabled = state.centerAutoCount; saveSettings(); if (state.centerResult && state.lines.length === 2) recomputeCenterPreview(); refreshPanel(); }); dom.numCount.addEventListener('input', () => { schedulePointCountApply(); }); dom.numCount.addEventListener('change', () => { applyPointCountInput(false); }); dom.numCount.addEventListener('keydown', (ev) => { ev.stopPropagation(); if (ev.key === 'Enter') { ev.preventDefault(); applyPointCountInput(true); } }); dom.panel.addEventListener('click', (ev) => { const act = ev.target && ev.target.getAttribute ? ev.target.getAttribute('data-act') : null; if (!act) return; ev.stopPropagation(); if (act === 'collapse') { state.collapsed = !state.collapsed; dom.panel.classList.toggle('lt-collapsed', state.collapsed); ev.target.textContent = state.collapsed ? '▸' : '▾'; saveSettings(); } else if (act === 'hide') { state.panelHidden = true; dom.panel.classList.add('lt-hidden'); saveSettings(); toast('面板已隐藏,按 Alt+H 重新显示', 'info', 3200); } else if (act === 'clear') { clearAll(true); } else if (act === 'cancel') { exitTool(); } }); } catch (err) { console.error(`${LOG} 绑定面板事件失败:`, err); } } function bindDrag() { if (!dom.panel) return; const header = dom.panel.querySelector('[data-lane-tool="header"]'); if (!header) return; let dragging = false; let startX = 0; let startY = 0; let originLeft = 0; let originTop = 0; const onMove = (ev) => { if (!dragging) return; let left = originLeft + (ev.clientX - startX); let top = originTop + (ev.clientY - startY); const rect = dom.panel.getBoundingClientRect(); const maxLeft = Math.max(0, window.innerWidth - rect.width); const maxTop = Math.max(0, window.innerHeight - rect.height); left = Math.min(Math.max(0, left), maxLeft); top = Math.min(Math.max(0, top), maxTop); dom.panel.style.left = `${left}px`; dom.panel.style.top = `${top}px`; dom.panel.style.right = 'auto'; state.settings.left = left; state.settings.top = top; }; const onUp = () => { if (!dragging) return; dragging = false; document.removeEventListener('mousemove', onMove, true); document.removeEventListener('mouseup', onUp, true); saveSettings(); }; header.addEventListener('mousedown', (ev) => { if (ev.button !== 0) return; const target = ev.target; if (target && target.closest && target.closest('button')) return; let rect; try { rect = dom.panel.getBoundingClientRect(); } catch (_) { return; } dragging = true; startX = ev.clientX; startY = ev.clientY; originLeft = rect.left; originTop = rect.top; dom.panel.style.left = `${rect.left}px`; dom.panel.style.top = `${rect.top}px`; dom.panel.style.right = 'auto'; document.addEventListener('mousemove', onMove, true); document.addEventListener('mouseup', onUp, true); ev.preventDefault(); ev.stopPropagation(); }); } function isTypingTarget(target) { if (!target || !target.tagName) return false; const tag = String(target.tagName).toUpperCase(); if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true; if (target.isContentEditable) return true; return false; } function isToolActive() { return state.tool !== 'idle'; } function waitingForClick() { if (state.tool === 'idle') return false; return ['pickRef', 'points', 'pick1', 'pick2'].includes(state.phase); } function clearSelectionState() { state.phase = ''; state.referenceLine = null; state.measurePair = []; state.measureResult = null; state.lines = []; state.centerResult = null; state.classOptions = []; state.centerClassId = ''; state.classSuggestion = null; state.classAttrNote = ''; state.generated = null; state.writeError = ''; state.saveState = 'idle'; state.saveError = ''; state.pickSource = ''; } function clearAll(verbose) { clearSelectionState(); if (isToolActive()) { state.phase = state.tool === 'measure' ? 'pickRef' : 'pick1'; } applyOverlayState(); refreshPanel(); if (verbose && !isToolActive()) toast('已清除测量/预览'); } function exitTool(options = {}) { const wasActive = isToolActive(); removeMouseCapture(); state.tool = 'idle'; clearSelectionState(); try { if (state.modeWasChoose !== null) platform.restoreMode(state.modeWasChoose); } catch (err) { console.warn(`${LOG} 恢复平台模式失败:`, err); } state.modeWasChoose = null; try { overlay.setActive(false); overlay.clearScene(); overlay.setVisible(state.overlayVisible); } catch (err) { console.warn(`${LOG} 关闭覆盖层失败:`, err); } refreshPanel(); if (wasActive && !options.silent) toast('已退出工具(测量结果已清除)', 'info'); } function toggleTool(tool) { if (isToolActive() && state.tool === tool) { exitTool(); return; } if (isToolActive()) exitTool({ silent: true }); activateTool(tool); } function activateTool(tool) { try { platform.refresh(); const issues = platform.getActivationIssues(); state.lastActivationIssues = issues; if (issues.length > 0) { issues.slice(0, 4).forEach((msg) => toast(msg, 'error', 4200)); console.warn(`${LOG} 工具激活被阻止:${issues.join(';')}`); refreshPanel(); return; } state.modeWasChoose = platform.getChooseState(); if (state.modeWasChoose === null) { if (platform.getStoreManager()) { toast('无法确认平台模式(modeStatus 不可用),请先按空格切到编辑/选择模式,再激活工具', 'error', 4600); state.modeWasChoose = null; refreshPanel(); return; } toast('无法确认平台模式,请确保平台处于编辑/选择模式后再点击,避免误画线', 'error', 4600); } let harden; if (typeof platform.hardenInteractionMode === 'function') { harden = platform.hardenInteractionMode(); } else { const chooseResult = platform.ensureChooseMode(); harden = { ok: chooseResult.ok, switched: chooseResult.switched, cancelledPainting: false, reason: chooseResult.reason || '', }; } if (!harden.ok) { state.modeWasChoose = null; toast(harden.reason || '平台当前处于绘制模式,请先按空格切到选择模式', 'error', 4600); refreshPanel(); return; } if (harden.cancelledPainting) toast('已取消平台当前未完成的画线', 'info', 3600); if (harden.switched) console.log(`${LOG} 已把平台切换到选择模式(避免误画线),退出时会恢复`); const multiFrame = platform.getMultiFrame(); state.tool = tool; if (tool === 'measure') { state.phase = 'pickRef'; toast('测距:请点击一条车道线作为基准线(Esc 退出)', 'info', 3600); } else { state.phase = 'pick1'; toast('中线:请依次点击两条车道线;或在两线中间点一下自动取两侧最近两条', 'info', 4000); if (multiFrame === true) toast('注意:当前为多帧合并模式,生成中线会被禁止', 'error', 4200); } installMouseCapture(); applyOverlayState(); refreshPanel(); console.log(`${LOG} 已激活${tool === 'measure' ? '测距' : '中线'}工具`); } catch (err) { console.error(`${LOG} 激活工具异常:`, err); toast('激活工具失败,请查看控制台诊断', 'error'); exitTool({ silent: true }); } } function applyOverlayState() { try { const active = isToolActive() && state.overlayVisible; overlay.setVisible(state.overlayVisible); if (active) { overlay.setScene(buildScene()); overlay.setActive(true); overlay.requestDraw(); } else { overlay.setActive(false); overlay.clearScene(); } } catch (err) { console.warn(`${LOG} 更新覆盖层失败:`, err); } } function refreshAll() { applyOverlayState(); refreshPanel(); } let mouseCaptureInstalled = false; let downInfo = null; let suppressClickUntil = 0; function isOurUIEvent(ev) { const target = ev && ev.target; if (!target || typeof target.closest !== 'function') return false; try { return !!target.closest('[data-lane-tool]'); } catch (_) { return false; } } function shouldBlockPlatformMouse(ev) { if (!waitingForClick()) return false; if (!ev || isOurUIEvent(ev)) return false; return platform.isEventInsideViewer(ev); } function onMouseDownCapture(ev) { if (!shouldBlockPlatformMouse(ev)) return; if (ev.button === 0) downInfo = { x: ev.clientX, y: ev.clientY, at: Date.now() }; try { ev.stopPropagation(); } catch (_) { /* 忽略 */ } } function onMouseMoveCapture(ev) { if (!shouldBlockPlatformMouse(ev)) return; try { ev.stopPropagation(); } catch (_) { /* 忽略 */ } } function onMouseUpCapture(ev) { if (!shouldBlockPlatformMouse(ev)) { downInfo = null; return; } try { ev.stopPropagation(); } catch (_) { /* 忽略 */ } if (ev.button !== 0) { downInfo = null; return; } const info = downInfo; downInfo = null; if (!info) return; const moved = Math.hypot(ev.clientX - info.x, ev.clientY - info.y); if (moved > CLICK_MOVE_PX) return; try { ev.preventDefault(); } catch (_) { /* 忽略 */ } suppressClickUntil = (typeof performance !== 'undefined' ? performance.now() : Date.now()) + 400; handleCanvasClick(ev); } function onClickCapture(ev) { if (!shouldBlockPlatformMouse(ev)) return; try { ev.stopPropagation(); ev.preventDefault(); } catch (_) { /* 忽略 */ } const now = typeof performance !== 'undefined' ? performance.now() : Date.now(); if (now < suppressClickUntil) return; handleCanvasClick(ev); } function onDblClickCapture(ev) { if (!shouldBlockPlatformMouse(ev)) return; try { ev.stopPropagation(); ev.preventDefault(); } catch (_) { /* 忽略 */ } } function installMouseCapture() { if (mouseCaptureInstalled) return; try { window.addEventListener('mousedown', onMouseDownCapture, true); window.addEventListener('mousemove', onMouseMoveCapture, true); window.addEventListener('mouseup', onMouseUpCapture, true); window.addEventListener('click', onClickCapture, true); window.addEventListener('dblclick', onDblClickCapture, true); mouseCaptureInstalled = true; } catch (err) { console.warn(`${LOG} 安装鼠标捕获失败:`, err); } } function removeMouseCapture() { if (!mouseCaptureInstalled) return; try { window.removeEventListener('mousedown', onMouseDownCapture, true); window.removeEventListener('mousemove', onMouseMoveCapture, true); window.removeEventListener('mouseup', onMouseUpCapture, true); window.removeEventListener('click', onClickCapture, true); window.removeEventListener('dblclick', onDblClickCapture, true); } catch (err) { console.warn(`${LOG} 移除鼠标捕获失败:`, err); } mouseCaptureInstalled = false; downInfo = null; suppressClickUntil = 0; } function handleCanvasClick(ev) { if (!waitingForClick()) return; try { const chooseResult = platform.ensureChooseMode(); if (!chooseResult.ok) { toast(chooseResult.reason || '平台处于绘制模式,已忽略本次点击(可先按空格切到选择模式)', 'error', 4000); return; } if (chooseResult.switched) toast('平台被切回绘制模式,已自动恢复选择模式(避免误画线)', 'error', 3200); const local = platform.eventToLocal(ev); if (!local) { toast('无法获取画布坐标,请确认点云视图已加载', 'error'); return; } if (state.tool === 'measure') { handleMeasureClick(ev, local); } else if (state.tool === 'center') { handleCenterClick(ev, local); } } catch (err) { console.error(`${LOG} 处理画布点击异常:`, err); toast('点击处理异常,请查看控制台', 'error'); } } function loadLineMarks() { const data = platform.readLineMarks({ force: true }); state.lastMarks = data; return data; } function pickLineAt(localX, localY, maxPx) { const data = loadLineMarks(); if (!data || !data.ok || !Array.isArray(data.marks) || data.marks.length === 0) { return { ok: false, reason: (data && data.reason) || '未读取到平台车道线标注(请先用平台「线段」工具绘制)', data }; } const projector = platform.getProjector(); const rect = platform.getCanvasRect(); if (!projector || !rect) return { ok: false, reason: '无法投影车道线(相机/画布不可用)', data }; const hit = pickPolylineByScreen(data.marks, localX, localY, projector, rect.width, rect.height, maxPx || PICK_PX); if (!hit) return { ok: false, reason: '未点中车道线,请靠近线条再点', data }; return { ok: true, line: hit.line, data, distPx: hit.distPx }; } function fmtSigned(v) { const n = Number(v); if (!Number.isFinite(n)) return '--'; return `${n >= 0 ? '+' : '-'}${Math.abs(n).toFixed(2)}`; } function is3DMode() { return state.measureMode === '3d'; } function measureValue(m) { if (!m) return NaN; return is3DMode() ? m.dist3D : m.distXY; } function handleMeasureClick(ev, local) { if (state.phase === 'pickRef') { const hit = pickLineAt(local.x, local.y, PICK_PX); if (!hit.ok) { toast(hit.reason, 'error', 3200); return; } state.referenceLine = hit.line; state.phase = 'points'; state.measurePair = []; state.measureResult = null; state.lastMarks = hit.data; state.pickSource = ''; toast(`已选基准线(ID ${hit.line.id},${hit.line.points.length} 个点)。请在车道线两侧各点一下`, 'ok', 3600); refreshAll(); return; } if (state.phase !== 'points') return; const pick = platform.pickPointByEvent(ev); if (!pick.ok) { toast(pick.reason, 'error', 3400); return; } state.pickSource = pick.source; const m = measureToPolyline(pick.point, state.referenceLine.points); if (!m) { toast('计算点到基准线的距离失败', 'error'); return; } if (!is3DMode() && Math.abs(m.dz) > 0.3) { toast(`点击点与车道线高度差 ${fmt2(Math.abs(m.dz))} 米,已按水平投影测量(可能点到了高于路面的物体)`, 'error', 4600); } if (state.measurePair.length >= 2) { state.measurePair = []; state.measureResult = null; } state.measurePair.push({ point: pick.point, m, source: pick.source }); if (state.measurePair.length === 2) { const a = state.measurePair[0]; const b = state.measurePair[1]; const summary = summarizeMeasure(state.referenceLine.points, a.point, b.point); if (!summary) { toast('测宽计算失败', 'error'); } else { state.measureResult = summary; const main = is3DMode() ? summary.width3d : summary.width; const modeText = is3DMode() ? '三维最短距离' : '水平投影'; const widthText = summary.opposite ? `宽度 ${fmt2(main)} 米(异侧相加)` : `同侧间距 ${fmt2(main)} 米(|A-B|)`; toast(`测量完成(${modeText}):A ${fmt2(measureValue(a.m))} 米 · B ${fmt2(measureValue(b.m))} 米 · ${widthText}`, 'ok', 4800); console.log(`${LOG} 测量[${modeText}]:A=${measureValue(a.m).toFixed(3)}m(${a.m.sideText}, dz=${fmtSigned(a.m.dz)}), B=${measureValue(b.m).toFixed(3)}m(${b.m.sideText}, dz=${fmtSigned(b.m.dz)}), 宽度=${main.toFixed(3)}m;水平=${summary.width.toFixed(3)}m,3D=${summary.width3d.toFixed(3)}m`); } } else { const modeText = is3DMode() ? '三维距离' : '水平距离'; toast(`已记录第 1 点(${m.sideText},${modeText} ${fmt2(measureValue(m))} 米)。请在另一侧点一下`, 'info', 3200); } refreshAll(); } function handleCenterClick(ev, local) { if (state.phase === 'pick1' || state.phase === 'pick2') { const hit = pickLineAt(local.x, local.y, PICK_PX); if (hit.ok) { if (state.phase === 'pick1') { state.lines = [hit.line]; state.lastMarks = hit.data; state.phase = 'pick2'; toast(`已选第 1 条线(ID ${hit.line.id},${hit.line.points.length} 点)。请再点第 2 条车道线`, 'ok', 3400); refreshAll(); return; } if (String(hit.line.id) === String(state.lines[0].id)) { toast('第 2 条线不能与第 1 条相同,请点另一条车道线', 'error', 3200); return; } state.lastMarks = hit.data; setCenterPreview(state.lines[0], hit.line); return; } if (state.phase === 'pick1') { const pair = pickTwoLinesAround(local.x, local.y); if (pair.ok) { state.lastMarks = pair.data; setCenterPreview(pair.left, pair.right); return; } toast(`${hit.reason};也可以在两线中间点一下自动取两侧最近两条(${pair.reason || '未找到合适的两条线'})`, 'error', 4200); return; } toast(hit.reason, 'error', 3200); } } function pickTwoLinesAround(localX, localY) { const data = loadLineMarks(); if (!data || !data.ok || !Array.isArray(data.marks) || data.marks.length < 2) { return { ok: false, reason: (data && data.reason) || '车道线数量不足 2 条', data }; } const projector = platform.getProjector(); const rect = platform.getCanvasRect(); if (!projector || !rect) return { ok: false, reason: '相机/画布不可用', data }; let left = null; let right = null; for (const line of data.marks) { const pts = line.points; if (!Array.isArray(pts) || pts.length < 2) continue; const projected = []; for (const p of pts) { projected.push(projectWorldToLocal(projector, p, rect.width, rect.height)); } let best = null; for (let i = 0; i + 1 < projected.length; i++) { const s0 = projected[i]; const s1 = projected[i + 1]; if (!s0 || !s1 || s0.behind || s1.behind) continue; const hit = screenDistanceToSegment(localX, localY, s0.x, s0.y, s1.x, s1.y); if (!best || hit.dist < best.distPx) best = { distPx: hit.dist, footX: hit.x }; } if (!best || best.distPx > AUTO_PICK_PX) continue; const candidate = { line, distPx: best.distPx, footX: best.footX }; if (best.footX <= localX) { if (!left || candidate.distPx < left.distPx) left = candidate; } else if (!right || candidate.distPx < right.distPx) { right = candidate; } } if (!left || !right) { return { ok: false, reason: left || right ? '点击点左右未同时找到车道线' : '附近没有可用的车道线', data }; } if (String(left.line.id) === String(right.line.id)) { return { ok: false, reason: '两侧取到了同一条线', data }; } return { ok: true, left: left.line, right: right.line, data }; } let pointCountTimer = 0; function getMinPointCount() { const n = Number(platform.getLineMinPointsNum()); return Number.isFinite(n) && n >= 2 ? Math.round(n) : 2; } function getRequestedPointCount() { return state.centerAutoCount ? null : state.centerPointCount; } function schedulePointCountApply() { if (pointCountTimer) clearTimeout(pointCountTimer); pointCountTimer = setTimeout(() => { pointCountTimer = 0; applyPointCountInput(false); }, 200); } function applyPointCountInput(force) { if (pointCountTimer) { clearTimeout(pointCountTimer); pointCountTimer = 0; } if (!dom.numCount) return; const minN = getMinPointCount(); const maxN = 500; const raw = String(dom.numCount.value == null ? '' : dom.numCount.value).trim(); let num = Number(raw); let needNormalize = false; if (!Number.isFinite(num)) { toast(`生成点数需为 ${minN}~${maxN} 的整数,已回退到最近合法值`, 'error', 3200); num = state.centerPointCount; needNormalize = true; } else { const rounded = Math.round(num); if (rounded !== num) { toast('生成点数需为整数,已四舍五入', 'error', 3000); num = rounded; needNormalize = true; } if (num < minN) { toast(`生成点数不能小于平台线段最小点数 ${minN},已自动调整`, 'error', 3200); num = minN; needNormalize = true; } else if (num > maxN) { toast(`生成点数过多,已限制为 ${maxN} 点`, 'error', 3200); num = maxN; needNormalize = true; } } if (!Number.isFinite(num)) num = minN; if (needNormalize) dom.numCount.value = String(num); const changed = state.centerPointCount !== num; state.centerPointCount = num; if (state.centerAutoCount) return; if (changed || force) { saveSettings(); if (state.centerResult && state.lines.length === 2) recomputeCenterPreview(); } } function recomputeCenterPreview() { if (!state.lines || state.lines.length !== 2) return; const result = buildCenterLine(state.lines[0].points, state.lines[1].points, { pointCount: getRequestedPointCount(), minPoints: getMinPointCount(), }); if (!result || result.ok === false) { toast(`中线计算失败:${(result && result.reason) || '未知原因'}`, 'error', 3800); return; } state.centerResult = result; state.generated = null; state.writeError = ''; state.saveState = 'idle'; state.saveError = ''; if (state.phase !== 'writing') state.phase = 'preview'; refreshAll(); } function setCenterPreview(lineA, lineB) { const result = buildCenterLine(lineA.points, lineB.points, { pointCount: getRequestedPointCount(), minPoints: getMinPointCount(), }); if (!result || result.ok === false) { toast(`中线计算失败:${(result && result.reason) || '未知原因'}`, 'error', 3800); return; } state.lines = [lineA, lineB]; state.centerResult = result; state.phase = 'preview'; state.generated = null; state.writeError = ''; state.saveState = 'idle'; state.saveError = ''; const marks = (state.lastMarks && state.lastMarks.marks) || []; const options = platform.getClassOptions(marks.concat(marks.length ? [] : [lineA, lineB])); state.classOptions = options; let fallbackClassId = ''; if (lineA.classId && lineB.classId && String(lineA.classId) === String(lineB.classId)) fallbackClassId = lineA.classId; else fallbackClassId = lineA.classId || lineB.classId || (options[0] && options[0].classId) || ''; const suggestion = suggestTargetClass(options, lineA.classId, lineB.classId, { manualClassId: getManualClassId() }); state.classSuggestion = suggestion; state.centerClassId = suggestion.classId || fallbackClassId; if (!state.classSuggestion.classId) { state.classSuggestion = { classId: state.centerClassId, label: state.centerClassId || '未知', reason: 'fallback', auto: true, crossSource: false, }; } const clsText = String(lineA.classId) === String(lineB.classId) ? `同类别 ${fallbackClassId || '未知'}` : `类别不同:${lineA.classId || '无'} / ${lineB.classId || '无'}`; const targetText = `目标类别:${state.classSuggestion.label || state.centerClassId || '未知'}(${state.classSuggestion.auto === false ? '手动选择' : '自动建议'})`; const sourceText = result.resampled ? '已按弧长重采样' : '点数相同直接对应'; const countText = state.centerAutoCount ? `自动 ${result.effectiveN} 点(取较多线)` : `手动 ${result.effectiveN} 点`; toast(`中线预览:${result.n} 点 / ${fmt2(result.length)} 米(${countText},${sourceText})${result.reversed ? ',已自动反转方向' : ''}`, 'ok', 5200); console.log(`${LOG} 中线:线1 ${lineA.points.length} 点 ${fmt2(result.rawLengths[0])} 米,线2 ${lineB.points.length} 点 ${fmt2(result.rawLengths[1])} 米,中线 ${result.n} 点 ${fmt2(result.length)} 米(${countText});${clsText};${targetText}(reason=${state.classSuggestion.reason})`); refreshAll(); } function generateCenter() { if (!state.centerResult || state.centerResult.ok === false) { toast('请先选择两条车道线生成预览', 'error'); return; } if (platform.getMultiFrame() === true) { toast('当前为多帧合并模式,禁止生成标注,请先退出多帧', 'error', 4200); return; } if (state.onlyPreview) { state.phase = 'done'; state.writeError = ''; toast('仅预览模式:未写入平台。可点「复制 JSON」手动在平台创建', 'info', 4200); refreshAll(); return; } if (!state.centerClassId) { toast('未确定新标注类别(classId),请在上方类别下拉选择', 'error', 3600); return; } state.phase = 'writing'; refreshAll(); const payload = { sourceTrackIds: state.lines.map((l) => l.id), classId: state.centerClassId, }; const result = platform.writeCenterLine(state.centerResult.points, payload); if (result.ok) { state.generated = { trackId: result.trackId, classId: result.classId, at: Date.now() }; state.writeError = ''; state.phase = 'done'; state.classAttrNote = ''; if (result.crossClass || result.attrsFrom === 'empty') { state.classAttrNote = '已生成,请在平台中由标注人员补充该类别属性(提交前需补全)'; toast(state.classAttrNote, 'info', 5600); } toast(`已写入平台标注(ID ${result.trackId},类别 ${result.classId})。请按 Ctrl+S 或点平台「保存」完成持久化`, 'ok', 5200); console.log(`${LOG} 生成成功:trackId=${result.trackId}, classId=${result.classId}, 跨类别=${result.crossClass}, attrs来源=${result.attrsFrom}, 方法=${result.method}`); if (state.autoSave) doSyncSave(true); } else { state.generated = null; state.writeError = result.reason || '写入平台失败'; state.phase = 'preview'; toast(`写入平台失败:${state.writeError}。已保留覆盖层预览,可点「复制 JSON」手动创建`, 'error', 6000); console.warn(`${LOG} 生成写入失败:${state.writeError}`); } refreshAll(); } function doSyncSave(auto) { if (!state.generated) { toast('还没有成功写入平台的中线标注', 'error'); return; } state.saveState = 'saving'; state.saveError = ''; refreshPanel(); const result = platform.syncMarks(); if (!result.ok) { state.saveState = 'error'; state.saveError = result.reason || '保存失败'; toast(`保存失败:${state.saveError}`, 'error', 4600); refreshPanel(); return; } if (result.pending && result.promise && typeof result.promise.then === 'function') { let timedOut = false; const timeoutPromise = new Promise((resolve) => { setTimeout(() => { timedOut = true; resolve({ __timeout: true }); }, 30000); }); result.promise.catch(() => { /* 超时后不再重复提示,避免未处理 rejection */ }); Promise.race([result.promise, timeoutPromise]).then((res) => { if (timedOut || (res && res.__timeout)) { state.saveState = 'error'; state.saveError = '保存请求超时(可能未登录、鉴权失败或网络不可达;也可回到平台内按 Ctrl+S 观察提示)'; toast(state.saveError, 'error', 6000); refreshPanel(); return; } state.saveState = 'saved'; if (res && res.noChange) { toast('平台数据已是最新,无需保存(CODE_NO_SAVE)', 'ok', 3600); } else { toast(auto ? '已自动执行平台保存(含 label_meta 同步)' : '平台保存请求已完成(含 label_meta 同步)', 'ok', 3600); } refreshPanel(); }).catch((err) => { state.saveState = 'error'; const msg = (err && (err.msg || err.message)) || String(err); const hint = /401|403|授权|鉴权|token|auth/i.test(msg) ? '(可能未登录或鉴权失败,可先在平台内登录/按 Ctrl+S)' : ''; state.saveError = msg; toast(`保存失败:${msg}${hint}`, 'error', 5400); refreshPanel(); }); return; } state.saveState = 'saved'; toast(auto ? '已自动执行平台保存' : '平台保存请求已发送', 'ok', 3600); refreshPanel(); } function copyCenterJson() { if (!state.centerResult || !state.centerResult.points) { toast('还没有可复制的中线预览', 'error'); return; } let payload = null; try { const built = platform.buildCenterMarkPayload(state.centerResult.points, { sourceTrackIds: state.lines.map((l) => l.id), classId: state.centerClassId, }); if (built && built.ok) payload = built.payload; } catch (err) { console.warn(`${LOG} 构造 JSON 失败:`, err); } if (!payload) { payload = { type: 'line_3d', visual_type: 0, class_id: state.centerClassId || '', points: state.centerResult.points.map((p) => [ Number(p.x.toFixed(6)), Number(p.y.toFixed(6)), Number(p.z.toFixed(6)), ]), }; } const text = JSON.stringify(payload, null, 2); console.log(`${LOG} 中线 JSON:\n${text}`); copyToClipboard(text).then((ok) => { toast(ok ? '中线 JSON 已复制到剪贴板' : '复制失败:已输出到控制台,可手动复制', ok ? 'ok' : 'error', 4200); }); } function copyToClipboard(text) { return new Promise((resolve) => { try { if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { navigator.clipboard.writeText(text).then(() => resolve(true)).catch(() => resolve(fallbackCopy(text))); return; } } catch (_) { /* 忽略 */ } resolve(fallbackCopy(text)); }); } function fallbackCopy(text) { try { const area = document.createElement('textarea'); area.value = text; area.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0;'; area.setAttribute('data-lane-tool', 'copy-area'); document.body.appendChild(area); area.select(); const ok = document.execCommand('copy'); document.body.removeChild(area); return !!ok; } catch (err) { console.warn(`${LOG} 剪贴板复制失败:`, err); return false; } } function getCenterColor() { try { const opt = (state.classOptions || []).find((o) => String(o.classId) === String(state.centerClassId)); if (opt && opt.color) return opt.color; if (state.lines && state.lines[0] && state.lines[0].color) return state.lines[0].color; } catch (_) { /* 忽略 */ } return '#fb923c'; } function getReferenceColor() { const ref = state.referenceLine; return (ref && ref.color) || '#fbbf24'; } function buildScene() { const lines = []; const points = []; const labels = []; try { if (state.referenceLine) { const ref = state.referenceLine; const refColor = getReferenceColor(); lines.push({ id: 'ref', points: ref.points, color: refColor, width: 3.5, halo: true, haloColor: 'rgba(255,255,255,0.55)', }); const midRef = ref.points[Math.floor(ref.points.length / 2)]; if (midRef) { labels.push({ id: 'ref-label', point: midRef, text: `基准线 ID ${ref.id}`, color: '#f8fafc', border: refColor, dotColor: refColor, offsetY: -16, }); } const pointLetters = ['A', 'B']; const threeD = is3DMode(); for (let i = 0; i < state.measurePair.length; i++) { const item = state.measurePair[i]; if (!item || !item.point || !item.m) continue; const m = item.m; const P = item.point; const sideColor = m.side > 0 ? '#4ade80' : (m.side < 0 ? '#fb923c' : '#e5e7eb'); let lineStart; let lineEnd; let value; if (threeD) { lineStart = m.foot3D || m.foot; lineEnd = P; value = m.dist3D; } else { lineStart = m.foot; lineEnd = { x: P.x, y: P.y, z: m.foot.z }; value = m.distXY; if (Math.abs(m.dz) > 0.05) { lines.push({ id: `measure-height-${i}`, points: [lineEnd, P], color: '#cbd5e1', width: 1.3, dash: [4, 4], halo: false, opacity: 0.9, }); const midH = averageVecs([lineEnd, P]); if (midH) { labels.push({ id: `measure-height-label-${i}`, point: midH, text: `高差 ${fmt2(Math.abs(m.dz))} 米`, color: '#e2e8f0', border: 'rgba(148,163,184,.85)', offsetX: 48, offsetY: 0, }); } } } points.push({ id: `measure-pt-${i}`, point: P, color: sideColor, radius: 5 }); points.push({ id: `measure-foot-${i}`, point: lineStart, color: '#f472b6', radius: 3.5 }); lines.push({ id: `measure-line-${i}`, points: [lineStart, lineEnd], color: sideColor, width: 2.5, halo: true }); const mid = averageVecs([lineStart, lineEnd]); if (mid) { labels.push({ id: `measure-dist-${i}`, point: mid, text: `${pointLetters[i] || i + 1} ${fmt2(value)} 米`, color: '#e0f2fe', border: sideColor, offsetY: -14, }); } } if (state.measureResult && state.measurePair.length === 2) { const summary = state.measureResult; const main = threeD ? summary.width3d : summary.width; const midOf = (idx) => { const item = state.measurePair[idx]; if (!item || !item.m || !item.point) return null; if (threeD) return averageVecs([item.m.foot3D || item.m.foot, item.point]); return averageVecs([item.m.foot, { x: item.point.x, y: item.point.y, z: item.m.foot.z }]); }; const center = averageVecs([midOf(0), midOf(1)].filter(Boolean)); if (center) { labels.push({ id: 'measure-width', point: center, text: `${threeD ? '3D ' : ''}${summary.opposite ? '合计宽度' : '同侧间距'} ${fmt2(main)} 米`, color: '#67e8f9', border: refColor, offsetY: 18, }); } } } if (state.centerResult && state.centerResult.ok !== false) { const centerColor = getCenterColor(); const srcColors = state.lines.map((line, i) => (line && line.color) || (i === 0 ? '#a78bfa' : '#38bdf8')); const sameColor = srcColors.length === 2 && String(srcColors[0]) === String(srcColors[1]); for (let i = 0; i < state.lines.length; i++) { const line = state.lines[i]; if (!line || !Array.isArray(line.points)) continue; lines.push({ id: `center-src-${i}`, points: line.points, color: srcColors[i], width: sameColor ? 2.5 : 2.2, dash: sameColor && i === 1 ? [6, 4] : null, opacity: 0.95, halo: true, haloColor: 'rgba(255,255,255,0.5)', }); const mid = line.points[Math.floor(line.points.length / 2)]; if (mid) { labels.push({ id: `center-src-label-${i}`, point: mid, text: `线${i + 1} ID ${line.id}`, color: '#f1f5f9', border: srcColors[i], dotColor: srcColors[i], offsetY: -16, }); } } const done = !!state.generated; lines.push({ id: 'center-line', points: state.centerResult.points, color: centerColor, width: 3.5, dash: done ? null : [9, 6], halo: true, }); const centerPts = state.centerResult.points || []; const maxDots = 600; for (let i = 0; i < centerPts.length && i < maxDots; i++) { points.push({ id: `center-dot-${i}`, point: centerPts[i], color: centerColor, radius: centerPts.length > 200 ? 1.8 : 2.8, halo: false, }); } const centerMid = state.centerResult.points[Math.floor(state.centerResult.points.length / 2)]; if (centerMid) { const text = done ? `已生成中线(ID ${state.generated.trackId} / ${state.centerResult.effectiveN} 点)` : `中线预览 ${fmt2(state.centerResult.length)} 米 / ${state.centerResult.effectiveN} 点`; labels.push({ id: 'center-label', point: centerMid, text, color: done ? '#bbf7d0' : '#fed7aa', border: centerColor, dotColor: centerColor, }); } } } catch (err) { console.warn(`${LOG} 构建覆盖层场景失败:`, err); } return { lines, points, labels }; } function refreshStatus() { try { const info = platform.getInfo(); const modeText = platform.getModeText(); if (dom.status) { dom.status.textContent = modeText; dom.status.classList.remove('lt-good', 'lt-warn'); dom.status.classList.add(info.mode === 'full' ? 'lt-good' : 'lt-warn'); } if (dom.modeShort) { dom.modeShort.textContent = info.mode === 'full' ? '平台已连接' : (info.mode === 'viewer' ? '只读模式' : '覆盖层模式'); } refreshProject(); } catch (err) { console.warn(`${LOG} 刷新平台状态失败:`, err); } } function refreshPanel() { if (!dom.panel) return; try { dom.btnMeasure.classList.toggle('lt-active', state.tool === 'measure'); dom.btnCenter.classList.toggle('lt-active', state.tool === 'center'); if (state.tool === 'measure') { if (state.phase === 'pickRef') dom.measureHint.textContent = '测距:请点击一条车道线作为基准线。'; else if (state.phase === 'points') { dom.measureHint.textContent = `已选基准线(ID ${state.referenceLine ? state.referenceLine.id : '?'})。请在车道线两侧各点一下(已点 ${state.measurePair.length}/2)。`; } else dom.measureHint.textContent = '测距:点击「测距」开始。'; } else { dom.measureHint.textContent = '工具一:点「测距」后,点击一条车道线作为基准线。'; } dom.measureResult.innerHTML = renderMeasureResult(); if (state.tool === 'center') { if (state.phase === 'pick1') dom.centerHint.textContent = '中线:请点击第 1 条车道线;或在两线中间点一下自动取两侧最近两条。'; else if (state.phase === 'pick2') dom.centerHint.textContent = `已选线1(ID ${state.lines[0] ? state.lines[0].id : '?'})。请点击第 2 条车道线。`; else if (state.phase === 'preview' || state.phase === 'writing' || state.phase === 'done') dom.centerHint.textContent = '中线预览已生成:确认无误后点「生成中线」写入平台。'; else dom.centerHint.textContent = '中线:点击「中线」开始。'; } else { dom.centerHint.textContent = '工具二:点「中线」后,依次点击两条车道线;或在两线中间点一下自动取两侧最近两条。'; } dom.centerInfo.innerHTML = renderCenterInfo(); renderClassOptions(); dom.centerStatus.innerHTML = renderCenterStatus(); dom.chkAutoCount.checked = state.centerAutoCount; dom.numCount.value = String(state.centerPointCount); dom.numCount.disabled = state.centerAutoCount; if (dom.countHint) { const minN = getMinPointCount(); dom.countHint.textContent = state.centerAutoCount ? `自动:取两条线较多者;2 点=直线,越多越贴合两条线形状(平台最小 ${minN} 点)` : `手动 ${state.centerPointCount} 点(范围 ${minN}~500);2 点=直线,越多越贴合两条线形状`; } const hasCenter = !!(state.centerResult && state.centerResult.ok !== false); dom.btnGenerate.disabled = !hasCenter || state.phase === 'writing'; dom.btnGenerate.textContent = state.onlyPreview ? '生成(仅预览)' : '生成中线'; dom.btnCopy.disabled = !hasCenter; const showSave = !!(state.generated && state.phase === 'done'); dom.btnSave.style.display = showSave ? '' : 'none'; dom.btnSave.disabled = state.saveState === 'saving'; dom.btnSave.textContent = state.saveState === 'saving' ? '保存中…' : '立即保存到平台'; dom.chkOverlay.checked = state.overlayVisible; dom.measureMode.value = state.measureMode; dom.chkPreview.checked = state.onlyPreview; dom.chkAutoSave.checked = state.autoSave; dom.pickSource.textContent = state.pickSource ? `拾取:${state.pickSource}` : ''; } catch (err) { console.warn(`${LOG} 刷新面板失败:`, err); } } function renderMeasureResult() { const threeD = is3DMode(); const modeLabel = threeD ? '三维最短距离' : '水平投影(车道宽度)'; if (!state.measureResult) { return [ '
', `测量方式:${modeLabel}。选择基准线并在两侧各点一下后显示 A/B 距离与合计宽度。`, '
', ].join(''); } const s = state.measureResult; const refColor = getReferenceColor(); const main = threeD ? s.width3d : s.width; const aVal = threeD ? s.a.dist3D : s.a.distXY; const bVal = threeD ? s.b.dist3D : s.b.distXY; const sideRule = s.opposite ? '异侧:合计宽度 = A + B' : '同侧:间距 = |A − B|'; const lineSub = threeD ? `
水平距离:A ${fmt2(s.a.distXY)} 米 · B ${fmt2(s.b.distXY)} 米(合计 ${fmt2(s.width)} 米)
` : `
3D 最短距离:A ${fmt2(s.a.dist3D)} 米 · B ${fmt2(s.b.dist3D)} 米(合计 ${fmt2(s.width3d)} 米)
`; const dzSub = `
高差:A ${fmtSigned(s.a.dz)} 米 · B ${fmtSigned(s.b.dz)} 米${s.a.dz === 0 && s.b.dz === 0 ? '(点击点与车道线同高)' : ''}
`; return [ `
`, `
${s.opposite ? '宽度' : '同侧间距'} ${fmt2(main)} 米 [${modeLabel}]
`, `
A:${fmt2(aVal)} 米(${escapeHtml(s.a.sideText)}) · B:${fmt2(bVal)} 米(${escapeHtml(s.b.sideText)})
`, `
${sideRule}
`, lineSub, dzSub, '
', ].join(''); } function renderCenterInfo() { if (!state.centerResult || state.centerResult.ok === false) { return '
选择两条车道线后显示:线1/线2 点数与长度 → 中线点数/长度预览。
'; } const r = state.centerResult; const centerColor = getCenterColor(); const srcColors = state.lines.map((l, i) => (l && l.color) || (i === 0 ? '#a78bfa' : '#38bdf8')); const lineInfo = state.lines.map((l, i) => { const c = escapeHtml(srcColors[i]); return `● 线${i + 1} ID ${escapeHtml(l.id)}:${l.points.length} 点 / ${fmt2(r.rawLengths[i])} 米`; }).join('
'); const sameClass = state.lines.length === 2 && String(state.lines[0].classId) === String(state.lines[1].classId); const srcAClass = state.lines[0] ? (state.lines[0].classId || '无') : '无'; const srcBClass = state.lines[1] ? (state.lines[1].classId || '无') : '无'; const srcDotColor = escapeHtml(srcColors[0] || centerColor); const classText = sameClass ? `源线类别:● ${escapeHtml(srcAClass)}(两条线相同)` : `源线类别不同:● ${escapeHtml(srcAClass)} / ${escapeHtml(srcBClass)}`; const sug = state.classSuggestion; const sugLabel = sug && sug.label ? sug.label : (state.centerClassId || '未知'); const sugMode = sug && sug.auto === false ? '手动选择' : '自动建议,可在下拉中修改'; const targetText = `目标类别:● ${escapeHtml(sugLabel)}(${sugMode})`; const crossText = sug && sug.crossSource ? '
跨类别生成:不写入属性,生成后请在平台中由标注人员补充该类别属性
' : ''; const countMode = state.centerAutoCount ? '自动(取两条线较多者)' : `手动 ${state.centerPointCount}`; const countText = `生成点数:${countMode} → 中线 ${r.effectiveN} 点${r.clamped ? '(已按最小/最大点数裁剪)' : ''}`; return [ `
`, `
${lineInfo}
`, `
中线 ${fmt2(r.length)} 米 / ${r.effectiveN} 点${r.resampled ? '(弧长重采样)' : ''}${r.reversed ? '(已反转方向)' : ''}
`, `
${countText}
`, `
${targetText}
`, crossText, `
${classText}
`, '
', ].join(''); } function renderClassOptions() { if (!dom.centerClass) return; const options = state.classOptions; const current = state.centerClassId; const key = options.map((o) => `${o.classId}:${o.label}:${o.color || ''}`).join('|') + `#${current}`; if (dom.centerClass.getAttribute('data-key') === key) return; dom.centerClass.setAttribute('data-key', key); dom.centerClass.innerHTML = ''; if (!options || options.length === 0) { const opt = document.createElement('option'); opt.value = ''; opt.textContent = '(未读取到类别)'; dom.centerClass.appendChild(opt); return; } for (const o of options) { const opt = document.createElement('option'); opt.value = o.classId; opt.textContent = `● ${o.label || o.classId || '默认'}${o.count ? `(${o.count} 条)` : ''}`; if (o.color) { opt.style.color = o.color; opt.style.background = '#0f172a'; } dom.centerClass.appendChild(opt); } if (current && options.some((o) => o.classId === current)) dom.centerClass.value = current; else if (options[0]) { dom.centerClass.value = options[0].classId; state.centerClassId = options[0].classId; } } function renderCenterStatus() { const parts = []; if (state.generated) { parts.push(`已写入平台标注:ID ${escapeHtml(state.generated.trackId)}(类别 ${escapeHtml(state.generated.classId)})`); if (state.classAttrNote) parts.push(`${escapeHtml(state.classAttrNote)}`); if (state.saveState === 'saving') parts.push('正在保存…'); else if (state.saveState === 'saved') parts.push('平台保存请求已完成'); else if (state.saveState === 'error') parts.push(`保存失败:${escapeHtml(state.saveError)}`); else parts.push('请按 Ctrl+S 或点平台「保存」按钮持久化'); } else if (state.writeError) { parts.push(`写入失败:${escapeHtml(state.writeError)}`); } else if (state.onlyPreview && state.centerResult) { parts.push('仅预览模式:不写入平台,可复制 JSON'); } return parts.join('
'); } function consumeKey(ev) { try { ev.preventDefault(); ev.stopPropagation(); if (typeof ev.stopImmediatePropagation === 'function') ev.stopImmediatePropagation(); } catch (_) { /* 忽略 */ } } function onKeyDown(ev) { try { if (ev.defaultPrevented) return; if (isTypingTarget(ev.target)) return; const key = ev.key ? String(ev.key).toLowerCase() : ''; if (ev.altKey && !ev.ctrlKey && !ev.metaKey) { if (key === 'm') { consumeKey(ev); toggleTool('measure'); return; } if (key === 'n') { consumeKey(ev); toggleTool('center'); return; } if (key === 'h') { consumeKey(ev); state.panelHidden = !state.panelHidden; if (dom.panel) dom.panel.classList.toggle('lt-hidden', state.panelHidden); saveSettings(); if (state.panelHidden) toast('面板已隐藏,按 Alt+H 重新显示', 'info', 2600); return; } } if (ev.key === 'Escape') { if (isToolActive()) { consumeKey(ev); exitTool(); } } } catch (err) { console.warn(`${LOG} 快捷键处理异常:`, err); } } try { loadSettings(); mountToastLayer(); mountPanel(); refreshStatus(); window.addEventListener('keydown', onKeyDown, true); platform.discover(); refreshStatus(); refreshPanel(); setTimeout(() => { try { platform.refresh(); refreshStatus(); if (dom.pickSource) { const info = platform.getInfo(); dom.pickSource.textContent = info.hasViewer ? '' : '未发现 window.viewer'; } } catch (err) { console.warn(`${LOG} 延迟探测平台失败:`, err); } }, 1500); window.__LANE_TOOL__ = { version: VERSION, get state() { return JSON.parse(JSON.stringify({ tool: state.tool, phase: state.phase, overlayVisible: state.overlayVisible, referenceLineId: state.referenceLine ? state.referenceLine.id : null, referenceColor: getReferenceColor(), measureMode: state.measureMode, projectKind: getProjectKind(), projectLabel: state.projectInfo ? state.projectInfo.label : null, isMergedFrame: (function () { try { return platform.getMergedFrameInfo().isMergedFrame; } catch (e) { return null; } })(), classSuggestion: state.classSuggestion ? { classId: state.classSuggestion.classId, label: state.classSuggestion.label, reason: state.classSuggestion.reason, auto: state.classSuggestion.auto, crossSource: state.classSuggestion.crossSource, } : null, classAttrNote: state.classAttrNote || '', measurePairCount: state.measurePair.length, measure: state.measureResult ? { width: state.measureResult.width, width3d: state.measureResult.width3d, opposite: state.measureResult.opposite, a: state.measureResult.a.distXY, b: state.measureResult.b.distXY, a3d: state.measureResult.a.dist3D, b3d: state.measureResult.b.dist3D, aDz: state.measureResult.a.dz, bDz: state.measureResult.b.dz, aFoot: state.measureResult.a.foot, aFoot3D: state.measureResult.a.foot3D, bFoot: state.measureResult.b.foot, bFoot3D: state.measureResult.b.foot3D, } : null, center: state.centerResult && state.centerResult.ok !== false ? { n: state.centerResult.effectiveN, requestedN: state.centerResult.requestedN, clamped: state.centerResult.clamped, length: state.centerResult.length, resampled: state.centerResult.resampled, reversed: state.centerResult.reversed, } : null, centerPointCount: { auto: state.centerAutoCount, value: state.centerPointCount }, generated: state.generated, writeError: state.writeError, })); }, platform, overlay, ui: { toggleTool, activateMeasure: () => toggleTool('measure'), activateCenter: () => toggleTool('center'), exitTool, clearAll, refreshPanel, refreshAll, refreshStatus, refreshProject, toast, generateCenter, doSyncSave, copyCenterJson, pickLineAt, pickTwoLinesAround, setCenterPreview: (lineA, lineB) => setCenterPreview(lineA, lineB), getProjectKind, setMeasureMode: (mode) => { state.measureMode = mode === '3d' ? '3d' : 'horizontal'; if (dom.measureMode) dom.measureMode.value = state.measureMode; saveSettings(); refreshAll(); }, getCenterColor, }, core: { summarizeMeasure, buildCenterLine, measureToPolyline, normalizePoints, fmt2, }, diagnostics: () => platform.getDiagnostics(), }; console.log(`${LOG} 已加载 v${VERSION}:Alt+M 测距 · Alt+N 中线 · Esc 取消 · Alt+H 面板`); try { const info = platform.getInfo(); if (info.mode !== 'full') { console.warn(`${LOG} 平台接口不完整(模式:${info.mode}),将使用降级模式;诊断:`, info); } } catch (_) { /* 忽略 */ } } catch (err) { console.error(`${LOG} 初始化失败(页面功能不受影响):`, err); try { exitTool({ silent: true }); } catch (_) { /* 忽略 */ } } } /* ==================== 启动入口 ==================== */ try { bootstrapLaneTool(); } catch (err) { console.error('[车道线工具] 初始化异常(页面功能不受影响):', err); } })();