Reference Source
public class | source

STLLoaderPlugin

Extends:

Plugin → STLLoaderPlugin

Viewer plugin that loads models from STL files.

Overview

  • Creates an Entity representing each model it loads, which will have Entity#isModel set true and will be registered by Entity#id in Scene#models.
  • Creates an Entity for each object within the model, which will have Entity#isObject set true and will be registered by Entity#id in Scene#objects.
  • When loading, can set the World-space position, scale and rotation of each model within World space, along with initial properties for all the model's Entitys.
  • Supports both binary and ASCII formats.
  • Supports double-precision vertex positions.
  • Supports custom data source configuration.

Smoothing STL Normals

STL models are normally flat-shaded, however providing a smoothNormals parameter when loading gives a smooth appearance. Triangles in STL are disjoint, where each triangle has its own separate vertex positions, normals and (optionally) colors. This means that you can have gaps between triangles in an STL model. Normals for each triangle are perpendicular to the triangle's surface, which gives the model a faceted appearance by default.

The smoothNormals parameter causes the plugin to recalculate the STL normals, so that each normal's direction is the average of the orientations of the triangles adjacent to its vertex. When smoothing, each vertex normal is set to the average of the orientations of all other triangles that have a vertex at the same position, excluding those triangles whose direction deviates from the direction of the vertice's triangle by a threshold given in the smoothNormalsAngleThreshold loading parameter. This makes smoothing robust for hard edges.

Creating Entities for Objects

An STL model is normally a single mesh, however providing a splitMeshes parameter when loading will create a separate object Entity for each group of faces that share the same vertex colors. This option only works with binary STL files.

See the STLLoaderPlugin#load method for more info on loading options.

Usage

In the example below, we'll use an STLLoaderPlugin to load an STL model of a spur gear. When the model has loaded, we'll use the CameraFlightAnimation to fly the Camera to look at boundary of the model. We'll then get the model's Entity from the Scene and highlight the whole model.

// Create a xeokit Viewer
const viewer = new Viewer({
     canvasId: "myCanvas"
});

// Add an STLLoaderPlugin to the Viewer
var plugin = new STLLoaderPlugin(viewer);

// Load the STL model
var model = plugin.load({ // Model is an Entity
     id: "myModel",
     src: "./models/stl/binary/spurGear.stl",
     scale: [0.1, 0.1, 0.1],
     rotate: [90, 0, 0],
     translate: [100,0,0],
     edges: true,
     smoothNormals: true,                // Default
     smoothNormalsAngleThreshold: 20,    // Default
     splitMeshes: true                   // Default
});

// When the model has loaded, fit it to view
model.on("loaded", function() { // Model is an Entity
     viewer.cameraFlight.flyTo(model);
});

// Find the model Entity by ID
model = viewer.scene.models["myModel"];

// Update properties of the model Entity
model.highlight = [1,0,0];

// Destroy the model Entity
model.destroy();

Loading from a Pre-Loaded STL File

If we already have our STL file in memory (perhaps pre-loaded, or even generated in-client), then we can just pass that file data straight into the STLLoaderPlugin#load method. In the example below, to show how it's done, we'll pre-load our STL file data, then pass it straight into that method.

loadSTL("./models/stl/binary/spurGear.stl", (stlData) =>{

     const model = stlLoader.load({
         id: "myModel",
         stl: stlData,
         smoothNormals: true
     });

     model.on("loaded", () => {
         viewer.cameraFlight.jumpTo(model);
         viewer.scene.on("tick", () => {
             viewer.camera.orbitYaw(0.4);
         })
     });
 })

function loadSTL(src, ok, error) {
    const request = new XMLHttpRequest();
    request.overrideMimeType("application/json");
    request.open('GET', src, true);
    request.responseType = 'arraybuffer';
    request.onreadystatechange = function () {
        if (request.readyState === 4) {
            if (request.status === 200) {
                ok(request.response);
            } else if (error) {
                    error(request.statusText);
            }
        }
    };
    request.send(null);
}

Configuring a Custom Data Source

In the example below, we'll create the STLLoaderPlugin again, this time configuring it with a custom data source object, through which it can load STL files. For this example, our data source just loads them via HTTP, for simplicity. Once we've created the STLLoaderPlugin, we'll load our STL file as before.

// Our custom STL data access strategy - implementation happens to be the same as STLDefaultDataSource

class MyDataSource {
     getSTL(src, ok, error) {
         const request = new XMLHttpRequest();
         request.overrideMimeType("application/json");
         request.open('GET', src, true);
         request.responseType = 'arraybuffer';
         request.onreadystatechange = function () {
             if (request.readyState === 4) {
                 if (request.status === 200) {
                     ok(request.response);
                 } else {
                     error(request.statusText);
                 }
             }
         };
         request.send(null);
     }
 }

const stlLoader = new STLLoaderPlugin(viewer, {
     dataSource: new MyDataSource()
 });

