mapEngine.ts 116 KB

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