mapEngine.ts 115 KB

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