mapEngine.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  1. import { getTileSizePx, screenToWorld, worldToScreen, type CameraState } from '../camera/camera'
  2. import { CompassHeadingController } from '../sensor/compassHeadingController'
  3. import { WebGLMapRenderer } from '../renderer/webglMapRenderer'
  4. import { type MapRendererStats } from '../renderer/mapRenderer'
  5. import { worldTileToLonLat, type LonLatPoint } from '../../utils/projection'
  6. const RENDER_MODE = 'Single WebGL Pipeline'
  7. const PROJECTION_MODE = 'WGS84 -> WorldTile -> Camera -> Screen'
  8. const MAP_NORTH_OFFSET_DEG = 0
  9. const MIN_ZOOM = 15
  10. const MAX_ZOOM = 20
  11. const DEFAULT_ZOOM = 17
  12. const DESIRED_VISIBLE_COLUMNS = 3
  13. const OVERDRAW = 1
  14. const DEFAULT_TOP_LEFT_TILE_X = 108132
  15. const DEFAULT_TOP_LEFT_TILE_Y = 51199
  16. const DEFAULT_CENTER_TILE_X = DEFAULT_TOP_LEFT_TILE_X + 1
  17. const DEFAULT_CENTER_TILE_Y = DEFAULT_TOP_LEFT_TILE_Y + 1
  18. const TILE_SOURCE = 'https://oss-mbh5.colormaprun.com/wxMap/lcx/{z}/{x}/{y}.png'
  19. const MIN_PREVIEW_SCALE = 0.55
  20. const MAX_PREVIEW_SCALE = 1.85
  21. const INERTIA_FRAME_MS = 16
  22. const INERTIA_DECAY = 0.92
  23. const INERTIA_MIN_SPEED = 0.02
  24. const PREVIEW_RESET_DURATION_MS = 140
  25. const UI_SYNC_INTERVAL_MS = 80
  26. const ROTATE_STEP_DEG = 15
  27. const AUTO_ROTATE_FRAME_MS = 10
  28. const AUTO_ROTATE_EASE = 0.24
  29. const AUTO_ROTATE_SNAP_DEG = 0.1
  30. const AUTO_ROTATE_DEADZONE_DEG = 1.5
  31. const AUTO_ROTATE_MAX_STEP_DEG = 0.9
  32. const AUTO_ROTATE_HEADING_SMOOTHING = 0.32
  33. const SAMPLE_TRACK_WGS84: LonLatPoint[] = [
  34. worldTileToLonLat({ x: DEFAULT_CENTER_TILE_X - 0.72, y: DEFAULT_CENTER_TILE_Y + 0.44 }, DEFAULT_ZOOM),
  35. worldTileToLonLat({ x: DEFAULT_CENTER_TILE_X - 0.18, y: DEFAULT_CENTER_TILE_Y + 0.08 }, DEFAULT_ZOOM),
  36. worldTileToLonLat({ x: DEFAULT_CENTER_TILE_X + 0.22, y: DEFAULT_CENTER_TILE_Y - 0.16 }, DEFAULT_ZOOM),
  37. worldTileToLonLat({ x: DEFAULT_CENTER_TILE_X + 0.64, y: DEFAULT_CENTER_TILE_Y - 0.52 }, DEFAULT_ZOOM),
  38. ]
  39. const SAMPLE_GPS_WGS84: LonLatPoint = worldTileToLonLat(
  40. { x: DEFAULT_CENTER_TILE_X + 0.12, y: DEFAULT_CENTER_TILE_Y - 0.06 },
  41. DEFAULT_ZOOM,
  42. )
  43. type TouchPoint = WechatMiniprogram.TouchDetail
  44. type GestureMode = 'idle' | 'pan' | 'pinch'
  45. type RotationMode = 'manual' | 'auto'
  46. type OrientationMode = 'manual' | 'north-up' | 'heading-up'
  47. type AutoRotateSourceMode = 'sensor' | 'course' | 'fusion'
  48. export interface MapEngineStageRect {
  49. width: number
  50. height: number
  51. left: number
  52. top: number
  53. }
  54. export interface MapEngineViewState {
  55. buildVersion: string
  56. renderMode: string
  57. projectionMode: string
  58. mapReady: boolean
  59. mapReadyText: string
  60. mapName: string
  61. zoom: number
  62. rotationDeg: number
  63. rotationText: string
  64. rotationMode: RotationMode
  65. rotationModeText: string
  66. rotationToggleText: string
  67. orientationMode: OrientationMode
  68. orientationModeText: string
  69. sensorHeadingText: string
  70. autoRotateSourceText: string
  71. autoRotateCalibrationText: string
  72. northReferenceText: string
  73. compassNeedleDeg: number
  74. centerTileX: number
  75. centerTileY: number
  76. centerText: string
  77. tileSource: string
  78. visibleColumnCount: number
  79. visibleTileCount: number
  80. readyTileCount: number
  81. memoryTileCount: number
  82. diskTileCount: number
  83. memoryHitCount: number
  84. diskHitCount: number
  85. networkFetchCount: number
  86. cacheHitRateText: string
  87. tileTranslateX: number
  88. tileTranslateY: number
  89. tileSizePx: number
  90. stageWidth: number
  91. stageHeight: number
  92. stageLeft: number
  93. stageTop: number
  94. statusText: string
  95. }
  96. export interface MapEngineCallbacks {
  97. onData: (patch: Partial<MapEngineViewState>) => void
  98. }
  99. const VIEW_SYNC_KEYS: Array<keyof MapEngineViewState> = [
  100. 'buildVersion',
  101. 'renderMode',
  102. 'projectionMode',
  103. 'mapReady',
  104. 'mapReadyText',
  105. 'mapName',
  106. 'zoom',
  107. 'rotationDeg',
  108. 'rotationText',
  109. 'rotationMode',
  110. 'rotationModeText',
  111. 'rotationToggleText',
  112. 'orientationMode',
  113. 'orientationModeText',
  114. 'sensorHeadingText',
  115. 'autoRotateSourceText',
  116. 'autoRotateCalibrationText',
  117. 'northReferenceText',
  118. 'compassNeedleDeg',
  119. 'centerText',
  120. 'tileSource',
  121. 'visibleTileCount',
  122. 'readyTileCount',
  123. 'memoryTileCount',
  124. 'diskTileCount',
  125. 'memoryHitCount',
  126. 'diskHitCount',
  127. 'networkFetchCount',
  128. 'cacheHitRateText',
  129. 'tileSizePx',
  130. 'statusText',
  131. ]
  132. function buildCenterText(zoom: number, x: number, y: number): string {
  133. return `z${zoom} / x${x} / y${y}`
  134. }
  135. function clamp(value: number, min: number, max: number): number {
  136. return Math.max(min, Math.min(max, value))
  137. }
  138. function normalizeRotationDeg(rotationDeg: number): number {
  139. const normalized = rotationDeg % 360
  140. return normalized < 0 ? normalized + 360 : normalized
  141. }
  142. function normalizeAngleDeltaRad(angleDeltaRad: number): number {
  143. let normalized = angleDeltaRad
  144. while (normalized > Math.PI) {
  145. normalized -= Math.PI * 2
  146. }
  147. while (normalized < -Math.PI) {
  148. normalized += Math.PI * 2
  149. }
  150. return normalized
  151. }
  152. function normalizeAngleDeltaDeg(angleDeltaDeg: number): number {
  153. let normalized = angleDeltaDeg
  154. while (normalized > 180) {
  155. normalized -= 360
  156. }
  157. while (normalized < -180) {
  158. normalized += 360
  159. }
  160. return normalized
  161. }
  162. function interpolateAngleDeg(currentDeg: number, targetDeg: number, factor: number): number {
  163. return normalizeRotationDeg(currentDeg + normalizeAngleDeltaDeg(targetDeg - currentDeg) * factor)
  164. }
  165. function formatRotationText(rotationDeg: number): string {
  166. return `${Math.round(normalizeRotationDeg(rotationDeg))}deg`
  167. }
  168. function formatHeadingText(headingDeg: number | null): string {
  169. if (headingDeg === null) {
  170. return '--'
  171. }
  172. return `${Math.round(normalizeRotationDeg(headingDeg))}deg`
  173. }
  174. function formatOrientationModeText(mode: OrientationMode): string {
  175. if (mode === 'north-up') {
  176. return 'North Up'
  177. }
  178. if (mode === 'heading-up') {
  179. return 'Heading Up'
  180. }
  181. return 'Manual Gesture'
  182. }
  183. function formatRotationModeText(mode: OrientationMode): string {
  184. return formatOrientationModeText(mode)
  185. }
  186. function formatRotationToggleText(mode: OrientationMode): string {
  187. if (mode === 'manual') {
  188. return '切到北朝上'
  189. }
  190. if (mode === 'north-up') {
  191. return '切到朝向朝上'
  192. }
  193. return '切到手动旋转'
  194. }
  195. function formatAutoRotateSourceText(mode: AutoRotateSourceMode, hasCourseHeading: boolean): string {
  196. if (mode === 'sensor') {
  197. return 'Sensor Only'
  198. }
  199. if (mode === 'course') {
  200. return hasCourseHeading ? 'Course Only' : 'Course Pending'
  201. }
  202. return hasCourseHeading ? 'Sensor + Course' : 'Sensor Only'
  203. }
  204. function formatAutoRotateCalibrationText(pending: boolean, offsetDeg: number | null): string {
  205. if (pending) {
  206. return 'Pending'
  207. }
  208. if (offsetDeg === null) {
  209. return '--'
  210. }
  211. return `Offset ${Math.round(normalizeRotationDeg(offsetDeg))}deg`
  212. }
  213. function formatNorthReferenceText(): string {
  214. return 'Map North = 0deg (TFW aligned)'
  215. }
  216. function formatCompassNeedleDeg(headingDeg: number | null): number {
  217. if (headingDeg === null) {
  218. return 0
  219. }
  220. return normalizeRotationDeg(360 - headingDeg)
  221. }
  222. function formatCacheHitRate(memoryHitCount: number, diskHitCount: number, networkFetchCount: number): string {
  223. const total = memoryHitCount + diskHitCount + networkFetchCount
  224. if (!total) {
  225. return '--'
  226. }
  227. const hitRate = ((memoryHitCount + diskHitCount) / total) * 100
  228. return `${Math.round(hitRate)}%`
  229. }
  230. export class MapEngine {
  231. buildVersion: string
  232. renderer: WebGLMapRenderer
  233. compassController: CompassHeadingController
  234. onData: (patch: Partial<MapEngineViewState>) => void
  235. state: MapEngineViewState
  236. previewScale: number
  237. previewOriginX: number
  238. previewOriginY: number
  239. panLastX: number
  240. panLastY: number
  241. panLastTimestamp: number
  242. panVelocityX: number
  243. panVelocityY: number
  244. pinchStartDistance: number
  245. pinchStartScale: number
  246. pinchStartAngle: number
  247. pinchStartRotationDeg: number
  248. pinchAnchorWorldX: number
  249. pinchAnchorWorldY: number
  250. gestureMode: GestureMode
  251. inertiaTimer: number
  252. previewResetTimer: number
  253. viewSyncTimer: number
  254. autoRotateTimer: number
  255. pendingViewPatch: Partial<MapEngineViewState>
  256. mounted: boolean
  257. sensorHeadingDeg: number | null
  258. smoothedSensorHeadingDeg: number | null
  259. autoRotateHeadingDeg: number | null
  260. courseHeadingDeg: number | null
  261. targetAutoRotationDeg: number | null
  262. autoRotateSourceMode: AutoRotateSourceMode
  263. autoRotateCalibrationOffsetDeg: number | null
  264. autoRotateCalibrationPending: boolean
  265. constructor(buildVersion: string, callbacks: MapEngineCallbacks) {
  266. this.buildVersion = buildVersion
  267. this.onData = callbacks.onData
  268. this.renderer = new WebGLMapRenderer(
  269. (stats) => {
  270. this.applyStats(stats)
  271. },
  272. (message) => {
  273. this.setState({
  274. statusText: `${message} (${this.buildVersion})`,
  275. })
  276. },
  277. )
  278. this.compassController = new CompassHeadingController({
  279. onHeading: (headingDeg) => {
  280. this.handleCompassHeading(headingDeg)
  281. },
  282. onError: (message) => {
  283. this.handleCompassError(message)
  284. },
  285. })
  286. this.state = {
  287. buildVersion: this.buildVersion,
  288. renderMode: RENDER_MODE,
  289. projectionMode: PROJECTION_MODE,
  290. mapReady: false,
  291. mapReadyText: 'BOOTING',
  292. mapName: 'LCX 测试地图',
  293. zoom: DEFAULT_ZOOM,
  294. rotationDeg: 0,
  295. rotationText: formatRotationText(0),
  296. rotationMode: 'manual',
  297. rotationModeText: formatRotationModeText('manual'),
  298. rotationToggleText: formatRotationToggleText('manual'),
  299. orientationMode: 'manual',
  300. orientationModeText: formatOrientationModeText('manual'),
  301. sensorHeadingText: '--',
  302. autoRotateSourceText: formatAutoRotateSourceText('fusion', false),
  303. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, MAP_NORTH_OFFSET_DEG),
  304. northReferenceText: formatNorthReferenceText(),
  305. compassNeedleDeg: 0,
  306. centerTileX: DEFAULT_CENTER_TILE_X,
  307. centerTileY: DEFAULT_CENTER_TILE_Y,
  308. centerText: buildCenterText(DEFAULT_ZOOM, DEFAULT_CENTER_TILE_X, DEFAULT_CENTER_TILE_Y),
  309. tileSource: TILE_SOURCE,
  310. visibleColumnCount: DESIRED_VISIBLE_COLUMNS,
  311. visibleTileCount: 0,
  312. readyTileCount: 0,
  313. memoryTileCount: 0,
  314. diskTileCount: 0,
  315. memoryHitCount: 0,
  316. diskHitCount: 0,
  317. networkFetchCount: 0,
  318. cacheHitRateText: '--',
  319. tileTranslateX: 0,
  320. tileTranslateY: 0,
  321. tileSizePx: 0,
  322. stageWidth: 0,
  323. stageHeight: 0,
  324. stageLeft: 0,
  325. stageTop: 0,
  326. statusText: `单 WebGL 管线已准备接入方向传感器 (${this.buildVersion})`,
  327. }
  328. this.previewScale = 1
  329. this.previewOriginX = 0
  330. this.previewOriginY = 0
  331. this.panLastX = 0
  332. this.panLastY = 0
  333. this.panLastTimestamp = 0
  334. this.panVelocityX = 0
  335. this.panVelocityY = 0
  336. this.pinchStartDistance = 0
  337. this.pinchStartScale = 1
  338. this.pinchStartAngle = 0
  339. this.pinchStartRotationDeg = 0
  340. this.pinchAnchorWorldX = 0
  341. this.pinchAnchorWorldY = 0
  342. this.gestureMode = 'idle'
  343. this.inertiaTimer = 0
  344. this.previewResetTimer = 0
  345. this.viewSyncTimer = 0
  346. this.autoRotateTimer = 0
  347. this.pendingViewPatch = {}
  348. this.mounted = false
  349. this.sensorHeadingDeg = null
  350. this.smoothedSensorHeadingDeg = null
  351. this.autoRotateHeadingDeg = null
  352. this.courseHeadingDeg = null
  353. this.targetAutoRotationDeg = null
  354. this.autoRotateSourceMode = 'fusion'
  355. this.autoRotateCalibrationOffsetDeg = MAP_NORTH_OFFSET_DEG
  356. this.autoRotateCalibrationPending = false
  357. }
  358. getInitialData(): MapEngineViewState {
  359. return { ...this.state }
  360. }
  361. destroy(): void {
  362. this.clearInertiaTimer()
  363. this.clearPreviewResetTimer()
  364. this.clearViewSyncTimer()
  365. this.clearAutoRotateTimer()
  366. this.compassController.destroy()
  367. this.renderer.destroy()
  368. this.mounted = false
  369. }
  370. setStage(rect: MapEngineStageRect): void {
  371. this.previewScale = 1
  372. this.previewOriginX = rect.width / 2
  373. this.previewOriginY = rect.height / 2
  374. this.commitViewport(
  375. {
  376. stageWidth: rect.width,
  377. stageHeight: rect.height,
  378. stageLeft: rect.left,
  379. stageTop: rect.top,
  380. },
  381. `地图视口与 WebGL 引擎已对齐 (${this.buildVersion})`,
  382. true,
  383. )
  384. }
  385. attachCanvas(canvasNode: any, width: number, height: number, dpr: number): void {
  386. this.renderer.attachCanvas(canvasNode, width, height, dpr)
  387. this.mounted = true
  388. this.state.mapReady = true
  389. this.state.mapReadyText = 'READY'
  390. this.onData({
  391. mapReady: true,
  392. mapReadyText: 'READY',
  393. statusText: `单 WebGL 管线已就绪,可切换手动或自动朝向 (${this.buildVersion})`,
  394. })
  395. this.syncRenderer()
  396. this.compassController.start()
  397. }
  398. handleTouchStart(event: WechatMiniprogram.TouchEvent): void {
  399. this.clearInertiaTimer()
  400. this.clearPreviewResetTimer()
  401. this.renderer.setAnimationPaused(true)
  402. this.panVelocityX = 0
  403. this.panVelocityY = 0
  404. if (event.touches.length >= 2) {
  405. const origin = this.getStagePoint(event.touches)
  406. this.gestureMode = 'pinch'
  407. this.pinchStartDistance = this.getTouchDistance(event.touches)
  408. this.pinchStartScale = this.previewScale || 1
  409. this.pinchStartAngle = this.getTouchAngle(event.touches)
  410. this.pinchStartRotationDeg = this.state.rotationDeg
  411. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  412. this.pinchAnchorWorldX = anchorWorld.x
  413. this.pinchAnchorWorldY = anchorWorld.y
  414. this.setPreviewState(this.pinchStartScale, origin.x, origin.y)
  415. this.syncRenderer()
  416. this.compassController.start()
  417. return
  418. }
  419. if (event.touches.length === 1) {
  420. this.gestureMode = 'pan'
  421. this.panLastX = event.touches[0].pageX
  422. this.panLastY = event.touches[0].pageY
  423. this.panLastTimestamp = event.timeStamp || Date.now()
  424. }
  425. }
  426. handleTouchMove(event: WechatMiniprogram.TouchEvent): void {
  427. if (event.touches.length >= 2) {
  428. const distance = this.getTouchDistance(event.touches)
  429. const angle = this.getTouchAngle(event.touches)
  430. const origin = this.getStagePoint(event.touches)
  431. if (!this.pinchStartDistance) {
  432. this.pinchStartDistance = distance
  433. this.pinchStartScale = this.previewScale || 1
  434. this.pinchStartAngle = angle
  435. this.pinchStartRotationDeg = this.state.rotationDeg
  436. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  437. this.pinchAnchorWorldX = anchorWorld.x
  438. this.pinchAnchorWorldY = anchorWorld.y
  439. }
  440. this.gestureMode = 'pinch'
  441. const nextRotationDeg = this.state.orientationMode === 'heading-up'
  442. ? this.state.rotationDeg
  443. : normalizeRotationDeg(this.pinchStartRotationDeg + normalizeAngleDeltaRad(angle - this.pinchStartAngle) * 180 / Math.PI)
  444. const anchorOffset = this.getWorldOffsetFromScreen(origin.x, origin.y, nextRotationDeg)
  445. const resolvedViewport = this.resolveViewportForExactCenter(
  446. this.pinchAnchorWorldX - anchorOffset.x,
  447. this.pinchAnchorWorldY - anchorOffset.y,
  448. nextRotationDeg,
  449. )
  450. this.setPreviewState(
  451. clamp(this.pinchStartScale * (distance / this.pinchStartDistance), MIN_PREVIEW_SCALE, MAX_PREVIEW_SCALE),
  452. origin.x,
  453. origin.y,
  454. )
  455. this.commitViewport(
  456. {
  457. ...resolvedViewport,
  458. rotationDeg: nextRotationDeg,
  459. rotationText: formatRotationText(nextRotationDeg),
  460. },
  461. this.state.orientationMode === 'heading-up'
  462. ? `双指缩放中,自动朝向保持开启 (${this.buildVersion})`
  463. : `双指缩放与旋转中 (${this.buildVersion})`,
  464. )
  465. return
  466. }
  467. if (this.gestureMode !== 'pan' || event.touches.length !== 1) {
  468. return
  469. }
  470. const touch = event.touches[0]
  471. const deltaX = touch.pageX - this.panLastX
  472. const deltaY = touch.pageY - this.panLastY
  473. const nextTimestamp = event.timeStamp || Date.now()
  474. const elapsed = Math.max(nextTimestamp - this.panLastTimestamp, 16)
  475. const instantVelocityX = deltaX / elapsed
  476. const instantVelocityY = deltaY / elapsed
  477. this.panVelocityX = this.panVelocityX * 0.72 + instantVelocityX * 0.28
  478. this.panVelocityY = this.panVelocityY * 0.72 + instantVelocityY * 0.28
  479. this.panLastX = touch.pageX
  480. this.panLastY = touch.pageY
  481. this.panLastTimestamp = nextTimestamp
  482. this.normalizeTranslate(
  483. this.state.tileTranslateX + deltaX,
  484. this.state.tileTranslateY + deltaY,
  485. `已拖拽单 WebGL 地图引擎 (${this.buildVersion})`,
  486. )
  487. }
  488. handleTouchEnd(event: WechatMiniprogram.TouchEvent): void {
  489. if (this.gestureMode === 'pinch' && event.touches.length < 2) {
  490. const gestureScale = this.previewScale || 1
  491. const zoomDelta = Math.round(Math.log2(gestureScale))
  492. const originX = this.previewOriginX || this.state.stageWidth / 2
  493. const originY = this.previewOriginY || this.state.stageHeight / 2
  494. if (zoomDelta) {
  495. const residualScale = gestureScale / Math.pow(2, zoomDelta)
  496. this.zoomAroundPoint(zoomDelta, originX, originY, residualScale)
  497. } else {
  498. this.animatePreviewToRest()
  499. }
  500. this.resetPinchState()
  501. this.panVelocityX = 0
  502. this.panVelocityY = 0
  503. if (event.touches.length === 1) {
  504. this.gestureMode = 'pan'
  505. this.panLastX = event.touches[0].pageX
  506. this.panLastY = event.touches[0].pageY
  507. this.panLastTimestamp = event.timeStamp || Date.now()
  508. return
  509. }
  510. this.gestureMode = 'idle'
  511. this.renderer.setAnimationPaused(false)
  512. this.scheduleAutoRotate()
  513. return
  514. }
  515. if (event.touches.length === 1) {
  516. this.gestureMode = 'pan'
  517. this.panLastX = event.touches[0].pageX
  518. this.panLastY = event.touches[0].pageY
  519. this.panLastTimestamp = event.timeStamp || Date.now()
  520. return
  521. }
  522. if (this.gestureMode === 'pan' && (Math.abs(this.panVelocityX) >= INERTIA_MIN_SPEED || Math.abs(this.panVelocityY) >= INERTIA_MIN_SPEED)) {
  523. this.startInertia()
  524. this.gestureMode = 'idle'
  525. this.resetPinchState()
  526. return
  527. }
  528. this.gestureMode = 'idle'
  529. this.resetPinchState()
  530. this.renderer.setAnimationPaused(false)
  531. this.scheduleAutoRotate()
  532. }
  533. handleTouchCancel(): void {
  534. this.gestureMode = 'idle'
  535. this.resetPinchState()
  536. this.panVelocityX = 0
  537. this.panVelocityY = 0
  538. this.clearInertiaTimer()
  539. this.animatePreviewToRest()
  540. this.renderer.setAnimationPaused(false)
  541. this.scheduleAutoRotate()
  542. }
  543. handleRecenter(): void {
  544. this.clearInertiaTimer()
  545. this.clearPreviewResetTimer()
  546. this.panVelocityX = 0
  547. this.panVelocityY = 0
  548. this.renderer.setAnimationPaused(false)
  549. this.commitViewport(
  550. {
  551. zoom: DEFAULT_ZOOM,
  552. centerTileX: DEFAULT_CENTER_TILE_X,
  553. centerTileY: DEFAULT_CENTER_TILE_Y,
  554. tileTranslateX: 0,
  555. tileTranslateY: 0,
  556. },
  557. `已回到单 WebGL 引擎默认首屏 (${this.buildVersion})`,
  558. true,
  559. () => {
  560. this.resetPreviewState()
  561. this.syncRenderer()
  562. this.compassController.start()
  563. this.scheduleAutoRotate()
  564. },
  565. )
  566. }
  567. handleRotateStep(stepDeg = ROTATE_STEP_DEG): void {
  568. if (this.state.rotationMode === 'auto') {
  569. this.setState({
  570. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  571. }, true)
  572. return
  573. }
  574. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  575. const nextRotationDeg = normalizeRotationDeg(this.state.rotationDeg + stepDeg)
  576. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  577. this.clearInertiaTimer()
  578. this.clearPreviewResetTimer()
  579. this.panVelocityX = 0
  580. this.panVelocityY = 0
  581. this.renderer.setAnimationPaused(false)
  582. this.commitViewport(
  583. {
  584. ...resolvedViewport,
  585. rotationDeg: nextRotationDeg,
  586. rotationText: formatRotationText(nextRotationDeg),
  587. },
  588. `旋转角度调整到 ${formatRotationText(nextRotationDeg)} (${this.buildVersion})`,
  589. true,
  590. () => {
  591. this.resetPreviewState()
  592. this.syncRenderer()
  593. this.compassController.start()
  594. },
  595. )
  596. }
  597. handleRotationReset(): void {
  598. if (this.state.rotationMode === 'auto') {
  599. this.setState({
  600. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  601. }, true)
  602. return
  603. }
  604. if (!this.state.rotationDeg) {
  605. return
  606. }
  607. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  608. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, 0)
  609. this.clearInertiaTimer()
  610. this.clearPreviewResetTimer()
  611. this.panVelocityX = 0
  612. this.panVelocityY = 0
  613. this.renderer.setAnimationPaused(false)
  614. this.commitViewport(
  615. {
  616. ...resolvedViewport,
  617. rotationDeg: 0,
  618. rotationText: formatRotationText(0),
  619. },
  620. `旋转角度已归零 (${this.buildVersion})`,
  621. true,
  622. () => {
  623. this.resetPreviewState()
  624. this.syncRenderer()
  625. this.compassController.start()
  626. },
  627. )
  628. }
  629. handleToggleRotationMode(): void {
  630. if (this.state.orientationMode === 'manual') {
  631. this.setNorthUpMode()
  632. return
  633. }
  634. if (this.state.orientationMode === 'north-up') {
  635. this.setHeadingUpMode()
  636. return
  637. }
  638. this.setManualMode()
  639. }
  640. handleSetManualMode(): void {
  641. this.setManualMode()
  642. }
  643. handleSetNorthUpMode(): void {
  644. this.setNorthUpMode()
  645. }
  646. handleSetHeadingUpMode(): void {
  647. this.setHeadingUpMode()
  648. }
  649. handleAutoRotateCalibrate(): void {
  650. if (this.state.orientationMode !== 'heading-up') {
  651. this.setState({
  652. statusText: `请先切到朝向朝上模式再校准 (${this.buildVersion})`,
  653. }, true)
  654. return
  655. }
  656. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  657. this.setState({
  658. statusText: `当前还没有传感器方向数据,暂时无法校准 (${this.buildVersion})`,
  659. }, true)
  660. return
  661. }
  662. this.setState({
  663. statusText: `已按当前持机方向完成朝向校准 (${this.buildVersion})`,
  664. }, true)
  665. this.scheduleAutoRotate()
  666. }
  667. setManualMode(): void {
  668. this.clearAutoRotateTimer()
  669. this.targetAutoRotationDeg = null
  670. this.autoRotateCalibrationPending = false
  671. this.setState({
  672. rotationMode: 'manual',
  673. rotationModeText: formatRotationModeText('manual'),
  674. rotationToggleText: formatRotationToggleText('manual'),
  675. orientationMode: 'manual',
  676. orientationModeText: formatOrientationModeText('manual'),
  677. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  678. statusText: `已切回手动地图旋转 (${this.buildVersion})`,
  679. }, true)
  680. }
  681. setNorthUpMode(): void {
  682. this.clearAutoRotateTimer()
  683. this.targetAutoRotationDeg = null
  684. this.autoRotateCalibrationPending = false
  685. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  686. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, MAP_NORTH_OFFSET_DEG)
  687. this.commitViewport(
  688. {
  689. ...resolvedViewport,
  690. rotationDeg: MAP_NORTH_OFFSET_DEG,
  691. rotationText: formatRotationText(MAP_NORTH_OFFSET_DEG),
  692. rotationMode: 'manual',
  693. rotationModeText: formatRotationModeText('north-up'),
  694. rotationToggleText: formatRotationToggleText('north-up'),
  695. orientationMode: 'north-up',
  696. orientationModeText: formatOrientationModeText('north-up'),
  697. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  698. },
  699. `地图已固定为北朝上 (${this.buildVersion})`,
  700. true,
  701. () => {
  702. this.resetPreviewState()
  703. this.syncRenderer()
  704. },
  705. )
  706. }
  707. setHeadingUpMode(): void {
  708. this.autoRotateCalibrationPending = false
  709. this.autoRotateCalibrationOffsetDeg = MAP_NORTH_OFFSET_DEG
  710. this.targetAutoRotationDeg = null
  711. this.setState({
  712. rotationMode: 'auto',
  713. rotationModeText: formatRotationModeText('heading-up'),
  714. rotationToggleText: formatRotationToggleText('heading-up'),
  715. orientationMode: 'heading-up',
  716. orientationModeText: formatOrientationModeText('heading-up'),
  717. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  718. statusText: `正在启用朝向朝上模式 (${this.buildVersion})`,
  719. }, true)
  720. if (this.refreshAutoRotateTarget()) {
  721. this.scheduleAutoRotate()
  722. }
  723. }
  724. handleCompassHeading(headingDeg: number): void {
  725. this.sensorHeadingDeg = normalizeRotationDeg(headingDeg)
  726. this.smoothedSensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  727. ? this.sensorHeadingDeg
  728. : interpolateAngleDeg(this.smoothedSensorHeadingDeg, this.sensorHeadingDeg, AUTO_ROTATE_HEADING_SMOOTHING)
  729. this.autoRotateHeadingDeg = this.smoothedSensorHeadingDeg
  730. this.setState({
  731. sensorHeadingText: formatHeadingText(this.smoothedSensorHeadingDeg),
  732. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  733. compassNeedleDeg: formatCompassNeedleDeg(this.smoothedSensorHeadingDeg),
  734. })
  735. if (!this.refreshAutoRotateTarget()) {
  736. return
  737. }
  738. if (this.state.orientationMode === 'heading-up') {
  739. this.scheduleAutoRotate()
  740. }
  741. }
  742. handleCompassError(message: string): void {
  743. this.clearAutoRotateTimer()
  744. this.targetAutoRotationDeg = null
  745. this.autoRotateCalibrationPending = false
  746. this.setState({
  747. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  748. statusText: `${message} (${this.buildVersion})`,
  749. }, true)
  750. }
  751. setCourseHeading(headingDeg: number | null): void {
  752. this.courseHeadingDeg = headingDeg === null ? null : normalizeRotationDeg(headingDeg)
  753. this.setState({
  754. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  755. })
  756. if (this.refreshAutoRotateTarget()) {
  757. this.scheduleAutoRotate()
  758. }
  759. }
  760. resolveAutoRotateInputHeadingDeg(): number | null {
  761. const sensorHeadingDeg = this.smoothedSensorHeadingDeg
  762. const courseHeadingDeg = this.courseHeadingDeg
  763. if (this.autoRotateSourceMode === 'sensor') {
  764. return sensorHeadingDeg
  765. }
  766. if (this.autoRotateSourceMode === 'course') {
  767. return courseHeadingDeg === null ? sensorHeadingDeg : courseHeadingDeg
  768. }
  769. if (sensorHeadingDeg !== null && courseHeadingDeg !== null) {
  770. return interpolateAngleDeg(sensorHeadingDeg, courseHeadingDeg, 0.35)
  771. }
  772. return sensorHeadingDeg === null ? courseHeadingDeg : sensorHeadingDeg
  773. }
  774. calibrateAutoRotateToCurrentOrientation(): boolean {
  775. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  776. if (inputHeadingDeg === null) {
  777. return false
  778. }
  779. this.autoRotateCalibrationOffsetDeg = normalizeRotationDeg(this.state.rotationDeg + inputHeadingDeg)
  780. this.autoRotateCalibrationPending = false
  781. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  782. this.setState({
  783. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  784. })
  785. return true
  786. }
  787. refreshAutoRotateTarget(): boolean {
  788. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  789. if (inputHeadingDeg === null) {
  790. return false
  791. }
  792. if (this.autoRotateCalibrationPending || this.autoRotateCalibrationOffsetDeg === null) {
  793. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  794. return false
  795. }
  796. return true
  797. }
  798. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  799. this.setState({
  800. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  801. })
  802. return true
  803. }
  804. scheduleAutoRotate(): void {
  805. if (this.autoRotateTimer || this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  806. return
  807. }
  808. const step = () => {
  809. this.autoRotateTimer = 0
  810. if (this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  811. return
  812. }
  813. if (this.gestureMode !== 'idle' || this.inertiaTimer || this.previewResetTimer) {
  814. this.scheduleAutoRotate()
  815. return
  816. }
  817. const currentRotationDeg = this.state.rotationDeg
  818. const deltaDeg = normalizeAngleDeltaDeg(this.targetAutoRotationDeg - currentRotationDeg)
  819. if (Math.abs(deltaDeg) <= AUTO_ROTATE_SNAP_DEG) {
  820. if (Math.abs(deltaDeg) > 0.01) {
  821. this.applyAutoRotation(this.targetAutoRotationDeg)
  822. }
  823. this.scheduleAutoRotate()
  824. return
  825. }
  826. if (Math.abs(deltaDeg) <= AUTO_ROTATE_DEADZONE_DEG) {
  827. this.scheduleAutoRotate()
  828. return
  829. }
  830. const easedStepDeg = clamp(deltaDeg * AUTO_ROTATE_EASE, -AUTO_ROTATE_MAX_STEP_DEG, AUTO_ROTATE_MAX_STEP_DEG)
  831. this.applyAutoRotation(normalizeRotationDeg(currentRotationDeg + easedStepDeg))
  832. this.scheduleAutoRotate()
  833. }
  834. this.autoRotateTimer = setTimeout(step, AUTO_ROTATE_FRAME_MS) as unknown as number
  835. }
  836. applyAutoRotation(nextRotationDeg: number): void {
  837. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  838. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  839. this.state = {
  840. ...this.state,
  841. ...resolvedViewport,
  842. rotationDeg: nextRotationDeg,
  843. rotationText: formatRotationText(nextRotationDeg),
  844. centerText: buildCenterText(this.state.zoom, resolvedViewport.centerTileX, resolvedViewport.centerTileY),
  845. }
  846. this.syncRenderer()
  847. }
  848. applyStats(stats: MapRendererStats): void {
  849. this.setState({
  850. visibleTileCount: stats.visibleTileCount,
  851. readyTileCount: stats.readyTileCount,
  852. memoryTileCount: stats.memoryTileCount,
  853. diskTileCount: stats.diskTileCount,
  854. memoryHitCount: stats.memoryHitCount,
  855. diskHitCount: stats.diskHitCount,
  856. networkFetchCount: stats.networkFetchCount,
  857. cacheHitRateText: formatCacheHitRate(stats.memoryHitCount, stats.diskHitCount, stats.networkFetchCount),
  858. })
  859. }
  860. setState(patch: Partial<MapEngineViewState>, immediateUi = false): void {
  861. this.state = {
  862. ...this.state,
  863. ...patch,
  864. }
  865. const viewPatch = this.pickViewPatch(patch)
  866. if (!Object.keys(viewPatch).length) {
  867. return
  868. }
  869. this.pendingViewPatch = {
  870. ...this.pendingViewPatch,
  871. ...viewPatch,
  872. }
  873. if (immediateUi) {
  874. this.flushViewPatch()
  875. return
  876. }
  877. if (this.viewSyncTimer) {
  878. return
  879. }
  880. this.viewSyncTimer = setTimeout(() => {
  881. this.viewSyncTimer = 0
  882. this.flushViewPatch()
  883. }, UI_SYNC_INTERVAL_MS) as unknown as number
  884. }
  885. commitViewport(
  886. patch: Partial<MapEngineViewState>,
  887. statusText: string,
  888. immediateUi = false,
  889. afterUpdate?: () => void,
  890. ): void {
  891. const nextZoom = typeof patch.zoom === 'number' ? patch.zoom : this.state.zoom
  892. const nextCenterTileX = typeof patch.centerTileX === 'number' ? patch.centerTileX : this.state.centerTileX
  893. const nextCenterTileY = typeof patch.centerTileY === 'number' ? patch.centerTileY : this.state.centerTileY
  894. const nextStageWidth = typeof patch.stageWidth === 'number' ? patch.stageWidth : this.state.stageWidth
  895. const nextStageHeight = typeof patch.stageHeight === 'number' ? patch.stageHeight : this.state.stageHeight
  896. const tileSizePx = getTileSizePx({
  897. centerWorldX: nextCenterTileX,
  898. centerWorldY: nextCenterTileY,
  899. viewportWidth: nextStageWidth,
  900. viewportHeight: nextStageHeight,
  901. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  902. })
  903. this.setState({
  904. ...patch,
  905. tileSizePx,
  906. centerText: buildCenterText(nextZoom, nextCenterTileX, nextCenterTileY),
  907. statusText,
  908. }, immediateUi)
  909. this.syncRenderer()
  910. this.compassController.start()
  911. if (afterUpdate) {
  912. afterUpdate()
  913. }
  914. }
  915. buildScene() {
  916. return {
  917. tileSource: this.state.tileSource,
  918. zoom: this.state.zoom,
  919. centerTileX: this.state.centerTileX,
  920. centerTileY: this.state.centerTileY,
  921. viewportWidth: this.state.stageWidth,
  922. viewportHeight: this.state.stageHeight,
  923. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  924. overdraw: OVERDRAW,
  925. translateX: this.state.tileTranslateX,
  926. translateY: this.state.tileTranslateY,
  927. rotationRad: this.getRotationRad(this.state.rotationDeg),
  928. previewScale: this.previewScale || 1,
  929. previewOriginX: this.previewOriginX || this.state.stageWidth / 2,
  930. previewOriginY: this.previewOriginY || this.state.stageHeight / 2,
  931. track: SAMPLE_TRACK_WGS84,
  932. gpsPoint: SAMPLE_GPS_WGS84,
  933. }
  934. }
  935. syncRenderer(): void {
  936. if (!this.mounted || !this.state.stageWidth || !this.state.stageHeight) {
  937. return
  938. }
  939. this.renderer.updateScene(this.buildScene())
  940. }
  941. getCameraState(rotationDeg = this.state.rotationDeg): CameraState {
  942. return {
  943. centerWorldX: this.state.centerTileX,
  944. centerWorldY: this.state.centerTileY,
  945. viewportWidth: this.state.stageWidth,
  946. viewportHeight: this.state.stageHeight,
  947. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  948. translateX: this.state.tileTranslateX,
  949. translateY: this.state.tileTranslateY,
  950. rotationRad: this.getRotationRad(rotationDeg),
  951. }
  952. }
  953. getRotationRad(rotationDeg = this.state.rotationDeg): number {
  954. return normalizeRotationDeg(rotationDeg) * Math.PI / 180
  955. }
  956. getBaseCamera(centerWorldX = this.state.centerTileX, centerWorldY = this.state.centerTileY, rotationDeg = this.state.rotationDeg): CameraState {
  957. return {
  958. centerWorldX,
  959. centerWorldY,
  960. viewportWidth: this.state.stageWidth,
  961. viewportHeight: this.state.stageHeight,
  962. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  963. rotationRad: this.getRotationRad(rotationDeg),
  964. }
  965. }
  966. getWorldOffsetFromScreen(stageX: number, stageY: number, rotationDeg = this.state.rotationDeg): { x: number; y: number } {
  967. const baseCamera = {
  968. centerWorldX: 0,
  969. centerWorldY: 0,
  970. viewportWidth: this.state.stageWidth,
  971. viewportHeight: this.state.stageHeight,
  972. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  973. rotationRad: this.getRotationRad(rotationDeg),
  974. }
  975. return screenToWorld(baseCamera, { x: stageX, y: stageY }, false)
  976. }
  977. getExactCenterFromTranslate(translateX: number, translateY: number): { x: number; y: number } {
  978. if (!this.state.stageWidth || !this.state.stageHeight) {
  979. return {
  980. x: this.state.centerTileX,
  981. y: this.state.centerTileY,
  982. }
  983. }
  984. const screenCenterX = this.state.stageWidth / 2
  985. const screenCenterY = this.state.stageHeight / 2
  986. return screenToWorld(this.getBaseCamera(), {
  987. x: screenCenterX - translateX,
  988. y: screenCenterY - translateY,
  989. }, false)
  990. }
  991. resolveViewportForExactCenter(centerWorldX: number, centerWorldY: number, rotationDeg = this.state.rotationDeg): {
  992. centerTileX: number
  993. centerTileY: number
  994. tileTranslateX: number
  995. tileTranslateY: number
  996. } {
  997. const nextCenterTileX = Math.round(centerWorldX)
  998. const nextCenterTileY = Math.round(centerWorldY)
  999. if (!this.state.stageWidth || !this.state.stageHeight) {
  1000. return {
  1001. centerTileX: nextCenterTileX,
  1002. centerTileY: nextCenterTileY,
  1003. tileTranslateX: 0,
  1004. tileTranslateY: 0,
  1005. }
  1006. }
  1007. const roundedCamera = this.getBaseCamera(nextCenterTileX, nextCenterTileY, rotationDeg)
  1008. const projectedCenter = worldToScreen(roundedCamera, { x: centerWorldX, y: centerWorldY }, false)
  1009. return {
  1010. centerTileX: nextCenterTileX,
  1011. centerTileY: nextCenterTileY,
  1012. tileTranslateX: this.state.stageWidth / 2 - projectedCenter.x,
  1013. tileTranslateY: this.state.stageHeight / 2 - projectedCenter.y,
  1014. }
  1015. }
  1016. setPreviewState(scale: number, originX: number, originY: number): void {
  1017. this.previewScale = scale
  1018. this.previewOriginX = originX
  1019. this.previewOriginY = originY
  1020. }
  1021. resetPreviewState(): void {
  1022. this.setPreviewState(1, this.state.stageWidth / 2, this.state.stageHeight / 2)
  1023. }
  1024. resetPinchState(): void {
  1025. this.pinchStartDistance = 0
  1026. this.pinchStartScale = 1
  1027. this.pinchStartAngle = 0
  1028. this.pinchStartRotationDeg = this.state.rotationDeg
  1029. this.pinchAnchorWorldX = 0
  1030. this.pinchAnchorWorldY = 0
  1031. }
  1032. clearPreviewResetTimer(): void {
  1033. if (this.previewResetTimer) {
  1034. clearTimeout(this.previewResetTimer)
  1035. this.previewResetTimer = 0
  1036. }
  1037. }
  1038. clearInertiaTimer(): void {
  1039. if (this.inertiaTimer) {
  1040. clearTimeout(this.inertiaTimer)
  1041. this.inertiaTimer = 0
  1042. }
  1043. }
  1044. clearViewSyncTimer(): void {
  1045. if (this.viewSyncTimer) {
  1046. clearTimeout(this.viewSyncTimer)
  1047. this.viewSyncTimer = 0
  1048. }
  1049. }
  1050. clearAutoRotateTimer(): void {
  1051. if (this.autoRotateTimer) {
  1052. clearTimeout(this.autoRotateTimer)
  1053. this.autoRotateTimer = 0
  1054. }
  1055. }
  1056. pickViewPatch(patch: Partial<MapEngineViewState>): Partial<MapEngineViewState> {
  1057. const viewPatch = {} as Partial<MapEngineViewState>
  1058. for (const key of VIEW_SYNC_KEYS) {
  1059. if (Object.prototype.hasOwnProperty.call(patch, key)) {
  1060. ;(viewPatch as any)[key] = patch[key]
  1061. }
  1062. }
  1063. return viewPatch
  1064. }
  1065. flushViewPatch(): void {
  1066. if (!Object.keys(this.pendingViewPatch).length) {
  1067. return
  1068. }
  1069. const patch = this.pendingViewPatch
  1070. this.pendingViewPatch = {}
  1071. this.onData(patch)
  1072. }
  1073. getTouchDistance(touches: TouchPoint[]): number {
  1074. if (touches.length < 2) {
  1075. return 0
  1076. }
  1077. const first = touches[0]
  1078. const second = touches[1]
  1079. const deltaX = first.pageX - second.pageX
  1080. const deltaY = first.pageY - second.pageY
  1081. return Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  1082. }
  1083. getTouchAngle(touches: TouchPoint[]): number {
  1084. if (touches.length < 2) {
  1085. return 0
  1086. }
  1087. const first = touches[0]
  1088. const second = touches[1]
  1089. return Math.atan2(second.pageY - first.pageY, second.pageX - first.pageX)
  1090. }
  1091. getStagePoint(touches: TouchPoint[]): { x: number; y: number } {
  1092. if (!touches.length) {
  1093. return {
  1094. x: this.state.stageWidth / 2,
  1095. y: this.state.stageHeight / 2,
  1096. }
  1097. }
  1098. let pageX = 0
  1099. let pageY = 0
  1100. for (const touch of touches) {
  1101. pageX += touch.pageX
  1102. pageY += touch.pageY
  1103. }
  1104. return {
  1105. x: pageX / touches.length - this.state.stageLeft,
  1106. y: pageY / touches.length - this.state.stageTop,
  1107. }
  1108. }
  1109. animatePreviewToRest(): void {
  1110. this.clearPreviewResetTimer()
  1111. const startScale = this.previewScale || 1
  1112. const originX = this.previewOriginX || this.state.stageWidth / 2
  1113. const originY = this.previewOriginY || this.state.stageHeight / 2
  1114. if (Math.abs(startScale - 1) < 0.01) {
  1115. this.resetPreviewState()
  1116. this.syncRenderer()
  1117. this.compassController.start()
  1118. this.scheduleAutoRotate()
  1119. return
  1120. }
  1121. const startAt = Date.now()
  1122. const step = () => {
  1123. const progress = Math.min(1, (Date.now() - startAt) / PREVIEW_RESET_DURATION_MS)
  1124. const eased = 1 - Math.pow(1 - progress, 3)
  1125. const nextScale = startScale + (1 - startScale) * eased
  1126. this.setPreviewState(nextScale, originX, originY)
  1127. this.syncRenderer()
  1128. this.compassController.start()
  1129. if (progress >= 1) {
  1130. this.resetPreviewState()
  1131. this.syncRenderer()
  1132. this.compassController.start()
  1133. this.previewResetTimer = 0
  1134. this.scheduleAutoRotate()
  1135. return
  1136. }
  1137. this.previewResetTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  1138. }
  1139. step()
  1140. }
  1141. normalizeTranslate(translateX: number, translateY: number, statusText: string): void {
  1142. if (!this.state.stageWidth) {
  1143. this.setState({
  1144. tileTranslateX: translateX,
  1145. tileTranslateY: translateY,
  1146. })
  1147. this.syncRenderer()
  1148. this.compassController.start()
  1149. return
  1150. }
  1151. const exactCenter = this.getExactCenterFromTranslate(translateX, translateY)
  1152. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y)
  1153. const centerChanged = resolvedViewport.centerTileX !== this.state.centerTileX || resolvedViewport.centerTileY !== this.state.centerTileY
  1154. if (centerChanged) {
  1155. this.commitViewport(resolvedViewport, statusText)
  1156. return
  1157. }
  1158. this.setState({
  1159. tileTranslateX: resolvedViewport.tileTranslateX,
  1160. tileTranslateY: resolvedViewport.tileTranslateY,
  1161. })
  1162. this.syncRenderer()
  1163. this.compassController.start()
  1164. }
  1165. zoomAroundPoint(zoomDelta: number, stageX: number, stageY: number, residualScale: number): void {
  1166. const nextZoom = clamp(this.state.zoom + zoomDelta, MIN_ZOOM, MAX_ZOOM)
  1167. const appliedDelta = nextZoom - this.state.zoom
  1168. if (!appliedDelta) {
  1169. this.animatePreviewToRest()
  1170. return
  1171. }
  1172. if (!this.state.stageWidth || !this.state.stageHeight) {
  1173. this.commitViewport(
  1174. {
  1175. zoom: nextZoom,
  1176. centerTileX: appliedDelta > 0 ? this.state.centerTileX * 2 : Math.floor(this.state.centerTileX / 2),
  1177. centerTileY: appliedDelta > 0 ? this.state.centerTileY * 2 : Math.floor(this.state.centerTileY / 2),
  1178. tileTranslateX: 0,
  1179. tileTranslateY: 0,
  1180. },
  1181. `缩放级别调整到 ${nextZoom}`,
  1182. true,
  1183. () => {
  1184. this.setPreviewState(residualScale, stageX, stageY)
  1185. this.syncRenderer()
  1186. this.compassController.start()
  1187. this.animatePreviewToRest()
  1188. },
  1189. )
  1190. return
  1191. }
  1192. const camera = this.getCameraState()
  1193. const world = screenToWorld(camera, { x: stageX, y: stageY }, true)
  1194. const zoomFactor = Math.pow(2, appliedDelta)
  1195. const nextWorldX = world.x * zoomFactor
  1196. const nextWorldY = world.y * zoomFactor
  1197. const anchorOffset = this.getWorldOffsetFromScreen(stageX, stageY)
  1198. const exactCenterX = nextWorldX - anchorOffset.x
  1199. const exactCenterY = nextWorldY - anchorOffset.y
  1200. const resolvedViewport = this.resolveViewportForExactCenter(exactCenterX, exactCenterY)
  1201. this.commitViewport(
  1202. {
  1203. zoom: nextZoom,
  1204. ...resolvedViewport,
  1205. },
  1206. `缩放级别调整到 ${nextZoom}`,
  1207. true,
  1208. () => {
  1209. this.setPreviewState(residualScale, stageX, stageY)
  1210. this.syncRenderer()
  1211. this.compassController.start()
  1212. this.animatePreviewToRest()
  1213. },
  1214. )
  1215. }
  1216. startInertia(): void {
  1217. this.clearInertiaTimer()
  1218. const step = () => {
  1219. this.panVelocityX *= INERTIA_DECAY
  1220. this.panVelocityY *= INERTIA_DECAY
  1221. if (Math.abs(this.panVelocityX) < INERTIA_MIN_SPEED && Math.abs(this.panVelocityY) < INERTIA_MIN_SPEED) {
  1222. this.setState({
  1223. statusText: `惯性滑动结束 (${this.buildVersion})`,
  1224. })
  1225. this.renderer.setAnimationPaused(false)
  1226. this.inertiaTimer = 0
  1227. this.scheduleAutoRotate()
  1228. return
  1229. }
  1230. this.normalizeTranslate(
  1231. this.state.tileTranslateX + this.panVelocityX * INERTIA_FRAME_MS,
  1232. this.state.tileTranslateY + this.panVelocityY * INERTIA_FRAME_MS,
  1233. `惯性滑动中 (${this.buildVersion})`,
  1234. )
  1235. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  1236. }
  1237. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  1238. }
  1239. }