Measure distance between points of STL file using three.js - javascript

I am trying to get the user to click on two different points and get distance between them.
The clicks seems to be happening at random positions, so the calculation is getting to be wrong.
The calculation is correct when the the OBJ loader is used and we use an OBJ file, but if I use an STL file using the STL loader, it just shows up incorrect.
Codepen link: https://codepen.io/anon/pen/NLXavX
JS Code:
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/qooungyrgltucai/three.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/ddt89ncslm4o7ie/Detector.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/mrhumrr2bxwt9nt/OBJLoader.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/n5sjyymajykna51/TGALoader.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/y4r5bmq2037jacg/OrbitControls.js"></script>
<script type="text/javascript" src="https://dl.dropboxusercontent.com/s/h18h48v52739df4/STLLoader.js"></script>
<script>
var container;
var camera, controls, scene, renderer, model;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
controls = new THREE.OrbitControls(camera);
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight(0x404040); //0x101030
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
// Loading manager
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
var onProgress = function (xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
}
};
var onError = function (xhr) {
console.log('Error: ' + xhr);
};
// Model
//model = new THREE.Object3D();
//scene.add(model);
var material = new THREE.MeshPhongMaterial({
color: 0xffffff,
needsUpdate: true
});
window.model ='';
// Added an if else here, STL code:
var loader = new THREE.STLLoader();
loader.load( 'https://dl.dropboxusercontent.com/s/t57h7xketafodui/5a9b75e521aaf-DI_PIPE_FBG_holder.stl', function ( geometry ) {
var material = new THREE.MeshPhongMaterial( { color: 0xff5533, specular: 0x111111, shininess: 200 } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.set( 0, - 0.25, 0.6 );
mesh.rotation.set( 0, - Math.PI / 2, 0 );
mesh.scale.set( 0.05, 0.05, 0.05 );
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add( mesh );
window.model = scene;
} );
// This OBJ Loader will load if user requests an OBJ file.
var loader = new THREE.OBJLoader(manager);
var object = loader.load('https://dl.dropboxusercontent.com/s/pn3yw6w5962o5r8/BIGIPIGI.obj', function (Object) {
Object.castShadow = true;
Object.position.x = 0;
Object.position.y = -1;
Object.position.z = 0;
Object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material = material;
}
});
console.log(Object);
window.model = Object;
scene.add(Object);
}, onProgress, onError);
// Object
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousedown', onDocumentMouseDown, false);
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// Measurement Code
var pointA = new THREE.Vector3( 0, 1, 0 );
var pointB = new THREE.Vector3();
var markerA = new THREE.Mesh( new THREE.SphereGeometry( 0.1, 16, 16 ), new THREE.MeshBasicMaterial( { color: 0xFF5555, depthTest: false, depthWrite: false } ) );
var markerB = markerA.clone();
scene.add( markerA );
scene.add( markerB );
var line;
function getIntersections( event ) {
var vector = new THREE.Vector2();
vector.set(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1 );
var raycaster = new THREE.Raycaster();
raycaster.setFromCamera( vector, camera );
var intersects = raycaster.intersectObjects( window.model.children );
return intersects;
}
function getLine( vectorA, vectorB ) {
var geometry = new THREE.Geometry();
geometry.vertices.push( vectorA );
geometry.vertices.push( vectorB );
var material = new THREE.LineBasicMaterial({
color: 0xFFFF00,
depthWrite: false,
depthTest: false
});
line = new THREE.Line( geometry, material );
return line;
}
function onDocumentMouseDown( event ) {
var intersects = getIntersections( event );
if( intersects.length > 0 ){
if ( ! pointB.equals( pointA ) ) {
pointB = intersects[ 0 ].point;
} else {
pointB = pointA;
}
pointA = intersects[ 0 ].point;
markerA.position.copy( pointA );
markerB.position.copy( pointB );
var distance = pointA.distanceTo( pointB );
if ( line instanceof THREE.Line ) {
scene.remove( line );
}
if ( distance > 0 ) {
console.log( "distance", distance );
alert( "distance: "+distance );
line = getLine( pointA, pointB );
scene.add(line);
}
}
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}</script>

