Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Kits — domain knowledge, ordinary Manic composition

The words so far (circle, move, flash, for…) are the core. On top of that, manic ships kits — bundles of higher-level figures for a domain. You use them exactly like any other call.

math

Coordinate frames, function plots, vectors, tables:

axes(ax, (cx, cy), 520, 240);            // a coordinate frame
plot(wave, (cx, cy), 78, 120, "sin(x)"); // y = f(x) from a formula
tangent(t, wave, 0.5);                    // the tangent line + dot at x = 0.5
vector(v, (cx, cy), (120, -90));         // an arrow from an origin
matrix(m, "1 0; 0 1", (cx, cy));         // a bracketed matrix

geo

Olympiad-style constructions — you write the geometry, not coordinates, and everything is live (drag a point and the circumcircle, centroid, angles all recompute):

point(A, (300, 500));  point(B, (900, 500));  point(C, (620, 180));
circumcircle(cc, A, B, C);   // recomputes if A/B/C move
midpoint(m, A, B);

algo

Data structures and algorithms — arrays + sorting, linked lists, stacks/queues, graphs, hash maps, BFS/DFS, Dijkstra:

array(a, "5 2 8 1", (cx, cy));  compare(a, 0, 1);  swap(a, 0, 1);
graph(g, "a b c d", "a-b:2 b-c:1 c-d:3", circular, (cx, cy), 200);
dijkstra(g, a);                 // animates shortest paths

Groups make these one-liners: a graph tags its nodes and edges, so draw(g.edges) or flash(g.nodes, cyan) animates the whole set.

ml

Small neural-network explanations whose displayed activations and probabilities come from the declared model rather than a staged effect:

network(net, (cx, cy), "3 6 4 3", "relu tanh softmax", 820, 350, 21);
forward(net, "0.15 0.92 0.38", 4.2, smooth);
loss(net, "1 0 0", crossentropy, 1.5, smooth);
backward(net, 3.2, smooth);
checkpoint(beforeUpdate, net);
update(net, 0.18, 2.3, smooth);
restore(net, beforeUpdate, 2.3, smooth); // exact rollback, not general unlearning

tensor(image, (260, 340), "0 0 1; 0 1 1; 0 0 1", 44);
kernel(edge, (560, 340), "-1 0 1; -2 0 2; -1 0 1", 44);
convolve(feature, image, edge, (850, 340), 1, 1, 0, relu, 44);
scan(feature, 4.0, smooth);

tokenize(words, (650, 150), "the cat chased the cat", word, 900);
embedding(context, words, (650, 470), "seeded 6 37", sinusoidal, 1080, 430);
transformer(block, context, (650, 500),
  "heads=2 mask=causal mlp=12 activation=gelu norm=pre dropout=0 mode=inference seed=41",
  1120, 520);
encode(block, 6.2, smooth);
logits(next, block, 5, (650, 500),
  "reason | predict | learn | adapt | explain | .", 0.8, 760, 440, 73);
sample(next, "top-p 0.90 seed=17", 3.8, smooth);

attention(head, (650, 360), "Art | ificial | intelligence | transforms | business",
  "1 0.2 -0.4 0.7; 0.8 0.1 -0.3 0.6; -0.2 1 0.5 0.3; 0.1 0.6 0.9 -0.2; 0.7 -0.1 0.4 1",
  980, 420, 23);
attend(head, 3, 5.2, smooth);

Use activation to introduce a scalar activation curve, then network and forward to follow one computation. Add loss, backward, and update for one explicit, numerically truthful learning step. Use tensor, kernel, convolve, pool, and the shared scan for CNN/operator stories. Large layers automatically reduce visual detail without reducing the numerical model. Use tokenize and embedding to reveal honest token boundaries, stable lookup vectors, exact positional values, and their elementwise sum. Use transformer and encode for one complete multi-head block with masking, normalization, residuals, MLP, and truthful training/inference dropout. Use logits and sample to keep the separate LM projection, temperature-scaled full softmax, filtering, renormalization, and seeded next-token choice truthful. Use attention and attend for one focused, exact self-attention head; add topk only when a deterministic educational candidate ranking helps the story. See Machine learning — models made visible.

three (3D)

A whole second world — a camera, solids, surfaces, and curves in real 3D space, which you spin and morph. Every 3D word ends in 3:

