Computational Classnotes

How Mochi and Onigiri became 3D, in the Wolfram Language

The same two VRM avatars, built again with the Python code replaced by Wolfram Language code, stage by stage, with figures drawn by Wolfram itself

By Dara O Shayda and Hikari Noor Hoshino (星野ヌール)
AI System Programming Laboratory, Computational Classnotes · 3 December 2026

Made at the owner’s request of 3 December 2026, 22:24 (“I like to know if you could repeat this in wolfram language, meaning the python code replaced by Wolfram and for that add .nb .pdf and .md”). The notebook: tools/ff_makevrm.nb, with its printout tools/ff_makevrm.pdf. The avatars it writes: art/vrm/wolfram/mochi.vrm and art/vrm/wolfram/onigiri.vrm. The Python original and its write-up: tools/make-vrm.py, how-mochi-and-onigiri-became-3d.md. Every function has its page in the Pyon manual, section 3vrmwl.

Contents

  1. Why a Wolfram version, and how to run it
  2. Stage 1 · Colours
  3. Stage 2 · The building blocks
  4. Stage 3 · Parts
  5. Stage 4 · The skeleton, and Stage 5 · the skin
  6. Stage 6 · Mochi and Onigiri, part by part
  7. Stage 7 · The expressions
  8. Drawing them in Wolfram
  9. Stage 8 · Writing the file
  10. Stage 9 · Checking: Wolfram against Python
  11. Python and Wolfram side by side

Figures

  1. Figure WL-1 · The building blocks, drawn by Wolfram
  2. Figure WL-2 · Mochi, part by part, drawn by Wolfram
  3. Figure WL-3 · Onigiri, part by part, drawn by Wolfram
  4. Figure WL-4 · The skeletons, drawn by Wolfram
  5. Figure WL-5 · The skin weights, drawn by Wolfram
  6. Figure WL-6 · The expressions, drawn by Wolfram
  7. Figure WL-7 · Both files in the real VRM loader, and their difference

1. Why a Wolfram version, and how to run it

  1. The same avatars, a second language. The Python of tools/make-vrm.py is rewritten here function by function in the Wolfram Language: the same formulas, the same order of work, the same file at the end. Nothing in a .vrm file depends on the language that wrote it: it is numbers in a buffer and a JSON description of them.
  2. What Wolfram changes. Arrays are native, so NumPy is not needed; a part is an Association; a creature is an Association of parts, bones and expressions; the binary file is joined from ByteArrays made by ExportByteArray, with no struct; and the shapes can be drawn in the notebook itself with Graphics3D, at every stage, without a browser (section 8).
  3. The notebook is tools/ff_makevrm.nb. Open it fresh and evaluate it from top to bottom (Evaluation › Evaluate Notebook). It defines every function, draws the figures, and writes art/vrm/wolfram/mochi.vrm and onigiri.vrm beside the Python ones, with the same thumbnails. It touches nothing in the cloud and deletes nothing.
  4. Names. Every function of ours begins with vrm and a lower-case letter, so that it can never be confused with Wolfram’s own functions, which begin with a capital (vrmSphere[ ] is ours, Sphere[ ] is Wolfram’s). Each code cell begins with its number, (*1*) to (*17*), so that a cell can be named in a request.
  5. The cells below are the notebook’s cells, in order, word for word.

2. Stage 1 · Colours

  1. Where the notebook is. The first cell finds the repository’s folder from the notebook’s own place (tools/), so that the files are written beside the Python ones wherever the repository is kept.
  2. vrmLin[ ] turns a drawn colour ("#f3e6d3", sRGB) into linear light, as glTF expects; vrmDarker[ ] makes the shade side of a toon material. vrmLinspace[ ] gives evenly spaced numbers, as NumPy’s linspace does, for the smile and the closed eyes.