Try to add in CSS section:
body{
overflow: hidden;
margin: 0;
}

Related

Cycle through materials onclick with three.js

I'm new to three.js and I'd like to learn how to cycle through materials onclick. This example shows what I'd like to achieve except it's cycling through textures rather than materials.
I'd like to have the materials in an array, then be able to click the canvas to cycle and loop through the materials.
Here's the code for the above example:
var scene = new THREE.Scene();
scene.background = new THREE.Color( 0xcccccc );
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;
camera.position.y = 5;
camera.position.x = 5;
camera.lookAt(new THREE.Vector3(0,0,0)); // Make the camera look at the point of origin
var renderer = new THREE.WebGLRenderer({antialias:true});
var devicePixelRatio = window.devicePixelRatio || 1; // To handle high pixel density displays
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(devicePixelRatio);
document.body.appendChild( renderer.domElement );
var render = function () {
requestAnimationFrame( render );
renderer.render(scene, camera);
};
// instantiate a texture loader
var loader = new THREE.TextureLoader();
//allow cross origin loading
loader.crossOrigin = '';
// The textures to use
var arr = [
'https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/THREE_gates.jpg',
'https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/THREE_crate1.jpg',
'https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/THREE_crate2.jpg'
];
var textureToShow = 0;
// Load the first texture
// var texture = loadTexture('https://s3-us-west-2.amazonaws.com/s.cdpn.io/259155/MarbleSurface.jpg');
// Instantiate the material we will be using
var material = new THREE.MeshBasicMaterial();
// Instantiate a geometry to use
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
// Instatiate the mesh with the geometry and material
var cube = new THREE.Mesh( geometry, material );
cube.position.y = 0.5;
// Then load the texture
loader.load(arr[textureToShow], function(tex) {
// Once the texture has loaded
// Asign it to the material
material.map = tex;
// Update the next texture to show
textureToShow++;
// Add the mesh into the scene
scene.add( cube );
});
// Click interaction
var canvas = document.getElementsByTagName("canvas")[0];
canvas.addEventListener("click", function() {
loader.load(arr[textureToShow], function(tex) {
// Once the texture has loaded
// Asign it to the material
material.map = tex;
// Update the next texture to show
textureToShow++;
// Have we got to the end of the textures array
if(textureToShow > arr.length-1) {
textureToShow = 0;
}
});
});
// Start rendering the scene
render();
Here's the code I can't get working:
var container, stats;
var camera, scene, renderer;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var globalObject;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.z = 500;
//scene
scene = new THREE.Scene();
ambientLight = new THREE.AmbientLight(0xffffff, 0.2);
scene.add(ambientLight);
pointLight = new THREE.PointLight(0xff0000, 0.5);
pointLight.position.z = 2500;
scene.add(pointLight);
var pointLight2 = new THREE.PointLight(0xff6666, 1);
camera.add(pointLight2);
var pointLight3 = new THREE.PointLight(0x0000ff, 0.5);
pointLight3.position.x = -1000;
pointLight3.position.z = 1000;
scene.add(pointLight3);
//manager
var manager = new THREE.LoadingManager();
manager.onProgress = function(item, loaded, total) {
console.log(item, loaded, total);
};
//materials
var path = "textures/cube/skybox/";
var format = '.jpg';
var urls = [
path + 'px' + format, path + 'nx' + format,
path + 'py' + format, path + 'ny' + format,
path + 'pz' + format, path + 'nz' + format
];
var reflectionCube = new THREE.CubeTextureLoader().load(urls);
var material = new THREE.MeshStandardMaterial({
envMap: reflectionCube,
roughness: 0.1,
metalness: 1,
color: 0xfee6af,
});
var materialTwo = new THREE.MeshStandardMaterial({
envMap: reflectionCube,
roughness: 0.1,
metalness: 0,
color: 0xffff00,
});
//model
var loader = new THREE.OBJLoader(manager);
loader.load('logo97.obj', function(object) {
//store global reference to .obj
globalObject = object;
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material = material;
child.material.needsUpdate = true;
}
});
object.position.y = 0;
scene.add(object);
});
//render
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousemove', onDocumentMouseMove, false);
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
// Click interaction
var canvas = document.getElementsByTagName("canvas")[0];
canvas.addEventListener("click", function() {
var materials = [
new THREE.MeshBasicMaterial( {color:'#b02030'} ),
new THREE.MeshLambertMaterial( {color:'#b02030'} ),
new THREE.MeshPhongMaterial( {color:'#b02030', shininess: 100 } ),
new THREE.MeshNormalMaterial(),
// ...
];
var materialToShow = 0;
materialToShow ++;
if ( materialToShow >= materials.length ) materialToShow = 0;
child.material = materials[materialToShow];
});
//animate
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * .05;
camera.position.y += (-mouseY - camera.position.y) * .05;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
You have to create an array of THREE.Materials:
e.g.
var materials = [
new THREE.MeshBasicMaterial( {color:'#b02030'} ),
new THREE.MeshLambertMaterial( {color:'#b02030'} ),
new THREE.MeshPhongMaterial( {color:'#b02030', shininess: 100 } ),
new THREE.MeshNormalMaterial(),
// ...
];
var materialToShow = 0;
In the "click" can change the current material of the THREE.Mesh by changing the property .material.
canvas.addEventListener("click", function() {
materialToShow ++;
if ( materialToShow >= materials.length ) materialToShow = 0;
mesh.material = materials[materialToShow];
});
Of course you have to add some light (e.g. THREE.AmbientLight, THREE.DirectionalLight) to the scne, to make the behaviour of the different materials "visible".
See the example, where I applied the suggested changes to your original code.
I used a sphere, to represent the specular highlight of the THREE.MeshPhongMaterial.
And I removed the texture, but of course you can apply the texture, too.
var scene = new THREE.Scene();
scene.background = new THREE.Color( 0xcccccc );
var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.y = 4;
camera.lookAt(new THREE.Vector3(0,0,0)); // Make the camera look at the point of origin
var renderer = new THREE.WebGLRenderer({antialias:true});
var devicePixelRatio = window.devicePixelRatio || 1; // To handle high pixel density displays
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(devicePixelRatio);
document.body.appendChild( renderer.domElement );
window.onresize = resize;
var ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
directionalLight.position.set(1,2,-1.0);
scene.add( directionalLight );
var render = function () {
requestAnimationFrame( render );
renderer.render(scene, camera);
};
var materials = [
new THREE.MeshBasicMaterial( {color:'#b02030'} ),
new THREE.MeshLambertMaterial( {color:'#b02030'} ),
new THREE.MeshPhongMaterial( {color:'#b02030', shininess: 100 } ),
new THREE.MeshNormalMaterial(),
// ...
];
var materialToShow = 0;
var geometry = new THREE.SphereGeometry( 1, 32, 16 );
var mesh = new THREE.Mesh( geometry, materials[materialToShow] );
scene.add( mesh );
// Click interaction
var canvas = document.getElementsByTagName("canvas")[0];
canvas.addEventListener("click", function() {
materialToShow ++;
if ( materialToShow >= materials.length ) materialToShow = 0;
mesh.material = materials[materialToShow];
});
function resize() {
var aspect = window.innerWidth / window.innerHeight;
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = aspect;
camera.updateProjectionMatrix();
}
// Start rendering the scene
render();
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/99/three.min.js"></script>
Since you have used the THREE.OBJLoader, you have to change of the .material of the .children of the root object globalObject (Object3D).
Of course materialToShow and materials have to be initialized only once:
var materials = [
new THREE.MeshBasicMaterial( {color:'#b02030'} ),
new THREE.MeshLambertMaterial( {color:'#b02030'} ),
new THREE.MeshPhongMaterial( {color:'#b02030', shininess: 100 } ),
new THREE.MeshNormalMaterial(),
// ...
];
var materialToShow = 0;
canvas.addEventListener("click", function() {
materialToShow ++;
if ( materialToShow >= materials.length ) materialToShow = 0;
globalObject.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material = materials[materialToShow];
child.material.needsUpdate = true;
}
});
});
See the example, where I applied the changes to your original code, with some changes to make it work in here:
var container, stats;
var camera, scene, renderer;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var globalObject;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.y = 3;
camera.position.z = 3;
//scene
scene = new THREE.Scene();
ambientLight = new THREE.AmbientLight(0xffffff, 0.2);
scene.add(ambientLight);
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
directionalLight.position.set(0.5,2,-1.0);
scene.add( directionalLight );
pointLight = new THREE.PointLight(0xff0000, 0.5);
pointLight.position.z = 10;
scene.add(pointLight);
var pointLight2 = new THREE.PointLight(0xff6666, 1);
camera.add(pointLight2);
var pointLight3 = new THREE.PointLight(0x0000ff, 0.5);
pointLight3.position.x = -10;
pointLight3.position.z = 10;
scene.add(pointLight3);
//manager
var manager = new THREE.LoadingManager();
manager.onProgress = function(item, loaded, total) {
console.log(item, loaded, total);
};
//materials
/*
var path = "textures/cube/skybox/";
var format = '.jpg';
var urls = [
path + 'px' + format, path + 'nx' + format,
path + 'py' + format, path + 'ny' + format,
path + 'pz' + format, path + 'nz' + format
];
*/
//var reflectionCube = new THREE.CubeTextureLoader().load(urls);
var material = new THREE.MeshStandardMaterial({
//envMap: reflectionCube,
roughness: 0.1,
metalness: 1,
color: 0xfee6af,
});
var materialTwo = new THREE.MeshStandardMaterial({
//envMap: reflectionCube,
roughness: 0.1,
metalness: 0,
color: 0xffff00,
});
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
var textFile = window.URL.createObjectURL(data);
return textFile;
}
var textbox_obj = document.getElementById('plane_obj');
var obj_url = makeTextFile(textbox_obj.value);
//model
var loader = new THREE.OBJLoader(manager);
loader.load(obj_url, function(object) {
//store global reference to .obj
globalObject = object;
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material = material;
child.material.needsUpdate = true;
}
});
object.position.y = 0;
scene.add(object);
});
//render
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousemove', onDocumentMouseMove, false);
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
// Click interaction
var canvas = document.getElementsByTagName("canvas")[0];
var materials = [
new THREE.MeshBasicMaterial( {color:'#b02030'} ),
new THREE.MeshLambertMaterial( {color:'#b02030'} ),
new THREE.MeshPhongMaterial( {color:'#b02030', shininess: 100 } ),
new THREE.MeshNormalMaterial(),
// ...
];
var materialToShow = 0;
canvas.addEventListener("click", function() {
materialToShow ++;
if ( materialToShow >= materials.length ) materialToShow = 0;
globalObject.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material = materials[materialToShow];
child.material.needsUpdate = true;
}
});
});
//animate
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
//camera.position.x += (mouseX - camera.position.x) * .05;
//camera.position.y += (-mouseY - camera.position.y) * .05;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
<textarea id="plane_obj" style="display:none;">
# Blender v2.77 (sub 0) OBJ File: 'Plane.blend'
# www.blender.org
mtllib Plane.mtl
o Plane
v -1.000000 0.000000 1.000000
v 1.000000 0.000000 1.000000
v -1.000000 0.000000 -1.000000
v 1.000000 0.000000 -1.000000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 0.000000 1.000000
vt 1.000000 1.000000
vn 0.0000 1.0000 0.0000
usemtl Material
s off
f 1/1/1 2/2/1 4/4/1 3/3/1
</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/99/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/loaders/OBJLoader.js"></script>

