mapEngine.ts 120 KB

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