Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Javascript for loading the output of the SpaceClaim Three.js plugin into Three.js
// Some of this code is from http://www.radiatedpixel.com/wordpress/2013/03/27/webgl-3d-model-viewer-using-three-js/
// Other parts are from http://math.hws.edu/eck/cs424/notes2013/threejs/json-loader-demo.html
/* Uses JSONLoader to load objects that have been saved
* in three.js's json format. Requires the folder models-json
* that contains the seven sample models.
*/
var renderer; // A three.js WebGL or Canvas renderer.
var scene; // The 3D scene that will be rendered, containing the model.
var camera; // The camera that takes the picture of the scene.
var model; // The three.js object that represents the model.
var rotateX = 0; // rotation of model about the x-axis
var rotateY = 0; // rotation of model about the y-axis
var container;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
function addObjects(object, index, parts) {
var part = parts[index];
var material = new THREE.MeshBasicMaterial( { vertexColors : THREE.FaceColors });
material.polygonOffset = true;
material.polygonOffsetFactor = 5;
material.polygonOffsetUnits = 0.1;
for (var i = 0; i < part.meshes.length; i++) {
var mesh = new THREE.Mesh(part.meshes[i], material);
object.add(mesh);
}
material = new THREE.LineBasicMaterial( { color: 0x0 } );
for (var i = 0; i < part.lines.length; i++) {
var line = new THREE.Line(part.lines[i], material);
object.add(line);
}
for (var i = 0; i < part.components.length; i++) {
var child = new THREE.Object3D();
child.applyMatrix(part.components[i].transformation);
child.name = part.components[i].name;
addObjects(child, part.components[i].id, parts);
object.add(child);
}
}
function getExtents(object, extents) {
for (var i = 0; i < object.children.length; i++) {
if(object.children[i].geometry == undefined || object.children[i].geometry.vertices.length == 0) {
getExtents(object.children[i], extents);
continue;
}
var vertices = object.children[i].geometry.vertices;
for(var k = 0; k < vertices.length; k++) {
var v = vertices[k].clone();
v.applyMatrix4(object.matrixWorld);
if (v.x < extents.xmin)
extents.xmin = v.x;
else if (v.x > extents.xmax)
extents.xmax = v.x;
if (v.y < extents.ymin)
extents.ymin = v.y;
else if (v.y > extents.ymax)
extents.ymax = v.y;
if (v.z < extents.zmin)
extents.zmin = v.z;
else if (v.z > extents.zmax)
extents.zmax = v.z;
}
}
}
function partCallback(parts) {
model = new THREE.Object3D();
addObjects(model, 0, parts);
model.updateMatrixWorld(true);
var extents = new Object();
extents.xmin = Infinity,
extents.xmax = -Infinity,
extents.ymin = Infinity,
extents.ymax = -Infinity,
extents.zmin = Infinity,
extents.zmax = -Infinity
getExtents(model, extents);
// translate the center of the object to the origin
var centerX = (extents.xmin+extents.xmax)/2;
var centerY = (extents.ymin+extents.ymax)/2;
var centerZ = (extents.zmin+extents.zmax)/2;
var max = Math.max(centerX - extents.xmin, extents.xmax - centerX);
max = Math.max(max, Math.max(centerY - extents.ymin, extents.ymax - centerY) );
max = Math.max(max, Math.max(centerZ - extents.zmin, extents.zmax - centerZ) );
var scale = 10 / max;
model.scale.set(scale, scale, scale);
rotateX = rotateY = 0.0;
scene.add(model);
render();
}
/**
* Called when the setting of the model-selection radio buttons is changed.
* starts loading the model from the specified file and sets the background
* color for the renderer (since black background doesn't work for all
* of the models.
*/
function installModel(file, bgColor) {
if (model) {
scene.remove(model);
}
renderer.setClearColor(bgColor);
render();
loadparts(file, partCallback);
}
/**
* The render function creates an image of the scene from the point of view
* of the camera and displays it in the canvas. This is called at the end of
* init() to produce the initial view of the model, and it is called each time
* the user presses an arrow key, return, or home.
*/
function render() {
renderer.render(scene, camera);
}
/*** The Loop ***/
function animate() {
// This function calls itself on every frame. You can for example change
// the objects rotation on every call to create a turntable animation.
requestAnimationFrame( animate );
// On every frame we need to calculate the new camera position
// and have it look exactly at the center of our scene.
controls.update();
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
function loadpart(json, url) {
var lines = [];
var meshes = [];
var components = [];
if (json.lines != undefined) {
for ( i = 0; i < json.lines.length; i++ ) {
var loader = new THREE.JSONLoader();
var result = loader.parse(json.lines[i], url);
lines.push(result.geometry);
}
}
if (json.meshes != undefined) {
for ( i = 0; i < json.meshes.length; i++ ) {
var loader = new THREE.JSONLoader();
var result = loader.parse(json.meshes[i], url);
meshes.push(result.geometry);
}
}
if (json.components != undefined) {
for ( i = 0; i < json.components.length; i++) {
component = json.components[i];
t = component.transformation;
component.transformation = new THREE.Matrix4(t[0], t[1], t[2], t[3],
t[4], t[5], t[6], t[7],
t[8], t[9], t[10], t[11],
t[12], t[13], t[14], t[15]);
components.push(component);
}
}
return {
lines: lines,
meshes: meshes,
components: components
}
}
function loadparts(url, callback) {
var xhr = new XMLHttpRequest();
var length = 0;
xhr.onreadystatechange = function () {
if ( xhr.readyState === xhr.DONE ) {
if ( xhr.status === 200 || xhr.status === 0 ) {
if ( xhr.responseText ) {
document.getElementById("loadingmessage").style.visibility = "hidden";
var json = JSON.parse( xhr.responseText );
var parts = [];
for ( partindex = 0; partindex < json.length; partindex++ ) {
parts.push(loadpart(json[partindex], url));
}
callback(parts);
} else {
console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
}
} else {
console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
}
}
};
xhr.open( "GET", url, true );
xhr.withCredentials = this.withCredentials;
xhr.send( null );
};
function init(file) {
try {
var theCanvas = document.getElementById("cnvs");
if (!theCanvas || !theCanvas.getContext) {
console.error("Sorry, your browser doesn't support canvas graphics.");
return;
}
try { // try to create a WebGLRenderer
if (window.WebGLRenderingContext) {
renderer = new THREE.WebGLRenderer( {
canvas: theCanvas,
antialias: true
} );
}
}
catch (e) {
}
if (!renderer) { // If the WebGLRenderer couldn't be created, try a CanvasRenderer.
renderer = new THREE.CanvasRenderer( { canvas: theCanvas } );
renderer.setSize(theCanvas.width,theCanvas.height);
console.error("WebGL not available; falling back to CanvasRenderer.");
}
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(45, theCanvas.width/theCanvas.height, 1, 1000);
camera.position.z = 30;
// These variables set the camera behaviour and sensitivity.
controls = new THREE.TrackballControls( camera, theCanvas );
controls.rotateSpeed = 5.0;
controls.zoomSpeed = 5;
controls.panSpeed = 2;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
var ambient = new THREE.AmbientLight();
scene.add( ambient );
installModel(file, 0x34495e);
render();
}
catch (e) {
console.error("Sorry, an error occurred: " + e);
}
animate();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment