mapEngine.ts 127 KB

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