nearest.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. // Selectors + DOM Manipulation
  2. const getColorInputNode = () => document.getElementById("color-input");
  3. const getMetricDropdownNode = () => document.getElementById("metric");
  4. const getIncludeXToggleNode = () => document.getElementById("include-x");
  5. const getNormQYToggleNode = () => document.getElementById("norm-q-y");
  6. const getCloseCoeffSliderNode = () => document.getElementById("close-coeff");
  7. const getCloseCoeffDisplayNode = () => document.getElementById("close-coeff-display");
  8. const getLimitSliderNode = () => document.getElementById("num-poke");
  9. const getLimitDisplayNode = () => document.getElementById("num-poke-display");
  10. const getNameInputNode = () => document.getElementById("pokemon-name");
  11. const getScoreListJABNode = () => document.getElementById("best-list-jab");
  12. const getScoreListRGBNode = () => document.getElementById("best-list-rgb");
  13. const getSearchListNode = () => document.getElementById("search-list");
  14. const getHideableControlNodes = () => document.querySelectorAll(".hideable_control");
  15. const getQJABDisplay = () => document.getElementById("q-vec-jab");
  16. const getQRGBDisplay = () => document.getElementById("q-vec-rgb");
  17. const getObjFnDisplay = () => document.getElementById("obj-fn");
  18. const getXDefinitionDisplay = () => document.getElementById("x-definition");
  19. const getYDefinitionDisplay = () => document.getElementById("y-definition");
  20. const getResultDefinitionDisplay = () => document.getElementById("result-definition");
  21. const clearNodeContents = node => { node.innerHTML = ""; };
  22. const hideCustomControls = () => getHideableControlNodes()
  23. .forEach(n => n.setAttribute("class", "hideable_control hideable_control--hidden"));
  24. const showCustomControls = () => getHideableControlNodes()
  25. .forEach(n => n.setAttribute("class", "hideable_control"));
  26. // Vector Math
  27. const vectorDot = (u, v) => u.map((x, i) => x * v[i]).reduce((x, y) => x + y);
  28. const vectorMag = v => Math.sqrt(vectorDot(v, v));
  29. const vectorNorm = v => { const n = vectorMag(v); return [ n, v.map(c => c / n) ]; };
  30. // Angle Math
  31. const angleDiff = (a, b) => { const raw = Math.abs(a - b); return raw < 180 ? raw : (360 - raw); };
  32. const rad2deg = 180 / Math.PI;
  33. // Pre-Compute Y Data
  34. const pokemonColorData = database.map(data => {
  35. const yRGBColor = d3.rgb(...data.yRGB);
  36. const [ yJABNorm, yJABHat ] = vectorNorm(data.yJAB);
  37. const [ yRGBNorm, yRGBHat ] = vectorNorm(data.yRGB);
  38. return {
  39. ...data,
  40. yJABHex: d3.jab(...data.yJAB).formatHex(),
  41. yJABNorm, yJABHat,
  42. yRGBHex: yRGBColor.formatHex(),
  43. yRGBNorm, yRGBHat,
  44. yHueAngleJAB: rad2deg * Math.atan2(data.yJAB[2], data.yJAB[1]),
  45. yHueAngleRGB: d3.hsl(yRGBColor).h,
  46. }
  47. });
  48. const pokemonLookup = new Fuse(pokemonColorData, { keys: [ "name" ] });
  49. // Color Calculations
  50. const getContrastingTextColor = rgb => vectorDot(rgb, [0.3, 0.6, 0.1]) >= 128 ? "#222" : "#ddd";
  51. const readColorInput = () => {
  52. const colorInput = "#" + (getColorInputNode()?.value?.replace("#", "") ?? "FFFFFF");
  53. if (colorInput.length !== 7) {
  54. return;
  55. }
  56. const rgb = d3.color(colorInput);
  57. const { J, a, b } = d3.jab(rgb);
  58. const qJAB = [ J, a, b ];
  59. const qRGB = [ rgb.r, rgb.g, rgb.b ];
  60. const [ qJABNorm, qJABHat ] = vectorNorm(qJAB);
  61. const qJABNormSq = qJABNorm * qJABNorm;
  62. const [ qRGBNorm, qRGBHat ] = vectorNorm(qRGB);
  63. const qRGBNormSq = qRGBNorm * qRGBNorm;
  64. return {
  65. qHex: rgb.formatHex(),
  66. qJAB, qJABHat, qJABNorm, qJABNormSq,
  67. qRGB, qRGBHat, qRGBNorm, qRGBNormSq,
  68. qHueAngleJAB: rad2deg * Math.atan2(b, a),
  69. qHueAngleRGB: d3.hsl(rgb).h,
  70. };
  71. };
  72. // State
  73. const state = {
  74. metric: null,
  75. includeX: null,
  76. normQY: null,
  77. closeCoeff: null,
  78. numPoke: null,
  79. searchTerm: null,
  80. targetColor: null,
  81. searchResults: null,
  82. };
  83. // Metrics
  84. const scoringMetrics = [
  85. ({ xJAB, xRGB, yJAB, yRGB }) => [
  86. xJAB - 2 * vectorDot(yJAB, state.targetColor.qJAB),
  87. xRGB - 2 * vectorDot(yRGB, state.targetColor.qRGB),
  88. ],
  89. ({ yJABHat, yRGBHat }) => [
  90. -vectorDot(yJABHat, state.targetColor.qJABHat),
  91. -vectorDot(yRGBHat, state.targetColor.qRGBHat),
  92. ],
  93. ({ yHueAngleJAB, yHueAngleRGB }) => [
  94. angleDiff(state.targetColor.qHueAngleJAB, yHueAngleJAB),
  95. angleDiff(state.targetColor.qHueAngleRGB, yHueAngleRGB),
  96. ],
  97. ({ xJAB, xRGB, yJAB, yRGB, yJABHat, yRGBHat }) => [
  98. (state.includeX ? xJAB : 0) - state.closeCoeff * vectorDot(
  99. state.normQY ? yJABHat : yJAB,
  100. state.normQY ? state.targetColor.qJABHat : state.targetColor.qJAB
  101. ),
  102. (state.includeX ? xRGB : 0) - state.closeCoeff * vectorDot(
  103. state.normQY ? yRGBHat : yRGB,
  104. state.normQY ? state.targetColor.qRGBHat : state.targetColor.qRGB
  105. ),
  106. ]
  107. ];
  108. const calcDisplayMetrics = ({
  109. xJAB, xRGB, yJABHat, yJABNorm, yRGBHat, yRGBNorm, yHueAngleJAB, yHueAngleRGB,
  110. }) => {
  111. // TODO - case on state.metric to avoid recalculation of subterms?
  112. const cosAngleJAB = vectorDot(state.targetColor.qJABHat, yJABHat);
  113. const yTermJAB = cosAngleJAB * yJABNorm * state.targetColor.qJABNorm;
  114. const cosAngleRGB = vectorDot(state.targetColor.qRGBHat, yRGBHat);
  115. const yTermRGB = cosAngleRGB * yRGBNorm * state.targetColor.qRGBNorm;
  116. return {
  117. stdDevRGB: Math.sqrt(xRGB - 2 * yTermRGB + state.targetColor.qRGBNormSq),
  118. stdDevJAB: Math.sqrt(xJAB - 2 * yTermJAB + state.targetColor.qJABNormSq),
  119. angleJAB: rad2deg * Math.acos(cosAngleJAB),
  120. angleRGB: rad2deg * Math.acos(cosAngleRGB),
  121. hueAngleJAB: angleDiff(state.targetColor.qHueAngleJAB, yHueAngleJAB),
  122. hueAngleRGB: angleDiff(state.targetColor.qHueAngleRGB, yHueAngleRGB),
  123. };
  124. };
  125. // Math Rendering
  126. const renderQVec = (q, node, sub) => {
  127. node.innerHTML = TeXZilla.toMathMLString(String.raw`\vec{q}_{\text{${sub}}} = \left(\text{${q.join(", ")}}\right)`);
  128. };
  129. const xDefinition = TeXZilla.toMathML(String.raw`
  130. X\left(P\right) = \frac{1}{\left|P\right|}\sum_{p\inP}{\left|\left|\vec{p}\right|\right|^2}
  131. `);
  132. const yDefinition = TeXZilla.toMathML(String.raw`
  133. \vec{Y}\left(P\right) = \frac{1}{\left|P\right|}\sum_{p\inP}{\vec{p}}
  134. `);
  135. const resultDefinition = TeXZilla.toMathML(String.raw`
  136. \left(
  137. \text{RMS}_P\left(q\right),
  138. \angle \left(\vec{q}, \vec{Y}\left(P\right)\right),
  139. \Delta{H}
  140. \right)
  141. `);
  142. const metricText = [
  143. String.raw`\text{RMS}_{P}\left(q\right) ~ \arg\min_{P}\left[X\left(P\right) - 2\vec{q}\cdot \vec{Y}\left(P\right)\right]`,
  144. String.raw`\angle \left(\vec{q}, \vec{Y}\left(P\right)\right) ~ \arg\max_{P}\left[\cos\left(\angle \left(\vec{q}, \vec{Y}\left(P\right)\right)\right)\right]`,
  145. String.raw`\Delta{H} = \angle \left(\vec{q}_{\perp}, \vec{Y}_{\perp}\left(P\right) \right), \vec{v}_{\perp} = \text{oproj}_{\left\{\vec{J}, \vec{L}\right\}}{\vec{v}}`,
  146. ].map(s => TeXZilla.toMathML(s));
  147. const renderVec = math => String.raw`\vec{${math.charAt(0)}}${math.substr(1)}`;
  148. const renderNorm = vec => String.raw`\frac{${vec}}{\left|\left|${vec}\right|\right|}`;
  149. const updateObjective = () => {
  150. let tex = metricText?.[state.metric];
  151. if (!tex) {
  152. const { includeX, normQY, closeCoeff } = state;
  153. if (!includeX && closeCoeff === 0) {
  154. tex = TeXZilla.toMathML(String.raw`\text{Empty Metric}`);
  155. } else {
  156. const qyMod = normQY ? c => renderNorm(renderVec(c)) : renderVec;
  157. tex = TeXZilla.toMathML(String.raw`
  158. \arg
  159. \m${includeX ? "in" : "ax"}_{P}
  160. \left[
  161. ${includeX ? String.raw`X\left(P\right)` : ""}
  162. ${closeCoeff === 0 ? "" : String.raw`
  163. ${includeX ? "-" : ""}
  164. ${(includeX && closeCoeff !== 1) ? closeCoeff : ""}
  165. ${qyMod("q")}
  166. \cdot
  167. ${qyMod(String.raw`Y\left(P\right)`)}
  168. `}
  169. \right]
  170. `);
  171. }
  172. }
  173. const objFnNode = getObjFnDisplay();
  174. clearNodeContents(objFnNode);
  175. objFnNode.appendChild(tex);
  176. };
  177. // Pokemon Rendering
  178. const stripForm = ["flabebe", "floette", "florges", "vivillon", "basculin", "furfrou", "magearna"];
  179. const getSprite = pokemon => {
  180. pokemon = pokemon
  181. .replace("-alola", "-alolan")
  182. .replace("-galar", "-galarian")
  183. .replace("darmanitan-galarian", "darmanitan-galarian-standard");
  184. if (stripForm.find(s => pokemon.includes(s))) {
  185. pokemon = pokemon.replace(/-.*$/, "");
  186. }
  187. return `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`;
  188. };
  189. const renderPokemon = (data, classes = {}) => {
  190. const { name, yJAB, yJABHex, yRGB, yRGBHex } = data;
  191. const { labelClass = "", rgbClass = "", jabClass = "" } = classes;
  192. let { resultsClass = "" } = classes;
  193. let displayMetrics = {};
  194. if (!state.targetColor) {
  195. // no color selected need to skip scores
  196. resultsClass = "hide";
  197. } else {
  198. displayMetrics = calcDisplayMetrics(data);
  199. }
  200. const {
  201. stdDevJAB = 0, stdDevRGB = 0,
  202. angleJAB = 0, angleRGB = 0,
  203. hueAngleJAB = 0, hueAngleRGB = 0,
  204. } = displayMetrics;
  205. const titleName = name.split("-").map(part => part.charAt(0).toUpperCase() + part.substr(1)).join(" ");
  206. const textHex = getContrastingTextColor(yRGB);
  207. const rgbVec = yRGB.map(c => c.toFixed()).join(", ");
  208. const jabVec = yJAB.map(c => c.toFixed(1)).join(", ");
  209. const pkmn = document.createElement("div");
  210. pkmn.setAttribute("class", "pokemon_tile");
  211. pkmn.innerHTML = `
  212. <div class="pokemon_tile-image-wrapper">
  213. <img src="${getSprite(name)}" />
  214. </div>
  215. <div class="pokemon_tile-info_panel">
  216. <span class="pokemon_tile-pokemon_name">${titleName}</span>
  217. <div class="pokemon_tile-results">
  218. <div class="pokemon_tile-labels ${labelClass}">
  219. <span class="${jabClass}">Jab: </span>
  220. <span class="${rgbClass}">RGB: </span>
  221. </div>
  222. <div class="pokemon_tile-score_column ${resultsClass}">
  223. <span class="pokemon_tile-no_flex ${jabClass}">
  224. (${stdDevJAB.toFixed(2)}, ${angleJAB.toFixed(2)}&deg;, ${hueAngleJAB.toFixed(2)}&deg;)
  225. </span>
  226. <span class="pokemon_tile-no_flex ${rgbClass}">
  227. (${stdDevRGB.toFixed(2)}, ${angleRGB.toFixed(2)}&deg;, ${hueAngleRGB.toFixed(2)}&deg;)
  228. </span>
  229. </div>
  230. <div class="pokemon_tile-hex_column">
  231. <div class="pokemon_tile-hex_color ${jabClass}" style="background-color: ${yJABHex}; color: ${textHex}">
  232. <span>${yJABHex}</span><span class="pokemon_tile-vector">(${jabVec})</span>
  233. </div>
  234. <div class="pokemon_tile-hex_color ${rgbClass}" style="background-color: ${yRGBHex}; color: ${textHex}">
  235. <span>${yRGBHex}</span><span class="pokemon_tile-vector">(${rgbVec})</span>
  236. </div>
  237. </div>
  238. </div>
  239. </div>
  240. `;
  241. return pkmn;
  242. };
  243. const getPokemonAppender = targetList => (pokemonData, classes) => {
  244. const li = document.createElement("li");
  245. li.appendChild(renderPokemon(pokemonData, classes));
  246. targetList.appendChild(li);
  247. };
  248. // Update Search Results
  249. const renderSearch = () => {
  250. const resultsNode = getSearchListNode();
  251. const append = getPokemonAppender(resultsNode);
  252. clearNodeContents(resultsNode);
  253. state.searchResults?.forEach(pkmn => append(pkmn));
  254. };
  255. // Scoring
  256. const rescore = () => {
  257. if (!state.targetColor) {
  258. return;
  259. }
  260. const metricFn = scoringMetrics[state.metric ?? 0];
  261. // TODO might like to save this somewhere instead of recomputing when limit changes
  262. const scores = pokemonColorData.map(data => ({ ...data, scores: metricFn(data) }));
  263. const jabList = getScoreListJABNode();
  264. const appendJAB = getPokemonAppender(jabList);
  265. const rgbList = getScoreListRGBNode();
  266. const appendRGB = getPokemonAppender(rgbList);
  267. // extract best CIECAM02 results
  268. const bestJAB = scores
  269. .sort((a, b) => a.scores[0] - b.scores[0])
  270. .slice(0, state.numPoke);
  271. clearNodeContents(jabList);
  272. bestJAB.forEach(data => appendJAB(data, { labelClass: "hide", rgbClass: "hide" }));
  273. // extract best RGB results
  274. const bestRGB = scores
  275. .sort((a, b) => a.scores[1] - b.scores[1])
  276. .slice(0, state.numPoke);
  277. clearNodeContents(rgbList);
  278. bestRGB.forEach(data => appendRGB(data, { labelClass: "hide", jabClass: "hide" }));
  279. // update the rendered search results as well
  280. renderSearch();
  281. };
  282. // Listeners
  283. const onColorChanged = skipScore => {
  284. const readColor = readColorInput();
  285. if (readColor) {
  286. state.targetColor = readColor;
  287. renderQVec(state.targetColor.qJAB.map(c => c.toFixed(2)), getQJABDisplay(), "Jab");
  288. renderQVec(state.targetColor.qRGB.map(c => c.toFixed()), getQRGBDisplay(), "RGB");
  289. const textColor = getContrastingTextColor(state.targetColor.qRGB);
  290. document.querySelector("body").setAttribute("style", `background: ${state.targetColor.qHex}; color: ${textColor}`);
  291. state.targetColor
  292. if (!skipScore) {
  293. rescore();
  294. }
  295. }
  296. };
  297. const onRandomColor = () => {
  298. const color = [Math.random(), Math.random(), Math.random()].map(c => c * 255);
  299. getColorInputNode().value = d3.rgb(...color).formatHex();
  300. onColorChanged(); // triggers rescore
  301. };
  302. const onCustomControlsChanged = skipScore => {
  303. state.includeX = getIncludeXToggleNode()?.checked ?? false;
  304. state.normQY = getNormQYToggleNode()?.checked ?? false;
  305. state.closeCoeff = parseFloat(getCloseCoeffSliderNode()?.value ?? 2);
  306. getCloseCoeffDisplayNode().innerHTML = state.closeCoeff;
  307. updateObjective();
  308. if (!skipScore) {
  309. rescore();
  310. }
  311. }
  312. const onMetricChanged = skipScore => {
  313. const metric = getMetricDropdownNode()?.selectedIndex ?? 0;
  314. if (metric === state.metric) {
  315. return;
  316. }
  317. state.metric = metric;
  318. if (state.metric === 3) { // Custom
  319. showCustomControls();
  320. onCustomControlsChanged(skipScore); // triggers rescore
  321. } else {
  322. hideCustomControls();
  323. updateObjective();
  324. if (!skipScore) {
  325. rescore();
  326. }
  327. }
  328. };
  329. const onLimitChanged = skipScore => {
  330. state.numPoke = parseInt(getLimitSliderNode()?.value ?? 10);
  331. getLimitDisplayNode().textContent = state.numPoke;
  332. if (!skipScore) {
  333. // TODO don't need to rescore just need to expand
  334. rescore();
  335. }
  336. };
  337. const onSearchChanged = () => {
  338. state.searchTerm = getNameInputNode()?.value?.toLowerCase() ?? "";
  339. if (state.searchTerm.length === 0) {
  340. state.searchResults = [];
  341. } else {
  342. state.searchResults = pokemonLookup
  343. .search(state.searchTerm, { limit: 10 })
  344. .map(({ item }) => item);
  345. }
  346. renderSearch();
  347. };
  348. const onRandomPokemon = () => {
  349. getNameInputNode().value = "";
  350. state.searchResults = Array.from({ length: 10 }, () => pokemonColorData[Math.floor(Math.random() * pokemonColorData.length)]);
  351. renderSearch();
  352. };
  353. const onPageLoad = () => {
  354. // render static explanations
  355. getXDefinitionDisplay().appendChild(xDefinition);
  356. getYDefinitionDisplay().appendChild(yDefinition);
  357. getResultDefinitionDisplay().appendChild(resultDefinition);
  358. // fake some events but don't do any scoring
  359. onColorChanged(true);
  360. onMetricChanged(true);
  361. onLimitChanged(true);
  362. // then do a rescore directly, which will do nothing unless old data was loaded
  363. rescore();
  364. // finally render search in case rescore didn't
  365. onSearchChanged();
  366. };