API Docs for: 0.7.0

Scene

Extends Component
Defined in: src/scene.js:1
Module: xeogl

A Scene represents a 3D world.

Usage

Creating a Scene

Creating a Scene with its own default canvas:

var scene = new Scene();

Creating a Scene with an existing canvas.

var scene2 = new Scene({
   canvas: "myCanvas"
});

var scene3 = new Scene({
   canvas: document.getElementById("myCanvas");
});

Creating entities

Creating an Entity within a Scene:

var entity = new xeogl.Entity(scene, {
   geometry: new xeogl.TeapotGeometry(scene),
   material: new xeogl.PhongMaterial(scene, {
       diffuse: [0.2, 0.2, 1.0]
   })
});

Creating an entity within the default Scene (which will be automatically created if not yet existing):

entity = new xeogl.Entity({
   geometry: new xeogl.TeapotGeometry(),
   material: new xeogl.PhongMaterial({
       diffuse: [0.2, 0.2, 1.0]
   })
});

entity.scene.camera.eye = [45, 45, 45];

The default Scene can be got from either the Entity or the xeogl namespace:

scene = entity.scene;
scene = xeogl.scene;

Loading models

Use GLTFModel components to load glTF models into a Scene:

var model = new xeogl.GLTFModel(scene, { // If we don't provide the Scene, will create in default Scene
   id: "gearbox",
   src: "models/gltf/gearbox/gearbox_assy.gltf"
});

Accessing content

Find components by ID in their Scene's components map:

var gear1 = scene.components["gearbox#gear99"];
gear1.visible = false;
//...

A Scene also has a map of component instances for each Component subtype:

var entities = scene.types["xeogl.Entity"];
var gear = entities["gearbox#gear99"];
gear.ghost = true;
//...

var glTFModels = scene.types["xeogl.GLTFModel"];
var gearbox = glTFModels["gearbox"];
gearbox.visible = false;
//...

a map containing just the Model instances:

gearbox = scene.models["gearbox"];

and a map containing just the Entity instances:

gear = scene.entities["gearbox#gear99"];

Controlling the camera

Use the Scene's Camera to control the current viewpoint and projection:

var camera = myScene.camera;

camera.eye = [-10,0,0];
camera.look = [-10,0,0];
camera.up = [0,1,0];

camera.projection = "perspective";
camera.perspective.fov = 45;
//...

Managing the canvas, taking snapshots

The Scene's Canvas component provides various conveniences relevant to the WebGL canvas, such as getting getting snapshots, firing resize events etc:

var canvas = scene.canvas;

canvas.on("boundary", function(boundary) {
   //...
});

var imageData = canvas.getSnapshot({
   width: 500,
   height: 500,
   format: "png"
});

Lighting

The Scene's Lights component manages lighting:

var lights = scene.lights;
lights[1].color = [0.9, 0.9, 0.9];
//...

Clipping

The Scene's Clips component manages clipping planes for custom cross-sections:

var clips = scene.clips;
clips.clips = [
new xeogl.Clip({  // Clip plane on negative diagonal
       pos: [1.0, 1.0, 1.0],
       dir: [-1.0, -1.0, -1.0],
       active: true
   }),
new xeogl.Clip({ // Clip plane on positive diagonal
       pos: [-1.0, -1.0, -1.0],
       dir: [1.0, 1.0, 1.0],
       active: true
   }),
//...
];

Emphasis effects

The Scene's ghostMaterial provides the default GhostMaterial for controlling ghost effects:

var ghostMaterial = scene.ghostMaterial;
ghostMaterial.edgeColor = [0.9, 0.9, 0.0];
//...

The Scene's highlightMaterial provides the default GhostMaterial for controlling highlight effects:

var highlightMaterial = scene.highlightMaterial;
highlightMaterial.color = [0.9, 0.9, 0.0];
//...

The Scene's outlineMaterial provides the default OutlineMaterial for controlling outline effects:

var outlineMaterial = scene.outlineMaterial;
outlineMaterial.edgeWidth = 6;

Picking entities

