mapEngine.ts 179 KB

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