Why is my PlaneGeometry not receiving a shadow?

I am using three.js to create a scene that has a model on it. I have a plane on which the model sits, and a spotlight shining on the model.
The model is made up of a number of different objects. All of the objects are set to receive and cast shadows. Shadows are being cast on the model itself from other areas of the model.
The plane, however, won't receive shadows. I'm unsure why.
I have adjusted the spotLight.shadowCameraNear and spotLight.shadowCameraFar properties to ensure both the model and plane are within the shadow area. Still nothing.
Below is a screenshot of the model with the spotlight visible.
I have the shadowmap enabled and set to the soft maps:
renderer.shadowMap.enabled = true; // Shadow map enabled
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
My code is as follows:
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats, controls;
var camera, scene, renderer, sceneAnimationClip ;
var clock = new THREE.Clock();
var mixers = [];
var globalObjects = [];
init();
function init() {
var loader = new THREE.TextureLoader();
container = document.createElement( 'div' );
document.body.appendChild( container );
// Scene
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xffffff, 50, 100 );
// Camera
camera = new THREE.PerspectiveCamera( 30, (window.innerWidth / window.innerHeight), 1, 10000 );
camera.position.x = 1000;
camera.position.y = 50;
camera.position.z = 1500;
scene.add( camera );
// LIGHTS
var spotLight = new THREE.SpotLight( 0xffffff,1 );
spotLight.position.set( 5, 5, 6 );
spotLight.castShadow = true;
spotLight.target.position.set(-1, 0, 2 );
spotLight.shadowDarkness = 0.5;
spotLight.shadowCameraNear = 4;
spotLight.shadowCameraFar = 25;
scene.add( spotLight );
// Camera helper for spotlight
var helper = new THREE.CameraHelper( spotLight.shadow.camera );
scene.add( helper );
// ground
var geometry = new THREE.PlaneGeometry( 30, 30 );
geometry.receiveShadow = true;
var material = new THREE.MeshBasicMaterial( {color: 0xcccccc, side: THREE.DoubleSide} );
material.receiveShadow = true;
var floor = new THREE.Mesh( geometry, material );
floor.receiveShadow = true;
floor.position.y = -1;
floor.rotation.x = Math.PI / 2;
scene.add( floor );
// stats
stats = new Stats();
container.appendChild( stats.dom );
// model
var manager = new THREE.LoadingManager();
manager.onProgress = function( item, loaded, total ) {
console.log( item, loaded, total );
};
// BEGIN Clara.io JSON loader code
var i = 0;
var objectLoader = new THREE.ObjectLoader();
objectLoader.load("final-master-20170426.json", function ( object ) {
var textureLoader = new THREE.TextureLoader();
object.traverse( function ( child )
{
if ( child instanceof THREE.Mesh ) {
var material = child.material.clone();
material.shininess = 0;
material.wireframe = false;
material.normalScale = new THREE.Vector2( 1, 1 );
/* Roof Glass */
if(child.name == 'Roof_Glass') {
material.shininess = 100;
material.alphaMap = grayscale;
material.transparent = true;
}
// Beading
if(child.name.endsWith('_Beading')) {
material.color.setHex( 0x1e1e1e );
material.shininess = 100;
}
/* Pillars */
if(
child.name.indexOf('Pillar') == 0 ||
child.name == 'Main_Frame' ||
child.name == 'Main_Cross_Supports' ||
child.name == 'roof_batons' ||
child.name == 'Roof_Flashings'
) {
material.color.setHex( 0x1e1e1e );
material.shininess = 100;
}
/* Lamps */
if(child.name.indexOf('Lamp') == 0) {
material.color.setHex( 0x1e1e1e );
material.shininess = 100;
}
// Set shadows for everything
material.castShadow = true;
material.receiveShadow = true;
child.material = material;
material = undefined;
globalObjects[child.name] = child;
console.log(child);
}
});
object.position.y = -1;
object.position.x = 0;
scene.add( object );
scene.fog = new THREE.Fog( 0xffffff, 50, 100 );
i++;
} );
// END Clara.io JSON loader code
renderer = new THREE.WebGLRenderer({
'antialias': true
});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( scene.fog.color );
container.appendChild( renderer.domElement );
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMap.enabled = true; // Shadow map enabled
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// controls, camera
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.target.set( 0, 0, 0 );
controls.maxPolarAngle = Math.PI * 0.5;
camera.position.set( 8, 3, 10 );
controls.update();
window.addEventListener( 'resize', onWindowResize, false );
animate();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
//
function animate() {
requestAnimationFrame( animate );
stats.update();
render();
}
function render() {
var delta = 0.75 * clock.getDelta();
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
This was fixed by using a THREE.MeshPhongMaterial instead of a THREE.MeshBasicMaterial.

Lean object towards mouse threejs

I am trying to recreate a mouse interaction with an obj file - similar to this example:
http://yungjake.com/usb/
Additionally, I am trying to have it animate when clicked upon - and I really want to recreate the smoothness/physics of the mouse interaction when the mouse is hovering.
My code so far is hardly close but here it is:
<script src="three.min.js"></script>
<script src="EffectComposer.js"></script>
<script src="CopyShader.js"></script>
<script src="DotScreenShader.js"></script>
<script src="RGBShiftShader.js"></script>
<script src="FilmShader.js"></script>
<script src="FilmPass.js"></script>
<script src="RenderPass.js"></script>
<script src="MaskPass.js"></script>
<script src="ShaderPass.js"></script>
<script src="Detector.js"></script>
<script src="OBJLoader.js"></script>
<script>
var camera, scene, renderer, composer;
var object, light;
var geometry;
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var composer = new THREE.EffectComposer(renderer);
//
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 20;
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0x000000, 1, 1000 );
//=======================================================================================================================================================
//=======================================================================================================================================================
// BACKGROUND
scene.background = new THREE.CubeTextureLoader()
.load( [ 'px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg' ] );
var textureCube = new THREE.CubeTextureLoader()
.load( [ 'px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg' ] );
textureCube.mapping = THREE.CubeRefractionMapping;
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
scene.add( new THREE.AmbientLight( 0x222222 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 );
scene.add( light );
// postprocessing
composer = new THREE.EffectComposer( renderer );
var effect = new THREE.ShaderPass( THREE.RGBShiftShader );
effect.uniforms[ 'amount' ].value = .05;
effect.renderToScreen = true;
composer.addPass( effect );
var renderPass = new THREE.RenderPass(scene, camera);
composer.addPass(renderPass);
var effectFilm = new THREE.FilmPass( .5, 0, 0, false);
effectFilm.renderToScreen = true;
composer.addPass(effectFilm);
var clock = new THREE.Clock();
function render() {
var delta = clock.getDelta();
composer.render(delta); //parameter must be set with render
requestAnimationFrame(render);
}
render();
//
//=======================================================================================================================================================
//=======================================================================================================================================================
// MATERIALS + OBJ LOADER + TEXTURE
var texture = new THREE.Texture();
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
var onError = function ( xhr ) {
};
//=======================================================================================================================================================
var material1 = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube, refractionRatio: .25 } );
var loader = new THREE.ImageLoader( manager );
loader.load( 'UV_Grid_Sm.jpg', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
var loader = new THREE.OBJLoader( manager );
loader.load( 'WorkPlease.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
child.material = material1;
}
} );
window.addEventListener('mousemove', function(e){
var mouse3D = new THREE.Vector3(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
2 );
object.lookAt(mouse3D);
var angle = Math.atan2(mouse3D.y-object.position.y, mouse3D.x-object.position.x);
object.rotation.z = angle;
})
scene.add( object );
// object.position.y = 0;
// //
// object.position.x = 0;
// //
// object.position.z = 0;
//object.rotateOnAxis( 50, 50, 50 );
// object.center.x = 0;
// object.center.y = 0;
// object.center.x = 0;
//
// mesh.position.set( object.center.x, object.center.y, object.center.z );
// mesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation( -object.center.x, -object.center.y, -object.center.z ) );
}, onProgress, onError );
function onDocumentMouseMove(event) {
mouseX = ( event.clientX - windowHalfX ) * .005;
mouseY = ( event.clientY - windowHalfY ) * .005;
}
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
//composer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
// object.rotation.x += 0.005;
// object.rotation.y += 0.01;
// composer.render();
}
</script>
</body>
Please let me know what I should change or if there are any tutorials that could help me out with this. I am a beginner so any help is appreciated.
Thanks.