Use the Scene's pick() method to pick and raycast entities.

For example, to pick a point on the surface of the closest entity at the given canvas coordinates:

var hit = scene.pick({
    pickSurface: true,
    canvasPos: [23, 131]
});

if (hit) { // Picked an Entity

     var entity = hit.entity;

     var primitive = hit.primitive; // Type of primitive that was picked, usually "triangles"
     var primIndex = hit.primIndex; // Position of triangle's first index in the picked Entity's Geometry's indices array
     var indices = hit.indices; // UInt32Array containing the triangle's vertex indices
     var localPos = hit.localPos; // Float32Array containing the picked Local-space position on the triangle
     var worldPos = hit.worldPos; // Float32Array containing the picked World-space position on the triangle
     var viewPos = hit.viewPos; // Float32Array containing the picked View-space position on the triangle
     var bary = hit.bary; // Float32Array containing the picked barycentric position within the triangle
     var normal = hit.normal; // Float32Array containing the interpolated normal vector at the picked position on the triangle
     var uv = hit.uv; // Float32Array containing the interpolated UV coordinates at the picked position on the triangle
}

Pick masking

We can use the pick() method's include and exclude options to mask which Entities we attempt to pick.

This is useful for picking through things, to pick only the Entities of interest.

Including entities

To pick only Entities "gearbox#77.0" and "gearbox#79.0", picking through any other Entities that are in the way, as if they weren't there:

var hit = scene.pick({
    canvasPos: [23, 131],
    include: ["gearbox#77.0", "gearbox#79.0"]
});

if (hit) {
     // Entity will always be either "gearbox#77.0" or "gearbox#79.0"
     var entity = hit.entity;
}

Excluding entities

To pick any pickable Entity, except for "gearbox#77.0" and "gearbox#79.0", picking through those Entities if they happen to be in the way:

var hit = scene.pick({
    canvasPos: [23, 131],
    exclude: ["gearbox#77.0", "gearbox#79.0"]
});

if (hit) {
     // Entity will never be "gearbox#77.0" or "gearbox#79.0"
     var entity = hit.entity;
}

See pick() for more info on picking.

Getting the World-space boundary

Getting a Scene's World-space boundary as an AABB:

var aabb = scene.aabb; // [xmin, ymin, zmin, xmax, ymax, zmax]

Subscribing to updates to the World-space boundary, which occur whenever Entities are Transformed, or their Geometries have been updated.

scene.on("boundary", function() {
    var aabb = scene.aabb;
    var obb = scene.obb;
});

Managing the viewport

The Scene's Viewport component manages the WebGL viewport:

var viewport = scene.viewport
viewport.boundary = [0, 0, 500, 400];;

Controlling rendering

You can configure a Scene to perform multiple "passes" (renders) per frame. This is useful when we want to render the scene to multiple viewports, such as for stereo effects.

In the example, below, we'll configure the Scene to render twice on each frame, each time to different viewport. We'll do this with a callback that intercepts the Scene before each render and sets its Viewport to a different portion of the canvas. By default, the Scene will clear the canvas only before the first render, allowing the two views to be shown on the canvas at the same time.

// Load glTF model
var model = new xeogl.GLTFModel({
   src: "models/gltf/GearboxAssy/glTF/GearboxAssy.gltf"
});

var scene = model.scene;
var viewport = scene.viewport;

// Configure Scene to render twice for each frame
scene.passes = 2; // Default is 1
scene.clearEachPass = false; // Default is false

// Render to a separate viewport on each render

var viewport = scene.viewport;
viewport.autoBoundary = false;

scene.on("rendering", function (e) {
    switch (e.pass) {
        case 0:
            viewport.boundary = [0, 0, 200, 200]; // xmin, ymin, width, height
            break;

        case 1:
            viewport.boundary = [200, 0, 200, 200];
            break;
    }
});

// We can also intercept the Scene after each render,
// (though we're not using this for anything here)
scene.on("rendered", function (e) {
    switch (e.pass) {
        case 0:
            break;

        case 1:
            break;
    }
});

Gamma correction

