|
| 1 | +import tgpu, { d } from 'typegpu'; |
| 2 | +import { rgbToOklab } from './oklab.ts'; |
| 3 | + |
| 4 | +export const hexToRgb = tgpu.comptime((hex: string | number): d.v3f => { |
| 5 | + let h: number; |
| 6 | + if (typeof hex === 'string') { |
| 7 | + let normalized = hex.trim(); |
| 8 | + if (normalized.startsWith('#')) { |
| 9 | + normalized = normalized.slice(1); |
| 10 | + } |
| 11 | + // Allow 6-digit (RRGGBB) or 8-digit (RRGGBBAA) hex strings. |
| 12 | + if (normalized.length !== 6 && normalized.length !== 8) { |
| 13 | + throw new Error(`hexToRgb expected a 6- or 8-digit hex string, got "${hex}".`); |
| 14 | + } |
| 15 | + // For 8-digit input, drop the alpha channel and keep RRGGBB. |
| 16 | + if (normalized.length === 8) { |
| 17 | + normalized = normalized.slice(0, 6); |
| 18 | + } |
| 19 | + h = Number.parseInt(normalized, 16); |
| 20 | + if (Number.isNaN(h)) { |
| 21 | + throw new Error(`hexToRgb could not parse hex string "${hex}".`); |
| 22 | + } |
| 23 | + } else { |
| 24 | + h = hex; |
| 25 | + if (!Number.isFinite(h)) { |
| 26 | + throw new Error(`hexToRgb expected a finite numeric value, got ${hex}.`); |
| 27 | + } |
| 28 | + } |
| 29 | + return d.vec3f((h >> 16) & 0xff, (h >> 8) & 0xff, h & 0xff).div(255); |
| 30 | +}); |
| 31 | + |
| 32 | +export const hexToRgba = tgpu.comptime((hex: string | number): d.v4f => { |
| 33 | + let h: number; |
| 34 | + if (typeof hex === 'string') { |
| 35 | + let normalized = hex.trim(); |
| 36 | + if (normalized.startsWith('#')) { |
| 37 | + normalized = normalized.slice(1); |
| 38 | + } |
| 39 | + // Allow 6-digit (RRGGBB) or 8-digit (RRGGBBAA) hex strings. |
| 40 | + // For 6-digit input, assume an implicit fully opaque alpha (FF). |
| 41 | + if (normalized.length === 6) { |
| 42 | + normalized = normalized + 'ff'; |
| 43 | + } else if (normalized.length !== 8) { |
| 44 | + throw new Error(`hexToRgba expected a 6- or 8-digit hex string, got "${hex}".`); |
| 45 | + } |
| 46 | + h = Number.parseInt(normalized, 16); |
| 47 | + if (Number.isNaN(h)) { |
| 48 | + throw new Error(`hexToRgba could not parse hex string "${hex}".`); |
| 49 | + } |
| 50 | + } else { |
| 51 | + h = hex; |
| 52 | + if (!Number.isFinite(h)) { |
| 53 | + throw new Error(`hexToRgba expected a finite numeric value, got ${hex}.`); |
| 54 | + } |
| 55 | + } |
| 56 | + return d.vec4f((h >> 24) & 0xff, (h >> 16) & 0xff, (h >> 8) & 0xff, h & 0xff).div(255); |
| 57 | +}); |
| 58 | + |
| 59 | +export const hexToOklab = tgpu.comptime((hex: string | number): d.v3f => { |
| 60 | + return rgbToOklab(hexToRgb(hex)); |
| 61 | +}); |
0 commit comments