Loading a JSON model in three.js

I have been trying to display a 3D json model using three.js. I am fairly new to three.js and have tried everything I can think of, but don't know anything else to try.
Currently when I try to load the model I get an error that says:
Uncaught TypeError: Cannot read property 'visible' of undefinedr # three.min.js:602r # three.min.js:602render # three.min.js:649render # test.html:106animate # test.html:100
I really am not sure where to go from here. Thanks for any help.
Here is my code:
<script type="text/javascript">
if (!Detector.webgl) Detector.addGetWebGLMessage();
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = 0;
var container;
var camera, scene;
var webglRenderer;
var zmesh, geometry;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
document.addEventListener(
'mousemove',
onDocumentMouseMove,
false
);
init();
animate();
// Renderer
webglRenderer = new THREE.WebGLRenderer();
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = 'relative';
container.appendChild(webglRenderer.domElement);
// Loader
var loader = new THREE.JSONLoader(),
callbackModel = function(geometry) {
createScene(geometry, 90, FLOOR, -50, 105)
};
loader.load('can.js', callbackModel);
function init() {
container = document.createElement('div');
document.body.appendChild(container);
// Camera
camera = new THREE.PerspectiveCamera(
75,
SCREEN_WIDTH / SCREEN_HEIGHT,
1,
100000
);
camera.position.z = 75;
// Scene
scene = new THREE.Scene();
// Lights
var ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);
// More lights
var directionalLight = new THREE.DirectionalLight(0xffeedd);
directionalLight.position.set(0, -70, 100).normalize();
scene.add(directionalLight);
}
function createScene( geometry, x, y, z, b ) {
zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );
zmesh.position.set( 0, 16, 0 );
zmesh.scale.set( 1, 1, 1 );
scene.add( zmesh );
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX);
mouseY = (event.clientY - windowHalfY);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
if(webglRenderer != undefined && zmesh != undefined) {
zmesh.rotation.set(-mouseY/500 + 1, -mouseX/200, 0);
webglRenderer.render(scene, camera);
}
}
</script>
If your JSON file contains material information, then a materials array will be passed to your callback function, and you need to do this:
callbackModel = function( geometry, materials ) {
// your code
};
...
zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
Otherwise, you need to define your own material. For example,
zmesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: 0xff000 } ) );
three.js r.77

