Hello i just want to show an object with three js without webcam and marker juste a blank background and the object
I try to pick some part of code from the damage helmet example but nothing work :/ I just want a simple thing.
For now i have this code:
function start(){
var renderer = new THREE.WebGLRenderer({
antialias : true,
alpha: true
});
//renderer.setClearColor(new THREE.Color('lightgrey'), 0)
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild( renderer.domElement );
// array of functions for the rendering loop
var onRenderFcts = [];
// init scene
var scene = new THREE.Scene();
// Create a camera
var camera = new THREE.Camera();
scene.add(camera);
// Create a light
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 0, 1);
scene.add(light);
var loader = new THREE.OBJLoader();
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( "3d_models/OBJ/ano/ano.mtl", function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load("3d_models/OBJ/ano/ano.obj", function ( object ) {
object.rotation.set(-Math.PI/2,0,0);
console.log(object.children[0])
scene.add( object );
});
},
function ( xhr ) {
console.log( 'OBJ ' + ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
function ( error ) {
console.log(error);
});
}
You're not positioning your camera, so it might be inside your objects.
Also without seeing the rest of your code.. it's not obvious where you are calling "start()" from ?
Here's a example of code that's work i found it on three js example and I modify some line of code to simplify it:
var renderer;
var clock = new THREE.Clock();
var mixers = [];
var onRenderFcts = [];
var camera2, scene2;
init2();
function init2() {
var container, stats;
container = document.createElement( 'div' );
document.body.appendChild( container );
camera2 = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera2.position.z = 250;
scene2 = new THREE.Scene();
var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
scene2.add( ambientLight );
var pointLight = new THREE.PointLight( 0xffffff, 0.8 );
camera2.add( pointLight );
scene2.add( camera2 );
var loader = new THREE.OBJLoader();
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( "3d_models/OBJ/ano/ano.mtl", function( materials ) {
materials.preload();
console.log(materials);
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load("3d_models/OBJ/ano/ano.obj", function ( object ) {
console.log(object.children[0])
scene2.add( object );
onRenderFcts.push(function(){
object.rotation.y += 0.03;
})
});
},
function ( xhr ) {
console.log( 'OBJ ' + ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
function ( error ) {
console.log(error);
});
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
}
onRenderFcts.push(function(){
renderer.render( scene2, camera2 );
})
// run the rendering loop
var lastTimeMsec= null
requestAnimationFrame(function animate(nowMsec){
// keep looping
requestAnimationFrame( animate );
if ( mixers.length > 0 ) {
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() );
}
}
// measure time
lastTimeMsec = lastTimeMsec || nowMsec-1000/60
var deltaMsec = Math.min(200, nowMsec - lastTimeMsec)
lastTimeMsec = nowMsec
// call each update function
onRenderFcts.forEach(function(onRenderFct){
onRenderFct(deltaMsec/1000, nowMsec/1000)
})
})
Related
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.
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.
I have downloaded the following model from TF3DM : http://tf3dm.com/3d-model/sprite-bottle-91563.html
And i'm trying to display it in a scene with threeJS.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var light = new THREE.DirectionalLight( 0xffffff, 1 );
light.position.set( 10, 10, 10 );
scene.add( light );
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 );
var mtlLoader = new THREE.MTLLoader();
// mtlLoader.setBaseUrl( '' );
mtlLoader.setPath( './' );
var url = "SpriteBottle.mtl";
mtlLoader.load( url, function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( './' );
objLoader.load( 'SpriteBottle.obj', function ( object ) {
object.position.y = - 95;
scene.add( object );
}, function() {}, function() {} );
});
camera.position.z = 5;
var render = function () {
requestAnimationFrame( render );
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
With this code, nothing appears but the cube. I sometimes manage to display the bottle but the texture is not set.
EDIT: I have also tried to convert the obj file to JSON using the python script, and then applied the texture on it, it displays but not at the right spot.
What am i doing wrong ?
I have exported two models from Blender, each to a separate json file using the latest three.js exporter, then I tried to load it and add to my test app. I have set all the required parameters to enable the shadow casting, but still the shadows are not appearing at all.. Any ideas as to what may be wrong here?
var renderer, camera, scene, controls;
/////// JSON DATA ////
var static_objects = [
{
name:"ground",
pos:{
x:-45.0, y:-1, z:14.0
},
size:20,
model_url: "obj.moon_ground.json",
},
{
name:"cylinder",
pos:{
x:-20.0, y:5.0, z:0.0
},
size:10,
model_url:"obj.cylinder.json",
}
];
var ObjectsToLoad = static_objects.length || 0;
///////////////////////////
function initRenderer( width, height){
console.log(" - renderer");
if(Detector.webgl){
renderer = new THREE.WebGLRenderer({antialias:true});
}else{
renderer = THREE.CanvasRenderer();
}
//// container ////
container = document.createElement( 'div' );
document.body.appendChild( container );
/////////////////////
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( width, height );
renderer.shadowMap.enabled = true;
renderer.shadowMapSoft = true;
renderer.setClearColor( 0x142639, 1 );
///////////////////////
container.appendChild( renderer.domElement );
}
function initCamera(width, height){
console.log(" - camera");
camera = new THREE.PerspectiveCamera(55, width/height, 1, 100 );
camera.position.set(17.05217, 8.07079, 0.0);
camera.lookAt( static_objects[1].pos );
controls = new THREE.OrbitControls( camera );
}
function InitLights(){
console.log(" - lights");
var ambient_light = new THREE.AmbientLight( 0xD0D0D0, 0.25);
scene.add(ambient_light);
var spot_light = new THREE.SpotLight( 0xC1C1C1 );
spot_light.position.set( -1.8, 38, 2.5 );
spot_light.castShadow = true;
spot_light.shadowDarkness = 3.5;
spot_light.shadowCameraNear = 0.1;
spot_light.shadowCameraFar = 41;
spot_light.shadowCameraFov = 45;
spot_light.shadowMapWidth = 1024;
spot_light.shadowMapHeight = 1024;
spot_light.target.position.set( static_objects[1].pos.x, static_objects[1].pos.y, static_objects[1].pos.z );
scene.add(spot_light);
var c_helper = new THREE.CameraHelper( spot_light.shadow.camera );
scene.add( c_helper );
}
function initScene(){
console.log(" - scene");
scene = new THREE.Scene();
}
function loadObjects(){
console.log(" - StaticObjects");
var loader = new THREE.JSONLoader();
for(var o = 0; o < static_objects.length; o++ ){
var o_data = static_objects[o];
loader.load( o_data.model_url, initObject(o) );
}
}
function initObject(o_id){
console.log("loading object "+ o_id );
return function(geometry, materials) {
geometry.translate( 0.0, 0.0, -2.0 );
mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
mesh.scale.set( static_objects[o_id].size, static_objects[o_id].size, static_objects[o_id].size ) ;
mesh.position.set( static_objects[o_id].pos.x, static_objects[o_id].pos.y, static_objects[o_id].pos.z );
mesh.traverse( function( node ) { if ( node instanceof THREE.Mesh ) { node.castShadow = true; node.receiveShadow = true; } } );
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.rotation.y = -Math.PI/2;
ObjectsToLoad--;
scene.add(mesh);
}
}
function initAll(){
console.log(" initializing:");
initRenderer(window.innerWidth / 2, window.innerHeight / 2);
initScene();
initCamera(window.innerWidth / 2, window.innerHeight / 2);
InitLights();
loadObjects();
animate();
}
function animate(){
window.requestAnimationFrame( animate );
if(ObjectsToLoad === 0){
render_all();
}
}
function render_all(){
//var timer = Date.now() * 0.001;
controls.update();
renderer.render(scene, camera);
}
initAll();
it appears that the spot_light had to be moved a little bit up along the Y axis. now it works perfectly.
I need to do very simple 3d model viewer with rotation and so on..
I have simple code, everything works fine, but when I add these two rows with OrbitControls then there'S only blank page:
controls = new THREE.OrbitControls( camera );
controls.addEventListener( 'change', render );
Whole code:
<body>
<script src="js/OrbitControls.js"></script>
<script src="js/three.min.js"></script>
<script src="js/OBJLoader.js"></script>
<div id="ahoj" style="width:1000px; height:700px">
</div>
<script>
var container;
var camera, controls, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = 1000 / 2;
var windowHalfY = 700 / 2;
init();
animate();
function init() {
container = document.getElementById('ahoj');
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 75, 1000 / 700, 1, 2000 );
camera.position.z = 200;
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x000 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 );
scene.add( directionalLight );
// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
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 loader = new THREE.ImageLoader( manager );
loader.load( 'textures/mapa1.png', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
// model
var loader = new THREE.OBJLoader( manager );
loader.load( 'obj/Immortal.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
//child.material.map = texture;
}
} );
object.scale.set(3,3,3);
object.position.y = 0;
object.position.z = 0;
object.position.x = 0;
scene.add( object );
}, onProgress, onError );
//
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
//controls = new THREE.OrbitControls( camera );
//controls.addEventListener( 'change', render );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( 1000, 700 );
container.appendChild( renderer.domElement )
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = 1000 / 2;
windowHalfY = 700 / 2;
camera.aspect = 1000 / 700;
camera.updateProjectionMatrix();
renderer.setSize( 1000, 700 );
}
function animate() {
render();
requestAnimationFrame( animate );
controls.update();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
Any idea where is the problem?
I tried some few tutorials, but no one helped me..
You need to include three.min.js first:
<script src="js/three.min.js"></script>
<script src="js/OrbitControls.js"></script>
<script src="js/OBJLoader.js"></script>