mapEngine.ts 84 KB

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