mapEngine.ts 57 KB

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