Object loaded with ObjLoader does not receive shadows in three.js - three.js

The model casts shadows on a ground-plane but it does NOT receive shadows from another small plane in front (which does cast shadows on the ground-plane), let alone from itself. Any ideas ???
var light = new THREE.DirectionalLight( 0xffefee, 1.2 );
light.position.set( 0, 40, 100 );
light.shadow.camera.left = -100;
light.shadow.camera.right = 100;
light.shadow.camera.top = 100;
light.shadow.camera.bottom = -100;
light.shadow.camera.far = 1000;
light.shadow.camera.near = 1;
light.shadow.mapSize.width = 512;
light.shadow.mapSize.height = 512;
light.castShadow = true;
light.shadowDarkness = 0.5;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
var femModel = null;
mtlLoader.setMaterialOptions({ side:THREE.DoubleSide });
mtlLoader.load( 'female02.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'female02/' );
objLoader.load( 'female02.obj', function ( object ) {
femModel = object;
femModel.position.set( 0, -80, 0 );
sceneRTTA.add( femModel );
}, onProgress, onError );
});
The setup function is called after it has loaded completely:
function setupmodel(){
femModel.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
} );
}
three.js 0.91.0

Related

MTLLoader breaks other 3js code and isn't loading texture right

I am having trouble getting the MTLLoader to work correctly. I have already been able to use the OBJLoader by itself to load the 3d object and I have a camera that works properly too in my scene. When I try and use the MTLLoader with the OBJLoader the object loads but it breaks my other three.js code. I get these errors:
three.js:24415 Uncaught TypeError: Cannot set property 'value' of undefined
at initMaterial (three.js:24415)
at setProgram (three.js:24493)
at WebGLRenderer.renderBufferDirect (three.js:23552)
at renderObject (three.js:24269)
at renderObjects (three.js:24239)
at WebGLRenderer.render (three.js:24037)
at render (demo2.html:480)
The object loads and it looks like some textures load but the textures don't look right, the camera breaks. I have been having trouble with this and could really use some guidance.
Here is my MTLLoader code by itself
var mesh = null;
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( 'dapHouseGood5.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load( 'dapHouseGood5.obj', function ( object ) {
mesh = object;
scene.add( mesh );
} );
Here is the rest of my three.js code for reference
<script>
/* global THREE */
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const renderer2 = new THREE.WebGLRenderer({canvas});
var kitchenCameraActive = false;
document.getElementById("roomSelect").addEventListener("change", changeIt);
function changeIt(e) {
document.getElementById(e.target.value).click();
console.log(e);
}
var fov = 45;
var aspect = 2; // the canvas default
var near = 0.1;
var far = 100;
var camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(-97.570, 5.878, -5.289);
camera.rotation.set(0,0,0);
const controls = new THREE.OrbitControls(camera, canvas);
controls.target.set(0, 5, 0);
controls.update();
document.getElementById("kitchen").addEventListener("click", changeCamera);
document.getElementById("bathroom").addEventListener("click", changeCamera);
document.getElementById("deck").addEventListener("click", changeCamera);
document.getElementById("livingRoom").addEventListener("click", changeCamera);
document.getElementById("bedRoom").addEventListener("click", changeCamera);
document.getElementById("walkway").addEventListener("click", changeCamera);
document.getElementById("sideHouse").addEventListener("click", changeCamera);
document.getElementById("frontPorch").addEventListener("click", changeCamera);
document.getElementById("garageDoor").addEventListener("click", changeCamera);
document.getElementById("insideGarage").addEventListener("click", changeCamera);
function changeCamera(e) {
camera.rotation.set(e.toElement.attributes[5].nodeValue,
e.toElement.attributes[6].nodeValue, e.toElement.attributes[7].nodeValue);
camera.fov = e.toElement.attributes[4].nodeValue;
camera.position.set(e.toElement.attributes[1].nodeValue,
e.toElement.attributes[2].nodeValue, e.toElement.attributes[3].nodeValue);
camera.updateProjectionMatrix();
if (e.target.id == "walkway" || e.target.id == "frontPorch" || e.target.id ==
"garageDoor" || e.target.id == "insideGarage")
{
controls.target.set(0, 5, 0);
controls.update();
}
if(e.target.id == "kitchen"){
controls.target.set(7, 6, 7);
}
if(e.target.id == "bathroom"){
controls.target.set(-9,15,-7);
}
if(e.target.id == "deck"){
controls.target.set(31, 7, 1);
}
if(e.target.id == "livingRoom"){
controls.target.set(-12.5, 1.5, -18.5);
}
if(e.target.id == "bedRoom"){
controls.target.set(-15.7, 14, -21);
}
if(e.target.id == "insideGarage"){
controls.target.set(24.405, 6.733, -6.425);
}
controls.update();
console.log(e);
}
const scene = new THREE.Scene();
scene.background = new THREE.Color('black');
{
const planeSize = 40;
}
{
const skyColor = 0xB1E1FF; // light blue
const groundColor = 0xB97A20; // brownish orange
const intensity = 1;
const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
scene.add(light);
}
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(5, 10, 2);
scene.add(light);
scene.add(light.target);
}
var mesh = null;
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( 'dapHouseGood5.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load( 'dapHouseGood5.obj', function ( object ) {
mesh = object;
scene.add( mesh );
} );
} );
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render() {
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
function onPositionChange(o) {
console.log("position changed in object");
console.log(o);
console.log('camera_default: '+camera.position.x+', '+camera.position.y+',
'+camera.position.z);
console.log('camera_default: '+camera.rotation.x+', '+camera.rotation.y+',
'+camera.rotation.z);
console.log(camera.fov);
console.log('quaternion_default: '+camera.quaternion.x+', '+
camera.quaternion.y+', '+camera.quaternion.z+', '+camera.quaternion.w);
}
controls.addEventListener('change', onPositionChange);
var mouse = new THREE.Vector2();
var raycaster, mouse = { x : 0, y : 0};
init();
function init () {
//Usual setup code here.
raycaster = new THREE.Raycaster();
renderer.domElement.addEventListener( 'click', raycast, false );
}
function raycast ( e ) {
//1. sets the mouse position with a coordinate system where the center
// of the screen is the origin
mouse.x = ( e.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
//2. set the picking ray from the camera position and mouse coordinates
raycaster.setFromCamera( mouse, camera );
//var mouse3D = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, -(
event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
//raycaster.setFromCamera( mouse3D, camera );
//3. compute intersections
var intersects = raycaster.intersectObjects( scene.children, true );
for ( var i = 0; i < intersects.length; i++ ) {
console.log( intersects[ i ].object.name );
}
}
}
main();
</script>

Can Not See 3d Obj. Model When Loaded With THREE.js

I load an obj file from an external resource with three.js. From onProgress callback function I can see that object is loaded without any error. However I can not see object on the screen.
I tried diffrent textures and different camera postion but still can not see the object.
Interestingly, obj file can be easily seen with Windows Object VÄ°ewer without any settings.
Here the boj file I used and CAD program settings while exporting obj:
Obj files and related files with obj file: https://ufile.io/e3oplk29
Obj File export options on the CAD program: https://pasteboard.co/Ieu9226.jpg
Here the code I use:
////************HERE LIGHT AND SCENE AND CAMERA****************////
var directionalLightIntensity = 1;
var ambientLightIntensity = 0.05;
var ambiColor = "#ffffff";
var metalValue = 0;
var roughValue = 1;
var kumas = "<?php echo CUSTOMSHIRT_PLUGIN_DIR_URL.'customshirt/';?>"+"kumas/kumas9.jpg";
var kumasNormal = "<?php echo CUSTOMSHIRT_PLUGIN_DIR_URL.'customshirt/';?>"+"kumas/kumas9_NORMAL.jpg";
var container = document.getElementById('cloth-container');
if(window.innerWidth > 767 ){
var render_height = document.documentElement.clientHeight - 8;
var render_width = document.documentElement.clientWidth - 130;
}else{
var render_height = document.documentElement.clientHeight - 95;
var render_width = document.documentElement.clientWidth;
}
const scene = new THREE.Scene();
var light = new THREE.DirectionalLight('#ffffff', directionalLightIntensity);
var ambientLight = new THREE.AmbientLight(ambiColor, ambientLightIntensity);
light.position.set(0,0,1);
scene.add(light);
scene.add(ambientLight);
const camera = new THREE.PerspectiveCamera(75, render_width/render_height,0.1,1000);
camera.position.z = 1.8 ;
camera.position.y = 1.2;
camera.position.x = 0;
camera.lookAt( 0,1.2,0);
const renderer = new THREE.WebGLRenderer({ alpha: true , antialias:true });
renderer.setSize(render_width, render_height);
renderer.setClearColor( 0xffffff, 0);
container.appendChild(renderer.domElement);
const objLoader = new THREE.OBJLoader();
const mtlLoader = new THREE.MTLLoader();
mtlLoader.setMaterialOptions({side:THREE.DoubleSide});
////************HERE OBJ LOAD WITH THREE.JS****************////
mtlLoader.load( "<?php echo CUSTOMSHIRT_PLUGIN_DIR_URL.'customshirt/yaka6-n4/';?>"+'yaka6-n4.mtl', function( materials ) {
materials.preload();
objLoader.setMaterials( materials );
objLoader.load( "<?php echo CUSTOMSHIRT_PLUGIN_DIR_URL.'customshirt/yaka6-n4/';?>"+'yaka6-n4.obj', function ( obj ) {
collar_obj = obj;
obj.position.set( obj_pos_x, obj_pos_y, obj_pos_z );
obj.rotation.y = 0;
// texture
texture = textureLoader.load(kumas);
textureNormal= textureLoader.load(kumasNormal);
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
textureNormal.wrapS = textureNormal.wrapT = THREE.RepeatWrapping;
texture.repeat.x = textureXRepeat;
texture.repeat.y = textureYRepeat;
textureNormal.repeat.x = textureXRepeat;
textureNormal.repeat.y = textureYRepeat;
obj.traverse( function ( child ) {
//if ( child.isMesh ) child.material.map = texture;
if ( child.isMesh ) child.material = new THREE.MeshStandardMaterial({
//color: 0x996633,
//specular: 0x050505,
//shininess: my_shine_value,
metalness: metalValue,
roughness: roughValue,
map: texture,
normalMap: textureNormal,
//side: THREE.DoubleSide
});
});
scene.add( obj );
},
// onProgress callback
function ( xhr ) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
// onError callback
function ( err ) {
console.log( 'An error happened' );
});
});
////************HERE RENDERER****************////
function render(){
requestAnimationFrame(render);
renderer.render(scene,camera);
}
render();
Any idea is appreciated.
Thanks
It seems your object's geometry is translated. Since the asset is composed of multiple meshes, I suggest the following code to center your OBJ.
const box = new THREE.Box3().setFromObject( object );
const center = box.getCenter( new THREE.Vector3() );
object.position.x += ( object.position.x - center.x );
object.position.y += ( object.position.y - center.y );
object.position.z += ( object.position.z - center.z );
I've added this code in the onLoad() callback of OBJLoader in the following official example and was able to see the object (a shirt collar).
https://threejs.org/examples/webgl_loader_obj_mtl
three.js R 104

three.js camera tween with switch statement

I am trying to tween a camera in three.js.
I have the following code in my init function.
A switch statement i am passing through an iFrame.
window.onmessage = function(evt) {
switch (evt.data.cameraYpos) {
case 'Ypos01':
var from01 = {
y: camera.position.y
};
var to01 = {
y: yPos01
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
case 'Ypos02':
var from02 = {
y: camera.position.y
};
var to02 = {
y: yPos02
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from02)
.to(to02, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
case 'Ypos03':
var from03 = {
y: camera.position.y
};
var to03 = {
y: yPos03
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from03)
.to(to03, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
}
}
In my main website where the iFrame is, I have 3 buttons.
Once one of them is pressed I want the camera to animate to the new Y position.
export function button03_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos03'});
console.log("cameraPos = -300");
}
export function button02_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos02'});
console.log("cameraPos = 0");
}
export function button01_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos01'});
console.log("cameraPos = 300");
}
This is my animate function
function animate() {
TWEEN.update();
requestAnimationFrame(animate);
render();
}
and this is my render function
function render() {
camera.lookAt(scene.position);
camera.position.x += ( - mouseX - camera.position.x ) * 0.05;
camera.lookAt( scene.position );
webglRenderer.render(scene, camera);
}
I manged to get it working with out a tween but now with the tween set
as soon as I press one of the buttons the model disappears from view.
I am sorry for not having a live version I am under strict NDA and switching the models just for this is allot of work. hope you understand.
Any help is most appreciated.
Thanks
You can see the full code here
<script>
/* Global vars
---------------------------------------------------
*/
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var camera, scene;
var canvasRenderer, webglRenderer;
var models_loaded = false;
var textures_loaded = false;
var container, mesh, geometry, loader, preloader;
var cameraPos
var yPos01 = 300;
var yPos02 = 0;
var yPos03 = -300;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var light;
var mouseX = 0, mouseY = 0;
/*
---------------------------------------------------
*/
/* Global materials and lighting controls
---------------------------------------------------
*/
//material
var roughness = 0.83;
var metal = 0.8;
var diffuse = 0x675f00;
//lights
var environmentInt = 0.5;
var ambiLightInt = 0.2;
var dirLightInt = 1.2;
var dirLightScalar = 1;
var hemiLightInt = 1;
/*
---------------------------------------------------
*/
/* Page Preloader
---------------------------------------------------
*/
preloader = document.createElement('img');
preloader.onload = function(){
window.addEventListener("mousemove", onmousemove, false);
init();
animate();
}
preloader.src = "https://assets.parastorage.com/marketingstudio/jessica_walsh/06/textures_512/preloader.gif";
preloader.className = "preloader";
document.body.appendChild(preloader);
/*
---------------------------------------------------
*/
/* init start
-----------------------------------------------------------------------------------------------------------------------------
*/
function init() {
/* 3D Json Loader
---------------------------------------------------
*/
container = document.createElement('div');
container.className = 'container';
container.style.visibility = 'hidden';
document.body.appendChild(container);
var manager = new THREE.LoadingManager();
manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
function onComplete(){
if(models_loaded && textures_loaded){
document.body.removeChild(preloader);
container.style.visibility = 'visible';
container.style.opacity =1;
SITE_BACKGROUNDcurrentVideovideo.play();
console.log( 'Loading completed');
}
}
manager.onLoad = function ( ) {
models_loaded = true;
onComplete();
};
manager.onProgress = function ( url, itemsLoaded, itemsTotal ) {
//console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
manager.onError = function ( url ) {
//console.log( 'There was an error loading ' + url );
};
loader = new THREE.JSONLoader(manager);
/*
---------------------------------------------------
*/
/* Creating the camera
---------------------------------------------------
*/
camera = new THREE.PerspectiveCamera(20, window.innerWidth / window.innerHeight, 10, 1500);
camera.position.z = 340;
/* Passing event through the iframe
---------------------------------------------------
*/
window.onmessage = function (evt) {
switch (evt.data.cameraYpos) {
case 'Ypos01':
var from01 = {y: camera.position.y};
var to01 = {y: yPos01};
TWEEN.removeAll();
var tween01 = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
case 'Ypos02':
var from02 = {y: camera.position.y};
var to02 = {y: yPos02};
TWEEN.removeAll();
var tween02 = new TWEEN.Tween(from02)
.to(to02, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
case 'Ypos03':
var from03 = {y: camera.position.y};
var to03 = {y: yPos03};
TWEEN.removeAll();
var tween03 = new TWEEN.Tween(from03)
.to(to03, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
}
};
/* Bulding the scene
---------------------------------------------------
*/
scene = new THREE.Scene();
//Lights
scene.add(new THREE.AmbientLight(0xffffff, ambiLightInt));
/* Main light
---------------------------------------------------
*/
light = new THREE.DirectionalLight(0xffffff, dirLightInt);
//light.position.set(100, -350, 0);
light.position.multiplyScalar(dirLightScalar);
//light.position.x = 100;
light.position.y = 100;
light.position.z = 100;
//Shadow parameters
light.castShadow = true;
light.shadowCameraVisible = true;
//light.shadowBias = 0.001;
light.shadowMapWidth = 1024;
light.shadowMapHeight = 1024;
//Shadow camera fov and position
var d = 50;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowcameranear = 0.1;
light.shadowCameraFar = 2000;
light.shadowcamerafov = 30;
light.shadowDarkness = 0;
scene.add(light);
/*
---------------------------------------------------
*/
//Skylight
var skylight = new THREE.HemisphereLight( 0xffffff, 0x080820, hemiLightInt );
scene.add( skylight );
/* Texture Loader
---------------------------------------------------
*/
var tx_manager = new THREE.LoadingManager();
tx_manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
//console.log(itemsTotal);
//console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
var total_textures = 0
tx_manager.itemEnd=function (url){
total_textures++;
if(total_textures == 20){
textures_loaded = true;
onComplete();
}
//console.log(++total_textures);
}
tx_manager.onLoad = function ( x) {
console.log(textureLoader);
//console.log( 'tx_manager complete!');
};
var textureLoader = new THREE.TextureLoader(tx_manager);
/*
---------------------------------------------------
*/
/* Environment map images
---------------------------------------------------
*/
var envUrls = [
'textures/env/02/px.jpg',
'textures/env/02/nx.jpg',
'textures/env/02/py.jpg',
'textures/env/02/ny.jpg',
'textures/env/02/pz.jpg',
'textures/env/02/nz.jpg'
],
// wrap it up into the object that we need
cubemap = THREE.ImageUtils.loadTextureCube(envUrls);
// set the format, likely RGB unless you've gone crazy
cubemap.format = THREE.RGBFormat;
/*
---------------------------------------------------
*/
/* 3D Json files loading
---------------------------------------------------
*/
// TRUNK 01
loader.load( "models/trunk_01.json", function( geometry, mat ) {
//var trunk_color = 0x0061ff;
//var trunk_01_color = textureLoader.load( "textures/trunk_01_curvature.jpg" );
var trunk_01_normal = textureLoader.load( "textures_512/trunk_01_normal.jpeg" );
var trunk_01_roughness = textureLoader.load( "textures_512/trunk_01_roughness.jpeg" );
trunk_01_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: trunk_01_roughness,
normalMap: trunk_01_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var trunk_01 = new THREE.Mesh( geometry, mat );
trunk_01.material = trunk_01_Material;
trunk_01.scale.set( 1, 1, 1 );
trunk_01.position.x = 0;
trunk_01.position.z = 0;
trunk_01.position.x = 0;
trunk_01.castShadow = true;
trunk_01.receiveShadow = true;
trunk_one = trunk_01;
scene.add( trunk_01 );
//controls_01 = new THREE.DeviceOrientationControls(trunk_one, true);
} );
// TRUNK 02
loader.load( "models/trunk_02.json", function( geometry, mat ) {
//var trunk_02_color = textureLoader.load( "textures/trunk_02_curvature.jpg" );
var trunk_02_normal = textureLoader.load( "textures_512/trunk_02_normal.jpeg" );
var trunk_02_roughness = textureLoader.load( "textures_512/trunk_02_roughness.jpg" );
trunk_02_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: trunk_02_roughness,
normalMap: trunk_02_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var trunk_02 = new THREE.Mesh( geometry, mat );
trunk_02.material = trunk_02_Material;
trunk_02.scale.set( 1, 1, 1 );
trunk_02.position.x = 0;
trunk_02.position.z = 0;
trunk_02.position.x = 0;
trunk_02.castShadow = true;
trunk_02.receiveShadow = true;
trunk_two = trunk_02;
scene.add( trunk_02 );
//controls_02 = new THREE.DeviceOrientationControls(trunk_two, true);
} );
// LEAFS
loader.load( "models/leafs.json", function( geometry, mat ) {
//var leafs_color = textureLoader.load( "textures/leafs_curvature.jpg" );
var leafs_normal = textureLoader.load( "textures_512/leafs_normal.jpeg" );
var leafs_roughness = textureLoader.load( "textures_512/leafs_roughness.jpeg" );
leafs_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: leafs_roughness,
normalMap: leafs_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var leafs = new THREE.Mesh( geometry, mat );
leafs.material = leafs_Material;
leafs.scale.set( 1, 1, 1 );
leafs.position.x = 0;
leafs.position.z = 0;
leafs.position.x = 0;
leafs.castShadow = true;
leafs.receiveShadow = true;
all_leafs = leafs;
scene.add( leafs );
//controls_03 = new THREE.DeviceOrientationControls(all_leafs, true);
} );
// ROSES
loader.load( "models/roses.json", function( geometry, mat ) {
//var roses_color = textureLoader.load( "textures/roses_curvature.jpg" );
var roses_normal = textureLoader.load( "textures_512/roses_normal.jpeg" );
var roses_roughness = textureLoader.load( "textures_512/roses_roughness.jpeg" );
roses_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: roses_roughness,
normalMap: roses_normal,
normalScale: new THREE.Vector2( 0.7, 0.7 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var roses = new THREE.Mesh( geometry, mat );
roses.material = roses_Material;
roses.scale.set( 1, 1, 1 );
roses.position.x = 0;
roses.position.z = 0;
roses.position.x = 0;
roses.castShadow = true;
roses.receiveShadow = true;
all_roses = roses;
scene.add( roses );
//controls_04 = new THREE.DeviceOrientationControls(all_roses, true);
} );
// TOPS
loader.load( "models/tops.json", function( geometry, mat ) {
//var tops_color = textureLoader.load( "textures/tops_curvature.jpg" );
var tops_normal = textureLoader.load( "textures_512/tops_normal.jpeg" );
var tops_roughness = textureLoader.load( "textures_512/tops_roughness.jpeg" );
tops_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: tops_roughness,
normalMap: tops_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var tops = new THREE.Mesh( geometry, mat );
tops.material = tops_Material;
tops.scale.set( 1, 1, 1 );
tops.position.x = 0;
tops.position.z = 0;
tops.position.x = 0;
tops.castShadow = true;
tops.receiveShadow = true;
all_tops = tops;
scene.add( tops );
//controls_05 = new THREE.DeviceOrientationControls(all_tops, true);
} );
// STEMS
loader.load( "jessica_walsh/06/models/stems.json", function( geometry, mat ) {
//var stems_color = textureLoader.load( "textures/stems_curvature.jpg" );
var stems_normal = textureLoader.load( "textures_512/stems_normal.jpeg" );
var stems_roughness = textureLoader.load( "textures_512/stems_roughness.jpeg" );
stems_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: stems_roughness,
normalMap: stems_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var stems = new THREE.Mesh( geometry, mat );
stems.material = stems_Material;
stems.scale.set( 1, 1, 1 );
stems.position.x = 0;
stems.position.z = 0;
stems.position.x = 0;
stems.castShadow = true;
stems.receiveShadow = true;
all_stems = stems;
scene.add( stems );
//controls_06 = new THREE.DeviceOrientationControls(all_stems, true);
} );
// THORNES 01
loader.load( "models/thornes_01.json", function( geometry, mat ) {
//var thornes_01_color = textureLoader.load( "textures/thornes_01_curvature.jpg" );
var thornes_01_normal = textureLoader.load( "textures_512/thornes_01_normal.jpeg" );
var thornes_01_roughness = textureLoader.load( "textures_512/thornes_01_roughness.jpeg" );
thornes_01_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: thornes_01_roughness,
normalMap: thornes_01_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var thornes_01 = new THREE.Mesh( geometry, mat );
thornes_01.material = thornes_01_Material;
thornes_01.scale.set( 1, 1, 1 );
thornes_01.position.x = 0;
thornes_01.position.z = 0;
thornes_01.position.x = 0;
thornes_01.castShadow = true;
thornes_01.receiveShadow = true;
thornes_one = thornes_01;
scene.add( thornes_01 );
//controls_07 = new THREE.DeviceOrientationControls(thornes_one, true);
} );
// THORNES 02
loader.load( "models/thornes_02.json", function( geometry, mat ) {
//var thornes_02_color = textureLoader.load( "textures/thornes_02_curvature.jpg" );
var thornes_02_normal = textureLoader.load( "textures_512/thornes_02_normal.jpeg" );
var thornes_02_roughness = textureLoader.load( "textures_512/thornes_02_roughness.jpeg" );
thornes_02_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: thornes_02_roughness,
normalMap: thornes_02_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var thornes_02 = new THREE.Mesh( geometry, mat );
thornes_02.material = thornes_02_Material;
thornes_02.scale.set( 1, 1, 1 );
thornes_02.position.x = 0;
thornes_02.position.z = 0;
thornes_02.position.x = 0;
thornes_02.castShadow = true;
thornes_02.receiveShadow = true;
thornes_two = thornes_02;
scene.add( thornes_02 );
//controls_08 = new THREE.DeviceOrientationControls(thornes_two, true);
} );
// SNAKE BOSY
loader.load( "models/snake_body.json", function( geometry, mat ) {
//var snake_body_color = textureLoader.load( "textures/snake_body_curvature.jpg" );
var snake_body_normal = textureLoader.load( "textures_512/snake_body_normal.jpeg" );
var snake_body_roughness = textureLoader.load( "textures_512/snake_body_roughness.jpg" );
snake_body_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: snake_body_roughness,
normalMap: snake_body_normal,
normalScale: new THREE.Vector2( 1.5, 1.5 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var snake_body = new THREE.Mesh( geometry, mat );
snake_body.material = snake_body_Material;
snake_body.scale.set( 1, 1, 1 );
snake_body.position.x = 0;
snake_body.position.z = 0;
snake_body.position.x = 0;
snake_body.castShadow = true;
snake_body.receiveShadow = true;
snake_b = snake_body;
scene.add( snake_body );
//controls_09 = new THREE.DeviceOrientationControls(snake_b, true);
} );
// SNAKE HEAD
loader.load( "models/snake_head.json", function( geometry, mat ) {
//var snake_head_color = textureLoader.load( "textures/snake_head_curvature.jpg" );
var snake_head_normal = textureLoader.load( "textures_512/snake_head_normal.jpeg" );
var snake_head_roughness = textureLoader.load( "textures_512/snake_head_roughness.jpeg" );
snake_head_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: snake_head_roughness,
normalMap: snake_head_normal,
normalScale: new THREE.Vector2( 2, 2 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var snake_head = new THREE.Mesh( geometry, mat );
snake_head.material = snake_head_Material;
snake_head.scale.set( 1, 1, 1 );
snake_head.position.x = 0;
snake_head.position.z = 0;
snake_head.position.x = 0;
snake_head.castShadow = true;
snake_head.receiveShadow = true;
snake_h = snake_head;
scene.add( snake_head );
//controls_10 = new THREE.DeviceOrientationControls(snake_h, true);
} );
/* 3D Json files end
---------------------------------------------------
*/
// RENDERER
webglRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = "relative";
webglRenderer.shadowMapEnabled = true;
//webglRenderer.shadowMapSoft = true;
webglRenderer.shadowMapType = THREE.PCFSoftShadowMap; // options are THREE.BasicShadowMap | THREE.PCFShadowMap | THREE.PCFSoftShadowMap
container.appendChild(webglRenderer.domElement);
window.addEventListener('resize', onWindowResize, false);
}
/* init end
-----------------------------------------------------------------------------------------------------------------------------
*/
/* Mouse mapping
---------------------------------------------------
*/
function onmousemove(event) {
//mouseX = (event.clientX / window.innerWidth) * 2 - 1;
//mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
mouseX = ( event.clientX - windowHalfX ) / 6;
mouseY = ( event.clientY - windowHalfY ) / 4;
}
/*
---------------------------------------------------
*/
/* Window resize
---------------------------------------------------
*/
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
var f = (camera.aspect/1.583);
if(f < 1){
camera.position.z = 340 /(camera.aspect/1.583);
}else{
camera.position.z = 340;
}
camera.updateProjectionMatrix();
webglRenderer.setSize(window.innerWidth, window.innerHeight);
}
/*
---------------------------------------------------
*/
/* Animate
---------------------------------------------------
*/
function animate() {
TWEEN.update();
requestAnimationFrame(animate);
render();
}
/*
---------------------------------------------------
*/
/* Render
---------------------------------------------------
*/
function render() {
camera.lookAt(scene.position);
camera.position.x += ( - mouseX - camera.position.x ) * 0.05;
camera.lookAt( scene.position );
//Light Position
light.position.x += ( - mouseX - camera.position.x ) * 0.03;
light.lookAt( scene.position );
webglRenderer.render(scene, camera);
}
/*
---------------------------------------------------
*/
</script>
As seeinvisible said the tween is passing an object
with all 3 parameters and I tried to pass only the Y.
This is my updated tween
var from01 = {y: camera.position.y, z: camera.position.z};
var to01 = {y: yPos01, z: zPos01};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function () {
camera.position.set(camera.position.x, this.y, this.z);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
In your onUpdate function you have camera.position.set(this.y). However that seems to take 3 parameters x, y, z. Try camera.position.setY(this.y) to only set the y value.

Adding image in the script code "Bad TV Shader"?

I want to be able to add images in the script code "Bad TV Shader" (https://www.airtightinteractive.com/demos/js/badtvshader/). It was originally developed for video, but I want to implement an image that also is under these distortion and noise effects.
Who can help I would be very grateful! =)
<script>
//Bad TV Effect Demo
//Using Three.js r.66
//by Felix Turner / www.airtight.cc / #felixturner
var camera, scene, renderer;
var video, videoTexture,videoMaterial;
var composer;
var shaderTime = 0;
var badTVParams, badTVPass;
var staticParams, staticPass;
var rgbParams, rgbPass;
var filmParams, filmPass;
var renderPass, copyPass;
var gui;
var pnoise, globalParams;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera(55, 1080/ 720, 20, 3000);
camera.position.z = 1000;
scene = new THREE.Scene();
//Load Video
video = document.createElement( 'video' );
video.loop = true;
video.src = "res/fits.mp4";
video.play();
//Use webcam
// video = document.createElement('video');
// video.width = 320;
// video.height = 240;
// video.autoplay = true;
// video.loop = true;
// //Webcam video
// window.URL = window.URL || window.webkitURL;
// navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
// //get webcam
// navigator.getUserMedia({
// video: true
// }, function(stream) {
// //on webcam enabled
// video.src = window.URL.createObjectURL(stream);
// }, function(error) {
// prompt.innerHTML = 'Unable to capture WebCam. Please reload the page.';
// });
//init video texture
videoTexture = new THREE.Texture( video );
videoTexture.minFilter = THREE.LinearFilter;
videoTexture.magFilter = THREE.LinearFilter;
videoMaterial = new THREE.MeshBasicMaterial( {
map: videoTexture
} );
//Add video plane
var planeGeometry = new THREE.PlaneGeometry( 1080, 720,1,1 );
var plane = new THREE.Mesh( planeGeometry, videoMaterial );
scene.add( plane );
plane.z = 0;
plane.scale.x = plane.scale.y = 1.45;
//add stats
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
//init renderer
renderer = new THREE.WebGLRenderer();
renderer.setSize( 800, 600 );
document.body.appendChild( renderer.domElement );
//POST PROCESSING
//Create Shader Passes
renderPass = new THREE.RenderPass( scene, camera );
badTVPass = new THREE.ShaderPass( THREE.BadTVShader );
rgbPass = new THREE.ShaderPass( THREE.RGBShiftShader );
filmPass = new THREE.ShaderPass( THREE.FilmShader );
staticPass = new THREE.ShaderPass( THREE.StaticShader );
copyPass = new THREE.ShaderPass( THREE.CopyShader );
//set shader uniforms
filmPass.uniforms[ "grayscale" ].value = 0;
//Init DAT GUI control panel
badTVParams = {
mute:true,
show: true,
distortion: 3.0,
distortion2: 1.0,
speed: 0.3,
rollSpeed: 0.1
}
staticParams = {
show: true,
amount:0.5,
size2:4.0
}
rgbParams = {
show: true,
amount: 0.005,
angle: 0.0,
}
filmParams = {
show: true,
count: 800,
sIntensity: 0.9,
nIntensity: 0.4
}
gui = new dat.GUI();
gui.add(badTVParams, 'mute').onChange(onToggleMute);
var f1 = gui.addFolder('Bad TV');
f1.add(badTVParams, 'show').onChange(onToggleShaders);
f1.add(badTVParams, 'distortion', 0.1, 20).step(0.1).listen().name("Thick Distort").onChange(onParamsChange);
f1.add(badTVParams, 'distortion2', 0.1, 20).step(0.1).listen().name("Fine Distort").onChange(onParamsChange);
f1.add(badTVParams, 'speed', 0.0,1.0).step(0.01).listen().name("Distort Speed").onChange(onParamsChange);
f1.add(badTVParams, 'rollSpeed', 0.0,1.0).step(0.01).listen().name("Roll Speed").onChange(onParamsChange);
f1.open();
var f2 = gui.addFolder('RGB Shift');
f2.add(rgbParams, 'show').onChange(onToggleShaders);
f2.add(rgbParams, 'amount', 0.0, 0.1).listen().onChange(onParamsChange);
f2.add(rgbParams, 'angle', 0.0, 2.0).listen().onChange(onParamsChange);
f2.open();
var f4 = gui.addFolder('Static');
f4.add(staticParams, 'show').onChange(onToggleShaders);
f4.add(staticParams, 'amount', 0.0,1.0).step(0.01).listen().onChange(onParamsChange);
f4.add(staticParams, 'size2', 1.0,100.0).step(1.0).onChange(onParamsChange);
f4.open();
var f3 = gui.addFolder('Scanlines');
f3.add(filmParams, 'show').onChange(onToggleShaders);
f3.add(filmParams, 'count', 50, 1000).onChange(onParamsChange);
f3.add(filmParams, 'sIntensity', 0.0, 2.0).step(0.1).onChange(onParamsChange);
f3.add(filmParams, 'nIntensity', 0.0, 2.0).step(0.1).onChange(onParamsChange);
f3.open();
gui.close();
onToggleShaders();
onToggleMute();
onParamsChange();
window.addEventListener('resize', onResize, false);
renderer.domElement.addEventListener('click', randomizeParams, false);
onResize();
randomizeParams();
}
function onParamsChange() {
//copy gui params into shader uniforms
badTVPass.uniforms[ "distortion" ].value = badTVParams.distortion;
badTVPass.uniforms[ "distortion2" ].value = badTVParams.distortion2;
badTVPass.uniforms[ "speed" ].value = badTVParams.speed;
badTVPass.uniforms[ "rollSpeed" ].value = badTVParams.rollSpeed;
staticPass.uniforms[ "amount" ].value = staticParams.amount;
staticPass.uniforms[ "size" ].value = staticParams.size2;
rgbPass.uniforms[ "angle" ].value = rgbParams.angle*Math.PI;
rgbPass.uniforms[ "amount" ].value = rgbParams.amount;
filmPass.uniforms[ "sCount" ].value = filmParams.count;
filmPass.uniforms[ "sIntensity" ].value = filmParams.sIntensity;
filmPass.uniforms[ "nIntensity" ].value = filmParams.nIntensity;
}
function randomizeParams() {
if (Math.random() <0.2){
//you fixed it!
badTVParams.distortion = 0.1;
badTVParams.distortion2 =0.1;
badTVParams.speed =0;
badTVParams.rollSpeed =0;
rgbParams.angle = 0;
rgbParams.amount = 0;
staticParams.amount = 0;
}else{
badTVParams.distortion = Math.random()*10+0.1;
badTVParams.distortion2 =Math.random()*10+0.1;
badTVParams.speed =Math.random()*.4;
badTVParams.rollSpeed =Math.random()*.2;
rgbParams.angle = Math.random()*2;
rgbParams.amount = Math.random()*0.03;
staticParams.amount = Math.random()*0.2;
}
onParamsChange();
}
function onToggleMute(){
video.volume = badTVParams.mute ? 0 : 1;
}
function onToggleShaders(){
//Add Shader Passes to Composer
//order is important
composer = new THREE.EffectComposer( renderer);
composer.addPass( renderPass );
if (filmParams.show){
composer.addPass( filmPass );
}
if (badTVParams.show){
composer.addPass( badTVPass );
}
if (rgbParams.show){
composer.addPass( rgbPass );
}
if (staticParams.show){
composer.addPass( staticPass );
}
composer.addPass( copyPass );
copyPass.renderToScreen = true;
}
function animate() {
shaderTime += 0.1;
badTVPass.uniforms[ 'time' ].value = shaderTime;
filmPass.uniforms[ 'time' ].value = shaderTime;
staticPass.uniforms[ 'time' ].value = shaderTime;
if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
if ( videoTexture ) videoTexture.needsUpdate = true;
}
requestAnimationFrame( animate );
composer.render( 0.1);
stats.update();
}
function onResize() {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
</script>
Using video or image is the same process, you can use Planegeometry and TextureLoader to place an image instead of a video like this :
YourGroup = new THREE.Group();
var YourImage = new THREE.TextureLoader();
YourImage.load( 'folder/to_image.png', function ( texture ) {
var geometry = new THREE.PlaneGeometry( width, height );
var material = new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
});
var mesh = new THREE.Mesh( geometry, material );
YourGroup.add( mesh );
});
scene.add( YourGroup );
Note:
Here i created a group with everything to put inside (a planegeometry with BasicMaterial to apply my loaded image to Plane, and create a mesh from these two.
I put a Png instead of jpeg because of transparency for Mesh.
I add my group to scene.

Three.js Restrict the mouse movement to Scene only

I am working on the cube example from three.js (webgl_interactive_cubes_gpu.html). I realized that events goes to the entire html page. I mean i can rotate, zoom in or zoom out, even if the mouse pointer is not inside the scene..
I google a little bit and found some answers (Allow mouse control of three.js scene only when mouse is over canvas) but they do not work for me..Below is my code...
var container, stats;
var camera, controls, scene, renderer;
var pickingData = [], pickingTexture, pickingScene;
var objects = [];
var highlightBox;
var mouse = new THREE.Vector2();
var offset = new THREE.Vector3( 10, 10, 10 );
init();
animate();
function init() {
container = document.getElementById( "container" );
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
//camera.translateZ( -500 );
controls = new THREE.TrackballControls(camera);
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 4;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
scene = new THREE.Scene();
pickingScene = new THREE.Scene();
pickingTexture = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
pickingTexture.minFilter = THREE.LinearFilter;
pickingTexture.generateMipmaps = false;
scene.add( new THREE.AmbientLight( 0x555555 ));
var light = new THREE.SpotLight( 0xffffff, 1.5 );
light.position.set( 0, 500, 2000 );
scene.add( light );
var geometry = new THREE.Geometry(),
pickingGeometry = new THREE.Geometry(),
pickingMaterial = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } ),
defaultMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors} );
function applyVertexColors( g, c ) {
g.faces.forEach( function( f ) {
var n = ( f instanceof THREE.Face3 ) ? 3 : 4;
for( var j = 0; j < n; j ++ ) {
f.vertexColors[ j ] = c;
}
} );
}
var geom = new THREE.BoxGeometry(0.005, 0.005, 0.005 );
var color = new THREE.Color();
var matrix = new THREE.Matrix4();
var quaternion = new THREE.Quaternion();
var coord="219_163_189;130_173_179;161_113_231;
var splitCoord=coord.split(";");
var coordColr="0_255_255;255_255_0;0_0_255;0_255_0;255_255_0;
var splitCoordColor=coordColr.split(";");
for ( var i = 0; i < splitCoord.length; i++ ) {
var position = new THREE.Vector3();
var xyz=splitCoord[i].split("_");
var col=splitCoordColor[i].split("_");
position.x = xyz[0];
position.y = xyz[1];
position.z = xyz[2];
var rotation = new THREE.Euler();
rotation.x = 0
rotation.y = 0;
rotation.z = 0;
var scale = new THREE.Vector3();
scale.x = 200 + 100;
scale.y = 200 + 100;
scale.z = 200 + 100;
quaternion.setFromEuler(rotation, false );
matrix.compose( position, quaternion, scale);
col[0]=col[0]/255;
col[1]=col[1]/255;
col[2]=col[2]/255;
applyVertexColors(geom, color.setRGB(col[0], col[1], col[2]));
geometry.merge(geom, matrix);
// give the geom's vertices a color corresponding to the "id"
applyVertexColors( geom, color.setHex( i ) );
pickingGeometry.merge( geom, matrix );
pickingData[ i ] = {
position: position,
rotation: rotation,
scale: scale
};
}
var drawnObject = new THREE.Mesh( geometry, defaultMaterial );
scene.add(drawnObject);
pickingScene.add( new THREE.Mesh( pickingGeometry, pickingMaterial ) );
highlightBox = new THREE.Mesh(
new THREE.BoxGeometry( 0.01, 0.01, 0.01 ),
new THREE.MeshLambertMaterial( { color: 0xffff00 }
) );
scene.add( highlightBox );
renderer = new THREE.WebGLRenderer( );
//renderer.setClearColor( 0xffffff );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(800, 800);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
//renderer.domElement.addEventListener('mousemove', onMouseMove );
}
function onMouseMove( e ) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function pick() {
//render the picking scene off-screen
renderer.render( pickingScene, camera, pickingTexture );
//create buffer for reading single pixel
var pixelBuffer = new Uint8Array( 4 );
//read the pixel under the mouse from the texture
renderer.readRenderTargetPixels(pickingTexture, mouse.x, pickingTexture.height - mouse.y, 1, 1, pixelBuffer);
//interpret the pixel as an ID
var id = ( pixelBuffer[0] << 16 ) | ( pixelBuffer[1] << 8 ) | ( pixelBuffer[2] );
var data = pickingData[ id ];
if (data) {
//move our highlightBox so that it surrounds the picked object
if ( data.position && data.rotation && data.scale ){
highlightBox.position.copy( data.position );
highlightBox.rotation.copy( data.rotation );
highlightBox.scale.copy( data.scale ).add( offset );
highlightBox.visible = true;
}
} else {
highlightBox.visible = false;
}
}
function render() {
controls.update();
pick();
renderer.render( scene, camera );
}
any help is greatly appreciated..
Thanks
You can pass in the canvas as an argument to the TrackballsControls constructor.
var controls = new THREE.TrackballControls(camera, renderer.domElement);
That should solve the problem.
EDIT: included a working example,
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, 400 / 300, 1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(400, 300);
document.body.appendChild(renderer.domElement);
var controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 4;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
var render = function() {
requestAnimationFrame(render);
controls.update();
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
could not get your code to run at all so..

Resources