// Load the STL model as before
var model = plugin.load({
     id: "myModel",
     src: "./models/stl/binary/spurGear.stl",
     scale: [0.1, 0.1, 0.1],
     rotate: [90, 0, 0],
     translate: [100,0,0],
     edges: true,
     smoothNormals: true,                // Default
     smoothNormalsAngleThreshold: 20,    // Default
     splitMeshes: true                   // Default
});

//...

Constructor Summary

Public Constructor
public

constructor(viewer: Viewer, cfg: Object)

Member Summary

Public Members
public set

Sets a custom data source through which the STLLoaderPlugin can load STL files.

public get

Gets the custom data source through which the STLLoaderPlugin can load STL files.

Method Summary

Public Methods
public

load(params: *): Entity

Loads an STL model from a file into this STLLoaderPlugin's Viewer.

Inherited Summary

From class Plugin
public

ID for this Plugin, unique within its Viewer.

public

The Viewer that contains this Plugin.

public

Destroys this Plugin and removes it from its Viewer.

public

error(msg: String)

Logs an error message to the JavaScript developer console, prefixed with the ID of this Plugin.

public

fire(event: String, value: Object, forget: Boolean)

Fires an event on this Plugin.

public

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

public

log(msg: String)

Logs a message to the JavaScript developer console, prefixed with the ID of this Plugin.

public

off(subId: String)

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

public

on(event: String, callback: Function, scope: Object): String

Subscribes to an event on this Plugin.

public

once(event: String, callback: Function, scope: Object)

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

public

scheduleTask(task: *)

Schedule a task to perform on the next browser interval

public

warn(msg: String)

Logs a warning message to the JavaScript developer console, prefixed with the ID of this Plugin.

Public Constructors

public constructor(viewer: Viewer, cfg: Object) source

Creates this Plugin and installs it into the given Viewer.

Override:

Plugin#constructor

Params:

NameTypeAttributeDescription
viewer Viewer

The Viewer.

cfg Object
  • optional

Plugin configuration.

cfg.id String
  • optional
  • default: "STLLoader"

Optional ID for this plugin, so that we can find it within Viewer#plugins.

cfg.dataSource Object
  • optional

A custom data source through which the STLLoaderPlugin can load STL files. Defaults to an instance of STLDefaultDataSource, which loads over HTTP.

Public Members

public set dataSource: Object source

Sets a custom data source through which the STLLoaderPlugin can load STL files.

Default value is STLDefaultDataSource, which loads via an XMLHttpRequest.

public get dataSource: Object source

Gets the custom data source through which the STLLoaderPlugin can load STL files.

Default value is STLDefaultDataSource, which loads via an XMLHttpRequest.

Public Methods

public load(params: *): Entity source

Loads an STL model from a file into this STLLoaderPlugin's Viewer.

Params:

NameTypeAttributeDescription
params *

Loading parameters.

params.id String

ID to assign to the model's root Entity, unique among all components in the Viewer's Scene.

params.src String
  • optional

Path to an STL file. Overrides the stl parameter.

params.stl String
  • optional

Contents of an STL file, either binary of ASCII. Overridden by the src parameter.

params.edges Boolean
  • optional
  • default: false

Whether or not to renders the model with edges emphasized.

params.origin Number[]
  • optional
  • default: [0,0,0]

The model's World-space double-precision 3D origin. Use this to position the model within xeokit's World coordinate system, using double-precision coordinates.

params.position Number[]
  • optional
  • default: [0,0,0]

The model single-precision 3D position, relative to the origin parameter.

params.scale Number[]
  • optional
  • default: [1,1,1]

The model's scale.

params.rotation Number[]
  • optional
  • default: [0,0,0]

The model's orientation, given as Euler angles in degrees, for each of the X, Y and Z axis.

params.matrix Number[]
  • optional
  • default: [1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]

The model's world transform matrix. Overrides the position, scale and rotation parameters. Relative to origin.

params.backfaces Boolean
  • optional
  • default: false

When true, allows visible backfaces, wherever specified in the STL. When false, ignores backfaces.

params.smoothNormals Boolean
  • optional
  • default: true

When true, automatically converts face-oriented normals to vertex normals for a smooth appearance.

params.smoothNormalsAngleThreshold Number
  • optional
  • default: 20

When xraying, highlighting, selecting or edging, this is the threshold angle between normals of adjacent triangles, below which their shared wireframe edge is not drawn.

params.edgeThreshold Number
  • optional
  • default: 20

When xraying, highlighting, selecting or edging, this is the threshold angle between normals of adjacent triangles, below which their shared wireframe edge is not drawn.

params.splitMeshes Boolean
  • optional
  • default: true

When true, creates a separate Mesh for each group of faces that share the same vertex colors. Only works with binary STL.

Return:

Entity

Entity representing the model, which will have Entity#isModel set true and will be registered by Entity#id in Scene#models