This catalog helps locate public APIs in webg 3.0 by feature. Check settings, defaults, and exception conditions against the current implementation, samples, and headless tests.
For a first application, begin with 05_AppStructure.md. For renaming and architectural changes from earlier versions, see Appendix B: Migration to webg 3.0.
webg 3.0 builds on the existing WebgApp and adds the application-oriented WebgSceneApp above it:
application code
├─ webg/app/index.js
│ └─ WebgSceneApp / SceneDefinition / ScenePhysics / PbrRenderer
└─ when direct control is needed
└─ WebgApp.js, Shape.js, ComputePhysicsSpace.js, and other core modules
webg/app/index.jscreateWebgSceneApp(), WebgSceneAppwebg/app/index.jsSceneDefinition, parseSceneYAML()webg/app/index.jsScenePhysicswebg/app/index.jsPbrRendererwebg/WebgApp.jsWebgAppwebg/ComputePhysicsSpace.js, webg/ComputeEffectPipeline.jsMost applications import from the aggregate entry point:
import {
WebgSceneApp,
createWebgSceneApp,
SceneDefinition,
parseSceneYAML,
ScenePhysics,
PbrRenderer,
WaterBody
} from "../../webg/app/index.js";
WebgSceneApp
createWebgSceneApp()
WebgSceneApp.create()SceneDefinition
parseSceneYAML()
parseSceneYAMLDocument()
stringifySceneYAML()
DocumentAsset
SceneAsset
ModelAsset
compressSceneYAML(text)
Promise<Blob>ScenePhysics
PbrRenderer
WaterBody
PBR_RENDERER_PROFILES
studioresolvePbrRendererProfile()
resolvePbrDofOptions()
validatePbrEnvironmentOptions()
validatePbrPipelineOptions()
validatePbrRendererOptions()
SceneFrame, backend, binding, and helper modules are internal to WebgSceneApp. For internal processing, see Chapter 9 and current webg/app/*.js.
const sceneApp = await createWebgSceneApp({
project: "./scene.webg.yaml",
camera: { target: [0.0, 1.0, 0.0], distance: 10.5 },
physics: { enabled: true, paused: true }
});
sceneApp.start();
new WebgSceneApp(options)
WebgSceneAppWebgSceneApp.create(options)
Promise<WebgSceneApp>createWebgSceneApp(options)
Promise<WebgSceneApp>WebgSceneApp.create()After create() completes, renderer and Compute-physics resources are available.
project
SceneAsset, SceneDefinition, or manifest objectdocument
DocumentrenderMode
"ondemand" or "continuous""ondemand"; use continuous mode to keep requesting frames when the page is inactive; browser scheduling still appliescamera
physics
false, true, or objecteffects
shadow, ssao, ssr, and dofpaused
physics.pausedtimeScale
0 < value <= 4label
scene-appcreateScene
onUpdate
onReadback
onPresented
onError
Physics option fields:
enabled
spatialMatch
report or require-matchpaused
Camera fields include target, distance, yaw, pitch, roll, minDistance, maxDistance, focusTarget, and focusTargetOffset. When DoF is active, focusTarget accepts a Node ID or Node.
sceneApp.start()
sceneAppsceneApp.stop()
sceneApp.setPaused(value)
sceneAppsceneApp.reset()
sceneApp.setTimeScale(value) / getTimeScale()
0 < value <= 4sceneApp.getAnimationIds() / getAnimationState(id)
sceneApp.playAnimation(id, options)
{ loop: true } repeatssceneApp.pauseAnimation(id) / resumeAnimation(id)
sceneApp.stopAnimation(id)
sceneApp.seekAnimation(id, seconds)
sceneApp.resetAnimations()
sceneApp.onBeginContact(listener)
sceneApp.getDiagnostics()
sceneApp.destroy()
The onReadback payload contains frameIndex, stateData, contacts, fixedSteps, and physics. contacts groups events into begin, stay, and end.
PBR-scene emissive particles use ComputeParticleEmitter. GPU computation handles initial values, movement, gravity, drag, and lifetime, and composites particles additively into the HDR image after transparency. Use rgba16float when registering with PBR. Set a display-format targetFormat when drawing directly to Canvas.
await sceneApp.createComputeParticleEmitter(options, id)
sceneApp.getComputeParticleEmitter(id)
emitter.emit(count, options)
emitter.startEmission({ rate, ...options })
emitter.stopEmission()
emitter.setPaused(boolean)
emitter.clear()
emitter.getEstimatedAliveCount()
emitter.getDiagnostics()
emitter.setTimeScale(value)
emitter.destroy()
Generation options include preset: "spark" | "light" | "fountain", capacity (default 1024), seed (default 1), overflow: "reject" | "replace-oldest" (default reject), simulation: { gravity, drag }, and appearance: { colors, intensity, size }. colors contains two linear HDR RGB values; size is a radius range [min, max].
Emission settings combine position, lifetime: [min, max], and either velocity with velocitySpread, or direction, spreadAngle, and speed: [min, max]. Units are seconds, world units per second, and degrees. Burst count is an integer from 1 through capacity; up to 32 requests can be pending. reject reserves a contiguous free ring region per request. Capacity failure reasons include particle-capacity and command-capacity.
WebgSceneApp uses the same data structure for SceneYAML and JSON project definitions. SceneDefinition.load() chooses YAML for .yaml and .yml, and JSON for .json. materialsUrl and physicsUrl follow the same extension rule. Original text and comments are preserved in source documents.
.yaml.gz, .yml.gz, and .json.gz are decompressed and passed to the same readers. compressSceneYAML(text), available from webg/app/index.js, is a serialization API that gzip-compresses UTF-8 source including comments.
SceneDefinition.fromData(manifest, options)
SceneDefinitionSceneDefinition.load(url, options)
Promise<SceneDefinition>SceneDefinition.fromYAML(text, options)
SceneDefinitiondefinition.getSourceDocument()
definition.getSourceDocuments()
definition.validate()
truedefinition.loadMaterials()
Promise<Array>definition.loadPhysics()
Promise<object>definition.getRendererOptions()
definition.getPhysicsOptions()
definition.getBindings()
definition.resolveUrl(value, fieldName)
definition.build(target)
Promise<object>scene or sceneUrldefinition.buildPrimitiveScene(target)
Promise<object>objects and objectSetsdefinition.buildModelRuntime(target)
Promise<object>definition.createLoader(target)
SceneLoaderdefinition.destroy()
name
version
1renderer
physics
physicsUrl
materials
materialsUrl
objects
meshes
format
webg-scene for projects with inline meshes or animationanimations
objectSets
scene / sceneUrl
modelAsset / modelAssetUrl
bindings
Choose a scene source from scene/sceneUrl, modelAsset/modelAssetUrl, objects/objectSets, or createScene. When a ModelAsset is the source, objects connects its Nodes to project IDs and physics settings. A primitive scene combines materials or materialsUrl with inline physics.space.
particleEmitters is an array of standard Compute-particle settings with unique IDs. Provide optional emission with rate and emission conditions for continuous emission. See Chapters 9 and 26 for examples.
id: ball
shape: {type: sphere, radius: 0.5}
transform: {position: [0.0, 3.2, 0.0]}
material: ball-material
physics:
bodyType: dynamic
mass: 1.0
material: {restitution: 0.18, friction: 0.36}
id
shape.type
box, sphere, or capsuleshape.size
shape.radius
shape.segmentLength
shape.offset
transform.position
[0, 0, 0]transform.orientation
{yaw, pitch, roll} or three degree values in [X, Y, Z] order; defaults to no rotationmaterial
materials[].idphysics
static, kinematic, or dynamic body settingsIf physics.shape is omitted, the display shape is shared as the body shape. For a proxy collider, specify physics.shape and colliderRelation: "proxy" explicitly.
objectSets[] combines a prototype or variants with a placement:
| Field | Description |
|---|---|
prototype |
Shared shape, transform, material, and physics |
variants |
Multiple shape definitions keyed by id |
variantPattern |
Choose variants per instance using cycle or range |
placement.type |
Currently grid3d |
placement.count |
Counts along X, Y, and Z |
placement.origin |
Placement origin |
placement.spacing |
Spacing between instances |
placement.seed |
Reproducible seed for jitter |
placement.jitter |
Per-axis placement variation |
instancePattern |
cycle or range for transform and physics |
overrides |
Overrides for the set or individual instances |
new PbrRenderer(gpu, options)
PbrRendererrenderer.waitUntilReady()
Promise<PbrRenderer>renderer.renderScene(space, cameraFrame, clearColor, options)
PbrRendererrenderer.encode(commandEncoder, options)
renderer.present(screen, options)
PbrRendererrenderer.createFrameCallbacks(app, options)
renderer.resize(width, height)
renderer.getDiagnostics()
renderer.setWater(body, options)
Promise<void>null releases dedicated GPU resourcesrenderer.getWaterStats()
renderer.afterGpuSubmit()
renderer.destroy()
For setWater(), surfaceEnabled and causticsEnabled default to false; quality is "low" or "high", defaulting to "high". Pause new frames while switching and resume after completion. ComputeEffectPipeline.setWater() has the same contract. With both features off, dedicated processing counts are zero and timing is null. ComputeEffectPipeline.getWaterStats() has the same contract.
For direct construction, pass an initialized WebGPU context with device and queue, and positive integer width and height. Ordinary applications let WebgSceneApp perform this setup.
The PbrRenderer used by WebgSceneApp runs PbrEnvironmentCompute on environment radiance to generate irradiance, specular mips, and a BRDF LUT on the GPU. A lower-level CPU-precomputed route combines PbrEnvironment with createProceduralEnvironmentData().
profile: studio
width: 960
height: 640
environment:
preset: dark-studio
resolution: {width: 128, height: 64}
dof: {enabled: false}
pipeline:
lighting: {ambient: 0.0, environmentIntensity: 0.42}
ssao: {radius: 12.0, strength: 1.15, samples: 8}
ssr: {intensity: 0.65, distance: 24.0, steps: 28}
toneMap: {exposure: 1.0}
profile
studioenvironment
preset, resolutionpipeline.shadow
type, bias, normalBias, pcfRadiuspipeline.ssao
radius, strength, bias, samples, resolutionScalepipeline.ssr
intensity, distance, thickness, steps, resolutionScale, reflectivityThresholdpipeline.lighting
unitSystem, ambient, directional/spot, environmentrelative or photometricpipeline.composer
modeadd, mix, or pbr-ssrpipeline.toneMap
mode, exposure, exposureEv100, saturation, gammadof
enabled, focus, blurRadiusrangeMeters and transitionMetersWhen environment lighting is enabled, set pipeline.lighting.ambient to 0.0. Photometric units require toneMap.exposureEv100. Choose either exposure or exposureEv100.
Primitive materials[] can specify color, metallic, roughness, specular, occlusion, emissive, emissiveFactor, and alphaMode. External materials for authoring scenes combine assetMaterialId with pbr or preset.
| Material value | Meaning |
|---|---|
color |
RGBA base color in the 0–1 range |
metallic |
Metal contribution, 0–1 |
roughness |
PBR specular roughness, 0.04–1 |
specular |
Dielectric specular amount |
occlusion |
Environment occlusion |
emissive, emissiveFactor |
Linear HDR emission separate from lighting |
alphaMode |
OPAQUE, MASK, or BLEND |
flatShading, doubleSided |
Normal and back-face rendering settings |
External-material preset can combine tile, appearance, scale, and uvMapping. uvMapping selects real-cuboid, real-sphere, or real-capsule.
Import from webg/WaterBody.js or webg/app/index.js. Connect water separately from the manifest using setWater(). See Chapter 35, samples/water/index.html, and samples/fantasy/main.js.
new WaterBody(options) stores the water region, waves, absorption, and receivers without creating GPU resources. Coordinates and distances use meters, time uses seconds, and absorption coefficients use inverse meters.
origin
[0, 0, 0]width, depth
extent
surfaceHeight
amplitude
wavelength, speed
waveMix
[1, 0, 0]variation
ior
absorption
[0.09, 0.035, 0.025]roughness
waterlineFade
extent must cover width and depth; average water depth surfaceHeight - origin[1] must exceed amplitude. See Chapter 35 and current source for valid ranges.
water.setOptions(patch)
setWater().water.setTime(seconds)
water.addReceiver(target, options)
strength is 0–1, default 1; children defaults true. Shape registration takes precedence; a Node uses its nearest registered ancestor. Receivers are opaque surfaces.water.removeReceiver(target)
water.clearReceivers()
WaterBody; renderer owns GPU connection and release.Caustics approximate projection of a horizontal irradiance image under vertical incoming light. Surface display is for a finite horizontal region viewed from above; underwater-camera rendering is outside this path.
const physics = new ScenePhysics({
gpu: app.getGPU(),
gravity: [0.0, -9.8, 0.0],
fixedTimeStepMs: 8.3333333333,
maxSubSteps: 8,
solverIterations: 10,
planes: [{ normal: [0.0, 1.0, 0.0], planeDistance: 0.0 }]
});
The default backend is compute; specify backend: "cpu" for comparison and verification.
new ScenePhysics(options)
physics.addBody(node, options) / addRawBody(body)
physics.addPlane(node, options)
physics.addJoint(joint) / removeJoint(joint)
physics.step(deltaMs, options)
physics.createStateReadbackBuffer()
physics.encodeStateReadback(...)
physics.readStateReadback(...)
physics.sync()
physics.syncReadback(stateData)
physics.syncFromNodes()
physics.syncComputeFromNode(bodyId, node, options)
physics.reset() / resetBody(bodyId, options)
physics.getBindings() / getBodies()
physics.getLastContacts() and related methods
physics.raycast() / raycastAll()
physics.queryAabb()
physics.overlapSphere()
physics.onBeginContact() and related methods
physics.destroy()
Compute step() accepts options.commandEncoder and records GPU commands. CPU step() takes milliseconds and simulates on the CPU. WebgSceneApp abstracts the backend difference for application use.
Use ComputePhysicsSpace for advanced code that accesses GPU state directly.
new ComputePhysicsSpace(gpu, options)
setBodies(bodies)
addBody(body) / removeBody(bodyId)
addJoint(joint) / removeJoint(jointId)
encode(commandEncoder, elapsedMs)
step(commandEncoder, elapsedMs)
encode()encodeFixedStep(commandEncoder)
getRenderState()
getCurrentStateBuffer() / getStateBuffers()
createStateReadbackBuffer()
encodeStateReadback()
readBodyStateFromReadback()
syncNodeFromPhysics() / syncNodesFromPhysics()
syncPhysicsFromNode()
applyForce() / applyImpulse()
applyTorque() / applyAngularImpulse()
teleport() / setBodyOrientation()
wakeBody() / sleepBody() / stopBodyMotion()
setBodyType() / setBodyMass()
getContactsFromReadback() and related methods
raycastFromReadback() and related methods
getBodyInfo() / getJointInfo()
destroy()
Compute colliders are ComputeBoxCollider, ComputeSphereCollider, and ComputeCapsuleCollider. Set planes in ComputePhysicsSpace.planes with normal and planeDistance. The standard broad phase uses an XZ grid.
For direct access to existing CPU physics, import webg/PhysicsSpace.js.
new PhysicsSpace(options)
addBody(body) / removeBody(body)
PhysicsNodeaddJoint(joint) / removeJoint(joint)
step(deltaMs)
raycast() / raycastAll()
queryAabb() / overlapSphere()
onBeginContact() and related methods
getLastContacts() and related methods
setGravity(), setFixedTimeStepMs()
WebgApp is the application foundation for GPU, Canvas, Screen, Space, camera, input, Message, and the update loop.
new WebgApp(options)
app.init()
app.start(handlers) / app.stop()
app.getGPU()
app.createCameraRig()
app.createOrbitEyeRig(options)
app.attachInput(handlers)
app.loadScene(scene)
app.loadModel(source, options)
app.showOverlayPanel(options)
app.setHudRows(rows, options)
app.setControlRows(rows, options)
app.createTween(target, to, options)
app.createParticleEmitter(options)
app.registerActionMap(map) / getAction(name)
app.setFog(options)
app.getCurrentDiagnosticsReport()
app.setDebugMode(mode)
debug/release modeapp.saveProgress() / loadProgress()
For compute-first frames, combine new WebgApp({ computeFrame: true }) with start({ onComputeFrame }). onComputeFrame records one frame containing Compute passes, Render passes, and queue submission. WebgSceneApp manages its own PBR and physics processing order.
Space
addNode(), findNode(), draw(), update(), raycast(), checkCollisions()Node
setParent(), setPosition(), setAttitude(), setScale(), addShape(), getWorldMatrix()Shape
setMaterial(), setMaterialAt(), setTexture(), applyPrimitiveAsset(), endShape(), draw(), destroy()Primitive
sphere(), capsule(), cuboid(), cone(), revolution(), mapRealCuboid()Screen
clear(), beginPass(), present(), resize(), beginPresentPass()To create a Shape, generate geometry with Primitive, pass it to Shape.applyPrimitiveAsset(), then finalize GPU resources with Shape.endShape(). Use setMaterial() for one material or setMaterialAt() and triangle material indices for multiple materials.
EyeRig
WebgApp.createOrbitEyeRig()
CameraFrame
createCameraFrameFromEye()
createRenderFrameToken()
CAMERA_REVERSE_Z
SHADOW_STANDARD_Z
The ordinary camera uses Reverse-Z; shadow maps use Standard-Z. Match depth format, clear value, compare function, and projection matrix to each convention.
PbrEnvironment
getResources(), destroy()ComputeEffectPipeline
renderScene(), encode(), resize(), getBindingResources(), destroy()ComputePass
setUniforms(), encode(), destroy()DeferredLightingPass
encode(), resize(), destroy()FullscreenPass
draw(), destroy()ModelAsset
load(), fromData(), validate(), build(), getClip()SceneAsset
load(), fromData(), assertValid(), toSceneDefinition(), build()DocumentAsset
fromYAML(), fromJSON(), getSourceDocument(), toYAMLText()MaterialParameters
resolveShapeMaterial(), validateTransparency(), applyTransmissionParameters()ComputePass.encode(commandEncoder, resources, options) records GPU commands. The caller submits them. Manage resources in this order:
ComputePass.encode() into the same encoder.queue.submit().destroy() when the page ends.Use rgba16float for HDR intermediates and a display format for the final Canvas target. Apply tone mapping once for final display.
SceneAsset, SceneDefinition, WebgSceneAppModelAssetPrimitive, Shape, SceneDefinitionSceneDefinition.applyMaterials()ProceduralMaterials, ProceduralTileSpec, Primitive.mapRealCuboid()Both inherit from DocumentAsset. They load a shared YAML/JSON data structure, then validate their respective asset contents.
SceneAsset.load(url) / ModelAsset.load(url)
.yaml, .yml, .json, and gzip variantsfromYAML(text, options) / fromJSON(text, options)
getData() / setData(data)
getSourceDocument() / getSourceUrl()
toYAMLText()
toJSONText(indent, options)
downloadYAML(filename) / downloadYAMLGz(filename)
assertValid()
To save an edited document with comments, pass updated YAML source to fromYAML(). toYAMLText() throws when parsed values change without a corresponding source update. To convert comment-bearing YAML to JSON, make the choice explicit with toJSONText(2, { allowCommentLoss: true }).
Joint
DistanceJoint
FixedJoint
BallSocketJoint
HingeJoint
JointDefinition
Distance Joint settings include bodyA, bodyB, localAnchorA, localAnchorB, distance, compliance, and collideConnected. Identify bodies by scene binding ID or Compute body ID; keep GPU slot indices internal.
BoxCollider
ComputeBoxColliderSphereCollider
ComputeSphereColliderCapsuleCollider
ComputeCapsuleColliderPlaneCollider
ComputePlaneColliderCPU colliders provide getAabb(), intersectRay(), overlapsAabb(), and overlapSphere(); infinite planes return no finite AABB. The Compute GPU solver supports Box, Sphere, Capsule, and Plane; a Capsule’s center line is local Y.
onBeginContact(listener)
onStayContact(listener)
onEndContact(listener)
offBeginContact(listener) and related methods
getContactsFromReadback()
getManifoldsFromReadback()
getContactEventsFromReadback()
raycastFromReadback() and related methods
WebgSceneApp.create(), createWebgSceneApp(), SceneDefinition.load(), PbrRenderer.waitUntilReady(), and asset load() methods return Promises. Start later drawing, physics, and material assignment after each Promise resolves.
Compute physics, ComputePass, and PbrRenderer.encode() record work into a command encoder. Choose one owner for encoder creation and queue submission per frame. Keep Compute, readback, draw, and presentation ordered for that frame. In WebgSceneApp, SceneFrame owns this order.
Public APIs validate unknown keys, array lengths, numeric ranges, unsupported enums, and GPU-resource state at call time. Errors identify their input path, such as renderer.pipeline.ssao.samples or physics.bodies[2].shape, so the setting can be corrected directly.
The class that creates a GPU resource owns its resize() and destroy(). On shutdown, release frame, renderer, physics, scene, Shape, and additional-pass resources according to their ownership. If ownership is shared, specify the boundary in options.
WebgSceneApp example in samples/project_app/.headless_tests/ for boundaries and exception conditions.unittest/ or a browser to inspect GPU output and interaction.webg/*.js.05_AppStructure.md, 12_UI.md09_Scenes.md, 08_Models.md27_Physics.md, 28_PhysicsEvents.md29_ProceduralTextures.md30_PBR.md, 31_PBRDesign.md37_LowLevelAPI.md42_PhysicsInternals.md, 27_Physics.mdThis catalog identifies current 3.0 entry points and major low-level APIs. For exact profile values, schemas, and implementation limits, consult current source in webg/app/ and webg/, sample SceneYAML/JSON, and the corresponding tests.