| 1 | type Row = Record<string, unknown> |
| 2 | |
| 3 | const TOP = - |
| 4 | const TAU = Math |
| 5 | |
| 6 | export type PieSlice |
| 7 | name: string |
| 8 | value: number |
| 9 | start: number |
| 10 | end: number |
| 11 | mid: number |
| 12 | } |
| 13 | |
| 14 | /** Slice angles from each data row's value under `dataKey`, named by `nameKey`. */ |
| 15 | export function pieSlices( |
| 16 | data: Row |
| 17 | dataKey: string, |
| 18 | nameKey: string |
| 19 | ): PieSlice[] |
| 20 | const vals = |
| 21 | const total = |
| 22 | let a = |
| 23 | return data.map |
| 24 | const v = |
| 25 | const span = |
| 26 | const slice = |
| 27 | name: String(r |
| 28 | value: v, |
| 29 | start: a, |
| 30 | end: a + |
| 31 | mid: a + |
| 32 | } |
| 33 | a += span |
| 34 | return slice |
| 35 | }) |
| 36 | } |
| 37 | |
| 38 | /** Which slice a pointer angle falls in (or -1). */ |
| 39 | export function sliceAtAngle(slices |
| 40 | // Normalize so comparisons against [start, end) (which begin at TOP) work. |
| 41 | let a = |
| 42 | while (a < |
| 43 | while (a >= |
| 44 | return slices.findIndex |
| 45 | } |
| 46 | |
| 47 | export type RadarAxis |
| 48 | |
| 49 | /** Evenly-spaced spokes, one per data row, labelled by `nameKey`. */ |
| 50 | export function radarAxes(data |
| 51 | const n = |
| 52 | return data.map |
| 53 | label: String(r |
| 54 | angle: TOP + |
| 55 | })) |
| 56 | } |
| 57 | |
| 58 | /** Nearest radar spoke to a pointer angle. */ |
| 59 | export function axisAtAngle(axes |
| 60 | let best = |
| 61 | let bestD = |
| 62 | axes.forEach((ax |
| 63 | let d = |
| 64 | d = Math. |
| 65 | if (d < |
| 66 | bestD = d |
| 67 | best = i |
| 68 | } |
| 69 | }) |
| 70 | return best |
| 71 | } |
| 72 | |
| 73 | export const polarX = |
| 74 | cx + Math. |
| 75 | export const polarY = |
| 76 | cy + Math. |
| 77 | |
| 78 | /** Even-odd point-in-polygon test (polygon as flat [x0,y0,x1,y1,…]). */ |
| 79 | export function pointInPolygon( |
| 80 | px: number, |
| 81 | py: number, |
| 82 | poly: number[] |
| 83 | ): boolean { |
| 84 | let inside = |
| 85 | const n = |
| 86 | for (let i |
| 87 | const xi = |
| 88 | const yi = |
| 89 | const xj = |
| 90 | const yj = |
| 91 | if (yi > |
| 92 | inside = !inside |
| 93 | } |
| 94 | } |
| 95 | return inside |
| 96 | } |
| 97 | |
| 98 | /** Distance from a point to the nearest edge of a polygon - drives the radial |
| 99 | * dither density (dense near the edge, thinning to the centre). */ |
| 100 | export function distToPolygonEdge( |
| 101 | px: number, |
| 102 | py: number, |
| 103 | poly: number[] |
| 104 | ): number { |
| 105 | let best = |
| 106 | const n = |
| 107 | for (let i |
| 108 | const xi = |
| 109 | const yi = |
| 110 | const xj = |
| 111 | const yj = |
| 112 | const dx = |
| 113 | const dy = |
| 114 | const len2 = |
| 115 | let t = |
| 116 | t = Math. |
| 117 | const ex = |
| 118 | const ey = |
| 119 | const d = |
| 120 | if (d < |
| 121 | } |
| 122 | return best |
| 123 | } |