@iagows/3d-dice-ts
v0.3.1
Published
A 3D environment for rolling game dice using threejs and cannon-es
Maintainers
Readme
🎲 @iagows/3d-dice-ts
Physics-based 3D dice for the web. Three.js + Cannon-ES.
✨ Features
- 🎲 7 dice types - d4 · d6 · d8 · d10 · d100 · d12 · d20
- ⚛️ Real physics (Cannon-ES) rendered with Three.js
- 🎯 Random & predetermined results - force any face, the throw still looks natural
- 🎨 31 color sets · 4 materials (glass · metal · wood · none) · per-face colors
- 🧰 Bring-your-own assets - inject custom textures, color sets & surface themes at runtime
- 🔊 Collision sounds
- 📐 RPG dice notation -
2d20+1d6 - 🧩 Results via Promise, callback, or DOM event
- 🛠️ reroll / add / remove dice at runtime
- 📘 TypeScript types bundled - Three.js & Cannon-ES stay as peers
📦 Install
npm install @iagows/3d-dice-ts three cannon-esthree and cannon-es are peer dependencies.
Copy the runtime assets (textures + sounds) into your static folder:
cp -r node_modules/@iagows/3d-dice-ts/public ./public/dice-box🚀 Quick start
import DiceBox from "@iagows/3d-dice-ts";
const box = new DiceBox("#scene-container", { assetPath: "/dice-box/" });
await box.initialize();
const result = await box.roll("2d20+1d6");
// { notation: "2d20+1d6", sets: [...], modifier: 0, total: 27 }The container needs a defined size. A <canvas> is rendered inside it.
Types are bundled: import type { DiceBoxConfig, RollCompleteResult } from "@iagows/3d-dice-ts";
🎯 Predetermined outcomes
Append @ and the forced face values:
box.roll("6d6@4,4,4,4,4,4"); // all six land on 4
box.roll("2d20@20,1"); // first → 20, second → 1Physics runs freely; geometry is swapped at settle time so the right face ends up on top.
🎨 Theming
Swap the look at runtime - no full reload:
await box.loadTheme({ colorset: "fire", texture: "", material: "glass" });- 31 color sets (
white,fire, …) - 4 materials -
none·metal·wood·glass - Per-face colors via
theme.faceColors - Toggle pips/numbers with
theme.showNumbers
Custom assets (catalog)
Inject your own textures, color sets, and surface themes through the catalog
option. Entries are merged over the built-ins - matching keys override, the
rest still resolve - then referenced by key from theme:
const box = new DiceBox("#scene", {
assetPath: "/dice-box/",
catalog: {
textures: {
galaxy: {
name: "Galaxy",
composite: "multiply",
source: "textures/galaxy.png", // webp · png · jpg · jpeg · gif · avif · svg
source_bump: "",
},
},
colorsets: {
nebula: {
name: "Nebula",
foreground: "#fff",
background: "#1a0b3e",
outline: "black",
texture: "galaxy", // references the custom texture above
},
},
},
theme: { colorset: "nebula" },
});Unsupported file extensions warn but still load (so data:/blob: URLs work);
structurally invalid entries throw. The supported list is exported as
SUPPORTED_TEXTURE_EXTENSIONS. The built-in TEXTURELIST, COLORSETS, and
THEMES maps are exported too, so you can spread and extend them.
The
catalogis applied once at construction; it is not re-read byupdateConfig.
📥 Getting results
Pick what fits your architecture.
// Promise
const result = await box.roll("4d6");
// Callback
new DiceBox("#scene", { assetPath: "/dice-box/", onRollComplete: (r) => {} });
// DOM event
document.addEventListener("rollComplete", (e) =>
console.log((e as CustomEvent).detail),
);📖 API
| Method | Description |
| --------------------------------- | --------------------------------------- |
| new DiceBox(container, config?) | container: CSS selector or element |
| initialize() | Build scene/physics/renderer. Call once |
| roll(notation) | Clear dice and roll a new set |
| reroll(diceIds) | Reroll specific dice by ID |
| add(notation) | Add dice without clearing |
| remove(diceIds) | Remove dice by ID |
| updateConfig(config) | Update config and rebuild |
| loadTheme(themeConfig) | Swap theme only |
| destroy() | Tear down + free the WebGL context |
const result = await box.roll("4d6");
const lowest = result.sets[0].rolls.sort((a, b) => a.value - b.value)[0];
await box.reroll([lowest.id]);⚙️ Config
{
assetPath: "", // required - path to the copied /public assets
framerate: 1 / 60,
sounds: true,
volume: 100,
color_spotlight: 0xefdfd5,
shadows: true,
sound_dieMaterial: "plastic",
theme: { // visual selection (since 0.2.0 - was flat theme_* keys)
surface: "green-felt",
colorset: "white",
customColorset: null,
texture: "",
material: "glass", // "none" | "metal" | "wood" | "glass"
faceColors: [],
showNumbers: true,
},
catalog: null, // inject custom textures/colorsets/themes (see Theming)
gravity_multiplier: 400,
light_intensity: 0.7,
baseScale: 100,
strength: 1,
iterationLimit: 1000,
onRollComplete: () => {},
onRerollComplete: () => {},
onAddDiceComplete: () => {},
onRemoveDiceComplete: () => {},
drawOver: undefined, // overlay the dice over another element (see below)
}theme accepts a partial - unspecified keys keep their defaults - in both the
constructor and updateConfig({ theme: { … } }).
Drawing over another element
By default the dice render inside the container you pass to the constructor. Set
drawOver to instead overlay them on top of an existing element — e.g. an RPG
character sheet — without that element losing interactivity:
const box = new DiceBox("#scene-container", {
assetPath: "/dice-box/",
drawOver: {
target: "#character-sheet", // selector of the element to draw over
clickPassThrough: true, // pointer-events:none so the sheet stays clickable
},
});
box.initialize();The container is pulled out of normal flow, stacked on top, and kept glued to the target's position and size as the page scrolls or resizes. The dice roll within the target's bounding box.
drawOveris applied atinitialize()time; changing it later viaupdateConfigdoes not re-run the overlay setup.- The renderer is transparent, so the target shows through behind the dice and their shadows.
🛣️ Roadmap
Next steps:
- isolate the "extra" as interfaces so there's only a simple DiceBox class to import
- other things shall be used as injected dependencies (textures, colors, sounds, particles)
- more particles (smoke, sparks, etc.)
- more materials (stone, marble, etc.)
- 'glow on' effect for specific dice results (e.g. crits)
📝 Changelog
0.3.1
Improved fire effect.
0.3.0
Adding particles for some dice themes:
- fire
- poison
[generation in wrong place - to be fixed soon]
more particles soon: acid, smoke, sparks, etc.
0.2.0
Breaking. Generic, copyright-clean release.
- Breaking: config
theme_*keys merged into a nestedthemeobject. - Inject custom textures/color sets/surface themes via the new
catalogoption. - Texture format validation +
SUPPORTED_TEXTURE_EXTENSIONS; newTEXTURELIST/THEMESexports. - Removed branded content - color sets 51 → 31 - and dead code.
0.1.11
- Makefile target to push git tags. No library changes.
0.1.9
- Reviewed and updated docs
- Allowing the
DiceBoxto be drawn over an existing HTML tag (which allows the dev to show a RPG sheet and draw the dice on top of it, for example)
0.1.8
- Internals modularized - SceneManager, PhysicsWorld, SoundController, GeometryBuilder
- Per-face ("side") colors
- Show/hide numbers
- Updated dependencies and docs
0.1.4–0.1.7
- Automated publish pipeline (CI/CD) + hotfixes
- React demo app and README updates
0.1.3
- TypeScript migration · Bun workspaces monorepo · renamed from fork
0.1.2
- Initial release
License
MIT
Thanks
- Fork of dice-box-threejs, based on Major's 3D Dice. Predetermined rolling from Teall Dice.
- Fire effect