camera3((8, -10, 6), (0, 0, 1), 45);      // an eye to look through
cube3(box, (0, 0, 1), (2, 2, 2));         // a shaded box
revolve3(vase, (3, 0, 1.5), "0.7+0.4*sin(t*2)", (0, 3));  // spin a profile
orbit3(70, 25, 12, 4, smooth);            // swing the camera around

It has its own chapter — see Going 3D.

stats

Turn data — or a random process — into a picture that reveals its shape, centre, and spread. Each builtin animates a process: a histogram builds up bar by bar, sample means pile into a bell, a running proportion settles onto the truth.

histogram(h, (cx, cy), "72 85 90 68 95 88 76 91 83", 8, 640, 300, rainbow);
bellcurve(b, (cx, cy), 100, 15);          // the 68-95-99.7 rule
clt(c, (cx, cy), 5, 1200);                 // the Central Limit Theorem

histogram · summary · boxplot · skew · bellcurve · correlation · lln · clt · hypothesis · covariance · bayes · distribution · confidence · montecarlo · randomwalk. Seeded, so renders are reproducible.

physics

Simulations built from their physics and pre-simulated with RK4 at build time, so every render is deterministic. Each sim’s parts are ordinary manic entities, and the optional views (phase · well · timegraph · energygraph) show the same motion as math panels. run(id) (alias swing) plays it.

pendulum(p, (cx, 200), 2, 50);   phase(p, (980, 200), 120);
well(p, (980, 470), 120);        run(p, 8);   // one swing, three views
doublependulum(dp, (400, 240));  par { run(dp, 12); draw(dp.path, 12); }  // chaos

Pendulum family: pendulum · doublependulum · springpendulum · kapitza · cartpendulum · comparependulum. Spring family: spring · verticalspring · springincline · bungee · resonance · doublespring · seriesparallel · carsuspension. Mechanics: robotarm · piston · molecule · ramp (with a forces(id) free-body diagram) · inclinepulley · doubleincline · inclinebumper · springchain · looptrack (a curved-track loop-the-loop) · stringwave (a wave on a string) · newtonscradle · collideblocks · bulletblock (event-driven collisions) · dropmass · raft · brachistochrone. Pulleys: pulley (Atwood) · pulleyscale (reads the tension) · blocktackle (N-strand block & tackle) · compoundpulley (fixed + movable, masses A/B/C).

Because a sim’s parts are ordinary entities, any base look composes over them — e.g. template("paper") + a hatched support turns a pulley or spring into a textbook figure (see Elevating a scene and the *-paper examples).

optics

Light as geometry, with the real physics underneath — Snell’s law, Sellmeier dispersion, and full spherical/aspheric ray tracing — so the bending, the colours and the focus are earned, not painted. Each builtin is static geometry that animates by a parameter sweep (run(id)) or by sketching its rays on (draw(id.rays)).

refract(r, (640, 380), 1.0, 1.52);   run(r, 7);   // Snell's law; run sweeps the angle (→ TIR)
lens(l, (620, 360));                 run(l, 7);   // parallel rays → a focal point
prism(p, (560, 400), "sf11");        run(p, 7);   // white light → a real rainbow (dispersion)

Foundations: refract (Snell + total internal reflection) · lens (a converging thin lens). Dispersion: prism (white → spectrum) · achromat (chromatic aberration → the doublet fix). Real lenses: lenssystem(id, [center], [preset], [object]) traces a prescription through its actual spherical/aspheric surfaces — pick a design by name ("singlet", "plano-convex", "aspheric", "doublet", "triplet") or write your own surface table "radius thickness glass [conic] [aperture] | …"; an optional finite object distance images a nearby point. Analysis: rayfan (the ray-fan aberration plot) · spotdiagram (the on-axis spot at focus) · fieldspot(id, [center], [preset], [field]) (the off-axis spot — a coma comet / astigmatic blur, with an Airy-disk diffraction-limit overlay). A rainbow glows on the dark bench; the geometric ray diagrams also take template("paper") for a textbook look.

chem

Real molecules, from real filesmolecule3 reads an MDL structure file (a PubChem Download → SDF, or a .mol) and lays out its atoms and bonds as ordinary 3-D entities. Nothing about the shape is authored: the coordinates are the file’s, in Ångströms.

camera3((0, -14, 4), (0, 0, 0), 40);
molecule3(caf, "asset:molecules/caffeine.sdf");        // turns by default
color(caf.N, cyan);                                    // every nitrogen
molecule3(bz, "asset:molecules/benzene.sdf", (6,0,0), 1.2, "style=sticks hydrogens=0");

