mapEngine.ts 133 KB

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