FreeDice integration guide
This guide describes the implemented public API for human developers and AI coding assistants. freedice@1.0.0 is published on npm. The version-pinned jsDelivr ESM entry and lazy chunks completed a Chrome physical-roll integration check. Source declarations in src/index.ts, src/core/runtimeTypes.ts, src/core/configuration.ts and src/multiplayer/protocol.ts are authoritative.
Fairness and release limitations
Production physical fairness certification FAILED. The 100,000-roll study found statistically significant individual-face and combined-total distribution bias. The owner accepted release with this known failed criterion and deferred physical correction/recertification. FreeDice is not certified fair or suitable for fairness-critical applications. The experimental A+B prototype separately showed short-gesture remembered-face dependence; that is not a production finding. Separate 100,000-pair fallback SHA-counter and native crypto cohorts passed their tested statistical gates, but sampled fallback evidence cannot certify physical simulation. See docs/fairness-M07-v2-report.md and docs/M07-closure-review.md.
M07 limited-verification exceptions remain untested: actual WebGL context loss/restoration; browser resource retention/memory leaks; controlled cold-start and actual GPU-presented first frame; remaining browser coverage including Edge and Android; and missing exact device/OS details. Publish these limits with any release.
Installation and local use
Install consumers with npm install freedice@1.0.0. Import FreeDice from freedice. Browser ESM without a bundler can import https://cdn.jsdelivr.net/npm/freedice@1.0.0/dist/freedice.js; the pinned entry and its lazy chunks were verified in Chrome. Offline hosts must serve the complete package's JS chunks and WASM-bearing assets from one origin. For source development run npm ci, npm run verify, npm run build, npm run build:site and npm run dev. Source: https://github.com/Hk41878/freedice; website documentation: https://freedice.aclub.it/docs/; issues: https://github.com/Hk41878/freedice/issues.
The published v1.0.0 npm tarball is immutable and includes the original prerelease-status wording in its README and GUIDE. This repository and the website correct that wording; the runtime files are unchanged. Future package releases must include the corrected documentation.
Simple standalone integration
import { FreeDice } from 'freedice';
const dice = new FreeDice({ maxWidth: 600, sound: true });
const off = dice.on('result', result => console.log(result.id, result.values, result.total));
await dice.open(); // initializes once; no networking/server required
// Later, while idle or displaying a result:
dice.close();
off();
dice.destroy();
Import/construction performs no DOM, storage, audio or WebGL initialization. Each instance owns scoped Shadow DOM/styles, renderer/camera, dice resources, input, feedback, result presentation and (when locally simulating) a separate Rapier world. Shared infrastructure is the immutable Rapier module initialization and reference-counted host-page scroll lock. Styles embed with the runtime; demo background and debugging/experimental controls are outside the library. Use a same-document container; iframe/cross-document mounting needs separate verification.
Methods and getters
new FreeDice(options?: FreeDiceOptions)
initialize(): Promise<void>
open(): Promise<boolean>
close(): boolean
reset(): boolean
updateConfig(options: FreeDiceUpdate): boolean
setAuthority(authority: Authority | null, mode?: Mode): Promise<boolean>
receive(packet: unknown): ReceiveStatus
getPlaybackSnapshot(): RollPacket | undefined
activateAudio(): Promise<boolean>
on<K extends keyof FreeDiceEvents>(event: K, listener: (value: FreeDiceEvents[K]) => void): () => void
off<K extends keyof FreeDiceEvents>(event: K, listener: (value: FreeDiceEvents[K]) => void): void
destroy(): void
readonly state: FreeDiceState
readonly config: Readonly<FreeDiceSettings>
readonly lastResult: RollResult | undefined
readonly authority: Readonly<Authority> | undefined
initialize/open coalesce concurrent calls. Initialization emits ready with the overlay still closed; open enters ready and emits open. Repeated open returns false. Invalid options throw TypeError; initialization failures emit error and reject the promise, and can be retried. reset/close/config updates reject unsafe lifecycle operations with false. Destroy is valid from every state and idempotent, aborts partial initialization, disposes late worlds, removes DOM/listeners/observers, stops rendering/feedback and clears replication buffers. Mutating methods and new subscriptions after destroy throw (async methods reject); off/unsubscribe and repeated destroy remain safe.
Active gestures, cancellation return, rolling/recovery, camera settling and result block config updates; reset is ready/error only. close is ready/error/result only. Continue calls close. Mode changes use setAuthority, not updateConfig; they deliberately cancel the old timeline without a result. setAuthority returns false during initial initialization: await initialize/open or set authority before initialization. Overlapping later handoffs use generation guards and dispose late worlds. A no-op authority returns false; the same authority can explicitly retry a failed handoff from error. New controller identity, role changes with an existing authority, or regranting a cleared authority in the same session require an increased epoch; lower epochs are rejected. setAuthority(null, 'standalone') restores offline local control; controller without an authority cannot launch.
All events are synchronous after state commitment. A throwing subscriber is reported to error subscribers without stopping other subscribers or corrupting physical state; error-subscriber exceptions are contained. A result is immutable and delivered once after valid physical settlement and camera completion. Destroy within event delivery prevents stale continuation. Getter lastResult is a local successful-result/display cache, not a multiplayer security claim.
Complete supported configuration
All settings are optional. Top-level updates merge; nested physics updates merge with current values. Owned configuration objects are frozen. Resource updates prepare a replacement world before commitment and preserve previous configuration on validation/allocation failure. Two identical D6s are v1.0's supported set; unsupported counts/types, experimental profiles, fallback flags and unknown options are rejected, not ignored. Future counts/types require a reviewed geometry/result generalization.
| Option | Default | Supported values / units |
| container | document.body | HTMLElement, construction only; owns a fixed overlay, not an inline layout API |
| diceCount / diceType | 2 / D6 | Literal 2 and D6 only |
| diceSizeMm | 16 | 12–20 mm; shared visual/collider dimensions, proportional pips and 2.5/16 corner-radius ratio |
| diceColor / pipColor | #ffffff / #000000 | Six-digit hexadecimal CSS colours |
| maxWidth | 600 | Positive finite CSS px, up to 10000 |
| maxHeight | 0 | 0 = available viewport; otherwise 240–10000 CSS px; safe areas retained |
| glassOpacity / edgeOpacity | .06 / .30 | 0–.25 / 0–1 |
| blur | adaptive | adaptive, subtle, reduced or off; per-device cadence degradation when adaptive |
| maxPixelRatio | 2 | 1–2, also capped by device DPR |
| rollingAngle / resultAngle | 45 / 90 | Supported literal elevations only; camera physically moves, no dice scaling for zoom |
| transitionMs | 700 | 0–2000 ms |
| showIndividualResults | true | Boolean; preserves accepted existing presentation |
| animateResult / resultCountMs | true / 450 | Boolean / 0–2000 ms; reduced-motion preference respected |
| showContinue / continueLabel | true / Continue | Boolean / nonempty string up to 200 characters; host must provide closing UI if hidden |
| sound / volume | true / .45 | Boolean / 0–1; browser user activation still required |
| vibration | false | Opt-in Boolean; standard API only, gracefully unavailable on iOS Safari |
| physics | values below | Partial typed PhysicsSettings |
| persistence | false | false or explicitly scoped key/optional adapter, described below |
| mode | standalone | standalone, controller, spectator; change through setAuthority |
| bufferMs | 100 | 50–500 ms, spectator interpolation delay |
| Physics setting | Default | Range |
| gravity | 9.81 | Magnitude 1–20 m/s², downwards |
| massGrams | 5 | 1–20 g per die, identical for both |
| friction | .5 | 0–1 |
| restitution | .3 | 0–.8 |
| linearDamping / angularDamping | .1 / .15 | 0–2 |
Cross-field safety: conservative launch-energy bound (0.003 / massKg)^2 / (2 * gravity) <= 0.35 m; restitution above .6 requires friction at least .02; zero friction requires nonzero linear AND angular damping. Individually in-range settings can therefore still be rejected. Existing fixed timestep, CCD, supported impulse caps and runtime area/launch validators remain enforced. These are implementation safety checks, not evidence that every non-default combination is realistic or statistically fair. Custom physics/size combinations need separate realism, containment and fairness validation. Production defaults are unchanged. Natural physics duration remains production behavior; optional public target-duration profiles are deferred pending independent fairness/realism verification and Helper approval. Named 3s/refined5s profiles remain demo-only experiments; no 8s profile, forced roll duration or public calibration-profile option.
Spectators follow controller geometry, visual settings, transforms, camera and result presentation. updateConfig rejects local authoritative visual/physics overrides in spectator mode; audio/vibration/volume, DPR, container width/height, buffering and persistence scope remain local settings subject to lifecycle guards. No unsupported fallback or future adaptive-quality implementation is advertised.
Persistence
const dice = new FreeDice({
persistence: { key: 'my-app:account-42:game-17:dice-panel' },
});
dice.on('persistenceError', error => console.warn('Display cache unavailable:', error));
await dice.open();
persistence: false | {key: string, storage?: StorageAdapter} is opt-in. Key must be nonempty, trimmed, at most 160 characters. StorageAdapter has synchronous getItem(key): string|null and setItem(key,value): void; default provider lazily accesses host-origin localStorage. Actual key: freedice:v1:<developer-key>. Different keys isolate instances; the same key intentionally shares a stored record, not live cross-tab synchronization. The host owns account/game naming, retention and removal. Do not put secrets in keys. Disabled storage still retains successful local faces in instance memory across close/open.
Version-1 records contain id, two integer D6 values and matching total. Invalid/version-mismatched/oversized data is ignored without deletion; denied/quota failures emit nonfatal persistenceError, never block rolling. Only a matching, completed local result after the camera transition writes. Failed/cancelled/incomplete rolls and settle alone do not write. Spectator results never write or replace local lastResult; spectator records are not loaded into playback. Returning to local authority can restore that instance's own local cache.
Fresh instances reload valid records and display their corresponding upper faces while idle, without emitting a new result/settle or replaying result presentation. Before a new grab/debug launch, stored face rotation is replaced with the independent idle orientation before drag/launch pose generation. The shown face may change when grabbed: this deliberately keeps storage out of future physical initial conditions. Cancellation returns to saved display faces. Persistent data never supplies seeds, impulses or an outcome. Browser private mode, user clearing and denied storage can prevent durability; actual restart tests remain manual.
Changing key/adapter or disabling persistence safely clears the old scoped lastResult/display cache and loads the new scope when locally controlling. Unrelated updates preserve it. No copying records into a new namespace. The development demo has enable/key/apply controls, starting with development-demo:default. Browser refresh/restart must use the same origin and scope.
Transport-independent multiplayer integration
const controller = new FreeDice({ mode: 'controller' });
const spectator = new FreeDice({ mode: 'spectator', bufferMs: 100 });
const authority = { sessionId: 'game-17', controllerId: 'player-2', epoch: 4 };
// Host validates player identity, turn and epoch BEFORE making these calls.
await Promise.all([controller.setAuthority(authority), spectator.setAuthority(authority)]);
controller.on('replication', packet => {
myAuthorizedTransport.send(JSON.stringify(packet)); // supplied by your application
});
myAuthorizedTransport.onMessage(payload => spectator.receive(payload));
controller.on('result', result => handleLocalAuthoritativeResult(result));
spectator.on('spectatorResult', event => showObservedResult(event.authority, event.result));
await Promise.all([controller.open(), spectator.open()]);
// On joining or reconnecting, route a fresh snapshot to the new spectator:
const snapshot = controller.getPlaybackSnapshot();
if (snapshot) myAuthorizedTransport.sendToNewSpectator(JSON.stringify(snapshot));
myAuthorizedTransport and the result handlers are application-provided pseudocode, not bundled services. Create one controller and the spectator count chosen by your integrating application. The library has no hardcoded four-player limit or spectator-count option/cap: your transport fans out the same packet to the recipients you choose. The four-player harness is only a demonstration. diceCount=2 describes dice per roll, not players. Tests cover 0, 1, 3, 8 and 16 protocol spectators, plus a real-runtime five-spectator slingshot trace with renderer/DOM doubles; this is not an unlimited performance guarantee or a sixteen-WebGL-device benchmark. No sockets, backend, authentication, turn manager or mandatory network service is bundled. Standalone never needs an authority or connection. Spectators do not create a Rapier world, accept local gestures or independently infer a result. A former spectator can become the controller after an explicit host-authorized epoch change; old-world initialization races and stale queued results are invalidated.
Protocol version 1 includes sessionId/controllerId/epoch, sequence, monotonic controller time in milliseconds, interaction ordinal/ID and actual physical roll ID. Before launch, an interaction has no physical roll ID; cancellation terminates it without a result. Frames cover idle, drag, charge, return, roll/recovery, settling/camera, result, error and close. Each validated frame includes both metre-based poses/unit quaternions, camera pose/FOV/aspect/clip planes, stage offset, four-point convex table, safe visual settings, result/count elapsed time and at most eight impact records. Ordinary frames repeat scene metadata for self-contained validation; keyframes additionally permit initial-join or diagnosed-interruption resynchronization. A periodic keyframe is not a seek command for an existing healthy spectator. Protocol limits include canonical aspect .1–10, camera FOV 10–170°, camera/stage coordinates within ±100 m, table/dice XZ within ±10 m and dice height 0–.6 m; source layouts must fit this supported envelope. Private storage keys/adapters, host assets and physics commands are not transmitted.
Source sends up to 30 Hz, plus forced lifecycle changes and explicit keyframes. getPlaybackSnapshot returns a fresh keyframe AND emits it through replication to avoid sequence gaps for existing recipients; duplicated delivery to the new recipient is safe. Route periodic fresh keyframes (the harness uses 1 Hz) for reconnect/drop recovery. Keep routes and timers bounded and remove them on destroy. receive accepts JSON strings or JSON-compatible objects; returns accepted, buffered, duplicate, stale, malformed, wrong-mode, need-keyframe, invalid-transition or overflow. It validates shape/finite ranges/UTF-8 size, convex geometry, quaternions, final face/total consistency, authority and lifecycle before committing playback. Out-of-order valid content, including keyframes, is staged until its predecessor allows transition validation. A contiguous refresh drains rather than discards already-buffered successors. Before the initial baseline, receive still returns need-keyframe while retaining a bounded startup reorder window; the baseline then validates/drains those successors. Healthy refreshes preserve queued animation and the established clock, including terminal frames. Packets cannot grant authority. Use unique session IDs for distinct games and never use a session switch to reset/reuse old epochs; bounded state tracks the current/last session, not an unlimited archive of every previous game.
Limits: 32 KiB per JSON packet, 120 queued frames, 32 reordered packets, 500 ms gap wait and 2 seconds without accepted packet progress. Duplicate/stale sequences/roll ordinals/epochs are rejected without result delivery. Overflow/gap/timeout clears pending playback and requires a newer explicit keyframe. High-water identity and delivered ordinal survive an interruption; authority change clears the old timeline and pending result. Late terminal keyframe produces at most one spectatorResult for that authority/ordinal, not a locally generated result. Missing entire outcomes are not fabricated from a later closed state.
Spectators linearly interpolate positions, shortest-path-slerp rotations and interpolate FOV/count timing. They hold a last frame through short gaps, never extrapolate physics or call a held pose settled. Controller aspect is letterboxed into each spectator viewport, preserving the same physical table/camera on different screens. Camera and dice are copied, not independently zoomed or repositioned to choose outcomes. Feedback replays bounded new impact records once; explicit refresh keyframes omit historical impacts. activateAudio should be called from a trusted local user gesture on each device; blocked audio/unsupported vibration never blocks playback.
result and settle/rollStart are local-authoritative gameplay events only. spectatorResult: {authority, result, ordinal} is a separate observation. Local overlay open/close events also reflect mirrored opening/closing. Errors initializing local resources use error; network interruption uses playbackError. A result getter/cache is not a source of secure game authority.
Accuracy: playback latency is one-way transport delay + configured buffer + rendering scheduling. Up-to-30Hz source samples, differing device FPS, jitter/loss and unsynchronized clocks prevent guaranteed wall-clock simultaneity or exact between-sample trajectories. This implementation aligns relative controller timelines on keyframes, without a cross-device clock-sync service; a host needing tighter global timing must provide that coordination in a later reviewed extension. Node tests and in-page transport are not real Wi-Fi/mobile accuracy measurements.
Trust: integrators must authenticate packets and authorize players, turns, authority epochs and the control channel; provide transport encryption/rate limiting as needed. Validation and physical-face consistency do not prevent a malicious controller from fabricating an entire valid-looking trajectory/result. Client-generated results and localStorage are not tamper-proof or server-authoritative. Fairness and anti-cheat require separate trusted application design.
Event reference
| Event | Payload / scope |
| ready / open / close / destroy | undefined; instance lifecycle |
| dragStart / dragCancel / rollStart | undefined; local interaction only |
| settle / result | immutable {id, values: readonly [number,number], total}; local authority only |
| error | Error; local resource/roll/subscriber failures |
| persistenceError | Error; nonfatal local cache diagnostic |
| replication | immutable serializable RollPacket; controller only |
| spectatorResult | {authority, result, ordinal}; once per observed completed roll |
| playbackError | {reason: timeout, gap or overflow}; needs fresh keyframe |
States: closed, initializing, ready, dragging, rolling, recovery, settling, result, error, destroyed. Charging and smooth cancellation return map to dragging for spectators; local input has these substates internally. Settling includes physical validity through the 700 ms default camera transition. Result blocks new local rolls. on returns idempotent unsubscribe; off accepts the same listener reference.
Local commands and verification scope
npm run verify
npm run build:demo
npm run measure:multiplayer
npm run dev:lan
On this Mac: http://localhost:3010/demo/ and http://localhost:3010/demo/multiplayer/. Other LAN devices use the Mac's current LAN IP, port3010; no public tunnel. The four-cell harness is an in-page diagnostic with demo-only contained viewport styling. It supplies bounded in-memory latency/jitter/loss/duplication, interruption, fresh-keyframe, late-join and controller-handoff controls. It is not four-device network verification and does not limit the library's player count. Open all / recover explicitly resets rejected-launch error states before reopening, without generating a roll. Short viewport framing reserves the existing physical release clearance and full 8mm backward pull; 45° camera angle, projected table/82% anchor and physics limits stay unchanged.
Measured terminal JSON payloads and methodology are in multiplayer-bandwidth-M04.json and TESTING.md. Published npm metadata/tarball integrity, independent npm installation and a Chrome browser CDN physical roll were verified for v1.0.0. Existing weak shadows, the large-chunk warning, iOS vibration limitation, supported-device physical vibration, Node 24 execution, broader browser coverage, controlled cold-start/GPU presentation and memory verification remain accepted limits or future checks. Production physical fairness certification failed; experimental/custom-physics fairness is not established. See TESTING.md and docs/M08-v1.0.0-release-review.md for evidence. README, MIT license and third-party notices are included in the published package, with the README/GUIDE wording caveat above.
M05-B02 runtime diagnostics and fallback
Optional runtimeMode event emits {mode:'physical'|'fallback', reason?:string} at initialization; subscribe before open/initialize. Initial WebGL/physics capability failure automatically unwinds resources and opens a labelled2D fallback. Sampled results retain the same result fields and exactly-once lifecycle; IDs start fallback-. The approved prefix identifies presentation provenance, not secure authority. Spectators never sample; spectatorResult remains distinct. No packet fields changed. Local2D viewers label physical versus sampled controller rolls;3D viewers show a fallback badge. Secure randomness unavailable→error/no result; reset can retry, destroy/recreate can retry physical capabilities. All local JS chunks must be shipped for offline use. See performance-M05-B02.md for limitations, adaptive DPR/blur behavior, measurement commands and pending manual checks.