Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Sunday, 19 December 2021

Universe 5: Font Detection

Any Unicode codepoint browser ends up as an exercise in font wrangling. Universe is no exception.

The threat of fingerprinting means a browser script cannot typically enumerate the locally installed fonts. There is also currently no native way of determining if a font supports a particular codepoint. One would think that determining font support for codepoints would therefore be problematic, but it turns out to be relatively easy for our use-case with Chrome.

Consider the following JavaScript snippet:

var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
context.font = "10px font-a,font-b,font-c";
var measure = context.measureText(text);

If a character in the "text" string is not supported by "font-a", Chrome text rendering falls back to using "font-b". If "font-b" also doesn't support the character, "font-c" is used. If the character is not supported by "font-c" either, a system default is used.

We can take advantage of this fall back mechanism by using a "blank" font that guarantees to render any glyph as zero-width/zero-mark. Fortunately, there's just such a font already out there: Adobe Blank:

@font-face {
  font-family: "blank";
  src: url("https://raw.githubusercontent.com/adobe-fonts/
         adobe-blank/master/AdobeBlank.otf.woff") format("woff");
}

Now, we can write a function to test a font for supported characters:

function IsBlank(font, text) {
  var canvas = document.createElement("canvas");
  var context = canvas.getContext("2d");
  context.font = `10px "${font}",blank`;
  var measure = context.measureText(text);
  return (measure.width <= 0) &&
    (measure.actualBoundingBoxRight <= -measure.actualBoundingBoxLeft);
}

The actual code in universe.js has some optimisations and additional features; see "MeasureTextContext()" and "TextIsBlank()".

Using this technique, we can iterate around some "well-known" fonts and render them where appropriate. For our example of codepoint U+0040:

The origins of each of the glyphs above are:

  1. "notoverse" is the 32-by-32 pixel bitmap glyph described previously.
  2. "(default)" is the default font used for this codepoint by Chrome. In my case, it's "Times New Roman".
  3. "(sans-serif)" is the default sans serif font: "Arial".
  4. "(serif)" is the default serif font: "Times New Roman".
  5. "(monospace)" is the default monospace font: "Consolas".
  6. "r12a.io" is the PNG from Richard Ishida's UniView online app.
  7. "glyphwiki.org" is the SVG from GlyphWiki. It looks a bit squashed because it's a half-width glyph; GlyphWiki is primarily concerned with CJK glyphs.
  8. "unifont" is the GNU Unifont font. I couldn't find a webfont-friendly source for version 14, so I had to piggyback version 12 from Terence Eden.
  9. "noto" is a composite font of several dozen Google Noto fonts. See ".noto" in universe.css.
  10. Subsequent "Noto ..." glyphs are from the corresponding, individual Noto font, in priority order.

Saturday, 18 December 2021

Universe 4: User Interface

The Universe character browser has a very basic user interface. In addition to the HTML5 presentation, there is a URL scheme that allows you to jump to various subpages.

Landing Page

universe.html#

The landing page gives a brief introduction and a collapsible table of statistics. As with all pages, a header contains breadcrumbs and a footer lists some useful jumping-off points.

Codepoints

To examine a specific codepoint, expressed in hexadecimal between "0000" and "10FFFF" inclusive, use:

universe.html#U+<hex>

In this case, "#U+0040" examines "@". The subpage lists the block, column and codepoint details, as well as font support, UCD data fields and external links, where appropriate.

Planes

To list all 17 Unicode planes, use:

universe.html#P

To examine details of the plane containing codepoint "U+<hex>", use:

universe.html#P+<hex>

Sheets

In this context, a "sheet" is a 32-by-32 grid of 1024 contiguous codepoints; it is how the Notoverse glyphs are organised.

To list all 161 sheets which contain allocated codepoints, use:

universe.html#S

To examine the sheet containing codepoint "U+<hex>", use:

universe.html#S+<hex>

Blocks

To list all 320 named Unicode blocks, use:

universe.html#B

To examine the block containing codepoint "U+<hex>", use:

universe.html#B+<hex>

This will list constituent codepoints, organised by column.

Columns

To examine just the column containing codepoint "U+<hex>", use:

universe.html#C+<hex>

This will list constituent codepoints in more detail.

Queries

To query the UCD for matching codepoints, use:

universe.html#<key>=<value>

The "<key>" can be:

  • One of the abbreviated UCD field names, such as "gc" or "na".
  • "id" to search the codepoint id (e.g. "U+0040").
  • "basic" to search the computed codepoint basic category.
  • "kind" to search the computed codepoint kind.
  • "script" to search the codepoint script list (see below).
  • "extra" to search NamesList.txt annotations.
  • "text" to search all the above.

The "<value>" can be simple text or a JavaScript regular expression in the form "/<expr>/<flags>". For example:

universe.html#na=/\bANT\b/i

This searches for codepoints whose name field contains the whole word "ANT" case-insensitively.

Scripts

Queries with the special key "script" search the fields "sc" and "scx". To query for the 29 codepoints of the Ogham script, use:

universe.html#script=Ogam

List all the 210 scripts of the ISO-15924 standard, use:

universe.html#script

Search

Queries with the special key "search" perform full-text searches. To bring up a search dialog, use:

universe.html#search

Gears

As mentioned earlier, loading the full UCD database and glyph sheets for the first time can take quite a few minutes. Searches can also take a few seconds. For long-running JavaScript functions, we display animated gears:

To keep the page responsive, we wrap the long-running functionality inside a call to the "Gears()" function in universe.js:

function Gears(parent, asynchronous, complete) {
  var gears = document.createElement("img");
  gears.className = "gears";
  gears.title = "Please wait...";
  gears.src = "gears.svg";
  parent.appendChild(gears);
  gears.onload = async () => {
    var result = await asynchronous();
    if (gears.parentNode === parent) {
      parent.removeChild(gears);
    }
    if (complete) {
      complete(result);
    }
  };
}

Inside the asynchronous, long-running function we have to make sure we periodically call "YieldAsync()":

function YieldAsync(milliseconds) {
  // Yield every few milliseconds 
  // (or every time this function is called if argument is missing)
  var now = performance.now();
  if (!YieldAsync.already) {
    // First call
    YieldAsync.already = Promise.resolve(undefined);
    YieldAsync.channel = new MessageChannel();
  } else if (milliseconds && ((now - YieldAsync.previous) < milliseconds)) {
    // Resolve immediately
    return YieldAsync.already;
  }
  YieldAsync.previous = now;
  return new Promise(resolve => {
    YieldAsync.channel.port1.addEventListener("message",
      () => resolve(), { once: true });
    YieldAsync.channel.port1.start();
    YieldAsync.channel.port2.postMessage(null);
  });
}

This was inspired by a much-underrated StackOverflow answer.

Thursday, 16 December 2021

Universe 2: Loading Resources

When the Universe web page first loads into a browser, about 100MB of data are pulled over the network in over 250 HTTP requests. This includes 77 web fonts (6MB), 161 glyph image sheets (77MB) and the Unicode Character Database, UCD, as a tab-separated value file (28MB).

It can take three or four minutes the first time around with a slow network connection, but all these resources are usually cached by the browser, so subsequent page loads perform very little actual data transfer. However, decoding the UCD is another matter.

Even the subset of the UCD data we're actually interested in takes up a quarter of a gigabyte when expressed as JSON. So caching the raw JSON file is problematic. I elected to transfer the data as sequential key-value deltas in TSV format. This reduces the size down to under 30MB and only 6.5MB when compressed "on the wire". It is also relatively quick to reconstitute the full UCD object hierarchy in JavaScript: it takes about seven seconds on my machine.

Here are the lines describing codepoint U+0040 ("@"):

na<tab>COMMERCIAL AT
lb<tab>AL
STerm<tab>N
Term<tab>N
SB<tab>XX
0040
<tab>= at sign

The first five lines (in "<key><tab><value>" form) list only the differences in UCD properties (keyed by short property aliases) compared to the preceding codepoint (i.e. U+003F "?").

The next line (in "<hex>" form) creates a new codepoint record for "U+0040".

The final line (in "<tab><extra>" form) adds an extra line of narrative to the preceding record. In this case, it refers to a NamesList.txt alias.

The ucd.14.0.0.tsv file is constructed using a NodeJS script from the following sources:

It is read and reconstituted by the "LoadDatabaseFileAsync()" function of universe.js. Notice that the final action of that function is to store the data in an IndexedDB database. This allows the JavaScript to test for the existence of that data in subsequent page reloads, obviating the need to fetch and decode each time. This saves several seconds each time. See "IndexedDatabaseGet()" and "IndexedDatabasePut()" in universe.js.

The downside of using this client-side caching is that it takes up 260MB of disk space:


We rely on the browser (Chrome, in this case) to manage the IndexedDB storage correctly, but even if the cache is purged, we fall back over to parsing the TSV again.

Monday, 13 September 2021

Machin Postage Stamps 2

Well, I thought I was being clever, didn't I? Using WebP images for Machin stamps. Alas, WebP has only recently been supported by Apple's Safari, so the web page didn't work at all on an older model iPad.

My original HTML was simply:

<img id="picture" class="shadow" src="machin.webp" />

And the source image path was accessed from JavaScript via:

document.getElementById("picture").src

The fix from Brett DeWoody is actually quite elegant. Change the HTML to use picture source sets:

<picture class="shadow">
    <source srcset="machin.webp" type="image/webp" />
    <img id="picture" src="machin.png" />
</picture>

And use the following to interrogate the chosen path after load:

document.getElementById("picture").currentSrc

Tuesday, 10 August 2021

Hexworld 3: Compression

Last time, we encoded our 311,040 world map hexel indices as a 622,080-character hexadecimal string as a way of embedding the data in an ASCII JavaScript file. We could use the following script:

hexworld(buffer => {
  const DATA = "00000000...ffffffff";
  buffer.set(DATA.match(/../g).map(x => parseInt(x, 16)));
});

This calls a function hexworld(), defined elsewhere, that takes as its only parameter a decompression function that fills in a pre-allocated Uint8Array buffer with the hexel indices. The "decompression" above consists of splitting the long hexadecimal string into 2-character segments and converting these to numeric values.

We can achieve better compression by using the built-in atob() function:

hexworld(buffer => {
  const DATA = "AAAAAAAA...////////";
  buffer.set(Array.from(atob(DATA), x => x.charCodeAt()));
});

The DATA string is reduced in size from 622,080 ASCII characters to 414,720.

If we look at the map itself, we see that it's ripe for run-length encoding or the like.

One possibility is the LZW compression algorithm. I tried this and came up with data plus decompressor what weigh in at under 32KB of ASCII:

function lzw(src) {
  var dic = Array.from({ length: 256 }, (_, i) => [i]);
  var key, dst = [];
  for (var val of src) {
    var nxt = dic[val] || [...key, key[0]];
    if (key) {
      dic.push([...key, nxt[0]]);
    }
    key = nxt;
    dst.push(...key);
  }
  return dst;
}
hexworld(buffer => {
  const DATA = "00007407...cb8cc80f";
  buffer.set(lzw(DATA.match(/.../g).map(x => parseInt(x, 36))));
});

The lzw() function above decompresses an array of integers into an array of bytes. For completeness, here's the corresponding compression function:

function compress(src) {
  const chr = String.fromCharCode;
  var dic = {};
  var idx = 0;
  do {
    dic[chr(idx)] = idx;
  } while (++idx < 256);
  var dst = [];
  var pre = "";
  for (var val of src) {
    var key = pre + chr(val);
    if (key in dic) {
      pre = key;
    } else {
      dst.push(dic[pre]);
      dic[key] = idx++;
      pre = chr(val);
    }
  }
  dst.push(dic[pre]);
  return dst;
}

In our Hexworld case, the LZW dictionary constructed during compression has about 10,000 entries, so those indices can be stored as three base-36 digits. This is a general-purpose compression scheme, so could a more tailored algorithm produce better results? Remember, we're aiming for something less than 16KB.

One solution I looked at was encoding the data as a sequence of 4-bit nybbles:

hexworld(buffer => {
  const DATA = "8bxQEhER...ER8NEw==";
  var input = Array.from(atob(DATA),
    x => x.charCodeAt().toString(16).padStart(2, "0")).join("");
  var i = 0;
  function read(n) {
    i += n;
    return parseInt(input.slice(i - n, i), 16);
  }
  var land = 0;
  var next = 0;
  var o = 0;
  while (o < buffer.length) {
    var n = read(1);
    switch (n) {
      case 0:
        land = next = read(2);
        continue;
      case 12:
        n = read(1) + 12;
        break;
      case 13:
        n = read(2) + 28;
        break;
      case 14:
        n = read(3) + 284;
        break;
      case 15:
        n = read(4) + 4380;
        break;
    }
    buffer.fill(next, o, o + n);
    o += n;
    next = next ? 0 : land;
  }
});

The algorithm is as follows:

  1. Read the next nybble in the stream
  2. If the nybble is 0, the next two nybbles contain the next "land" hexel index and go back to Step 1
  3. If the nybble is between 1 and 11 inclusive, it is used as the count below
  4. If the nybble is 12, the count to use is the value in the next nybble plus 12
  5. If the nybble is 13, the count to use is the value in the next two nybbles plus 28
  6. If the nybble is 14, the count to use is the value in the next three nybbles plus 284
  7. If the nybble is 15, the count to use is the value in the next four nybbles plus 4380
  8. If the last set of values output were "land", write out "count" indices of "water" (0)
  9. Otherwise, write out "count" indices of the current "land"
  10. Go back to Step 1
This algorithm assumes there are never more than about 70,000 value repetitions, which is more than enough for our map. It weighs in at under 19KB of ASCII text, which is getting very close to our goal. One thing to notice is that the nybbles are encoded into ASCII via atob/btoa which use base-64 and are therefore relatively inefficient.

My final attempt (the one that achieved my goal of data plus decompressor within 16KB of ASCII) uses base-95:

hexworld(buffer => {
  const DATA = ')  )gD}l...$)wA#).n';
  for (var d = Array.from(DATA, x => 126 - x.charCodeAt()),
    i = 0, o = 0, a = 0, b = 0, c = 0; DATA[i]; c = c ? 0 : a) {
    var v = d[i++];
    if (v >= 90) {
      v -= 88;
      while (--v) {
        d[--i] = 0;
      }
    }
    var n = ~~(v / 5);
    if (v %= 5) {
      c = v---4 ? v * 95 + d[i++] : b;
      b = a;
      a = c; 
    }
    switch (n++) {
      case 17:
        n = d[i++] * 95 + 112;
      case 16:
        n += d[i++] - 1;
        break;
    }
    buffer.fill(c, o, o + n);
    o += n;
  }
});

This is slightly golfed, so I'll clarify it below.

[In a perverse way, I quite like the expression "v---4" which is shorthand for "(v--) !== 4"]

The data is encoded in base-95: the number of printable ASCII characters. This means that backslashes and quotes need to be escaped within the string. The choices of (a) using single quotes (as opposed to double- or backquotes) and (b) storing values in reverse order ("126 - x" versus "x - 32") minimize the number of escape backslashes needed for our particular map data.

Lead base-95 values are split into two values: low (0 to 4 inclusive) and high (0 to 18 inclusive). The high value holds the repetition count:

  • High values from 0 to 15 inclusive imply repetition counts from 1 to 16,
  • Sixteen takes the next base-95 value to produce a repetition counts from 17 to 111,
  • Seventeen takes the next two base-95 values to produce a repetition counts from 112 to 9136,
  • Eighteen is a special "repeated zero" value that simulates a lead zero repeated 2 to 6 times based on the low value.
The low value (except for when the high value is eighteen) encodes what should be repeated:
  • Zero alternates between the last land index and the water index (0),
  • One sets the land index to the next base-95 value,
  • Two sets the land index to the next base-95 value plus 95,
  • Three sets the land index to the next base-95 value plus 190,
  • Four alternates between the last land index and the previous land index specified.

This rather ad hoc algorithm is based on the following observations:

  1. Water (hexel index zero) is common throughout the whole map,
  2. If the last land hexel was a particular index, it is likely that the next land will be the same index,
  3. Due to the staggered hexel layout, land indices quite often alternate with either water or the previous land index

I'm sure there's plenty more mileage using bespoke compression, but after a certain point it becomes unhealthy. For example, one option I didn't pursue is re-ordering the country-to-hexel index allocation in order to improve compression. This smells suspiciously like super-optimisation.

One last avenue to explore for compressing the hexel map is the recent JavaScript Compression Stream API, but that's for another time.

        Friday, 6 August 2021

        Hexworld 2: Encoding

        As mentioned in the first part, the map of Hexworld consists of a 864-by-360 staggered grid of hexagons. Each hexagon (hexel) holds an 8-bit index, so the whole thing fits into about 300KB of binary data. It can be stored as an 8-bit PNG weighing in at about 13½KB:

        Greyscale optimisations and PNG Crush will reduce this to about 11½KB. However, reading the pixel index values back using JavaScript so that we can reconstruct the hexel data is problematic. One would think you could simply do the following:

        • Encode the greyscale PNG as a data URL,
        • Load it into an offscreen img element,
        • Draw it into an offscreen canvas element, 
        • Capture the pixel data via getImageData() element, then
        • Reconstruct the indices.

        The two main stumbling blocks are:

        1. Loading images (even data URLs) is an asynchronous activity.
        2. Colour space management typically applied a "gamma" correction which means the greyscale RGB values are not one-to-one with the original indices.
        The first problem can be solved with some truly horrific fudging:

            var done = false;
            img.onload = () => {
              process(img);
              done = true;
            };
            img.src = dataURL;
            while (!done) {
              await new Promise(r => setTimeout(r, 100));
            }

          The second issue cannot be solved without using a third-party JavaScript library (like pngjs) to decode the raw PNG data and extracting the indices directly.

          Another option is to encode the raw pixel data (as opposed to the PNG) into the JavaScript script itself. For example:

            function decode_hex(buffer) {
              const HEXWORLD = /* hexadecimal string */;
              buffer.set(HEXWORLD.match(/../g).map(x => parseInt(x, 16)));
            }

          This function takes a 311,040-element Uint8Array (that's 864 times 360) as an argument and fills it with the indices. Unfortunately, the hexadecimal string is over 600,000 characters long!

          If we limit ourselves to ASCII JavaScript, can we do better?

          Friday, 30 July 2021

          Hexworld 1: World Map

          I've long been fascinated by hexagonal grids. And maps. So it was probably only a matter of time before I created a world map based on a hexagonal grid: Hexworld.

          I'm certainly not the first to try this, but most of the other attempts I've seen are either low resolution or do not try to capture national boundaries.

          The obvious way of generating such a map is to take an existing one (in this case, an equirectangular projection) and post-process it. I started down this track but quickly discovered that it produces ugly results. As cartographers through the ages have discovered, making political maps (as opposed to maps for navigation) is more of an art-form that a science. So I dusted off my faithful copy of Paint Shop Pro 5 and hand-filled the 100,000 or so hexagons that make up the land masses:


          I initially coloured the regions using five colours (red, green, blue, yellow and pink) and then used a Wikimedia four colour map as the basis for whittling it down to four.

          With the seas coloured cyan (hue 180°), it made sense to use equidistant hues for the remaining four colours: red (324°), green (108°), blue (252°) and yellow (36°).

          Each "hexel" is given one of 241 unique 8-bit indices:

          • One index (0) is reserved for water,
          • 193 indices cover the current full UN member states,
          • 2 indices cover the UN observer states (Vatican and Palestine),
          • 6 indices cover disputed territories (Western Sahara, Taiwan, Abkhazia, Crimea, Kosovo and South Ossetia),
          • 28 indices cover overseas territories belonging to UN states (e.g. Falklands), and
          • One index (255) for Antarctica.

          The lowest two bits of the index encodes the region's colour; except for 0 and 255, which are treated specially. The world is indeed four-colourable!

          Obviously, there's no real advantage in rendering a world map using hexagons instead of rectangular pixels or arbitrary polygons. But it's a fun exercise.


          Friday, 26 March 2021

          Colour Pick 1: Goldenrod

          As part of my investigation into colour names, I've been writing a lot of JavaScript code to perform colour space transformations.

          When I started the colour pick work, I did the "right thing" and refactored all the colour-related functionality into a library. The library is named "goldenrod" after the X11 colour of that name (#DAA520).

          Solidago virgaurea minuta "Dwarf Goldenrod"

          The library is just a plain old bunch of functions and lists organised into three files:

          goldenrod.js

          This script contains the main entry points exposed as fields of the global object "chilliant.goldenrod". They are primarily conversion functions with signatures of the following form:

          float[3] chilliant.goldenrod.{source}_to_{destination}(float value[3])

          Above, "{source}" and "{destination}" are colour space tags as listed in the following table:

          TagColour Spacevalue[0]value[1]value[2]
          sRGBsRGBred
          0.0 to 1.0
          green
          0.0 to 1.0
          blue
          0.0 to 1.0
          HSVHSV
          a.k.a. HSB
          hue
          0.0 to 360.0 degrees
          saturation
          0.0 to 1.0
          value
          0.0 to 1.0
          HSLHSLhue
          0.0 to 360.0 degrees
          saturation
          0.0 to 1.0
          lightness
          0.0 to 1.0
          HWBHWBhue
          0.0 to 360.0 degrees
          whiteness
          0.0 to 1.0
          blackness
          0.0 to 1.0
          CIEXYZCIE 1931 XYZX
          0.0 to 1.0
          Y luminance
          0.0 to 1.0
          Z
          0.0 to 1.0
          CIExyYCIE 1931 xyYx
          0.0 to 100.0
          y
          0.0 to 100.0
          Y luminance
          0.0 to 100.0
          CIELabCIE 1976 L*a*b*L* lightness
          0.0 to 100.0
          a*
          ~ -100.0 to 100.0
          b*
          ~ -100.0 to 100.0
          CIELuvCIE 1976 L*u*v*L* lightness
          0.0 to 100.0
          u*
          ~ -200.0 to 200.0
          v*
          ~ -200.0 to 200.0
          CIELChabCIE 1976 L*C*habL* lightness
          0.0 to 100.0
          C* chroma
          ~ 0.0 to 100.0
          hab hue
          0.0 to 360.0 degrees
          CIELChuvCIE 1976 L*C*huvL* lightness
          0.0 to 100.0
          C* chroma
          ~ 0.0 to 100.0
          huv hue
          0.0 to 360.0 degrees

          Note that for conversions to and from the hexacone colour spaces (HSV/HSL/HWB) the tag "RGB" is used instead of "sRGB" to emphasize the fact that no linearization or delinearization is performed. Thus, the name "chilliant.goldenrod.RGB_to_HSL" is used instead of "chilliant.goldenrod.sRGB_to_HSL".

          All conversions assume a standard D65 illuminant with a two-degree observer angle.

          At the time of writing, not all permutations of source and destination are directly supported, but it's a trivial change to add the missing "chains".

          The additional members of "chilliant.goldenrod" are listed below.

          bool chilliant.goldenrod.within_sRGB(any srgb)

          A function that returns true if, and only if, 'srgb' is an array of at least three numbers all between 0.0 and 1.0 inclusive.

          float[3] chilliant.goldenrod.force_sRGB(any srgb)

          Forces 'srgb' to be a valid sRGB triplet with each element between 0.0 and 1.0. If any channel is greater than one, the whole triplet is scaled back. If 'srgb' cannot be interpretted as a valid triplet, black [0,0,0] is returned.

          float chilliant.goldenrod.deltaE1994(float ref[3], float lab[3])

          Computes the CIELAB ΔE*(1994) colour difference between the two CIEL*a*b* colours. Note that this metric is not symmetric.

          float chilliant.goldenrod.deltaE2000(float ref[3], float lab[3])

          Computes the CIELAB ΔE*(2000) colour difference between the two CIEL*a*b* colours.

          string chilliant.goldenrod.sRGB_to_HEX(float srgb[])

          Converts the sRGB triplet (or quartet with alpha) 'srgb' to a hexadecimal colour in the form "#rrggbb" or "#rrggbbaa".

          float[3] chilliant.goldenrod.HEX_to_sRGB(string hex)

          Converts an hexadecimal colour string in the form "#rgb", "#rgba", "#rrggbb" or "#rrggbbaa" into an sRGB triplet. Any alpha component is ignored.

          string chilliant.goldenrod.version

          A string field containing the goldenrod library version in semver format, e.g. "1.0.0".

          util.js

          This script contains the guts of the functionality of goldenrod exposed as members of the object "chilliant.goldenrod.util". A large portion is based on the formulae outlined on Bruce Lindbloom's excellent site and should be fairly self-explanatory.

          data.js

          This script contains useful datasets exposed as members of the object "chilliant.goldenrod.data".

          float[][] chilliant.goldenrod.data.cie1931_xyy

          The CIE 1931 2-degree chromaticity xyY coordinates from UCL Colour & Vision Research Laboratory. The columns are:

          1. Wavelength in nm,
          2. CIE xyY x-ordinate,
          3. CIE xyY y-ordinate, and
          4. CIE xyY Y luminance.

          object[] chilliant.goldenrod.data.css4

          The CSS 4 colour names taken from Mozilla.

          any[] chilliant.goldenrod.data.centore

          The 267 ISCC-NBS centroids from Paul Centore's site in index order. The columns are:

          1. Name (string),
          2. Munsell colour (string),
          3. Red (int),
          4. Green (int),
          5. Blue (int),
          6. sRGB hexadecimal (string).

          Note that seven of the centroids are outside the sRGB gamut so are missing the final four columns. It would be nice to have the out-of-gamut values for red/green/blue because those points could still be matched via (for instance) Euclidean distance searchers. However, I have been unable to recreate Paul's methodology to fill in the blanks.

          object chilliant.goldenrod.data.cns

          A 627-entry map between the Color Naming System and sRGB values in the form:

          {
            "black": {hex: "#000000", srgb: [0,0,0]},
            ...
            "yellowish orange": {hex: "#CC9333", srgb: [0.8,0.575,0.2]}
          }

          This is a "best guess" at the values based on "A New Color-Naming System for Graphics Languages".

          See "generateCNS()" for details.

          any[] chilliant.goldenrod.data.iscc

          The 260 ISCC-NBS centroids from "data.centore" that are within the sRGB gamut, formatted like "data.cns".

          See "generateISCC()" for details.

          Unit Tests

          The goldenrod library has a minimal unit test suite. The values were checked against Bruce Lindbloom's colour calculator, amongst other tools.

          Friday, 3 July 2020

          Arm Clock

          Seven-segment displays have long been used in digital clocks as they are a natural fit for LCD and LED technologies. There are even electro-mechanical displays for larger applications. However, for some reason I wondered if there was an alternative to flipping each segment in a binary fashion.

          The ten digits are typically rendered in the following fashion:


          If we want to produce these shapes using articulated arms (with each black segment being a "bone" and each grey dot being a "joint") we quickly see two constraints:
          1. There must be at least seven bones.
          2. The "root" of any arm must be located at one of the three right-hand pivot points.
          If we further limit ourselves to the minimum number of bones (seven) it becomes apparent that we need at least two arms: try to manipulate a single seven-bone arm to make the "8" digit without breaking it.

          I chose to use two arms: one rooted in the top-right corner with four bones (red), the other rooted at the middle-right pivot with three bones (blue):


          By manipulating the angles between the bones, these two arms can fold themselves into any of the shapes making up the ten digits above:


          If we wish to physically build this arrangement, there are two main problems to overcome:
          1. Bone are sometimes coincident (the joints fold back on themselves 180 degrees)
          2. The joint motors (or linkages) have to somehow fit in the arm bones
          But these are merely robotics issues.

          So we can theoretically create the shapes of digits to form a clock. But can we create some feasible transitions to animate it? If we assume a twenty-four hour clock, it turns out there are thirteen transitions we need to concern ourselves with:
          1. "0" → "1"
          2. "1" → "2"
          3. "2" → "3"
          4. "3" → "4"
          5. "4" → "5"
          6. "5" → "6"
          7. "6" → "7"
          8. "7" → "8"
          9. "8" → "9"
          10. "9" → "0"
          11. "2" → "0" (e.g. "23:59:59" to "00:00:00")
          12. "3" → "0" (e.g. "23:59:59" to "00:00:00")
          13. "5" → "0" (e.g. "23:59:59" to "00:00:00")
          By manually fettling the angles of the arm joints, I came up with a fairly pleasing series of transitions that don't flail the arms too much, clattering them into adjacent digits.

          The resulting web page uses CSS transitions to animate an inline SVG. Both the CSS rules and SVG elements are created programmatically in a fairly concise JavaScript script.


          Monday, 18 May 2020

          United Nations Flags

          There are 193 full members of the United Nations. I've put together a web page animating between those flags based on the SVG images in Wikimedia Commons.


          The process was:

          1. Curate the 193 state flags plus the flag of the UN itself.
          2. Construct 194 approximations of those flags using JavaScript and HTML canvas elements.
          3. Reorder those approximations into a loop of 194 transitions based on similarity.
          4. Encode the 194 animations.
          5. Create a web page to allow the user to explore the animations.
          Of course, there are 194! ÷ 2 animations needed to get between any two flags directly, but that's such an absurd number I didn't even think about trying. I did think about creating "shortcuts" between flags in the loop and minimising the number of animations between two arbitrary flags to, say, 10, but this is still a huge amount of work. I'll leave it as an exercise for the reader to work out the total number of animations required to reduce the maximum number of hops to "N".

          In an ideal world, I'd animate the high-quality SVG images themselves; but that's also a task for another day ... if ever.

          Wednesday, 30 May 2018

          egg Chronology of Computer Languages 4

          I couldn't resist re-visiting this after the Bank Holiday weekend.

          After a bit more research, the type of diagram I'm actually looking for for COCL is a layered graph drawing, also known as a Sugiyama diagram. As suspected, it's a difficult problem to lay out these diagrams but there are some well-known heuristics. Placing a descendant at an x-position that is an average (mean, median, etc.) of its ancestors' x-positions helps reduce edge crossings. It also seems to organise the programming languages of COCL into related groups.

          So I did a bit more fettling of the box-drawing version of the data-set and then produced a colourful SVG version based on that layout data. The only slight wrinkle was getting the arcs looking good when there isn't enough room for a full ninety-degree elbow. See the purple link between "Lisp" and "Logo" below:

          I didn't animate the final SVG because it's just too expensive computationally and there's no scope for caching frames like I did with the canvas-based "waterfall" version.


          The opacity of each connection is a function of the time in years between the appearance of the ancestor and the descendant. I'm not sure it's strictly meaningful, but it adds variety.

          Saturday, 26 May 2018

          egg Chronology of Computer Languages 3

          As one last task, I looked at producing a more traditional "flow chart" from the COCL data-set. Yet again, it turned out to be surprisingly difficult.

          A Sankey diagram is a close match for what I'm looking for: an ordered DAG of ancestors and descendants. But, in all the little tools I briefly looked at, the layouts of the final charts leave a lot to be desired.

          I started work on a basic network layout engine in C++ but quickly came to a dead end: the number of permutations for the node positioning alone is in the order of 1e+96 which is just not tractable. And this doesn't even take into consideration the edge routing.

          I finally plumped for two tools (one in C++ and the other in JavaScript) to semi-automate the layout and then continually fettled it by hand (for instance, lining up the C and Pascal families of languages vertically) until it was relatively compact.

          The final result (bottom) displays the diagram using fixed-width, box-drawing characters:



          Wednesday, 23 May 2018

          egg Chronology of Computer Languages 2

          Another visualisation I tried with the COCL data-set was a chord diagram (revamped from the cocktail version I did a couple of years ago). Apart for realising how bad my JavaScript was back then, I discovered that chord diagrams do not make the "direction" of relationships obvious. I've added a bit of animation to try to remedy that when you hover over a language name.
          I find this visualisation much more aesthetically pleasing that the rather workman-like "waterfall". The fact that the chronology is clock-like is also rather agreeable.

          I turns out that drawing "marching ant" lines is quite expensive, even in modern browsers; so I re-vamped the "waterfall" diagram from yesterday to cache frames. It means that the animation is a bit jittery for the first few seconds after landing on the web page, but quickly becomes very smooth.

          Click here for the interactive versions.

          Tuesday, 22 May 2018

          egg Chronology of Computer Languages 1

          I was thinking about "curly brace languages" in the context of egg at the weekend, and remembered a graphic I'd seen of the "family tree" of computer programming languages. I googled around and found the images I'd seen at the turn of the millennium (e.g. here and here), but nothing from the last ten years. Strange, I thought; I'll have a go at either updating or redrawing a tree.

          It quickly became apparent why I couldn't find such a chart.

          I started by manually scraping the data from the Wikipedia pages and producing a spreadsheet of dependencies with:

          • Language name
          • Year it first appeared
          • Ancestors (prior languages that are said to have influenced it)
          • Link to Wikipedia page
          That dataset (COCL: A Chronology of Computer Languages) is stored as JavaScript here. There are over sixty data points ranging from FORTRAN (1957) to Swift (2014). The choice of points is fairly subjective, the data is direct from Wikipedia.

          Then I tried to draw the recombining tree (DAG) by hand. I got this far and gave up:


          Even just concentrating on a subset (the "curlies") didn't help much:


          The problem is that I'm trying to get the ordering of the chronology fixed in one of the axes (the y-axis in this case: oldest at the top, newest at the bottom). I've tried curved lines and even duplicated nodes to try to minimise the number of crossing edges. I've tried putting the oldest languages in the centre of the canvas and working outwards, like a bulls-eye. But nothing seems to work. I'm sure there are technique and/or software out there that can solve this problem, but the linear ordering seems to be beyond the ones I briefly looked at.

          So I decided to throw a bit of JavaScript at it. It turns out it's easy to get ugly results from the dataset; the trick is to make it pretty.

          My first attempt is an animated waterfall chart:


          It's not very elegant, but does give some useful insights into popular ancestors. Everyone seems to want Lisp in their language's DNA these days.

          Click here for the interactive version.

          Friday, 23 March 2018

          A Prime Example of JavaScript Golf

          This is why you shouldn't play JavaScript golf:

          for(a=[1];!a[999];)/^(11+)\1+$/.test(a+=1)||print(a.length)

          Sunday, 27 November 2016

          Lexicon 2

          To finish off the discussion of my Lexicon demo, I'll outline the in-memory data structure used to store the dictionary.

          In the first part, I described how the lexicon is stored trivially-compressed for transmission "over the wire". The words are then expanded in memory into a form that makes searching simple and efficient.

          The main data structure is a four-dimensional array of JavaScript objects named "Lexicon.byRaritySubsetLength":

          1. The first index is an integer rarity between one and five inclusive: one means "not very rare", whereas five means "esoteric".
          2. The second index is an integer bit-field (one to seven inclusive) which encodes which dictionaries the corresponding list is part of: TWL06, SOWPODS and SCOWL.
          3. The third index is the integer length of the word (two to fifteen inclusive).
          4. The fourth index is an integer index into a list sorted alphabetically (starting from zero).
          By default, the demo looks at all rarities and word lengths for the SOWPODS lexicon. This means that without changing the criteria, when matching words, the client must look through 5 * 4 * 14 = 70 lists of words.

          Each word entry is a JavaScript object of the following form:

              word : string
              rarity : integer
              subset : integer
              mask : integer

          The first three fields contain the uppercase word, rarity index and lexicon subset mask. The last field is used when searching for anagrams. It is a bit-field that encodes which letters are contained within the word: 1 for "A", 2 for "B", 4 for "C", 8 for "D", etc.

          For instance, to find anagrams for "WORDS" in SOWPODS, the client needs to search through only 20 lists of words: five rarities (1 to 5), four lists for SOWPODS and one word length (5). These lists contain 12,478 entries which can be scanned quickly by looking for those that have a "mask" with the bits for "D", "O", "R", "S" and "W" all set. It will typically come up with the solution ("SWORD" and "DROWS") within a couple of milliseconds.

          Saturday, 16 July 2016

          Blok Clok

          When I was a boy, I was given a curious present: a perpetual desk calendar made from wooden cubes:
          You can still buy them, so there must be some enduring appeal. The calendar interested me because of a strange quirk that isn't immediately obvious.

          There are four blocks: one for the day of the week (with seven labels), two for the day of the month (1 to 31) and one for the month (with twelve labels). The "weekday" and "month" blocks are easy to label. For example, two months on each face fills the "month" block and, providing the container covers up the lower half of the block, all is peachy.

          The two date blocks are a little more involved. Dates run from "01" to "31":

          01,02,03,04,05,06,07,08,09,10,  
          11,12,13,14,15,16,17,18,19,20,  
          21,22,23,24,25,26,27,28,29,30,31

          By inspection, we see that the only digits that appear twice on a single date are "1" and "2". However, if you sit down with a pencil and paper, it quickly becomes apparent that you'll also need two zeroes. That means that the following digits are required:

          0,0,1,1,2,2,3,4,5,6,7,8,9

          But, hang on! That's thirteen digits. Two cubes have only twelve faces between them. How do they fit? The clever "quirk" is that "6" and "9" occupy the same face; you simply flip the block around 180 degrees. This gives you the following faces for the two blocks:

          0,1,2,3,4,5
          0,1,2,6,7,8

          This arrangement allows to you represent all integers between "00" to "32" inclusive; just enough! It's deceptively clever. And that's probably why I like my wooden perpetual calendar so much.

          Fast forward several years, if not decades, and my current fascination with clocks led me to consider whether you could tell the time with a similar arrangement. I knew representing the hours would not be a problem: as we've seen, two blocks can represent all integers between "00" to "23" inclusive for a twenty-four-hour clock. But representing minutes is harder.

          It is fairly obvious that you need at least three blocks to represent all integers between "00" to "59" inclusive. But are three sufficient? It turns out that they are; you don't even need to use the upside-down "9" trick. The solution uses an additional cube to display a colon between the hours and minutes digits. For example:

          23:59

          The "tens minutes" digit takes up a single block: "0" to "5" inclusive. So the problem simplifies to trying to represent the "units minutes" digit ("0" to "9") and a colon with two blocks. The following labelling is one solution:

          :,0,1,2,3,4
          :,5,6,7,8,9

          Using three blocks to represent minutes between ":00" to ":59" inclusive can be repeated for the seconds. This gives us eight blocks:

            hours-a    0,1,2,3,4,5
            hours-b    0,1,2,6,7,8
          minutes-a    :,0,1,2,3,4
          minutes-b    0,1,2,3,4,5
          minutes-c    :,5,6,7,8,9
          seconds-a    :,0,1,2,3,4
          seconds-b    0,1,2,3,4,5
          seconds-c    :,5,6,7,8,9

          Not only do the blocks need to rotate to any of their six faces (and in the case of "hours-b", the "6" sometimes has to be flipped to become a "9") but pairs of blocks also have to be swapped periodically:

          hours-a <=> hours-b
          minutes-a <=> minutes-c
          seconds-a <=> seconds-c

          Some extra fettling is needed to make the rotations aesthetically pleasing, but the result is a twenty-four-hour clock that twists and turns at a fair old lick.