(*1*)
(* How Mochi and Onigiri became 3D, in the Wolfram Language: ff_makevrm.nb. By Dara O Shayda and Hikari Noor Hoshino, AI System Programming Laboratory. *)
(* (c) Computational Classnotes, CC BY-NC-SA 4.0. Stage 1: colours. *)
vrmRoot = Quiet[Check[ParentDirectory[NotebookDirectory[]], Directory[]]];
vrmLin[hex_String, a_ : 1.] := Append[Map[If[# <= 0.04045, #/12.92, ((# + 0.055)/1.055)^2.4] &, N[FromDigits[#, 16]/255] & /@ StringPartition[StringDrop[hex, 1], 2]], a];
vrmDarker[hex_String, f_ : 0.82] := "#" <> StringJoin[IntegerString[Floor[FromDigits[#, 16] f], 16, 2] & /@ StringPartition[StringDrop[hex, 1], 2]];
vrmLinspace[a_, b_, n_Integer] := Append[Table[a + i ((b - a)/(n - 1)), {i, 0, n - 2}], b];
{vrmLin["#f3e6d3"], vrmDarker["#f3e6d3"]}

3. Stage 2 · The building blocks

  1. Every shape is a list {v, n, i}: the vertices’ positions, their unit normals, and the triangles as triples of vertex numbers. The vertex numbers count from 0, as glTF counts; Wolfram counts list positions from 1, so + 1 appears wherever a triangle picks its corners out of a list.
  2. vrmRotTo[ ] is a rotation whose local +Z points along a direction: it lays an eye or a cheek on the curved body.
  3. vrmSphere[ ] is a grid of slices and rings; vrmEllipsoid[ ] stretches, turns and moves it, stretching the normals by the inverse of the radii; vrmTube[ ] runs a tube along a path with a parallel-transport frame, so that it never twists; vrmLathe[ ] turns a profile like a potter’s wheel (the ears); vrmSmooth[ ] draws a Catmull-Rom curve through a few points (the tail); vrmVertexNormals[ ] sums each triangle’s normal into its three corners, for a surface whose normals must be worked out again (Onigiri’s body).
(*2*)
(* Stage 2: the building blocks. Each returns {v, n, i}: positions, unit normals, triangles (vertex numbers from 0, as glTF counts). *)
vrmRotTo[zAxis_] := Module[{z = Normalize[N[zAxis]], up, x},
  up = If[Abs[z[[2]]] < 0.95, {0., 1., 0.}, {0., 0., 1.}];
  x = Normalize[Cross[up, z]];
  Transpose[{x, Cross[z, x], z}]];
vrmSphere[nu_ : 40, nv_ : 24] := Module[{v, i},
  v = Flatten[Table[With[{th = N[Pi] j/nv, ph = 2 N[Pi] k/nu}, {Sin[th] Sin[ph], Cos[th], Sin[th] Cos[ph]}], {j, 0, nv}, {k, 0, nu}], 1];
  i = Reap[Do[With[{a = j (nu + 1) + k, b = j (nu + 1) + k + nu + 1},
      If[j > 0, Sow[{a, b, a + 1}]]; If[j < nv - 1, Sow[{a + 1, b, b + 1}]]], {j, 0, nv - 1}, {k, 0, nu - 1}]][[2, 1]];
  {v, v, i}];
vrmEllipsoid[c_, r_, rot_ : IdentityMatrix[3], nu_ : 40, nv_ : 24] := Module[{v, n, i},
  {v, n, i} = vrmSphere[nu, nv];
  {(# + c) & /@ ((r # & /@ v) . Transpose[rot]), Normalize /@ ((#/r & /@ n) . Transpose[rot]), i}];
vrmTube[path0_, rad0_, sides_ : 12, caps_ : True] := Module[{path = N[path0], n, rad, t, ref, prev = None, nrm, b, d, v = {}, nr = {}, idx, e},
  n = Length[path]; rad = If[ListQ[rad0], N[rad0], ConstantArray[N[rad0], n]];
  t = Normalize /@ Table[Which[k == 1, path[[2]] - path[[1]], k == n, path[[n]] - path[[n - 1]], True, (path[[k + 1]] - path[[k - 1]])/2], {k, n}];
  ref = If[Abs[t[[1, 3]]] < 0.9, {0., 0., 1.}, {1., 0., 0.}];
  Do[nrm = If[prev === None, Normalize[Cross[t[[k]], ref]], Normalize[prev - (prev . t[[k]]) t[[k]]]];
    prev = nrm; b = Cross[t[[k]], nrm];
    Do[d = Cos[2 N[Pi] s/sides] nrm + Sin[2 N[Pi] s/sides] b; AppendTo[v, path[[k]] + rad[[k]] d]; AppendTo[nr, d], {s, 0, sides}], {k, n}];
  idx = Flatten[Table[With[{a = k (sides + 1) + s}, {{a, a + 1, a + sides + 1}, {a + 1, a + sides + 2, a + sides + 1}}], {k, 0, n - 2}, {s, 0, sides - 1}], 2];
  If[caps, Do[e = vrmEllipsoid[path[[end]], ConstantArray[rad[[end]], 3], IdentityMatrix[3], sides, 8];
      idx = Join[idx, e[[3]] + Length[v]]; v = Join[v, e[[1]]]; nr = Join[nr, e[[2]]], {end, {1, n}}]];
  {v, nr, idx}];
vrmLathe[profile_, origin_, axis_, segs_ : 24] := Module[{rot = vrmRotTo[axis], pr = N[profile], m, v = {}, nr = {}, dr, dh, nn, idx},
  m = Length[pr];
  Do[dr = pr[[Min[k + 1, m], 1]] - pr[[Max[k - 1, 1], 1]]; dh = pr[[Min[k + 1, m], 2]] - pr[[Max[k - 1, 1], 2]];
    Do[With[{ca = Cos[2 N[Pi] s/segs], sa = Sin[2 N[Pi] s/segs]},
      nn = {dh ca, dh sa, -dr}; nn = If[Norm[nn] > 0, nn/Norm[nn], nn];
      AppendTo[v, rot . {pr[[k, 1]] ca, pr[[k, 1]] sa, pr[[k, 2]]} + origin]; AppendTo[nr, rot . nn]], {s, 0, segs}], {k, m}];
  idx = Flatten[Table[With[{a = k (segs + 1) + s}, {{a, a + 1, a + segs + 1}, {a + 1, a + segs + 2, a + segs + 1}}], {k, 0, m - 2}, {s, 0, segs - 1}], 2];
  {v, nr, idx}];
vrmSmooth[pts_, rads_, k_ : 8] := Module[{p = N[pts], r = N[rads], n, out = {}, rr = {}},
  n = Length[p];
  Do[With[{p0 = p[[Max[i - 1, 1]]], p1 = p[[i]], p2 = p[[i + 1]], p3 = p[[Min[i + 2, n]]]},
    Do[AppendTo[out, 0.5 (2 p1 + (-p0 + p2) t + (2 p0 - 5 p1 + 4 p2 - p3) t^2 + (-p0 + 3 p1 - 3 p2 + p3) t^3)];
      AppendTo[rr, r[[i]] + (r[[i + 1]] - r[[i]]) t], {t, N[Range[0, k - 1]/k]}]], {i, n - 1}];
  {Append[out, Last[p]], Append[rr, Last[r]]}];
vrmVertexNormals[p_, tri_] := Module[{acc = ConstantArray[0., Dimensions[p]], n},
  Do[n = Cross[p[[t[[2]] + 1]] - p[[t[[1]] + 1]], p[[t[[3]] + 1]] - p[[t[[1]] + 1]]];
    acc[[t[[1]] + 1]] += n; acc[[t[[2]] + 1]] += n; acc[[t[[3]] + 1]] += n, {t, tri}];
  acc];
Length /@ vrmSphere[]

4. Stage 3 · Parts

  1. A part is an Association: its name, its material (a key of the creature’s colours), which mesh it belongs to ("body" or "face"), its shape, the bones it follows, and its morph targets. "bones" is one bone’s name, or a function from the vertices to one <|bone -> weight|> per vertex.
  2. vrmOnSurface[ ] finds the point on the front of Mochi’s round body above a point of the drawing, and the body’s normal there; vrmSquash[ ] scales a part about a centre and lifts it: the tool of every expression.
(*3*)
(* Stage 3: parts. A part is an Association; its "morphs" are filled by the expressions (stage 7). *)
vrmPart[name_, mat_, {v_, n_, i_}, bones_, mesh_ : "body"] := <|"name" -> name, "mat" -> mat, "mesh" -> mesh, "V" -> v, "N" -> n, "I" -> i, "bones" -> bones, "morphs" -> <||>|>;
vrmOnSurface[cx_, cy_, rx_, ry_, rz_, x_, y_, out_ : 0.004] := Module[{u, z, n},
  u = 1 - (x/rx)^2 - ((y - cy)/ry)^2; z = rz Sqrt[Max[u, 0.]];
  n = Normalize[N[{x/rx^2, (y - cy)/ry^2, z/rz^2}]];
  {N[{x, y, z}] + out n, n}];
vrmSquash[v_, c_, {sx_, sy_, sz_}, dy_ : 0.] := (((# - c) {sx, sy, sz} + c) + {0., dy, 0.}) & /@ v;
Keys[vrmPart["Test", "body", vrmSphere[8, 4], "hips"]]

5. Stage 4 · The skeleton, and Stage 5 · the skin

  1. vrmSkeleton[ ] lists the bones as {name, parent, position}: VRM 1.0’s 19 humanoid bones (the arm bones inside the body, carrying nothing; the stub feet on the foot bones), and with them Mochi’s tail and each ear’s bone and end. The avatar’s left is +X.
  2. vrmYWeights[ ] skins a body by height, each band blending into the next by a smoothstep; vrmTailWeights[ ] skins Mochi’s tail along its length.
(*4*)
(* Stage 4: the skeleton; Stage 5: the skin. *)
vrmSkeleton[s_, tail_ : False, ears_ : {}] := Module[{b},
  b = {{"hips", None, {0, .14, 0}}, {"spine", "hips", {0, .20, 0}}, {"chest", "spine", {0, .28, 0}}, {"neck", "chest", {0, .36, 0}}, {"head", "neck", {0, .40, 0}}};
  Do[With[{side = sd[[1]], sx = sd[[2]]},
    b = Join[b, {{side <> "UpperLeg", "hips", {sx .11, .12, 0}}, {side <> "LowerLeg", side <> "UpperLeg", {sx .11, .08, 0}},
      {side <> "Foot", side <> "LowerLeg", {sx .11, .045, .015}}, {side <> "Toes", side <> "Foot", {sx .11, .03, .08}},
      {side <> "UpperArm", "chest", {sx .17, .30, 0}}, {side <> "LowerArm", side <> "UpperArm", {sx .22, .30, 0}},
      {side <> "Hand", side <> "LowerArm", {sx .26, .30, 0}}}]], {sd, {{"left", 1}, {"right", -1}}}];
  If[tail, b = Join[b, {{"tail1", "hips", {-.20, .16, -.16}}, {"tail2", "tail1", {-.27, .22, -.20}}, {"tail3", "tail2", {-.30, .31, -.22}}, {"tail_end", "tail3", {-.27, .38, -.21}}}]];
  Do[b = Join[b, {{e[[1]], "head", e[[2]]}, {e[[1]] <> "_end", e[[1]], e[[3]]}}], {e, ears}];
  {#1, #2, N[#3] s} & @@@ b];
vrmYWeights[v_, s_] := Map[Function[y, Which[
    y <= .10, <|"hips" -> 1.|>, y >= .44, <|"head" -> 1.|>,
    True, Module[{keys = {{"hips", .10}, {"spine", .20}, {"chest", .30}, {"head", .44}}, k, t},
      k = SelectFirst[Range[3], keys[[#, 2]] <= y <= keys[[# + 1, 2]] &];
      t = (y - keys[[k, 2]])/(keys[[k + 1, 2]] - keys[[k, 2]]); t = t t (3 - 2 t);
      <|keys[[k, 1]] -> 1 - t, keys[[k + 1, 1]] -> t|>]]], v[[All, 2]]/s];
vrmTailWeights[v_, s_] := Map[Which[# < .18, <|"hips" -> .5, "tail1" -> .5|>, # < .26, <|"tail1" -> .6, "tail2" -> .4|>, # < .33, <|"tail2" -> .5, "tail3" -> .5|>, True, <|"tail3" -> 1.|>] &, v[[All, 2]]/s];
Length[vrmSkeleton[1., True]]

6. Stage 6 · Mochi and Onigiri, part by part

  1. Mochi is a squat ellipsoid skinned by height; two stub feet on the foot bones; ears turned on the lathe, each with a smaller pink one inside; a tail of six points made smooth and wrapped in a thinning tube; and on the head, eyes with highlights laid on the body, cheeks, a smile and a mouth 2 mm tall that the expressions open.
  2. Onigiri is a sphere reshaped by vrmOnigiriShape[ ] (narrow at the top, wide at the bottom), its normals worked out again; the nori, a clean strip made on the unit sphere under the bottom and given the same shape, lifted 6 mm; the orange dot; white ears; the stub feet; closed smiling eyes (tubes bent into arches), cheeks, a “w” mouth and the hidden mouth behind it. vrmFront[ ] finds the body’s vertex nearest a point of the drawing among those that face the front.
  3. Each creature is an Association: name, colours, parts, bones, morph targets’ names, spring chains, the height of the eyes and the creature’s height. The colours are Pyon’s own, from LOOKS in src/pyon.html.
(*5*)
(* Stage 6: Mochi. *)
vrmMochi[s_ : 1.] := Module[{col, cx = 0., cy = .30 s, rx = .30 s, ry = .27 s, rz = .26 s, parts = {}, ears = {}, face = {}, base, axis, prof, ib, ax, tpath, trad, p, n, e, h1, bp, bn, bl, mp, mn, smile, sm, mo},
  col = <|"body" -> "#f3e6d3", "line" -> "#c9b392", "inner" -> "#ffb3c1", "eye" -> "#1b1b2e", "white" -> "#ffffff", "blush" -> "#ff9aa8", "feet" -> "#e3d2bb", "mouth" -> "#c45a6a"|>;
  (* the body, skinned from the hips to the head by height *)
  AppendTo[parts, vrmPart["Body", "body", vrmEllipsoid[{cx, cy, 0.}, {rx, ry, rz}, IdentityMatrix[3], 56, 36], Function[v, vrmYWeights[v, s]]]];
  (* the tiny stub feet, each on its foot bone *)
  Do[AppendTo[parts, vrmPart["Foot_" <> sd[[1]], "feet", vrmEllipsoid[{sd[[2]] .11, .035, .045} s, {.065, .036, .075} s], sd[[1]] <> "Foot"]], {sd, {{"left", 1}, {"right", -1}}}];
  (* the ears: rounded cones on the lathe, each with a smaller pink cone inside, on its own bone *)
  Do[With[{side = sd[[1]], sx = sd[[2]]},
    base = {sx .16, .49, 0.} s; axis = {sx .45, 1., .05};
    prof = {{.085 s, 0.}, {.08 s, .03 s}, {.06 s, .08 s}, {.035 s, .12 s}, {.012 s, .145 s}, {0., .15 s}};
    AppendTo[parts, vrmPart["Ear_" <> side, "body", vrmLathe[prof, base, axis], "ear_" <> side]];
    ib = base + vrmRotTo[axis] . {0., -0.012 s, .02 s} + {0., 0., .035 s};
    AppendTo[parts, vrmPart["EarInner_" <> side, "inner", vrmLathe[{.62 #1, .85 #2} & @@@ prof, ib, axis], "ear_" <> side]];
    ax = Normalize[axis];
    AppendTo[ears, {"ear_" <> side, base/s + ax .02, base/s + ax .15}]], {sd, {{"L", 1}, {"R", -1}}}];
  (* the tail: six points curling up from the back, made smooth, then a tube thinning to its tip *)
  {tpath, trad} = vrmSmooth[s # & /@ {{-.17, .14, -.15}, {-.24, .17, -.19}, {-.29, .23, -.21}, {-.31, .30, -.22}, {-.29, .36, -.21}, {-.25, .39, -.19}}, {.038 s, .042 s, .04 s, .036 s, .032 s, .028 s}, 8];
  AppendTo[parts, vrmPart["Tail", "body", vrmTube[tpath, trad, 16], Function[v, vrmTailWeights[v, s]]]];
  (* the face, on the head bone: eyes with highlights, cheeks, a smile, and a hidden mouth that opens *)
  Do[With[{side = sd[[1]], sx = sd[[2]]},
    {p, n} = vrmOnSurface[cx, cy, rx, ry, rz, sx .095 s, .325 s, .002 s];
    e = vrmPart["Eye_" <> side, "eye", vrmEllipsoid[p, {.042, .052, .014} s, vrmRotTo[n], 32, 20], "head", "face"];
    h1 = vrmPart["Shine_" <> side, "white", vrmEllipsoid[p + {sx .012 + .006, .018, .012} s, {.016, .016, .006} s, vrmRotTo[n], 16, 10], "head", "face"];
    {bp, bn} = vrmOnSurface[cx, cy, rx, ry, rz, sx .19 s, .255 s, .001 s];
    bl = vrmPart["Cheek_" <> side, "blush", vrmEllipsoid[bp, {.038, .022, .006} s, vrmRotTo[bn], 24, 12], "head", "face"];
    AppendTo[face, {side, p, e, h1}]; parts = Join[parts, {e, h1, bl}]], {sd, {{"L", 1}, {"R", -1}}}];
  {mp, mn} = vrmOnSurface[cx, cy, rx, ry, rz, 0., .255 s, .003 s];
  smile = (mp + {#, -.009 (1 - (#/.022)^2) + .002, 0.} s) & /@ vrmLinspace[-.022, .022, 11];
  sm = vrmPart["Smile", "eye", vrmTube[smile, .0045 s, 8], "head", "face"];
  mo = vrmPart["Mouth", "mouth", vrmEllipsoid[mp + {0., -.016, -.004} s, {.02, .002, .008} s, vrmRotTo[mn], 24, 12], "head", "face"];
  parts = Join[parts, {sm, mo}];
  (* Stage 7: the expressions, as morph targets on the face *)
  <|"name" -> "Mochi", "colours" -> col, "parts" -> vrmWithMorphs[parts, vrmFaceTargets[face, sm, mo, s, False]],
    "bones" -> vrmSkeleton[s, True, ears], "targets" -> vrmTargetNames,
    "springs" -> {{"tail", {"tail1", "tail2", "tail3", "tail_end"}}, {"ear_L", {"ear_L", "ear_L_end"}}, {"ear_R", {"ear_R", "ear_R_end"}}},
    "eyesY" -> .325 s, "height" -> .64 s|>];
(*6*)
(* Stage 6: Onigiri. *)
vrmOnigiriShape[u_, s_, cy_, h_] := Module[{x = u[[All, 1]], y = u[[All, 2]], z = u[[All, 3]], w, bot},
  w = .52 + .48 (1 - (y + 1)/2)^.8;
  bot = If[# < -.55, 1 - (# + .55) .25, 1.] & /@ y;
  Transpose[{x w .32 s bot, cy + y h (If[# < 0, .92, 1.] & /@ y), z (.75 + .25 (1 - (y + 1)/2)) .25 s}]];
vrmFront[p_, nn_, x_, y_, out_, s_] := Module[{k},
  k = First[Ordering[MapThread[Norm[#1[[;; 2]] - {x, y}] + If[#2[[3]] < .3, 9, 0] &, {p, nn}], 1]];
  {p[[k]] + nn[[k]] out s, nn[[k]]}];
vrmOnigiri[s_ : 1.] := Module[{col, cy = .30 s, h = .30 s, v, n0, i, p, nn, parts, g, ni, np0, nnr, np, k, ears = {}, face = {}, base, axis, prof, ax, e, bp, bn, bl, pe, ne, arc, mp, mn, w, sm, mo},
  col = <|"body" -> "#fafafa", "line" -> "#b9b9b9", "nori" -> "#1f3b2d", "dot" -> "#ff8c1a", "eye" -> "#1b1b2e", "blush" -> "#ff9aa8", "feet" -> "#e8e8e8", "mouth" -> "#c45a6a"|>;
  {v, n0, i} = vrmSphere[64, 40];
  (* the body: the sphere reshaped into the rice ball; its normals worked out again (the sphere's own at the two poles) *)
  p = vrmOnigiriShape[v, s, cy, h];
  nn = MapThread[If[Norm[#1] > 1*^-9, #1/Max[Norm[#1], 1*^-12], #2] &, {vrmVertexNormals[p, i], v}];
  parts = {vrmPart["Body", "body", {p, nn, i}, Function[vv, vrmYWeights[vv, s]]]};
  (* the nori: a clean strip on the unit sphere, swept under the bottom from the back to the front, given the same shape, lifted 6 mm *)
  g = Flatten[Table[With[{phi = -1.25 + 2.5 j/40, u = -.36 + .72 k/16}, {u, -Sqrt[1 - u^2] Cos[phi], Sqrt[1 - u^2] Sin[phi]}], {j, 0, 40}, {k, 0, 16}], 1];
  np0 = vrmOnigiriShape[g, s, cy, h];
  ni = Flatten[Table[With[{a = j 17 + k}, {{a, a + 1, a + 17}, {a + 1, a + 18, a + 17}}], {j, 0, 39}, {k, 0, 15}], 2];
  nnr = #/Max[Norm[#], 1*^-12] & /@ vrmVertexNormals[np0, ni];
  If[Mean[MapThread[Dot, {nnr, (# - {0, cy, 0}) & /@ np0}]] < 0, nnr = -nnr; ni = ni[[All, {1, 3, 2}]]];
  np = np0 + nnr .006 s;
  AppendTo[parts, vrmPart["Nori", "nori", {np, nnr, ni}, Function[vv, vrmYWeights[vv, s]]]];
  (* the orange dot, on the nori in front *)
  k = First[Ordering[Norm[# - {0, -.55, .83}] & /@ v, 1]];
  AppendTo[parts, vrmPart["Dot", "dot", vrmEllipsoid[p[[k]] + nn[[k]] .008 s, {.02, .02, .006} s, vrmRotTo[nn[[k]]], 20, 10], "spine"]];
  (* the ears: white rounded cones, each on its own bone *)
  Do[With[{side = sd[[1]], sx = sd[[2]]},
    base = {sx .13, .51, -.01} s; axis = {sx .35, 1., 0.};
    prof = {{.075 s, 0.}, {.07 s, .03 s}, {.05 s, .075 s}, {.025 s, .11 s}, {.008 s, .128 s}, {0., .132 s}};
    AppendTo[parts, vrmPart["Ear_" <> side, "body", vrmLathe[prof, base, axis], "ear_" <> side]];
    ax = Normalize[axis]; AppendTo[ears, {"ear_" <> side, base/s + ax .02, base/s + ax .13}]], {sd, {{"L", 1}, {"R", -1}}}];
  (* the tiny stub feet *)
  Do[AppendTo[parts, vrmPart["Foot_" <> sd[[1]], "feet", vrmEllipsoid[{sd[[2]] .10, .035, .04} s, {.06, .034, .07} s], sd[[1]] <> "Foot"]], {sd, {{"left", 1}, {"right", -1}}}];
  (* the face: closed, smiling eyes (arches), cheeks, a "w" mouth, and a hidden mouth that opens *)
  Do[With[{side = sd[[1]], sx = sd[[2]]},
    {pe, ne} = vrmFront[p, nn, sx .085 s, .33 s, .003, s];
    arc = (pe + {#, .013 Cos[#/.022 N[Pi]/2] - .013, 0.}) & /@ (vrmLinspace[-.022, .022, 9] s);
    e = vrmPart["Eye_" <> side, "eye", vrmTube[arc, .005 s, 8], "head", "face"];
    {bp, bn} = vrmFront[p, nn, sx .155 s, .27 s, .001, s];
    bl = vrmPart["Cheek_" <> side, "blush", vrmEllipsoid[bp, {.032, .019, .006} s, vrmRotTo[bn], 24, 12], "head", "face"];
    parts = Join[parts, {e, bl}]; AppendTo[face, {side, pe, e, None}]], {sd, {{"L", 1}, {"R", -1}}}];
  {mp, mn} = vrmFront[p, nn, 0., .275 s, .003, s];
  w = (mp + {#, -.006 Abs[Sin[#/.011 N[Pi]/2]], 0.}) & /@ (vrmLinspace[-.016, .016, 13] s);
  sm = vrmPart["Smile", "eye", vrmTube[w, .004 s, 8], "head", "face"];
  mo = vrmPart["Mouth", "mouth", vrmEllipsoid[mp + {0., -.012, -.004} s, {.016, .002, .007} s, vrmRotTo[mn], 24, 12], "head", "face"];
  parts = Join[parts, {sm, mo}];
  <|"name" -> "Onigiri", "colours" -> col, "parts" -> vrmWithMorphs[parts, vrmFaceTargets[face, sm, mo, s, True]],
    "bones" -> vrmSkeleton[s, False, ears], "targets" -> vrmTargetNames,
    "springs" -> {{"ear_L", {"ear_L", "ear_L_end"}}, {"ear_R", {"ear_R", "ear_R_end"}}}, "eyesY" -> .33 s, "height" -> .64 s|>];

7. Stage 7 · The expressions

  1. Seven morph targets on the face: 0 blinkL and 1 blinkR (an eye squashed flat, its highlight shrunk away), 2 mouthOpen, 3 mouthWide, 4 mouthRound, 5 happyEyes (Mochi’s eyes squashed thin and bent up in the middle, ^ ^), 6 wideEyes. Onigiri’s eyes are always closed arches, so they are lowered, raised or stretched instead.
  2. In Python the targets were written into each part as the function went; in Wolfram vrmFaceTargets[ ] returns them, keyed by the part’s name, and vrmWithMorphs[ ] puts them into the parts: a value is never changed behind one’s back.
(*7*)
(* Stage 7: the expressions. *)
vrmTargetNames = {"blinkL", "blinkR", "mouthOpen", "mouthWide", "mouthRound", "happyEyes", "wideEyes"};
vrmFaceTargets[face_, smile_, mouth_, s_, closed_] := Module[{m = <||>, side, c, eye, shine, ti, hv, rx, mc, sc},
  Do[{side, c, eye, shine} = f; ti = If[side == "L", 0, 1];
    If[closed,
      m[eye["name"]] = <|ti -> vrmSquash[eye["V"], c, {1, .35, 1}], 5 -> vrmSquash[eye["V"], c, {1, 1.3, 1}, .006 s], 6 -> vrmSquash[eye["V"], c, {1.15, 1.6, 1}, .004 s]|>,
      hv = vrmSquash[eye["V"], c, {1, .22, 1}, .002 s];
      rx = (Max[eye["V"][[All, 1]]] - Min[eye["V"][[All, 1]]])/2; If[rx == 0, rx = 1];
      hv[[All, 2]] += .014 s (1 - ((eye["V"][[All, 1]] - c[[1]])/rx)^2);
      m[eye["name"]] = <|ti -> vrmSquash[eye["V"], c, {1, .08, 1}, -.012 s], 5 -> hv, 6 -> vrmSquash[eye["V"], c, {1.15, 1.2, 1}]|>;
      If[shine =!= None, m[shine["name"]] = <|ti -> vrmSquash[shine["V"], c, {.01, .01, .01}, -.012 s], 5 -> vrmSquash[shine["V"], c, {.01, .01, .01}], 6 -> vrmSquash[shine["V"], c, {1.15, 1.2, 1}]|>]],
    {f, face}];
  mc = Mean[mouth["V"]];
  m[mouth["name"]] = <|2 -> vrmSquash[mouth["V"], mc, {1.05, 14, 1}, -.012 s], 3 -> vrmSquash[mouth["V"], mc, {1.5, 6, 1}, -.005 s], 4 -> vrmSquash[mouth["V"], mc, {.6, 11, 1}, -.010 s]|>;
  sc = Mean[smile["V"]];
  m[smile["name"]] = <|3 -> vrmSquash[smile["V"], sc, {1.3, 1, 1}], 4 -> vrmSquash[smile["V"], sc, {.7, 1, 1}]|>;
  m];
vrmWithMorphs[parts_, m_] := If[KeyExistsQ[m, #["name"]], Append[#, "morphs" -> m[#["name"]]], #] & /@ parts;
mochi = vrmMochi[]; onigiri = vrmOnigiri[];
{Length[mochi["parts"]], Length[onigiri["parts"]], Total[Length[#["V"]] & /@ mochi["parts"]], Total[Length[#["V"]] & /@ onigiri["parts"]]}

8. Drawing them in Wolfram

  1. What Python could not do alone, Wolfram does in the notebook: every shape, stage, skeleton, skin and expression is drawn with Graphics3D, straight from the vertex lists, before any file is written. The Python version needed a browser, three.js and three-vrm to see anything (tools/vrm-figures.py).
  2. vrmCamera[ ] sets the camera and the paper colour; vrmDraw[ ] draws parts in their colours; vrmDrawShape[ ] draws one building block with its edges (under three soft lights of our own, vrmLights, not the toon shading, which belongs to the avatar programs); vrmDrawSkeleton[ ] draws the bones over a see-through body; vrmDrawWeights[ ] colours each vertex by its bones mixed by their weights; vrmMorphed[ ] applies expression weights to the face; vrmSheet[ ] lays pictures side by side with captions, a title and the copyright line.
(*8*)
(* Drawing in Wolfram: Graphics3D straight from the parts. *)
vrmPaper = RGBColor["#fdf6ea"];
vrmCopyright = "\[Copyright] Computational Classnotes \[CenterDot] CC BY-NC-SA 4.0";
vrmLights = {{"Ambient", GrayLevel[.62]}, {"Directional", GrayLevel[.42], {{-1, 2, 3}, {0, 0, 0}}}, {"Directional", GrayLevel[.12], {{2, 1, -1}, {0, 0, 0}}}};
vrmCamera[cr_] := {Boxed -> False, Lighting -> vrmLights, ViewVertical -> {0, 1, 0}, ViewPoint -> {-1.5, 0.6, 3}, ViewAngle -> 0.36,
   PlotRange -> {{-.40, .40}, {-.01, .70}, {-.36, .36}}, SphericalRegion -> True, Background -> vrmPaper, ImageSize -> 300};
vrmMesh[p_, opts___] := GraphicsComplex[p["V"], Polygon[p["I"] + 1], VertexNormals -> p["N"], opts];
vrmDraw[cr_, parts_, opts___] := Graphics3D[{EdgeForm[], Specularity[GrayLevel[.15], 12], {RGBColor[cr["colours"][#["mat"]]], vrmMesh[#]} & /@ parts}, opts, Sequence @@ vrmCamera[cr]];
vrmDrawSkeleton[cr_, opts___] := Module[{pos = AssociationThread[cr["bones"][[All, 1]] -> cr["bones"][[All, 3]]]},
  Graphics3D[{EdgeForm[], {Opacity[.22], RGBColor[cr["colours"][#["mat"]]], vrmMesh[#]} & /@ cr["parts"],
    {RGBColor["#669bbc"], Thickness[.006], Line[{pos[#2], pos[#1]}] & @@@ Select[cr["bones"], StringQ[#[[2]]] &]},
    {RGBColor["#c0392b"], Sphere[#, .009] & /@ Values[pos]}}, opts, Sequence @@ vrmCamera[cr]]];
vrmBoneColours = <|"hips" -> "#e4572e", "spine" -> "#f3a712", "chest" -> "#a8c686", "neck" -> "#669bbc", "head" -> "#3f88c5", "leftFoot" -> "#9b5de5", "rightFoot" -> "#f15bb5",
   "tail1" -> "#00bbf9", "tail2" -> "#00f5d4", "tail3" -> "#8ac926", "ear_L" -> "#ff595e", "ear_R" -> "#ffca3a"|>;
vrmDrawWeights[cr_, opts___] := Graphics3D[{EdgeForm[], Map[Function[p, Module[{ws = If[StringQ[p["bones"]], ConstantArray[<|p["bones"] -> 1.|>, Length[p["V"]]], p["bones"][p["V"]]]},
      vrmMesh[p, VertexColors -> (RGBColor @@ Total[KeyValueMap[Function[{b, wt}, wt List @@ RGBColor[Lookup[vrmBoneColours, b, "#3f88c5"]]], #]] & /@ ws)]]], cr["parts"]]}, opts, Sequence @@ vrmCamera[cr]];
vrmMorphed[cr_, weights_Association] := Map[Function[p, If[p["morphs"] === <||>, p,
     Append[p, "V" -> p["V"] + Total[KeyValueMap[Function[{t, wt}, If[KeyExistsQ[p["morphs"], t], wt (p["morphs"][t] - p["V"]), 0 p["V"]]], weights]]]]], cr["parts"]];
vrmSheet[title_, pics_, labels_, cols_] := Framed[Column[{Style[title, 18, Bold, FontFamily -> "Source Sans Pro"],
    Grid[Partition[MapThread[Column[{#1, Style[#2, 13, FontFamily -> "Source Sans Pro"]}, Alignment -> Left] &, {pics, labels}], UpTo[cols]], Spacings -> {2, 2}, Alignment -> {Left, Top}],
    Item[Style[vrmCopyright, 11, GrayLevel[.4], FontFamily -> "Source Sans Pro"], Alignment -> Right]}, Spacings -> 1.2], Background -> vrmPaper, FrameStyle -> None, FrameMargins -> 16];
vrmDrawShape[{v_, n_, i_}, colour_] := Graphics3D[{EdgeForm[{Thickness[.001], GrayLevel[.55]}], Specularity[GrayLevel[.15], 12], RGBColor[colour], GraphicsComplex[v, Polygon[i + 1], VertexNormals -> n]},
   Boxed -> False, Lighting -> vrmLights, ViewVertical -> {0, 1, 0}, ViewPoint -> {1.3, 0.8, 3}, Background -> vrmPaper, ImageSize -> 240];
vrmByName[cr_, names_List] := Select[cr["parts"], StringStartsQ[#["name"], names] &];
vrmDraw[mochi, mochi["parts"]]
  1. Figure WL-1 draws the four building blocks straight from their vertex lists, with their edges, so that the grids show: the sphere’s slices and rings, an ellipsoid turned by vrmRotTo[ ], a tube along a smooth curve, and an ear turned on the lathe.
(*9*)
(*figure: wl-01-shapes · The building blocks, drawn by Wolfram*)
vrmSheet["Stage 2 \[CenterDot] The building blocks, drawn by Wolfram", {
   vrmDrawShape[vrmSphere[20, 12], "#f3e6d3"],
   vrmDrawShape[vrmEllipsoid[{0, 0, 0}, {.30, .18, .12}, vrmRotTo[{.4, .3, 1}], 24, 14], "#ffb3c1"],
   vrmDrawShape[vrmTube @@ Append[vrmSmooth[{{0, 0, 0}, {.1, .12, .05}, {.18, .3, .02}, {.12, .45, -.05}}, {.05, .045, .035, .02}, 6], 12], "#e3d2bb"],
   vrmDrawShape[vrmLathe[{{.085, 0}, {.08, .03}, {.06, .08}, {.035, .12}, {.012, .145}, {0, .15}}, {0, 0, 0}, {.45, 1, .05}], "#f3e6d3"]},
  {"vrmSphere[20, 12]", "vrmEllipsoid, turned by vrmRotTo", "vrmTube along vrmSmooth", "vrmLathe: an ear"}, 4]
Figure WL-1 · The building blocks, drawn by Wolfram
  1. Figure WL-2 builds Mochi up part by part with vrmByName[ ], which picks the parts whose names begin with the given words; Figure WL-3 does the same for Onigiri, from the bare sphere to the finished rice ball.
(*10*)
(*figure: wl-02-mochi-stages · Mochi, part by part, drawn by Wolfram*)
vrmSheet["Mochi, part by part, drawn by Wolfram", vrmDraw[mochi, vrmByName[mochi, #]] & /@ {{"Body"}, {"Body", "Foot"}, {"Body", "Foot", "Ear"}, {"Body", "Foot", "Ear", "Tail"}, {"Body", "Foot", "Ear", "Tail", "Eye", "Shine"}, {""}},
  {"1 \[CenterDot] the body", "2 \[CenterDot] the stub feet", "3 \[CenterDot] the ears, pink inside", "4 \[CenterDot] the tail", "5 \[CenterDot] the eyes and highlights", "6 \[CenterDot] cheeks, smile and mouth: Mochi"}, 3]
Figure WL-2 · Mochi, part by part, drawn by Wolfram
(*11*)
(*figure: wl-03-onigiri-stages · Onigiri, part by part, drawn by Wolfram*)
vrmSheet["Onigiri, part by part, drawn by Wolfram", Join[{With[{sv = vrmSphere[64, 40]}, vrmDraw[onigiri, {vrmPart["Sphere", "body", {(# {.32, .30, .25} + {0, .30, 0}) & /@ sv[[1]], sv[[2]], sv[[3]]}, "hips"]}]]},
   vrmDraw[onigiri, vrmByName[onigiri, #]] & /@ {{"Body"}, {"Body", "Nori", "Dot"}, {"Body", "Nori", "Dot", "Ear", "Foot"}, {"Body", "Nori", "Dot", "Ear", "Foot", "Eye"}, {""}}],
  {"1 \[CenterDot] a sphere, 64 \[Times] 40", "2 \[CenterDot] reshaped: vrmOnigiriShape", "3 \[CenterDot] the nori and the orange dot", "4 \[CenterDot] the ears and stub feet", "5 \[CenterDot] the closed, smiling eyes", "6 \[CenterDot] cheeks and the \"w\" mouth: Onigiri"}, 3]
Figure WL-3 · Onigiri, part by part, drawn by Wolfram
  1. Figure WL-4 shows each skeleton over a see-through body: blue lines from each bone to its parent, a red ball at each bone. Figure WL-5 colours every vertex by the bones it follows, mixed by their weights, in the colours of the Python write-up’s Figure 4: hips red-orange, spine amber, chest green, head blue, the feet purple and pink, the tail’s three bones cyan to green, the ears red and yellow.
(*12*)
(*figure: wl-04-skeletons · The skeletons, drawn by Wolfram*)
vrmSheet["The skeletons, drawn by Wolfram", {vrmDrawSkeleton[mochi], vrmDrawSkeleton[onigiri]},
  {"Mochi: 19 humanoid bones, the tail's 4, the ears' 4", "Onigiri: 19 humanoid bones, the ears' 4"}, 2]
Figure WL-4 · The skeletons, drawn by Wolfram
(*13*)
(*figure: wl-05-weights · The skin weights, drawn by Wolfram*)
vrmSheet["The skin: each point coloured by the bones it follows", {vrmDrawWeights[mochi], vrmDrawWeights[mochi, ViewPoint -> {1.5, 0.6, -3}], vrmDrawWeights[onigiri], vrmDrawWeights[onigiri, ViewPoint -> {1.5, 0.6, -3}]},
  {"Mochi, front", "Mochi, back: the tail along its bones", "Onigiri, front", "Onigiri, back"}, 4]
Figure WL-5 · The skin weights, drawn by Wolfram
  1. Figure WL-6 applies the expressions to the face with vrmMorphed[ ]: each preset is the mixture of morph targets that vrmExpressions[ ] writes into the file (blink: targets 0 and 1; aa: 2; ou: 4; happy: 5, with 3 at 0.4; surprised: 6, with 4 at 0.6).
(*14*)
(*figure: wl-06-expressions · The expressions, drawn by Wolfram*)
With[{presets = {"neutral" -> <||>, "blink" -> <|0 -> 1, 1 -> 1|>, "aa" -> <|2 -> 1|>, "ou" -> <|4 -> 1|>, "happy" -> <|5 -> 1, 3 -> .4|>, "surprised" -> <|6 -> 1, 4 -> .6|>},
   face = Sequence[ViewPoint -> {0, 0.1, 4}, ViewAngle -> 0.15, ViewCenter -> {0.5, 0.45, 0.86}, ImageSize -> 200]},
  vrmSheet["The expressions, drawn by Wolfram", Join[vrmDraw[mochi, vrmMorphed[mochi, Last[#]], face] & /@ presets, vrmDraw[onigiri, vrmMorphed[onigiri, Last[#]], face] & /@ presets],
   Join["Mochi \[CenterDot] " <> First[#] & /@ presets, "Onigiri \[CenterDot] " <> First[#] & /@ presets], 6]]
Figure WL-6 · The expressions, drawn by Wolfram

9. Stage 8 · Writing the file

  1. The file is built in an Association held in a symbol: the JSON as nested associations and lists, and the binary buffer as a list of ByteArrays with its length. The functions that add to it hold their first argument (HoldFirst), so that they can change the file being built, as the Python class’s methods do.
  2. vrmBufferView[ ] pads the buffer to 4 bytes and appends bytes and a bufferView; vrmAccessor[ ] turns an array into 32-bit floats or unsigned integers with NumericArray, writes its bytes with ExportByteArray, and records its accessor, with the bounds glTF requires for positions; vrmImage[ ] embeds the thumbnail; vrmWrite[ ] joins the 12-byte header, the JSON chunk (padded with spaces) and the binary chunk (padded with zeros), little-endian, and writes them with BinaryWrite.
  3. vrmMToon[ ] and vrmAddMaterials[ ] make the toon materials; vrmAddSkeleton[ ] the nodes and the skin; vrmAddMeshes[ ] the Body and Face meshes, every vertex with its four strongest bones (ties kept in their first order, as Python’s sort keeps them), the face with its seven targets; vrmExpressions[ ], vrmMeta[ ] and vrmSprings[ ] the VRM extensions; vrmBuild[ ] the whole avatar; vrmMain[ ] writes both files.
(*15*)
(* Stage 8: the binary glTF file. *)
vrmNewGLB[] := <|"bin" -> {}, "len" -> 0, "j" -> <|"asset" -> <|"version" -> "2.0", "generator" -> "Pyon ff_makevrm.nb \[CenterDot] Computational Classnotes"|>,
    "buffers" -> {}, "bufferViews" -> {}, "accessors" -> {}, "meshes" -> {}, "nodes" -> {}, "materials" -> {}, "skins" -> {}, "scenes" -> {<|"nodes" -> {}|>}, "scene" -> 0|>|>;
SetAttributes[{vrmBufferView, vrmAccessor, vrmImage, vrmAddMaterials, vrmAddSkeleton, vrmAddMeshes}, HoldFirst];
vrmBufferView[g_, data_ByteArray, target_ : None] := Module[{pad = Mod[-g[["len"]], 4], v},
  If[pad > 0, AppendTo[g[["bin"]], ByteArray[ConstantArray[0, pad]]]; g[["len"]] += pad];
  v = <|"buffer" -> 0, "byteOffset" -> g[["len"]], "byteLength" -> Length[data]|>;
  If[target =!= None, v["target"] = target];
  AppendTo[g[["bin"]], data]; g[["len"]] += Length[data];
  AppendTo[g[["j", "bufferViews"]], v]; Length[g[["j", "bufferViews"]]] - 1];
vrmAccessor[g_, arr_, ctype_, type_, target_ : None, minmax_ : False] := Module[{fmt, vals, a},
  fmt = Switch[ctype, 5126, "Real32", 5125, "UnsignedInteger32", 5121, "UnsignedInteger8"];
  vals = Normal[NumericArray[arr, fmt]];
  a = <|"bufferView" -> vrmBufferView[g, ExportByteArray[Flatten[vals], fmt, ByteOrdering -> -1], target], "componentType" -> ctype, "count" -> Length[arr], "type" -> type|>;
  If[minmax, a["min"] = Min /@ Transpose[vals]; a["max"] = Max /@ Transpose[vals]];
  AppendTo[g[["j", "accessors"]], a]; Length[g[["j", "accessors"]]] - 1];
vrmImage[g_, png_ByteArray] := (If[! KeyExistsQ[g[["j"]], "images"], g[["j", "images"]] = {}];
  AppendTo[g[["j", "images"]], <|"bufferView" -> vrmBufferView[g, png], "mimeType" -> "image/png", "name" -> "thumbnail"|>]; Length[g[["j", "images"]]] - 1);
vrmWrite[g_, path_] := Module[{j, js, b, u32, out, st},
  j = g["j"]; j["buffers"] = {<|"byteLength" -> g["len"]|>};
  js = ExportByteArray[j, "RawJSON", "Compact" -> True];
  If[Mod[Length[js], 4] > 0, js = Join[js, ByteArray[ConstantArray[32, Mod[-Length[js], 4]]]]];
  b = Join @@ g["bin"]; If[Mod[Length[b], 4] > 0, b = Join[b, ByteArray[ConstantArray[0, Mod[-Length[b], 4]]]]];
  u32 = ExportByteArray[#, "UnsignedInteger32", ByteOrdering -> -1] &;
  out = Join[u32[{16^^46546C67, 2, 12 + 8 + Length[js] + 8 + Length[b]}], u32[{Length[js], 16^^4E4F534A}], js, u32[{Length[b], 16^^004E4942}], b];
  st = OpenWrite[path, BinaryFormat -> True]; BinaryWrite[st, out]; Close[st]; FileByteCount[path]];
(*16*)
(* Stage 8: materials, the skeleton and the skin, the meshes. *)
vrmMToon[name_, colour_, shade_, outline_, width_ : .004] := <|"name" -> name, "pbrMetallicRoughness" -> <|"baseColorFactor" -> vrmLin[colour], "metallicFactor" -> 0, "roughnessFactor" -> 1|>,
   "doubleSided" -> False, "alphaMode" -> "OPAQUE",
   "extensions" -> <|"VRMC_materials_mtoon" -> <|"specVersion" -> "1.0", "transparentWithZWrite" -> False, "renderQueueOffsetNumber" -> 0,
      "shadeColorFactor" -> Most[vrmLin[shade]], "shadingShiftFactor" -> -0.05, "shadingToonyFactor" -> 0.92, "giEqualizationFactor" -> 0.9,
      "matcapFactor" -> {0, 0, 0}, "parametricRimColorFactor" -> {0, 0, 0}, "parametricRimFresnelPowerFactor" -> 4.0, "parametricRimLiftFactor" -> 0.0, "rimLightingMixFactor" -> 0.0,
      "outlineWidthMode" -> If[width > 0, "worldCoordinates", "none"], "outlineWidthFactor" -> width, "outlineColorFactor" -> Most[vrmLin[outline]], "outlineLightingMixFactor" -> 1.0|>|>|>;
vrmAddMaterials[g_, col_] := Module[{mats = <||>},
  KeyValueMap[Function[{key, c}, If[key =!= "line",
     mats[key] = Length[g[["j", "materials"]]];
     AppendTo[g[["j", "materials"]], vrmMToon[key, c, vrmDarker[c, If[key == "eye", 1, .86]], If[MemberQ[{"body", "feet"}, key], col["line"], vrmDarker[c, .6]], If[MemberQ[{"body", "feet", "nori"}, key], .0045, 0.]]]]], col];
  mats];
vrmAddSkeleton[g_, cr_] := Module[{names = cr["bones"][[All, 1]], pos = AssociationThread[cr["bones"][[All, 1]] -> cr["bones"][[All, 3]]], par = AssociationThread[cr["bones"][[All, 1]] -> cr["bones"][[All, 2]]], nid = <||>, ibm},
  AppendTo[g[["j", "nodes"]], <|"name" -> cr["name"], "children" -> {}|>];
  Do[nid[n] = Length[g[["j", "nodes"]]]; AppendTo[g[["j", "nodes"]], <|"name" -> n, "translation" -> pos[n] - If[StringQ[par[n]], pos[par[n]], 0]|>], {n, names}];
  Do[If[StringQ[par[n]],
     If[! KeyExistsQ[g[["j", "nodes", nid[par[n]] + 1]], "children"], g[["j", "nodes", nid[par[n]] + 1, "children"]] = {}];
     AppendTo[g[["j", "nodes", nid[par[n]] + 1, "children"]], nid[n]],
     AppendTo[g[["j", "nodes", 1, "children"]], nid[n]]], {n, names}];
  ibm = Flatten[{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, Append[-pos[#], 1]}] & /@ names;
  AppendTo[g[["j", "skins"]], <|"joints" -> (nid /@ names), "inverseBindMatrices" -> vrmAccessor[g, N[ibm], 5126, "MAT4"], "skeleton" -> nid["hips"], "name" -> "skin"|>];
  {names, pos, nid, AssociationThread[names -> Range[0, Length[names] - 1]]}];
vrmTopFour[w_Association, jindex_] := Module[{items = Normal[w], ord, top, tot},
  ord = SortBy[Range[Length[items]], {-items[[#, 2]] &, Identity}];
  top = Select[items[[Take[ord, UpTo[4]]]], #[[2]] > 1*^-4 &]; tot = Total[top[[All, 2]]];
  {PadRight[jindex /@ top[[All, 1]], 4], PadRight[top[[All, 2]]/tot, 4, 0.]}];
vrmAddMeshes[g_, cr_, mats_, jindex_] := Module[{faceNode = None, meshNodes = {}, ps, prims, group, v, n, i, jw, tg, off, prim, m},
  Do[ps = Select[cr["parts"], #["mesh"] == mesh &];
    If[ps =!= {},
      prims = Table[group = Select[ps, #["mat"] == mkey &];
        off = 0; i = {}; Do[i = Join[i, p["I"] + off]; off += Length[p["V"]], {p, group}];
        v = Join @@ group[[All, "V"]]; n = Join @@ group[[All, "N"]];
        jw = Join @@ (Function[p, vrmTopFour[#, jindex] & /@ If[StringQ[p["bones"]], ConstantArray[<|p["bones"] -> 1.|>, Length[p["V"]]], p["bones"][p["V"]]]] /@ group);
        prim = <|"attributes" -> <|"POSITION" -> vrmAccessor[g, v, 5126, "VEC3", 34962, True], "NORMAL" -> vrmAccessor[g, n, 5126, "VEC3", 34962],
            "JOINTS_0" -> vrmAccessor[g, jw[[All, 1]], 5121, "VEC4", 34962], "WEIGHTS_0" -> vrmAccessor[g, jw[[All, 2]], 5126, "VEC4", 34962]|>,
          "indices" -> vrmAccessor[g, Flatten[i], 5125, "SCALAR", 34963], "material" -> mats[mkey], "mode" -> 4|>;
        If[mesh == "face", prim["targets"] = Table[<|"POSITION" -> vrmAccessor[g, Join @@ (If[KeyExistsQ[#["morphs"], t], #["morphs"][t] - #["V"], 0. #["V"]] & /@ group), 5126, "VEC3", 34962, True]|>, {t, 0, Length[cr["targets"]] - 1}]];
        prim, {mkey, DeleteDuplicates[ps[[All, "mat"]]]}];
      m = <|"name" -> If[mesh == "face", "Face", "Body"], "primitives" -> prims|>;
      If[mesh == "face", m["weights"] = ConstantArray[0., Length[cr["targets"]]]; m["extras"] = <|"targetNames" -> cr["targets"]|>];
      AppendTo[g[["j", "meshes"]], m];
      AppendTo[g[["j", "nodes"]], <|"name" -> m["name"], "mesh" -> Length[g[["j", "meshes"]]] - 1, "skin" -> 0|>];
      AppendTo[meshNodes, Length[g[["j", "nodes"]]] - 1];
      If[mesh == "face", faceNode = Length[g[["j", "nodes"]]] - 1]], {mesh, {"body", "face"}}];
  {faceNode, meshNodes}];
(*17*)
(* Stage 8: the VRM extensions, the whole avatar, and both files. *)
vrmExpressions[cr_, faceNode_] := Module[{t = AssociationThread[cr["targets"] -> Range[0, Length[cr["targets"]] - 1]], binds, expr},
  binds[pairs__] := <|"morphTargetBinds" -> (<|"node" -> faceNode, "index" -> t[#[[1]]], "weight" -> #[[2]]|> & /@ {pairs}), "isBinary" -> False, "overrideBlink" -> "none", "overrideLookAt" -> "none", "overrideMouth" -> "none"|>;
  expr = <|"blink" -> binds[{"blinkL", 1}, {"blinkR", 1}], "blinkLeft" -> binds[{"blinkL", 1}], "blinkRight" -> binds[{"blinkR", 1}],
    "aa" -> binds[{"mouthOpen", 1}], "ih" -> binds[{"mouthWide", .6}], "ee" -> binds[{"mouthWide", 1}], "ou" -> binds[{"mouthRound", 1}],
    "oh" -> binds[{"mouthRound", .7}, {"mouthOpen", .4}], "happy" -> binds[{"happyEyes", 1}, {"mouthWide", .4}],
    "surprised" -> binds[{"wideEyes", 1}, {"mouthRound", .6}], "relaxed" -> binds[{"blinkL", .45}, {"blinkR", .45}, {"mouthWide", .2}],
    "sad" -> binds[{"blinkL", .3}, {"blinkR", .3}, {"mouthRound", .2}], "angry" -> binds[{"blinkL", .2}, {"blinkR", .2}]|>;
  expr[["happy", "overrideBlink"]] = "block"; expr];
vrmMeta[cr_] := <|"name" -> cr["name"], "version" -> "1.0 (Pyon 1.0a1)", "authors" -> {"Dara O Shayda", "Hikari Noor Hoshino (\:661f\:91ce\:30cc\:30fc\:30eb)"},
   "copyrightInformation" -> "\[Copyright] Computational Classnotes \[CenterDot] CC BY-NC-SA 4.0", "contactInformation" -> "https://lossofgenerality.github.io/ccn-pyon/library.html",
   "references" -> {"https://lossofgenerality.github.io/ccn-pyon/"}, "licenseUrl" -> "https://vrm.dev/licenses/1.0/", "avatarPermission" -> "everyone",
   "allowExcessivelyViolentUsage" -> False, "allowExcessivelySexualUsage" -> False, "commercialUsage" -> "personalNonProfit", "allowPoliticalOrReligiousUsage" -> False,
   "allowAntisocialOrHateUsage" -> False, "creditNotation" -> "required", "allowRedistribution" -> True, "modification" -> "allowModificationRedistribution",
   "otherLicenseUrl" -> "https://creativecommons.org/licenses/by-nc-sa/4.0/"|>;
vrmSprings[cr_, nid_] := <|"specVersion" -> "1.0", "springs" -> Function[{nm, chain}, With[{soft = nm == "tail"},
      <|"name" -> nm, "joints" -> (<|"node" -> nid[#], "hitRadius" -> .02, "stiffness" -> If[soft, .9, 1.6], "gravityPower" -> If[soft, .05, 0], "gravityDir" -> {0, -1, 0}, "dragForce" -> If[soft, .35, .55]|> & /@ chain)|>]] @@@ cr["springs"]|>;
vrmBuild[cr_, thumb_ : None] := Module[{g = vrmNewGLB[], mats, names, pos, nid, jindex, faceNode, meshNodes, meta, head},
  mats = vrmAddMaterials[g, cr["colours"]];
  {names, pos, nid, jindex} = vrmAddSkeleton[g, cr];
  {faceNode, meshNodes} = vrmAddMeshes[g, cr, mats, jindex];
  g[["j", "scenes", 1, "nodes"]] = Prepend[meshNodes, 0];
  meta = vrmMeta[cr]; If[thumb =!= None, meta["thumbnailImage"] = vrmImage[g, thumb]];
  head = pos["head"];
  g[["j", "extensions"]] = <|"VRMC_vrm" -> <|"specVersion" -> "1.0", "meta" -> meta,
      "humanoid" -> <|"humanBones" -> AssociationMap[<|"node" -> nid[#]|> &, Select[names, ! StringStartsQ[#, {"tail", "ear_"}] &]]|>,
      "firstPerson" -> <|"meshAnnotations" -> Join[If[faceNode =!= None, {<|"node" -> faceNode, "type" -> "thirdPersonOnly"|>}, {}], {<|"node" -> If[faceNode =!= None, faceNode - 1, First[meshNodes]], "type" -> "auto"|>}]|>,
      "lookAt" -> <|"offsetFromHeadBone" -> {0., cr["eyesY"] - head[[2]], 0.24}, "type" -> "expression",
        "rangeMapHorizontalInner" -> <|"inputMaxValue" -> 90, "outputScale" -> 1|>, "rangeMapHorizontalOuter" -> <|"inputMaxValue" -> 90, "outputScale" -> 1|>,
        "rangeMapVerticalDown" -> <|"inputMaxValue" -> 90, "outputScale" -> 1|>, "rangeMapVerticalUp" -> <|"inputMaxValue" -> 90, "outputScale" -> 1|>|>,
      "expressions" -> <|"preset" -> If[faceNode =!= None, vrmExpressions[cr, faceNode], <||>]|>|>,
    "VRMC_springBone" -> vrmSprings[cr, nid]|>;
  g[["j", "extensionsUsed"]] = {"VRMC_vrm", "VRMC_materials_mtoon", "VRMC_springBone"};
  g];
vrmMain[] := Module[{out = FileNameJoin[{vrmRoot, "art", "vrm", "wolfram"}]},
  Quiet[CreateDirectory[out, CreateIntermediateDirectories -> True]];
  Table[With[{cr = make[1.], png = FileNameJoin[{vrmRoot, "art", "vrm", ToLowerCase[make[1.]["name"]] <> ".png"}]},
     FileNameTake[FileNameJoin[{out, ToLowerCase[cr["name"]] <> ".vrm"}], -3] -> vrmWrite[vrmBuild[cr, If[FileExistsQ[png], ReadByteArray[png], None]], FileNameJoin[{out, ToLowerCase[cr["name"]] <> ".vrm"}]]],
    {make, {vrmMochi, vrmOnigiri}}]];
vrmMain[]

10. Stage 9 · Checking: Wolfram against Python

  1. The glTF validator (Khronos, npm gltf-validator) finds 0 errors and 0 warnings in both Wolfram files, as in the Python ones.
  2. The JSON is the same, key for key and in the same order, integers where Python wrote integers and decimals where it wrote decimals, except for two things: the generator names the notebook in place of the Python file; and the last one or two of the seventeen significant digits of 18 colour numbers in Mochi and 13 in Onigiri, because x^2.4 (sRGB to linear) is computed by different mathematics libraries in the two languages.
  3. The binary buffer has the same length, 912,404 bytes for Mochi and 706,564 for Onigiri, with every bufferView at the same offset. Every integer is identical: every triangle, every joint number. Of the 150,928 decimal numbers in Mochi’s buffer, 276 differ, by at most 3.5 × 10⁻¹⁸ m; of Onigiri’s 113,738, 24 differ, by at most 1.8 × 10⁻¹⁵ m. These are numbers that are almost zero (a normal’s tiny component, a target’s tiny shift), whose last bit depends on the order in which a sum or a division is done; a millionth of a millimetre is 10⁻⁹ m.
  4. The real VRM loader draws them identically. Figure WL-7 shows each file in three.js with three-vrm, as the avatar programs load them, beside the Python file, and the difference between the two pictures, pixel by pixel: in all four views not one pixel differs.
  5. So either pair can be used, in Clown Run, VRoid Hub or any VRM program. The published avatars remain the Python ones in art/vrm/; the Wolfram ones are in art/vrm/wolfram/.
Figure WL-7 · Both files in the real VRM loader, and their difference

11. Python and Wolfram side by side

Python (tools/make-vrm.py) Wolfram (tools/ff_makevrm.nb) What changes
lin, darker vrmLin, vrmDarker FromDigits[ , 16] and IntegerString[ , 16, 2] read and write hexadecimal
np.linspace vrmLinspace written out, as NumPy computes it
rot_to, sphere, ellipsoid, tube, lathe, smooth vrmRotTo, vrmSphere, vrmEllipsoid, vrmTube, vrmLathe, vrmSmooth lists are arrays; Cross, Normalize and . are built in; Reap and Sow gather triangles
the loops that sum triangle normals vrmVertexNormals one function for Onigiri’s body and its nori
class Part vrmPart an Association
on_surface, squash vrmOnSurface, vrmSquash the same formulas
skeleton, y_weights, tail_w vrmSkeleton, vrmYWeights, vrmTailWeights weights are associations, <|bone -> weight|>
mochi, onigiri, shape, front vrmMochi, vrmOnigiri, vrmOnigiriShape, vrmFront a creature is an Association
targets_for_face vrmFaceTargets, vrmWithMorphs returns the targets instead of changing the parts
(a browser and three.js) vrmDraw, vrmDrawSkeleton, vrmDrawWeights, vrmMorphed, vrmSheet Graphics3D in the notebook
class GLB: view, acc, image, write vrmNewGLB, vrmBufferView, vrmAccessor, vrmImage, vrmWrite NumericArray, ExportByteArray, BinaryWrite; HoldFirst in place of self
mtoon, add_materials, add_skeleton, add_meshes vrmMToon, vrmAddMaterials, vrmAddSkeleton, vrmTopFour, vrmAddMeshes the same JSON, built as associations
expressions, vrm_meta, springs, build, main vrmExpressions, vrmMeta, vrmSprings, vrmBuild, vrmMain the same

© Computational Classnotes · CC BY-NC-SA 4.0