Within its shaders, xeogl performs shading calculations in linear space.

By default, the Scene expects color textures (ie. diffuseMap, baseColorMap and diffuseMap) to be in pre-multipled gamma space, so will convert those to linear space before they are used in shaders. Other textures are always expected to be in linear space.

By default, the Scene will also gamma-correct its rendered output.

You can configure the Scene to expect all those color textures to be linear space, so that it does not gamma-correct them:

scene.gammaInput = false;

You would still need to gamma-correct the output, though, if it's going straight to the canvas, so normally we would leave that enabled:

scene.gammaOutput = true;

See Texture for more information on texture encoding and gamma.

Constructor

Scene

(
  • [cfg]
)

Defined in src/scene.js:1

Parameters:

  • [cfg] Object optional

    Scene parameters

    • [id] String optional

      Optional ID, unique among all Scenes in xeogl, generated automatically when omitted.

    • [meta] String:Object optional

      Optional map of user-defined metadata to attach to this Scene.

    • [canvasId] String optional

      ID of existing HTML5 canvas in the DOM - creates a full-page canvas automatically if this is omitted

    • [webgl2=true] Boolean optional

      Set this false when we don't want to use WebGL 2 for our Scene; the Scene will fall back on WebGL 1 if not available. This property will be deprecated when WebGL 2 is supported everywhere.

    • [components] Array(Object) optional

      JSON array containing parameters for Component subtypes to immediately create within the Scene.

    • [ticksPerRender=1] Number optional

      The number of Scene/tick:event that happen between each render or this Scene.

    • [passes=1] Number optional

      The number of times this Scene renders per frame.

    • [clearEachPass=false] Boolean optional

      When doing multiple passes per frame, specifies whether to clear the canvas before each pass (true) or just before the first pass (false).

    • [transparent=false] Boolean optional

      Whether or not the canvas is transparent.

    • [backgroundColor] Float32Array optional

      RGBA color for canvas background, when canvas is not transparent. Overridden by backgroundImage.

    • [backgroundImage] String optional

      URL of an image to show as the canvas background, when canvas is not transparent. Overrides backgroundImage.

    • [gammaInput=false] Boolean optional

      When true, expects that all textures and colors are premultiplied gamma.

    • [gammaOutput=true] Boolean optional

      Whether or not to render with pre-multiplied gama.

    • [gammaFactor=2.2] Number optional

      The gamma factor to use when rendering with pre-multiplied gamma.

Methods

clear

()

Defined in src/scene.js:1773

Resets this Scene to its default state.

References to any components in this Scene will become invalid.

create

(
  • [cfg]
)

Convenience method for creating a Component within this Component's Scene.

The method is given a component configuration, like so:

var material = myComponent.create({
     type: "xeogl.PhongMaterial",
     diffuse: [1,0,0],
     specular: [1,1,0]
}, "myMaterial");

Parameters:

  • [cfg] optional

    Configuration for the component instance.

Returns:

:

destroy

()

Destroys this component.

Fires a destroyed event on this Component.

Automatically disassociates this component from other components, causing them to fall back on any defaults that this component overrode on them.

TODO: describe effect with respect to #create

error

(
  • message
)

Logs an error for this component to the JavaScript console.

