mapEngine.ts 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334
  1. import { getTileSizePx, screenToWorld, worldToScreen, type CameraState } from '../camera/camera'
  2. import { CompassHeadingController } from '../sensor/compassHeadingController'
  3. import { type HeartRateDiscoveredDevice } from '../sensor/heartRateController'
  4. import { HeartRateInputController } from '../sensor/heartRateInputController'
  5. import { LocationController } from '../sensor/locationController'
  6. import { WebGLMapRenderer } from '../renderer/webglMapRenderer'
  7. import { type MapRendererStats } from '../renderer/mapRenderer'
  8. import { lonLatToWorldTile, worldTileToLonLat, type LonLatPoint, type MapCalibration } from '../../utils/projection'
  9. import { type OrienteeringCourseData } from '../../utils/orienteeringCourse'
  10. import { isTileWithinBounds, type RemoteMapConfig, type TileZoomBounds } from '../../utils/remoteMapConfig'
  11. import { GameRuntime } from '../../game/core/gameRuntime'
  12. import { type GameEffect, type GameResult } from '../../game/core/gameResult'
  13. import { buildGameDefinitionFromCourse } from '../../game/content/courseToGameDefinition'
  14. import { FeedbackDirector } from '../../game/feedback/feedbackDirector'
  15. import { EMPTY_GAME_PRESENTATION_STATE, type GamePresentationState } from '../../game/presentation/presentationState'
  16. import { TelemetryRuntime } from '../../game/telemetry/telemetryRuntime'
  17. import { getHeartRateToneSampleBpm, type HeartRateTone } from '../../game/telemetry/telemetryConfig'
  18. const RENDER_MODE = 'Single WebGL Pipeline'
  19. const PROJECTION_MODE = 'WGS84 -> WorldTile -> Camera -> Screen'
  20. const MAP_NORTH_OFFSET_DEG = 0
  21. let MAGNETIC_DECLINATION_DEG = -6.91
  22. let MAGNETIC_DECLINATION_TEXT = '6.91掳 W'
  23. const MIN_ZOOM = 15
  24. const MAX_ZOOM = 20
  25. const DEFAULT_ZOOM = 17
  26. const DESIRED_VISIBLE_COLUMNS = 3
  27. const OVERDRAW = 1
  28. const DEFAULT_TOP_LEFT_TILE_X = 108132
  29. const DEFAULT_TOP_LEFT_TILE_Y = 51199
  30. const DEFAULT_CENTER_TILE_X = DEFAULT_TOP_LEFT_TILE_X + 1
  31. const DEFAULT_CENTER_TILE_Y = DEFAULT_TOP_LEFT_TILE_Y + 1
  32. const TILE_SOURCE = 'https://oss-mbh5.colormaprun.com/wxMap/lcx/{z}/{x}/{y}.png'
  33. const OSM_TILE_SOURCE = 'https://tiles.mymarsgo.xyz/{z}/{x}/{y}.png'
  34. const MAP_OVERLAY_OPACITY = 0.72
  35. const GPS_MAP_CALIBRATION: MapCalibration = {
  36. offsetEastMeters: 0,
  37. offsetNorthMeters: 0,
  38. rotationDeg: 0,
  39. scale: 1,
  40. }
  41. const MIN_PREVIEW_SCALE = 0.55
  42. const MAX_PREVIEW_SCALE = 1.85
  43. const INERTIA_FRAME_MS = 16
  44. const INERTIA_DECAY = 0.92
  45. const INERTIA_MIN_SPEED = 0.02
  46. const PREVIEW_RESET_DURATION_MS = 140
  47. const UI_SYNC_INTERVAL_MS = 80
  48. const ROTATE_STEP_DEG = 15
  49. const AUTO_ROTATE_FRAME_MS = 8
  50. const AUTO_ROTATE_EASE = 0.34
  51. const AUTO_ROTATE_SNAP_DEG = 0.1
  52. const AUTO_ROTATE_DEADZONE_DEG = 4
  53. const AUTO_ROTATE_MAX_STEP_DEG = 0.75
  54. const AUTO_ROTATE_HEADING_SMOOTHING = 0.32
  55. const COMPASS_NEEDLE_SMOOTHING = 0.12
  56. const SMART_HEADING_BLEND_START_SPEED_KMH = 1.2
  57. const SMART_HEADING_MOVEMENT_SPEED_KMH = 3.0
  58. const SMART_HEADING_MIN_DISTANCE_METERS = 8
  59. const SMART_HEADING_MAX_ACCURACY_METERS = 25
  60. const GPS_TRACK_MAX_POINTS = 200
  61. const GPS_TRACK_MIN_STEP_METERS = 3
  62. const MAP_TAP_MOVE_THRESHOLD_PX = 14
  63. const MAP_TAP_DURATION_MS = 280
  64. type TouchPoint = WechatMiniprogram.TouchDetail
  65. type GestureMode = 'idle' | 'pan' | 'pinch'
  66. type RotationMode = 'manual' | 'auto'
  67. type OrientationMode = 'manual' | 'north-up' | 'heading-up'
  68. type AutoRotateSourceMode = 'sensor' | 'course' | 'fusion' | 'smart'
  69. type SmartHeadingSource = 'sensor' | 'blended' | 'movement'
  70. type NorthReferenceMode = 'magnetic' | 'true'
  71. const DEFAULT_NORTH_REFERENCE_MODE: NorthReferenceMode = 'magnetic'
  72. export interface MapEngineStageRect {
  73. width: number
  74. height: number
  75. left: number
  76. top: number
  77. }
  78. export interface MapEngineViewState {
  79. buildVersion: string
  80. renderMode: string
  81. projectionMode: string
  82. mapReady: boolean
  83. mapReadyText: string
  84. mapName: string
  85. configStatusText: string
  86. zoom: number
  87. rotationDeg: number
  88. rotationText: string
  89. rotationMode: RotationMode
  90. rotationModeText: string
  91. rotationToggleText: string
  92. orientationMode: OrientationMode
  93. orientationModeText: string
  94. sensorHeadingText: string
  95. compassDeclinationText: string
  96. northReferenceButtonText: string
  97. autoRotateSourceText: string
  98. autoRotateCalibrationText: string
  99. northReferenceText: string
  100. compassNeedleDeg: number
  101. centerTileX: number
  102. centerTileY: number
  103. centerText: string
  104. tileSource: string
  105. visibleColumnCount: number
  106. visibleTileCount: number
  107. readyTileCount: number
  108. memoryTileCount: number
  109. diskTileCount: number
  110. memoryHitCount: number
  111. diskHitCount: number
  112. networkFetchCount: number
  113. cacheHitRateText: string
  114. tileTranslateX: number
  115. tileTranslateY: number
  116. tileSizePx: number
  117. stageWidth: number
  118. stageHeight: number
  119. stageLeft: number
  120. stageTop: number
  121. statusText: string
  122. gpsTracking: boolean
  123. gpsTrackingText: string
  124. gpsLockEnabled: boolean
  125. gpsLockAvailable: boolean
  126. locationSourceMode: 'real' | 'mock'
  127. locationSourceText: string
  128. mockBridgeConnected: boolean
  129. mockBridgeStatusText: string
  130. mockBridgeUrlText: string
  131. mockCoordText: string
  132. mockSpeedText: string
  133. gpsCoordText: string
  134. heartRateSourceMode: 'real' | 'mock'
  135. heartRateSourceText: string
  136. heartRateConnected: boolean
  137. heartRateStatusText: string
  138. heartRateDeviceText: string
  139. heartRateScanText: string
  140. heartRateDiscoveredDevices: Array<{
  141. deviceId: string
  142. name: string
  143. rssiText: string
  144. preferred: boolean
  145. connected: boolean
  146. }>
  147. mockHeartRateBridgeConnected: boolean
  148. mockHeartRateBridgeStatusText: string
  149. mockHeartRateBridgeUrlText: string
  150. mockHeartRateText: string
  151. gameSessionStatus: 'idle' | 'running' | 'finished' | 'failed'
  152. gameModeText: string
  153. panelTimerText: string
  154. panelMileageText: string
  155. panelActionTagText: string
  156. panelDistanceTagText: string
  157. panelDistanceValueText: string
  158. panelDistanceUnitText: string
  159. panelProgressText: string
  160. panelSpeedValueText: string
  161. panelTelemetryTone: 'blue' | 'purple' | 'green' | 'yellow' | 'orange' | 'red'
  162. panelHeartRateZoneNameText: string
  163. panelHeartRateZoneRangeText: string
  164. panelHeartRateValueText: string
  165. panelHeartRateUnitText: string
  166. panelCaloriesValueText: string
  167. panelCaloriesUnitText: string
  168. panelAverageSpeedValueText: string
  169. panelAverageSpeedUnitText: string
  170. panelAccuracyValueText: string
  171. panelAccuracyUnitText: string
  172. punchButtonText: string
  173. punchButtonEnabled: boolean
  174. skipButtonEnabled: boolean
  175. punchHintText: string
  176. punchFeedbackVisible: boolean
  177. punchFeedbackText: string
  178. punchFeedbackTone: 'neutral' | 'success' | 'warning'
  179. contentCardVisible: boolean
  180. contentCardTitle: string
  181. contentCardBody: string
  182. punchButtonFxClass: string
  183. punchFeedbackFxClass: string
  184. contentCardFxClass: string
  185. mapPulseVisible: boolean
  186. mapPulseLeftPx: number
  187. mapPulseTopPx: number
  188. mapPulseFxClass: string
  189. stageFxVisible: boolean
  190. stageFxClass: string
  191. osmReferenceEnabled: boolean
  192. osmReferenceText: string
  193. }
  194. export interface MapEngineCallbacks {
  195. onData: (patch: Partial<MapEngineViewState>) => void
  196. }
  197. export interface MapEngineGameInfoRow {
  198. label: string
  199. value: string
  200. }
  201. export interface MapEngineGameInfoSnapshot {
  202. title: string
  203. subtitle: string
  204. localRows: MapEngineGameInfoRow[]
  205. globalRows: MapEngineGameInfoRow[]
  206. }
  207. const VIEW_SYNC_KEYS: Array<keyof MapEngineViewState> = [
  208. 'buildVersion',
  209. 'renderMode',
  210. 'projectionMode',
  211. 'mapReady',
  212. 'mapReadyText',
  213. 'mapName',
  214. 'configStatusText',
  215. 'zoom',
  216. 'rotationDeg',
  217. 'rotationText',
  218. 'rotationMode',
  219. 'rotationModeText',
  220. 'rotationToggleText',
  221. 'orientationMode',
  222. 'orientationModeText',
  223. 'sensorHeadingText',
  224. 'compassDeclinationText',
  225. 'northReferenceButtonText',
  226. 'autoRotateSourceText',
  227. 'autoRotateCalibrationText',
  228. 'northReferenceText',
  229. 'compassNeedleDeg',
  230. 'centerText',
  231. 'tileSource',
  232. 'visibleTileCount',
  233. 'readyTileCount',
  234. 'memoryTileCount',
  235. 'diskTileCount',
  236. 'memoryHitCount',
  237. 'diskHitCount',
  238. 'networkFetchCount',
  239. 'cacheHitRateText',
  240. 'tileSizePx',
  241. 'statusText',
  242. 'gpsTracking',
  243. 'gpsTrackingText',
  244. 'gpsLockEnabled',
  245. 'gpsLockAvailable',
  246. 'locationSourceMode',
  247. 'locationSourceText',
  248. 'mockBridgeConnected',
  249. 'mockBridgeStatusText',
  250. 'mockBridgeUrlText',
  251. 'mockCoordText',
  252. 'mockSpeedText',
  253. 'gpsCoordText',
  254. 'heartRateSourceMode',
  255. 'heartRateSourceText',
  256. 'heartRateConnected',
  257. 'heartRateStatusText',
  258. 'heartRateDeviceText',
  259. 'heartRateScanText',
  260. 'heartRateDiscoveredDevices',
  261. 'mockHeartRateBridgeConnected',
  262. 'mockHeartRateBridgeStatusText',
  263. 'mockHeartRateBridgeUrlText',
  264. 'mockHeartRateText',
  265. 'gameSessionStatus',
  266. 'gameModeText',
  267. 'panelTimerText',
  268. 'panelMileageText',
  269. 'panelActionTagText',
  270. 'panelDistanceTagText',
  271. 'panelDistanceValueText',
  272. 'panelDistanceUnitText',
  273. 'panelProgressText',
  274. 'panelSpeedValueText',
  275. 'panelTelemetryTone',
  276. 'panelHeartRateZoneNameText',
  277. 'panelHeartRateZoneRangeText',
  278. 'panelHeartRateValueText',
  279. 'panelHeartRateUnitText',
  280. 'panelCaloriesValueText',
  281. 'panelCaloriesUnitText',
  282. 'panelAverageSpeedValueText',
  283. 'panelAverageSpeedUnitText',
  284. 'panelAccuracyValueText',
  285. 'panelAccuracyUnitText',
  286. 'punchButtonText',
  287. 'punchButtonEnabled',
  288. 'skipButtonEnabled',
  289. 'punchHintText',
  290. 'punchFeedbackVisible',
  291. 'punchFeedbackText',
  292. 'punchFeedbackTone',
  293. 'contentCardVisible',
  294. 'contentCardTitle',
  295. 'contentCardBody',
  296. 'punchButtonFxClass',
  297. 'punchFeedbackFxClass',
  298. 'contentCardFxClass',
  299. 'mapPulseVisible',
  300. 'mapPulseLeftPx',
  301. 'mapPulseTopPx',
  302. 'mapPulseFxClass',
  303. 'stageFxVisible',
  304. 'stageFxClass',
  305. 'osmReferenceEnabled',
  306. 'osmReferenceText',
  307. ]
  308. function buildCenterText(zoom: number, x: number, y: number): string {
  309. return `z${zoom} / x${x} / y${y}`
  310. }
  311. function clamp(value: number, min: number, max: number): number {
  312. return Math.max(min, Math.min(max, value))
  313. }
  314. function normalizeRotationDeg(rotationDeg: number): number {
  315. const normalized = rotationDeg % 360
  316. return normalized < 0 ? normalized + 360 : normalized
  317. }
  318. function normalizeAngleDeltaRad(angleDeltaRad: number): number {
  319. let normalized = angleDeltaRad
  320. while (normalized > Math.PI) {
  321. normalized -= Math.PI * 2
  322. }
  323. while (normalized < -Math.PI) {
  324. normalized += Math.PI * 2
  325. }
  326. return normalized
  327. }
  328. function normalizeAngleDeltaDeg(angleDeltaDeg: number): number {
  329. let normalized = angleDeltaDeg
  330. while (normalized > 180) {
  331. normalized -= 360
  332. }
  333. while (normalized < -180) {
  334. normalized += 360
  335. }
  336. return normalized
  337. }
  338. function interpolateAngleDeg(currentDeg: number, targetDeg: number, factor: number): number {
  339. return normalizeRotationDeg(currentDeg + normalizeAngleDeltaDeg(targetDeg - currentDeg) * factor)
  340. }
  341. function formatGameSessionStatusText(status: 'idle' | 'running' | 'finished' | 'failed'): string {
  342. if (status === 'running') {
  343. return '进行中'
  344. }
  345. if (status === 'finished') {
  346. return '已结束'
  347. }
  348. if (status === 'failed') {
  349. return '已失败'
  350. }
  351. return '未开始'
  352. }
  353. function formatRotationText(rotationDeg: number): string {
  354. return `${Math.round(normalizeRotationDeg(rotationDeg))}deg`
  355. }
  356. function formatHeadingText(headingDeg: number | null): string {
  357. if (headingDeg === null) {
  358. return '--'
  359. }
  360. return `${Math.round(normalizeRotationDeg(headingDeg))}掳`
  361. }
  362. function formatOrientationModeText(mode: OrientationMode): string {
  363. if (mode === 'north-up') {
  364. return 'North Up'
  365. }
  366. if (mode === 'heading-up') {
  367. return 'Heading Up'
  368. }
  369. return 'Manual Gesture'
  370. }
  371. function formatRotationModeText(mode: OrientationMode): string {
  372. return formatOrientationModeText(mode)
  373. }
  374. function formatRotationToggleText(mode: OrientationMode): string {
  375. if (mode === 'manual') {
  376. return '切到北朝上'
  377. }
  378. if (mode === 'north-up') {
  379. return '切到朝向朝上'
  380. }
  381. return '切到手动旋转'
  382. }
  383. function formatAutoRotateSourceText(mode: AutoRotateSourceMode, hasCourseHeading: boolean): string {
  384. if (mode === 'smart') {
  385. return 'Smart / 手机朝向'
  386. }
  387. if (mode === 'sensor') {
  388. return 'Sensor Only'
  389. }
  390. if (mode === 'course') {
  391. return hasCourseHeading ? 'Course Only' : 'Course Pending'
  392. }
  393. return hasCourseHeading ? 'Sensor + Course' : 'Sensor Only'
  394. }
  395. function formatSmartHeadingSourceText(source: SmartHeadingSource): string {
  396. if (source === 'movement') {
  397. return 'Smart / 前进方向'
  398. }
  399. if (source === 'blended') {
  400. return 'Smart / 融合'
  401. }
  402. return 'Smart / 手机朝向'
  403. }
  404. function formatAutoRotateCalibrationText(pending: boolean, offsetDeg: number | null): string {
  405. if (pending) {
  406. return 'Pending'
  407. }
  408. if (offsetDeg === null) {
  409. return '--'
  410. }
  411. return `Offset ${Math.round(normalizeRotationDeg(offsetDeg))}deg`
  412. }
  413. function getTrueHeadingDeg(magneticHeadingDeg: number): number {
  414. return normalizeRotationDeg(magneticHeadingDeg + MAGNETIC_DECLINATION_DEG)
  415. }
  416. function getMagneticHeadingDeg(trueHeadingDeg: number): number {
  417. return normalizeRotationDeg(trueHeadingDeg - MAGNETIC_DECLINATION_DEG)
  418. }
  419. function getMapNorthOffsetDeg(_mode: NorthReferenceMode): number {
  420. return MAP_NORTH_OFFSET_DEG
  421. }
  422. function getCompassReferenceHeadingDeg(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  423. if (mode === 'true') {
  424. return getTrueHeadingDeg(magneticHeadingDeg)
  425. }
  426. return normalizeRotationDeg(magneticHeadingDeg)
  427. }
  428. function getMapReferenceHeadingDegFromSensor(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  429. if (mode === 'magnetic') {
  430. return normalizeRotationDeg(magneticHeadingDeg)
  431. }
  432. return getTrueHeadingDeg(magneticHeadingDeg)
  433. }
  434. function getMapReferenceHeadingDegFromCourse(mode: NorthReferenceMode, trueHeadingDeg: number): number {
  435. if (mode === 'magnetic') {
  436. return getMagneticHeadingDeg(trueHeadingDeg)
  437. }
  438. return normalizeRotationDeg(trueHeadingDeg)
  439. }
  440. function formatNorthReferenceText(mode: NorthReferenceMode): string {
  441. if (mode === 'magnetic') {
  442. return `Compass Magnetic / Heading-Up Magnetic (${MAGNETIC_DECLINATION_TEXT})`
  443. }
  444. return `Compass True / Heading-Up True (${MAGNETIC_DECLINATION_TEXT})`
  445. }
  446. function formatCompassDeclinationText(mode: NorthReferenceMode): string {
  447. if (mode === 'true') {
  448. return MAGNETIC_DECLINATION_TEXT
  449. }
  450. return ''
  451. }
  452. function formatNorthReferenceButtonText(mode: NorthReferenceMode): string {
  453. return mode === 'magnetic' ? '北参照:磁北' : '北参照:真北'
  454. }
  455. function formatNorthReferenceStatusText(mode: NorthReferenceMode): string {
  456. if (mode === 'magnetic') {
  457. return '已切到磁北模式'
  458. }
  459. return '已切到真北模式'
  460. }
  461. function getNextNorthReferenceMode(mode: NorthReferenceMode): NorthReferenceMode {
  462. return mode === 'magnetic' ? 'true' : 'magnetic'
  463. }
  464. function formatCompassNeedleDegForMode(mode: NorthReferenceMode, magneticHeadingDeg: number | null): number {
  465. if (magneticHeadingDeg === null) {
  466. return 0
  467. }
  468. const referenceHeadingDeg = mode === 'true'
  469. ? getTrueHeadingDeg(magneticHeadingDeg)
  470. : normalizeRotationDeg(magneticHeadingDeg)
  471. return normalizeRotationDeg(360 - referenceHeadingDeg)
  472. }
  473. function formatCacheHitRate(memoryHitCount: number, diskHitCount: number, networkFetchCount: number): string {
  474. const total = memoryHitCount + diskHitCount + networkFetchCount
  475. if (!total) {
  476. return '--'
  477. }
  478. const hitRate = ((memoryHitCount + diskHitCount) / total) * 100
  479. return `${Math.round(hitRate)}%`
  480. }
  481. function formatGpsCoordText(point: LonLatPoint | null, accuracyMeters: number | null): string {
  482. if (!point) {
  483. return '--'
  484. }
  485. const base = `${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}`
  486. if (accuracyMeters === null || !Number.isFinite(accuracyMeters)) {
  487. return base
  488. }
  489. return `${base} / 卤${Math.round(accuracyMeters)}m`
  490. }
  491. function getApproxDistanceMeters(a: LonLatPoint, b: LonLatPoint): number {
  492. const avgLatRad = ((a.lat + b.lat) / 2) * Math.PI / 180
  493. const dx = (b.lon - a.lon) * 111320 * Math.cos(avgLatRad)
  494. const dy = (b.lat - a.lat) * 110540
  495. return Math.sqrt(dx * dx + dy * dy)
  496. }
  497. function resolveSmartHeadingSource(speedKmh: number | null, movementReliable: boolean): SmartHeadingSource {
  498. if (!movementReliable || speedKmh === null || !Number.isFinite(speedKmh) || speedKmh <= SMART_HEADING_BLEND_START_SPEED_KMH) {
  499. return 'sensor'
  500. }
  501. if (speedKmh >= SMART_HEADING_MOVEMENT_SPEED_KMH) {
  502. return 'movement'
  503. }
  504. return 'blended'
  505. }
  506. function getInitialBearingDeg(from: LonLatPoint, to: LonLatPoint): number {
  507. const fromLatRad = from.lat * Math.PI / 180
  508. const toLatRad = to.lat * Math.PI / 180
  509. const deltaLonRad = (to.lon - from.lon) * Math.PI / 180
  510. const y = Math.sin(deltaLonRad) * Math.cos(toLatRad)
  511. const x = Math.cos(fromLatRad) * Math.sin(toLatRad) - Math.sin(fromLatRad) * Math.cos(toLatRad) * Math.cos(deltaLonRad)
  512. const bearingDeg = Math.atan2(y, x) * 180 / Math.PI
  513. return normalizeRotationDeg(bearingDeg)
  514. }
  515. export class MapEngine {
  516. buildVersion: string
  517. renderer: WebGLMapRenderer
  518. compassController: CompassHeadingController
  519. locationController: LocationController
  520. heartRateController: HeartRateInputController
  521. feedbackDirector: FeedbackDirector
  522. onData: (patch: Partial<MapEngineViewState>) => void
  523. state: MapEngineViewState
  524. previewScale: number
  525. previewOriginX: number
  526. previewOriginY: number
  527. panLastX: number
  528. panLastY: number
  529. panLastTimestamp: number
  530. tapStartX: number
  531. tapStartY: number
  532. tapStartAt: number
  533. panVelocityX: number
  534. panVelocityY: number
  535. pinchStartDistance: number
  536. pinchStartScale: number
  537. pinchStartAngle: number
  538. pinchStartRotationDeg: number
  539. pinchAnchorWorldX: number
  540. pinchAnchorWorldY: number
  541. gestureMode: GestureMode
  542. inertiaTimer: number
  543. previewResetTimer: number
  544. viewSyncTimer: number
  545. autoRotateTimer: number
  546. pendingViewPatch: Partial<MapEngineViewState>
  547. mounted: boolean
  548. northReferenceMode: NorthReferenceMode
  549. sensorHeadingDeg: number | null
  550. smoothedSensorHeadingDeg: number | null
  551. compassDisplayHeadingDeg: number | null
  552. autoRotateHeadingDeg: number | null
  553. courseHeadingDeg: number | null
  554. targetAutoRotationDeg: number | null
  555. autoRotateSourceMode: AutoRotateSourceMode
  556. autoRotateCalibrationOffsetDeg: number | null
  557. autoRotateCalibrationPending: boolean
  558. minZoom: number
  559. maxZoom: number
  560. defaultZoom: number
  561. defaultCenterTileX: number
  562. defaultCenterTileY: number
  563. tileBoundsByZoom: Record<number, TileZoomBounds> | null
  564. currentGpsPoint: LonLatPoint | null
  565. currentGpsTrack: LonLatPoint[]
  566. currentGpsAccuracyMeters: number | null
  567. currentGpsInsideMap: boolean
  568. courseData: OrienteeringCourseData | null
  569. courseOverlayVisible: boolean
  570. cpRadiusMeters: number
  571. configAppId: string
  572. configSchemaVersion: string
  573. configVersion: string
  574. controlScoreOverrides: Record<string, number>
  575. defaultControlScore: number | null
  576. gameRuntime: GameRuntime
  577. telemetryRuntime: TelemetryRuntime
  578. gamePresentation: GamePresentationState
  579. gameMode: 'classic-sequential' | 'score-o'
  580. punchPolicy: 'enter' | 'enter-confirm'
  581. punchRadiusMeters: number
  582. requiresFocusSelection: boolean
  583. skipEnabled: boolean
  584. skipRadiusMeters: number
  585. skipRequiresConfirm: boolean
  586. autoFinishOnLastControl: boolean
  587. punchFeedbackTimer: number
  588. contentCardTimer: number
  589. mapPulseTimer: number
  590. stageFxTimer: number
  591. sessionTimerInterval: number
  592. hasGpsCenteredOnce: boolean
  593. gpsLockEnabled: boolean
  594. constructor(buildVersion: string, callbacks: MapEngineCallbacks) {
  595. this.buildVersion = buildVersion
  596. this.onData = callbacks.onData
  597. this.renderer = new WebGLMapRenderer(
  598. (stats) => {
  599. this.applyStats(stats)
  600. },
  601. (message) => {
  602. this.setState({
  603. statusText: `${message} (${this.buildVersion})`,
  604. })
  605. },
  606. )
  607. this.compassController = new CompassHeadingController({
  608. onHeading: (headingDeg) => {
  609. this.handleCompassHeading(headingDeg)
  610. },
  611. onError: (message) => {
  612. this.handleCompassError(message)
  613. },
  614. })
  615. this.locationController = new LocationController({
  616. onLocation: (update) => {
  617. this.handleLocationUpdate(update.longitude, update.latitude, typeof update.accuracy === 'number' ? update.accuracy : null)
  618. },
  619. onStatus: (message) => {
  620. this.setState({
  621. gpsTracking: this.locationController.listening,
  622. gpsTrackingText: message,
  623. ...this.getLocationControllerViewPatch(),
  624. }, true)
  625. },
  626. onError: (message) => {
  627. this.setState({
  628. gpsTracking: this.locationController.listening,
  629. gpsTrackingText: message,
  630. ...this.getLocationControllerViewPatch(),
  631. statusText: `${message} (${this.buildVersion})`,
  632. }, true)
  633. },
  634. onDebugStateChange: () => {
  635. this.setState(this.getLocationControllerViewPatch(), true)
  636. },
  637. })
  638. this.heartRateController = new HeartRateInputController({
  639. onHeartRate: (bpm) => {
  640. this.telemetryRuntime.dispatch({
  641. type: 'heart_rate_updated',
  642. at: Date.now(),
  643. bpm,
  644. })
  645. this.syncSessionTimerText()
  646. },
  647. onStatus: (message) => {
  648. const deviceName = this.heartRateController.currentDeviceName
  649. || (this.heartRateController.reconnecting ? this.heartRateController.lastDeviceName : null)
  650. || '--'
  651. this.setState({
  652. heartRateStatusText: message,
  653. heartRateDeviceText: deviceName,
  654. heartRateScanText: this.getHeartRateScanText(),
  655. ...this.getHeartRateControllerViewPatch(),
  656. }, true)
  657. },
  658. onError: (message) => {
  659. this.clearHeartRateSignal()
  660. const deviceName = this.heartRateController.reconnecting
  661. ? (this.heartRateController.lastDeviceName || '--')
  662. : '--'
  663. this.setState({
  664. heartRateConnected: false,
  665. heartRateStatusText: message,
  666. heartRateDeviceText: deviceName,
  667. heartRateScanText: this.getHeartRateScanText(),
  668. ...this.getHeartRateControllerViewPatch(),
  669. statusText: `${message} (${this.buildVersion})`,
  670. }, true)
  671. },
  672. onConnectionChange: (connected, deviceName) => {
  673. if (!connected) {
  674. this.clearHeartRateSignal()
  675. }
  676. const resolvedDeviceName = connected
  677. ? (deviceName || '--')
  678. : (this.heartRateController.reconnecting
  679. ? (this.heartRateController.lastDeviceName || '--')
  680. : '--')
  681. this.setState({
  682. heartRateConnected: connected,
  683. heartRateDeviceText: resolvedDeviceName,
  684. heartRateStatusText: connected
  685. ? (this.heartRateController.sourceMode === 'mock' ? '模拟心率源已连接' : '心率带已连接')
  686. : (this.heartRateController.reconnecting ? '心率带自动重连中' : (this.heartRateController.sourceMode === 'mock' ? '模拟心率源未连接' : '心率带未连接')),
  687. heartRateScanText: this.getHeartRateScanText(),
  688. heartRateDiscoveredDevices: this.formatHeartRateDevices(this.heartRateController.discoveredDevices),
  689. ...this.getHeartRateControllerViewPatch(),
  690. }, true)
  691. },
  692. onDeviceListChange: (devices) => {
  693. this.setState({
  694. heartRateDiscoveredDevices: this.formatHeartRateDevices(devices),
  695. heartRateScanText: this.getHeartRateScanText(),
  696. ...this.getHeartRateControllerViewPatch(),
  697. }, true)
  698. },
  699. onDebugStateChange: () => {
  700. this.setState(this.getHeartRateControllerViewPatch(), true)
  701. },
  702. })
  703. this.feedbackDirector = new FeedbackDirector({
  704. showPunchFeedback: (text, tone, motionClass) => {
  705. this.showPunchFeedback(text, tone, motionClass)
  706. },
  707. showContentCard: (title, body, motionClass) => {
  708. this.showContentCard(title, body, motionClass)
  709. },
  710. setPunchButtonFxClass: (className) => {
  711. this.setPunchButtonFxClass(className)
  712. },
  713. showMapPulse: (controlId, motionClass) => {
  714. this.showMapPulse(controlId, motionClass)
  715. },
  716. showStageFx: (className) => {
  717. this.showStageFx(className)
  718. },
  719. stopLocationTracking: () => {
  720. if (this.locationController.listening) {
  721. this.locationController.stop()
  722. }
  723. },
  724. })
  725. this.minZoom = MIN_ZOOM
  726. this.maxZoom = MAX_ZOOM
  727. this.defaultZoom = DEFAULT_ZOOM
  728. this.defaultCenterTileX = DEFAULT_CENTER_TILE_X
  729. this.defaultCenterTileY = DEFAULT_CENTER_TILE_Y
  730. this.tileBoundsByZoom = null
  731. this.currentGpsPoint = null
  732. this.currentGpsTrack = []
  733. this.currentGpsAccuracyMeters = null
  734. this.currentGpsInsideMap = false
  735. this.courseData = null
  736. this.courseOverlayVisible = false
  737. this.cpRadiusMeters = 5
  738. this.configAppId = ''
  739. this.configSchemaVersion = '1'
  740. this.configVersion = ''
  741. this.controlScoreOverrides = {}
  742. this.defaultControlScore = null
  743. this.gameRuntime = new GameRuntime()
  744. this.telemetryRuntime = new TelemetryRuntime()
  745. this.telemetryRuntime.configure()
  746. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  747. this.gameMode = 'classic-sequential'
  748. this.punchPolicy = 'enter-confirm'
  749. this.punchRadiusMeters = 5
  750. this.requiresFocusSelection = false
  751. this.skipEnabled = false
  752. this.skipRadiusMeters = 30
  753. this.skipRequiresConfirm = true
  754. this.autoFinishOnLastControl = true
  755. this.gpsLockEnabled = false
  756. this.punchFeedbackTimer = 0
  757. this.contentCardTimer = 0
  758. this.mapPulseTimer = 0
  759. this.stageFxTimer = 0
  760. this.sessionTimerInterval = 0
  761. this.hasGpsCenteredOnce = false
  762. this.state = {
  763. buildVersion: this.buildVersion,
  764. renderMode: RENDER_MODE,
  765. projectionMode: PROJECTION_MODE,
  766. mapReady: false,
  767. mapReadyText: 'BOOTING',
  768. mapName: '未命名配置',
  769. configStatusText: '远程配置待加载',
  770. zoom: DEFAULT_ZOOM,
  771. rotationDeg: 0,
  772. rotationText: formatRotationText(0),
  773. rotationMode: 'manual',
  774. rotationModeText: formatRotationModeText('manual'),
  775. rotationToggleText: formatRotationToggleText('manual'),
  776. orientationMode: 'manual',
  777. orientationModeText: formatOrientationModeText('manual'),
  778. sensorHeadingText: '--',
  779. compassDeclinationText: formatCompassDeclinationText(DEFAULT_NORTH_REFERENCE_MODE),
  780. northReferenceButtonText: formatNorthReferenceButtonText(DEFAULT_NORTH_REFERENCE_MODE),
  781. autoRotateSourceText: formatAutoRotateSourceText('smart', false),
  782. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)),
  783. northReferenceText: formatNorthReferenceText(DEFAULT_NORTH_REFERENCE_MODE),
  784. compassNeedleDeg: 0,
  785. centerTileX: DEFAULT_CENTER_TILE_X,
  786. centerTileY: DEFAULT_CENTER_TILE_Y,
  787. centerText: buildCenterText(DEFAULT_ZOOM, DEFAULT_CENTER_TILE_X, DEFAULT_CENTER_TILE_Y),
  788. tileSource: TILE_SOURCE,
  789. visibleColumnCount: DESIRED_VISIBLE_COLUMNS,
  790. visibleTileCount: 0,
  791. readyTileCount: 0,
  792. memoryTileCount: 0,
  793. diskTileCount: 0,
  794. memoryHitCount: 0,
  795. diskHitCount: 0,
  796. networkFetchCount: 0,
  797. cacheHitRateText: '--',
  798. tileTranslateX: 0,
  799. tileTranslateY: 0,
  800. tileSizePx: 0,
  801. stageWidth: 0,
  802. stageHeight: 0,
  803. stageLeft: 0,
  804. stageTop: 0,
  805. statusText: `单 WebGL 管线已就绪,等待传感器接入 (${this.buildVersion})`,
  806. gpsTracking: false,
  807. gpsTrackingText: '持续定位待启动',
  808. gpsLockEnabled: false,
  809. gpsLockAvailable: false,
  810. locationSourceMode: 'real',
  811. locationSourceText: '真实定位',
  812. mockBridgeConnected: false,
  813. mockBridgeStatusText: '未连接',
  814. mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  815. mockCoordText: '--',
  816. mockSpeedText: '--',
  817. gpsCoordText: '--',
  818. heartRateSourceMode: 'real',
  819. heartRateSourceText: '真实心率',
  820. heartRateConnected: false,
  821. heartRateStatusText: '心率带未连接',
  822. heartRateDeviceText: '--',
  823. heartRateScanText: '未扫描',
  824. heartRateDiscoveredDevices: [],
  825. mockHeartRateBridgeConnected: false,
  826. mockHeartRateBridgeStatusText: '未连接',
  827. mockHeartRateBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  828. mockHeartRateText: '--',
  829. panelTimerText: '00:00:00',
  830. panelMileageText: '0m',
  831. panelActionTagText: '目标',
  832. panelDistanceTagText: '点距',
  833. panelDistanceValueText: '--',
  834. panelDistanceUnitText: '',
  835. panelProgressText: '0/0',
  836. panelSpeedValueText: '0',
  837. panelTelemetryTone: 'blue',
  838. panelHeartRateZoneNameText: '激活放松',
  839. panelHeartRateZoneRangeText: '<=39%',
  840. panelHeartRateValueText: '--',
  841. panelHeartRateUnitText: '',
  842. panelCaloriesValueText: '0',
  843. panelCaloriesUnitText: 'kcal',
  844. panelAverageSpeedValueText: '0',
  845. panelAverageSpeedUnitText: 'km/h',
  846. panelAccuracyValueText: '--',
  847. panelAccuracyUnitText: '',
  848. punchButtonText: '打点',
  849. gameSessionStatus: 'idle',
  850. gameModeText: '顺序赛',
  851. punchButtonEnabled: false,
  852. skipButtonEnabled: false,
  853. punchHintText: '等待进入检查点范围',
  854. punchFeedbackVisible: false,
  855. punchFeedbackText: '',
  856. punchFeedbackTone: 'neutral',
  857. contentCardVisible: false,
  858. contentCardTitle: '',
  859. contentCardBody: '',
  860. punchButtonFxClass: '',
  861. punchFeedbackFxClass: '',
  862. contentCardFxClass: '',
  863. mapPulseVisible: false,
  864. mapPulseLeftPx: 0,
  865. mapPulseTopPx: 0,
  866. mapPulseFxClass: '',
  867. stageFxVisible: false,
  868. stageFxClass: '',
  869. osmReferenceEnabled: false,
  870. osmReferenceText: 'OSM参考:关',
  871. }
  872. this.previewScale = 1
  873. this.previewOriginX = 0
  874. this.previewOriginY = 0
  875. this.panLastX = 0
  876. this.panLastY = 0
  877. this.panLastTimestamp = 0
  878. this.tapStartX = 0
  879. this.tapStartY = 0
  880. this.tapStartAt = 0
  881. this.panVelocityX = 0
  882. this.panVelocityY = 0
  883. this.pinchStartDistance = 0
  884. this.pinchStartScale = 1
  885. this.pinchStartAngle = 0
  886. this.pinchStartRotationDeg = 0
  887. this.pinchAnchorWorldX = 0
  888. this.pinchAnchorWorldY = 0
  889. this.gestureMode = 'idle'
  890. this.inertiaTimer = 0
  891. this.previewResetTimer = 0
  892. this.viewSyncTimer = 0
  893. this.autoRotateTimer = 0
  894. this.pendingViewPatch = {}
  895. this.mounted = false
  896. this.northReferenceMode = DEFAULT_NORTH_REFERENCE_MODE
  897. this.sensorHeadingDeg = null
  898. this.smoothedSensorHeadingDeg = null
  899. this.compassDisplayHeadingDeg = null
  900. this.autoRotateHeadingDeg = null
  901. this.courseHeadingDeg = null
  902. this.targetAutoRotationDeg = null
  903. this.autoRotateSourceMode = 'smart'
  904. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)
  905. this.autoRotateCalibrationPending = false
  906. }
  907. getInitialData(): MapEngineViewState {
  908. return { ...this.state }
  909. }
  910. getGameInfoSnapshot(): MapEngineGameInfoSnapshot {
  911. const definition = this.gameRuntime.definition
  912. const sessionState = this.gameRuntime.state
  913. const telemetryState = this.telemetryRuntime.state
  914. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  915. const currentTarget = definition && sessionState
  916. ? definition.controls.find((control) => control.id === sessionState.currentTargetControlId) || null
  917. : null
  918. const currentTargetText = currentTarget
  919. ? `${currentTarget.label} / ${currentTarget.kind === 'start'
  920. ? '开始点'
  921. : currentTarget.kind === 'finish'
  922. ? '结束点'
  923. : '检查点'}`
  924. : '--'
  925. const title = this.state.mapName || (definition ? definition.title : '当前游戏')
  926. const subtitle = `${this.getGameModeText()} / ${formatGameSessionStatusText(this.state.gameSessionStatus)}`
  927. const localRows: MapEngineGameInfoRow[] = [
  928. { label: '比赛名称', value: title || '--' },
  929. { label: '配置版本', value: this.configVersion || '--' },
  930. { label: 'Schema版本', value: this.configSchemaVersion || '--' },
  931. { label: '活动ID', value: this.configAppId || '--' },
  932. { label: '地图', value: this.state.mapName || '--' },
  933. { label: '模式', value: this.getGameModeText() },
  934. { label: '状态', value: formatGameSessionStatusText(this.state.gameSessionStatus) },
  935. { label: '当前目标', value: currentTargetText },
  936. { label: '进度', value: this.gamePresentation.hud.progressText || '--' },
  937. { label: '当前积分', value: sessionState ? String(sessionState.score) : '0' },
  938. { label: '已完成点', value: sessionState ? String(sessionState.completedControlIds.length) : '0' },
  939. { label: '已跳过点', value: sessionState ? String(sessionState.skippedControlIds.length) : '0' },
  940. { label: '打点规则', value: `${this.punchPolicy} / ${this.punchRadiusMeters}m` },
  941. { label: '跳点规则', value: this.skipEnabled ? `${this.skipRadiusMeters}m / ${this.skipRequiresConfirm ? '确认跳过' : '直接跳过'}` : '关闭' },
  942. { label: '定位源', value: this.state.locationSourceText || '--' },
  943. { label: '当前位置', value: this.state.gpsCoordText || '--' },
  944. { label: 'GPS精度', value: telemetryState.lastGpsAccuracyMeters == null ? '--' : `${telemetryState.lastGpsAccuracyMeters.toFixed(1)}m` },
  945. { label: '目标距离', value: `${telemetryPresentation.distanceToTargetValueText}${telemetryPresentation.distanceToTargetUnitText}` || '--' },
  946. { label: '当前速度', value: `${telemetryPresentation.speedText} km/h` },
  947. { label: '心率源', value: this.state.heartRateSourceText || '--' },
  948. { label: '当前心率', value: this.state.panelHeartRateValueText === '--' ? '--' : `${this.state.panelHeartRateValueText}${this.state.panelHeartRateUnitText}` },
  949. { label: '心率设备', value: this.state.heartRateDeviceText || '--' },
  950. { label: '心率分区', value: this.state.panelHeartRateZoneNameText === '--' ? '--' : `${this.state.panelHeartRateZoneNameText} ${this.state.panelHeartRateZoneRangeText}` },
  951. { label: '本局用时', value: telemetryPresentation.timerText },
  952. { label: '累计里程', value: telemetryPresentation.mileageText },
  953. { label: '累计消耗', value: `${telemetryPresentation.caloriesValueText}${telemetryPresentation.caloriesUnitText}` },
  954. { label: '提示状态', value: this.state.punchHintText || '--' },
  955. ]
  956. const globalRows: MapEngineGameInfoRow[] = [
  957. { label: '全球积分', value: '未接入' },
  958. { label: '全球排名', value: '未接入' },
  959. { label: '在线人数', value: '未接入' },
  960. { label: '队伍状态', value: '未接入' },
  961. { label: '实时广播', value: '未接入' },
  962. ]
  963. return {
  964. title,
  965. subtitle,
  966. localRows,
  967. globalRows,
  968. }
  969. }
  970. destroy(): void {
  971. this.clearInertiaTimer()
  972. this.clearPreviewResetTimer()
  973. this.clearViewSyncTimer()
  974. this.clearAutoRotateTimer()
  975. this.clearPunchFeedbackTimer()
  976. this.clearContentCardTimer()
  977. this.clearMapPulseTimer()
  978. this.clearStageFxTimer()
  979. this.clearSessionTimerInterval()
  980. this.compassController.destroy()
  981. this.locationController.destroy()
  982. this.heartRateController.destroy()
  983. this.feedbackDirector.destroy()
  984. this.renderer.destroy()
  985. this.mounted = false
  986. }
  987. handleAppShow(): void {
  988. this.feedbackDirector.setAppAudioMode('foreground')
  989. }
  990. handleAppHide(): void {
  991. this.feedbackDirector.setAppAudioMode('foreground')
  992. }
  993. clearGameRuntime(): void {
  994. this.gameRuntime.clear()
  995. this.telemetryRuntime.reset()
  996. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  997. this.courseOverlayVisible = !!this.courseData
  998. this.clearSessionTimerInterval()
  999. this.setCourseHeading(null)
  1000. }
  1001. clearHeartRateSignal(): void {
  1002. this.telemetryRuntime.dispatch({
  1003. type: 'heart_rate_updated',
  1004. at: Date.now(),
  1005. bpm: null,
  1006. })
  1007. this.syncSessionTimerText()
  1008. }
  1009. clearFinishedTestOverlay(): void {
  1010. this.currentGpsPoint = null
  1011. this.currentGpsTrack = []
  1012. this.currentGpsAccuracyMeters = null
  1013. this.currentGpsInsideMap = false
  1014. this.courseOverlayVisible = false
  1015. this.setCourseHeading(null)
  1016. }
  1017. clearStartSessionResidue(): void {
  1018. this.currentGpsTrack = []
  1019. this.courseOverlayVisible = false
  1020. this.setCourseHeading(null)
  1021. }
  1022. handleClearMapTestArtifacts(): void {
  1023. this.clearFinishedTestOverlay()
  1024. this.setState({
  1025. gpsTracking: false,
  1026. gpsTrackingText: '测试痕迹已清空',
  1027. gpsCoordText: '--',
  1028. statusText: `已清空地图点位与轨迹 (${this.buildVersion})`,
  1029. }, true)
  1030. this.syncRenderer()
  1031. }
  1032. getHudTargetControlId(): string | null {
  1033. return this.gamePresentation.hud.hudTargetControlId
  1034. }
  1035. isSkipAvailable(): boolean {
  1036. const definition = this.gameRuntime.definition
  1037. const state = this.gameRuntime.state
  1038. if (!definition || !state || state.status !== 'running' || !definition.skipEnabled) {
  1039. return false
  1040. }
  1041. const currentTarget = definition.controls.find((control) => control.id === state.currentTargetControlId) || null
  1042. if (!currentTarget || currentTarget.kind !== 'control' || !this.currentGpsPoint) {
  1043. return false
  1044. }
  1045. const avgLatRad = ((currentTarget.point.lat + this.currentGpsPoint.lat) / 2) * Math.PI / 180
  1046. const dx = (this.currentGpsPoint.lon - currentTarget.point.lon) * 111320 * Math.cos(avgLatRad)
  1047. const dy = (this.currentGpsPoint.lat - currentTarget.point.lat) * 110540
  1048. const distanceMeters = Math.sqrt(dx * dx + dy * dy)
  1049. return distanceMeters <= definition.skipRadiusMeters
  1050. }
  1051. shouldConfirmSkipAction(): boolean {
  1052. return !!(this.gameRuntime.definition && this.gameRuntime.definition.skipRequiresConfirm)
  1053. }
  1054. getLocationControllerViewPatch(): Partial<MapEngineViewState> {
  1055. const debugState = this.locationController.getDebugState()
  1056. return {
  1057. gpsTracking: debugState.listening,
  1058. gpsLockEnabled: this.gpsLockEnabled,
  1059. gpsLockAvailable: !!this.currentGpsPoint && this.currentGpsInsideMap,
  1060. locationSourceMode: debugState.sourceMode,
  1061. locationSourceText: debugState.sourceModeText,
  1062. mockBridgeConnected: debugState.mockBridgeConnected,
  1063. mockBridgeStatusText: debugState.mockBridgeStatusText,
  1064. mockBridgeUrlText: debugState.mockBridgeUrlText,
  1065. mockCoordText: debugState.mockCoordText,
  1066. mockSpeedText: debugState.mockSpeedText,
  1067. }
  1068. }
  1069. getHeartRateControllerViewPatch(): Partial<MapEngineViewState> {
  1070. const debugState = this.heartRateController.getDebugState()
  1071. return {
  1072. heartRateSourceMode: debugState.sourceMode,
  1073. heartRateSourceText: debugState.sourceModeText,
  1074. mockHeartRateBridgeConnected: debugState.mockBridgeConnected,
  1075. mockHeartRateBridgeStatusText: debugState.mockBridgeStatusText,
  1076. mockHeartRateBridgeUrlText: debugState.mockBridgeUrlText,
  1077. mockHeartRateText: debugState.mockHeartRateText,
  1078. }
  1079. }
  1080. getGameModeText(): string {
  1081. return this.gameMode === 'score-o' ? '积分赛' : '顺序赛'
  1082. }
  1083. loadGameDefinitionFromCourse(): GameResult | null {
  1084. if (!this.courseData) {
  1085. this.clearGameRuntime()
  1086. return null
  1087. }
  1088. const definition = buildGameDefinitionFromCourse(
  1089. this.courseData,
  1090. this.cpRadiusMeters,
  1091. this.gameMode,
  1092. this.autoFinishOnLastControl,
  1093. this.punchPolicy,
  1094. this.punchRadiusMeters,
  1095. this.requiresFocusSelection,
  1096. this.skipEnabled,
  1097. this.skipRadiusMeters,
  1098. this.skipRequiresConfirm,
  1099. this.controlScoreOverrides,
  1100. this.defaultControlScore,
  1101. )
  1102. const result = this.gameRuntime.loadDefinition(definition)
  1103. this.telemetryRuntime.loadDefinition(definition)
  1104. this.courseOverlayVisible = true
  1105. this.syncGameResultState(result)
  1106. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, result.nextState, result.presentation.hud.hudTargetControlId)
  1107. this.updateSessionTimerLoop()
  1108. return result
  1109. }
  1110. refreshCourseHeadingFromPresentation(): void {
  1111. if (!this.courseData || !this.gamePresentation.map.activeLegIndices.length) {
  1112. this.setCourseHeading(null)
  1113. return
  1114. }
  1115. const activeLegIndex = this.gamePresentation.map.activeLegIndices[0]
  1116. const activeLeg = this.courseData.layers.legs[activeLegIndex]
  1117. if (!activeLeg) {
  1118. this.setCourseHeading(null)
  1119. return
  1120. }
  1121. this.setCourseHeading(getInitialBearingDeg(activeLeg.fromPoint, activeLeg.toPoint))
  1122. }
  1123. resolveGameStatusText(effects: GameEffect[]): string | null {
  1124. const lastEffect = effects.length ? effects[effects.length - 1] : null
  1125. if (!lastEffect) {
  1126. return null
  1127. }
  1128. if (lastEffect.type === 'control_completed') {
  1129. const sequenceText = typeof lastEffect.sequence === 'number' ? String(lastEffect.sequence) : lastEffect.controlId
  1130. return `宸插畬鎴愭鏌ョ偣 ${sequenceText} (${this.buildVersion})`
  1131. }
  1132. if (lastEffect.type === 'session_finished') {
  1133. return `璺嚎宸插畬鎴?(${this.buildVersion})`
  1134. }
  1135. if (lastEffect.type === 'session_started') {
  1136. return `椤哄簭鎵撶偣宸插紑濮?(${this.buildVersion})`
  1137. }
  1138. return null
  1139. }
  1140. getGameViewPatch(statusText?: string | null): Partial<MapEngineViewState> {
  1141. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  1142. const patch: Partial<MapEngineViewState> = {
  1143. gameSessionStatus: this.gameRuntime.state ? this.gameRuntime.state.status : 'idle',
  1144. gameModeText: this.getGameModeText(),
  1145. panelTimerText: telemetryPresentation.timerText,
  1146. panelMileageText: telemetryPresentation.mileageText,
  1147. panelActionTagText: this.gamePresentation.hud.actionTagText,
  1148. panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
  1149. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  1150. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  1151. panelSpeedValueText: telemetryPresentation.speedText,
  1152. panelTelemetryTone: telemetryPresentation.heartRateTone,
  1153. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  1154. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  1155. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  1156. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  1157. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  1158. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  1159. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  1160. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  1161. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  1162. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  1163. panelProgressText: this.gamePresentation.hud.progressText,
  1164. punchButtonText: this.gamePresentation.hud.punchButtonText,
  1165. punchButtonEnabled: this.gamePresentation.hud.punchButtonEnabled,
  1166. skipButtonEnabled: this.isSkipAvailable(),
  1167. punchHintText: this.gamePresentation.hud.punchHintText,
  1168. gpsLockEnabled: this.gpsLockEnabled,
  1169. gpsLockAvailable: !!this.currentGpsPoint && this.currentGpsInsideMap,
  1170. }
  1171. if (statusText) {
  1172. patch.statusText = statusText
  1173. }
  1174. return patch
  1175. }
  1176. clearPunchFeedbackTimer(): void {
  1177. if (this.punchFeedbackTimer) {
  1178. clearTimeout(this.punchFeedbackTimer)
  1179. this.punchFeedbackTimer = 0
  1180. }
  1181. }
  1182. clearContentCardTimer(): void {
  1183. if (this.contentCardTimer) {
  1184. clearTimeout(this.contentCardTimer)
  1185. this.contentCardTimer = 0
  1186. }
  1187. }
  1188. clearMapPulseTimer(): void {
  1189. if (this.mapPulseTimer) {
  1190. clearTimeout(this.mapPulseTimer)
  1191. this.mapPulseTimer = 0
  1192. }
  1193. }
  1194. clearStageFxTimer(): void {
  1195. if (this.stageFxTimer) {
  1196. clearTimeout(this.stageFxTimer)
  1197. this.stageFxTimer = 0
  1198. }
  1199. }
  1200. resetTransientGameUiState(): void {
  1201. this.clearPunchFeedbackTimer()
  1202. this.clearContentCardTimer()
  1203. this.clearMapPulseTimer()
  1204. this.clearStageFxTimer()
  1205. this.setState({
  1206. punchFeedbackVisible: false,
  1207. punchFeedbackText: '',
  1208. punchFeedbackTone: 'neutral',
  1209. punchFeedbackFxClass: '',
  1210. contentCardVisible: false,
  1211. contentCardTitle: '',
  1212. contentCardBody: '',
  1213. contentCardFxClass: '',
  1214. mapPulseVisible: false,
  1215. mapPulseFxClass: '',
  1216. stageFxVisible: false,
  1217. stageFxClass: '',
  1218. punchButtonFxClass: '',
  1219. }, true)
  1220. }
  1221. clearSessionTimerInterval(): void {
  1222. if (this.sessionTimerInterval) {
  1223. clearInterval(this.sessionTimerInterval)
  1224. this.sessionTimerInterval = 0
  1225. }
  1226. }
  1227. syncSessionTimerText(): void {
  1228. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  1229. this.setState({
  1230. panelTimerText: telemetryPresentation.timerText,
  1231. panelMileageText: telemetryPresentation.mileageText,
  1232. panelActionTagText: this.gamePresentation.hud.actionTagText,
  1233. panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
  1234. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  1235. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  1236. panelSpeedValueText: telemetryPresentation.speedText,
  1237. panelTelemetryTone: telemetryPresentation.heartRateTone,
  1238. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  1239. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  1240. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  1241. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  1242. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  1243. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  1244. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  1245. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  1246. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  1247. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  1248. }, true)
  1249. }
  1250. updateSessionTimerLoop(): void {
  1251. const gameState = this.gameRuntime.state
  1252. const shouldRun = !!gameState && gameState.status === 'running' && gameState.endedAt === null
  1253. this.syncSessionTimerText()
  1254. if (!shouldRun) {
  1255. this.clearSessionTimerInterval()
  1256. return
  1257. }
  1258. if (this.sessionTimerInterval) {
  1259. return
  1260. }
  1261. this.sessionTimerInterval = setInterval(() => {
  1262. this.syncSessionTimerText()
  1263. }, 1000) as unknown as number
  1264. }
  1265. getControlScreenPoint(controlId: string): { x: number; y: number } | null {
  1266. if (!this.gameRuntime.definition || !this.state.stageWidth || !this.state.stageHeight) {
  1267. return null
  1268. }
  1269. const control = this.gameRuntime.definition.controls.find((item) => item.id === controlId)
  1270. if (!control) {
  1271. return null
  1272. }
  1273. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1274. const screenPoint = worldToScreen({
  1275. centerWorldX: exactCenter.x,
  1276. centerWorldY: exactCenter.y,
  1277. viewportWidth: this.state.stageWidth,
  1278. viewportHeight: this.state.stageHeight,
  1279. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  1280. rotationRad: this.getRotationRad(this.state.rotationDeg),
  1281. }, lonLatToWorldTile(control.point, this.state.zoom), false)
  1282. if (screenPoint.x < -80 || screenPoint.x > this.state.stageWidth + 80 || screenPoint.y < -80 || screenPoint.y > this.state.stageHeight + 80) {
  1283. return null
  1284. }
  1285. return screenPoint
  1286. }
  1287. setPunchButtonFxClass(className: string): void {
  1288. this.setState({
  1289. punchButtonFxClass: className,
  1290. }, true)
  1291. }
  1292. showMapPulse(controlId: string, motionClass = ''): void {
  1293. const screenPoint = this.getControlScreenPoint(controlId)
  1294. if (!screenPoint) {
  1295. return
  1296. }
  1297. this.clearMapPulseTimer()
  1298. this.setState({
  1299. mapPulseVisible: true,
  1300. mapPulseLeftPx: screenPoint.x,
  1301. mapPulseTopPx: screenPoint.y,
  1302. mapPulseFxClass: motionClass,
  1303. }, true)
  1304. this.mapPulseTimer = setTimeout(() => {
  1305. this.mapPulseTimer = 0
  1306. this.setState({
  1307. mapPulseVisible: false,
  1308. mapPulseFxClass: '',
  1309. }, true)
  1310. }, 820) as unknown as number
  1311. }
  1312. showStageFx(className: string): void {
  1313. if (!className) {
  1314. return
  1315. }
  1316. this.clearStageFxTimer()
  1317. this.setState({
  1318. stageFxVisible: true,
  1319. stageFxClass: className,
  1320. }, true)
  1321. this.stageFxTimer = setTimeout(() => {
  1322. this.stageFxTimer = 0
  1323. this.setState({
  1324. stageFxVisible: false,
  1325. stageFxClass: '',
  1326. }, true)
  1327. }, 760) as unknown as number
  1328. }
  1329. showPunchFeedback(text: string, tone: 'neutral' | 'success' | 'warning', motionClass = ''): void {
  1330. this.clearPunchFeedbackTimer()
  1331. this.setState({
  1332. punchFeedbackVisible: true,
  1333. punchFeedbackText: text,
  1334. punchFeedbackTone: tone,
  1335. punchFeedbackFxClass: motionClass,
  1336. }, true)
  1337. this.punchFeedbackTimer = setTimeout(() => {
  1338. this.punchFeedbackTimer = 0
  1339. this.setState({
  1340. punchFeedbackVisible: false,
  1341. punchFeedbackFxClass: '',
  1342. }, true)
  1343. }, 1400) as unknown as number
  1344. }
  1345. showContentCard(title: string, body: string, motionClass = ''): void {
  1346. this.clearContentCardTimer()
  1347. this.setState({
  1348. contentCardVisible: true,
  1349. contentCardTitle: title,
  1350. contentCardBody: body,
  1351. contentCardFxClass: motionClass,
  1352. }, true)
  1353. this.contentCardTimer = setTimeout(() => {
  1354. this.contentCardTimer = 0
  1355. this.setState({
  1356. contentCardVisible: false,
  1357. contentCardFxClass: '',
  1358. }, true)
  1359. }, 2600) as unknown as number
  1360. }
  1361. closeContentCard(): void {
  1362. this.clearContentCardTimer()
  1363. this.setState({
  1364. contentCardVisible: false,
  1365. contentCardFxClass: '',
  1366. }, true)
  1367. }
  1368. applyGameEffects(effects: GameEffect[]): string | null {
  1369. this.feedbackDirector.handleEffects(effects)
  1370. if (effects.some((effect) => effect.type === 'session_finished')) {
  1371. this.setState({
  1372. gpsTracking: false,
  1373. gpsTrackingText: '测试结束,定位已停止',
  1374. }, true)
  1375. }
  1376. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, this.gameRuntime.state, this.getHudTargetControlId())
  1377. this.updateSessionTimerLoop()
  1378. return this.resolveGameStatusText(effects)
  1379. }
  1380. syncGameResultState(result: GameResult): void {
  1381. this.gamePresentation = result.presentation
  1382. this.refreshCourseHeadingFromPresentation()
  1383. }
  1384. resolveAppliedGameStatusText(result: GameResult, fallbackStatusText?: string | null): string | null {
  1385. return this.applyGameEffects(result.effects) || fallbackStatusText || this.resolveGameStatusText(result.effects)
  1386. }
  1387. commitGameResult(
  1388. result: GameResult,
  1389. fallbackStatusText?: string | null,
  1390. extraPatch: Partial<MapEngineViewState> = {},
  1391. syncRenderer = true,
  1392. ): string | null {
  1393. this.syncGameResultState(result)
  1394. const gameStatusText = this.resolveAppliedGameStatusText(result, fallbackStatusText)
  1395. this.setState({
  1396. ...this.getGameViewPatch(gameStatusText),
  1397. ...extraPatch,
  1398. }, true)
  1399. if (syncRenderer) {
  1400. this.syncRenderer()
  1401. }
  1402. return gameStatusText
  1403. }
  1404. handleStartGame(): void {
  1405. if (!this.gameRuntime.definition || !this.gameRuntime.state) {
  1406. this.setState({
  1407. statusText: `当前还没有可开始的路线 (${this.buildVersion})`,
  1408. }, true)
  1409. return
  1410. }
  1411. if (this.gameRuntime.state.status !== 'idle') {
  1412. return
  1413. }
  1414. this.feedbackDirector.reset()
  1415. this.resetTransientGameUiState()
  1416. this.clearStartSessionResidue()
  1417. if (!this.locationController.listening) {
  1418. this.locationController.start()
  1419. }
  1420. const startedAt = Date.now()
  1421. const startResult = this.gameRuntime.startSession(startedAt)
  1422. let gameResult = startResult
  1423. if (this.currentGpsPoint) {
  1424. const gpsResult = this.gameRuntime.dispatch({
  1425. type: 'gps_updated',
  1426. at: Date.now(),
  1427. lon: this.currentGpsPoint.lon,
  1428. lat: this.currentGpsPoint.lat,
  1429. accuracyMeters: this.currentGpsAccuracyMeters,
  1430. })
  1431. gameResult = {
  1432. nextState: gpsResult.nextState,
  1433. presentation: gpsResult.presentation,
  1434. effects: [...startResult.effects, ...gpsResult.effects],
  1435. }
  1436. }
  1437. this.courseOverlayVisible = true
  1438. const defaultStatusText = this.currentGpsPoint
  1439. ? `顺序打点已开始 (${this.buildVersion})`
  1440. : `顺序打点已开始,GPS定位启动中 (${this.buildVersion})`
  1441. this.commitGameResult(gameResult, defaultStatusText)
  1442. }
  1443. handleForceExitGame(): void {
  1444. this.feedbackDirector.reset()
  1445. if (!this.courseData) {
  1446. this.clearGameRuntime()
  1447. this.resetTransientGameUiState()
  1448. this.feedbackDirector.handleEffects([{ type: 'session_cancelled' }])
  1449. this.setState({
  1450. ...this.getGameViewPatch(`已退出当前对局 (${this.buildVersion})`),
  1451. }, true)
  1452. this.syncRenderer()
  1453. return
  1454. }
  1455. this.loadGameDefinitionFromCourse()
  1456. this.resetTransientGameUiState()
  1457. this.feedbackDirector.handleEffects([{ type: 'session_cancelled' }])
  1458. this.setState({
  1459. ...this.getGameViewPatch(`已退出当前对局 (${this.buildVersion})`),
  1460. }, true)
  1461. this.syncRenderer()
  1462. }
  1463. handlePunchAction(): void {
  1464. const gameResult = this.gameRuntime.dispatch({
  1465. type: 'punch_requested',
  1466. at: Date.now(),
  1467. })
  1468. this.commitGameResult(gameResult)
  1469. }
  1470. handleLocationUpdate(longitude: number, latitude: number, accuracyMeters: number | null): void {
  1471. const nextPoint: LonLatPoint = { lon: longitude, lat: latitude }
  1472. const lastTrackPoint = this.currentGpsTrack.length ? this.currentGpsTrack[this.currentGpsTrack.length - 1] : null
  1473. if (!lastTrackPoint || getApproxDistanceMeters(lastTrackPoint, nextPoint) >= GPS_TRACK_MIN_STEP_METERS) {
  1474. this.currentGpsTrack = [...this.currentGpsTrack, nextPoint].slice(-GPS_TRACK_MAX_POINTS)
  1475. }
  1476. this.currentGpsPoint = nextPoint
  1477. this.currentGpsAccuracyMeters = accuracyMeters
  1478. const gpsWorldPoint = lonLatToWorldTile(nextPoint, this.state.zoom)
  1479. const gpsTileX = Math.floor(gpsWorldPoint.x)
  1480. const gpsTileY = Math.floor(gpsWorldPoint.y)
  1481. const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
  1482. this.currentGpsInsideMap = gpsInsideMap
  1483. let gameStatusText: string | null = null
  1484. if (!gpsInsideMap && this.gpsLockEnabled) {
  1485. this.gpsLockEnabled = false
  1486. gameStatusText = `GPS已超出地图范围,锁定已关闭 (${this.buildVersion})`
  1487. }
  1488. if (this.courseData) {
  1489. const eventAt = Date.now()
  1490. const gameResult = this.gameRuntime.dispatch({
  1491. type: 'gps_updated',
  1492. at: eventAt,
  1493. lon: longitude,
  1494. lat: latitude,
  1495. accuracyMeters,
  1496. })
  1497. this.telemetryRuntime.dispatch({
  1498. type: 'gps_updated',
  1499. at: eventAt,
  1500. lon: longitude,
  1501. lat: latitude,
  1502. accuracyMeters,
  1503. })
  1504. this.syncGameResultState(gameResult)
  1505. gameStatusText = this.resolveAppliedGameStatusText(gameResult)
  1506. }
  1507. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1508. this.scheduleAutoRotate()
  1509. }
  1510. if (gpsInsideMap && (this.gpsLockEnabled || !this.hasGpsCenteredOnce)) {
  1511. this.hasGpsCenteredOnce = true
  1512. const lockedViewport = this.resolveViewportForExactCenter(gpsWorldPoint.x, gpsWorldPoint.y)
  1513. this.commitViewport({
  1514. ...lockedViewport,
  1515. gpsTracking: true,
  1516. gpsTrackingText: '持续定位进行中',
  1517. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1518. autoRotateSourceText: this.getAutoRotateSourceText(),
  1519. gpsLockEnabled: this.gpsLockEnabled,
  1520. gpsLockAvailable: true,
  1521. ...this.getGameViewPatch(),
  1522. }, gameStatusText || (this.gpsLockEnabled ? `GPS锁定跟随中 (${this.buildVersion})` : `GPS定位成功,已定位到当前位置 (${this.buildVersion})`), true)
  1523. return
  1524. }
  1525. this.setState({
  1526. gpsTracking: true,
  1527. gpsTrackingText: gpsInsideMap ? '持续定位进行中' : 'GPS不在当前地图范围内',
  1528. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1529. autoRotateSourceText: this.getAutoRotateSourceText(),
  1530. gpsLockEnabled: this.gpsLockEnabled,
  1531. gpsLockAvailable: gpsInsideMap,
  1532. ...this.getGameViewPatch(gameStatusText || (gpsInsideMap ? `GPS位置已更新 (${this.buildVersion})` : `GPS位置超出当前地图范围 (${this.buildVersion})`)),
  1533. }, true)
  1534. this.syncRenderer()
  1535. }
  1536. handleToggleGpsLock(): void {
  1537. if (!this.currentGpsPoint || !this.currentGpsInsideMap) {
  1538. this.setState({
  1539. gpsLockEnabled: false,
  1540. gpsLockAvailable: false,
  1541. statusText: this.currentGpsPoint
  1542. ? `当前位置不在地图范围内,无法锁定 (${this.buildVersion})`
  1543. : `当前还没有可锁定的GPS位置 (${this.buildVersion})`,
  1544. }, true)
  1545. return
  1546. }
  1547. const nextEnabled = !this.gpsLockEnabled
  1548. this.gpsLockEnabled = nextEnabled
  1549. if (nextEnabled) {
  1550. const gpsWorldPoint = lonLatToWorldTile(this.currentGpsPoint, this.state.zoom)
  1551. const gpsTileX = Math.floor(gpsWorldPoint.x)
  1552. const gpsTileY = Math.floor(gpsWorldPoint.y)
  1553. const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
  1554. if (gpsInsideMap) {
  1555. this.hasGpsCenteredOnce = true
  1556. const lockedViewport = this.resolveViewportForExactCenter(gpsWorldPoint.x, gpsWorldPoint.y)
  1557. this.commitViewport({
  1558. ...lockedViewport,
  1559. gpsLockEnabled: true,
  1560. gpsLockAvailable: true,
  1561. }, `GPS已锁定在屏幕中央 (${this.buildVersion})`, true)
  1562. return
  1563. }
  1564. this.setState({
  1565. gpsLockEnabled: true,
  1566. gpsLockAvailable: true,
  1567. statusText: `GPS锁定已开启,等待进入地图范围 (${this.buildVersion})`,
  1568. }, true)
  1569. this.syncRenderer()
  1570. return
  1571. }
  1572. this.setState({
  1573. gpsLockEnabled: false,
  1574. gpsLockAvailable: true,
  1575. statusText: `GPS锁定已关闭 (${this.buildVersion})`,
  1576. }, true)
  1577. this.syncRenderer()
  1578. }
  1579. handleToggleOsmReference(): void {
  1580. const nextEnabled = !this.state.osmReferenceEnabled
  1581. this.setState({
  1582. osmReferenceEnabled: nextEnabled,
  1583. osmReferenceText: nextEnabled ? 'OSM参考:开' : 'OSM参考:关',
  1584. statusText: nextEnabled ? `OSM参考底图已开启 (${this.buildVersion})` : `OSM参考底图已关闭 (${this.buildVersion})`,
  1585. }, true)
  1586. this.syncRenderer()
  1587. }
  1588. handleToggleGpsTracking(): void {
  1589. if (this.locationController.listening) {
  1590. this.locationController.stop()
  1591. return
  1592. }
  1593. this.locationController.start()
  1594. }
  1595. handleSetRealLocationMode(): void {
  1596. this.locationController.setSourceMode('real')
  1597. }
  1598. handleSetMockLocationMode(): void {
  1599. this.locationController.setSourceMode('mock')
  1600. }
  1601. handleConnectMockLocationBridge(): void {
  1602. this.locationController.connectMockBridge()
  1603. }
  1604. handleDisconnectMockLocationBridge(): void {
  1605. this.locationController.disconnectMockBridge()
  1606. }
  1607. handleSetMockLocationBridgeUrl(url: string): void {
  1608. this.locationController.setMockBridgeUrl(url)
  1609. }
  1610. handleSetGameMode(nextMode: 'classic-sequential' | 'score-o'): void {
  1611. if (this.gameMode === nextMode) {
  1612. return
  1613. }
  1614. this.gameMode = nextMode
  1615. const result = this.loadGameDefinitionFromCourse()
  1616. const modeText = this.getGameModeText()
  1617. if (!result) {
  1618. return
  1619. }
  1620. this.commitGameResult(result, `已切换到${modeText} (${this.buildVersion})`, {
  1621. gameModeText: modeText,
  1622. })
  1623. }
  1624. handleSkipAction(): void {
  1625. const gameResult = this.gameRuntime.dispatch({
  1626. type: 'skip_requested',
  1627. at: Date.now(),
  1628. lon: this.currentGpsPoint ? this.currentGpsPoint.lon : null,
  1629. lat: this.currentGpsPoint ? this.currentGpsPoint.lat : null,
  1630. })
  1631. this.commitGameResult(gameResult)
  1632. }
  1633. handleConnectHeartRate(): void {
  1634. this.heartRateController.startScanAndConnect()
  1635. }
  1636. handleDisconnectHeartRate(): void {
  1637. this.heartRateController.disconnect()
  1638. }
  1639. handleSetRealHeartRateMode(): void {
  1640. this.heartRateController.setSourceMode('real')
  1641. }
  1642. handleSetMockHeartRateMode(): void {
  1643. this.heartRateController.setSourceMode('mock')
  1644. }
  1645. handleConnectMockHeartRateBridge(): void {
  1646. this.heartRateController.connectMockBridge()
  1647. }
  1648. handleDisconnectMockHeartRateBridge(): void {
  1649. this.heartRateController.disconnectMockBridge()
  1650. }
  1651. handleSetMockHeartRateBridgeUrl(url: string): void {
  1652. this.heartRateController.setMockBridgeUrl(url)
  1653. }
  1654. handleConnectHeartRateDevice(deviceId: string): void {
  1655. this.heartRateController.connectToDiscoveredDevice(deviceId)
  1656. }
  1657. handleClearPreferredHeartRateDevice(): void {
  1658. this.heartRateController.clearPreferredDevice()
  1659. this.setState({
  1660. heartRateDeviceText: this.heartRateController.currentDeviceName || '--',
  1661. heartRateScanText: this.getHeartRateScanText(),
  1662. }, true)
  1663. }
  1664. handleDebugHeartRateTone(tone: HeartRateTone): void {
  1665. const sampleBpm = getHeartRateToneSampleBpm(tone, this.telemetryRuntime.config)
  1666. this.telemetryRuntime.dispatch({
  1667. type: 'heart_rate_updated',
  1668. at: Date.now(),
  1669. bpm: sampleBpm,
  1670. })
  1671. this.setState({
  1672. heartRateStatusText: `调试心率: ${sampleBpm} bpm / ${tone.toUpperCase()}`,
  1673. }, true)
  1674. this.syncSessionTimerText()
  1675. }
  1676. handleClearDebugHeartRate(): void {
  1677. this.telemetryRuntime.dispatch({
  1678. type: 'heart_rate_updated',
  1679. at: Date.now(),
  1680. bpm: null,
  1681. })
  1682. this.setState({
  1683. heartRateStatusText: this.heartRateController.connected
  1684. ? (this.heartRateController.sourceMode === 'mock' ? '模拟心率源已连接' : '心率带已连接')
  1685. : (this.heartRateController.sourceMode === 'mock' ? '模拟心率源未连接' : '心率带未连接'),
  1686. heartRateScanText: this.getHeartRateScanText(),
  1687. ...this.getHeartRateControllerViewPatch(),
  1688. }, true)
  1689. this.syncSessionTimerText()
  1690. }
  1691. formatHeartRateDevices(devices: HeartRateDiscoveredDevice[]): Array<{ deviceId: string; name: string; rssiText: string; preferred: boolean; connected: boolean }> {
  1692. return devices.map((device) => ({
  1693. deviceId: device.deviceId,
  1694. name: device.name,
  1695. rssiText: device.rssi === null ? '--' : `${device.rssi} dBm`,
  1696. preferred: device.isPreferred,
  1697. connected: !!this.heartRateController.currentDeviceId && this.heartRateController.currentDeviceId === device.deviceId && this.heartRateController.connected,
  1698. }))
  1699. }
  1700. getHeartRateScanText(): string {
  1701. if (this.heartRateController.sourceMode === 'mock') {
  1702. if (this.heartRateController.connected) {
  1703. return '模拟源已连接'
  1704. }
  1705. if (this.heartRateController.connecting) {
  1706. return '模拟源连接中'
  1707. }
  1708. return '模拟模式'
  1709. }
  1710. if (this.heartRateController.connected) {
  1711. return '已连接'
  1712. }
  1713. if (this.heartRateController.connecting) {
  1714. return '连接中'
  1715. }
  1716. if (this.heartRateController.disconnecting) {
  1717. return '断开中'
  1718. }
  1719. if (this.heartRateController.scanning) {
  1720. return this.heartRateController.lastDeviceId ? '扫描中(优先首选)' : '扫描中(等待选择)'
  1721. }
  1722. return this.heartRateController.discoveredDevices.length
  1723. ? `已发现 ${this.heartRateController.discoveredDevices.length} 个设备`
  1724. : '未扫描'
  1725. }
  1726. setStage(rect: MapEngineStageRect): void {
  1727. this.previewScale = 1
  1728. this.previewOriginX = rect.width / 2
  1729. this.previewOriginY = rect.height / 2
  1730. this.commitViewport(
  1731. {
  1732. stageWidth: rect.width,
  1733. stageHeight: rect.height,
  1734. stageLeft: rect.left,
  1735. stageTop: rect.top,
  1736. },
  1737. `地图视口已与 WebGL 引擎对齐 (${this.buildVersion})`,
  1738. true,
  1739. )
  1740. }
  1741. attachCanvas(canvasNode: any, width: number, height: number, dpr: number, labelCanvasNode?: any): void {
  1742. this.renderer.attachCanvas(canvasNode, width, height, dpr, labelCanvasNode)
  1743. this.mounted = true
  1744. this.state.mapReady = true
  1745. this.state.mapReadyText = 'READY'
  1746. this.onData({
  1747. mapReady: true,
  1748. mapReadyText: 'READY',
  1749. statusText: `单 WebGL 管线已完成,可切换手动或自动朝向 (${this.buildVersion})`,
  1750. })
  1751. this.syncRenderer()
  1752. this.compassController.start()
  1753. }
  1754. applyRemoteMapConfig(config: RemoteMapConfig): void {
  1755. MAGNETIC_DECLINATION_DEG = config.magneticDeclinationDeg
  1756. MAGNETIC_DECLINATION_TEXT = config.magneticDeclinationText
  1757. this.minZoom = config.minZoom
  1758. this.maxZoom = config.maxZoom
  1759. this.defaultZoom = config.defaultZoom
  1760. this.defaultCenterTileX = config.initialCenterTileX
  1761. this.defaultCenterTileY = config.initialCenterTileY
  1762. this.tileBoundsByZoom = config.tileBoundsByZoom
  1763. this.courseData = config.course
  1764. this.cpRadiusMeters = config.cpRadiusMeters
  1765. this.configAppId = config.configAppId
  1766. this.configSchemaVersion = config.configSchemaVersion
  1767. this.configVersion = config.configVersion
  1768. this.controlScoreOverrides = config.controlScoreOverrides
  1769. this.defaultControlScore = config.defaultControlScore
  1770. this.gameMode = config.gameMode
  1771. this.punchPolicy = config.punchPolicy
  1772. this.punchRadiusMeters = config.punchRadiusMeters
  1773. this.requiresFocusSelection = config.requiresFocusSelection
  1774. this.skipEnabled = config.skipEnabled
  1775. this.skipRadiusMeters = config.skipRadiusMeters
  1776. this.skipRequiresConfirm = config.skipRequiresConfirm
  1777. this.autoFinishOnLastControl = config.autoFinishOnLastControl
  1778. this.telemetryRuntime.configure(config.telemetryConfig)
  1779. this.feedbackDirector.configure({
  1780. audioConfig: config.audioConfig,
  1781. hapticsConfig: config.hapticsConfig,
  1782. uiEffectsConfig: config.uiEffectsConfig,
  1783. })
  1784. const gameResult = this.loadGameDefinitionFromCourse()
  1785. const gameStatusText = gameResult ? this.resolveAppliedGameStatusText(gameResult) : null
  1786. const statePatch: Partial<MapEngineViewState> = {
  1787. mapName: config.configTitle,
  1788. configStatusText: `配置已载入 / ${config.configTitle} / ${config.courseStatusText}`,
  1789. projectionMode: config.projectionModeText,
  1790. tileSource: config.tileSource,
  1791. sensorHeadingText: formatHeadingText(this.smoothedSensorHeadingDeg === null ? null : getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)),
  1792. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  1793. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  1794. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1795. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  1796. ...this.getGameViewPatch(gameStatusText),
  1797. }
  1798. if (!this.state.stageWidth || !this.state.stageHeight) {
  1799. this.setState({
  1800. ...statePatch,
  1801. zoom: this.defaultZoom,
  1802. centerTileX: this.defaultCenterTileX,
  1803. centerTileY: this.defaultCenterTileY,
  1804. centerText: buildCenterText(this.defaultZoom, this.defaultCenterTileX, this.defaultCenterTileY),
  1805. statusText: gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`,
  1806. }, true)
  1807. return
  1808. }
  1809. this.commitViewport({
  1810. ...statePatch,
  1811. zoom: this.defaultZoom,
  1812. centerTileX: this.defaultCenterTileX,
  1813. centerTileY: this.defaultCenterTileY,
  1814. tileTranslateX: 0,
  1815. tileTranslateY: 0,
  1816. }, gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`, true, () => {
  1817. this.resetPreviewState()
  1818. this.syncRenderer()
  1819. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1820. this.scheduleAutoRotate()
  1821. }
  1822. })
  1823. }
  1824. handleTouchStart(event: WechatMiniprogram.TouchEvent): void {
  1825. this.clearInertiaTimer()
  1826. this.clearPreviewResetTimer()
  1827. this.panVelocityX = 0
  1828. this.panVelocityY = 0
  1829. if (event.touches.length >= 2) {
  1830. const origin = this.gpsLockEnabled
  1831. ? { x: this.state.stageWidth / 2, y: this.state.stageHeight / 2 }
  1832. : this.getStagePoint(event.touches)
  1833. this.gestureMode = 'pinch'
  1834. this.pinchStartDistance = this.getTouchDistance(event.touches)
  1835. this.pinchStartScale = this.previewScale || 1
  1836. this.pinchStartAngle = this.getTouchAngle(event.touches)
  1837. this.pinchStartRotationDeg = this.state.rotationDeg
  1838. const anchorWorld = this.gpsLockEnabled && this.currentGpsPoint
  1839. ? lonLatToWorldTile(this.currentGpsPoint, this.state.zoom)
  1840. : screenToWorld(this.getCameraState(), origin, true)
  1841. this.pinchAnchorWorldX = anchorWorld.x
  1842. this.pinchAnchorWorldY = anchorWorld.y
  1843. this.setPreviewState(this.pinchStartScale, origin.x, origin.y)
  1844. this.syncRenderer()
  1845. this.compassController.start()
  1846. return
  1847. }
  1848. if (event.touches.length === 1) {
  1849. this.gestureMode = 'pan'
  1850. this.panLastX = event.touches[0].pageX
  1851. this.panLastY = event.touches[0].pageY
  1852. this.panLastTimestamp = event.timeStamp || Date.now()
  1853. this.tapStartX = event.touches[0].pageX
  1854. this.tapStartY = event.touches[0].pageY
  1855. this.tapStartAt = event.timeStamp || Date.now()
  1856. }
  1857. }
  1858. handleTouchMove(event: WechatMiniprogram.TouchEvent): void {
  1859. if (event.touches.length >= 2) {
  1860. const distance = this.getTouchDistance(event.touches)
  1861. const angle = this.getTouchAngle(event.touches)
  1862. const origin = this.gpsLockEnabled
  1863. ? { x: this.state.stageWidth / 2, y: this.state.stageHeight / 2 }
  1864. : this.getStagePoint(event.touches)
  1865. if (!this.pinchStartDistance) {
  1866. this.pinchStartDistance = distance
  1867. this.pinchStartScale = this.previewScale || 1
  1868. this.pinchStartAngle = angle
  1869. this.pinchStartRotationDeg = this.state.rotationDeg
  1870. const anchorWorld = this.gpsLockEnabled && this.currentGpsPoint
  1871. ? lonLatToWorldTile(this.currentGpsPoint, this.state.zoom)
  1872. : screenToWorld(this.getCameraState(), origin, true)
  1873. this.pinchAnchorWorldX = anchorWorld.x
  1874. this.pinchAnchorWorldY = anchorWorld.y
  1875. }
  1876. this.gestureMode = 'pinch'
  1877. const nextRotationDeg = this.state.orientationMode === 'heading-up'
  1878. ? this.state.rotationDeg
  1879. : normalizeRotationDeg(this.pinchStartRotationDeg + normalizeAngleDeltaRad(angle - this.pinchStartAngle) * 180 / Math.PI)
  1880. const anchorOffset = this.getWorldOffsetFromScreen(origin.x, origin.y, nextRotationDeg)
  1881. const resolvedViewport = this.resolveViewportForExactCenter(
  1882. this.pinchAnchorWorldX - anchorOffset.x,
  1883. this.pinchAnchorWorldY - anchorOffset.y,
  1884. nextRotationDeg,
  1885. )
  1886. this.setPreviewState(
  1887. clamp(this.pinchStartScale * (distance / this.pinchStartDistance), MIN_PREVIEW_SCALE, MAX_PREVIEW_SCALE),
  1888. origin.x,
  1889. origin.y,
  1890. )
  1891. this.commitViewport(
  1892. {
  1893. ...resolvedViewport,
  1894. rotationDeg: nextRotationDeg,
  1895. rotationText: formatRotationText(nextRotationDeg),
  1896. },
  1897. this.state.orientationMode === 'heading-up'
  1898. ? `双指缩放中,自动朝向保持开启 (${this.buildVersion})`
  1899. : `双指缩放与旋转中 (${this.buildVersion})`,
  1900. )
  1901. return
  1902. }
  1903. if (this.gestureMode !== 'pan' || event.touches.length !== 1) {
  1904. return
  1905. }
  1906. const touch = event.touches[0]
  1907. const deltaX = touch.pageX - this.panLastX
  1908. const deltaY = touch.pageY - this.panLastY
  1909. const nextTimestamp = event.timeStamp || Date.now()
  1910. const elapsed = Math.max(nextTimestamp - this.panLastTimestamp, 16)
  1911. const instantVelocityX = deltaX / elapsed
  1912. const instantVelocityY = deltaY / elapsed
  1913. this.panVelocityX = this.panVelocityX * 0.72 + instantVelocityX * 0.28
  1914. this.panVelocityY = this.panVelocityY * 0.72 + instantVelocityY * 0.28
  1915. this.panLastX = touch.pageX
  1916. this.panLastY = touch.pageY
  1917. this.panLastTimestamp = nextTimestamp
  1918. if (this.gpsLockEnabled) {
  1919. this.panVelocityX = 0
  1920. this.panVelocityY = 0
  1921. return
  1922. }
  1923. this.normalizeTranslate(
  1924. this.state.tileTranslateX + deltaX,
  1925. this.state.tileTranslateY + deltaY,
  1926. `宸叉嫋鎷藉崟 WebGL 鍦板浘寮曟搸 (${this.buildVersion})`,
  1927. )
  1928. }
  1929. handleTouchEnd(event: WechatMiniprogram.TouchEvent): void {
  1930. const changedTouch = event.changedTouches && event.changedTouches.length ? event.changedTouches[0] : null
  1931. const endedAsTap = changedTouch
  1932. && this.gestureMode === 'pan'
  1933. && event.touches.length === 0
  1934. && Math.abs(changedTouch.pageX - this.tapStartX) <= MAP_TAP_MOVE_THRESHOLD_PX
  1935. && Math.abs(changedTouch.pageY - this.tapStartY) <= MAP_TAP_MOVE_THRESHOLD_PX
  1936. && ((event.timeStamp || Date.now()) - this.tapStartAt) <= MAP_TAP_DURATION_MS
  1937. if (this.gestureMode === 'pinch' && event.touches.length < 2) {
  1938. const gestureScale = this.previewScale || 1
  1939. const zoomDelta = Math.round(Math.log2(gestureScale))
  1940. const originX = this.gpsLockEnabled ? this.state.stageWidth / 2 : (this.previewOriginX || this.state.stageWidth / 2)
  1941. const originY = this.gpsLockEnabled ? this.state.stageHeight / 2 : (this.previewOriginY || this.state.stageHeight / 2)
  1942. if (zoomDelta) {
  1943. const residualScale = gestureScale / Math.pow(2, zoomDelta)
  1944. this.zoomAroundPoint(zoomDelta, originX, originY, residualScale)
  1945. } else {
  1946. this.animatePreviewToRest()
  1947. }
  1948. this.resetPinchState()
  1949. this.panVelocityX = 0
  1950. this.panVelocityY = 0
  1951. if (event.touches.length === 1) {
  1952. this.gestureMode = 'pan'
  1953. this.panLastX = event.touches[0].pageX
  1954. this.panLastY = event.touches[0].pageY
  1955. this.panLastTimestamp = event.timeStamp || Date.now()
  1956. return
  1957. }
  1958. this.gestureMode = 'idle'
  1959. this.renderer.setAnimationPaused(false)
  1960. this.scheduleAutoRotate()
  1961. return
  1962. }
  1963. if (event.touches.length === 1) {
  1964. this.gestureMode = 'pan'
  1965. this.panLastX = event.touches[0].pageX
  1966. this.panLastY = event.touches[0].pageY
  1967. this.panLastTimestamp = event.timeStamp || Date.now()
  1968. return
  1969. }
  1970. if (this.gestureMode === 'pan' && (Math.abs(this.panVelocityX) >= INERTIA_MIN_SPEED || Math.abs(this.panVelocityY) >= INERTIA_MIN_SPEED)) {
  1971. this.startInertia()
  1972. this.gestureMode = 'idle'
  1973. this.resetPinchState()
  1974. return
  1975. }
  1976. if (endedAsTap && changedTouch) {
  1977. this.handleMapTap(changedTouch.pageX - this.state.stageLeft, changedTouch.pageY - this.state.stageTop)
  1978. }
  1979. this.gestureMode = 'idle'
  1980. this.resetPinchState()
  1981. this.renderer.setAnimationPaused(false)
  1982. this.scheduleAutoRotate()
  1983. }
  1984. handleTouchCancel(): void {
  1985. this.gestureMode = 'idle'
  1986. this.resetPinchState()
  1987. this.panVelocityX = 0
  1988. this.panVelocityY = 0
  1989. this.clearInertiaTimer()
  1990. this.animatePreviewToRest()
  1991. this.renderer.setAnimationPaused(false)
  1992. this.scheduleAutoRotate()
  1993. }
  1994. handleMapTap(stageX: number, stageY: number): void {
  1995. if (!this.gameRuntime.definition || !this.gameRuntime.state || this.gameRuntime.definition.mode !== 'score-o') {
  1996. return
  1997. }
  1998. const focusedControlId = this.findFocusableControlAt(stageX, stageY)
  1999. if (focusedControlId === undefined) {
  2000. return
  2001. }
  2002. const gameResult = this.gameRuntime.dispatch({
  2003. type: 'control_focused',
  2004. at: Date.now(),
  2005. controlId: focusedControlId,
  2006. })
  2007. this.commitGameResult(
  2008. gameResult,
  2009. focusedControlId ? `已选择目标点 (${this.buildVersion})` : `已取消目标点选择 (${this.buildVersion})`,
  2010. )
  2011. }
  2012. findFocusableControlAt(stageX: number, stageY: number): string | null | undefined {
  2013. if (!this.gameRuntime.definition || !this.courseData || !this.state.stageWidth || !this.state.stageHeight) {
  2014. return undefined
  2015. }
  2016. const focusableControls = this.gameRuntime.definition.controls.filter((control) => (
  2017. this.gamePresentation.map.focusableControlIds.includes(control.id)
  2018. ))
  2019. let matchedControlId: string | null | undefined
  2020. let matchedDistance = Number.POSITIVE_INFINITY
  2021. const hitRadiusPx = Math.max(28, this.getControlHitRadiusPx())
  2022. for (const control of focusableControls) {
  2023. const screenPoint = this.getControlScreenPoint(control.id)
  2024. if (!screenPoint) {
  2025. continue
  2026. }
  2027. const distancePx = Math.sqrt(
  2028. Math.pow(screenPoint.x - stageX, 2)
  2029. + Math.pow(screenPoint.y - stageY, 2),
  2030. )
  2031. if (distancePx <= hitRadiusPx && distancePx < matchedDistance) {
  2032. matchedDistance = distancePx
  2033. matchedControlId = control.id
  2034. }
  2035. }
  2036. if (matchedControlId === undefined) {
  2037. return undefined
  2038. }
  2039. return matchedControlId === this.gamePresentation.map.focusedControlId ? null : matchedControlId
  2040. }
  2041. getControlHitRadiusPx(): number {
  2042. if (!this.state.tileSizePx) {
  2043. return 28
  2044. }
  2045. const centerLonLat = worldTileToLonLat({ x: this.state.centerTileX + 0.5, y: this.state.centerTileY + 0.5 }, this.state.zoom)
  2046. const metersPerTile = Math.cos(centerLonLat.lat * Math.PI / 180) * 40075016.686 / Math.pow(2, this.state.zoom)
  2047. if (!metersPerTile) {
  2048. return 28
  2049. }
  2050. const pixelsPerMeter = this.state.tileSizePx / metersPerTile
  2051. return Math.max(28, this.cpRadiusMeters * pixelsPerMeter * 1.6)
  2052. }
  2053. handleRecenter(): void {
  2054. this.clearInertiaTimer()
  2055. this.clearPreviewResetTimer()
  2056. this.panVelocityX = 0
  2057. this.panVelocityY = 0
  2058. this.renderer.setAnimationPaused(false)
  2059. this.commitViewport(
  2060. {
  2061. zoom: this.defaultZoom,
  2062. centerTileX: this.defaultCenterTileX,
  2063. centerTileY: this.defaultCenterTileY,
  2064. tileTranslateX: 0,
  2065. tileTranslateY: 0,
  2066. },
  2067. `已回到单 WebGL 引擎默认首屏 (${this.buildVersion})`,
  2068. true,
  2069. () => {
  2070. this.resetPreviewState()
  2071. this.syncRenderer()
  2072. this.compassController.start()
  2073. this.scheduleAutoRotate()
  2074. },
  2075. )
  2076. }
  2077. handleRotateStep(stepDeg = ROTATE_STEP_DEG): void {
  2078. if (this.state.rotationMode === 'auto') {
  2079. this.setState({
  2080. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  2081. }, true)
  2082. return
  2083. }
  2084. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2085. const nextRotationDeg = normalizeRotationDeg(this.state.rotationDeg + stepDeg)
  2086. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  2087. this.clearInertiaTimer()
  2088. this.clearPreviewResetTimer()
  2089. this.panVelocityX = 0
  2090. this.panVelocityY = 0
  2091. this.renderer.setAnimationPaused(false)
  2092. this.commitViewport(
  2093. {
  2094. ...resolvedViewport,
  2095. rotationDeg: nextRotationDeg,
  2096. rotationText: formatRotationText(nextRotationDeg),
  2097. },
  2098. `旋转角度调整到 ${formatRotationText(nextRotationDeg)} (${this.buildVersion})`,
  2099. true,
  2100. () => {
  2101. this.resetPreviewState()
  2102. this.syncRenderer()
  2103. this.compassController.start()
  2104. },
  2105. )
  2106. }
  2107. handleRotationReset(): void {
  2108. if (this.state.rotationMode === 'auto') {
  2109. this.setState({
  2110. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  2111. }, true)
  2112. return
  2113. }
  2114. const targetRotationDeg = MAP_NORTH_OFFSET_DEG
  2115. if (Math.abs(normalizeAngleDeltaDeg(this.state.rotationDeg - targetRotationDeg)) <= 0.01) {
  2116. return
  2117. }
  2118. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2119. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, targetRotationDeg)
  2120. this.clearInertiaTimer()
  2121. this.clearPreviewResetTimer()
  2122. this.panVelocityX = 0
  2123. this.panVelocityY = 0
  2124. this.renderer.setAnimationPaused(false)
  2125. this.commitViewport(
  2126. {
  2127. ...resolvedViewport,
  2128. rotationDeg: targetRotationDeg,
  2129. rotationText: formatRotationText(targetRotationDeg),
  2130. },
  2131. `旋转角度已回到真北参考 (${this.buildVersion})`,
  2132. true,
  2133. () => {
  2134. this.resetPreviewState()
  2135. this.syncRenderer()
  2136. this.compassController.start()
  2137. },
  2138. )
  2139. }
  2140. handleToggleRotationMode(): void {
  2141. if (this.state.orientationMode === 'manual') {
  2142. this.setNorthUpMode()
  2143. return
  2144. }
  2145. if (this.state.orientationMode === 'north-up') {
  2146. this.setHeadingUpMode()
  2147. return
  2148. }
  2149. this.setManualMode()
  2150. }
  2151. handleSetManualMode(): void {
  2152. this.setManualMode()
  2153. }
  2154. handleSetNorthUpMode(): void {
  2155. this.setNorthUpMode()
  2156. }
  2157. handleSetHeadingUpMode(): void {
  2158. this.setHeadingUpMode()
  2159. }
  2160. handleCycleNorthReferenceMode(): void {
  2161. this.cycleNorthReferenceMode()
  2162. }
  2163. handleAutoRotateCalibrate(): void {
  2164. if (this.state.orientationMode !== 'heading-up') {
  2165. this.setState({
  2166. statusText: `请先切到朝向朝上模式再校准 (${this.buildVersion})`,
  2167. }, true)
  2168. return
  2169. }
  2170. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  2171. this.setState({
  2172. statusText: `当前还没有传感器方向数据,暂时无法校准 (${this.buildVersion})`,
  2173. }, true)
  2174. return
  2175. }
  2176. this.setState({
  2177. statusText: `已按当前持机方向完成朝向校准 (${this.buildVersion})`,
  2178. }, true)
  2179. this.scheduleAutoRotate()
  2180. }
  2181. setManualMode(): void {
  2182. this.clearAutoRotateTimer()
  2183. this.targetAutoRotationDeg = null
  2184. this.autoRotateCalibrationPending = false
  2185. this.setState({
  2186. rotationMode: 'manual',
  2187. rotationModeText: formatRotationModeText('manual'),
  2188. rotationToggleText: formatRotationToggleText('manual'),
  2189. orientationMode: 'manual',
  2190. orientationModeText: formatOrientationModeText('manual'),
  2191. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2192. statusText: `已切回手动地图旋转 (${this.buildVersion})`,
  2193. }, true)
  2194. }
  2195. setNorthUpMode(): void {
  2196. this.clearAutoRotateTimer()
  2197. this.targetAutoRotationDeg = null
  2198. this.autoRotateCalibrationPending = false
  2199. const mapNorthOffsetDeg = MAP_NORTH_OFFSET_DEG
  2200. this.autoRotateCalibrationOffsetDeg = mapNorthOffsetDeg
  2201. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2202. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, mapNorthOffsetDeg)
  2203. this.commitViewport(
  2204. {
  2205. ...resolvedViewport,
  2206. rotationDeg: mapNorthOffsetDeg,
  2207. rotationText: formatRotationText(mapNorthOffsetDeg),
  2208. rotationMode: 'manual',
  2209. rotationModeText: formatRotationModeText('north-up'),
  2210. rotationToggleText: formatRotationToggleText('north-up'),
  2211. orientationMode: 'north-up',
  2212. orientationModeText: formatOrientationModeText('north-up'),
  2213. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, mapNorthOffsetDeg),
  2214. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  2215. },
  2216. `地图已固定为真北朝上 (${this.buildVersion})`,
  2217. true,
  2218. () => {
  2219. this.resetPreviewState()
  2220. this.syncRenderer()
  2221. },
  2222. )
  2223. }
  2224. setHeadingUpMode(): void {
  2225. this.autoRotateCalibrationPending = false
  2226. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(this.northReferenceMode)
  2227. this.targetAutoRotationDeg = null
  2228. this.setState({
  2229. rotationMode: 'auto',
  2230. rotationModeText: formatRotationModeText('heading-up'),
  2231. rotationToggleText: formatRotationToggleText('heading-up'),
  2232. orientationMode: 'heading-up',
  2233. orientationModeText: formatOrientationModeText('heading-up'),
  2234. autoRotateSourceText: this.getAutoRotateSourceText(),
  2235. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2236. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  2237. statusText: `正在启用朝向朝上模式 (${this.buildVersion})`,
  2238. }, true)
  2239. if (this.refreshAutoRotateTarget()) {
  2240. this.scheduleAutoRotate()
  2241. }
  2242. }
  2243. handleCompassHeading(headingDeg: number): void {
  2244. this.sensorHeadingDeg = normalizeRotationDeg(headingDeg)
  2245. this.smoothedSensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  2246. ? this.sensorHeadingDeg
  2247. : interpolateAngleDeg(this.smoothedSensorHeadingDeg, this.sensorHeadingDeg, AUTO_ROTATE_HEADING_SMOOTHING)
  2248. const compassHeadingDeg = getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  2249. this.compassDisplayHeadingDeg = this.compassDisplayHeadingDeg === null
  2250. ? compassHeadingDeg
  2251. : interpolateAngleDeg(this.compassDisplayHeadingDeg, compassHeadingDeg, COMPASS_NEEDLE_SMOOTHING)
  2252. this.autoRotateHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  2253. this.setState({
  2254. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  2255. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  2256. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  2257. autoRotateSourceText: this.getAutoRotateSourceText(),
  2258. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  2259. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  2260. })
  2261. if (!this.refreshAutoRotateTarget()) {
  2262. return
  2263. }
  2264. if (this.state.orientationMode === 'heading-up') {
  2265. this.scheduleAutoRotate()
  2266. }
  2267. }
  2268. handleCompassError(message: string): void {
  2269. this.clearAutoRotateTimer()
  2270. this.targetAutoRotationDeg = null
  2271. this.autoRotateCalibrationPending = false
  2272. this.setState({
  2273. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2274. statusText: `${message} (${this.buildVersion})`,
  2275. }, true)
  2276. }
  2277. cycleNorthReferenceMode(): void {
  2278. const nextMode = getNextNorthReferenceMode(this.northReferenceMode)
  2279. const nextMapNorthOffsetDeg = getMapNorthOffsetDeg(nextMode)
  2280. const compassHeadingDeg = this.smoothedSensorHeadingDeg === null
  2281. ? null
  2282. : getCompassReferenceHeadingDeg(nextMode, this.smoothedSensorHeadingDeg)
  2283. this.northReferenceMode = nextMode
  2284. this.autoRotateCalibrationOffsetDeg = nextMapNorthOffsetDeg
  2285. this.compassDisplayHeadingDeg = compassHeadingDeg
  2286. if (this.state.orientationMode === 'north-up') {
  2287. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2288. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, MAP_NORTH_OFFSET_DEG)
  2289. this.commitViewport(
  2290. {
  2291. ...resolvedViewport,
  2292. rotationDeg: MAP_NORTH_OFFSET_DEG,
  2293. rotationText: formatRotationText(MAP_NORTH_OFFSET_DEG),
  2294. northReferenceText: formatNorthReferenceText(nextMode),
  2295. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  2296. compassDeclinationText: formatCompassDeclinationText(nextMode),
  2297. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  2298. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  2299. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  2300. },
  2301. `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  2302. true,
  2303. () => {
  2304. this.resetPreviewState()
  2305. this.syncRenderer()
  2306. },
  2307. )
  2308. return
  2309. }
  2310. this.setState({
  2311. northReferenceText: formatNorthReferenceText(nextMode),
  2312. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  2313. compassDeclinationText: formatCompassDeclinationText(nextMode),
  2314. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  2315. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  2316. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  2317. statusText: `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  2318. }, true)
  2319. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  2320. this.scheduleAutoRotate()
  2321. }
  2322. }
  2323. setCourseHeading(headingDeg: number | null): void {
  2324. this.courseHeadingDeg = headingDeg === null ? null : normalizeRotationDeg(headingDeg)
  2325. this.setState({
  2326. autoRotateSourceText: this.getAutoRotateSourceText(),
  2327. })
  2328. if (this.refreshAutoRotateTarget()) {
  2329. this.scheduleAutoRotate()
  2330. }
  2331. }
  2332. getMovementHeadingDeg(): number | null {
  2333. if (!this.currentGpsInsideMap) {
  2334. return null
  2335. }
  2336. if (this.currentGpsAccuracyMeters !== null && this.currentGpsAccuracyMeters > SMART_HEADING_MAX_ACCURACY_METERS) {
  2337. return null
  2338. }
  2339. if (this.currentGpsTrack.length < 2) {
  2340. return null
  2341. }
  2342. const lastPoint = this.currentGpsTrack[this.currentGpsTrack.length - 1]
  2343. let accumulatedDistanceMeters = 0
  2344. for (let index = this.currentGpsTrack.length - 2; index >= 0; index -= 1) {
  2345. const nextPoint = this.currentGpsTrack[index + 1]
  2346. const point = this.currentGpsTrack[index]
  2347. accumulatedDistanceMeters += getApproxDistanceMeters(point, nextPoint)
  2348. if (accumulatedDistanceMeters >= SMART_HEADING_MIN_DISTANCE_METERS) {
  2349. return getInitialBearingDeg(point, lastPoint)
  2350. }
  2351. }
  2352. return null
  2353. }
  2354. getSmartAutoRotateHeadingDeg(): number | null {
  2355. const sensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  2356. ? null
  2357. : getMapReferenceHeadingDegFromSensor(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  2358. const movementHeadingDeg = this.getMovementHeadingDeg()
  2359. const speedKmh = this.telemetryRuntime.state.currentSpeedKmh
  2360. const smartSource = resolveSmartHeadingSource(speedKmh, movementHeadingDeg !== null)
  2361. if (smartSource === 'movement') {
  2362. return movementHeadingDeg === null ? sensorHeadingDeg : movementHeadingDeg
  2363. }
  2364. if (smartSource === 'blended' && sensorHeadingDeg !== null && movementHeadingDeg !== null && speedKmh !== null) {
  2365. const blend = Math.max(0, Math.min(1, (speedKmh - SMART_HEADING_BLEND_START_SPEED_KMH) / (SMART_HEADING_MOVEMENT_SPEED_KMH - SMART_HEADING_BLEND_START_SPEED_KMH)))
  2366. return interpolateAngleDeg(sensorHeadingDeg, movementHeadingDeg, blend)
  2367. }
  2368. return sensorHeadingDeg === null ? movementHeadingDeg : sensorHeadingDeg
  2369. }
  2370. getAutoRotateSourceText(): string {
  2371. if (this.autoRotateSourceMode !== 'smart') {
  2372. return formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null)
  2373. }
  2374. const smartSource = resolveSmartHeadingSource(
  2375. this.telemetryRuntime.state.currentSpeedKmh,
  2376. this.getMovementHeadingDeg() !== null,
  2377. )
  2378. return formatSmartHeadingSourceText(smartSource)
  2379. }
  2380. resolveAutoRotateInputHeadingDeg(): number | null {
  2381. if (this.autoRotateSourceMode === 'smart') {
  2382. return this.getSmartAutoRotateHeadingDeg()
  2383. }
  2384. const sensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  2385. ? null
  2386. : getMapReferenceHeadingDegFromSensor(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  2387. const courseHeadingDeg = this.courseHeadingDeg === null
  2388. ? null
  2389. : getMapReferenceHeadingDegFromCourse(this.northReferenceMode, this.courseHeadingDeg)
  2390. if (this.autoRotateSourceMode === 'sensor') {
  2391. return sensorHeadingDeg
  2392. }
  2393. if (this.autoRotateSourceMode === 'course') {
  2394. return courseHeadingDeg === null ? sensorHeadingDeg : courseHeadingDeg
  2395. }
  2396. if (sensorHeadingDeg !== null && courseHeadingDeg !== null) {
  2397. return interpolateAngleDeg(sensorHeadingDeg, courseHeadingDeg, 0.35)
  2398. }
  2399. return sensorHeadingDeg === null ? courseHeadingDeg : sensorHeadingDeg
  2400. }
  2401. calibrateAutoRotateToCurrentOrientation(): boolean {
  2402. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  2403. if (inputHeadingDeg === null) {
  2404. return false
  2405. }
  2406. this.autoRotateCalibrationOffsetDeg = normalizeRotationDeg(this.state.rotationDeg + inputHeadingDeg)
  2407. this.autoRotateCalibrationPending = false
  2408. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  2409. this.setState({
  2410. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2411. })
  2412. return true
  2413. }
  2414. refreshAutoRotateTarget(): boolean {
  2415. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  2416. if (inputHeadingDeg === null) {
  2417. return false
  2418. }
  2419. if (this.autoRotateCalibrationPending || this.autoRotateCalibrationOffsetDeg === null) {
  2420. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  2421. return false
  2422. }
  2423. return true
  2424. }
  2425. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  2426. this.setState({
  2427. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  2428. })
  2429. return true
  2430. }
  2431. scheduleAutoRotate(): void {
  2432. if (this.autoRotateTimer || this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  2433. return
  2434. }
  2435. const step = () => {
  2436. this.autoRotateTimer = 0
  2437. if (this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  2438. return
  2439. }
  2440. if (this.gestureMode !== 'idle' || this.inertiaTimer || this.previewResetTimer) {
  2441. this.scheduleAutoRotate()
  2442. return
  2443. }
  2444. const currentRotationDeg = this.state.rotationDeg
  2445. const deltaDeg = normalizeAngleDeltaDeg(this.targetAutoRotationDeg - currentRotationDeg)
  2446. if (Math.abs(deltaDeg) <= AUTO_ROTATE_SNAP_DEG) {
  2447. if (Math.abs(deltaDeg) > 0.01) {
  2448. this.applyAutoRotation(this.targetAutoRotationDeg)
  2449. }
  2450. this.scheduleAutoRotate()
  2451. return
  2452. }
  2453. if (Math.abs(deltaDeg) <= AUTO_ROTATE_DEADZONE_DEG) {
  2454. this.scheduleAutoRotate()
  2455. return
  2456. }
  2457. const easedStepDeg = clamp(deltaDeg * AUTO_ROTATE_EASE, -AUTO_ROTATE_MAX_STEP_DEG, AUTO_ROTATE_MAX_STEP_DEG)
  2458. this.applyAutoRotation(normalizeRotationDeg(currentRotationDeg + easedStepDeg))
  2459. this.scheduleAutoRotate()
  2460. }
  2461. this.autoRotateTimer = setTimeout(step, AUTO_ROTATE_FRAME_MS) as unknown as number
  2462. }
  2463. applyAutoRotation(nextRotationDeg: number): void {
  2464. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2465. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  2466. this.setState({
  2467. ...resolvedViewport,
  2468. rotationDeg: nextRotationDeg,
  2469. rotationText: formatRotationText(nextRotationDeg),
  2470. centerText: buildCenterText(this.state.zoom, resolvedViewport.centerTileX, resolvedViewport.centerTileY),
  2471. })
  2472. this.syncRenderer()
  2473. }
  2474. applyStats(stats: MapRendererStats): void {
  2475. this.setState({
  2476. visibleTileCount: stats.visibleTileCount,
  2477. readyTileCount: stats.readyTileCount,
  2478. memoryTileCount: stats.memoryTileCount,
  2479. diskTileCount: stats.diskTileCount,
  2480. memoryHitCount: stats.memoryHitCount,
  2481. diskHitCount: stats.diskHitCount,
  2482. networkFetchCount: stats.networkFetchCount,
  2483. cacheHitRateText: formatCacheHitRate(stats.memoryHitCount, stats.diskHitCount, stats.networkFetchCount),
  2484. })
  2485. }
  2486. setState(patch: Partial<MapEngineViewState>, immediateUi = false): void {
  2487. this.state = {
  2488. ...this.state,
  2489. ...patch,
  2490. }
  2491. const viewPatch = this.pickViewPatch(patch)
  2492. if (!Object.keys(viewPatch).length) {
  2493. return
  2494. }
  2495. this.pendingViewPatch = {
  2496. ...this.pendingViewPatch,
  2497. ...viewPatch,
  2498. }
  2499. if (immediateUi) {
  2500. this.flushViewPatch()
  2501. return
  2502. }
  2503. if (this.viewSyncTimer) {
  2504. return
  2505. }
  2506. this.viewSyncTimer = setTimeout(() => {
  2507. this.viewSyncTimer = 0
  2508. this.flushViewPatch()
  2509. }, UI_SYNC_INTERVAL_MS) as unknown as number
  2510. }
  2511. commitViewport(
  2512. patch: Partial<MapEngineViewState>,
  2513. statusText: string,
  2514. immediateUi = false,
  2515. afterUpdate?: () => void,
  2516. ): void {
  2517. const nextZoom = typeof patch.zoom === 'number' ? patch.zoom : this.state.zoom
  2518. const nextCenterTileX = typeof patch.centerTileX === 'number' ? patch.centerTileX : this.state.centerTileX
  2519. const nextCenterTileY = typeof patch.centerTileY === 'number' ? patch.centerTileY : this.state.centerTileY
  2520. const nextStageWidth = typeof patch.stageWidth === 'number' ? patch.stageWidth : this.state.stageWidth
  2521. const nextStageHeight = typeof patch.stageHeight === 'number' ? patch.stageHeight : this.state.stageHeight
  2522. const tileSizePx = getTileSizePx({
  2523. centerWorldX: nextCenterTileX,
  2524. centerWorldY: nextCenterTileY,
  2525. viewportWidth: nextStageWidth,
  2526. viewportHeight: nextStageHeight,
  2527. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2528. })
  2529. this.setState({
  2530. ...patch,
  2531. tileSizePx,
  2532. centerText: buildCenterText(nextZoom, nextCenterTileX, nextCenterTileY),
  2533. statusText,
  2534. }, immediateUi)
  2535. this.syncRenderer()
  2536. this.compassController.start()
  2537. if (afterUpdate) {
  2538. afterUpdate()
  2539. }
  2540. }
  2541. buildScene() {
  2542. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2543. return {
  2544. tileSource: this.state.tileSource,
  2545. osmTileSource: OSM_TILE_SOURCE,
  2546. zoom: this.state.zoom,
  2547. centerTileX: this.state.centerTileX,
  2548. centerTileY: this.state.centerTileY,
  2549. exactCenterWorldX: exactCenter.x,
  2550. exactCenterWorldY: exactCenter.y,
  2551. tileBoundsByZoom: this.tileBoundsByZoom,
  2552. viewportWidth: this.state.stageWidth,
  2553. viewportHeight: this.state.stageHeight,
  2554. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2555. overdraw: OVERDRAW,
  2556. translateX: this.state.tileTranslateX,
  2557. translateY: this.state.tileTranslateY,
  2558. rotationRad: this.getRotationRad(this.state.rotationDeg),
  2559. previewScale: this.previewScale || 1,
  2560. previewOriginX: this.previewOriginX || this.state.stageWidth / 2,
  2561. previewOriginY: this.previewOriginY || this.state.stageHeight / 2,
  2562. track: this.currentGpsTrack,
  2563. gpsPoint: this.currentGpsPoint,
  2564. gpsCalibration: GPS_MAP_CALIBRATION,
  2565. gpsCalibrationOrigin: worldTileToLonLat({ x: this.defaultCenterTileX, y: this.defaultCenterTileY }, this.defaultZoom),
  2566. course: this.courseOverlayVisible ? this.courseData : null,
  2567. cpRadiusMeters: this.cpRadiusMeters,
  2568. controlVisualMode: this.gamePresentation.map.controlVisualMode,
  2569. showCourseLegs: this.gamePresentation.map.showCourseLegs,
  2570. guidanceLegAnimationEnabled: this.gamePresentation.map.guidanceLegAnimationEnabled,
  2571. focusableControlIds: this.gamePresentation.map.focusableControlIds,
  2572. focusedControlId: this.gamePresentation.map.focusedControlId,
  2573. focusedControlSequences: this.gamePresentation.map.focusedControlSequences,
  2574. activeControlSequences: this.gamePresentation.map.activeControlSequences,
  2575. activeStart: this.gamePresentation.map.activeStart,
  2576. completedStart: this.gamePresentation.map.completedStart,
  2577. activeFinish: this.gamePresentation.map.activeFinish,
  2578. focusedFinish: this.gamePresentation.map.focusedFinish,
  2579. completedFinish: this.gamePresentation.map.completedFinish,
  2580. revealFullCourse: this.gamePresentation.map.revealFullCourse,
  2581. activeLegIndices: this.gamePresentation.map.activeLegIndices,
  2582. completedLegIndices: this.gamePresentation.map.completedLegIndices,
  2583. completedControlSequences: this.gamePresentation.map.completedControlSequences,
  2584. skippedControlIds: this.gamePresentation.map.skippedControlIds,
  2585. skippedControlSequences: this.gamePresentation.map.skippedControlSequences,
  2586. osmReferenceEnabled: this.state.osmReferenceEnabled,
  2587. overlayOpacity: MAP_OVERLAY_OPACITY,
  2588. }
  2589. }
  2590. syncRenderer(): void {
  2591. if (!this.mounted || !this.state.stageWidth || !this.state.stageHeight) {
  2592. return
  2593. }
  2594. this.renderer.updateScene(this.buildScene())
  2595. }
  2596. getCameraState(rotationDeg = this.state.rotationDeg): CameraState {
  2597. return {
  2598. centerWorldX: this.state.centerTileX + 0.5,
  2599. centerWorldY: this.state.centerTileY + 0.5,
  2600. viewportWidth: this.state.stageWidth,
  2601. viewportHeight: this.state.stageHeight,
  2602. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2603. translateX: this.state.tileTranslateX,
  2604. translateY: this.state.tileTranslateY,
  2605. rotationRad: this.getRotationRad(rotationDeg),
  2606. }
  2607. }
  2608. getRotationRad(rotationDeg = this.state.rotationDeg): number {
  2609. return normalizeRotationDeg(rotationDeg) * Math.PI / 180
  2610. }
  2611. getBaseCamera(centerTileX = this.state.centerTileX, centerTileY = this.state.centerTileY, rotationDeg = this.state.rotationDeg): CameraState {
  2612. return {
  2613. centerWorldX: centerTileX + 0.5,
  2614. centerWorldY: centerTileY + 0.5,
  2615. viewportWidth: this.state.stageWidth,
  2616. viewportHeight: this.state.stageHeight,
  2617. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2618. rotationRad: this.getRotationRad(rotationDeg),
  2619. }
  2620. }
  2621. getWorldOffsetFromScreen(stageX: number, stageY: number, rotationDeg = this.state.rotationDeg): { x: number; y: number } {
  2622. const baseCamera = {
  2623. centerWorldX: 0,
  2624. centerWorldY: 0,
  2625. viewportWidth: this.state.stageWidth,
  2626. viewportHeight: this.state.stageHeight,
  2627. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2628. rotationRad: this.getRotationRad(rotationDeg),
  2629. }
  2630. return screenToWorld(baseCamera, { x: stageX, y: stageY }, false)
  2631. }
  2632. getExactCenterFromTranslate(translateX: number, translateY: number): { x: number; y: number } {
  2633. if (!this.state.stageWidth || !this.state.stageHeight) {
  2634. return {
  2635. x: this.state.centerTileX + 0.5,
  2636. y: this.state.centerTileY + 0.5,
  2637. }
  2638. }
  2639. const screenCenterX = this.state.stageWidth / 2
  2640. const screenCenterY = this.state.stageHeight / 2
  2641. return screenToWorld(this.getBaseCamera(), {
  2642. x: screenCenterX - translateX,
  2643. y: screenCenterY - translateY,
  2644. }, false)
  2645. }
  2646. resolveViewportForExactCenter(centerWorldX: number, centerWorldY: number, rotationDeg = this.state.rotationDeg): {
  2647. centerTileX: number
  2648. centerTileY: number
  2649. tileTranslateX: number
  2650. tileTranslateY: number
  2651. } {
  2652. const nextCenterTileX = Math.floor(centerWorldX)
  2653. const nextCenterTileY = Math.floor(centerWorldY)
  2654. if (!this.state.stageWidth || !this.state.stageHeight) {
  2655. return {
  2656. centerTileX: nextCenterTileX,
  2657. centerTileY: nextCenterTileY,
  2658. tileTranslateX: 0,
  2659. tileTranslateY: 0,
  2660. }
  2661. }
  2662. const roundedCamera = this.getBaseCamera(nextCenterTileX, nextCenterTileY, rotationDeg)
  2663. const projectedCenter = worldToScreen(roundedCamera, { x: centerWorldX, y: centerWorldY }, false)
  2664. return {
  2665. centerTileX: nextCenterTileX,
  2666. centerTileY: nextCenterTileY,
  2667. tileTranslateX: this.state.stageWidth / 2 - projectedCenter.x,
  2668. tileTranslateY: this.state.stageHeight / 2 - projectedCenter.y,
  2669. }
  2670. }
  2671. setPreviewState(scale: number, originX: number, originY: number): void {
  2672. this.previewScale = scale
  2673. this.previewOriginX = originX
  2674. this.previewOriginY = originY
  2675. }
  2676. resetPreviewState(): void {
  2677. this.setPreviewState(1, this.state.stageWidth / 2, this.state.stageHeight / 2)
  2678. }
  2679. resetPinchState(): void {
  2680. this.pinchStartDistance = 0
  2681. this.pinchStartScale = 1
  2682. this.pinchStartAngle = 0
  2683. this.pinchStartRotationDeg = this.state.rotationDeg
  2684. this.pinchAnchorWorldX = 0
  2685. this.pinchAnchorWorldY = 0
  2686. }
  2687. clearPreviewResetTimer(): void {
  2688. if (this.previewResetTimer) {
  2689. clearTimeout(this.previewResetTimer)
  2690. this.previewResetTimer = 0
  2691. }
  2692. }
  2693. clearInertiaTimer(): void {
  2694. if (this.inertiaTimer) {
  2695. clearTimeout(this.inertiaTimer)
  2696. this.inertiaTimer = 0
  2697. }
  2698. }
  2699. clearViewSyncTimer(): void {
  2700. if (this.viewSyncTimer) {
  2701. clearTimeout(this.viewSyncTimer)
  2702. this.viewSyncTimer = 0
  2703. }
  2704. }
  2705. clearAutoRotateTimer(): void {
  2706. if (this.autoRotateTimer) {
  2707. clearTimeout(this.autoRotateTimer)
  2708. this.autoRotateTimer = 0
  2709. }
  2710. }
  2711. pickViewPatch(patch: Partial<MapEngineViewState>): Partial<MapEngineViewState> {
  2712. const viewPatch = {} as Partial<MapEngineViewState>
  2713. for (const key of VIEW_SYNC_KEYS) {
  2714. if (Object.prototype.hasOwnProperty.call(patch, key)) {
  2715. ;(viewPatch as any)[key] = patch[key]
  2716. }
  2717. }
  2718. return viewPatch
  2719. }
  2720. flushViewPatch(): void {
  2721. if (!Object.keys(this.pendingViewPatch).length) {
  2722. return
  2723. }
  2724. const patch = this.pendingViewPatch
  2725. this.pendingViewPatch = {}
  2726. this.onData(patch)
  2727. }
  2728. getTouchDistance(touches: TouchPoint[]): number {
  2729. if (touches.length < 2) {
  2730. return 0
  2731. }
  2732. const first = touches[0]
  2733. const second = touches[1]
  2734. const deltaX = first.pageX - second.pageX
  2735. const deltaY = first.pageY - second.pageY
  2736. return Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  2737. }
  2738. getTouchAngle(touches: TouchPoint[]): number {
  2739. if (touches.length < 2) {
  2740. return 0
  2741. }
  2742. const first = touches[0]
  2743. const second = touches[1]
  2744. return Math.atan2(second.pageY - first.pageY, second.pageX - first.pageX)
  2745. }
  2746. getStagePoint(touches: TouchPoint[]): { x: number; y: number } {
  2747. if (!touches.length) {
  2748. return {
  2749. x: this.state.stageWidth / 2,
  2750. y: this.state.stageHeight / 2,
  2751. }
  2752. }
  2753. let pageX = 0
  2754. let pageY = 0
  2755. for (const touch of touches) {
  2756. pageX += touch.pageX
  2757. pageY += touch.pageY
  2758. }
  2759. return {
  2760. x: pageX / touches.length - this.state.stageLeft,
  2761. y: pageY / touches.length - this.state.stageTop,
  2762. }
  2763. }
  2764. animatePreviewToRest(): void {
  2765. this.clearPreviewResetTimer()
  2766. const startScale = this.previewScale || 1
  2767. const originX = this.previewOriginX || this.state.stageWidth / 2
  2768. const originY = this.previewOriginY || this.state.stageHeight / 2
  2769. if (Math.abs(startScale - 1) < 0.01) {
  2770. this.resetPreviewState()
  2771. this.syncRenderer()
  2772. this.compassController.start()
  2773. this.scheduleAutoRotate()
  2774. return
  2775. }
  2776. const startAt = Date.now()
  2777. const step = () => {
  2778. const progress = Math.min(1, (Date.now() - startAt) / PREVIEW_RESET_DURATION_MS)
  2779. const eased = 1 - Math.pow(1 - progress, 3)
  2780. const nextScale = startScale + (1 - startScale) * eased
  2781. this.setPreviewState(nextScale, originX, originY)
  2782. this.syncRenderer()
  2783. this.compassController.start()
  2784. if (progress >= 1) {
  2785. this.resetPreviewState()
  2786. this.syncRenderer()
  2787. this.compassController.start()
  2788. this.previewResetTimer = 0
  2789. this.scheduleAutoRotate()
  2790. return
  2791. }
  2792. this.previewResetTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2793. }
  2794. step()
  2795. }
  2796. normalizeTranslate(translateX: number, translateY: number, statusText: string): void {
  2797. if (!this.state.stageWidth) {
  2798. this.setState({
  2799. tileTranslateX: translateX,
  2800. tileTranslateY: translateY,
  2801. })
  2802. this.syncRenderer()
  2803. this.compassController.start()
  2804. return
  2805. }
  2806. const exactCenter = this.getExactCenterFromTranslate(translateX, translateY)
  2807. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y)
  2808. const centerChanged = resolvedViewport.centerTileX !== this.state.centerTileX || resolvedViewport.centerTileY !== this.state.centerTileY
  2809. if (centerChanged) {
  2810. this.commitViewport(resolvedViewport, statusText)
  2811. return
  2812. }
  2813. this.setState({
  2814. tileTranslateX: resolvedViewport.tileTranslateX,
  2815. tileTranslateY: resolvedViewport.tileTranslateY,
  2816. })
  2817. this.syncRenderer()
  2818. this.compassController.start()
  2819. }
  2820. zoomAroundPoint(zoomDelta: number, stageX: number, stageY: number, residualScale: number): void {
  2821. const nextZoom = clamp(this.state.zoom + zoomDelta, this.minZoom, this.maxZoom)
  2822. const appliedDelta = nextZoom - this.state.zoom
  2823. if (!appliedDelta) {
  2824. this.animatePreviewToRest()
  2825. return
  2826. }
  2827. if (this.gpsLockEnabled && this.currentGpsPoint) {
  2828. const nextGpsWorldPoint = lonLatToWorldTile(this.currentGpsPoint, nextZoom)
  2829. const resolvedViewport = this.resolveViewportForExactCenter(nextGpsWorldPoint.x, nextGpsWorldPoint.y)
  2830. this.commitViewport(
  2831. {
  2832. zoom: nextZoom,
  2833. ...resolvedViewport,
  2834. },
  2835. `缩放级别调整到 ${nextZoom}`,
  2836. true,
  2837. () => {
  2838. this.setPreviewState(residualScale, this.state.stageWidth / 2, this.state.stageHeight / 2)
  2839. this.syncRenderer()
  2840. this.compassController.start()
  2841. this.animatePreviewToRest()
  2842. },
  2843. )
  2844. return
  2845. }
  2846. if (!this.state.stageWidth || !this.state.stageHeight) {
  2847. this.commitViewport(
  2848. {
  2849. zoom: nextZoom,
  2850. centerTileX: appliedDelta > 0 ? this.state.centerTileX * 2 : Math.floor(this.state.centerTileX / 2),
  2851. centerTileY: appliedDelta > 0 ? this.state.centerTileY * 2 : Math.floor(this.state.centerTileY / 2),
  2852. tileTranslateX: 0,
  2853. tileTranslateY: 0,
  2854. },
  2855. `缩放级别调整到 ${nextZoom}`,
  2856. true,
  2857. () => {
  2858. this.setPreviewState(residualScale, stageX, stageY)
  2859. this.syncRenderer()
  2860. this.compassController.start()
  2861. this.animatePreviewToRest()
  2862. },
  2863. )
  2864. return
  2865. }
  2866. const camera = this.getCameraState()
  2867. const world = screenToWorld(camera, { x: stageX, y: stageY }, true)
  2868. const zoomFactor = Math.pow(2, appliedDelta)
  2869. const nextWorldX = world.x * zoomFactor
  2870. const nextWorldY = world.y * zoomFactor
  2871. const anchorOffset = this.getWorldOffsetFromScreen(stageX, stageY)
  2872. const exactCenterX = nextWorldX - anchorOffset.x
  2873. const exactCenterY = nextWorldY - anchorOffset.y
  2874. const resolvedViewport = this.resolveViewportForExactCenter(exactCenterX, exactCenterY)
  2875. this.commitViewport(
  2876. {
  2877. zoom: nextZoom,
  2878. ...resolvedViewport,
  2879. },
  2880. `缩放级别调整到 ${nextZoom}`,
  2881. true,
  2882. () => {
  2883. this.setPreviewState(residualScale, stageX, stageY)
  2884. this.syncRenderer()
  2885. this.compassController.start()
  2886. this.animatePreviewToRest()
  2887. },
  2888. )
  2889. }
  2890. startInertia(): void {
  2891. this.clearInertiaTimer()
  2892. const step = () => {
  2893. this.panVelocityX *= INERTIA_DECAY
  2894. this.panVelocityY *= INERTIA_DECAY
  2895. if (Math.abs(this.panVelocityX) < INERTIA_MIN_SPEED && Math.abs(this.panVelocityY) < INERTIA_MIN_SPEED) {
  2896. this.setState({
  2897. statusText: `惯性滑动结束 (${this.buildVersion})`,
  2898. })
  2899. this.renderer.setAnimationPaused(false)
  2900. this.inertiaTimer = 0
  2901. this.scheduleAutoRotate()
  2902. return
  2903. }
  2904. this.normalizeTranslate(
  2905. this.state.tileTranslateX + this.panVelocityX * INERTIA_FRAME_MS,
  2906. this.state.tileTranslateY + this.panVelocityY * INERTIA_FRAME_MS,
  2907. `惯性滑动中 (${this.buildVersion})`,
  2908. )
  2909. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2910. }
  2911. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2912. }
  2913. }