How to show a cube map reflection on a object without showing the cubemap in the background?

How to show a cube map reflection on a object without showing the cubemap in the background?
I like to receive a reflection on a lever mechanism without showing a cubemap in the background. The background should be with a gradient from blue to white.
So basicially, the cubemap should be only visible on the object.
Thank you very much in advance!
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container;
var loader;
var camera, cameraTarget, controls, scene, renderer;
init();
animate();
function init() {
var previewDiv = document.getElementById("preview");
camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 15 );
camera.position.set( 3, 0.15, 3 );
cameraTarget = new THREE.Vector3( 0, -0.25, 0 );
controls = new THREE.OrbitControls( camera );
controls.maxPolarAngle = Math.PI / 2.2;
controls.minDistance = 3;
controls.maxDistance = 8;
// controls.noPan = true;
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xdae1e6, 2, 15 );
// Ground
var plane = new THREE.Mesh(
new THREE.PlaneBufferGeometry( 40, 40 ),
new THREE.MeshPhongMaterial( { color: 0x999999, specular: 0x101010 } )
);
plane.rotation.x = -Math.PI/2;
plane.position.y = -0.5;
scene.add( plane );
plane.receiveShadow = true;
// feinleinen
var feinleinen = THREE.ImageUtils.loadTexture( 'textures/feinleinen.jpg' );
feinleinen.anisotropy = 1;
feinleinen.wrapS = feinleinen.wrapT = THREE.RepeatWrapping;
feinleinen.repeat.set( 5, 5 );
// create a cube
var basisGeometry = new THREE.BoxGeometry(3,0.02,3);
var basisMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff, map: feinleinen } );
var basis = new THREE.Mesh(basisGeometry, basisMaterial);
basis.castShadow = false;
basis.receiveShadow = true;
// position the cube
basis.position.set( 0, -0.47, 0 );
// add the cube to the scene
scene.add(basis);
var loader = new THREE.JSONLoader();
loader.load('/models/hebelmechanik.js', function(geo, mat){
var chrome = new THREE.MeshLambertMaterial( { ambient: 0x444444, color: 0x111111, shininess: 800, specular: 0x111111, shading: THREE.SmoothShading, reflectivity: 1.1 } );
var mesh = new THREE.Mesh(geo, chrome);
mesh.position.set( 0, - 0.497, 0 );
mesh.rotation.set( 0, - Math.PI / 2, 0 );
mesh.scale.set( 0.008, 0.008, 0.008 );
mesh.castShadow = true;
mesh.receiveShadow = true;
loadJson(mesh );
});
function loadJson(mesh){
scene.add( mesh );
}
// Lights
scene.add( new THREE.AmbientLight( 0x777777 ) );
addShadowedLight( 1, 1, 1, 0xffffff, 1.35 );
addShadowedLight( 0.5, 1, -1, 0xffffff, 1 );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( scene.fog.color );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
renderer.shadowMapCullFace = THREE.CullFaceBack;
previewDiv.appendChild (renderer.domElement);
// resize
window.addEventListener( 'resize', onWindowResize, false );
}
function addShadowedLight( x, y, z, color, intensity ) {
var directionalLight = new THREE.DirectionalLight( color, intensity );
directionalLight.position.set( x, y, z )
scene.add( directionalLight );
directionalLight.castShadow = true;
// directionalLight.shadowCameraVisible = true;
var d = 1;
directionalLight.shadowCameraLeft = -d;
directionalLight.shadowCameraRight = d;
directionalLight.shadowCameraTop = d;
directionalLight.shadowCameraBottom = -d;
directionalLight.shadowCameraNear = 1;
directionalLight.shadowCameraFar = 4;
directionalLight.shadowMapWidth = 2048;
directionalLight.shadowMapHeight = 2048;
directionalLight.shadowBias = -0.005;
directionalLight.shadowDarkness = 0.15;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.lookAt( cameraTarget );
controls.update();
renderer.render( scene, camera );
}
</script>
You can add a cubemap reflection to your model by specifying the envMap property of the model's material.
Use a pattern like this one:
var path = "textures/cube/foo/";
var format = '.png';
var urls = [
path + 'px' + format, path + 'nx' + format,
path + 'py' + format, path + 'ny' + format,
path + 'pz' + format, path + 'nz' + format
];
var envMap = THREE.ImageUtils.loadTextureCube( urls, THREE.CubeReflectionMapping, callback ); // callback function is optional
var material = new THREE.MeshPhongMaterial( {
color : 0x999999,
specular : 0x050505,
shininess : 50,
envMap : envMap,
combine : THREE.MixOperation, // or THREE.AddOperation, THREE.MultiplyOperation
reflectivity : 0.5
} );
three.js r.71

Categories