The console message will have this format: [ERROR] [<component type> =<component id>: <message>

Also fires the message as an error event on the parent Scene.

Parameters:

  • message String

    The message to log

fire

(
  • event
  • value
  • [forget=false]
)

Fires an event on this component.

Notifies existing subscribers to the event, optionally retains the event to give to any subsequent notifications on the event as they are made.

Parameters:

  • event String

    The event type name

  • value Object

    The event parameters

  • [forget=false] Boolean optional

    When true, does not retain for subsequent subscribers

hasSubs

(
  • event
)
Boolean

Returns true if there are any subscribers to the given event on this component.

Parameters:

  • event String

    The event

Returns:

Boolean:

True if there are any subscribers to the given event on this component.

isType

(
  • type
)
Boolean

Tests if this component is of the given type, or is a subclass of the given type.

The type may be given as either a string or a component constructor.

This method works by walking up the inheritance type chain, which this component provides in property superTypes, returning true as soon as one of the type strings in the chain matches the given type, of false if none match.

Examples:

var myRotate = new xeogl.Rotate({ ... });

myRotate.isType(xeogl.Component); // Returns true for all xeogl components
myRotate.isType("xeogl.Component"); // Returns true for all xeogl components
myRotate.isType(xeogl.Rotate); // Returns true
myRotate.isType(xeogl.Transform); // Returns true
myRotate.isType("xeogl.Transform"); // Returns true
myRotate.isType(xeogl.Entity); // Returns false, because xeogl.Rotate does not (even indirectly) extend xeogl.Entity

Parameters:

  • type String | Function

    Component type to compare with, eg "xeogl.PhongMaterial", or a xeogl component constructor.

Returns:

Boolean:

True if this component is of given type or is subclass of the given type.

log

(
  • message
)

Logs a console debugging message for this component.

The console message will have this format: [LOG] [<component type> <component id>: <message>

Also fires the message as a log event on the parent Scene.

Parameters:

  • message String

    The message to log

off

(
  • handle
)

Cancels an event subscription that was previously made with on or once.

Parameters:

  • handle String

    Publication handle

on

(
  • event
  • callback
  • [scope=this]
)
String

Subscribes to an event on this component.

The callback is be called with this component as scope.

Parameters:

  • event String

    The event

  • callback Function

    Called fired on the event

  • [scope=this] Object optional

    Scope for the callback

Returns:

String:

Handle to the subscription, which may be used to unsubscribe with {@link #off}.

once

(
  • event
  • callback
  • [scope=this]
)

Subscribes to the next occurrence of the given event, then un-subscribes as soon as the event is handled.

This is equivalent to calling on, and then calling off inside the callback function.

Parameters:

  • event String

    Data event to listen to

  • callback Function(data)

    Called when fresh data is available at the event

  • [scope=this] Object optional

    Scope for the callback

pick

(
  • params
)

Defined in src/scene.js:1387

Attempts to pick an Entity in this Scene.

Ignores Entities with pickable set false.

Picking the Entity at the given canvas coordinates:

var hit = scene.pick({
    canvasPos: [23, 131]
 });

if (hit) { // Picked an Entity
    var entity = hit.entity;
}

Usage:

Picking the Entity that intersects a ray cast through the canvas:

var hit = scene.pick({
    pickSurface: true,
    canvasPos: [23, 131]
 });

if (hit) { // Picked an Entity

    var entity = hit.entity;

    // These properties are only on the hit result when we do a ray-pick:

    var primitive = hit.primitive; // Type of primitive that was picked, usually "triangles"
    var primIndex = hit.primIndex; // Position of triangle's first index in the picked Entity's Geometry's indices array
    var indices = hit.indices; // UInt32Array containing the triangle's vertex indices
    var localPos = hit.localPos; // Float32Array containing the picked Local-space position on the triangle
    var worldPos = hit.worldPos; // Float32Array containing the picked World-space position on the triangle
    var viewPos = hit.viewPos; // Float32Array containing the picked View-space position on the triangle
    var bary = hit.bary; // Float32Array containing the picked barycentric position within the triangle
    var normal = hit.normal; // Float32Array containing the interpolated normal vector at the picked position on the triangle
    var uv = hit.uv; // Float32Array containing the interpolated UV coordinates at the picked position on the triangle
}

Picking the Entity that intersects an arbitrarily-aligned World-space ray:

var hit = scene.pick({
    pickSurface: true,       // Picking with arbitrarily-positioned ray
    origin: [0,0,-5],    // Ray origin
    direction: [0,0,1]   // Ray direction
});

if (hit) { // Picked an Entity with the ray

    var entity = hit.entity;

    var primitive = hit.primitive; // Type of primitive that was picked, usually "triangles"
    var primIndex = hit.primIndex; // Position of triangle's first index in the picked Entity's Geometry's indices array
    var indices = hit.indices; // UInt32Array containing the triangle's vertex indices
    var localPos = hit.localPos; // Float32Array containing the picked Local-space position on the triangle
    var worldPos = hit.worldPos; // Float32Array containing the picked World-space position on the triangle
    var viewPos = hit.viewPos; // Float32Array containing the picked View-space position on the triangle
    var bary = hit.bary; // Float32Array containing the picked barycentric position within the triangle
    var normal = hit.normal; // Float32Array containing the interpolated normal vector at the picked position on the triangle
    var uv = hit.uv; // Float32Array containing the interpolated UV coordinates at the picked position on the triangle
    var origin = hit.origin; // Float32Array containing the World-space ray origin
    var direction = hit.direction; // Float32Array containing the World-space ray direction
}

Parameters:

  • params

    Picking parameters.

    • [pickSurface=false] Boolean optional

      Whether to find the picked position on the surface of the Entity.

    • [canvasPos] Float32Array optional

      Canvas-space coordinates. When ray-picking, this will override the origin and direction parameters and will cause the ray to be fired through the canvas at this position, directly along the negative View-space Z-axis.

    • [origin] Float32Array optional

      World-space ray origin when ray-picking. Ignored when canvasPos given.

    • [direction] Float32Array optional

      World-space ray direction when ray-picking. Also indicates the length of the ray. Ignored when canvasPos given.

    • [include] Array optional

      IDs of Entities to pick from amongst. When given, ignores Entities whose IDs are not in this list.

    • [exclude] Array optional

      IDs of Entities to ignore. When given, will pick through these Entities, as if they were not there.

Returns:

:

Hit record, returned when an Entity is picked, else null. See method comments for description.

render

(
  • [forceRender=false]
)

Defined in src/scene.js:800

Renders a single frame of this Scene.

The Scene will periodically render itself after any updates, but you can call this method to force a render if required. This method is typically used when we want to synchronously take a snapshot of the canvas and need everything rendered right at that moment.

Parameters:

  • [forceRender=false] Boolean optional

    Forces a render when true, otherwise only renders if something has changed in this Scene since the last render.

warn

(
  • message
)

Logs a warning for this component to the JavaScript console.

The console message will have this format: [WARN] [<component type> =<component id>: <message>

Also fires the message as a warn event on the parent Scene.

Parameters:

  • message String

    The message to log

Properties

aabb

Float32Array final

Defined in src/scene.js:1296

World-space axis-aligned 3D boundary (AABB) of this Scene.

The AABB is represented by a six-element Float32Array containing the min/max extents of the axis-aligned volume, ie. [xmin, ymin,zmin,xmax,ymax, zmax].

camera

Camera final

Defined in src/scene.js:1270

The Camera belonging to this Scene.

canvas

Canvas final

Defined in src/scene.js:506

Manages the HTML5 canvas for this Scene.

clearEachPass

Boolean

Defined in src/scene.js:988

When doing multiple passes per frame, specifies whether to clear the canvas before each pass (true) or just before the first pass (false).

Default: false

clips

Clips final

Defined in src/scene.js:1283

The Clips belonging to this Scene.

components

String:xeogl.Component

Defined in src/scene.js:461

The Components within this Scene, mapped to their IDs.

Will also contain the Entitys contained in Entity/components:property.

destroyed

Boolean

True as soon as this Component has been destroyed

entities

String:xeogl.Model

Defined in src/scene.js:494

The Models within this Scene, mapped to their IDs.

entities

String:xeogl.Entity

Defined in src/scene.js:482

The Entitys within this Scene, mapped to their IDs.

The Entitys in this map will also be contained in Entity/components:property.

gammaInput

Boolean

Defined in src/scene.js:1016

When true, expects all textures and colors are premultiplied gamma.

Default: false

gammaOutput

Boolean

Defined in src/scene.js:1047

Whether or not to render pixels with pre-multiplied gama.

Default: true

gammaOutput

Number

Defined in src/scene.js:1078

The gamma factor to use when Scene/property:gammaOutput is set true.

Default: 1.0

geometry

BoxGeometry final

Defined in src/scene.js:1128

The default geometry for this Scene, which is a BoxGeometry.

This BoxGeometry has an id equal to "default.geometry".

Entities within this Scene are attached to this Geometry by default.

ghostMaterial

GhostMaterial final

Defined in src/scene.js:1173

The default GhostMaterial for this Scene.

This GhostMaterial has an id equal to "default.ghostMaterial", with all other properties initialised to their default values.

Entities within this Scene are attached to this GhostMaterial by default.

highlightMaterial

HighlightMaterial final

Defined in src/scene.js:1197

The default HighlightMaterial for this Scene.

This HighlightMaterial has an id equal to "default.highlightMaterial", with all other properties initialised to their default values.

Entities within this Scene are attached to this HighlightMaterial by default.

id

String final

Unique ID for this Component within its parent Scene.

input

Input final

Defined in src/scene.js:536

Publishes input events that occur on this Scene's canvas.

isDefault

Boolean

Indicates whether this is one of the Scene's built-in Components.

lights

Lights final

Defined in src/scene.js:1257

The Lights belonging to this Scene.

loading

Number

Defined in src/scene.js:445

The number of models currently loading.

material

PhongMaterial final

Defined in src/scene.js:1149

The default drawing material for this Scene, which is a PhongMaterial.

This PhongMaterial has an id equal to "default.material", with all other properties initialised to their default values.

Entities within this Scene are attached to this PhongMaterial by default.

metadata

Object

Arbitrary, user-defined metadata on this component.

outlineMaterial

OutlineMaterial final

Defined in src/scene.js:1221

The default OutlineMaterial for this Scene.

This OutlineMaterial has an id equal to "default.outlineMaterial", with all other properties initialised to their default values.

Entities within this Scene are attached to this OutlineMaterial by default.

passes

Number

Defined in src/scene.js:952

The number of times this Scene renders per frame.

Default: 1

scene

Scene final

The parent Scene that contains this Component.

superTypes

Array of String final

An array of strings that indicates the chain of super-types within this component's inheritance hierarchy.

For example, if this component is a Rotate, which extends Transform, which in turn extends Component, then this property will have the value:

["xeogl.Component", "xeogl.Transform"]
                    

Note that the chain is ordered downwards in the hierarchy, ie. from super-class down towards sub-class.

ticksPerRender

Number

Defined in src/scene.js:918

The number of Scene/tick:property that happen between each render or this Scene.

Default: 1

timeCreated

Number

Defined in src/scene.js:453

The epoch time (in milliseconds since 1970) when this Scene was instantiated.

transform

Transform final

Defined in src/scene.js:1105

The default modelling Transform for this Scene.

This Transform has an id equal to "default.transform", with all other properties initialised to their default values (ie. an identity matrix).

Entities within this Scene are attached to this Transform by default.

type

String final

JavaScript class name for this Component.

For example: "xeogl.AmbientLight", "xeogl.ColorTarget", "xeogl.Lights" etc.

types

String:{String:xeogl.Component}

Defined in src/scene.js:473

For each Component type, a map of IDs to instances.

viewport

Viewport final

Defined in src/scene.js:1244

The Viewport belonging to this Scene.

Events

destroyed

Fired when this Component is destroyed.

error

Defined in src/scene.js:424

Fired whenever an error is logged on a component within this Scene.

Event Payload:

  • value String

    The error message

log

Defined in src/scene.js:418

Fired whenever a debug message logged on a component within this Scene.

Event Payload:

  • value String

    The debug message

rendering

Defined in src/scene.js:851

Fired when about to render a frame for a Scene.

Event Payload:

  • sceneID String

    The ID of this Scene.

  • pass Number

    Index of the pass we are about to render (see passes).

rendering

Defined in src/scene.js:864

Fired when we have just rendered a frame for a Scene.

Event Payload:

  • sceneID String

    The ID of this Scene.

  • pass Number

    Index of the pass we rendered (see passes).

warn

Defined in src/scene.js:430

Fired whenever a warning is logged on a component within this Scene.

Event Payload:

  • value String

    The warning message