Four styles (ball & stick, sticks, wireframe, space-filling), hydrogens on or off, and a slow turn about its own axis on by default, because a shape only reads in three dimensions. Atoms are CPK/Jmol coloured and sized by covalent radius; every atom is tagged by its element, so color(caf.N, cyan) addresses the chemistry rather than an index. 26 molecules bundled.

structure is the flat half: the skeletal formula from a file’s 2-D depiction coordinates — carbons as bare vertices, OH/NH2 folded from the explicit hydrogens, double bonds leaning into the ring, wedge and hash bonds where the file records stereochemistry.

template("paper");
structure(glc, "asset:molecules/glucose-2d.sdf", (400, 360), 62);
untraced(glc.bonds);
stagger(0.05) { draw(glc.bonds, 0.4); }   // written on, bond by bond

See the chemistry guide.

circuit

A netlist in, a working schematic out — Modified Nodal Analysis under easy builtins, so every voltage, current and glow on screen was solved, not drawn, and pre-simulated at build time so it scrubs and records exactly.

circuit(rc, (640, 360), `
  dc-voltage 0 4 0 0 v=5
  resistor   0 0 5 0 r=1k name=R1
  capacitor  5 0 5 4 c=1u
  wire       5 4 0 4
  ground     0 4
`);
probe(rc, (5, 0));      // 63.2% of 5 V at one time constant
run(rc, 6);             // draws itself, then charges
cut(rc, R1, 0.8);       // take the resistor out …
run(rc, 3);             // … and nothing flows

The topology comes from the geometry — coinciding points, or points joined by a wire, are the same node, so there are no node numbers to write. The schematic draws itself one component at a time and each prefix of the netlist is really solved, so nothing flows until the loop closes. A lamp glows because it is dissipating power. cut re-solves what is left from scratch, which is why breaking a series loop darkens every lamp in it.

44 component types: passives and sources, six kinds of switch, junctions (diode/led/zener), eight transistors (bipolar, MOSFET, JFET, Darlington), opamp/comparator/schmitt/vco/transmission-line, and the logic family down to flip-flops. current(id, speed, shape, color, size) is the animator’s dial; probe and scope are the instruments. Everything is an ordinary tagged entity, so framebox, zoom, cam and pulse do the presentation.

See the circuits guide for the end-to-end walkthrough.

creator

A format layer (not a subject): responsive, pre-timed social-video templates a content creator fills in—question, answers, media and a reusable profile. V2 adapts the same source to 9:16, 4:5, 1:1 and 16:9, with named platform safe areas, a polished studio default, configurable motion/timers, responsive footers and end cards.

canvas("9:16"); template("shorts");
creator(me, "@anish2good name=Math_With_Me yt=zarigatongy x=@anish2good web=maniclang.com footer=social accent=magenta");
quiz(q, "What is 7 x 8?", "studio labels=letters pace=calm motion=calm");
option(q, "54"); option(q, "56", correct); option(q, "48"); option(q, "63");
timerstyle(q, "look=segments position=media finish=pulse");
run(q, 8);                                  // scales the calm ask → think → reveal beat
socials(me);
endcard(me);                                // reveal later with show(me.endcard)

quiz(id, "question", ["style"]) starts the format; style mixes a card skinstudio (rounded editorial default) · badge (framed panel + coloured letter badges) · minimal (kicker + accent rule, outline rows) · glass (glowing borders) · plain (flat) — and a question revealtype (typewriter, default) · fade · rise · pop · cut. option(id, "text", [correct]) adds an answer; run auto-lays-out one to six cards, fits their type, slides them in, plays the selected native timer, and lights up the correct card (green badge + check). timing(id,"preset ask=... options=... think=... reveal=... hold=... stagger=...") separates exact choreography from timerstyle(id,"look=... position=... direction=... finish=..."). The zero-config default remains a balanced draining ring; run(id,dur) scales a preset, while an explicitly timed quiz uses run(id) so authored seconds remain exact. Also standalone: countdown(id, [at], [secs], ["style"]), safezone(id, [inset|"profile"]), figure(target, [center], [size]), optional explain, and endcard. Social icons are vector-drawn with normalized native marks for YouTube, X, Instagram, TikTok, Facebook, LinkedIn, GitHub, web, and email. Profile values appear beside up to three icons; no image or SVG assets are required.


Each kit has a full reference at https://docs.maniclang.com, and you can see them all in motion in the Examples gallery.