mapEngine.ts 86 KB

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