courseLabelRenderer.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import { calibratedLonLatToWorldTile } from '../../utils/projection'
  2. import { worldToScreen, type CameraState } from '../camera/camera'
  3. import { type MapScene } from './mapRenderer'
  4. import { CourseLayer } from '../layer/courseLayer'
  5. import { resolveControlStyle } from './courseStyleResolver'
  6. import { type MockSimulatorDebugLogLevel } from '../debug/mockSimulatorDebugLogger'
  7. const EARTH_CIRCUMFERENCE_METERS = 40075016.686
  8. const LABEL_FONT_SIZE_RATIO = 1.08
  9. const LABEL_OFFSET_X_RATIO = 1.18
  10. const LABEL_OFFSET_Y_RATIO = -0.68
  11. const SCORE_LABEL_FONT_SIZE_RATIO = 0.7
  12. const SCORE_LABEL_OFFSET_Y_RATIO = 0.06
  13. const ACTIVE_LABEL_COLOR = 'rgba(255, 219, 54, 0.98)'
  14. const READY_LABEL_COLOR = 'rgba(98, 255, 214, 0.98)'
  15. const MULTI_ACTIVE_LABEL_COLOR = 'rgba(255, 202, 72, 0.96)'
  16. const FOCUSED_LABEL_COLOR = 'rgba(255, 252, 255, 0.98)'
  17. function rgbaToCss(color: [number, number, number, number], alphaOverride?: number): string {
  18. const alpha = alphaOverride !== undefined ? alphaOverride : color[3]
  19. return `rgba(${Math.round(color[0] * 255)}, ${Math.round(color[1] * 255)}, ${Math.round(color[2] * 255)}, ${alpha.toFixed(3)})`
  20. }
  21. function normalizeHexColor(rawValue: string | undefined): string | null {
  22. if (typeof rawValue !== 'string') {
  23. return null
  24. }
  25. const trimmed = rawValue.trim()
  26. return /^#[0-9a-fA-F]{6}$/.test(trimmed) || /^#[0-9a-fA-F]{8}$/.test(trimmed) ? trimmed : null
  27. }
  28. export class CourseLabelRenderer {
  29. courseLayer: CourseLayer
  30. canvas: any
  31. ctx: any
  32. dpr: number
  33. width: number
  34. height: number
  35. gpsLogoUrl: string
  36. gpsLogoResolvedSrc: string
  37. gpsLogoImage: any
  38. gpsLogoStatus: 'idle' | 'loading' | 'ready' | 'error'
  39. onDebugLog?: (
  40. scope: string,
  41. level: MockSimulatorDebugLogLevel,
  42. message: string,
  43. payload?: Record<string, unknown>,
  44. ) => void
  45. constructor(
  46. courseLayer: CourseLayer,
  47. onDebugLog?: (
  48. scope: string,
  49. level: MockSimulatorDebugLogLevel,
  50. message: string,
  51. payload?: Record<string, unknown>,
  52. ) => void,
  53. ) {
  54. this.courseLayer = courseLayer
  55. this.onDebugLog = onDebugLog
  56. this.canvas = null
  57. this.ctx = null
  58. this.dpr = 1
  59. this.width = 0
  60. this.height = 0
  61. this.gpsLogoUrl = ''
  62. this.gpsLogoResolvedSrc = ''
  63. this.gpsLogoImage = null
  64. this.gpsLogoStatus = 'idle'
  65. }
  66. emitDebugLog(
  67. level: MockSimulatorDebugLogLevel,
  68. message: string,
  69. payload?: Record<string, unknown>,
  70. ): void {
  71. if (this.onDebugLog) {
  72. this.onDebugLog('gps-logo', level, message, payload)
  73. }
  74. }
  75. attachCanvas(canvasNode: any, width: number, height: number, dpr: number): void {
  76. this.canvas = canvasNode
  77. this.ctx = canvasNode.getContext('2d')
  78. this.dpr = dpr || 1
  79. this.width = width
  80. this.height = height
  81. canvasNode.width = Math.max(1, Math.floor(width * this.dpr))
  82. canvasNode.height = Math.max(1, Math.floor(height * this.dpr))
  83. }
  84. destroy(): void {
  85. this.ctx = null
  86. this.canvas = null
  87. this.width = 0
  88. this.height = 0
  89. this.gpsLogoUrl = ''
  90. this.gpsLogoResolvedSrc = ''
  91. this.gpsLogoImage = null
  92. this.gpsLogoStatus = 'idle'
  93. }
  94. getGpsLogoDebugInfo(): { status: string; url: string; resolvedSrc: string } {
  95. return {
  96. status: this.gpsLogoStatus,
  97. url: this.gpsLogoUrl,
  98. resolvedSrc: this.gpsLogoResolvedSrc,
  99. }
  100. }
  101. render(scene: MapScene): void {
  102. if (!this.ctx || !this.canvas) {
  103. return
  104. }
  105. const course = this.courseLayer.projectCourse(scene)
  106. const ctx = this.ctx
  107. this.clearCanvas(ctx)
  108. this.ensureGpsLogo(scene)
  109. this.applyPreviewTransform(ctx, scene)
  110. ctx.save()
  111. if (course && course.controls.length && scene.revealFullCourse) {
  112. const controlRadiusMeters = scene.cpRadiusMeters > 0 ? scene.cpRadiusMeters : 5
  113. const scoreOffsetY = this.getMetric(scene, controlRadiusMeters * SCORE_LABEL_OFFSET_Y_RATIO)
  114. const offsetX = this.getMetric(scene, controlRadiusMeters * LABEL_OFFSET_X_RATIO)
  115. const offsetY = this.getMetric(scene, controlRadiusMeters * LABEL_OFFSET_Y_RATIO)
  116. if (scene.gameMode === 'score-o' || scene.controlVisualMode === 'multi-target') {
  117. ctx.textAlign = 'center'
  118. ctx.textBaseline = 'middle'
  119. for (const control of course.controls) {
  120. const resolvedStyle = resolveControlStyle(scene, 'control', control.sequence)
  121. const labelScale = Math.max(0.72, resolvedStyle.entry.labelScale || 1)
  122. const scoreFontSizePx = this.getMetric(scene, controlRadiusMeters * SCORE_LABEL_FONT_SIZE_RATIO * labelScale)
  123. ctx.save()
  124. ctx.font = `900 ${scoreFontSizePx}px sans-serif`
  125. ctx.fillStyle = this.getScoreLabelColor(scene, control.sequence)
  126. ctx.translate(control.point.x, control.point.y)
  127. ctx.rotate(scene.rotationRad)
  128. ctx.fillText(this.getControlLabelText(scene, control.sequence), 0, scoreOffsetY)
  129. ctx.restore()
  130. }
  131. } else {
  132. ctx.textAlign = 'left'
  133. ctx.textBaseline = 'middle'
  134. for (const control of course.controls) {
  135. const resolvedStyle = resolveControlStyle(scene, 'control', control.sequence)
  136. const labelScale = Math.max(0.72, resolvedStyle.entry.labelScale || 1)
  137. const fontSizePx = this.getMetric(scene, controlRadiusMeters * LABEL_FONT_SIZE_RATIO * labelScale)
  138. ctx.save()
  139. ctx.font = `700 ${fontSizePx}px sans-serif`
  140. ctx.fillStyle = this.getLabelColor(scene, control.sequence)
  141. ctx.translate(control.point.x, control.point.y)
  142. ctx.rotate(scene.rotationRad)
  143. ctx.fillText(String(control.sequence), offsetX, offsetY)
  144. ctx.restore()
  145. }
  146. }
  147. }
  148. this.renderGpsLogo(scene)
  149. ctx.restore()
  150. }
  151. buildVectorCamera(scene: MapScene): CameraState {
  152. return {
  153. centerWorldX: scene.exactCenterWorldX,
  154. centerWorldY: scene.exactCenterWorldY,
  155. viewportWidth: scene.viewportWidth,
  156. viewportHeight: scene.viewportHeight,
  157. visibleColumns: scene.visibleColumns,
  158. rotationRad: scene.rotationRad,
  159. }
  160. }
  161. ensureGpsLogo(scene: MapScene): void {
  162. const nextUrl = typeof scene.gpsMarkerStyleConfig.logoUrl === 'string'
  163. ? scene.gpsMarkerStyleConfig.logoUrl.trim()
  164. : ''
  165. if (!nextUrl) {
  166. if (this.gpsLogoUrl || this.gpsLogoStatus !== 'idle') {
  167. this.emitDebugLog('info', 'logo not configured')
  168. }
  169. this.gpsLogoUrl = ''
  170. this.gpsLogoResolvedSrc = ''
  171. this.gpsLogoImage = null
  172. this.gpsLogoStatus = 'idle'
  173. return
  174. }
  175. if (this.gpsLogoUrl === nextUrl && (this.gpsLogoStatus === 'loading' || this.gpsLogoStatus === 'ready')) {
  176. return
  177. }
  178. if (!this.canvas || typeof this.canvas.createImage !== 'function') {
  179. this.emitDebugLog('warn', 'canvas createImage unavailable')
  180. return
  181. }
  182. const image = this.canvas.createImage()
  183. this.gpsLogoUrl = nextUrl
  184. this.gpsLogoResolvedSrc = ''
  185. this.gpsLogoImage = image
  186. this.gpsLogoStatus = 'loading'
  187. this.emitDebugLog('info', 'start loading logo', {
  188. src: nextUrl,
  189. style: scene.gpsMarkerStyleConfig.style,
  190. logoMode: scene.gpsMarkerStyleConfig.logoMode,
  191. })
  192. const attachImageHandlers = () => {
  193. image.onload = () => {
  194. if (this.gpsLogoUrl !== nextUrl) {
  195. return
  196. }
  197. this.gpsLogoStatus = 'ready'
  198. this.emitDebugLog('info', 'logo image ready', {
  199. src: nextUrl,
  200. resolvedSrc: this.gpsLogoResolvedSrc,
  201. })
  202. }
  203. image.onerror = () => {
  204. if (this.gpsLogoUrl !== nextUrl) {
  205. return
  206. }
  207. this.gpsLogoStatus = 'error'
  208. this.gpsLogoImage = null
  209. this.emitDebugLog('error', 'logo image error', {
  210. src: nextUrl,
  211. resolvedSrc: this.gpsLogoResolvedSrc,
  212. })
  213. }
  214. }
  215. const assignImageSource = (src: string) => {
  216. if (this.gpsLogoUrl !== nextUrl) {
  217. return
  218. }
  219. this.gpsLogoResolvedSrc = src
  220. this.emitDebugLog('info', 'assign image source', {
  221. src: nextUrl,
  222. resolvedSrc: src,
  223. })
  224. attachImageHandlers()
  225. image.src = src
  226. }
  227. if (/^https?:\/\//i.test(nextUrl) && typeof wx !== 'undefined' && typeof wx.getImageInfo === 'function') {
  228. wx.getImageInfo({
  229. src: nextUrl,
  230. success: (result) => {
  231. if (this.gpsLogoUrl !== nextUrl || !result.path) {
  232. return
  233. }
  234. this.emitDebugLog('info', 'wx.getImageInfo success', {
  235. src: nextUrl,
  236. path: result.path,
  237. })
  238. assignImageSource(result.path)
  239. },
  240. fail: (error) => {
  241. if (this.gpsLogoUrl !== nextUrl) {
  242. return
  243. }
  244. this.emitDebugLog('warn', 'wx.getImageInfo failed, fallback to remote url', {
  245. src: nextUrl,
  246. error: error && typeof error === 'object' && 'errMsg' in error ? (error as { errMsg?: string }).errMsg || '' : '',
  247. })
  248. assignImageSource(nextUrl)
  249. },
  250. })
  251. return
  252. }
  253. assignImageSource(nextUrl)
  254. }
  255. getGpsLogoBadgeRadius(scene: MapScene): number {
  256. const base = scene.gpsMarkerStyleConfig.size === 'small'
  257. ? 4.1
  258. : scene.gpsMarkerStyleConfig.size === 'large'
  259. ? 6
  260. : 5
  261. const effectScale = Math.max(0.88, Math.min(1.28, scene.gpsMarkerStyleConfig.effectScale || 1))
  262. const logoScale = Math.max(0.86, Math.min(1.16, scene.gpsMarkerStyleConfig.logoScale || 1))
  263. return base * effectScale * logoScale
  264. }
  265. renderGpsLogo(scene: MapScene): void {
  266. if (
  267. !scene.gpsPoint
  268. || !scene.gpsMarkerStyleConfig.visible
  269. || scene.gpsMarkerStyleConfig.style !== 'badge'
  270. || scene.gpsMarkerStyleConfig.logoMode !== 'center-badge'
  271. || !scene.gpsMarkerStyleConfig.logoUrl
  272. || this.gpsLogoStatus !== 'ready'
  273. || !this.gpsLogoImage
  274. ) {
  275. return
  276. }
  277. const screenPoint = worldToScreen(
  278. this.buildVectorCamera(scene),
  279. calibratedLonLatToWorldTile(scene.gpsPoint, scene.zoom, scene.gpsCalibration, scene.gpsCalibrationOrigin),
  280. false,
  281. )
  282. const radius = this.getGpsLogoBadgeRadius(scene)
  283. const diameter = radius * 2
  284. const ctx = this.ctx
  285. ctx.save()
  286. ctx.beginPath()
  287. ctx.fillStyle = 'rgba(255, 255, 255, 0.96)'
  288. ctx.arc(screenPoint.x, screenPoint.y, radius + 1.15, 0, Math.PI * 2)
  289. ctx.fill()
  290. ctx.beginPath()
  291. ctx.strokeStyle = 'rgba(12, 36, 42, 0.18)'
  292. ctx.lineWidth = Math.max(1.1, radius * 0.18)
  293. ctx.arc(screenPoint.x, screenPoint.y, radius + 0.3, 0, Math.PI * 2)
  294. ctx.stroke()
  295. ctx.beginPath()
  296. ctx.arc(screenPoint.x, screenPoint.y, radius, 0, Math.PI * 2)
  297. ctx.clip()
  298. ctx.drawImage(this.gpsLogoImage, screenPoint.x - radius, screenPoint.y - radius, diameter, diameter)
  299. ctx.restore()
  300. }
  301. getLabelColor(scene: MapScene, sequence: number): string {
  302. const resolvedStyle = resolveControlStyle(scene, 'control', sequence)
  303. const customLabelColor = normalizeHexColor(resolvedStyle.entry.labelColorHex)
  304. if (customLabelColor) {
  305. return customLabelColor
  306. }
  307. if (scene.focusedControlSequences.includes(sequence)) {
  308. return FOCUSED_LABEL_COLOR
  309. }
  310. if (scene.readyControlSequences.includes(sequence)) {
  311. return READY_LABEL_COLOR
  312. }
  313. if (scene.activeControlSequences.includes(sequence)) {
  314. return scene.controlVisualMode === 'multi-target' ? MULTI_ACTIVE_LABEL_COLOR : ACTIVE_LABEL_COLOR
  315. }
  316. if (scene.completedControlSequences.includes(sequence)) {
  317. return resolvedStyle.entry.style === 'badge'
  318. ? 'rgba(255, 255, 255, 0.96)'
  319. : rgbaToCss(resolvedStyle.color, 0.94)
  320. }
  321. if (scene.skippedControlSequences.includes(sequence)) {
  322. return resolvedStyle.entry.style === 'badge'
  323. ? 'rgba(255, 255, 255, 0.9)'
  324. : rgbaToCss(resolvedStyle.color, 0.88)
  325. }
  326. return resolvedStyle.entry.style === 'badge'
  327. ? 'rgba(255, 255, 255, 0.98)'
  328. : rgbaToCss(resolvedStyle.color, 0.98)
  329. }
  330. getScoreLabelColor(scene: MapScene, sequence: number): string {
  331. const resolvedStyle = resolveControlStyle(scene, 'control', sequence)
  332. const customLabelColor = normalizeHexColor(resolvedStyle.entry.labelColorHex)
  333. if (customLabelColor) {
  334. return customLabelColor
  335. }
  336. if (scene.focusedControlSequences.includes(sequence)) {
  337. return FOCUSED_LABEL_COLOR
  338. }
  339. if (scene.readyControlSequences.includes(sequence)) {
  340. return READY_LABEL_COLOR
  341. }
  342. if (scene.completedControlSequences.includes(sequence)) {
  343. return resolvedStyle.entry.style === 'badge'
  344. ? 'rgba(255, 255, 255, 0.96)'
  345. : rgbaToCss(resolvedStyle.color, 0.94)
  346. }
  347. if (scene.skippedControlSequences.includes(sequence)) {
  348. return resolvedStyle.entry.style === 'badge'
  349. ? 'rgba(255, 255, 255, 0.92)'
  350. : rgbaToCss(resolvedStyle.color, 0.9)
  351. }
  352. return resolvedStyle.entry.style === 'badge'
  353. ? 'rgba(255, 255, 255, 0.98)'
  354. : rgbaToCss(resolvedStyle.color, 0.98)
  355. }
  356. getControlLabelText(scene: MapScene, sequence: number): string {
  357. if (scene.gameMode === 'score-o') {
  358. const score = scene.controlScoresBySequence[sequence]
  359. if (typeof score === 'number' && Number.isFinite(score)) {
  360. return String(score)
  361. }
  362. }
  363. return String(sequence)
  364. }
  365. clearCanvas(ctx: any): void {
  366. ctx.setTransform(1, 0, 0, 1, 0, 0)
  367. ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
  368. }
  369. applyPreviewTransform(ctx: any, scene: MapScene): void {
  370. const previewScale = scene.previewScale || 1
  371. const previewOriginX = scene.previewOriginX || scene.viewportWidth / 2
  372. const previewOriginY = scene.previewOriginY || scene.viewportHeight / 2
  373. const translateX = (previewOriginX - previewOriginX * previewScale) * this.dpr
  374. const translateY = (previewOriginY - previewOriginY * previewScale) * this.dpr
  375. ctx.setTransform(
  376. this.dpr * previewScale,
  377. 0,
  378. 0,
  379. this.dpr * previewScale,
  380. translateX,
  381. translateY,
  382. )
  383. }
  384. getMetric(scene: MapScene, meters: number): number {
  385. return meters * this.getPixelsPerMeter(scene)
  386. }
  387. getPixelsPerMeter(scene: MapScene): number {
  388. const tileSizePx = scene.viewportWidth / scene.visibleColumns
  389. const centerLat = this.worldTileYToLat(scene.exactCenterWorldY, scene.zoom)
  390. const metersPerTile = Math.cos(centerLat * Math.PI / 180) * EARTH_CIRCUMFERENCE_METERS / Math.pow(2, scene.zoom)
  391. if (!tileSizePx || !metersPerTile) {
  392. return 0
  393. }
  394. return tileSizePx / metersPerTile
  395. }
  396. worldTileYToLat(worldY: number, zoom: number): number {
  397. const scale = Math.pow(2, zoom)
  398. const latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * worldY / scale)))
  399. return latRad * 180 / Math.PI
  400. }
  401. }