mapEngine.ts 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721
  1. import { getTileSizePx, screenToWorld, worldToScreen, type CameraState } from '../camera/camera'
  2. import { CompassHeadingController } from '../sensor/compassHeadingController'
  3. import { HeartRateController } from '../sensor/heartRateController'
  4. import { LocationController } from '../sensor/locationController'
  5. import { WebGLMapRenderer } from '../renderer/webglMapRenderer'
  6. import { type MapRendererStats } from '../renderer/mapRenderer'
  7. import { lonLatToWorldTile, worldTileToLonLat, type LonLatPoint, type MapCalibration } from '../../utils/projection'
  8. import { type OrienteeringCourseData } from '../../utils/orienteeringCourse'
  9. import { isTileWithinBounds, type RemoteMapConfig, type TileZoomBounds } from '../../utils/remoteMapConfig'
  10. import { GameRuntime } from '../../game/core/gameRuntime'
  11. import { type GameEffect } from '../../game/core/gameResult'
  12. import { buildGameDefinitionFromCourse } from '../../game/content/courseToGameDefinition'
  13. import { FeedbackDirector } from '../../game/feedback/feedbackDirector'
  14. import { EMPTY_GAME_PRESENTATION_STATE, type GamePresentationState } from '../../game/presentation/presentationState'
  15. import { TelemetryRuntime } from '../../game/telemetry/telemetryRuntime'
  16. import { getHeartRateToneSampleBpm, type HeartRateTone } from '../../game/telemetry/telemetryConfig'
  17. const RENDER_MODE = 'Single WebGL Pipeline'
  18. const PROJECTION_MODE = 'WGS84 -> WorldTile -> Camera -> Screen'
  19. const MAP_NORTH_OFFSET_DEG = 0
  20. let MAGNETIC_DECLINATION_DEG = -6.91
  21. let MAGNETIC_DECLINATION_TEXT = '6.91掳 W'
  22. const MIN_ZOOM = 15
  23. const MAX_ZOOM = 20
  24. const DEFAULT_ZOOM = 17
  25. const DESIRED_VISIBLE_COLUMNS = 3
  26. const OVERDRAW = 1
  27. const DEFAULT_TOP_LEFT_TILE_X = 108132
  28. const DEFAULT_TOP_LEFT_TILE_Y = 51199
  29. const DEFAULT_CENTER_TILE_X = DEFAULT_TOP_LEFT_TILE_X + 1
  30. const DEFAULT_CENTER_TILE_Y = DEFAULT_TOP_LEFT_TILE_Y + 1
  31. const TILE_SOURCE = 'https://oss-mbh5.colormaprun.com/wxMap/lcx/{z}/{x}/{y}.png'
  32. const OSM_TILE_SOURCE = 'https://tiles.mymarsgo.xyz/{z}/{x}/{y}.png'
  33. const MAP_OVERLAY_OPACITY = 0.72
  34. const GPS_MAP_CALIBRATION: MapCalibration = {
  35. offsetEastMeters: 0,
  36. offsetNorthMeters: 0,
  37. rotationDeg: 0,
  38. scale: 1,
  39. }
  40. const MIN_PREVIEW_SCALE = 0.55
  41. const MAX_PREVIEW_SCALE = 1.85
  42. const INERTIA_FRAME_MS = 16
  43. const INERTIA_DECAY = 0.92
  44. const INERTIA_MIN_SPEED = 0.02
  45. const PREVIEW_RESET_DURATION_MS = 140
  46. const UI_SYNC_INTERVAL_MS = 80
  47. const ROTATE_STEP_DEG = 15
  48. const AUTO_ROTATE_FRAME_MS = 8
  49. const AUTO_ROTATE_EASE = 0.34
  50. const AUTO_ROTATE_SNAP_DEG = 0.1
  51. const AUTO_ROTATE_DEADZONE_DEG = 4
  52. const AUTO_ROTATE_MAX_STEP_DEG = 0.75
  53. const AUTO_ROTATE_HEADING_SMOOTHING = 0.32
  54. const COMPASS_NEEDLE_SMOOTHING = 0.12
  55. const GPS_TRACK_MAX_POINTS = 200
  56. const GPS_TRACK_MIN_STEP_METERS = 3
  57. const MAP_TAP_MOVE_THRESHOLD_PX = 14
  58. const MAP_TAP_DURATION_MS = 280
  59. type TouchPoint = WechatMiniprogram.TouchDetail
  60. type GestureMode = 'idle' | 'pan' | 'pinch'
  61. type RotationMode = 'manual' | 'auto'
  62. type OrientationMode = 'manual' | 'north-up' | 'heading-up'
  63. type AutoRotateSourceMode = 'sensor' | 'course' | 'fusion'
  64. type NorthReferenceMode = 'magnetic' | 'true'
  65. const DEFAULT_NORTH_REFERENCE_MODE: NorthReferenceMode = 'magnetic'
  66. export interface MapEngineStageRect {
  67. width: number
  68. height: number
  69. left: number
  70. top: number
  71. }
  72. export interface MapEngineViewState {
  73. buildVersion: string
  74. renderMode: string
  75. projectionMode: string
  76. mapReady: boolean
  77. mapReadyText: string
  78. mapName: string
  79. configStatusText: string
  80. zoom: number
  81. rotationDeg: number
  82. rotationText: string
  83. rotationMode: RotationMode
  84. rotationModeText: string
  85. rotationToggleText: string
  86. orientationMode: OrientationMode
  87. orientationModeText: string
  88. sensorHeadingText: string
  89. compassDeclinationText: string
  90. northReferenceButtonText: string
  91. autoRotateSourceText: string
  92. autoRotateCalibrationText: string
  93. northReferenceText: string
  94. compassNeedleDeg: number
  95. centerTileX: number
  96. centerTileY: number
  97. centerText: string
  98. tileSource: string
  99. visibleColumnCount: number
  100. visibleTileCount: number
  101. readyTileCount: number
  102. memoryTileCount: number
  103. diskTileCount: number
  104. memoryHitCount: number
  105. diskHitCount: number
  106. networkFetchCount: number
  107. cacheHitRateText: string
  108. tileTranslateX: number
  109. tileTranslateY: number
  110. tileSizePx: number
  111. stageWidth: number
  112. stageHeight: number
  113. stageLeft: number
  114. stageTop: number
  115. statusText: string
  116. gpsTracking: boolean
  117. gpsTrackingText: string
  118. locationSourceMode: 'real' | 'mock'
  119. locationSourceText: string
  120. mockBridgeConnected: boolean
  121. mockBridgeStatusText: string
  122. mockBridgeUrlText: string
  123. mockCoordText: string
  124. mockSpeedText: string
  125. gpsCoordText: string
  126. heartRateConnected: boolean
  127. heartRateStatusText: string
  128. heartRateDeviceText: string
  129. gameSessionStatus: 'idle' | 'running' | 'finished' | 'failed'
  130. gameModeText: string
  131. panelTimerText: string
  132. panelMileageText: string
  133. panelActionTagText: string
  134. panelDistanceTagText: string
  135. panelDistanceValueText: string
  136. panelDistanceUnitText: string
  137. panelProgressText: string
  138. panelSpeedValueText: string
  139. panelTelemetryTone: 'blue' | 'purple' | 'green' | 'yellow' | 'orange' | 'red'
  140. panelHeartRateZoneNameText: string
  141. panelHeartRateZoneRangeText: string
  142. panelHeartRateValueText: string
  143. panelHeartRateUnitText: string
  144. panelCaloriesValueText: string
  145. panelCaloriesUnitText: string
  146. panelAverageSpeedValueText: string
  147. panelAverageSpeedUnitText: string
  148. panelAccuracyValueText: string
  149. panelAccuracyUnitText: string
  150. punchButtonText: string
  151. punchButtonEnabled: boolean
  152. punchHintText: string
  153. punchFeedbackVisible: boolean
  154. punchFeedbackText: string
  155. punchFeedbackTone: 'neutral' | 'success' | 'warning'
  156. contentCardVisible: boolean
  157. contentCardTitle: string
  158. contentCardBody: string
  159. punchButtonFxClass: string
  160. punchFeedbackFxClass: string
  161. contentCardFxClass: string
  162. mapPulseVisible: boolean
  163. mapPulseLeftPx: number
  164. mapPulseTopPx: number
  165. mapPulseFxClass: string
  166. stageFxVisible: boolean
  167. stageFxClass: string
  168. osmReferenceEnabled: boolean
  169. osmReferenceText: string
  170. }
  171. export interface MapEngineCallbacks {
  172. onData: (patch: Partial<MapEngineViewState>) => void
  173. }
  174. const VIEW_SYNC_KEYS: Array<keyof MapEngineViewState> = [
  175. 'buildVersion',
  176. 'renderMode',
  177. 'projectionMode',
  178. 'mapReady',
  179. 'mapReadyText',
  180. 'mapName',
  181. 'configStatusText',
  182. 'zoom',
  183. 'rotationDeg',
  184. 'rotationText',
  185. 'rotationMode',
  186. 'rotationModeText',
  187. 'rotationToggleText',
  188. 'orientationMode',
  189. 'orientationModeText',
  190. 'sensorHeadingText',
  191. 'compassDeclinationText',
  192. 'northReferenceButtonText',
  193. 'autoRotateSourceText',
  194. 'autoRotateCalibrationText',
  195. 'northReferenceText',
  196. 'compassNeedleDeg',
  197. 'centerText',
  198. 'tileSource',
  199. 'visibleTileCount',
  200. 'readyTileCount',
  201. 'memoryTileCount',
  202. 'diskTileCount',
  203. 'memoryHitCount',
  204. 'diskHitCount',
  205. 'networkFetchCount',
  206. 'cacheHitRateText',
  207. 'tileSizePx',
  208. 'statusText',
  209. 'gpsTracking',
  210. 'gpsTrackingText',
  211. 'locationSourceMode',
  212. 'locationSourceText',
  213. 'mockBridgeConnected',
  214. 'mockBridgeStatusText',
  215. 'mockBridgeUrlText',
  216. 'mockCoordText',
  217. 'mockSpeedText',
  218. 'gpsCoordText',
  219. 'heartRateConnected',
  220. 'heartRateStatusText',
  221. 'heartRateDeviceText',
  222. 'gameSessionStatus',
  223. 'gameModeText',
  224. 'panelTimerText',
  225. 'panelMileageText',
  226. 'panelActionTagText',
  227. 'panelDistanceTagText',
  228. 'panelDistanceValueText',
  229. 'panelDistanceUnitText',
  230. 'panelProgressText',
  231. 'panelSpeedValueText',
  232. 'panelTelemetryTone',
  233. 'panelHeartRateZoneNameText',
  234. 'panelHeartRateZoneRangeText',
  235. 'panelHeartRateValueText',
  236. 'panelHeartRateUnitText',
  237. 'panelCaloriesValueText',
  238. 'panelCaloriesUnitText',
  239. 'panelAverageSpeedValueText',
  240. 'panelAverageSpeedUnitText',
  241. 'panelAccuracyValueText',
  242. 'panelAccuracyUnitText',
  243. 'punchButtonText',
  244. 'punchButtonEnabled',
  245. 'punchHintText',
  246. 'punchFeedbackVisible',
  247. 'punchFeedbackText',
  248. 'punchFeedbackTone',
  249. 'contentCardVisible',
  250. 'contentCardTitle',
  251. 'contentCardBody',
  252. 'punchButtonFxClass',
  253. 'punchFeedbackFxClass',
  254. 'contentCardFxClass',
  255. 'mapPulseVisible',
  256. 'mapPulseLeftPx',
  257. 'mapPulseTopPx',
  258. 'mapPulseFxClass',
  259. 'stageFxVisible',
  260. 'stageFxClass',
  261. 'osmReferenceEnabled',
  262. 'osmReferenceText',
  263. ]
  264. function buildCenterText(zoom: number, x: number, y: number): string {
  265. return `z${zoom} / x${x} / y${y}`
  266. }
  267. function clamp(value: number, min: number, max: number): number {
  268. return Math.max(min, Math.min(max, value))
  269. }
  270. function normalizeRotationDeg(rotationDeg: number): number {
  271. const normalized = rotationDeg % 360
  272. return normalized < 0 ? normalized + 360 : normalized
  273. }
  274. function normalizeAngleDeltaRad(angleDeltaRad: number): number {
  275. let normalized = angleDeltaRad
  276. while (normalized > Math.PI) {
  277. normalized -= Math.PI * 2
  278. }
  279. while (normalized < -Math.PI) {
  280. normalized += Math.PI * 2
  281. }
  282. return normalized
  283. }
  284. function normalizeAngleDeltaDeg(angleDeltaDeg: number): number {
  285. let normalized = angleDeltaDeg
  286. while (normalized > 180) {
  287. normalized -= 360
  288. }
  289. while (normalized < -180) {
  290. normalized += 360
  291. }
  292. return normalized
  293. }
  294. function interpolateAngleDeg(currentDeg: number, targetDeg: number, factor: number): number {
  295. return normalizeRotationDeg(currentDeg + normalizeAngleDeltaDeg(targetDeg - currentDeg) * factor)
  296. }
  297. function formatRotationText(rotationDeg: number): string {
  298. return `${Math.round(normalizeRotationDeg(rotationDeg))}deg`
  299. }
  300. function formatHeadingText(headingDeg: number | null): string {
  301. if (headingDeg === null) {
  302. return '--'
  303. }
  304. return `${Math.round(normalizeRotationDeg(headingDeg))}掳`
  305. }
  306. function formatOrientationModeText(mode: OrientationMode): string {
  307. if (mode === 'north-up') {
  308. return 'North Up'
  309. }
  310. if (mode === 'heading-up') {
  311. return 'Heading Up'
  312. }
  313. return 'Manual Gesture'
  314. }
  315. function formatRotationModeText(mode: OrientationMode): string {
  316. return formatOrientationModeText(mode)
  317. }
  318. function formatRotationToggleText(mode: OrientationMode): string {
  319. if (mode === 'manual') {
  320. return '切到北朝上'
  321. }
  322. if (mode === 'north-up') {
  323. return '切到朝向朝上'
  324. }
  325. return '切到手动旋转'
  326. }
  327. function formatAutoRotateSourceText(mode: AutoRotateSourceMode, hasCourseHeading: boolean): string {
  328. if (mode === 'sensor') {
  329. return 'Sensor Only'
  330. }
  331. if (mode === 'course') {
  332. return hasCourseHeading ? 'Course Only' : 'Course Pending'
  333. }
  334. return hasCourseHeading ? 'Sensor + Course' : 'Sensor Only'
  335. }
  336. function formatAutoRotateCalibrationText(pending: boolean, offsetDeg: number | null): string {
  337. if (pending) {
  338. return 'Pending'
  339. }
  340. if (offsetDeg === null) {
  341. return '--'
  342. }
  343. return `Offset ${Math.round(normalizeRotationDeg(offsetDeg))}deg`
  344. }
  345. function getTrueHeadingDeg(magneticHeadingDeg: number): number {
  346. return normalizeRotationDeg(magneticHeadingDeg + MAGNETIC_DECLINATION_DEG)
  347. }
  348. function getMagneticHeadingDeg(trueHeadingDeg: number): number {
  349. return normalizeRotationDeg(trueHeadingDeg - MAGNETIC_DECLINATION_DEG)
  350. }
  351. function getMapNorthOffsetDeg(_mode: NorthReferenceMode): number {
  352. return MAP_NORTH_OFFSET_DEG
  353. }
  354. function getCompassReferenceHeadingDeg(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  355. if (mode === 'true') {
  356. return getTrueHeadingDeg(magneticHeadingDeg)
  357. }
  358. return normalizeRotationDeg(magneticHeadingDeg)
  359. }
  360. function getMapReferenceHeadingDegFromSensor(mode: NorthReferenceMode, magneticHeadingDeg: number): number {
  361. if (mode === 'magnetic') {
  362. return normalizeRotationDeg(magneticHeadingDeg)
  363. }
  364. return getTrueHeadingDeg(magneticHeadingDeg)
  365. }
  366. function getMapReferenceHeadingDegFromCourse(mode: NorthReferenceMode, trueHeadingDeg: number): number {
  367. if (mode === 'magnetic') {
  368. return getMagneticHeadingDeg(trueHeadingDeg)
  369. }
  370. return normalizeRotationDeg(trueHeadingDeg)
  371. }
  372. function formatNorthReferenceText(mode: NorthReferenceMode): string {
  373. if (mode === 'magnetic') {
  374. return `Compass Magnetic / Heading-Up Magnetic (${MAGNETIC_DECLINATION_TEXT})`
  375. }
  376. return `Compass True / Heading-Up True (${MAGNETIC_DECLINATION_TEXT})`
  377. }
  378. function formatCompassDeclinationText(mode: NorthReferenceMode): string {
  379. if (mode === 'true') {
  380. return MAGNETIC_DECLINATION_TEXT
  381. }
  382. return ''
  383. }
  384. function formatNorthReferenceButtonText(mode: NorthReferenceMode): string {
  385. return mode === 'magnetic' ? '北参照:磁北' : '北参照:真北'
  386. }
  387. function formatNorthReferenceStatusText(mode: NorthReferenceMode): string {
  388. if (mode === 'magnetic') {
  389. return '已切到磁北模式'
  390. }
  391. return '已切到真北模式'
  392. }
  393. function getNextNorthReferenceMode(mode: NorthReferenceMode): NorthReferenceMode {
  394. return mode === 'magnetic' ? 'true' : 'magnetic'
  395. }
  396. function formatCompassNeedleDegForMode(mode: NorthReferenceMode, magneticHeadingDeg: number | null): number {
  397. if (magneticHeadingDeg === null) {
  398. return 0
  399. }
  400. const referenceHeadingDeg = mode === 'true'
  401. ? getTrueHeadingDeg(magneticHeadingDeg)
  402. : normalizeRotationDeg(magneticHeadingDeg)
  403. return normalizeRotationDeg(360 - referenceHeadingDeg)
  404. }
  405. function formatCacheHitRate(memoryHitCount: number, diskHitCount: number, networkFetchCount: number): string {
  406. const total = memoryHitCount + diskHitCount + networkFetchCount
  407. if (!total) {
  408. return '--'
  409. }
  410. const hitRate = ((memoryHitCount + diskHitCount) / total) * 100
  411. return `${Math.round(hitRate)}%`
  412. }
  413. function formatGpsCoordText(point: LonLatPoint | null, accuracyMeters: number | null): string {
  414. if (!point) {
  415. return '--'
  416. }
  417. const base = `${point.lat.toFixed(6)}, ${point.lon.toFixed(6)}`
  418. if (accuracyMeters === null || !Number.isFinite(accuracyMeters)) {
  419. return base
  420. }
  421. return `${base} / 卤${Math.round(accuracyMeters)}m`
  422. }
  423. function getApproxDistanceMeters(a: LonLatPoint, b: LonLatPoint): number {
  424. const avgLatRad = ((a.lat + b.lat) / 2) * Math.PI / 180
  425. const dx = (b.lon - a.lon) * 111320 * Math.cos(avgLatRad)
  426. const dy = (b.lat - a.lat) * 110540
  427. return Math.sqrt(dx * dx + dy * dy)
  428. }
  429. function getInitialBearingDeg(from: LonLatPoint, to: LonLatPoint): number {
  430. const fromLatRad = from.lat * Math.PI / 180
  431. const toLatRad = to.lat * Math.PI / 180
  432. const deltaLonRad = (to.lon - from.lon) * Math.PI / 180
  433. const y = Math.sin(deltaLonRad) * Math.cos(toLatRad)
  434. const x = Math.cos(fromLatRad) * Math.sin(toLatRad) - Math.sin(fromLatRad) * Math.cos(toLatRad) * Math.cos(deltaLonRad)
  435. const bearingDeg = Math.atan2(y, x) * 180 / Math.PI
  436. return normalizeRotationDeg(bearingDeg)
  437. }
  438. export class MapEngine {
  439. buildVersion: string
  440. renderer: WebGLMapRenderer
  441. compassController: CompassHeadingController
  442. locationController: LocationController
  443. heartRateController: HeartRateController
  444. feedbackDirector: FeedbackDirector
  445. onData: (patch: Partial<MapEngineViewState>) => void
  446. state: MapEngineViewState
  447. previewScale: number
  448. previewOriginX: number
  449. previewOriginY: number
  450. panLastX: number
  451. panLastY: number
  452. panLastTimestamp: number
  453. tapStartX: number
  454. tapStartY: number
  455. tapStartAt: number
  456. panVelocityX: number
  457. panVelocityY: number
  458. pinchStartDistance: number
  459. pinchStartScale: number
  460. pinchStartAngle: number
  461. pinchStartRotationDeg: number
  462. pinchAnchorWorldX: number
  463. pinchAnchorWorldY: number
  464. gestureMode: GestureMode
  465. inertiaTimer: number
  466. previewResetTimer: number
  467. viewSyncTimer: number
  468. autoRotateTimer: number
  469. pendingViewPatch: Partial<MapEngineViewState>
  470. mounted: boolean
  471. northReferenceMode: NorthReferenceMode
  472. sensorHeadingDeg: number | null
  473. smoothedSensorHeadingDeg: number | null
  474. compassDisplayHeadingDeg: number | null
  475. autoRotateHeadingDeg: number | null
  476. courseHeadingDeg: number | null
  477. targetAutoRotationDeg: number | null
  478. autoRotateSourceMode: AutoRotateSourceMode
  479. autoRotateCalibrationOffsetDeg: number | null
  480. autoRotateCalibrationPending: boolean
  481. minZoom: number
  482. maxZoom: number
  483. defaultZoom: number
  484. defaultCenterTileX: number
  485. defaultCenterTileY: number
  486. tileBoundsByZoom: Record<number, TileZoomBounds> | null
  487. currentGpsPoint: LonLatPoint | null
  488. currentGpsTrack: LonLatPoint[]
  489. currentGpsAccuracyMeters: number | null
  490. courseData: OrienteeringCourseData | null
  491. courseOverlayVisible: boolean
  492. cpRadiusMeters: number
  493. gameRuntime: GameRuntime
  494. telemetryRuntime: TelemetryRuntime
  495. gamePresentation: GamePresentationState
  496. gameMode: 'classic-sequential' | 'score-o'
  497. punchPolicy: 'enter' | 'enter-confirm'
  498. punchRadiusMeters: number
  499. autoFinishOnLastControl: boolean
  500. punchFeedbackTimer: number
  501. contentCardTimer: number
  502. mapPulseTimer: number
  503. stageFxTimer: number
  504. sessionTimerInterval: number
  505. hasGpsCenteredOnce: boolean
  506. constructor(buildVersion: string, callbacks: MapEngineCallbacks) {
  507. this.buildVersion = buildVersion
  508. this.onData = callbacks.onData
  509. this.renderer = new WebGLMapRenderer(
  510. (stats) => {
  511. this.applyStats(stats)
  512. },
  513. (message) => {
  514. this.setState({
  515. statusText: `${message} (${this.buildVersion})`,
  516. })
  517. },
  518. )
  519. this.compassController = new CompassHeadingController({
  520. onHeading: (headingDeg) => {
  521. this.handleCompassHeading(headingDeg)
  522. },
  523. onError: (message) => {
  524. this.handleCompassError(message)
  525. },
  526. })
  527. this.locationController = new LocationController({
  528. onLocation: (update) => {
  529. this.handleLocationUpdate(update.longitude, update.latitude, typeof update.accuracy === 'number' ? update.accuracy : null)
  530. },
  531. onStatus: (message) => {
  532. this.setState({
  533. gpsTracking: this.locationController.listening,
  534. gpsTrackingText: message,
  535. ...this.getLocationControllerViewPatch(),
  536. }, true)
  537. },
  538. onError: (message) => {
  539. this.setState({
  540. gpsTracking: this.locationController.listening,
  541. gpsTrackingText: message,
  542. ...this.getLocationControllerViewPatch(),
  543. statusText: `${message} (${this.buildVersion})`,
  544. }, true)
  545. },
  546. onDebugStateChange: () => {
  547. this.setState(this.getLocationControllerViewPatch(), true)
  548. },
  549. })
  550. this.heartRateController = new HeartRateController({
  551. onHeartRate: (bpm) => {
  552. this.telemetryRuntime.dispatch({
  553. type: 'heart_rate_updated',
  554. at: Date.now(),
  555. bpm,
  556. })
  557. this.syncSessionTimerText()
  558. },
  559. onStatus: (message) => {
  560. this.setState({
  561. heartRateStatusText: message,
  562. heartRateDeviceText: this.heartRateController.currentDeviceName || '--',
  563. }, true)
  564. },
  565. onError: (message) => {
  566. this.setState({
  567. heartRateConnected: false,
  568. heartRateStatusText: message,
  569. heartRateDeviceText: '--',
  570. statusText: `${message} (${this.buildVersion})`,
  571. }, true)
  572. },
  573. onConnectionChange: (connected, deviceName) => {
  574. this.setState({
  575. heartRateConnected: connected,
  576. heartRateDeviceText: deviceName || '--',
  577. heartRateStatusText: connected ? '心率带已连接' : '心率带未连接',
  578. }, true)
  579. },
  580. })
  581. this.feedbackDirector = new FeedbackDirector({
  582. showPunchFeedback: (text, tone, motionClass) => {
  583. this.showPunchFeedback(text, tone, motionClass)
  584. },
  585. showContentCard: (title, body, motionClass) => {
  586. this.showContentCard(title, body, motionClass)
  587. },
  588. setPunchButtonFxClass: (className) => {
  589. this.setPunchButtonFxClass(className)
  590. },
  591. showMapPulse: (controlId, motionClass) => {
  592. this.showMapPulse(controlId, motionClass)
  593. },
  594. showStageFx: (className) => {
  595. this.showStageFx(className)
  596. },
  597. stopLocationTracking: () => {
  598. if (this.locationController.listening) {
  599. this.locationController.stop()
  600. }
  601. },
  602. })
  603. this.minZoom = MIN_ZOOM
  604. this.maxZoom = MAX_ZOOM
  605. this.defaultZoom = DEFAULT_ZOOM
  606. this.defaultCenterTileX = DEFAULT_CENTER_TILE_X
  607. this.defaultCenterTileY = DEFAULT_CENTER_TILE_Y
  608. this.tileBoundsByZoom = null
  609. this.currentGpsPoint = null
  610. this.currentGpsTrack = []
  611. this.currentGpsAccuracyMeters = null
  612. this.courseData = null
  613. this.courseOverlayVisible = false
  614. this.cpRadiusMeters = 5
  615. this.gameRuntime = new GameRuntime()
  616. this.telemetryRuntime = new TelemetryRuntime()
  617. this.telemetryRuntime.configure()
  618. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  619. this.gameMode = 'classic-sequential'
  620. this.punchPolicy = 'enter-confirm'
  621. this.punchRadiusMeters = 5
  622. this.autoFinishOnLastControl = true
  623. this.punchFeedbackTimer = 0
  624. this.contentCardTimer = 0
  625. this.mapPulseTimer = 0
  626. this.stageFxTimer = 0
  627. this.sessionTimerInterval = 0
  628. this.hasGpsCenteredOnce = false
  629. this.state = {
  630. buildVersion: this.buildVersion,
  631. renderMode: RENDER_MODE,
  632. projectionMode: PROJECTION_MODE,
  633. mapReady: false,
  634. mapReadyText: 'BOOTING',
  635. mapName: 'LCX 测试地图',
  636. configStatusText: '远程配置待加载',
  637. zoom: DEFAULT_ZOOM,
  638. rotationDeg: 0,
  639. rotationText: formatRotationText(0),
  640. rotationMode: 'manual',
  641. rotationModeText: formatRotationModeText('manual'),
  642. rotationToggleText: formatRotationToggleText('manual'),
  643. orientationMode: 'manual',
  644. orientationModeText: formatOrientationModeText('manual'),
  645. sensorHeadingText: '--',
  646. compassDeclinationText: formatCompassDeclinationText(DEFAULT_NORTH_REFERENCE_MODE),
  647. northReferenceButtonText: formatNorthReferenceButtonText(DEFAULT_NORTH_REFERENCE_MODE),
  648. autoRotateSourceText: formatAutoRotateSourceText('sensor', false),
  649. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)),
  650. northReferenceText: formatNorthReferenceText(DEFAULT_NORTH_REFERENCE_MODE),
  651. compassNeedleDeg: 0,
  652. centerTileX: DEFAULT_CENTER_TILE_X,
  653. centerTileY: DEFAULT_CENTER_TILE_Y,
  654. centerText: buildCenterText(DEFAULT_ZOOM, DEFAULT_CENTER_TILE_X, DEFAULT_CENTER_TILE_Y),
  655. tileSource: TILE_SOURCE,
  656. visibleColumnCount: DESIRED_VISIBLE_COLUMNS,
  657. visibleTileCount: 0,
  658. readyTileCount: 0,
  659. memoryTileCount: 0,
  660. diskTileCount: 0,
  661. memoryHitCount: 0,
  662. diskHitCount: 0,
  663. networkFetchCount: 0,
  664. cacheHitRateText: '--',
  665. tileTranslateX: 0,
  666. tileTranslateY: 0,
  667. tileSizePx: 0,
  668. stageWidth: 0,
  669. stageHeight: 0,
  670. stageLeft: 0,
  671. stageTop: 0,
  672. statusText: `单 WebGL 管线已就绪,等待传感器接入 (${this.buildVersion})`,
  673. gpsTracking: false,
  674. gpsTrackingText: '持续定位待启动',
  675. locationSourceMode: 'real',
  676. locationSourceText: '真实定位',
  677. mockBridgeConnected: false,
  678. mockBridgeStatusText: '未连接',
  679. mockBridgeUrlText: 'wss://gs.gotomars.xyz/mock-gps',
  680. mockCoordText: '--',
  681. mockSpeedText: '--',
  682. gpsCoordText: '--',
  683. heartRateConnected: false,
  684. heartRateStatusText: '心率带未连接',
  685. heartRateDeviceText: '--',
  686. panelTimerText: '00:00:00',
  687. panelMileageText: '0m',
  688. panelActionTagText: '目标',
  689. panelDistanceTagText: '点距',
  690. panelDistanceValueText: '--',
  691. panelDistanceUnitText: '',
  692. panelProgressText: '0/0',
  693. panelSpeedValueText: '0',
  694. panelTelemetryTone: 'blue',
  695. panelHeartRateZoneNameText: '激活放松',
  696. panelHeartRateZoneRangeText: '<=39%',
  697. panelHeartRateValueText: '--',
  698. panelHeartRateUnitText: '',
  699. panelCaloriesValueText: '0',
  700. panelCaloriesUnitText: 'kcal',
  701. panelAverageSpeedValueText: '0',
  702. panelAverageSpeedUnitText: 'km/h',
  703. panelAccuracyValueText: '--',
  704. panelAccuracyUnitText: '',
  705. punchButtonText: '打点',
  706. gameSessionStatus: 'idle',
  707. gameModeText: '顺序赛',
  708. punchButtonEnabled: false,
  709. punchHintText: '等待进入检查点范围',
  710. punchFeedbackVisible: false,
  711. punchFeedbackText: '',
  712. punchFeedbackTone: 'neutral',
  713. contentCardVisible: false,
  714. contentCardTitle: '',
  715. contentCardBody: '',
  716. punchButtonFxClass: '',
  717. punchFeedbackFxClass: '',
  718. contentCardFxClass: '',
  719. mapPulseVisible: false,
  720. mapPulseLeftPx: 0,
  721. mapPulseTopPx: 0,
  722. mapPulseFxClass: '',
  723. stageFxVisible: false,
  724. stageFxClass: '',
  725. osmReferenceEnabled: false,
  726. osmReferenceText: 'OSM参考:关',
  727. }
  728. this.previewScale = 1
  729. this.previewOriginX = 0
  730. this.previewOriginY = 0
  731. this.panLastX = 0
  732. this.panLastY = 0
  733. this.panLastTimestamp = 0
  734. this.tapStartX = 0
  735. this.tapStartY = 0
  736. this.tapStartAt = 0
  737. this.panVelocityX = 0
  738. this.panVelocityY = 0
  739. this.pinchStartDistance = 0
  740. this.pinchStartScale = 1
  741. this.pinchStartAngle = 0
  742. this.pinchStartRotationDeg = 0
  743. this.pinchAnchorWorldX = 0
  744. this.pinchAnchorWorldY = 0
  745. this.gestureMode = 'idle'
  746. this.inertiaTimer = 0
  747. this.previewResetTimer = 0
  748. this.viewSyncTimer = 0
  749. this.autoRotateTimer = 0
  750. this.pendingViewPatch = {}
  751. this.mounted = false
  752. this.northReferenceMode = DEFAULT_NORTH_REFERENCE_MODE
  753. this.sensorHeadingDeg = null
  754. this.smoothedSensorHeadingDeg = null
  755. this.compassDisplayHeadingDeg = null
  756. this.autoRotateHeadingDeg = null
  757. this.courseHeadingDeg = null
  758. this.targetAutoRotationDeg = null
  759. this.autoRotateSourceMode = 'sensor'
  760. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(DEFAULT_NORTH_REFERENCE_MODE)
  761. this.autoRotateCalibrationPending = false
  762. }
  763. getInitialData(): MapEngineViewState {
  764. return { ...this.state }
  765. }
  766. destroy(): void {
  767. this.clearInertiaTimer()
  768. this.clearPreviewResetTimer()
  769. this.clearViewSyncTimer()
  770. this.clearAutoRotateTimer()
  771. this.clearPunchFeedbackTimer()
  772. this.clearContentCardTimer()
  773. this.clearMapPulseTimer()
  774. this.clearStageFxTimer()
  775. this.clearSessionTimerInterval()
  776. this.compassController.destroy()
  777. this.locationController.destroy()
  778. this.heartRateController.destroy()
  779. this.feedbackDirector.destroy()
  780. this.renderer.destroy()
  781. this.mounted = false
  782. }
  783. clearGameRuntime(): void {
  784. this.gameRuntime.clear()
  785. this.telemetryRuntime.reset()
  786. this.gamePresentation = EMPTY_GAME_PRESENTATION_STATE
  787. this.courseOverlayVisible = !!this.courseData
  788. this.clearSessionTimerInterval()
  789. this.setCourseHeading(null)
  790. }
  791. clearFinishedTestOverlay(): void {
  792. this.currentGpsPoint = null
  793. this.currentGpsTrack = []
  794. this.currentGpsAccuracyMeters = null
  795. this.courseOverlayVisible = false
  796. this.setCourseHeading(null)
  797. }
  798. handleClearMapTestArtifacts(): void {
  799. this.clearFinishedTestOverlay()
  800. this.setState({
  801. gpsTracking: false,
  802. gpsTrackingText: '测试痕迹已清空',
  803. gpsCoordText: '--',
  804. statusText: `已清空地图点位与轨迹 (${this.buildVersion})`,
  805. }, true)
  806. this.syncRenderer()
  807. }
  808. getHudTargetControlId(): string | null {
  809. return this.gamePresentation.hud.hudTargetControlId
  810. }
  811. getLocationControllerViewPatch(): Partial<MapEngineViewState> {
  812. const debugState = this.locationController.getDebugState()
  813. return {
  814. gpsTracking: debugState.listening,
  815. locationSourceMode: debugState.sourceMode,
  816. locationSourceText: debugState.sourceModeText,
  817. mockBridgeConnected: debugState.mockBridgeConnected,
  818. mockBridgeStatusText: debugState.mockBridgeStatusText,
  819. mockBridgeUrlText: debugState.mockBridgeUrlText,
  820. mockCoordText: debugState.mockCoordText,
  821. mockSpeedText: debugState.mockSpeedText,
  822. }
  823. }
  824. getGameModeText(): string {
  825. return this.gameMode === 'score-o' ? '积分赛' : '顺序赛'
  826. }
  827. loadGameDefinitionFromCourse(): GameEffect[] {
  828. if (!this.courseData) {
  829. this.clearGameRuntime()
  830. return []
  831. }
  832. const definition = buildGameDefinitionFromCourse(
  833. this.courseData,
  834. this.cpRadiusMeters,
  835. this.gameMode,
  836. this.autoFinishOnLastControl,
  837. this.punchPolicy,
  838. this.punchRadiusMeters,
  839. )
  840. const result = this.gameRuntime.loadDefinition(definition)
  841. this.telemetryRuntime.loadDefinition(definition)
  842. this.gamePresentation = result.presentation
  843. this.courseOverlayVisible = true
  844. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, result.nextState, this.getHudTargetControlId())
  845. this.refreshCourseHeadingFromPresentation()
  846. this.updateSessionTimerLoop()
  847. this.setState({
  848. gameModeText: this.getGameModeText(),
  849. })
  850. return result.effects
  851. }
  852. refreshCourseHeadingFromPresentation(): void {
  853. if (!this.courseData || !this.gamePresentation.map.activeLegIndices.length) {
  854. this.setCourseHeading(null)
  855. return
  856. }
  857. const activeLegIndex = this.gamePresentation.map.activeLegIndices[0]
  858. const activeLeg = this.courseData.layers.legs[activeLegIndex]
  859. if (!activeLeg) {
  860. this.setCourseHeading(null)
  861. return
  862. }
  863. this.setCourseHeading(getInitialBearingDeg(activeLeg.fromPoint, activeLeg.toPoint))
  864. }
  865. resolveGameStatusText(effects: GameEffect[]): string | null {
  866. const lastEffect = effects.length ? effects[effects.length - 1] : null
  867. if (!lastEffect) {
  868. return null
  869. }
  870. if (lastEffect.type === 'control_completed') {
  871. const sequenceText = typeof lastEffect.sequence === 'number' ? String(lastEffect.sequence) : lastEffect.controlId
  872. return `宸插畬鎴愭鏌ョ偣 ${sequenceText} (${this.buildVersion})`
  873. }
  874. if (lastEffect.type === 'session_finished') {
  875. return `璺嚎宸插畬鎴?(${this.buildVersion})`
  876. }
  877. if (lastEffect.type === 'session_started') {
  878. return `椤哄簭鎵撶偣宸插紑濮?(${this.buildVersion})`
  879. }
  880. return null
  881. }
  882. getGameViewPatch(statusText?: string | null): Partial<MapEngineViewState> {
  883. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  884. const patch: Partial<MapEngineViewState> = {
  885. gameSessionStatus: this.gameRuntime.state ? this.gameRuntime.state.status : 'idle',
  886. gameModeText: this.getGameModeText(),
  887. panelTimerText: telemetryPresentation.timerText,
  888. panelMileageText: telemetryPresentation.mileageText,
  889. panelActionTagText: this.gamePresentation.hud.actionTagText,
  890. panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
  891. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  892. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  893. panelSpeedValueText: telemetryPresentation.speedText,
  894. panelTelemetryTone: telemetryPresentation.heartRateTone,
  895. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  896. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  897. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  898. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  899. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  900. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  901. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  902. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  903. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  904. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  905. panelProgressText: this.gamePresentation.hud.progressText,
  906. punchButtonText: this.gamePresentation.hud.punchButtonText,
  907. punchButtonEnabled: this.gamePresentation.hud.punchButtonEnabled,
  908. punchHintText: this.gamePresentation.hud.punchHintText,
  909. }
  910. if (statusText) {
  911. patch.statusText = statusText
  912. }
  913. return patch
  914. }
  915. clearPunchFeedbackTimer(): void {
  916. if (this.punchFeedbackTimer) {
  917. clearTimeout(this.punchFeedbackTimer)
  918. this.punchFeedbackTimer = 0
  919. }
  920. }
  921. clearContentCardTimer(): void {
  922. if (this.contentCardTimer) {
  923. clearTimeout(this.contentCardTimer)
  924. this.contentCardTimer = 0
  925. }
  926. }
  927. clearMapPulseTimer(): void {
  928. if (this.mapPulseTimer) {
  929. clearTimeout(this.mapPulseTimer)
  930. this.mapPulseTimer = 0
  931. }
  932. }
  933. clearStageFxTimer(): void {
  934. if (this.stageFxTimer) {
  935. clearTimeout(this.stageFxTimer)
  936. this.stageFxTimer = 0
  937. }
  938. }
  939. clearSessionTimerInterval(): void {
  940. if (this.sessionTimerInterval) {
  941. clearInterval(this.sessionTimerInterval)
  942. this.sessionTimerInterval = 0
  943. }
  944. }
  945. syncSessionTimerText(): void {
  946. const telemetryPresentation = this.telemetryRuntime.getPresentation()
  947. this.setState({
  948. panelTimerText: telemetryPresentation.timerText,
  949. panelMileageText: telemetryPresentation.mileageText,
  950. panelActionTagText: this.gamePresentation.hud.actionTagText,
  951. panelDistanceTagText: this.gamePresentation.hud.distanceTagText,
  952. panelDistanceValueText: telemetryPresentation.distanceToTargetValueText,
  953. panelDistanceUnitText: telemetryPresentation.distanceToTargetUnitText,
  954. panelSpeedValueText: telemetryPresentation.speedText,
  955. panelTelemetryTone: telemetryPresentation.heartRateTone,
  956. panelHeartRateZoneNameText: telemetryPresentation.heartRateZoneNameText,
  957. panelHeartRateZoneRangeText: telemetryPresentation.heartRateZoneRangeText,
  958. panelHeartRateValueText: telemetryPresentation.heartRateValueText,
  959. panelHeartRateUnitText: telemetryPresentation.heartRateUnitText,
  960. panelCaloriesValueText: telemetryPresentation.caloriesValueText,
  961. panelCaloriesUnitText: telemetryPresentation.caloriesUnitText,
  962. panelAverageSpeedValueText: telemetryPresentation.averageSpeedValueText,
  963. panelAverageSpeedUnitText: telemetryPresentation.averageSpeedUnitText,
  964. panelAccuracyValueText: telemetryPresentation.accuracyValueText,
  965. panelAccuracyUnitText: telemetryPresentation.accuracyUnitText,
  966. }, true)
  967. }
  968. updateSessionTimerLoop(): void {
  969. const gameState = this.gameRuntime.state
  970. const shouldRun = !!gameState && gameState.status === 'running' && gameState.endedAt === null
  971. this.syncSessionTimerText()
  972. if (!shouldRun) {
  973. this.clearSessionTimerInterval()
  974. return
  975. }
  976. if (this.sessionTimerInterval) {
  977. return
  978. }
  979. this.sessionTimerInterval = setInterval(() => {
  980. this.syncSessionTimerText()
  981. }, 1000) as unknown as number
  982. }
  983. getControlScreenPoint(controlId: string): { x: number; y: number } | null {
  984. if (!this.gameRuntime.definition || !this.state.stageWidth || !this.state.stageHeight) {
  985. return null
  986. }
  987. const control = this.gameRuntime.definition.controls.find((item) => item.id === controlId)
  988. if (!control) {
  989. return null
  990. }
  991. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  992. const screenPoint = worldToScreen({
  993. centerWorldX: exactCenter.x,
  994. centerWorldY: exactCenter.y,
  995. viewportWidth: this.state.stageWidth,
  996. viewportHeight: this.state.stageHeight,
  997. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  998. rotationRad: this.getRotationRad(this.state.rotationDeg),
  999. }, lonLatToWorldTile(control.point, this.state.zoom), false)
  1000. if (screenPoint.x < -80 || screenPoint.x > this.state.stageWidth + 80 || screenPoint.y < -80 || screenPoint.y > this.state.stageHeight + 80) {
  1001. return null
  1002. }
  1003. return screenPoint
  1004. }
  1005. setPunchButtonFxClass(className: string): void {
  1006. this.setState({
  1007. punchButtonFxClass: className,
  1008. }, true)
  1009. }
  1010. showMapPulse(controlId: string, motionClass = ''): void {
  1011. const screenPoint = this.getControlScreenPoint(controlId)
  1012. if (!screenPoint) {
  1013. return
  1014. }
  1015. this.clearMapPulseTimer()
  1016. this.setState({
  1017. mapPulseVisible: true,
  1018. mapPulseLeftPx: screenPoint.x,
  1019. mapPulseTopPx: screenPoint.y,
  1020. mapPulseFxClass: motionClass,
  1021. }, true)
  1022. this.mapPulseTimer = setTimeout(() => {
  1023. this.mapPulseTimer = 0
  1024. this.setState({
  1025. mapPulseVisible: false,
  1026. mapPulseFxClass: '',
  1027. }, true)
  1028. }, 820) as unknown as number
  1029. }
  1030. showStageFx(className: string): void {
  1031. if (!className) {
  1032. return
  1033. }
  1034. this.clearStageFxTimer()
  1035. this.setState({
  1036. stageFxVisible: true,
  1037. stageFxClass: className,
  1038. }, true)
  1039. this.stageFxTimer = setTimeout(() => {
  1040. this.stageFxTimer = 0
  1041. this.setState({
  1042. stageFxVisible: false,
  1043. stageFxClass: '',
  1044. }, true)
  1045. }, 760) as unknown as number
  1046. }
  1047. showPunchFeedback(text: string, tone: 'neutral' | 'success' | 'warning', motionClass = ''): void {
  1048. this.clearPunchFeedbackTimer()
  1049. this.setState({
  1050. punchFeedbackVisible: true,
  1051. punchFeedbackText: text,
  1052. punchFeedbackTone: tone,
  1053. punchFeedbackFxClass: motionClass,
  1054. }, true)
  1055. this.punchFeedbackTimer = setTimeout(() => {
  1056. this.punchFeedbackTimer = 0
  1057. this.setState({
  1058. punchFeedbackVisible: false,
  1059. punchFeedbackFxClass: '',
  1060. }, true)
  1061. }, 1400) as unknown as number
  1062. }
  1063. showContentCard(title: string, body: string, motionClass = ''): void {
  1064. this.clearContentCardTimer()
  1065. this.setState({
  1066. contentCardVisible: true,
  1067. contentCardTitle: title,
  1068. contentCardBody: body,
  1069. contentCardFxClass: motionClass,
  1070. }, true)
  1071. this.contentCardTimer = setTimeout(() => {
  1072. this.contentCardTimer = 0
  1073. this.setState({
  1074. contentCardVisible: false,
  1075. contentCardFxClass: '',
  1076. }, true)
  1077. }, 2600) as unknown as number
  1078. }
  1079. closeContentCard(): void {
  1080. this.clearContentCardTimer()
  1081. this.setState({
  1082. contentCardVisible: false,
  1083. contentCardFxClass: '',
  1084. }, true)
  1085. }
  1086. applyGameEffects(effects: GameEffect[]): string | null {
  1087. this.feedbackDirector.handleEffects(effects)
  1088. if (effects.some((effect) => effect.type === 'session_finished')) {
  1089. this.setState({
  1090. gpsTracking: false,
  1091. gpsTrackingText: '测试结束,定位已停止',
  1092. }, true)
  1093. }
  1094. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, this.gameRuntime.state, this.getHudTargetControlId())
  1095. this.updateSessionTimerLoop()
  1096. return this.resolveGameStatusText(effects)
  1097. }
  1098. handleStartGame(): void {
  1099. if (!this.gameRuntime.definition || !this.gameRuntime.state) {
  1100. this.setState({
  1101. statusText: `当前还没有可开始的路线 (${this.buildVersion})`,
  1102. }, true)
  1103. return
  1104. }
  1105. if (this.gameRuntime.state.status !== 'idle') {
  1106. return
  1107. }
  1108. if (!this.locationController.listening) {
  1109. this.locationController.start()
  1110. }
  1111. const startedAt = Date.now()
  1112. let gameResult = this.gameRuntime.startSession(startedAt)
  1113. if (this.currentGpsPoint) {
  1114. gameResult = this.gameRuntime.dispatch({
  1115. type: 'gps_updated',
  1116. at: Date.now(),
  1117. lon: this.currentGpsPoint.lon,
  1118. lat: this.currentGpsPoint.lat,
  1119. accuracyMeters: this.currentGpsAccuracyMeters,
  1120. })
  1121. }
  1122. this.gamePresentation = this.gameRuntime.getPresentation()
  1123. this.courseOverlayVisible = true
  1124. this.refreshCourseHeadingFromPresentation()
  1125. const defaultStatusText = this.currentGpsPoint
  1126. ? `顺序打点已开始 (${this.buildVersion})`
  1127. : `顺序打点已开始,GPS定位启动中 (${this.buildVersion})`
  1128. const gameStatusText = this.applyGameEffects(gameResult.effects) || defaultStatusText
  1129. this.setState({
  1130. ...this.getGameViewPatch(gameStatusText),
  1131. }, true)
  1132. this.syncRenderer()
  1133. }
  1134. handlePunchAction(): void {
  1135. const gameResult = this.gameRuntime.dispatch({
  1136. type: 'punch_requested',
  1137. at: Date.now(),
  1138. })
  1139. this.gamePresentation = gameResult.presentation
  1140. this.refreshCourseHeadingFromPresentation()
  1141. const gameStatusText = this.applyGameEffects(gameResult.effects)
  1142. this.setState({
  1143. ...this.getGameViewPatch(gameStatusText),
  1144. }, true)
  1145. this.syncRenderer()
  1146. }
  1147. handleLocationUpdate(longitude: number, latitude: number, accuracyMeters: number | null): void {
  1148. const nextPoint: LonLatPoint = { lon: longitude, lat: latitude }
  1149. const lastTrackPoint = this.currentGpsTrack.length ? this.currentGpsTrack[this.currentGpsTrack.length - 1] : null
  1150. if (!lastTrackPoint || getApproxDistanceMeters(lastTrackPoint, nextPoint) >= GPS_TRACK_MIN_STEP_METERS) {
  1151. this.currentGpsTrack = [...this.currentGpsTrack, nextPoint].slice(-GPS_TRACK_MAX_POINTS)
  1152. }
  1153. this.currentGpsPoint = nextPoint
  1154. this.currentGpsAccuracyMeters = accuracyMeters
  1155. const gpsWorldPoint = lonLatToWorldTile(nextPoint, this.state.zoom)
  1156. const gpsTileX = Math.floor(gpsWorldPoint.x)
  1157. const gpsTileY = Math.floor(gpsWorldPoint.y)
  1158. const gpsInsideMap = isTileWithinBounds(this.tileBoundsByZoom, this.state.zoom, gpsTileX, gpsTileY)
  1159. let gameStatusText: string | null = null
  1160. if (this.courseData) {
  1161. const eventAt = Date.now()
  1162. const gameResult = this.gameRuntime.dispatch({
  1163. type: 'gps_updated',
  1164. at: eventAt,
  1165. lon: longitude,
  1166. lat: latitude,
  1167. accuracyMeters,
  1168. })
  1169. this.telemetryRuntime.dispatch({
  1170. type: 'gps_updated',
  1171. at: eventAt,
  1172. lon: longitude,
  1173. lat: latitude,
  1174. accuracyMeters,
  1175. })
  1176. this.gamePresentation = gameResult.presentation
  1177. this.refreshCourseHeadingFromPresentation()
  1178. gameStatusText = this.applyGameEffects(gameResult.effects)
  1179. }
  1180. if (gpsInsideMap && !this.hasGpsCenteredOnce) {
  1181. this.hasGpsCenteredOnce = true
  1182. this.commitViewport({
  1183. centerTileX: gpsWorldPoint.x,
  1184. centerTileY: gpsWorldPoint.y,
  1185. tileTranslateX: 0,
  1186. tileTranslateY: 0,
  1187. gpsTracking: true,
  1188. gpsTrackingText: '持续定位进行中',
  1189. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1190. ...this.getGameViewPatch(),
  1191. }, gameStatusText || `GPS定位成功,已定位到当前位置 (${this.buildVersion})`, true)
  1192. return
  1193. }
  1194. this.setState({
  1195. gpsTracking: true,
  1196. gpsTrackingText: gpsInsideMap ? '持续定位进行中' : 'GPS不在当前地图范围内',
  1197. gpsCoordText: formatGpsCoordText(nextPoint, accuracyMeters),
  1198. ...this.getGameViewPatch(gameStatusText || (gpsInsideMap ? `GPS位置已更新 (${this.buildVersion})` : `GPS位置超出当前地图范围 (${this.buildVersion})`)),
  1199. }, true)
  1200. this.syncRenderer()
  1201. }
  1202. handleToggleOsmReference(): void {
  1203. const nextEnabled = !this.state.osmReferenceEnabled
  1204. this.setState({
  1205. osmReferenceEnabled: nextEnabled,
  1206. osmReferenceText: nextEnabled ? 'OSM参考:开' : 'OSM参考:关',
  1207. statusText: nextEnabled ? `OSM参考底图已开启 (${this.buildVersion})` : `OSM参考底图已关闭 (${this.buildVersion})`,
  1208. }, true)
  1209. this.syncRenderer()
  1210. }
  1211. handleToggleGpsTracking(): void {
  1212. if (this.locationController.listening) {
  1213. this.locationController.stop()
  1214. return
  1215. }
  1216. this.locationController.start()
  1217. }
  1218. handleSetRealLocationMode(): void {
  1219. this.locationController.setSourceMode('real')
  1220. }
  1221. handleSetMockLocationMode(): void {
  1222. this.locationController.setSourceMode('mock')
  1223. }
  1224. handleConnectMockLocationBridge(): void {
  1225. this.locationController.connectMockBridge()
  1226. }
  1227. handleDisconnectMockLocationBridge(): void {
  1228. this.locationController.disconnectMockBridge()
  1229. }
  1230. handleSetMockLocationBridgeUrl(url: string): void {
  1231. this.locationController.setMockBridgeUrl(url)
  1232. }
  1233. handleSetGameMode(nextMode: 'classic-sequential' | 'score-o'): void {
  1234. if (this.gameMode === nextMode) {
  1235. return
  1236. }
  1237. this.gameMode = nextMode
  1238. const effects = this.loadGameDefinitionFromCourse()
  1239. const modeText = this.getGameModeText()
  1240. const statusText = this.applyGameEffects(effects) || `已切换到${modeText} (${this.buildVersion})`
  1241. this.setState({
  1242. ...this.getGameViewPatch(statusText),
  1243. gameModeText: modeText,
  1244. }, true)
  1245. this.syncRenderer()
  1246. }
  1247. handleConnectHeartRate(): void {
  1248. this.heartRateController.startScanAndConnect()
  1249. }
  1250. handleDisconnectHeartRate(): void {
  1251. this.heartRateController.disconnect()
  1252. }
  1253. handleDebugHeartRateTone(tone: HeartRateTone): void {
  1254. const sampleBpm = getHeartRateToneSampleBpm(tone, this.telemetryRuntime.config)
  1255. this.telemetryRuntime.dispatch({
  1256. type: 'heart_rate_updated',
  1257. at: Date.now(),
  1258. bpm: sampleBpm,
  1259. })
  1260. this.setState({
  1261. heartRateStatusText: `调试心率: ${sampleBpm} bpm / ${tone.toUpperCase()}`,
  1262. }, true)
  1263. this.syncSessionTimerText()
  1264. }
  1265. handleClearDebugHeartRate(): void {
  1266. this.telemetryRuntime.dispatch({
  1267. type: 'heart_rate_updated',
  1268. at: Date.now(),
  1269. bpm: null,
  1270. })
  1271. this.setState({
  1272. heartRateStatusText: this.heartRateController.connected ? '心率带已连接' : '心率带未连接',
  1273. }, true)
  1274. this.syncSessionTimerText()
  1275. }
  1276. setStage(rect: MapEngineStageRect): void {
  1277. this.previewScale = 1
  1278. this.previewOriginX = rect.width / 2
  1279. this.previewOriginY = rect.height / 2
  1280. this.commitViewport(
  1281. {
  1282. stageWidth: rect.width,
  1283. stageHeight: rect.height,
  1284. stageLeft: rect.left,
  1285. stageTop: rect.top,
  1286. },
  1287. `地图视口已与 WebGL 引擎对齐 (${this.buildVersion})`,
  1288. true,
  1289. )
  1290. }
  1291. attachCanvas(canvasNode: any, width: number, height: number, dpr: number, labelCanvasNode?: any): void {
  1292. this.renderer.attachCanvas(canvasNode, width, height, dpr, labelCanvasNode)
  1293. this.mounted = true
  1294. this.state.mapReady = true
  1295. this.state.mapReadyText = 'READY'
  1296. this.onData({
  1297. mapReady: true,
  1298. mapReadyText: 'READY',
  1299. statusText: `单 WebGL 管线已完成,可切换手动或自动朝向 (${this.buildVersion})`,
  1300. })
  1301. this.syncRenderer()
  1302. this.compassController.start()
  1303. }
  1304. applyRemoteMapConfig(config: RemoteMapConfig): void {
  1305. MAGNETIC_DECLINATION_DEG = config.magneticDeclinationDeg
  1306. MAGNETIC_DECLINATION_TEXT = config.magneticDeclinationText
  1307. this.minZoom = config.minZoom
  1308. this.maxZoom = config.maxZoom
  1309. this.defaultZoom = config.defaultZoom
  1310. this.defaultCenterTileX = config.initialCenterTileX
  1311. this.defaultCenterTileY = config.initialCenterTileY
  1312. this.tileBoundsByZoom = config.tileBoundsByZoom
  1313. this.courseData = config.course
  1314. this.cpRadiusMeters = config.cpRadiusMeters
  1315. this.gameMode = config.gameMode
  1316. this.punchPolicy = config.punchPolicy
  1317. this.punchRadiusMeters = config.punchRadiusMeters
  1318. this.autoFinishOnLastControl = config.autoFinishOnLastControl
  1319. this.telemetryRuntime.configure(config.telemetryConfig)
  1320. this.feedbackDirector.configure({
  1321. audioConfig: config.audioConfig,
  1322. hapticsConfig: config.hapticsConfig,
  1323. uiEffectsConfig: config.uiEffectsConfig,
  1324. })
  1325. const gameEffects = this.loadGameDefinitionFromCourse()
  1326. const gameStatusText = this.applyGameEffects(gameEffects)
  1327. const statePatch: Partial<MapEngineViewState> = {
  1328. configStatusText: `远程配置已载入 / ${config.courseStatusText}`,
  1329. projectionMode: config.projectionModeText,
  1330. tileSource: config.tileSource,
  1331. sensorHeadingText: formatHeadingText(this.smoothedSensorHeadingDeg === null ? null : getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)),
  1332. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  1333. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  1334. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1335. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  1336. ...this.getGameViewPatch(),
  1337. }
  1338. if (!this.state.stageWidth || !this.state.stageHeight) {
  1339. this.setState({
  1340. ...statePatch,
  1341. zoom: this.defaultZoom,
  1342. centerTileX: this.defaultCenterTileX,
  1343. centerTileY: this.defaultCenterTileY,
  1344. centerText: buildCenterText(this.defaultZoom, this.defaultCenterTileX, this.defaultCenterTileY),
  1345. statusText: gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`,
  1346. }, true)
  1347. return
  1348. }
  1349. this.commitViewport({
  1350. ...statePatch,
  1351. zoom: this.defaultZoom,
  1352. centerTileX: this.defaultCenterTileX,
  1353. centerTileY: this.defaultCenterTileY,
  1354. tileTranslateX: 0,
  1355. tileTranslateY: 0,
  1356. }, gameStatusText || `路线已载入,点击开始进入游戏 (${this.buildVersion})`, true, () => {
  1357. this.resetPreviewState()
  1358. this.syncRenderer()
  1359. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1360. this.scheduleAutoRotate()
  1361. }
  1362. })
  1363. }
  1364. handleTouchStart(event: WechatMiniprogram.TouchEvent): void {
  1365. this.clearInertiaTimer()
  1366. this.clearPreviewResetTimer()
  1367. this.panVelocityX = 0
  1368. this.panVelocityY = 0
  1369. if (event.touches.length >= 2) {
  1370. const origin = this.getStagePoint(event.touches)
  1371. this.gestureMode = 'pinch'
  1372. this.pinchStartDistance = this.getTouchDistance(event.touches)
  1373. this.pinchStartScale = this.previewScale || 1
  1374. this.pinchStartAngle = this.getTouchAngle(event.touches)
  1375. this.pinchStartRotationDeg = this.state.rotationDeg
  1376. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  1377. this.pinchAnchorWorldX = anchorWorld.x
  1378. this.pinchAnchorWorldY = anchorWorld.y
  1379. this.setPreviewState(this.pinchStartScale, origin.x, origin.y)
  1380. this.syncRenderer()
  1381. this.compassController.start()
  1382. return
  1383. }
  1384. if (event.touches.length === 1) {
  1385. this.gestureMode = 'pan'
  1386. this.panLastX = event.touches[0].pageX
  1387. this.panLastY = event.touches[0].pageY
  1388. this.panLastTimestamp = event.timeStamp || Date.now()
  1389. this.tapStartX = event.touches[0].pageX
  1390. this.tapStartY = event.touches[0].pageY
  1391. this.tapStartAt = event.timeStamp || Date.now()
  1392. }
  1393. }
  1394. handleTouchMove(event: WechatMiniprogram.TouchEvent): void {
  1395. if (event.touches.length >= 2) {
  1396. const distance = this.getTouchDistance(event.touches)
  1397. const angle = this.getTouchAngle(event.touches)
  1398. const origin = this.getStagePoint(event.touches)
  1399. if (!this.pinchStartDistance) {
  1400. this.pinchStartDistance = distance
  1401. this.pinchStartScale = this.previewScale || 1
  1402. this.pinchStartAngle = angle
  1403. this.pinchStartRotationDeg = this.state.rotationDeg
  1404. const anchorWorld = screenToWorld(this.getCameraState(), origin, true)
  1405. this.pinchAnchorWorldX = anchorWorld.x
  1406. this.pinchAnchorWorldY = anchorWorld.y
  1407. }
  1408. this.gestureMode = 'pinch'
  1409. const nextRotationDeg = this.state.orientationMode === 'heading-up'
  1410. ? this.state.rotationDeg
  1411. : normalizeRotationDeg(this.pinchStartRotationDeg + normalizeAngleDeltaRad(angle - this.pinchStartAngle) * 180 / Math.PI)
  1412. const anchorOffset = this.getWorldOffsetFromScreen(origin.x, origin.y, nextRotationDeg)
  1413. const resolvedViewport = this.resolveViewportForExactCenter(
  1414. this.pinchAnchorWorldX - anchorOffset.x,
  1415. this.pinchAnchorWorldY - anchorOffset.y,
  1416. nextRotationDeg,
  1417. )
  1418. this.setPreviewState(
  1419. clamp(this.pinchStartScale * (distance / this.pinchStartDistance), MIN_PREVIEW_SCALE, MAX_PREVIEW_SCALE),
  1420. origin.x,
  1421. origin.y,
  1422. )
  1423. this.commitViewport(
  1424. {
  1425. ...resolvedViewport,
  1426. rotationDeg: nextRotationDeg,
  1427. rotationText: formatRotationText(nextRotationDeg),
  1428. },
  1429. this.state.orientationMode === 'heading-up'
  1430. ? `双指缩放中,自动朝向保持开启 (${this.buildVersion})`
  1431. : `双指缩放与旋转中 (${this.buildVersion})`,
  1432. )
  1433. return
  1434. }
  1435. if (this.gestureMode !== 'pan' || event.touches.length !== 1) {
  1436. return
  1437. }
  1438. const touch = event.touches[0]
  1439. const deltaX = touch.pageX - this.panLastX
  1440. const deltaY = touch.pageY - this.panLastY
  1441. const nextTimestamp = event.timeStamp || Date.now()
  1442. const elapsed = Math.max(nextTimestamp - this.panLastTimestamp, 16)
  1443. const instantVelocityX = deltaX / elapsed
  1444. const instantVelocityY = deltaY / elapsed
  1445. this.panVelocityX = this.panVelocityX * 0.72 + instantVelocityX * 0.28
  1446. this.panVelocityY = this.panVelocityY * 0.72 + instantVelocityY * 0.28
  1447. this.panLastX = touch.pageX
  1448. this.panLastY = touch.pageY
  1449. this.panLastTimestamp = nextTimestamp
  1450. this.normalizeTranslate(
  1451. this.state.tileTranslateX + deltaX,
  1452. this.state.tileTranslateY + deltaY,
  1453. `宸叉嫋鎷藉崟 WebGL 鍦板浘寮曟搸 (${this.buildVersion})`,
  1454. )
  1455. }
  1456. handleTouchEnd(event: WechatMiniprogram.TouchEvent): void {
  1457. const changedTouch = event.changedTouches && event.changedTouches.length ? event.changedTouches[0] : null
  1458. const endedAsTap = changedTouch
  1459. && this.gestureMode === 'pan'
  1460. && event.touches.length === 0
  1461. && Math.abs(changedTouch.pageX - this.tapStartX) <= MAP_TAP_MOVE_THRESHOLD_PX
  1462. && Math.abs(changedTouch.pageY - this.tapStartY) <= MAP_TAP_MOVE_THRESHOLD_PX
  1463. && ((event.timeStamp || Date.now()) - this.tapStartAt) <= MAP_TAP_DURATION_MS
  1464. if (this.gestureMode === 'pinch' && event.touches.length < 2) {
  1465. const gestureScale = this.previewScale || 1
  1466. const zoomDelta = Math.round(Math.log2(gestureScale))
  1467. const originX = this.previewOriginX || this.state.stageWidth / 2
  1468. const originY = this.previewOriginY || this.state.stageHeight / 2
  1469. if (zoomDelta) {
  1470. const residualScale = gestureScale / Math.pow(2, zoomDelta)
  1471. this.zoomAroundPoint(zoomDelta, originX, originY, residualScale)
  1472. } else {
  1473. this.animatePreviewToRest()
  1474. }
  1475. this.resetPinchState()
  1476. this.panVelocityX = 0
  1477. this.panVelocityY = 0
  1478. if (event.touches.length === 1) {
  1479. this.gestureMode = 'pan'
  1480. this.panLastX = event.touches[0].pageX
  1481. this.panLastY = event.touches[0].pageY
  1482. this.panLastTimestamp = event.timeStamp || Date.now()
  1483. return
  1484. }
  1485. this.gestureMode = 'idle'
  1486. this.renderer.setAnimationPaused(false)
  1487. this.scheduleAutoRotate()
  1488. return
  1489. }
  1490. if (event.touches.length === 1) {
  1491. this.gestureMode = 'pan'
  1492. this.panLastX = event.touches[0].pageX
  1493. this.panLastY = event.touches[0].pageY
  1494. this.panLastTimestamp = event.timeStamp || Date.now()
  1495. return
  1496. }
  1497. if (this.gestureMode === 'pan' && (Math.abs(this.panVelocityX) >= INERTIA_MIN_SPEED || Math.abs(this.panVelocityY) >= INERTIA_MIN_SPEED)) {
  1498. this.startInertia()
  1499. this.gestureMode = 'idle'
  1500. this.resetPinchState()
  1501. return
  1502. }
  1503. if (endedAsTap && changedTouch) {
  1504. this.handleMapTap(changedTouch.pageX - this.state.stageLeft, changedTouch.pageY - this.state.stageTop)
  1505. }
  1506. this.gestureMode = 'idle'
  1507. this.resetPinchState()
  1508. this.renderer.setAnimationPaused(false)
  1509. this.scheduleAutoRotate()
  1510. }
  1511. handleTouchCancel(): void {
  1512. this.gestureMode = 'idle'
  1513. this.resetPinchState()
  1514. this.panVelocityX = 0
  1515. this.panVelocityY = 0
  1516. this.clearInertiaTimer()
  1517. this.animatePreviewToRest()
  1518. this.renderer.setAnimationPaused(false)
  1519. this.scheduleAutoRotate()
  1520. }
  1521. handleMapTap(stageX: number, stageY: number): void {
  1522. if (!this.gameRuntime.definition || !this.gameRuntime.state || this.gameRuntime.definition.mode !== 'score-o') {
  1523. return
  1524. }
  1525. const focusedControlId = this.findFocusableControlAt(stageX, stageY)
  1526. if (focusedControlId === undefined) {
  1527. return
  1528. }
  1529. const gameResult = this.gameRuntime.dispatch({
  1530. type: 'control_focused',
  1531. at: Date.now(),
  1532. controlId: focusedControlId,
  1533. })
  1534. this.gamePresentation = gameResult.presentation
  1535. this.telemetryRuntime.syncGameState(this.gameRuntime.definition, this.gameRuntime.state, this.getHudTargetControlId())
  1536. this.setState({
  1537. ...this.getGameViewPatch(focusedControlId ? `已选择目标点 (${this.buildVersion})` : `已取消目标点选择 (${this.buildVersion})`),
  1538. }, true)
  1539. this.syncRenderer()
  1540. }
  1541. findFocusableControlAt(stageX: number, stageY: number): string | null | undefined {
  1542. if (!this.gameRuntime.definition || !this.courseData || !this.state.stageWidth || !this.state.stageHeight) {
  1543. return undefined
  1544. }
  1545. const focusableControls = this.gameRuntime.definition.controls.filter((control) => (
  1546. this.gamePresentation.map.focusableControlIds.includes(control.id)
  1547. ))
  1548. let matchedControlId: string | null | undefined
  1549. let matchedDistance = Number.POSITIVE_INFINITY
  1550. const hitRadiusPx = Math.max(28, this.getControlHitRadiusPx())
  1551. for (const control of focusableControls) {
  1552. const screenPoint = this.getControlScreenPoint(control.id)
  1553. if (!screenPoint) {
  1554. continue
  1555. }
  1556. const distancePx = Math.sqrt(
  1557. Math.pow(screenPoint.x - stageX, 2)
  1558. + Math.pow(screenPoint.y - stageY, 2),
  1559. )
  1560. if (distancePx <= hitRadiusPx && distancePx < matchedDistance) {
  1561. matchedDistance = distancePx
  1562. matchedControlId = control.id
  1563. }
  1564. }
  1565. if (matchedControlId === undefined) {
  1566. return undefined
  1567. }
  1568. return matchedControlId === this.gamePresentation.map.focusedControlId ? null : matchedControlId
  1569. }
  1570. getControlHitRadiusPx(): number {
  1571. if (!this.state.tileSizePx) {
  1572. return 28
  1573. }
  1574. const centerLonLat = worldTileToLonLat({ x: this.state.centerTileX + 0.5, y: this.state.centerTileY + 0.5 }, this.state.zoom)
  1575. const metersPerTile = Math.cos(centerLonLat.lat * Math.PI / 180) * 40075016.686 / Math.pow(2, this.state.zoom)
  1576. if (!metersPerTile) {
  1577. return 28
  1578. }
  1579. const pixelsPerMeter = this.state.tileSizePx / metersPerTile
  1580. return Math.max(28, this.cpRadiusMeters * pixelsPerMeter * 1.6)
  1581. }
  1582. handleRecenter(): void {
  1583. this.clearInertiaTimer()
  1584. this.clearPreviewResetTimer()
  1585. this.panVelocityX = 0
  1586. this.panVelocityY = 0
  1587. this.renderer.setAnimationPaused(false)
  1588. this.commitViewport(
  1589. {
  1590. zoom: this.defaultZoom,
  1591. centerTileX: this.defaultCenterTileX,
  1592. centerTileY: this.defaultCenterTileY,
  1593. tileTranslateX: 0,
  1594. tileTranslateY: 0,
  1595. },
  1596. `已回到单 WebGL 引擎默认首屏 (${this.buildVersion})`,
  1597. true,
  1598. () => {
  1599. this.resetPreviewState()
  1600. this.syncRenderer()
  1601. this.compassController.start()
  1602. this.scheduleAutoRotate()
  1603. },
  1604. )
  1605. }
  1606. handleRotateStep(stepDeg = ROTATE_STEP_DEG): void {
  1607. if (this.state.rotationMode === 'auto') {
  1608. this.setState({
  1609. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  1610. }, true)
  1611. return
  1612. }
  1613. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1614. const nextRotationDeg = normalizeRotationDeg(this.state.rotationDeg + stepDeg)
  1615. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  1616. this.clearInertiaTimer()
  1617. this.clearPreviewResetTimer()
  1618. this.panVelocityX = 0
  1619. this.panVelocityY = 0
  1620. this.renderer.setAnimationPaused(false)
  1621. this.commitViewport(
  1622. {
  1623. ...resolvedViewport,
  1624. rotationDeg: nextRotationDeg,
  1625. rotationText: formatRotationText(nextRotationDeg),
  1626. },
  1627. `旋转角度调整到 ${formatRotationText(nextRotationDeg)} (${this.buildVersion})`,
  1628. true,
  1629. () => {
  1630. this.resetPreviewState()
  1631. this.syncRenderer()
  1632. this.compassController.start()
  1633. },
  1634. )
  1635. }
  1636. handleRotationReset(): void {
  1637. if (this.state.rotationMode === 'auto') {
  1638. this.setState({
  1639. statusText: `当前不是手动旋转模式,请先切回手动 (${this.buildVersion})`,
  1640. }, true)
  1641. return
  1642. }
  1643. const targetRotationDeg = MAP_NORTH_OFFSET_DEG
  1644. if (Math.abs(normalizeAngleDeltaDeg(this.state.rotationDeg - targetRotationDeg)) <= 0.01) {
  1645. return
  1646. }
  1647. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1648. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, targetRotationDeg)
  1649. this.clearInertiaTimer()
  1650. this.clearPreviewResetTimer()
  1651. this.panVelocityX = 0
  1652. this.panVelocityY = 0
  1653. this.renderer.setAnimationPaused(false)
  1654. this.commitViewport(
  1655. {
  1656. ...resolvedViewport,
  1657. rotationDeg: targetRotationDeg,
  1658. rotationText: formatRotationText(targetRotationDeg),
  1659. },
  1660. `旋转角度已回到真北参考 (${this.buildVersion})`,
  1661. true,
  1662. () => {
  1663. this.resetPreviewState()
  1664. this.syncRenderer()
  1665. this.compassController.start()
  1666. },
  1667. )
  1668. }
  1669. handleToggleRotationMode(): void {
  1670. if (this.state.orientationMode === 'manual') {
  1671. this.setNorthUpMode()
  1672. return
  1673. }
  1674. if (this.state.orientationMode === 'north-up') {
  1675. this.setHeadingUpMode()
  1676. return
  1677. }
  1678. this.setManualMode()
  1679. }
  1680. handleSetManualMode(): void {
  1681. this.setManualMode()
  1682. }
  1683. handleSetNorthUpMode(): void {
  1684. this.setNorthUpMode()
  1685. }
  1686. handleSetHeadingUpMode(): void {
  1687. this.setHeadingUpMode()
  1688. }
  1689. handleCycleNorthReferenceMode(): void {
  1690. this.cycleNorthReferenceMode()
  1691. }
  1692. handleAutoRotateCalibrate(): void {
  1693. if (this.state.orientationMode !== 'heading-up') {
  1694. this.setState({
  1695. statusText: `请先切到朝向朝上模式再校准 (${this.buildVersion})`,
  1696. }, true)
  1697. return
  1698. }
  1699. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  1700. this.setState({
  1701. statusText: `当前还没有传感器方向数据,暂时无法校准 (${this.buildVersion})`,
  1702. }, true)
  1703. return
  1704. }
  1705. this.setState({
  1706. statusText: `已按当前持机方向完成朝向校准 (${this.buildVersion})`,
  1707. }, true)
  1708. this.scheduleAutoRotate()
  1709. }
  1710. setManualMode(): void {
  1711. this.clearAutoRotateTimer()
  1712. this.targetAutoRotationDeg = null
  1713. this.autoRotateCalibrationPending = false
  1714. this.setState({
  1715. rotationMode: 'manual',
  1716. rotationModeText: formatRotationModeText('manual'),
  1717. rotationToggleText: formatRotationToggleText('manual'),
  1718. orientationMode: 'manual',
  1719. orientationModeText: formatOrientationModeText('manual'),
  1720. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1721. statusText: `已切回手动地图旋转 (${this.buildVersion})`,
  1722. }, true)
  1723. }
  1724. setNorthUpMode(): void {
  1725. this.clearAutoRotateTimer()
  1726. this.targetAutoRotationDeg = null
  1727. this.autoRotateCalibrationPending = false
  1728. const mapNorthOffsetDeg = MAP_NORTH_OFFSET_DEG
  1729. this.autoRotateCalibrationOffsetDeg = mapNorthOffsetDeg
  1730. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1731. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, mapNorthOffsetDeg)
  1732. this.commitViewport(
  1733. {
  1734. ...resolvedViewport,
  1735. rotationDeg: mapNorthOffsetDeg,
  1736. rotationText: formatRotationText(mapNorthOffsetDeg),
  1737. rotationMode: 'manual',
  1738. rotationModeText: formatRotationModeText('north-up'),
  1739. rotationToggleText: formatRotationToggleText('north-up'),
  1740. orientationMode: 'north-up',
  1741. orientationModeText: formatOrientationModeText('north-up'),
  1742. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, mapNorthOffsetDeg),
  1743. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1744. },
  1745. `地图已固定为真北朝上 (${this.buildVersion})`,
  1746. true,
  1747. () => {
  1748. this.resetPreviewState()
  1749. this.syncRenderer()
  1750. },
  1751. )
  1752. }
  1753. setHeadingUpMode(): void {
  1754. this.autoRotateCalibrationPending = false
  1755. this.autoRotateCalibrationOffsetDeg = getMapNorthOffsetDeg(this.northReferenceMode)
  1756. this.targetAutoRotationDeg = null
  1757. this.setState({
  1758. rotationMode: 'auto',
  1759. rotationModeText: formatRotationModeText('heading-up'),
  1760. rotationToggleText: formatRotationToggleText('heading-up'),
  1761. orientationMode: 'heading-up',
  1762. orientationModeText: formatOrientationModeText('heading-up'),
  1763. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1764. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1765. statusText: `正在启用朝向朝上模式 (${this.buildVersion})`,
  1766. }, true)
  1767. if (this.refreshAutoRotateTarget()) {
  1768. this.scheduleAutoRotate()
  1769. }
  1770. }
  1771. handleCompassHeading(headingDeg: number): void {
  1772. this.sensorHeadingDeg = normalizeRotationDeg(headingDeg)
  1773. this.smoothedSensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  1774. ? this.sensorHeadingDeg
  1775. : interpolateAngleDeg(this.smoothedSensorHeadingDeg, this.sensorHeadingDeg, AUTO_ROTATE_HEADING_SMOOTHING)
  1776. const compassHeadingDeg = getCompassReferenceHeadingDeg(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  1777. this.compassDisplayHeadingDeg = this.compassDisplayHeadingDeg === null
  1778. ? compassHeadingDeg
  1779. : interpolateAngleDeg(this.compassDisplayHeadingDeg, compassHeadingDeg, COMPASS_NEEDLE_SMOOTHING)
  1780. this.autoRotateHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1781. this.setState({
  1782. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1783. compassDeclinationText: formatCompassDeclinationText(this.northReferenceMode),
  1784. northReferenceButtonText: formatNorthReferenceButtonText(this.northReferenceMode),
  1785. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  1786. compassNeedleDeg: formatCompassNeedleDegForMode(this.northReferenceMode, this.smoothedSensorHeadingDeg),
  1787. northReferenceText: formatNorthReferenceText(this.northReferenceMode),
  1788. })
  1789. if (!this.refreshAutoRotateTarget()) {
  1790. return
  1791. }
  1792. if (this.state.orientationMode === 'heading-up') {
  1793. this.scheduleAutoRotate()
  1794. }
  1795. }
  1796. handleCompassError(message: string): void {
  1797. this.clearAutoRotateTimer()
  1798. this.targetAutoRotationDeg = null
  1799. this.autoRotateCalibrationPending = false
  1800. this.setState({
  1801. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1802. statusText: `${message} (${this.buildVersion})`,
  1803. }, true)
  1804. }
  1805. cycleNorthReferenceMode(): void {
  1806. const nextMode = getNextNorthReferenceMode(this.northReferenceMode)
  1807. const nextMapNorthOffsetDeg = getMapNorthOffsetDeg(nextMode)
  1808. const compassHeadingDeg = this.smoothedSensorHeadingDeg === null
  1809. ? null
  1810. : getCompassReferenceHeadingDeg(nextMode, this.smoothedSensorHeadingDeg)
  1811. this.northReferenceMode = nextMode
  1812. this.autoRotateCalibrationOffsetDeg = nextMapNorthOffsetDeg
  1813. this.compassDisplayHeadingDeg = compassHeadingDeg
  1814. if (this.state.orientationMode === 'north-up') {
  1815. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1816. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, MAP_NORTH_OFFSET_DEG)
  1817. this.commitViewport(
  1818. {
  1819. ...resolvedViewport,
  1820. rotationDeg: MAP_NORTH_OFFSET_DEG,
  1821. rotationText: formatRotationText(MAP_NORTH_OFFSET_DEG),
  1822. northReferenceText: formatNorthReferenceText(nextMode),
  1823. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1824. compassDeclinationText: formatCompassDeclinationText(nextMode),
  1825. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  1826. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  1827. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  1828. },
  1829. `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  1830. true,
  1831. () => {
  1832. this.resetPreviewState()
  1833. this.syncRenderer()
  1834. },
  1835. )
  1836. return
  1837. }
  1838. this.setState({
  1839. northReferenceText: formatNorthReferenceText(nextMode),
  1840. sensorHeadingText: formatHeadingText(compassHeadingDeg),
  1841. compassDeclinationText: formatCompassDeclinationText(nextMode),
  1842. northReferenceButtonText: formatNorthReferenceButtonText(nextMode),
  1843. compassNeedleDeg: formatCompassNeedleDegForMode(nextMode, this.smoothedSensorHeadingDeg),
  1844. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, nextMapNorthOffsetDeg),
  1845. statusText: `${formatNorthReferenceStatusText(nextMode)} (${this.buildVersion})`,
  1846. }, true)
  1847. if (this.state.orientationMode === 'heading-up' && this.refreshAutoRotateTarget()) {
  1848. this.scheduleAutoRotate()
  1849. }
  1850. }
  1851. setCourseHeading(headingDeg: number | null): void {
  1852. this.courseHeadingDeg = headingDeg === null ? null : normalizeRotationDeg(headingDeg)
  1853. this.setState({
  1854. autoRotateSourceText: formatAutoRotateSourceText(this.autoRotateSourceMode, this.courseHeadingDeg !== null),
  1855. })
  1856. if (this.refreshAutoRotateTarget()) {
  1857. this.scheduleAutoRotate()
  1858. }
  1859. }
  1860. resolveAutoRotateInputHeadingDeg(): number | null {
  1861. const sensorHeadingDeg = this.smoothedSensorHeadingDeg === null
  1862. ? null
  1863. : getMapReferenceHeadingDegFromSensor(this.northReferenceMode, this.smoothedSensorHeadingDeg)
  1864. const courseHeadingDeg = this.courseHeadingDeg === null
  1865. ? null
  1866. : getMapReferenceHeadingDegFromCourse(this.northReferenceMode, this.courseHeadingDeg)
  1867. if (this.autoRotateSourceMode === 'sensor') {
  1868. return sensorHeadingDeg
  1869. }
  1870. if (this.autoRotateSourceMode === 'course') {
  1871. return courseHeadingDeg === null ? sensorHeadingDeg : courseHeadingDeg
  1872. }
  1873. if (sensorHeadingDeg !== null && courseHeadingDeg !== null) {
  1874. return interpolateAngleDeg(sensorHeadingDeg, courseHeadingDeg, 0.35)
  1875. }
  1876. return sensorHeadingDeg === null ? courseHeadingDeg : sensorHeadingDeg
  1877. }
  1878. calibrateAutoRotateToCurrentOrientation(): boolean {
  1879. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1880. if (inputHeadingDeg === null) {
  1881. return false
  1882. }
  1883. this.autoRotateCalibrationOffsetDeg = normalizeRotationDeg(this.state.rotationDeg + inputHeadingDeg)
  1884. this.autoRotateCalibrationPending = false
  1885. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  1886. this.setState({
  1887. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1888. })
  1889. return true
  1890. }
  1891. refreshAutoRotateTarget(): boolean {
  1892. const inputHeadingDeg = this.resolveAutoRotateInputHeadingDeg()
  1893. if (inputHeadingDeg === null) {
  1894. return false
  1895. }
  1896. if (this.autoRotateCalibrationPending || this.autoRotateCalibrationOffsetDeg === null) {
  1897. if (!this.calibrateAutoRotateToCurrentOrientation()) {
  1898. return false
  1899. }
  1900. return true
  1901. }
  1902. this.targetAutoRotationDeg = normalizeRotationDeg(this.autoRotateCalibrationOffsetDeg - inputHeadingDeg)
  1903. this.setState({
  1904. autoRotateCalibrationText: formatAutoRotateCalibrationText(false, this.autoRotateCalibrationOffsetDeg),
  1905. })
  1906. return true
  1907. }
  1908. scheduleAutoRotate(): void {
  1909. if (this.autoRotateTimer || this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  1910. return
  1911. }
  1912. const step = () => {
  1913. this.autoRotateTimer = 0
  1914. if (this.state.rotationMode !== 'auto' || this.targetAutoRotationDeg === null) {
  1915. return
  1916. }
  1917. if (this.gestureMode !== 'idle' || this.inertiaTimer || this.previewResetTimer) {
  1918. this.scheduleAutoRotate()
  1919. return
  1920. }
  1921. const currentRotationDeg = this.state.rotationDeg
  1922. const deltaDeg = normalizeAngleDeltaDeg(this.targetAutoRotationDeg - currentRotationDeg)
  1923. if (Math.abs(deltaDeg) <= AUTO_ROTATE_SNAP_DEG) {
  1924. if (Math.abs(deltaDeg) > 0.01) {
  1925. this.applyAutoRotation(this.targetAutoRotationDeg)
  1926. }
  1927. this.scheduleAutoRotate()
  1928. return
  1929. }
  1930. if (Math.abs(deltaDeg) <= AUTO_ROTATE_DEADZONE_DEG) {
  1931. this.scheduleAutoRotate()
  1932. return
  1933. }
  1934. const easedStepDeg = clamp(deltaDeg * AUTO_ROTATE_EASE, -AUTO_ROTATE_MAX_STEP_DEG, AUTO_ROTATE_MAX_STEP_DEG)
  1935. this.applyAutoRotation(normalizeRotationDeg(currentRotationDeg + easedStepDeg))
  1936. this.scheduleAutoRotate()
  1937. }
  1938. this.autoRotateTimer = setTimeout(step, AUTO_ROTATE_FRAME_MS) as unknown as number
  1939. }
  1940. applyAutoRotation(nextRotationDeg: number): void {
  1941. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  1942. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y, nextRotationDeg)
  1943. this.setState({
  1944. ...resolvedViewport,
  1945. rotationDeg: nextRotationDeg,
  1946. rotationText: formatRotationText(nextRotationDeg),
  1947. centerText: buildCenterText(this.state.zoom, resolvedViewport.centerTileX, resolvedViewport.centerTileY),
  1948. })
  1949. this.syncRenderer()
  1950. }
  1951. applyStats(stats: MapRendererStats): void {
  1952. this.setState({
  1953. visibleTileCount: stats.visibleTileCount,
  1954. readyTileCount: stats.readyTileCount,
  1955. memoryTileCount: stats.memoryTileCount,
  1956. diskTileCount: stats.diskTileCount,
  1957. memoryHitCount: stats.memoryHitCount,
  1958. diskHitCount: stats.diskHitCount,
  1959. networkFetchCount: stats.networkFetchCount,
  1960. cacheHitRateText: formatCacheHitRate(stats.memoryHitCount, stats.diskHitCount, stats.networkFetchCount),
  1961. })
  1962. }
  1963. setState(patch: Partial<MapEngineViewState>, immediateUi = false): void {
  1964. this.state = {
  1965. ...this.state,
  1966. ...patch,
  1967. }
  1968. const viewPatch = this.pickViewPatch(patch)
  1969. if (!Object.keys(viewPatch).length) {
  1970. return
  1971. }
  1972. this.pendingViewPatch = {
  1973. ...this.pendingViewPatch,
  1974. ...viewPatch,
  1975. }
  1976. if (immediateUi) {
  1977. this.flushViewPatch()
  1978. return
  1979. }
  1980. if (this.viewSyncTimer) {
  1981. return
  1982. }
  1983. this.viewSyncTimer = setTimeout(() => {
  1984. this.viewSyncTimer = 0
  1985. this.flushViewPatch()
  1986. }, UI_SYNC_INTERVAL_MS) as unknown as number
  1987. }
  1988. commitViewport(
  1989. patch: Partial<MapEngineViewState>,
  1990. statusText: string,
  1991. immediateUi = false,
  1992. afterUpdate?: () => void,
  1993. ): void {
  1994. const nextZoom = typeof patch.zoom === 'number' ? patch.zoom : this.state.zoom
  1995. const nextCenterTileX = typeof patch.centerTileX === 'number' ? patch.centerTileX : this.state.centerTileX
  1996. const nextCenterTileY = typeof patch.centerTileY === 'number' ? patch.centerTileY : this.state.centerTileY
  1997. const nextStageWidth = typeof patch.stageWidth === 'number' ? patch.stageWidth : this.state.stageWidth
  1998. const nextStageHeight = typeof patch.stageHeight === 'number' ? patch.stageHeight : this.state.stageHeight
  1999. const tileSizePx = getTileSizePx({
  2000. centerWorldX: nextCenterTileX,
  2001. centerWorldY: nextCenterTileY,
  2002. viewportWidth: nextStageWidth,
  2003. viewportHeight: nextStageHeight,
  2004. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2005. })
  2006. this.setState({
  2007. ...patch,
  2008. tileSizePx,
  2009. centerText: buildCenterText(nextZoom, nextCenterTileX, nextCenterTileY),
  2010. statusText,
  2011. }, immediateUi)
  2012. this.syncRenderer()
  2013. this.compassController.start()
  2014. if (afterUpdate) {
  2015. afterUpdate()
  2016. }
  2017. }
  2018. buildScene() {
  2019. const exactCenter = this.getExactCenterFromTranslate(this.state.tileTranslateX, this.state.tileTranslateY)
  2020. return {
  2021. tileSource: this.state.tileSource,
  2022. osmTileSource: OSM_TILE_SOURCE,
  2023. zoom: this.state.zoom,
  2024. centerTileX: this.state.centerTileX,
  2025. centerTileY: this.state.centerTileY,
  2026. exactCenterWorldX: exactCenter.x,
  2027. exactCenterWorldY: exactCenter.y,
  2028. tileBoundsByZoom: this.tileBoundsByZoom,
  2029. viewportWidth: this.state.stageWidth,
  2030. viewportHeight: this.state.stageHeight,
  2031. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2032. overdraw: OVERDRAW,
  2033. translateX: this.state.tileTranslateX,
  2034. translateY: this.state.tileTranslateY,
  2035. rotationRad: this.getRotationRad(this.state.rotationDeg),
  2036. previewScale: this.previewScale || 1,
  2037. previewOriginX: this.previewOriginX || this.state.stageWidth / 2,
  2038. previewOriginY: this.previewOriginY || this.state.stageHeight / 2,
  2039. track: this.currentGpsTrack,
  2040. gpsPoint: this.currentGpsPoint,
  2041. gpsCalibration: GPS_MAP_CALIBRATION,
  2042. gpsCalibrationOrigin: worldTileToLonLat({ x: this.defaultCenterTileX, y: this.defaultCenterTileY }, this.defaultZoom),
  2043. course: this.courseOverlayVisible ? this.courseData : null,
  2044. cpRadiusMeters: this.cpRadiusMeters,
  2045. controlVisualMode: this.gamePresentation.map.controlVisualMode,
  2046. showCourseLegs: this.gamePresentation.map.showCourseLegs,
  2047. guidanceLegAnimationEnabled: this.gamePresentation.map.guidanceLegAnimationEnabled,
  2048. focusableControlIds: this.gamePresentation.map.focusableControlIds,
  2049. focusedControlId: this.gamePresentation.map.focusedControlId,
  2050. focusedControlSequences: this.gamePresentation.map.focusedControlSequences,
  2051. activeControlSequences: this.gamePresentation.map.activeControlSequences,
  2052. activeStart: this.gamePresentation.map.activeStart,
  2053. completedStart: this.gamePresentation.map.completedStart,
  2054. activeFinish: this.gamePresentation.map.activeFinish,
  2055. focusedFinish: this.gamePresentation.map.focusedFinish,
  2056. completedFinish: this.gamePresentation.map.completedFinish,
  2057. revealFullCourse: this.gamePresentation.map.revealFullCourse,
  2058. activeLegIndices: this.gamePresentation.map.activeLegIndices,
  2059. completedLegIndices: this.gamePresentation.map.completedLegIndices,
  2060. completedControlSequences: this.gamePresentation.map.completedControlSequences,
  2061. osmReferenceEnabled: this.state.osmReferenceEnabled,
  2062. overlayOpacity: MAP_OVERLAY_OPACITY,
  2063. }
  2064. }
  2065. syncRenderer(): void {
  2066. if (!this.mounted || !this.state.stageWidth || !this.state.stageHeight) {
  2067. return
  2068. }
  2069. this.renderer.updateScene(this.buildScene())
  2070. }
  2071. getCameraState(rotationDeg = this.state.rotationDeg): CameraState {
  2072. return {
  2073. centerWorldX: this.state.centerTileX + 0.5,
  2074. centerWorldY: this.state.centerTileY + 0.5,
  2075. viewportWidth: this.state.stageWidth,
  2076. viewportHeight: this.state.stageHeight,
  2077. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2078. translateX: this.state.tileTranslateX,
  2079. translateY: this.state.tileTranslateY,
  2080. rotationRad: this.getRotationRad(rotationDeg),
  2081. }
  2082. }
  2083. getRotationRad(rotationDeg = this.state.rotationDeg): number {
  2084. return normalizeRotationDeg(rotationDeg) * Math.PI / 180
  2085. }
  2086. getBaseCamera(centerTileX = this.state.centerTileX, centerTileY = this.state.centerTileY, rotationDeg = this.state.rotationDeg): CameraState {
  2087. return {
  2088. centerWorldX: centerTileX + 0.5,
  2089. centerWorldY: centerTileY + 0.5,
  2090. viewportWidth: this.state.stageWidth,
  2091. viewportHeight: this.state.stageHeight,
  2092. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2093. rotationRad: this.getRotationRad(rotationDeg),
  2094. }
  2095. }
  2096. getWorldOffsetFromScreen(stageX: number, stageY: number, rotationDeg = this.state.rotationDeg): { x: number; y: number } {
  2097. const baseCamera = {
  2098. centerWorldX: 0,
  2099. centerWorldY: 0,
  2100. viewportWidth: this.state.stageWidth,
  2101. viewportHeight: this.state.stageHeight,
  2102. visibleColumns: DESIRED_VISIBLE_COLUMNS,
  2103. rotationRad: this.getRotationRad(rotationDeg),
  2104. }
  2105. return screenToWorld(baseCamera, { x: stageX, y: stageY }, false)
  2106. }
  2107. getExactCenterFromTranslate(translateX: number, translateY: number): { x: number; y: number } {
  2108. if (!this.state.stageWidth || !this.state.stageHeight) {
  2109. return {
  2110. x: this.state.centerTileX + 0.5,
  2111. y: this.state.centerTileY + 0.5,
  2112. }
  2113. }
  2114. const screenCenterX = this.state.stageWidth / 2
  2115. const screenCenterY = this.state.stageHeight / 2
  2116. return screenToWorld(this.getBaseCamera(), {
  2117. x: screenCenterX - translateX,
  2118. y: screenCenterY - translateY,
  2119. }, false)
  2120. }
  2121. resolveViewportForExactCenter(centerWorldX: number, centerWorldY: number, rotationDeg = this.state.rotationDeg): {
  2122. centerTileX: number
  2123. centerTileY: number
  2124. tileTranslateX: number
  2125. tileTranslateY: number
  2126. } {
  2127. const nextCenterTileX = Math.floor(centerWorldX)
  2128. const nextCenterTileY = Math.floor(centerWorldY)
  2129. if (!this.state.stageWidth || !this.state.stageHeight) {
  2130. return {
  2131. centerTileX: nextCenterTileX,
  2132. centerTileY: nextCenterTileY,
  2133. tileTranslateX: 0,
  2134. tileTranslateY: 0,
  2135. }
  2136. }
  2137. const roundedCamera = this.getBaseCamera(nextCenterTileX, nextCenterTileY, rotationDeg)
  2138. const projectedCenter = worldToScreen(roundedCamera, { x: centerWorldX, y: centerWorldY }, false)
  2139. return {
  2140. centerTileX: nextCenterTileX,
  2141. centerTileY: nextCenterTileY,
  2142. tileTranslateX: this.state.stageWidth / 2 - projectedCenter.x,
  2143. tileTranslateY: this.state.stageHeight / 2 - projectedCenter.y,
  2144. }
  2145. }
  2146. setPreviewState(scale: number, originX: number, originY: number): void {
  2147. this.previewScale = scale
  2148. this.previewOriginX = originX
  2149. this.previewOriginY = originY
  2150. }
  2151. resetPreviewState(): void {
  2152. this.setPreviewState(1, this.state.stageWidth / 2, this.state.stageHeight / 2)
  2153. }
  2154. resetPinchState(): void {
  2155. this.pinchStartDistance = 0
  2156. this.pinchStartScale = 1
  2157. this.pinchStartAngle = 0
  2158. this.pinchStartRotationDeg = this.state.rotationDeg
  2159. this.pinchAnchorWorldX = 0
  2160. this.pinchAnchorWorldY = 0
  2161. }
  2162. clearPreviewResetTimer(): void {
  2163. if (this.previewResetTimer) {
  2164. clearTimeout(this.previewResetTimer)
  2165. this.previewResetTimer = 0
  2166. }
  2167. }
  2168. clearInertiaTimer(): void {
  2169. if (this.inertiaTimer) {
  2170. clearTimeout(this.inertiaTimer)
  2171. this.inertiaTimer = 0
  2172. }
  2173. }
  2174. clearViewSyncTimer(): void {
  2175. if (this.viewSyncTimer) {
  2176. clearTimeout(this.viewSyncTimer)
  2177. this.viewSyncTimer = 0
  2178. }
  2179. }
  2180. clearAutoRotateTimer(): void {
  2181. if (this.autoRotateTimer) {
  2182. clearTimeout(this.autoRotateTimer)
  2183. this.autoRotateTimer = 0
  2184. }
  2185. }
  2186. pickViewPatch(patch: Partial<MapEngineViewState>): Partial<MapEngineViewState> {
  2187. const viewPatch = {} as Partial<MapEngineViewState>
  2188. for (const key of VIEW_SYNC_KEYS) {
  2189. if (Object.prototype.hasOwnProperty.call(patch, key)) {
  2190. ;(viewPatch as any)[key] = patch[key]
  2191. }
  2192. }
  2193. return viewPatch
  2194. }
  2195. flushViewPatch(): void {
  2196. if (!Object.keys(this.pendingViewPatch).length) {
  2197. return
  2198. }
  2199. const patch = this.pendingViewPatch
  2200. this.pendingViewPatch = {}
  2201. this.onData(patch)
  2202. }
  2203. getTouchDistance(touches: TouchPoint[]): number {
  2204. if (touches.length < 2) {
  2205. return 0
  2206. }
  2207. const first = touches[0]
  2208. const second = touches[1]
  2209. const deltaX = first.pageX - second.pageX
  2210. const deltaY = first.pageY - second.pageY
  2211. return Math.sqrt(deltaX * deltaX + deltaY * deltaY)
  2212. }
  2213. getTouchAngle(touches: TouchPoint[]): number {
  2214. if (touches.length < 2) {
  2215. return 0
  2216. }
  2217. const first = touches[0]
  2218. const second = touches[1]
  2219. return Math.atan2(second.pageY - first.pageY, second.pageX - first.pageX)
  2220. }
  2221. getStagePoint(touches: TouchPoint[]): { x: number; y: number } {
  2222. if (!touches.length) {
  2223. return {
  2224. x: this.state.stageWidth / 2,
  2225. y: this.state.stageHeight / 2,
  2226. }
  2227. }
  2228. let pageX = 0
  2229. let pageY = 0
  2230. for (const touch of touches) {
  2231. pageX += touch.pageX
  2232. pageY += touch.pageY
  2233. }
  2234. return {
  2235. x: pageX / touches.length - this.state.stageLeft,
  2236. y: pageY / touches.length - this.state.stageTop,
  2237. }
  2238. }
  2239. animatePreviewToRest(): void {
  2240. this.clearPreviewResetTimer()
  2241. const startScale = this.previewScale || 1
  2242. const originX = this.previewOriginX || this.state.stageWidth / 2
  2243. const originY = this.previewOriginY || this.state.stageHeight / 2
  2244. if (Math.abs(startScale - 1) < 0.01) {
  2245. this.resetPreviewState()
  2246. this.syncRenderer()
  2247. this.compassController.start()
  2248. this.scheduleAutoRotate()
  2249. return
  2250. }
  2251. const startAt = Date.now()
  2252. const step = () => {
  2253. const progress = Math.min(1, (Date.now() - startAt) / PREVIEW_RESET_DURATION_MS)
  2254. const eased = 1 - Math.pow(1 - progress, 3)
  2255. const nextScale = startScale + (1 - startScale) * eased
  2256. this.setPreviewState(nextScale, originX, originY)
  2257. this.syncRenderer()
  2258. this.compassController.start()
  2259. if (progress >= 1) {
  2260. this.resetPreviewState()
  2261. this.syncRenderer()
  2262. this.compassController.start()
  2263. this.previewResetTimer = 0
  2264. this.scheduleAutoRotate()
  2265. return
  2266. }
  2267. this.previewResetTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2268. }
  2269. step()
  2270. }
  2271. normalizeTranslate(translateX: number, translateY: number, statusText: string): void {
  2272. if (!this.state.stageWidth) {
  2273. this.setState({
  2274. tileTranslateX: translateX,
  2275. tileTranslateY: translateY,
  2276. })
  2277. this.syncRenderer()
  2278. this.compassController.start()
  2279. return
  2280. }
  2281. const exactCenter = this.getExactCenterFromTranslate(translateX, translateY)
  2282. const resolvedViewport = this.resolveViewportForExactCenter(exactCenter.x, exactCenter.y)
  2283. const centerChanged = resolvedViewport.centerTileX !== this.state.centerTileX || resolvedViewport.centerTileY !== this.state.centerTileY
  2284. if (centerChanged) {
  2285. this.commitViewport(resolvedViewport, statusText)
  2286. return
  2287. }
  2288. this.setState({
  2289. tileTranslateX: resolvedViewport.tileTranslateX,
  2290. tileTranslateY: resolvedViewport.tileTranslateY,
  2291. })
  2292. this.syncRenderer()
  2293. this.compassController.start()
  2294. }
  2295. zoomAroundPoint(zoomDelta: number, stageX: number, stageY: number, residualScale: number): void {
  2296. const nextZoom = clamp(this.state.zoom + zoomDelta, this.minZoom, this.maxZoom)
  2297. const appliedDelta = nextZoom - this.state.zoom
  2298. if (!appliedDelta) {
  2299. this.animatePreviewToRest()
  2300. return
  2301. }
  2302. if (!this.state.stageWidth || !this.state.stageHeight) {
  2303. this.commitViewport(
  2304. {
  2305. zoom: nextZoom,
  2306. centerTileX: appliedDelta > 0 ? this.state.centerTileX * 2 : Math.floor(this.state.centerTileX / 2),
  2307. centerTileY: appliedDelta > 0 ? this.state.centerTileY * 2 : Math.floor(this.state.centerTileY / 2),
  2308. tileTranslateX: 0,
  2309. tileTranslateY: 0,
  2310. },
  2311. `缩放级别调整到 ${nextZoom}`,
  2312. true,
  2313. () => {
  2314. this.setPreviewState(residualScale, stageX, stageY)
  2315. this.syncRenderer()
  2316. this.compassController.start()
  2317. this.animatePreviewToRest()
  2318. },
  2319. )
  2320. return
  2321. }
  2322. const camera = this.getCameraState()
  2323. const world = screenToWorld(camera, { x: stageX, y: stageY }, true)
  2324. const zoomFactor = Math.pow(2, appliedDelta)
  2325. const nextWorldX = world.x * zoomFactor
  2326. const nextWorldY = world.y * zoomFactor
  2327. const anchorOffset = this.getWorldOffsetFromScreen(stageX, stageY)
  2328. const exactCenterX = nextWorldX - anchorOffset.x
  2329. const exactCenterY = nextWorldY - anchorOffset.y
  2330. const resolvedViewport = this.resolveViewportForExactCenter(exactCenterX, exactCenterY)
  2331. this.commitViewport(
  2332. {
  2333. zoom: nextZoom,
  2334. ...resolvedViewport,
  2335. },
  2336. `缩放级别调整到 ${nextZoom}`,
  2337. true,
  2338. () => {
  2339. this.setPreviewState(residualScale, stageX, stageY)
  2340. this.syncRenderer()
  2341. this.compassController.start()
  2342. this.animatePreviewToRest()
  2343. },
  2344. )
  2345. }
  2346. startInertia(): void {
  2347. this.clearInertiaTimer()
  2348. const step = () => {
  2349. this.panVelocityX *= INERTIA_DECAY
  2350. this.panVelocityY *= INERTIA_DECAY
  2351. if (Math.abs(this.panVelocityX) < INERTIA_MIN_SPEED && Math.abs(this.panVelocityY) < INERTIA_MIN_SPEED) {
  2352. this.setState({
  2353. statusText: `惯性滑动结束 (${this.buildVersion})`,
  2354. })
  2355. this.renderer.setAnimationPaused(false)
  2356. this.inertiaTimer = 0
  2357. this.scheduleAutoRotate()
  2358. return
  2359. }
  2360. this.normalizeTranslate(
  2361. this.state.tileTranslateX + this.panVelocityX * INERTIA_FRAME_MS,
  2362. this.state.tileTranslateY + this.panVelocityY * INERTIA_FRAME_MS,
  2363. `惯性滑动中 (${this.buildVersion})`,
  2364. )
  2365. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2366. }
  2367. this.inertiaTimer = setTimeout(step, INERTIA_FRAME_MS) as unknown as number
  2368. }
  2369. }