mapEngine.ts 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486
  1. import { getTileSizePx, screenToWorld, worldToScreen, type CameraState } from '../camera/camera'
  2. import { CompassHeadingController } from '../sensor/compassHeadingController'
  3. import { HeartRateController } from '../sensor/heartRateController'
  4. import { LocationController } from '../sensor/locationController'
  5. import { WebGLMapRenderer } from '../renderer/webglMapRenderer'
  6. import { type MapRendererStats } from '../renderer/mapRenderer'
  7. import { lonLatToWorldTile, worldTileToLonLat, type LonLatPoint, type MapCalibration } from '../../utils/projection'
  8. import { type OrienteeringCourseData } from '../../utils/orienteeringCourse'
  9. import { isTileWithinBounds, type RemoteMapConfig, type TileZoomBounds } from '../../utils/remoteMapConfig'
  10. import { GameRuntime } from '../../game/core/gameRuntime'
  11. import { type GameEffect } from '../../game/core/gameResult'
  12. import { buildGameDefinitionFromCourse } from '../../game/content/courseToGameDefinition'
  13. import { FeedbackDirector } from '../../game/feedback/feedbackDirector'
  14. import { EMPTY_GAME_PRESENTATION_STATE, type GamePresentationState } from '../../game/presentation/presentationState'
  15. import { TelemetryRuntime } from '../../game/telemetry/telemetryRuntime'
  16. import { getHeartRateToneSampleBpm, type HeartRateTone } from '../../game/telemetry/telemetryConfig'
  17. const RENDER_MODE = 'Single WebGL Pipeline'
  18. const PROJECTION_MODE = 'WGS84 -> WorldTile -> Camera -> Screen'
  19. const MAP_NORTH_OFFSET_DEG = 0
  20. let MAGNETIC_DECLINATION_DEG = -6.91
  21. let MAGNETIC_DECLINATION_TEXT = '6.91掳 W'
  22. const MIN_ZOOM = 15
  23. const MAX_ZOOM = 20
  24. const DEFAULT_ZOOM = 17
  25. const DESIRED_VISIBLE_COLUMNS = 3
  26. const OVERDRAW = 1
  27. const DEFAULT_TOP_LEFT_TILE_X = 108132
  28. const DEFAULT_TOP_LEFT_TILE_Y = 51199
  29. const DEFAULT_CENTER_TILE_X = DEFAULT_TOP_LEFT_TILE_X + 1
  30. const DEFAULT_CENTER_TILE_Y = DEFAULT_TOP_LEFT_TILE_Y + 1
  31. const TILE_SOURCE = 'https://oss-mbh5.colormaprun.com/wxMap/lcx/{z}/{x}/{y}.png'
  32. const OSM_TILE_SOURCE = 'https://tiles.mymarsgo.xyz/{z}/{x}/{y}.png'
  33. const MAP_OVERLAY_OPACITY = 0.72
  34. const GPS_MAP_CALIBRATION: MapCalibration = {
  35. offsetEastMeters: 0,
  36. offsetNorthMeters: 0,
  37. rotationDeg: 0,
  38. scale: 1,
  39. }
  40. const MIN_PREVIEW_SCALE = 0.55
  41. const MAX_PREVIEW_SCALE = 1.85
  42. const INERTIA_FRAME_MS = 16
  43. const INERTIA_DECAY = 0.92
  44. const INERTIA_MIN_SPEED = 0.02
  45. const PREVIEW_RESET_DURATION_MS = 140
  46. const UI_SYNC_INTERVAL_MS = 80
  47. const ROTATE_STEP_DEG = 15
  48. const AUTO_ROTATE_FRAME_MS = 8
  49. const AUTO_ROTATE_EASE = 0.34
  50. const AUTO_ROTATE_SNAP_DEG = 0.1
  51. const AUTO_ROTATE_DEADZONE_DEG = 4
  52. const AUTO_ROTATE_MAX_STEP_DEG = 0.75
  53. const AUTO_ROTATE_HEADING_SMOOTHING = 0.32
  54. const COMPASS_NEEDLE_SMOOTHING = 0.12
  55. const GPS_TRACK_MAX_POINTS = 200
  56. const GPS_TRACK_MIN_STEP_METERS = 3
  57. type TouchPoint = WechatMiniprogram.TouchDetail
  58. type GestureMode = 'idle' | 'pan' | 'pinch'
  59. type RotationMode = 'manual' | 'auto'
  60. type OrientationMode = 'manual' | 'north-up' | 'heading-up'
  61. type AutoRotateSourceMode = 'sensor' | 'course' | 'fusion'
  62. type NorthReferenceMode = 'magnetic' | 'true'
  63. const DEFAULT_NORTH_REFERENCE_MODE: NorthReferenceMode = 'magnetic'
  64. export interface MapEngineStageRect {
  65. width: number
  66. height: number
  67. left: number
  68. top: number
  69. }
  70. export interface MapEngineViewState {
  71. buildVersion: string
  72. renderMode: string
  73. projectionMode: string
  74. mapReady: boolean
  75. mapReadyText: string
  76. mapName: string
  77. configStatusText: string
  78. zoom: number
  79. rotationDeg: number
  80. rotationText: string
  81. rotationMode: RotationMode
  82. rotationModeText: string
  83. rotationToggleText: string
  84. orientationMode: OrientationMode
  85. orientationModeText: string
  86. sensorHeadingText: string
  87. compassDeclinationText: string
  88. northReferenceButtonText: string
  89. autoRotateSourceText: string
  90. autoRotateCalibrationText: string
  91. northReferenceText: string
  92. compassNeedleDeg: number
  93. centerTileX: number
  94. centerTileY: number
  95. centerText: string
  96. tileSource: string
  97. visibleColumnCount: number
  98. visibleTileCount: number
  99. readyTileCount: number
  100. memoryTileCount: number
  101. diskTileCount: number
  102. memoryHitCount: number
  103. diskHitCount: number
  104. networkFetchCount: number
  105. cacheHitRateText: string
  106. tileTranslateX: number
  107. tileTranslateY: number
  108. tileSizePx: number
  109. stageWidth: number
  110. stageHeight: number
  111. stageLeft: number
  112. stageTop: number
  113. statusText: string
  114. gpsTracking: boolean
  115. gpsTrackingText: string
  116. gpsCoordText: string
  117. heartRateConnected: boolean
  118. heartRateStatusText: string
  119. heartRateDeviceText: string
  120. gameSessionStatus: 'idle' | 'running' | 'finished' | 'failed'
  121. panelTimerText: string
  122. panelMileageText: string
  123. panelDistanceValueText: string
  124. panelDistanceUnitText: string
  125. panelProgressText: string
  126. panelSpeedValueText: string
  127. panelTelemetryTone: 'blue' | 'purple' | 'green' | 'yellow' | 'orange' | 'red'
  128. panelHeartRateZoneNameText: string
  129. panelHeartRateZoneRangeText: string
  130. panelHeartRateValueText: string
  131. panelHeartRateUnitText: string
  132. panelCaloriesValueText: string
  133. panelCaloriesUnitText: string
  134. panelAverageSpeedValueText: string
  135. panelAverageSpeedUnitText: string
  136. panelAccuracyValueText: string
  137. panelAccuracyUnitText: string
  138. punchButtonText: string
  139. punchButtonEnabled: boolean
  140. punchHintText: string
  141. punchFeedbackVisible: boolean
  142. punchFeedbackText: string
  143. punchFeedbackTone: 'neutral' | 'success' | 'warning'
  144. contentCardVisible: boolean
  145. contentCardTitle: string
  146. contentCardBody: string
  147. punchButtonFxClass: string
  148. punchFeedbackFxClass: string
  149. contentCardFxClass: string
  150. mapPulseVisible: boolean
  151. mapPulseLeftPx: number
  152. mapPulseTopPx: number
  153. mapPulseFxClass: string
  154. stageFxVisible: boolean
  155. stageFxClass: string
  156. osmReferenceEnabled: boolean
  157. osmReferenceText: string
  158. }
  159. export interface MapEngineCallbacks {
  160. onData: (patch: Partial<MapEngineViewState>) => void
  161. }
  162. const VIEW_SYNC_KEYS: Array<keyof MapEngineViewState> = [
  163. 'buildVersion',
  164. 'renderMode',
  165. 'projectionMode',
  166. 'mapReady',
  167. 'mapReadyText',
  168. 'mapName',
  169. 'configStatusText',
  170. 'zoom',
  171. 'rotationDeg',
  172. 'rotationText',
  173. 'rotationMode',
  174. 'rotationModeText',
  175. 'rotationToggleText',
  176. 'orientationMode',
  177. 'orientationModeText',
  178. 'sensorHeadingText',
  179. 'compassDeclinationText',
  180. 'northReferenceButtonText',
  181. 'autoRotateSourceText',
  182. 'autoRotateCalibrationText',
  183. 'northReferenceText',
  184. 'compassNeedleDeg',
  185. 'centerText',
  186. 'tileSource',
  187. 'visibleTileCount',
  188. 'readyTileCount',
  189. 'memoryTileCount',
  190. 'diskTileCount',
  191. 'memoryHitCount',
  192. 'diskHitCount',
  193. 'networkFetchCount',
  194. 'cacheHitRateText',
  195. 'tileSizePx',
  196. 'statusText',
  197. 'gpsTracking',
  198. 'gpsTrackingText',
  199. 'gpsCoordText',
  200. 'heartRateConnected',
  201. 'heartRateStatusText',
  202. 'heartRateDeviceText',
  203. 'gameSessionStatus',
  204. 'panelTimerText',
  205. 'panelMileageText',
  206. 'panelDistanceValueText',
  207. 'panelDistanceUnitText',
  208. 'panelProgressText',
  209. 'panelSpeedValueText',
  210. 'panelTelemetryTone',
  211. 'panelHeartRateZoneNameText',
  212. 'panelHeartRateZoneRangeText',
  213. 'panelHeartRateValueText',
  214. 'panelHeartRateUnitText',
  215. 'panelCaloriesValueText',
  216. 'panelCaloriesUnitText',
  217. 'panelAverageSpeedValueText',
  218. 'panelAverageSpeedUnitText',
  219. 'panelAccuracyValueText',
  220. 'panelAccuracyUnitText',
  221. 'punchButtonText',
  222. 'punchButtonEnabled',
  223. 'punchHintText',
  224. 'punchFeedbackVisible',
  225. 'punchFeedbackText',
  226. 'punchFeedbackTone',
  227. 'contentCardVisible',
  228. 'contentCardTitle',
  229. 'contentCardBody',
  230. 'punchButtonFxClass',
  231. 'punchFeedbackFxClass',
  232. 'contentCardFxClass',
  233. 'mapPulseVisible',
  234. 'mapPulseLeftPx',
  235. 'mapPulseTopPx',
  236. 'mapPulseFxClass',
  237. 'stageFxVisible',
  238. 'stageFxClass',
  239. 'osmReferenceEnabled',
  240. 'osmReferenceText',
  241. ]
  242. function buildCenterText(zoom: number, x: number, y: number): string {
  243. return `z${zoom} / x${x} / y${y}`
  244. }
  245. function clamp(value: number, min: number, max: number): number {
  246. return Math.max(min, Math.min(max, value))
  247. }
  248. function normalizeRotationDeg(rotationDeg: number): number {
  249. const normalized = rotationDeg % 360
  250. return normalized < 0 ? normalized + 360 : normalized
  251. }
  252. function normalizeAngleDeltaRad(angleDeltaRad: number): number {
  253. let normalized = angleDeltaRad
  254. while (normalized > Math.PI) {
  255. normalized -= Math.PI * 2
  256. }
  257. while (normalized < -Math.PI) {
  258. normalized += Math.PI * 2
  259. }
  260. return normalized
  261. }
  262. function normalizeAngleDeltaDeg(angleDeltaDeg: number): number {
  263. let normalized = angleDeltaDeg
  264. while (normalized > 180) {
  265. normalized -= 360
  266. }
  267. while (normalized < -180) {
  268. normalized += 360
  269. }
  270. return normalized
  271. }
  272. function interpolateAngleDeg(currentDeg: number, targetDeg: number, factor: number): number {
  273. return normalizeRotationDeg(currentDeg + normalizeAngleDeltaDeg(targetDeg - currentDeg) * factor)
  274. }
  275. function formatRotationText(rotationDeg: number): string {
  276. return `${Math.round(normalizeRotationDeg(rotationDeg))}deg`
  277. }
  278. function formatHeadingText(headingDeg: number | null): string {
  279. if (headingDeg === null) {
  280. return '--'
  281. }
  282. return `${Math.round(normalizeRotationDeg(headingDeg))}掳`
  283. }
  284. function formatOrientationModeText(mode: OrientationMode): string {
  285. if (mode === 'north-up') {
  286. return 'North Up'
  287. }
  288. if (mode === 'heading-up') {
  289. return 'Heading Up'
  290. }
  291. return 'Manual Gesture'
  292. }
  293. function formatRotationModeText(mode: OrientationMode): string {
  294. return formatOrientationModeText(mode)
  295. }
  296. function formatRotationToggleText(mode: OrientationMode): string {
  297. if (mode === 'manual') {
  298. return '切到北朝上'
  299. }
  300. if (mode === 'north-up') {
  301. return '切到朝向朝上'
  302. }
  303. return '切到手动旋转'
  304. }
  305. function formatAutoRotateSourceText(mode: AutoRotateSourceMode, hasCourseHeading: boolean): string {
  306. if (mode === 'sensor') {
  307. return 'Sensor Only'
  308. }
  309. if (mode === 'course') {
  310. return hasCourseHeading ? 'Course Only' : 'Course Pending'
  311. }
  312. return hasCourseHeading ? 'Sensor + Course' : 'Sensor Only'
  313. }
  314. function formatAutoRotateCalibrationText(pending: boolean, offsetDeg: number | null): string {
  315. if (pending) {
  316. return 'Pending'
  317. }
  318. if (offsetDeg === null) {
  319. return '--'
  320. }
  321. return `Offset ${Math.round(normalizeRotationDeg(offsetDeg))}deg`
  322. }
  323. function getTrueHeadingDeg(magneticHeadingDeg: number): number {
  324. return normalizeRotationDeg(magneticHeadingDeg + MAGNETIC_DECLINATION_DEG)
  325. }
  326. function getMagneticHeadingDeg(trueHeadingDeg: number): number {
  327. return normalizeRotationDeg(trueHeadingDeg - MAGNETIC_DECLINATION_DEG)
  328. }
  329. function getMapNorthOffsetDeg(_mode: NorthReferenceMode): number {
  330. return MAP_NORTH_OFFSET_DEG
  331. }
  332. function getCompassReferenceHeadingDeg(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  333. if (mode === 'true') {
  334. return getTrueHeadingDeg(magneticHeadingDeg)
  335. }
  336. return normalizeRotationDeg(magneticHeadingDeg)
  337. }
  338. function getMapReferenceHeadingDegFromSensor(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  339. if (mode === 'magnetic') {
  340. return normalizeRotationDeg(magneticHeadingDeg)
  341. }
  342. return getTrueHeadingDeg(magneticHeadingDeg)
  343. }
  344. function getMapReferenceHeadingDegFromCourse(mode: NorthReferenceMode, trueHeadingDeg: number): number {
  345. if (mode === 'magnetic') {
  346. return getMagneticHeadingDeg(trueHeadingDeg)
  347. }
  348. return normalizeRotationDeg(trueHeadingDeg)
  349. }
  350. function formatNorthReferenceText(mode: NorthReferenceMode): string {
  351. if (mode === 'magnetic') {
  352. return `Compass Magnetic / Heading-Up Magnetic (${MAGNETIC_DECLINATION_TEXT})`
  353. }
  354. return `Compass True / Heading-Up True (${MAGNETIC_DECLINATION_TEXT})`
  355. }
  356. function formatCompassDeclinationText(mode: NorthReferenceMode): string {
  357. if (mode === 'true') {
  358. return MAGNETIC_DECLINATION_TEXT
  359. }
  360. return ''
  361. }
  362. function formatNorthReferenceButtonText(mode: NorthReferenceMode): string {
  363. return mode === 'magnetic' ? '北参照:磁北' : '北参照:真北'
  364. }
  365. function formatNorthReferenceStatusText(mode: NorthReferenceMode): string {
  366. if (mode === 'magnetic') {
  367. return '已切到磁北模式'
  368. }
  369. return '已切到真北模式'
  370. }
  371. function getNextNorthReferenceMode(mode: NorthReferenceMode): NorthReferenceMode {
  372. return mode === 'magnetic' ? 'true' : 'magnetic'
  373. }
  374. function formatCompassNeedleDegForMode(mode: NorthReferenceMode, magneticHeadingDeg: number | null): number {
  375. if (magneticHeadingDeg === null) {
  376. return 0
  377. }
  378. const referenceHeadingDeg = mode === 'true'
  379. ? getTrueHeadingDeg(magneticHeadingDeg)
  380. : normalizeRotationDeg(magneticHeadingDeg)
  381. return normalizeRotationDeg(360 - referenceHeadingDeg)
  382. }
  383. function formatCacheHitRate(memoryHitCount: number, diskHitCount: number, networkFetchCount: number): string {
  384. const total = memoryHitCount + diskHitCount + networkFetchCount
  385. if (!total) {
  386. return '--'
  387. }
  388. const hitRate = ((memoryHitCount + diskHitCount) / total) * 100
  389. return `${Math.round(hitRate)}%`
  390. }
  391. function formatGpsCoordText(point: LonLatPoint | null, accuracyMeters: number | null): string {
  392. if (!point) {
  393. return '--'
  394. }
  395. const base = `${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}`
  396. if (accuracyMeters === null || !Number.isFinite(accuracyMeters)) {
  397. return base
  398. }
  399. return `${base} / 卤${Math.round(accuracyMeters)}m`
  400. }
  401. function getApproxDistanceMeters(a: LonLatPoint, b: LonLatPoint): number {
  402. const avgLatRad = ((a.lat + b.lat) / 2) * Math.PI / 180
  403. const dx = (b.lon - a.lon) * 111320 * Math.cos(avgLatRad)
  404. const dy = (b.lat - a.lat) * 110540
  405. return Math.sqrt(dx * dx + dy * dy)
  406. }
  407. function getInitialBearingDeg(from: LonLatPoint, to: LonLatPoint): number {
  408. const fromLatRad = from.lat * Math.PI / 180
  409. const toLatRad = to.lat * Math.PI / 180
  410. const deltaLonRad = (to.lon - from.lon) * Math.PI / 180
  411. const y = Math.sin(deltaLonRad) * Math.cos(toLatRad)
  412. const x = Math.cos(fromLatRad) * Math.sin(toLatRad) - Math.sin(fromLatRad) * Math.cos(toLatRad) * Math.cos(deltaLonRad)
  413. const bearingDeg = Math.atan2(y, x) * 180 / Math.PI
  414. return normalizeRotationDeg(bearingDeg)
  415. }
  416. export class MapEngine {
  417. buildVersion: string
  418. renderer: WebGLMapRenderer
  419. compassController: CompassHeadingController
  420. locationController: LocationController
  421. heartRateController: HeartRateController
  422. feedbackDirector: FeedbackDirector
  423. onData: (patch: Partial<MapEngineViewState>) => void
  424. state: MapEngineViewState
  425. previewScale: number
  426. previewOriginX: number
  427. previewOriginY: number
  428. panLastX: number
  429. panLastY: number
  430. panLastTimestamp: number
  431. panVelocityX: number
  432. panVelocityY: number
  433. pinchStartDistance: number
  434. pinchStartScale: number
  435. pinchStartAngle: number
  436. pinchStartRotationDeg: number
  437. pinchAnchorWorldX: number
  438. pinchAnchorWorldY: number
  439. gestureMode: GestureMode
  440. inertiaTimer: number
  441. previewResetTimer: number
  442. viewSyncTimer: number
  443. autoRotateTimer: number
  444. pendingViewPatch: Partial<MapEngineViewState>
  445. mounted: boolean
  446. northReferenceMode: NorthReferenceMode
  447. sensorHeadingDeg: number | null
  448. smoothedSensorHeadingDeg: number | null
  449. compassDisplayHeadingDeg: number | null
  450. autoRotateHeadingDeg: number | null
  451. courseHeadingDeg: number | null
  452. targetAutoRotationDeg: number | null
  453. autoRotateSourceMode: AutoRotateSourceMode
  454. autoRotateCalibrationOffsetDeg: number | null
  455. autoRotateCalibrationPending: boolean
  456. minZoom: number
  457. maxZoom: number
  458. defaultZoom: number
  459. defaultCenterTileX: number
  460. defaultCenterTileY: number
  461. tileBoundsByZoom: Record<number, TileZoomBounds> | null
  462. currentGpsPoint: LonLatPoint | null
  463. currentGpsTrack: LonLatPoint[]
  464. currentGpsAccuracyMeters: number | null
  465. courseData: OrienteeringCourseData | null
  466. cpRadiusMeters: number
  467. gameRuntime: GameRuntime
  468. telemetryRuntime: TelemetryRuntime
  469. gamePresentation: GamePresentationState
  470. gameMode: 'classic-sequential'
  471. punchPolicy: 'enter' | 'enter-confirm'
  472. punchRadiusMeters: number
  473. autoFinishOnLastControl: boolean
  474. punchFeedbackTimer: number
  475. contentCardTimer: number
  476. mapPulseTimer: number
  477. stageFxTimer: number
  478. sessionTimerInterval: number
  479. hasGpsCenteredOnce: boolean
  480. constructor(buildVersion: string, callbacks: MapEngineCallbacks) {
  481. this.buildVersion = buildVersion
  482. this.onData = callbacks.onData
  483. this.renderer = new WebGLMapRenderer(
  484. (stats) => {
  485. this.applyStats(stats)
  486. },
  487. (message) => {
  488. this.setState({
  489. statusText: `${message} (${this.buildVersion})`,
  490. })
  491. },
  492. )
  493. this.compassController = new CompassHeadingController({
  494. onHeading: (headingDeg) => {
  495. this.handleCompassHeading(headingDeg)
  496. },
  497. onError: (message) => {
  498. this.handleCompassError(message)
  499. },
  500. })
  501. this.locationController = new LocationController({
  502. onLocation: (update) => {
  503. this.handleLocationUpdate(update.longitude, update.latitude, typeof update.accuracy === 'number' ? update.accuracy : null)
  504. },
  505. onStatus: (message) => {
  506. this.setState({
  507. gpsTracking: this.locationController.listening,
  508. gpsTrackingText: message,
  509. }, true)
  510. },
  511. onError: (message) => {
  512. this.setState({
  513. gpsTracking: false,
  514. gpsTrackingText: message,
  515. statusText: `${message} (${this.buildVersion})`,
  516. }, true)
  517. },
  518. })
  519. this.heartRateController = new HeartRateController({
  520. onHeartRate: (bpm) => {
  521. this.telemetryRuntime.dispatch({
  522. type: 'heart_rate_updated',
  523. at: Date.now(),
  524. bpm,
  525. })
  526. this.syncSessionTimerText()
  527. },
  528. onStatus: (message) => {
  529. this.setState({
  530. heartRateStatusText: message,
  531. heartRateDeviceText: this.heartRateController.currentDeviceName || '--',
  532. }, true)
  533. },
  534. onError: (message) => {
  535. this.setState({
  536. heartRateConnected: false,
  537. heartRateStatusText: message,
  538. heartRateDeviceText: '--',
  539. statusText: `${message} (${this.buildVersion})`,
  540. }, true)
  541. },
  542. onConnectionChange: (connected, deviceName) => {
  543. this.setState({
  544. heartRateConnected: connected,
  545. heartRateDeviceText: deviceName || '--',
  546. heartRateStatusText: connected ? '心率带已连接' : '心率带未连接',
  547. }, true)
  548. },
  549. })
  550. this.feedbackDirector = new FeedbackDirector({
  551. showPunchFeedback: (text, tone, motionClass) => {
  552. this.showPunchFeedback(text, tone, motionClass)
  553. },
  554. showContentCard: (title, body, motionClass) => {
  555. this.showContentCard(title, body, motionClass)
  556. },
  557. setPunchButtonFxClass: (className) => {
  558. this.setPunchButtonFxClass(className)
  559. },
  560. showMapPulse: (controlId, motionClass) => {
  561. this.showMapPulse(controlId, motionClass)
  562. },
  563. showStageFx: (className) => {
  564. this.showStageFx(className)
  565. },
  566. stopLocationTracking: () => {
  567. if (this.locationController.listening) {
  568. this.locationController.stop()
  569. }
  570. },
  571. })
  572. this.minZoom = MIN_ZOOM
  573. this.maxZoom = MAX_ZOOM
  574. this.defaultZoom = DEFAULT_ZOOM
  575. this.defaultCenterTileX = DEFAULT_CENTER_TILE_X
  576. this.defaultCenterTileY = DEFAULT_CENTER_TILE_Y
  577. this.tileBoundsByZoom = null
  578. this.currentGpsPoint = null
  579. this.currentGpsTrack = []
  580. this.currentGpsAccuracyMeters = null
  581. this.courseData = null
  582. this.cpRadiusMeters = 5
  583. this.gameRuntime = new GameRuntime()
  584. this.telemetryRuntime = new TelemetryRuntime()
  585. this.telemetryRuntime.configure()
  586. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  587. this.gameMode = 'classic-sequential'
  588. this.punchPolicy = 'enter-confirm'
  589. this.punchRadiusMeters = 5
  590. this.autoFinishOnLastControl = true
  591. this.punchFeedbackTimer = 0
  592. this.contentCardTimer = 0
  593. this.mapPulseTimer = 0
  594. this.stageFxTimer = 0
  595. this.sessionTimerInterval = 0
  596. this.hasGpsCenteredOnce = false
  597. this.state = {
  598. buildVersion: this.buildVersion,
  599. renderMode: RENDER_MODE,
  600. projectionMode: PROJECTION_MODE,
  601. mapReady: false,
  602. mapReadyText: 'BOOTING',
  603. mapName: 'LCX 测试地图',
  604. configStatusText: '远程配置待加载',
  605. zoom: DEFAULT_ZOOM,
  606. rotationDeg: 0,
  607. rotationText: formatRotationText(0),
  608. rotationMode: 'manual',
  609. rotationModeText: formatRotationModeText('manual'),
  610. rotationToggleText: formatRotationToggleText('manual'),
  611. orientationMode: 'manual',
  612. orientationModeText: formatOrientationModeText('manual'),
  613. sensorHeadingText: '--',
  614. compassDeclinationText: formatCompassDeclinationText(DEFAULT_NORTH_REFERENCE_MODE),
  615. northReferenceButtonText: formatNorthReferenceButtonText(DEFAULT_NORTH_REFERENCE_MODE),
  616. autoRotateSourceText: formatAutoRotateSourceText('sensor', false),
  617. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)),
  618. northReferenceText: formatNorthReferenceText(DEFAULT_NORTH_REFERENCE_MODE),
  619. compassNeedleDeg: 0,
  620. centerTileX: DEFAULT_CENTER_TILE_X,
  621. centerTileY: DEFAULT_CENTER_TILE_Y,
  622. centerText: buildCenterText(DEFAULT_ZOOM, DEFAULT_CENTER_TILE_X, DEFAULT_CENTER_TILE_Y),
  623. tileSource: TILE_SOURCE,
  624. visibleColumnCount: DESIRED_VISIBLE_COLUMNS,
  625. visibleTileCount: 0,
  626. readyTileCount: 0,
  627. memoryTileCount: 0,
  628. diskTileCount: 0,
  629. memoryHitCount: 0,
  630. diskHitCount: 0,
  631. networkFetchCount: 0,
  632. cacheHitRateText: '--',
  633. tileTranslateX: 0,
  634. tileTranslateY: 0,
  635. tileSizePx: 0,
  636. stageWidth: 0,
  637. stageHeight: 0,
  638. stageLeft: 0,
  639. stageTop: 0,
  640. statusText: `单 WebGL 管线已就绪,等待传感器接入 (${this.buildVersion})`,
  641. gpsTracking: false,
  642. gpsTrackingText: '持续定位待启动',
  643. gpsCoordText: '--',
  644. heartRateConnected: false,
  645. heartRateStatusText: '心率带未连接',
  646. heartRateDeviceText: '--',
  647. panelTimerText: '00:00:00',
  648. panelMileageText: '0m',
  649. panelDistanceValueText: '--',
  650. panelDistanceUnitText: '',
  651. panelProgressText: '0/0',
  652. panelSpeedValueText: '0',
  653. panelTelemetryTone: 'blue',
  654. panelHeartRateZoneNameText: '激活放松',
  655. panelHeartRateZoneRangeText: '<=39%',
  656. panelHeartRateValueText: '--',
  657. panelHeartRateUnitText: '',
  658. panelCaloriesValueText: '0',
  659. panelCaloriesUnitText: 'kcal',
  660. panelAverageSpeedValueText: '0',
  661. panelAverageSpeedUnitText: 'km/h',
  662. panelAccuracyValueText: '--',
  663. panelAccuracyUnitText: '',
  664. punchButtonText: '打点',
  665. gameSessionStatus: 'idle',
  666. punchButtonEnabled: false,
  667. punchHintText: '等待进入检查点范围',
  668. punchFeedbackVisible: false,
  669. punchFeedbackText: '',
  670. punchFeedbackTone: 'neutral',
  671. contentCardVisible: false,
  672. contentCardTitle: '',
  673. contentCardBody: '',
  674. punchButtonFxClass: '',
  675. punchFeedbackFxClass: '',
  676. contentCardFxClass: '',
  677. mapPulseVisible: false,
  678. mapPulseLeftPx: 0,
  679. mapPulseTopPx: 0,
  680. mapPulseFxClass: '',
  681. stageFxVisible: false,
  682. stageFxClass: '',
  683. osmReferenceEnabled: false,
  684. osmReferenceText: 'OSM参考:关',
  685. }
  686. this.previewScale = 1
  687. this.previewOriginX = 0
  688. this.previewOriginY = 0
  689. this.panLastX = 0
  690. this.panLastY = 0
  691. this.panLastTimestamp = 0
  692. this.panVelocityX = 0
  693. this.panVelocityY = 0
  694. this.pinchStartDistance = 0
  695. this.pinchStartScale = 1
  696. this.pinchStartAngle = 0
  697. this.pinchStartRotationDeg = 0
  698. this.pinchAnchorWorldX = 0
  699. this.pinchAnchorWorldY = 0
  700. this.gestureMode = 'idle'
  701. this.inertiaTimer = 0
  702. this.previewResetTimer = 0
  703. this.viewSyncTimer = 0
  704. this.autoRotateTimer = 0
  705. this.pendingViewPatch = {}
  706. this.mounted = false
  707. this.northReferenceMode = DEFAULT_NORTH_REFERENCE_MODE
  708. this.sensorHeadingDeg = null
  709. this.smoothedSensorHeadingDeg = null
  710. this.compassDisplayHeadingDeg = null
  711. this.autoRotateHeadingDeg = null
  712. this.courseHeadingDeg = null
  713. this.targetAutoRotationDeg = null
  714. this.autoRotateSourceMode = 'sensor'
  715. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)
  716. this.autoRotateCalibrationPending = false
  717. }
  718. getInitialData(): MapEngineViewState {
  719. return { ...this.state }
  720. }
  721. destroy(): void {
  722. this.clearInertiaTimer()
  723. this.clearPreviewResetTimer()
  724. this.clearViewSyncTimer()
  725. this.clearAutoRotateTimer()
  726. this.clearPunchFeedbackTimer()
  727. this.clearContentCardTimer()
  728. this.clearMapPulseTimer()
  729. this.clearStageFxTimer()
  730. this.clearSessionTimerInterval()
  731. this.compassController.destroy()
  732. this.locationController.destroy()
  733. this.heartRateController.destroy()
  734. this.feedbackDirector.destroy()
  735. this.renderer.destroy()
  736. this.mounted = false
  737. }
  738. clearGameRuntime(): void {
  739. this.gameRuntime.clear()
  740. this.telemetryRuntime.reset()
  741. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  742. this.clearSessionTimerInterval()
  743. this.setCourseHeading(null)
  744. }
  745. loadGameDefinitionFromCourse(): GameEffect[] {
  746. if (!this.courseData) {
  747. this.clearGameRuntime()
  748. return []
  749. }
  750. const definition = buildGameDefinitionFromCourse(
  751. this.courseData,
  752. this.cpRadiusMeters,
  753. this.gameMode,
  754. this.autoFinishOnLastControl,
  755. this.punchPolicy,
  756. this.punchRadiusMeters,
  757. )
  758. const result = this.gameRuntime.loadDefinition(definition)
  759. this.telemetryRuntime.loadDefinition(definition)
  760. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, result.nextState)
  761. this.gamePresentation = result.presentation
  762. this.refreshCourseHeadingFromPresentation()
  763. this.updateSessionTimerLoop()
  764. return result.effects
  765. }
  766. refreshCourseHeadingFromPresentation(): void {
  767. if (!this.courseData || !this.gamePresentation.activeLegIndices.length) {
  768. this.setCourseHeading(null)
  769. return
  770. }
  771. const activeLegIndex = this.gamePresentation.activeLegIndices[0]
  772. const activeLeg = this.courseData.layers.legs[activeLegIndex]
  773. if (!activeLeg) {
  774. this.setCourseHeading(null)
  775. return
  776. }
  777. this.setCourseHeading(getInitialBearingDeg(activeLeg.fromPoint, activeLeg.toPoint))
  778. }
  779. resolveGameStatusText(effects: GameEffect[]): string | null {
  780. const lastEffect = effects.length ? effects[effects.length - 1] : null
  781. if (!lastEffect) {
  782. return null
  783. }
  784. if (lastEffect.type === 'control_completed') {
  785. const sequenceText = typeof lastEffect.sequence === 'number' ? String(lastEffect.sequence) : lastEffect.controlId
  786. return `宸插畬鎴愭鏌ョ偣 ${sequenceText} (${this.buildVersion})`
  787. }
  788. if (lastEffect.type === 'session_finished') {
  789. return `璺嚎宸插畬鎴?(${this.buildVersion})`
  790. }
  791. if (lastEffect.type === 'session_started') {
  792. return `椤哄簭鎵撶偣宸插紑濮?(${this.buildVersion})`
  793. }
  794. return null
  795. }
  796. getGameViewPatch(statusText?: string | null): Partial<MapEngineViewState> {
  797. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  798. const patch: Partial<MapEngineViewState> = {
  799. gameSessionStatus: this.gameRuntime.state ? this.gameRuntime.state.status : 'idle',
  800. panelTimerText: telemetryPresentation.timerText,
  801. panelMileageText: telemetryPresentation.mileageText,
  802. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  803. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  804. panelSpeedValueText: telemetryPresentation.speedText,
  805. panelTelemetryTone: telemetryPresentation.heartRateTone,
  806. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  807. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  808. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  809. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  810. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  811. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  812. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  813. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  814. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  815. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  816. panelProgressText: this.gamePresentation.progressText,
  817. punchButtonText: this.gamePresentation.punchButtonText,
  818. punchButtonEnabled: this.gamePresentation.punchButtonEnabled,
  819. punchHintText: this.gamePresentation.punchHintText,
  820. }
  821. if (statusText) {
  822. patch.statusText = statusText
  823. }
  824. return patch
  825. }
  826. clearPunchFeedbackTimer(): void {
  827. if (this.punchFeedbackTimer) {
  828. clearTimeout(this.punchFeedbackTimer)
  829. this.punchFeedbackTimer = 0
  830. }
  831. }
  832. clearContentCardTimer(): void {
  833. if (this.contentCardTimer) {
  834. clearTimeout(this.contentCardTimer)
  835. this.contentCardTimer = 0
  836. }
  837. }
  838. clearMapPulseTimer(): void {
  839. if (this.mapPulseTimer) {
  840. clearTimeout(this.mapPulseTimer)
  841. this.mapPulseTimer = 0
  842. }
  843. }
  844. clearStageFxTimer(): void {
  845. if (this.stageFxTimer) {
  846. clearTimeout(this.stageFxTimer)
  847. this.stageFxTimer = 0
  848. }
  849. }
  850. clearSessionTimerInterval(): void {
  851. if (this.sessionTimerInterval) {
  852. clearInterval(this.sessionTimerInterval)
  853. this.sessionTimerInterval = 0
  854. }
  855. }
  856. syncSessionTimerText(): void {
  857. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  858. this.setState({
  859. panelTimerText: telemetryPresentation.timerText,
  860. panelMileageText: telemetryPresentation.mileageText,
  861. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  862. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  863. panelSpeedValueText: telemetryPresentation.speedText,
  864. panelTelemetryTone: telemetryPresentation.heartRateTone,
  865. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  866. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  867. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  868. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  869. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  870. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  871. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  872. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  873. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  874. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  875. }, true)
  876. }
  877. updateSessionTimerLoop(): void {
  878. const gameState = this.gameRuntime.state
  879. const shouldRun = !!gameState && gameState.status === 'running' && gameState.endedAt === null
  880. this.syncSessionTimerText()
  881. if (!shouldRun) {
  882. this.clearSessionTimerInterval()
  883. return
  884. }
  885. if (this.sessionTimerInterval) {
  886. return
  887. }
  888. this.sessionTimerInterval = setInterval(() => {
  889. this.syncSessionTimerText()
  890. }, 1000) as unknown as number
  891. }
  892. getControlScreenPoint(controlId: string): { x: number; y: number } | null {
  893. if (!this.gameRuntime.definition || !this.state.stageWidth || !this.state.stageHeight) {
  894. return null
  895. }
  896. const control = this.gameRuntime.definition.controls.find((item) => item.id === controlId)
  897. if (!control) {
  898. return null
  899. }
  900. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  901. const screenPoint = worldToScreen({
  902. centerWorldX: exactCenter.x,
  903. centerWorldY: exactCenter.y,
  904. viewportWidth: this.state.stageWidth,
  905. viewportHeight: this.state.stageHeight,
  906. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  907. rotationRad: this.getRotationRad(this.state.rotationDeg),
  908. }, lonLatToWorldTile(control.point, this.state.zoom), false)
  909. if (screenPoint.x < -80 || screenPoint.x > this.state.stageWidth + 80 || screenPoint.y < -80 || screenPoint.y > this.state.stageHeight + 80) {
  910. return null
  911. }
  912. return screenPoint
  913. }
  914. setPunchButtonFxClass(className: string): void {
  915. this.setState({
  916. punchButtonFxClass: className,
  917. }, true)
  918. }
  919. showMapPulse(controlId: string, motionClass = ''): void {
  920. const screenPoint = this.getControlScreenPoint(controlId)
  921. if (!screenPoint) {
  922. return
  923. }
  924. this.clearMapPulseTimer()
  925. this.setState({
  926. mapPulseVisible: true,
  927. mapPulseLeftPx: screenPoint.x,
  928. mapPulseTopPx: screenPoint.y,
  929. mapPulseFxClass: motionClass,
  930. }, true)
  931. this.mapPulseTimer = setTimeout(() => {
  932. this.mapPulseTimer = 0
  933. this.setState({
  934. mapPulseVisible: false,
  935. mapPulseFxClass: '',
  936. }, true)
  937. }, 820) as unknown as number
  938. }
  939. showStageFx(className: string): void {
  940. if (!className) {
  941. return
  942. }
  943. this.clearStageFxTimer()
  944. this.setState({
  945. stageFxVisible: true,
  946. stageFxClass: className,
  947. }, true)
  948. this.stageFxTimer = setTimeout(() => {
  949. this.stageFxTimer = 0
  950. this.setState({
  951. stageFxVisible: false,
  952. stageFxClass: '',
  953. }, true)
  954. }, 760) as unknown as number
  955. }
  956. showPunchFeedback(text: string, tone: 'neutral' | 'success' | 'warning', motionClass = ''): void {
  957. this.clearPunchFeedbackTimer()
  958. this.setState({
  959. punchFeedbackVisible: true,
  960. punchFeedbackText: text,
  961. punchFeedbackTone: tone,
  962. punchFeedbackFxClass: motionClass,
  963. }, true)
  964. this.punchFeedbackTimer = setTimeout(() => {
  965. this.punchFeedbackTimer = 0
  966. this.setState({
  967. punchFeedbackVisible: false,
  968. punchFeedbackFxClass: '',
  969. }, true)
  970. }, 1400) as unknown as number
  971. }
  972. showContentCard(title: string, body: string, motionClass = ''): void {
  973. this.clearContentCardTimer()
  974. this.setState({
  975. contentCardVisible: true,
  976. contentCardTitle: title,
  977. contentCardBody: body,
  978. contentCardFxClass: motionClass,
  979. }, true)
  980. this.contentCardTimer = setTimeout(() => {
  981. this.contentCardTimer = 0
  982. this.setState({
  983. contentCardVisible: false,
  984. contentCardFxClass: '',
  985. }, true)
  986. }, 2600) as unknown as number
  987. }
  988. closeContentCard(): void {
  989. this.clearContentCardTimer()
  990. this.setState({
  991. contentCardVisible: false,
  992. contentCardFxClass: '',
  993. }, true)
  994. }
  995. applyGameEffects(effects: GameEffect[]): string | null {
  996. this.feedbackDirector.handleEffects(effects)
  997. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, this.gameRuntime.state)
  998. this.updateSessionTimerLoop()
  999. return this.resolveGameStatusText(effects)
  1000. }
  1001. handleStartGame(): void {
  1002. if (!this.gameRuntime.definition || !this.gameRuntime.state) {
  1003. this.setState({
  1004. statusText: `当前还没有可开始的路线 (${this.buildVersion})`,
  1005. }, true)
  1006. return
  1007. }
  1008. if (this.gameRuntime.state.status !== 'idle') {
  1009. return
  1010. }
  1011. if (!this.locationController.listening) {
  1012. this.locationController.start()
  1013. }
  1014. const startedAt = Date.now()
  1015. let gameResult = this.gameRuntime.startSession(startedAt)
  1016. if (this.currentGpsPoint) {
  1017. gameResult = this.gameRuntime.dispatch({
  1018. type: 'gps_updated',
  1019. at: Date.now(),
  1020. lon: this.currentGpsPoint.lon,
  1021. lat: this.currentGpsPoint.lat,
  1022. accuracyMeters: this.currentGpsAccuracyMeters,
  1023. })
  1024. }
  1025. this.gamePresentation = this.gameRuntime.getPresentation()
  1026. this.refreshCourseHeadingFromPresentation()
  1027. const defaultStatusText = this.currentGpsPoint
  1028. ? `顺序打点已开始 (${this.buildVersion})`
  1029. : `顺序打点已开始,GPS定位启动中 (${this.buildVersion})`
  1030. const gameStatusText = this.applyGameEffects(gameResult.effects) || defaultStatusText
  1031. this.setState({
  1032. ...this.getGameViewPatch(gameStatusText),
  1033. }, true)
  1034. this.syncRenderer()
  1035. }
  1036. handlePunchAction(): void {
  1037. const gameResult = this.gameRuntime.dispatch({
  1038. type: 'punch_requested',
  1039. at: Date.now(),
  1040. })
  1041. this.gamePresentation = gameResult.presentation
  1042. this.refreshCourseHeadingFromPresentation()
  1043. const gameStatusText = this.applyGameEffects(gameResult.effects)
  1044. this.setState({
  1045. ...this.getGameViewPatch(gameStatusText),
  1046. }, true)
  1047. this.syncRenderer()
  1048. }
  1049. handleLocationUpdate(longitude: number, latitude: number, accuracyMeters: number | null): void {
  1050. const nextPoint: LonLatPoint = { lon: longitude, lat: latitude }
  1051. const lastTrackPoint = this.currentGpsTrack.length ? this.currentGpsTrack[this.currentGpsTrack.length - 1] : null
  1052. if (!lastTrackPoint || getApproxDistanceMeters(lastTrackPoint, nextPoint) >= GPS_TRACK_MIN_STEP_METERS) {
  1053. this.currentGpsTrack = [...this.currentGpsTrack, nextPoint].slice(-GPS_TRACK_MAX_POINTS)
  1054. }
  1055. this.currentGpsPoint = nextPoint
  1056. this.currentGpsAccuracyMeters = accuracyMeters
  1057. const gpsWorldPoint = lonLatToWorldTile(nextPoint, this.state.zoom)
  1058. const gpsTileX = Math.floor(gpsWorldPoint.x)
  1059. const gpsTileY = Math.floor(gpsWorldPoint.y)
  1060. const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
  1061. let gameStatusText: string | null = null
  1062. if (this.courseData) {
  1063. const eventAt = Date.now()
  1064. const gameResult = this.gameRuntime.dispatch({
  1065. type: 'gps_updated',
  1066. at: eventAt,
  1067. lon: longitude,
  1068. lat: latitude,
  1069. accuracyMeters,
  1070. })
  1071. this.telemetryRuntime.dispatch({
  1072. type: 'gps_updated',
  1073. at: eventAt,
  1074. lon: longitude,
  1075. lat: latitude,
  1076. accuracyMeters,
  1077. })
  1078. this.gamePresentation = gameResult.presentation
  1079. this.refreshCourseHeadingFromPresentation()
  1080. gameStatusText = this.applyGameEffects(gameResult.effects)
  1081. }
  1082. if (gpsInsideMap && !this.hasGpsCenteredOnce) {
  1083. this.hasGpsCenteredOnce = true
  1084. this.commitViewport({
  1085. centerTileX: gpsWorldPoint.x,
  1086. centerTileY: gpsWorldPoint.y,
  1087. tileTranslateX: 0,
  1088. tileTranslateY: 0,
  1089. gpsTracking: true,
  1090. gpsTrackingText: '持续定位进行中',
  1091. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1092. ...this.getGameViewPatch(),
  1093. }, gameStatusText || `GPS定位成功,已定位到当前位置 (${this.buildVersion})`, true)
  1094. return
  1095. }
  1096. this.setState({
  1097. gpsTracking: true,
  1098. gpsTrackingText: gpsInsideMap ? '持续定位进行中' : 'GPS不在当前地图范围内',
  1099. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1100. ...this.getGameViewPatch(gameStatusText || (gpsInsideMap ? `GPS位置已更新 (${this.buildVersion})` : `GPS位置超出当前地图范围 (${this.buildVersion})`)),
  1101. }, true)
  1102. this.syncRenderer()
  1103. }
  1104. handleToggleOsmReference(): void {
  1105. const nextEnabled = !this.state.osmReferenceEnabled
  1106. this.setState({
  1107. osmReferenceEnabled: nextEnabled,
  1108. osmReferenceText: nextEnabled ? 'OSM参考:开' : 'OSM参考:关',
  1109. statusText: nextEnabled ? `OSM参考底图已开启 (${this.buildVersion})` : `OSM参考底图已关闭 (${this.buildVersion})`,
  1110. }, true)
  1111. this.syncRenderer()
  1112. }
  1113. handleToggleGpsTracking(): void {
  1114. if (this.locationController.listening) {
  1115. this.locationController.stop()
  1116. return
  1117. }
  1118. this.locationController.start()
  1119. }
  1120. handleConnectHeartRate(): void {
  1121. this.heartRateController.startScanAndConnect()
  1122. }
  1123. handleDisconnectHeartRate(): void {
  1124. this.heartRateController.disconnect()
  1125. }
  1126. handleDebugHeartRateTone(tone: HeartRateTone): void {
  1127. const sampleBpm = getHeartRateToneSampleBpm(tone, this.telemetryRuntime.config)
  1128. this.telemetryRuntime.dispatch({
  1129. type: 'heart_rate_updated',
  1130. at: Date.now(),
  1131. bpm: sampleBpm,
  1132. })
  1133. this.setState({
  1134. heartRateStatusText: `调试心率: ${sampleBpm} bpm / ${tone.toUpperCase()}`,
  1135. }, true)
  1136. this.syncSessionTimerText()
  1137. }
  1138. handleClearDebugHeartRate(): void {
  1139. this.telemetryRuntime.dispatch({
  1140. type: 'heart_rate_updated',
  1141. at: Date.now(),
  1142. bpm: null,
  1143. })
  1144. this.setState({
  1145. heartRateStatusText: this.heartRateController.connected ? '心率带已连接' : '心率带未连接',
  1146. }, true)
  1147. this.syncSessionTimerText()
  1148. }
  1149. setStage(rect: MapEngineStageRect): void {
  1150. this.previewScale = 1
  1151. this.previewOriginX = rect.width / 2
  1152. this.previewOriginY = rect.height / 2
  1153. this.commitViewport(
  1154. {
  1155. stageWidth: rect.width,
  1156. stageHeight: rect.height,
  1157. stageLeft: rect.left,
  1158. stageTop: rect.top,
  1159. },
  1160. `地图视口已与 WebGL 引擎对齐 (${this.buildVersion})`,
  1161. true,
  1162. )
  1163. }
  1164. attachCanvas(canvasNode: any, width: number, height: number, dpr: number, labelCanvasNode?: any): void {
  1165. this.renderer.attachCanvas(canvasNode, width, height, dpr, labelCanvasNode)
  1166. this.mounted = true
  1167. this.state.mapReady = true
  1168. this.state.mapReadyText = 'READY'
  1169. this.onData({
  1170. mapReady: true,
  1171. mapReadyText: 'READY',
  1172. statusText: `单 WebGL 管线已完成,可切换手动或自动朝向 (${this.buildVersion})`,
  1173. })
  1174. this.syncRenderer()
  1175. this.compassController.start()
  1176. }
  1177. applyRemoteMapConfig(config: RemoteMapConfig): void {
  1178. MAGNETIC_DECLINATION_DEG = config.magneticDeclinationDeg
  1179. MAGNETIC_DECLINATION_TEXT = config.magneticDeclinationText
  1180. this.minZoom = config.minZoom
  1181. this.maxZoom = config.maxZoom
  1182. this.defaultZoom = config.defaultZoom
  1183. this.defaultCenterTileX = config.initialCenterTileX
  1184. this.defaultCenterTileY = config.initialCenterTileY
  1185. this.tileBoundsByZoom = config.tileBoundsByZoom
  1186. this.courseData = config.course
  1187. this.cpRadiusMeters = config.cpRadiusMeters
  1188. this.gameMode = config.gameMode
  1189. this.punchPolicy = config.punchPolicy
  1190. this.punchRadiusMeters = config.punchRadiusMeters
  1191. this.autoFinishOnLastControl = config.autoFinishOnLastControl
  1192. this.telemetryRuntime.configure(config.telemetryConfig)
  1193. this.feedbackDirector.configure({
  1194. audioConfig: config.audioConfig,
  1195. hapticsConfig: config.hapticsConfig,
  1196. uiEffectsConfig: config.uiEffectsConfig,
  1197. })
  1198. const gameEffects = this.loadGameDefinitionFromCourse()
  1199. const gameStatusText = this.applyGameEffects(gameEffects)
  1200. const statePatch: Partial<MapEngineViewState> = {
  1201. configStatusText: `远程配置已载入 / ${config.courseStatusText}`,
  1202. projectionMode: config.projectionModeText,
  1203. tileSource: config.tileSource,
  1204. sensorHeadingText: formatHeadingText(this.smoothedSensorHeadingDeg === null ? null : getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)),
  1205. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  1206. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  1207. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1208. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  1209. ...this.getGameViewPatch(),
  1210. }
  1211. if (!this.state.stageWidth || !this.state.stageHeight) {
  1212. this.setState({
  1213. ...statePatch,
  1214. zoom: this.defaultZoom,
  1215. centerTileX: this.defaultCenterTileX,
  1216. centerTileY: this.defaultCenterTileY,
  1217. centerText: buildCenterText(this.defaultZoom, this.defaultCenterTileX, this.defaultCenterTileY),
  1218. statusText: gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`,
  1219. }, true)
  1220. return
  1221. }
  1222. this.commitViewport({
  1223. ...statePatch,
  1224. zoom: this.defaultZoom,
  1225. centerTileX: this.defaultCenterTileX,
  1226. centerTileY: this.defaultCenterTileY,
  1227. tileTranslateX: 0,
  1228. tileTranslateY: 0,
  1229. }, gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`, true, () => {
  1230. this.resetPreviewState()
  1231. this.syncRenderer()
  1232. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1233. this.scheduleAutoRotate()
  1234. }
  1235. })
  1236. }
  1237. handleTouchStart(event: WechatMiniprogram.TouchEvent): void {
  1238. this.clearInertiaTimer()
  1239. this.clearPreviewResetTimer()
  1240. this.panVelocityX = 0
  1241. this.panVelocityY = 0
  1242. if (event.touches.length >= 2) {
  1243. const origin = this.getStagePoint(event.touches)
  1244. this.gestureMode = 'pinch'
  1245. this.pinchStartDistance = this.getTouchDistance(event.touches)
  1246. this.pinchStartScale = this.previewScale || 1
  1247. this.pinchStartAngle = this.getTouchAngle(event.touches)
  1248. this.pinchStartRotationDeg = this.state.rotationDeg
  1249. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  1250. this.pinchAnchorWorldX = anchorWorld.x
  1251. this.pinchAnchorWorldY = anchorWorld.y
  1252. this.setPreviewState(this.pinchStartScale, origin.x, origin.y)
  1253. this.syncRenderer()
  1254. this.compassController.start()
  1255. return
  1256. }
  1257. if (event.touches.length === 1) {
  1258. this.gestureMode = 'pan'
  1259. this.panLastX = event.touches[0].pageX
  1260. this.panLastY = event.touches[0].pageY
  1261. this.panLastTimestamp = event.timeStamp || Date.now()
  1262. }
  1263. }
  1264. handleTouchMove(event: WechatMiniprogram.TouchEvent): void {
  1265. if (event.touches.length >= 2) {
  1266. const distance = this.getTouchDistance(event.touches)
  1267. const angle = this.getTouchAngle(event.touches)
  1268. const origin = this.getStagePoint(event.touches)
  1269. if (!this.pinchStartDistance) {
  1270. this.pinchStartDistance = distance
  1271. this.pinchStartScale = this.previewScale || 1
  1272. this.pinchStartAngle = angle
  1273. this.pinchStartRotationDeg = this.state.rotationDeg
  1274. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  1275. this.pinchAnchorWorldX = anchorWorld.x
  1276. this.pinchAnchorWorldY = anchorWorld.y
  1277. }
  1278. this.gestureMode = 'pinch'
  1279. const nextRotationDeg = this.state.orientationMode === 'heading-up'
  1280. ? this.state.rotationDeg
  1281. : normalizeRotationDeg(this.pinchStartRotationDeg + normalizeAngleDeltaRad(angle - this.pinchStartAngle) * 180 / Math.PI)
  1282. const anchorOffset = this.getWorldOffsetFromScreen(origin.x, origin.y, nextRotationDeg)
  1283. const resolvedViewport = this.resolveViewportForExactCenter(
  1284. this.pinchAnchorWorldX - anchorOffset.x,
  1285. this.pinchAnchorWorldY - anchorOffset.y,
  1286. nextRotationDeg,
  1287. )
  1288. this.setPreviewState(
  1289. clamp(this.pinchStartScale * (distance / this.pinchStartDistance), MIN_PREVIEW_SCALE, MAX_PREVIEW_SCALE),
  1290. origin.x,
  1291. origin.y,
  1292. )
  1293. this.commitViewport(
  1294. {
  1295. ...resolvedViewport,
  1296. rotationDeg: nextRotationDeg,
  1297. rotationText: formatRotationText(nextRotationDeg),
  1298. },
  1299. this.state.orientationMode === 'heading-up'
  1300. ? `双指缩放中,自动朝向保持开启 (${this.buildVersion})`
  1301. : `双指缩放与旋转中 (${this.buildVersion})`,
  1302. )
  1303. return
  1304. }
  1305. if (this.gestureMode !== 'pan' || event.touches.length !== 1) {
  1306. return
  1307. }
  1308. const touch = event.touches[0]
  1309. const deltaX = touch.pageX - this.panLastX
  1310. const deltaY = touch.pageY - this.panLastY
  1311. const nextTimestamp = event.timeStamp || Date.now()
  1312. const elapsed = Math.max(nextTimestamp - this.panLastTimestamp, 16)
  1313. const instantVelocityX = deltaX / elapsed
  1314. const instantVelocityY = deltaY / elapsed
  1315. this.panVelocityX = this.panVelocityX * 0.72 + instantVelocityX * 0.28
  1316. this.panVelocityY = this.panVelocityY * 0.72 + instantVelocityY * 0.28
  1317. this.panLastX = touch.pageX
  1318. this.panLastY = touch.pageY
  1319. this.panLastTimestamp = nextTimestamp
  1320. this.normalizeTranslate(
  1321. this.state.tileTranslateX + deltaX,
  1322. this.state.tileTranslateY + deltaY,
  1323. `宸叉嫋鎷藉崟 WebGL 鍦板浘寮曟搸 (${this.buildVersion})`,
  1324. )
  1325. }
  1326. handleTouchEnd(event: WechatMiniprogram.TouchEvent): void {
  1327. if (this.gestureMode === 'pinch' && event.touches.length < 2) {
  1328. const gestureScale = this.previewScale || 1
  1329. const zoomDelta = Math.round(Math.log2(gestureScale))
  1330. const originX = this.previewOriginX || this.state.stageWidth / 2
  1331. const originY = this.previewOriginY || this.state.stageHeight / 2
  1332. if (zoomDelta) {
  1333. const residualScale = gestureScale / Math.pow(2, zoomDelta)
  1334. this.zoomAroundPoint(zoomDelta, originX, originY, residualScale)
  1335. } else {
  1336. this.animatePreviewToRest()
  1337. }
  1338. this.resetPinchState()
  1339. this.panVelocityX = 0
  1340. this.panVelocityY = 0
  1341. if (event.touches.length === 1) {
  1342. this.gestureMode = 'pan'
  1343. this.panLastX = event.touches[0].pageX
  1344. this.panLastY = event.touches[0].pageY
  1345. this.panLastTimestamp = event.timeStamp || Date.now()
  1346. return
  1347. }
  1348. this.gestureMode = 'idle'
  1349. this.renderer.setAnimationPaused(false)
  1350. this.scheduleAutoRotate()
  1351. return
  1352. }
  1353. if (event.touches.length === 1) {
  1354. this.gestureMode = 'pan'
  1355. this.panLastX = event.touches[0].pageX
  1356. this.panLastY = event.touches[0].pageY
  1357. this.panLastTimestamp = event.timeStamp || Date.now()
  1358. return
  1359. }
  1360. if (this.gestureMode === 'pan' && (Math.abs(this.panVelocityX) >= INERTIA_MIN_SPEED || Math.abs(this.panVelocityY) >= INERTIA_MIN_SPEED)) {
  1361. this.startInertia()
  1362. this.gestureMode = 'idle'
  1363. this.resetPinchState()
  1364. return
  1365. }
  1366. this.gestureMode = 'idle'
  1367. this.resetPinchState()
  1368. this.renderer.setAnimationPaused(false)
  1369. this.scheduleAutoRotate()
  1370. }
  1371. handleTouchCancel(): void {
  1372. this.gestureMode = 'idle'
  1373. this.resetPinchState()
  1374. this.panVelocityX = 0
  1375. this.panVelocityY = 0
  1376. this.clearInertiaTimer()
  1377. this.animatePreviewToRest()
  1378. this.renderer.setAnimationPaused(false)
  1379. this.scheduleAutoRotate()
  1380. }
  1381. handleRecenter(): void {
  1382. this.clearInertiaTimer()
  1383. this.clearPreviewResetTimer()
  1384. this.panVelocityX = 0
  1385. this.panVelocityY = 0
  1386. this.renderer.setAnimationPaused(false)
  1387. this.commitViewport(
  1388. {
  1389. zoom: this.defaultZoom,
  1390. centerTileX: this.defaultCenterTileX,
  1391. centerTileY: this.defaultCenterTileY,
  1392. tileTranslateX: 0,
  1393. tileTranslateY: 0,
  1394. },
  1395. `已回到单 WebGL 引擎默认首屏 (${this.buildVersion})`,
  1396. true,
  1397. () => {
  1398. this.resetPreviewState()
  1399. this.syncRenderer()
  1400. this.compassController.start()
  1401. this.scheduleAutoRotate()
  1402. },
  1403. )
  1404. }
  1405. handleRotateStep(stepDeg = ROTATE_STEP_DEG): void {
  1406. if (this.state.rotationMode === 'auto') {
  1407. this.setState({
  1408. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  1409. }, true)
  1410. return
  1411. }
  1412. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1413. const nextRotationDeg = normalizeRotationDeg(this.state.rotationDeg + stepDeg)
  1414. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  1415. this.clearInertiaTimer()
  1416. this.clearPreviewResetTimer()
  1417. this.panVelocityX = 0
  1418. this.panVelocityY = 0
  1419. this.renderer.setAnimationPaused(false)
  1420. this.commitViewport(
  1421. {
  1422. ...resolvedViewport,
  1423. rotationDeg: nextRotationDeg,
  1424. rotationText: formatRotationText(nextRotationDeg),
  1425. },
  1426. `旋转角度调整到 ${formatRotationText(nextRotationDeg)} (${this.buildVersion})`,
  1427. true,
  1428. () => {
  1429. this.resetPreviewState()
  1430. this.syncRenderer()
  1431. this.compassController.start()
  1432. },
  1433. )
  1434. }
  1435. handleRotationReset(): void {
  1436. if (this.state.rotationMode === 'auto') {
  1437. this.setState({
  1438. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  1439. }, true)
  1440. return
  1441. }
  1442. const targetRotationDeg = MAP_NORTH_OFFSET_DEG
  1443. if (Math.abs(normalizeAngleDeltaDeg(this.state.rotationDeg - targetRotationDeg)) <= 0.01) {
  1444. return
  1445. }
  1446. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1447. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, targetRotationDeg)
  1448. this.clearInertiaTimer()
  1449. this.clearPreviewResetTimer()
  1450. this.panVelocityX = 0
  1451. this.panVelocityY = 0
  1452. this.renderer.setAnimationPaused(false)
  1453. this.commitViewport(
  1454. {
  1455. ...resolvedViewport,
  1456. rotationDeg: targetRotationDeg,
  1457. rotationText: formatRotationText(targetRotationDeg),
  1458. },
  1459. `旋转角度已回到真北参考 (${this.buildVersion})`,
  1460. true,
  1461. () => {
  1462. this.resetPreviewState()
  1463. this.syncRenderer()
  1464. this.compassController.start()
  1465. },
  1466. )
  1467. }
  1468. handleToggleRotationMode(): void {
  1469. if (this.state.orientationMode === 'manual') {
  1470. this.setNorthUpMode()
  1471. return
  1472. }
  1473. if (this.state.orientationMode === 'north-up') {
  1474. this.setHeadingUpMode()
  1475. return
  1476. }
  1477. this.setManualMode()
  1478. }
  1479. handleSetManualMode(): void {
  1480. this.setManualMode()
  1481. }
  1482. handleSetNorthUpMode(): void {
  1483. this.setNorthUpMode()
  1484. }
  1485. handleSetHeadingUpMode(): void {
  1486. this.setHeadingUpMode()
  1487. }
  1488. handleCycleNorthReferenceMode(): void {
  1489. this.cycleNorthReferenceMode()
  1490. }
  1491. handleAutoRotateCalibrate(): void {
  1492. if (this.state.orientationMode !== 'heading-up') {
  1493. this.setState({
  1494. statusText: `请先切到朝向朝上模式再校准 (${this.buildVersion})`,
  1495. }, true)
  1496. return
  1497. }
  1498. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  1499. this.setState({
  1500. statusText: `当前还没有传感器方向数据,暂时无法校准 (${this.buildVersion})`,
  1501. }, true)
  1502. return
  1503. }
  1504. this.setState({
  1505. statusText: `已按当前持机方向完成朝向校准 (${this.buildVersion})`,
  1506. }, true)
  1507. this.scheduleAutoRotate()
  1508. }
  1509. setManualMode(): void {
  1510. this.clearAutoRotateTimer()
  1511. this.targetAutoRotationDeg = null
  1512. this.autoRotateCalibrationPending = false
  1513. this.setState({
  1514. rotationMode: 'manual',
  1515. rotationModeText: formatRotationModeText('manual'),
  1516. rotationToggleText: formatRotationToggleText('manual'),
  1517. orientationMode: 'manual',
  1518. orientationModeText: formatOrientationModeText('manual'),
  1519. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1520. statusText: `已切回手动地图旋转 (${this.buildVersion})`,
  1521. }, true)
  1522. }
  1523. setNorthUpMode(): void {
  1524. this.clearAutoRotateTimer()
  1525. this.targetAutoRotationDeg = null
  1526. this.autoRotateCalibrationPending = false
  1527. const mapNorthOffsetDeg = MAP_NORTH_OFFSET_DEG
  1528. this.autoRotateCalibrationOffsetDeg = mapNorthOffsetDeg
  1529. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1530. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, mapNorthOffsetDeg)
  1531. this.commitViewport(
  1532. {
  1533. ...resolvedViewport,
  1534. rotationDeg: mapNorthOffsetDeg,
  1535. rotationText: formatRotationText(mapNorthOffsetDeg),
  1536. rotationMode: 'manual',
  1537. rotationModeText: formatRotationModeText('north-up'),
  1538. rotationToggleText: formatRotationToggleText('north-up'),
  1539. orientationMode: 'north-up',
  1540. orientationModeText: formatOrientationModeText('north-up'),
  1541. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, mapNorthOffsetDeg),
  1542. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1543. },
  1544. `地图已固定为真北朝上 (${this.buildVersion})`,
  1545. true,
  1546. () => {
  1547. this.resetPreviewState()
  1548. this.syncRenderer()
  1549. },
  1550. )
  1551. }
  1552. setHeadingUpMode(): void {
  1553. this.autoRotateCalibrationPending = false
  1554. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(this.northReferenceMode)
  1555. this.targetAutoRotationDeg = null
  1556. this.setState({
  1557. rotationMode: 'auto',
  1558. rotationModeText: formatRotationModeText('heading-up'),
  1559. rotationToggleText: formatRotationToggleText('heading-up'),
  1560. orientationMode: 'heading-up',
  1561. orientationModeText: formatOrientationModeText('heading-up'),
  1562. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1563. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1564. statusText: `正在启用朝向朝上模式 (${this.buildVersion})`,
  1565. }, true)
  1566. if (this.refreshAutoRotateTarget()) {
  1567. this.scheduleAutoRotate()
  1568. }
  1569. }
  1570. handleCompassHeading(headingDeg: number): void {
  1571. this.sensorHeadingDeg = normalizeRotationDeg(headingDeg)
  1572. this.smoothedSensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  1573. ? this.sensorHeadingDeg
  1574. : interpolateAngleDeg(this.smoothedSensorHeadingDeg, this.sensorHeadingDeg, AUTO_ROTATE_HEADING_SMOOTHING)
  1575. const compassHeadingDeg = getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  1576. this.compassDisplayHeadingDeg = this.compassDisplayHeadingDeg === null
  1577. ? compassHeadingDeg
  1578. : interpolateAngleDeg(this.compassDisplayHeadingDeg, compassHeadingDeg, COMPASS_NEEDLE_SMOOTHING)
  1579. this.autoRotateHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1580. this.setState({
  1581. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1582. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  1583. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  1584. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  1585. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  1586. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1587. })
  1588. if (!this.refreshAutoRotateTarget()) {
  1589. return
  1590. }
  1591. if (this.state.orientationMode === 'heading-up') {
  1592. this.scheduleAutoRotate()
  1593. }
  1594. }
  1595. handleCompassError(message: string): void {
  1596. this.clearAutoRotateTimer()
  1597. this.targetAutoRotationDeg = null
  1598. this.autoRotateCalibrationPending = false
  1599. this.setState({
  1600. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1601. statusText: `${message} (${this.buildVersion})`,
  1602. }, true)
  1603. }
  1604. cycleNorthReferenceMode(): void {
  1605. const nextMode = getNextNorthReferenceMode(this.northReferenceMode)
  1606. const nextMapNorthOffsetDeg = getMapNorthOffsetDeg(nextMode)
  1607. const compassHeadingDeg = this.smoothedSensorHeadingDeg === null
  1608. ? null
  1609. : getCompassReferenceHeadingDeg(nextMode, this.smoothedSensorHeadingDeg)
  1610. this.northReferenceMode = nextMode
  1611. this.autoRotateCalibrationOffsetDeg = nextMapNorthOffsetDeg
  1612. this.compassDisplayHeadingDeg = compassHeadingDeg
  1613. if (this.state.orientationMode === 'north-up') {
  1614. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1615. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, MAP_NORTH_OFFSET_DEG)
  1616. this.commitViewport(
  1617. {
  1618. ...resolvedViewport,
  1619. rotationDeg: MAP_NORTH_OFFSET_DEG,
  1620. rotationText: formatRotationText(MAP_NORTH_OFFSET_DEG),
  1621. northReferenceText: formatNorthReferenceText(nextMode),
  1622. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1623. compassDeclinationText: formatCompassDeclinationText(nextMode),
  1624. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  1625. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  1626. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  1627. },
  1628. `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  1629. true,
  1630. () => {
  1631. this.resetPreviewState()
  1632. this.syncRenderer()
  1633. },
  1634. )
  1635. return
  1636. }
  1637. this.setState({
  1638. northReferenceText: formatNorthReferenceText(nextMode),
  1639. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1640. compassDeclinationText: formatCompassDeclinationText(nextMode),
  1641. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  1642. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  1643. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  1644. statusText: `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  1645. }, true)
  1646. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1647. this.scheduleAutoRotate()
  1648. }
  1649. }
  1650. setCourseHeading(headingDeg: number | null): void {
  1651. this.courseHeadingDeg = headingDeg === null ? null : normalizeRotationDeg(headingDeg)
  1652. this.setState({
  1653. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  1654. })
  1655. if (this.refreshAutoRotateTarget()) {
  1656. this.scheduleAutoRotate()
  1657. }
  1658. }
  1659. resolveAutoRotateInputHeadingDeg(): number | null {
  1660. const sensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  1661. ? null
  1662. : getMapReferenceHeadingDegFromSensor(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  1663. const courseHeadingDeg = this.courseHeadingDeg === null
  1664. ? null
  1665. : getMapReferenceHeadingDegFromCourse(this.northReferenceMode, this.courseHeadingDeg)
  1666. if (this.autoRotateSourceMode === 'sensor') {
  1667. return sensorHeadingDeg
  1668. }
  1669. if (this.autoRotateSourceMode === 'course') {
  1670. return courseHeadingDeg === null ? sensorHeadingDeg : courseHeadingDeg
  1671. }
  1672. if (sensorHeadingDeg !== null && courseHeadingDeg !== null) {
  1673. return interpolateAngleDeg(sensorHeadingDeg, courseHeadingDeg, 0.35)
  1674. }
  1675. return sensorHeadingDeg === null ? courseHeadingDeg : sensorHeadingDeg
  1676. }
  1677. calibrateAutoRotateToCurrentOrientation(): boolean {
  1678. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1679. if (inputHeadingDeg === null) {
  1680. return false
  1681. }
  1682. this.autoRotateCalibrationOffsetDeg = normalizeRotationDeg(this.state.rotationDeg + inputHeadingDeg)
  1683. this.autoRotateCalibrationPending = false
  1684. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  1685. this.setState({
  1686. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1687. })
  1688. return true
  1689. }
  1690. refreshAutoRotateTarget(): boolean {
  1691. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1692. if (inputHeadingDeg === null) {
  1693. return false
  1694. }
  1695. if (this.autoRotateCalibrationPending || this.autoRotateCalibrationOffsetDeg === null) {
  1696. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  1697. return false
  1698. }
  1699. return true
  1700. }
  1701. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  1702. this.setState({
  1703. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1704. })
  1705. return true
  1706. }
  1707. scheduleAutoRotate(): void {
  1708. if (this.autoRotateTimer || this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  1709. return
  1710. }
  1711. const step = () => {
  1712. this.autoRotateTimer = 0
  1713. if (this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  1714. return
  1715. }
  1716. if (this.gestureMode !== 'idle' || this.inertiaTimer || this.previewResetTimer) {
  1717. this.scheduleAutoRotate()
  1718. return
  1719. }
  1720. const currentRotationDeg = this.state.rotationDeg
  1721. const deltaDeg = normalizeAngleDeltaDeg(this.targetAutoRotationDeg - currentRotationDeg)
  1722. if (Math.abs(deltaDeg) <= AUTO_ROTATE_SNAP_DEG) {
  1723. if (Math.abs(deltaDeg) > 0.01) {
  1724. this.applyAutoRotation(this.targetAutoRotationDeg)
  1725. }
  1726. this.scheduleAutoRotate()
  1727. return
  1728. }
  1729. if (Math.abs(deltaDeg) <= AUTO_ROTATE_DEADZONE_DEG) {
  1730. this.scheduleAutoRotate()
  1731. return
  1732. }
  1733. const easedStepDeg = clamp(deltaDeg * AUTO_ROTATE_EASE, -AUTO_ROTATE_MAX_STEP_DEG, AUTO_ROTATE_MAX_STEP_DEG)
  1734. this.applyAutoRotation(normalizeRotationDeg(currentRotationDeg + easedStepDeg))
  1735. this.scheduleAutoRotate()
  1736. }
  1737. this.autoRotateTimer = setTimeout(step, AUTO_ROTATE_FRAME_MS) as unknown as number
  1738. }
  1739. applyAutoRotation(nextRotationDeg: number): void {
  1740. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1741. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  1742. this.setState({
  1743. ...resolvedViewport,
  1744. rotationDeg: nextRotationDeg,
  1745. rotationText: formatRotationText(nextRotationDeg),
  1746. centerText: buildCenterText(this.state.zoom, resolvedViewport.centerTileX, resolvedViewport.centerTileY),
  1747. })
  1748. this.syncRenderer()
  1749. }
  1750. applyStats(stats: MapRendererStats): void {
  1751. this.setState({
  1752. visibleTileCount: stats.visibleTileCount,
  1753. readyTileCount: stats.readyTileCount,
  1754. memoryTileCount: stats.memoryTileCount,
  1755. diskTileCount: stats.diskTileCount,
  1756. memoryHitCount: stats.memoryHitCount,
  1757. diskHitCount: stats.diskHitCount,
  1758. networkFetchCount: stats.networkFetchCount,
  1759. cacheHitRateText: formatCacheHitRate(stats.memoryHitCount, stats.diskHitCount, stats.networkFetchCount),
  1760. })
  1761. }
  1762. setState(patch: Partial<MapEngineViewState>, immediateUi = false): void {
  1763. this.state = {
  1764. ...this.state,
  1765. ...patch,
  1766. }
  1767. const viewPatch = this.pickViewPatch(patch)
  1768. if (!Object.keys(viewPatch).length) {
  1769. return
  1770. }
  1771. this.pendingViewPatch = {
  1772. ...this.pendingViewPatch,
  1773. ...viewPatch,
  1774. }
  1775. if (immediateUi) {
  1776. this.flushViewPatch()
  1777. return
  1778. }
  1779. if (this.viewSyncTimer) {
  1780. return
  1781. }
  1782. this.viewSyncTimer = setTimeout(() => {
  1783. this.viewSyncTimer = 0
  1784. this.flushViewPatch()
  1785. }, UI_SYNC_INTERVAL_MS) as unknown as number
  1786. }
  1787. commitViewport(
  1788. patch: Partial<MapEngineViewState>,
  1789. statusText: string,
  1790. immediateUi = false,
  1791. afterUpdate?: () => void,
  1792. ): void {
  1793. const nextZoom = typeof patch.zoom === 'number' ? patch.zoom : this.state.zoom
  1794. const nextCenterTileX = typeof patch.centerTileX === 'number' ? patch.centerTileX : this.state.centerTileX
  1795. const nextCenterTileY = typeof patch.centerTileY === 'number' ? patch.centerTileY : this.state.centerTileY
  1796. const nextStageWidth = typeof patch.stageWidth === 'number' ? patch.stageWidth : this.state.stageWidth
  1797. const nextStageHeight = typeof patch.stageHeight === 'number' ? patch.stageHeight : this.state.stageHeight
  1798. const tileSizePx = getTileSizePx({
  1799. centerWorldX: nextCenterTileX,
  1800. centerWorldY: nextCenterTileY,
  1801. viewportWidth: nextStageWidth,
  1802. viewportHeight: nextStageHeight,
  1803. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1804. })
  1805. this.setState({
  1806. ...patch,
  1807. tileSizePx,
  1808. centerText: buildCenterText(nextZoom, nextCenterTileX, nextCenterTileY),
  1809. statusText,
  1810. }, immediateUi)
  1811. this.syncRenderer()
  1812. this.compassController.start()
  1813. if (afterUpdate) {
  1814. afterUpdate()
  1815. }
  1816. }
  1817. buildScene() {
  1818. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1819. return {
  1820. tileSource: this.state.tileSource,
  1821. osmTileSource: OSM_TILE_SOURCE,
  1822. zoom: this.state.zoom,
  1823. centerTileX: this.state.centerTileX,
  1824. centerTileY: this.state.centerTileY,
  1825. exactCenterWorldX: exactCenter.x,
  1826. exactCenterWorldY: exactCenter.y,
  1827. tileBoundsByZoom: this.tileBoundsByZoom,
  1828. viewportWidth: this.state.stageWidth,
  1829. viewportHeight: this.state.stageHeight,
  1830. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1831. overdraw: OVERDRAW,
  1832. translateX: this.state.tileTranslateX,
  1833. translateY: this.state.tileTranslateY,
  1834. rotationRad: this.getRotationRad(this.state.rotationDeg),
  1835. previewScale: this.previewScale || 1,
  1836. previewOriginX: this.previewOriginX || this.state.stageWidth / 2,
  1837. previewOriginY: this.previewOriginY || this.state.stageHeight / 2,
  1838. track: this.currentGpsTrack,
  1839. gpsPoint: this.currentGpsPoint,
  1840. gpsCalibration: GPS_MAP_CALIBRATION,
  1841. gpsCalibrationOrigin: worldTileToLonLat({ x: this.defaultCenterTileX, y: this.defaultCenterTileY }, this.defaultZoom),
  1842. course: this.courseData,
  1843. cpRadiusMeters: this.cpRadiusMeters,
  1844. activeControlSequences: this.gamePresentation.activeControlSequences,
  1845. activeStart: this.gamePresentation.activeStart,
  1846. completedStart: this.gamePresentation.completedStart,
  1847. activeFinish: this.gamePresentation.activeFinish,
  1848. completedFinish: this.gamePresentation.completedFinish,
  1849. revealFullCourse: this.gamePresentation.revealFullCourse,
  1850. activeLegIndices: this.gamePresentation.activeLegIndices,
  1851. completedLegIndices: this.gamePresentation.completedLegIndices,
  1852. completedControlSequences: this.gamePresentation.completedControlSequences,
  1853. osmReferenceEnabled: this.state.osmReferenceEnabled,
  1854. overlayOpacity: MAP_OVERLAY_OPACITY,
  1855. }
  1856. }
  1857. syncRenderer(): void {
  1858. if (!this.mounted || !this.state.stageWidth || !this.state.stageHeight) {
  1859. return
  1860. }
  1861. this.renderer.updateScene(this.buildScene())
  1862. }
  1863. getCameraState(rotationDeg = this.state.rotationDeg): CameraState {
  1864. return {
  1865. centerWorldX: this.state.centerTileX + 0.5,
  1866. centerWorldY: this.state.centerTileY + 0.5,
  1867. viewportWidth: this.state.stageWidth,
  1868. viewportHeight: this.state.stageHeight,
  1869. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1870. translateX: this.state.tileTranslateX,
  1871. translateY: this.state.tileTranslateY,
  1872. rotationRad: this.getRotationRad(rotationDeg),
  1873. }
  1874. }
  1875. getRotationRad(rotationDeg = this.state.rotationDeg): number {
  1876. return normalizeRotationDeg(rotationDeg) * Math.PI / 180
  1877. }
  1878. getBaseCamera(centerTileX = this.state.centerTileX, centerTileY = this.state.centerTileY, rotationDeg = this.state.rotationDeg): CameraState {
  1879. return {
  1880. centerWorldX: centerTileX + 0.5,
  1881. centerWorldY: centerTileY + 0.5,
  1882. viewportWidth: this.state.stageWidth,
  1883. viewportHeight: this.state.stageHeight,
  1884. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1885. rotationRad: this.getRotationRad(rotationDeg),
  1886. }
  1887. }
  1888. getWorldOffsetFromScreen(stageX: number, stageY: number, rotationDeg = this.state.rotationDeg): { x: number; y: number } {
  1889. const baseCamera = {
  1890. centerWorldX: 0,
  1891. centerWorldY: 0,
  1892. viewportWidth: this.state.stageWidth,
  1893. viewportHeight: this.state.stageHeight,
  1894. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1895. rotationRad: this.getRotationRad(rotationDeg),
  1896. }
  1897. return screenToWorld(baseCamera, { x: stageX, y: stageY }, false)
  1898. }
  1899. getExactCenterFromTranslate(translateX: number, translateY: number): { x: number; y: number } {
  1900. if (!this.state.stageWidth || !this.state.stageHeight) {
  1901. return {
  1902. x: this.state.centerTileX + 0.5,
  1903. y: this.state.centerTileY + 0.5,
  1904. }
  1905. }
  1906. const screenCenterX = this.state.stageWidth / 2
  1907. const screenCenterY = this.state.stageHeight / 2
  1908. return screenToWorld(this.getBaseCamera(), {
  1909. x: screenCenterX - translateX,
  1910. y: screenCenterY - translateY,
  1911. }, false)
  1912. }
  1913. resolveViewportForExactCenter(centerWorldX: number, centerWorldY: number, rotationDeg = this.state.rotationDeg): {
  1914. centerTileX: number
  1915. centerTileY: number
  1916. tileTranslateX: number
  1917. tileTranslateY: number
  1918. } {
  1919. const nextCenterTileX = Math.floor(centerWorldX)
  1920. const nextCenterTileY = Math.floor(centerWorldY)
  1921. if (!this.state.stageWidth || !this.state.stageHeight) {
  1922. return {
  1923. centerTileX: nextCenterTileX,
  1924. centerTileY: nextCenterTileY,
  1925. tileTranslateX: 0,
  1926. tileTranslateY: 0,
  1927. }
  1928. }
  1929. const roundedCamera = this.getBaseCamera(nextCenterTileX, nextCenterTileY, rotationDeg)
  1930. const projectedCenter = worldToScreen(roundedCamera, { x: centerWorldX, y: centerWorldY }, false)
  1931. return {
  1932. centerTileX: nextCenterTileX,
  1933. centerTileY: nextCenterTileY,
  1934. tileTranslateX: this.state.stageWidth / 2 - projectedCenter.x,
  1935. tileTranslateY: this.state.stageHeight / 2 - projectedCenter.y,
  1936. }
  1937. }
  1938. setPreviewState(scale: number, originX: number, originY: number): void {
  1939. this.previewScale = scale
  1940. this.previewOriginX = originX
  1941. this.previewOriginY = originY
  1942. }
  1943. resetPreviewState(): void {
  1944. this.setPreviewState(1, this.state.stageWidth / 2, this.state.stageHeight / 2)
  1945. }
  1946. resetPinchState(): void {
  1947. this.pinchStartDistance = 0
  1948. this.pinchStartScale = 1
  1949. this.pinchStartAngle = 0
  1950. this.pinchStartRotationDeg = this.state.rotationDeg
  1951. this.pinchAnchorWorldX = 0
  1952. this.pinchAnchorWorldY = 0
  1953. }
  1954. clearPreviewResetTimer(): void {
  1955. if (this.previewResetTimer) {
  1956. clearTimeout(this.previewResetTimer)
  1957. this.previewResetTimer = 0
  1958. }
  1959. }
  1960. clearInertiaTimer(): void {
  1961. if (this.inertiaTimer) {
  1962. clearTimeout(this.inertiaTimer)
  1963. this.inertiaTimer = 0
  1964. }
  1965. }
  1966. clearViewSyncTimer(): void {
  1967. if (this.viewSyncTimer) {
  1968. clearTimeout(this.viewSyncTimer)
  1969. this.viewSyncTimer = 0
  1970. }
  1971. }
  1972. clearAutoRotateTimer(): void {
  1973. if (this.autoRotateTimer) {
  1974. clearTimeout(this.autoRotateTimer)
  1975. this.autoRotateTimer = 0
  1976. }
  1977. }
  1978. pickViewPatch(patch: Partial<MapEngineViewState>): Partial<MapEngineViewState> {
  1979. const viewPatch = {} as Partial<MapEngineViewState>
  1980. for (const key of VIEW_SYNC_KEYS) {
  1981. if (Object.prototype.hasOwnProperty.call(patch, key)) {
  1982. ;(viewPatch as any)[key] = patch[key]
  1983. }
  1984. }
  1985. return viewPatch
  1986. }
  1987. flushViewPatch(): void {
  1988. if (!Object.keys(this.pendingViewPatch).length) {
  1989. return
  1990. }
  1991. const patch = this.pendingViewPatch
  1992. this.pendingViewPatch = {}
  1993. this.onData(patch)
  1994. }
  1995. getTouchDistance(touches: TouchPoint[]): number {
  1996. if (touches.length < 2) {
  1997. return 0
  1998. }
  1999. const first = touches[0]
  2000. const second = touches[1]
  2001. const deltaX = first.pageX - second.pageX
  2002. const deltaY = first.pageY - second.pageY
  2003. return Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  2004. }
  2005. getTouchAngle(touches: TouchPoint[]): number {
  2006. if (touches.length < 2) {
  2007. return 0
  2008. }
  2009. const first = touches[0]
  2010. const second = touches[1]
  2011. return Math.atan2(second.pageY - first.pageY, second.pageX - first.pageX)
  2012. }
  2013. getStagePoint(touches: TouchPoint[]): { x: number; y: number } {
  2014. if (!touches.length) {
  2015. return {
  2016. x: this.state.stageWidth / 2,
  2017. y: this.state.stageHeight / 2,
  2018. }
  2019. }
  2020. let pageX = 0
  2021. let pageY = 0
  2022. for (const touch of touches) {
  2023. pageX += touch.pageX
  2024. pageY += touch.pageY
  2025. }
  2026. return {
  2027. x: pageX / touches.length - this.state.stageLeft,
  2028. y: pageY / touches.length - this.state.stageTop,
  2029. }
  2030. }
  2031. animatePreviewToRest(): void {
  2032. this.clearPreviewResetTimer()
  2033. const startScale = this.previewScale || 1
  2034. const originX = this.previewOriginX || this.state.stageWidth / 2
  2035. const originY = this.previewOriginY || this.state.stageHeight / 2
  2036. if (Math.abs(startScale - 1) < 0.01) {
  2037. this.resetPreviewState()
  2038. this.syncRenderer()
  2039. this.compassController.start()
  2040. this.scheduleAutoRotate()
  2041. return
  2042. }
  2043. const startAt = Date.now()
  2044. const step = () => {
  2045. const progress = Math.min(1, (Date.now() - startAt) / PREVIEW_RESET_DURATION_MS)
  2046. const eased = 1 - Math.pow(1 - progress, 3)
  2047. const nextScale = startScale + (1 - startScale) * eased
  2048. this.setPreviewState(nextScale, originX, originY)
  2049. this.syncRenderer()
  2050. this.compassController.start()
  2051. if (progress >= 1) {
  2052. this.resetPreviewState()
  2053. this.syncRenderer()
  2054. this.compassController.start()
  2055. this.previewResetTimer = 0
  2056. this.scheduleAutoRotate()
  2057. return
  2058. }
  2059. this.previewResetTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2060. }
  2061. step()
  2062. }
  2063. normalizeTranslate(translateX: number, translateY: number, statusText: string): void {
  2064. if (!this.state.stageWidth) {
  2065. this.setState({
  2066. tileTranslateX: translateX,
  2067. tileTranslateY: translateY,
  2068. })
  2069. this.syncRenderer()
  2070. this.compassController.start()
  2071. return
  2072. }
  2073. const exactCenter = this.getExactCenterFromTranslate(translateX, translateY)
  2074. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y)
  2075. const centerChanged = resolvedViewport.centerTileX !== this.state.centerTileX || resolvedViewport.centerTileY !== this.state.centerTileY
  2076. if (centerChanged) {
  2077. this.commitViewport(resolvedViewport, statusText)
  2078. return
  2079. }
  2080. this.setState({
  2081. tileTranslateX: resolvedViewport.tileTranslateX,
  2082. tileTranslateY: resolvedViewport.tileTranslateY,
  2083. })
  2084. this.syncRenderer()
  2085. this.compassController.start()
  2086. }
  2087. zoomAroundPoint(zoomDelta: number, stageX: number, stageY: number, residualScale: number): void {
  2088. const nextZoom = clamp(this.state.zoom + zoomDelta, this.minZoom, this.maxZoom)
  2089. const appliedDelta = nextZoom - this.state.zoom
  2090. if (!appliedDelta) {
  2091. this.animatePreviewToRest()
  2092. return
  2093. }
  2094. if (!this.state.stageWidth || !this.state.stageHeight) {
  2095. this.commitViewport(
  2096. {
  2097. zoom: nextZoom,
  2098. centerTileX: appliedDelta > 0 ? this.state.centerTileX * 2 : Math.floor(this.state.centerTileX / 2),
  2099. centerTileY: appliedDelta > 0 ? this.state.centerTileY * 2 : Math.floor(this.state.centerTileY / 2),
  2100. tileTranslateX: 0,
  2101. tileTranslateY: 0,
  2102. },
  2103. `缩放级别调整到 ${nextZoom}`,
  2104. true,
  2105. () => {
  2106. this.setPreviewState(residualScale, stageX, stageY)
  2107. this.syncRenderer()
  2108. this.compassController.start()
  2109. this.animatePreviewToRest()
  2110. },
  2111. )
  2112. return
  2113. }
  2114. const camera = this.getCameraState()
  2115. const world = screenToWorld(camera, { x: stageX, y: stageY }, true)
  2116. const zoomFactor = Math.pow(2, appliedDelta)
  2117. const nextWorldX = world.x * zoomFactor
  2118. const nextWorldY = world.y * zoomFactor
  2119. const anchorOffset = this.getWorldOffsetFromScreen(stageX, stageY)
  2120. const exactCenterX = nextWorldX - anchorOffset.x
  2121. const exactCenterY = nextWorldY - anchorOffset.y
  2122. const resolvedViewport = this.resolveViewportForExactCenter(exactCenterX, exactCenterY)
  2123. this.commitViewport(
  2124. {
  2125. zoom: nextZoom,
  2126. ...resolvedViewport,
  2127. },
  2128. `缩放级别调整到 ${nextZoom}`,
  2129. true,
  2130. () => {
  2131. this.setPreviewState(residualScale, stageX, stageY)
  2132. this.syncRenderer()
  2133. this.compassController.start()
  2134. this.animatePreviewToRest()
  2135. },
  2136. )
  2137. }
  2138. startInertia(): void {
  2139. this.clearInertiaTimer()
  2140. const step = () => {
  2141. this.panVelocityX *= INERTIA_DECAY
  2142. this.panVelocityY *= INERTIA_DECAY
  2143. if (Math.abs(this.panVelocityX) < INERTIA_MIN_SPEED && Math.abs(this.panVelocityY) < INERTIA_MIN_SPEED) {
  2144. this.setState({
  2145. statusText: `惯性滑动结束 (${this.buildVersion})`,
  2146. })
  2147. this.renderer.setAnimationPaused(false)
  2148. this.inertiaTimer = 0
  2149. this.scheduleAutoRotate()
  2150. return
  2151. }
  2152. this.normalizeTranslate(
  2153. this.state.tileTranslateX + this.panVelocityX * INERTIA_FRAME_MS,
  2154. this.state.tileTranslateY + this.panVelocityY * INERTIA_FRAME_MS,
  2155. `惯性滑动中 (${this.buildVersion})`,
  2156. )
  2157. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2158. }
  2159. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2160. }
  2161. }