daynight.js
A free, open-source 3D engine for the web. Neon-grade lighting, physics, picking and spatial sound from one script tag, no build step.
<script src="https://sayuptalk.com/games/daynight.js"></script>Version 1.0.0. MIT license. 272 KB readable, 204 KB minified.
Lighting that sells it
Deferred WebGL2 pipeline with a compact 16-byte G-buffer (half the old size), 3D clustered lights (up to 128), cascaded shadows, image-based reflections, bloom, ACES tone mapping and a full colour grade.
A scene you can touch
Boxes, spheres, capsules, tubes, glTF models and particles, with click and hover events, orbit and fly controls, tweens and simple physics.
Matter that flows
New in 1.2: fluids and swarms that pour, splash, scatter and pull themselves back into shapes; a collision world of boxes; and a third-person character with smooth, camera-relative turning.
Sound in space
HRTF spatial audio that rides on the camera. Attach a hum to a machine and hear it pass from ear to ear as you orbit. Synth presets included.
Saves that heal
Sealed saves with checksums and Reed-Solomon repair keep two copies and mend a damaged one when it loads.
Get started
Add the script
Any page, any server. It defines one global, DN.
<script src="https://sayuptalk.com/games/daynight.js"></script>
Make a stage
Give it an element. The stage fills it, keeps itself sized, and adds orbit controls you can turn off.
<div id="stage" style="height:480px"></div> <script> const app = DN.create('#stage', { environment: 'neon' }); </script>Add things and make them react
Shapes take a position, a size and a material. Events work on every object.
app.add(DN.plane({ size: [40, 40], color: '#1b1033', pattern: 'panels' })); const orb = app.add(DN.sphere({ position: [0, 1.2, 0], radius: 1, color: 'pink', emissive: .6 })); app.add(DN.light({ position: [0, 3, 0], color: 'orange', range: 10 })); orb.on('click', () => { app.burst('spark', orb, 40); // particles app.play('chime', { at: orb }); // a sound placed in 3D }); app.on('update', (dt, t) => { orb.y = 1.2 + Math.sin(t * 2) * .2; });
Playground
Edit the code and run it. It runs in a sandboxed frame with daynight.js already loaded and a full-size #stage.
API
The app
DN.create(target, options) returns an app. target is a selector, an element or a canvas; leave it out for a full-window stage. The world is Y-up with +Z away from a camera at yaw 0. Angles are radians.
| environment | Preset look: 'neon' (default), 'sunset', 'day', 'noir', 'studio', 'space'. |
| camera | { position, target, yaw, pitch, fov } |
| controls | 'orbit' (default), 'fly' (WASD, Q/E, drag to look) or false. Orbit settings go in orbit: { target, distance, minDistance, maxDistance, minPitch, maxPitch, autoRotate, autoRotateDelay, damping, zoom, pan, rotate, keys }. |
| quality | 'auto' (default), 'low', 'medium', 'high', 'ultra', 'retro' (CPU renderer) or a resolution scale such as 1.25. |
| look | 'cinematic' (HDR, bloom, grade) or 'classic' (the dithered retro look). |
| fx, sky, fog | Overrides for the environment (see Light and atmosphere). |
| shadows, shadowRadius, ao | Sun shadows on or off (default on), the shadowed radius around the camera, ambient occlusion strength. |
| physics | true or { gravity, ground } to create app.physics. |
| autoStart | Start the render loop right away (default true). |
| width, height, maxPixels, alwaysRender | Fixed size, a cap on the drawing buffer, and whether to keep drawing while scrolled out of view. |
| app.add(...nodes) | Adds to the scene and returns the first node. |
| app.remove(...nodes), app.find(name) | Remove, or find by name. |
| app.start(), stop(), pause(on) | Control the loop. app.timeScale slows or speeds time. |
| app.step(dt), app.render() | Advance and draw by hand (offline rendering, tests). |
| app.snapshot(type) | A data URL of the current frame. |
| app.stats(), app.fps | Frame rate, object count and renderer counters. |
| app.destroy() | Stops everything and frees the GPU. |
| app.scene, camera, controls, canvas, overlay, time, dt, gpu | The root node, the camera, the controls, the canvas, the label layer, seconds elapsed, the last step, and whether WebGL2 is in use. |
Shapes and nodes
Every shape is a node. Nodes have name, position, rotation as [pitch, yaw, roll] (or the yaw, pitch, roll, x, y, z shortcuts), scale, visible, pickable and data. Positions are centres.
| DN.box({ size }) | [w, h, d], or width, height, depth. |
| DN.sphere({ radius }) | |
| DN.ellipsoid({ size }) | Turns around Y only. |
| DN.capsule({ radius, radius2, height }) | Or from and to points. radius2 tapers it. |
| DN.cylinder / DN.cone({ radius, height, segments }) | Or from and to points. |
| DN.tube({ points, radius }) | A smooth tube through points. Pair it with DN.curve(points).sample(n). |
| DN.plane({ size: [w, d] }) | Flat, facing up. |
| DN.mesh({ faces }) | Your own convex polygons: [[[x,y,z], ...], ...]. |
| DN.group() | An empty node to move things together. |
| DN.light({ color, intensity, range }) | A point light. Children of moving nodes move with them. |
| DN.label({ text | html, offset, anchor, fade, className, onClick }) | HTML that follows a point. app.label(text, { at: node | [x,y,z] }) is the shortcut. |
| node.add(...), remove(...), destroy() | Build a hierarchy. Children inherit position, rotation and scale. |
| node.set({ ... }) | Assign several properties at once, including material ones. |
| node.lookAt(point | node) | Turn +Z toward something. |
| node.worldPosition(), forward(), localToWorld(p) | Where it is after its parents. |
| node.traverse(fn), find(name), findAll(test) | Walk the tree. |
Materials
Pass material settings straight to a shape, or change them later on node.material (node.color and node.emissive are shortcuts). Colours accept '#ff3ea5', '#f3a', 'rgb(255,62,165)', 0xff3ea5, [255, 62, 165] and names like 'pink', 'violet', 'orange', 'cyan'.
| color, emissive | Base colour; glow from 0 up (bloom picks it up). |
| metalness, roughness, specular, clearcoat | Physically based surface. |
| pattern | A GPU texture: 'bricks', 'planks', 'plaster', 'shingles', 'panels', 'sand', 'rock', 'weave', 'tiles', 'stripes', 'diamond', 'waves', 'stone', 'speckle', 'blocks', or a number. |
| outline | false removes the ink outline around the shape. |
Light and atmosphere
| app.environment(name | object) | Switch presets at any time. |
| app.sky(top, horizon) | Sky gradient. |
| app.sun(direction, color, intensity) | The key light and its shadows. |
| app.ambient(k, skyColor, groundColor) | Fill light from above and below. |
| app.fog(distance, density, color) | |
| app.fx({ ... }) | Post effects: bloom, thr, exp, vig, grain, sat, con, lift, gamma, gain, tint, rays, dof: [focus, range, amount], mblur, ca, clouds, stars, outline, fade, taa. app.fx(null) switches to the classic look. |
| app.reflections(at, box) | Capture the scene around a point for reflections on shiny surfaces. |
| app.texture(key, image) | Register an image for models. |
Camera and controls
| camera.position, yaw, pitch, fov | Positive pitch looks down; yaw turns right. |
| camera.lookAt(point | node) | |
| camera.project(point) | { x, y, depth } on the stage, or null behind the camera. |
| camera.ray(x, y) | A world ray through a stage point. |
| camera.forward(), right(), up() | |
| controls.focus(target, distance, { yaw, pitch, duration }) | Glide the orbit somewhere. |
| controls.target, distance, yaw, pitch, autoRotate | Orbit state you can read and set. |
Events and picking
Listen with on, once and off. Object events bubble to parents, so a click on any part of a group reaches the group. Set node.cursor = 'pointer' to change the cursor on hover.
| click, dblclick, pointerdown, pointerup | On objects and on the app. The event has target, point, distance, x, y and stopPropagation(). |
| pointerenter, pointerleave | Hover, on objects. |
| update (dt, t), fixed (dt) | Every frame; and at a steady 60 per second. |
| render, draw (R), resize, rebuild, contextlost, destroy | App lifecycle. |
| app.pick(x, y, { filter }) | The nearest object under a stage point: { object, point, distance }. |
Tweens and particles
| app.tween(target, to, { duration, ease, delay, loop, yoyo, onUpdate, onComplete }) | Animate numbers, arrays (position, scale) and colours. Await it, or call .stop(). Eases: linear, inOutSine, outCubic, inOutCubic, outQuint, outBack, outElastic, outBounce and more in DN.ease. |
| app.wait(seconds) | A promise on the app's clock. |
| app.burst(kind, at, count, { d, sp, sz, r, c }) | Kinds: spark, flash, smoke, dust, fire, ember, steam, mote, glass, money, splash, rain, hay, spit, drip. |
| DN.emitter({ kind, rate, direction, speed, size, spread, color }) | A node that keeps emitting. |
| app.defineParticle(name, preset) | Your own kind. |
| app.shatter(node, { pieces, power }) | Break a box into rigid shards. |
Physics
Spheres and boxes with gravity, a ground plane, bounces, friction and sleeping. Bodies should be direct children of the scene.
| app.physics.add(node, { mass, static, velocity, restitution, friction, shape, radius, size }) | Shape comes from the node unless you set it. |
| app.physics.impulse(node, [x, y, z]) | A push. |
| app.physics.gravity, ground | Default [0, -9.8, 0] and 0 (null for no ground). |
| app.world = DN.world() | Bodies also collide with the world's solid boxes (walls, crates, steps), bounce off them and rest on top. See Characters and worlds. |
| Many bodies | Above 40 bodies, pairs are found with a uniform grid, so only neighbours are tested. |
Fluids and swarms
A fluid is a node holding many small particles. Loose particles fall, splash, slide and settle, keeping their spacing and smoothing their velocities so they move like a liquid. Bound particles spring toward targets, so the same particles can pour into a tank, hold a word, burst apart and pull themselves back together.
| DN.fluid({ count, radius, color | colors, emissive, viscosity, stiffness, damping, gravity, curl, world, maxAge }) | count is the most particles it holds. curl adds a gentle swirl to bound particles; maxAge (seconds) retires loose ones. |
| fluid.pour(n, at, velocity, spread) | Adds up to n loose particles at a point. Returns how many it made. |
| fluid.shape(points | fn(i, n, time), { fill }) | Hold a shape in the node's own space; fill makes any missing particles. A function animates it. |
| fluid.text(string, { width, fill }) | A word made of particles in the node's XY plane. |
| fluid.scatter(at, count, speed) | Knocks the nearest bound particles loose. Returns how many. |
| fluid.gather(at, radius, dt) | Call each frame to pull loose particles back into the shape. |
| fluid.release(), clear(), count, bound | Let everything flow; remove everything; how many exist; how many are holding the shape. |
| fluid.swarm | The simulation underneath (DN.matter.Swarm): typed arrays of positions, velocities and targets for your own effects. |
Characters and worlds
A world is a set of solid boxes that characters, fluids and physics bodies respect. A character walks relative to the camera: it turns smoothly toward where you push, so a short tap turns a little, holding keeps turning, and it never overshoots. It steps up low ledges, slides along walls and jumps.
| DN.world({ cell }) | An empty world. Set app.world to share it with physics and fluids. |
| world.box(min, max) | A solid box by its corners. Returns a handle; set handle.on = false to switch it off, like an open door. |
| world.addScene(node, filter) | Every visible box mesh under node becomes a solid. |
| world.raycast(origin, dir, maxDistance), lineOfSight(a, b) | The first box a ray hits, as { t, q, n }; whether two points can see each other. |
| app.character(node, { world, speed, runSpeed, jump, turnRate, step, radius, height, camera, distance, cameraHeight, pitch }) | Takes over the controls. WASD or arrows move, Shift runs, Space jumps, Q and E or a drag turn the camera, a gamepad works too; on touch screens the left half is a joystick. Events: jump, land, move. |
| DN.steer(state, goal, dt, { rate, accel, brake }) | The same smooth turning for anything with a heading state.a: enemies, vehicles, cameras. |
| DN.spin(state, axis, dt, { rate }) | Tank-style turning from a -1 to 1 axis: a tap turns a few degrees, holding ramps up. |
Spatial audio
Browsers keep sound off until the person clicks, taps or presses a key; daynight.js unlocks audio on that first input for you. The listener follows the camera.
| app.sound(src, { at, loop, volume, rate, spatial, doppler, reverb, refDistance, maxDistance, rolloff, occlusion, cone }) | A sound in the scene. src is a URL, an AudioBuffer or a synth preset. at a node or point. |
| sound.play(), stop(), fadeTo(volume, seconds) | Also volume, rate, occlusion (0 to 1 muffles it). |
| app.play(src, { at, volume, rate }) | Fire and forget. |
| Synth presets | blip, click, chime, coin, hit, thud, zap, laser, powerup, error, whoosh; loops: hum, drone, engine, wind. Add your own with DN.defineSynth(name, seconds, t => sample, loop). |
| DN.audio.mute(on), setVolume(v), room(seconds, decay), load(url), unlock() | The shared mixer. |
glTF models
| DN.model(url | ArrayBuffer, { scale, animation, speed, autoplay, tint }) | .glb or .gltf with skins, animations and base-colour textures, on the GPU skinning path. Add it straight away; it appears when loaded. model.ready is a promise. |
| model.play(nameOrIndex), stop(), animations, time, speed |
Saves
| app.save(key, data) | Seals the data (checksums and Reed-Solomon repair) and keeps two copies in localStorage. |
| app.load(key, fallback) | Repairs small damage, falls back to the other copy, heals the broken one. |
| DN.vault | The sealing layer itself: seal, unseal, load, crc32, sha256. |
Utilities
| DN.curve(points, closed) | Catmull-Rom curve: at(t), atLength(u) for even speed, tangent(t), sample(n), length. |
| DN.random(seed) | Seeded random numbers with range, int and pick. |
| DN.noise(x, y, seed) | Smooth value noise from 0 to 1. |
| DN.color(c), DN.V3, DN.lerp, DN.clamp | |
| DN.supported() | { webgl2, audio }. Without WebGL2 the app falls back to the CPU renderer by itself. |
The engine underneath
app.R is the Poly3D-GL renderer the SayUp Talk games use, with its immediate-mode calls (box, ell, cap, chain, light, emit, skinDraw and more). Draw extra things in the draw event. DN.engine holds the renderer constructors and particle presets.
Examples
daynight.js is free software under the MIT license. Copyright 2026 Golden Era Holdings / SayUp Talk. Read the license.