mapEngine.ts 52 KB

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