mapEngine.ts 147 KB

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