mapEngine.ts 56 KB

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