Box Clipping in three JS - three.js

Here I'm trying to achieve box clipping where a model will be loaded inside the box. Where I can able to clip at any side of the box and view inside the model.
Here I came across some example of forming a transparent layer above the model where I can able to clip in all the sides to view the model. Here's the fiddle https://jsfiddle.net/qz0Lye3b/
var camera, scene, renderer, controls;
var isTransformRoom = false,
roomIndex = 1,
tween;
var planeConstant = {
constant: 5.1
};
var clipPlanes = [
new THREE.Plane(new THREE.Vector3(1, 0, 0), -20.1),
new THREE.Plane(new THREE.Vector3(0, -1, 0), 5.1),
new THREE.Plane(new THREE.Vector3(0, 0, -1), -5.1)
];
var clipPlanes1 = [
new THREE.Plane(new THREE.Vector3(1, 0, 0), -5.1),
new THREE.Plane(new THREE.Vector3(0, 1, 0), -5.1),
new THREE.Plane(new THREE.Vector3(0, 0, -1), -5.1)
];
init();
render();
var btn1 = document.getElementById("btn1");
var btn2 = document.getElementById("btn2");
btn1.onclick = function() { // show white box
if (roomIndex == 1) {
return
};
isTransformRoom = true;
planeConstant = {
constant: 5.1
};
tween = new TWEEN.Tween(planeConstant);
tween.easing(TWEEN.Easing.Quadratic.Out);
tween.to({
constant: -5.1
}, 500);
tween.start();
};
btn2.onclick = function() { // show red box
if (roomIndex == 2) {
return
};
isTransformRoom = true;
planeConstant = {
constant: 5.1
};
tween = new TWEEN.Tween(planeConstant);
tween.easing(TWEEN.Easing.Quadratic.Out);
tween.to({
constant: -5.1
}, 500);
tween.start();
};
function init() {
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.localClippingEnabled = true;
document.body.appendChild(renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 200);
camera.position.set(0, 0, 20);
controls = new THREE.OrbitControls(camera, renderer.domElement);
var light = new THREE.HemisphereLight(0xffffff, 0x080808, 1);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff));
var pointLight = new THREE.PointLight(0xffffff, 0.4);
pointLight.position.set(20, 20, 20);
scene.add(pointLight)
var geometry = new THREE.BoxGeometry(10, 10, 10);
var material = new THREE.MeshStandardMaterial({
color: new THREE.Color(0xffffff),
side: THREE.DoubleSide,
clippingPlanes: clipPlanes,
clipIntersection: true
});
var whiteBox = new THREE.Mesh(geometry, material);
scene.add(whiteBox);
var geometry1 = new THREE.BoxGeometry(6, 6, 6);
var material1 = new THREE.MeshStandardMaterial({
color: new THREE.Color(0xff0000),
side: THREE.DoubleSide,
clippingPlanes: clipPlanes1,
clipIntersection: true
});
var redBox = new THREE.Mesh(geometry1, material1);
scene.add(redBox);
};
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
controls.update();
if (isTransformRoom) {
TWEEN.update();
if (roomIndex == 1) {
clipPlanes[1].constant = planeConstant.constant;
clipPlanes1[1].constant = -planeConstant.constant;
if (clipPlanes[1].constant <= -5.1) {
isTransformRoom = false;
roomIndex = 2
}
} else {
clipPlanes[1].constant = -planeConstant.constant;
clipPlanes1[1].constant = planeConstant.constant;
if (clipPlanes[1].constant >= 5.1) {
isTransformRoom = false;
roomIndex = 1
}
}
}
}

Related

Three.js all texture are white

I've changed the version of my three.js because i wanted to use projector but now all my texture went white. I can't find what is wrong with it. I'm not getting any error in the console, which makes me a bit lost.
I was using r122.
Any body know what is happening ?
most of the code here comes from a code pen :
https://codepen.io/yitliu/pen/bJoQLw
//----------VARIABLES----------
const dpi = window.devicePixelRatio;
const theCanvas = document.getElementById('canvas');
var h = window.innerHeight,
w = window.innerWidth;
aspectRatio = w / h,
fieldOfView = 25,
nearPlane = .1,
farPlane = 1000;
container = document.getElementById('container');
var dae, scene, camera, renderer;
var Colors = {
cyan: 0x248079,
brown: 0xA98F78,
brownDark: 0x9A6169,
green: 0x65BB61,
greenLight: 0xABD66A,
blue: 0x6BC6FF
};
function init() {
//----------SCENE----------
scene = new THREE.Scene();
//----------CAMERA----------
camera = new THREE.PerspectiveCamera(
fieldOfView,
aspectRatio,
nearPlane,
farPlane);
//----------RENDER----------
renderer = new THREE.WebGLRenderer({ canvas: canvas, alpha: true, antialias: true });
renderer.setSize(w * dpi, h * dpi);
theCanvas.style.width = `${w}px`;
theCanvas.style.height = `${h}px`;
renderer.shadowMapEnabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
camera.position.set(-5, 6, 8);
camera.lookAt(new THREE.Vector3(0, 0, 0));
//---------LIGHT---------
var light = new THREE.AmbientLight(0xffffff, .5);
var shadowLight = new THREE.DirectionalLight(0xffffff, .5);
shadowLight.position.set(200, 200, 200);
shadowLight.castShadow = true;
var backLight = new THREE.DirectionalLight(0xffffff, .2);
backLight.position.set(-100, 200, 50);
backLight.castShadow = true;
scene.add(backLight);
scene.add(light);
scene.add(shadowLight);
//---------CONTROLS---------
const controls = new THREE.OrbitControls(camera, renderer.domElement);
//---------GEOMETRY---------
var geometry_left = new THREE.CubeGeometry(2, .2, 4);
var material_grass = new THREE.MeshLambertMaterial({ color: Colors.greenLight });
var ground_left = new THREE.Mesh(geometry_left, material_grass);
ground_left.position.set(-1, 0.1, 0);
ground_left.receiveShadow = true;
scene.add(ground_left);
var geometry_bot = new THREE.CubeGeometry(4, .2, 1);
var material_grass = new THREE.MeshLambertMaterial({ color: Colors.greenLight });
var ground_bot = new THREE.Mesh(geometry_bot, material_grass);
ground_bot.position.set(0, 0.1, 2);
ground_bot.receiveShadow = true;
scene.add(ground_bot);
var geometry_top = new THREE.CubeGeometry(4, .2, 1);
var material_grass = new THREE.MeshLambertMaterial({ color: Colors.greenLight });
var ground_top = new THREE.Mesh(geometry_top, material_grass);
ground_top.position.set(0, 0.1, -2);
ground_top.receiveShadow = true;
scene.add(ground_top);
var geometry_river = new THREE.CubeGeometry(1, .1, 4);
var material_river = new THREE.MeshLambertMaterial({ color: Colors.blue });
var river = new THREE.Mesh(geometry_river, material_river);
river.position.set(.5, .1, 0);
river.receiveShadow = true;
scene.add(river);
var geometry_bed = new THREE.CubeGeometry(1, .05, 4);
var bed = new THREE.Mesh(geometry_bed, material_grass);
bed.position.set(.5, .025, 0);
scene.add(bed);
var geometry_right = new THREE.CubeGeometry(1, .2, 4);
var ground_right = new THREE.Mesh(geometry_right, material_grass);
ground_right.position.set(1.5, 0.1, 0);
ground_right.receiveShadow = true;
scene.add(ground_right);
var tree = function (x, z) {
this.x = x;
this.z = z;
var material_trunk = new THREE.MeshLambertMaterial({ color: Colors.brownDark });
var geometry_trunk = new THREE.CubeGeometry(.15, .15, .15);
var trunk = new THREE.Mesh(geometry_trunk, material_trunk);
trunk.position.set(this.x, .275, this.z);
trunk.castShadow = true;
trunk.receiveShadow = true;
scene.add(trunk);
var geometry_leaves = new THREE.CubeGeometry(.25, .4, .25);
var material_leaves = new THREE.MeshLambertMaterial({ color: Colors.green });
var leaves = new THREE.Mesh(geometry_leaves, material_leaves);
leaves.position.set(this.x, .2 + .15 + .4 / 2, this.z);
leaves.castShadow = true;
scene.add(leaves);
}
tree(-1.5, -1.5);
//tree(-1.25,.75);
tree(-.25, -.85);
tree(0.4, 2);
//tree(1.25,-2);
tree(1.75, .35);
var material_wood = new THREE.MeshLambertMaterial({ color: Colors.brown });
var geometry_block = new THREE.CubeGeometry(1.3, .02, .6);
var block = new THREE.Mesh(geometry_block, material_wood);
block.position.set(.5, .21, .2);
block.castShadow = true;
block.receiveShadow = true;
scene.add(block);
//---------CAR---------
var loader = new THREE.ColladaLoader();
loader.load('offroadcar.dae', function (collada) {
dae = collada.scene;
dae.scale.x = dae.scale.y = dae.scale.z = 0.1;
dae.position.set(-1, .2, 0);
dae.updateMatrix();
//customizeShadow(dae, .25)
scene.add(dae);
dae.castShadow = true;
dae.receiveShadow = true;
})
}// end of init
//---------STARTING---------
init();
animate();
//---------LISTENERS---------
theCanvas.addEventListener('click', function (evt) {
clickInfo.userHasClicked = true;
clickInfo.x = evt.clientX - theCanvas.offsetLeft;
clickInfo.y = evt.clientY - theCanvas.offsetTop;
}, false);
//---------METHODS---------
function animate() {
renderer.render(scene, camera);
requestAnimationFrame(function () { animate(); });
}

I need to use the data from first picture to draw cylinder,put two cylinders point B is not coincide(like second picture)

**I need to use the data from first picture to draw cylinder,put two cylinders point B is not coincide(like second picture) **
var geometry = new THREE.CylinderGeometry(10, 10,151.02648774304458, 20, 1, false);
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(1,75.5,1);
scene.add(mesh);
var material1 = new THREE.MeshBasicMaterial({ color: 0xff0000 });
var geometry1 = new THREE.CylinderGeometry(10, 10,158.8741640418605, 20, 1, false);
var mesh1 = new THREE.Mesh(geometry1, material1);
mesh1.position.set(-30,217,32.5);
mesh1.rotation.set(2,151,2);
scene.add(mesh1);
You have to add the red cylinder to a Group. Set the position in that way, that the bottom of the cylinder is at (0, 0, 0). Set the position of the group in that way, that it's origin is at the top of the black cylinder.
Finally you have to rotate the group:
let height = 151.02648774304458;
let height1 = 158.8741640418605;
var geometry = new THREE.CylinderGeometry(10, 10, height, 20, 1, false);
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(1, 75.5, 1);
scene.add(mesh);
var material1 = new THREE.MeshBasicMaterial({ color: 0xff0000 });
var geometry1 = new THREE.CylinderGeometry(10, 10, height1, 20, 1, false);
var mesh1 = new THREE.Mesh(geometry1, material1);
mesh1.position.set(0, height1/2, 0);
group = new THREE.Group();
group.position.set(mesh.position.x, mesh.position.y + height/2, mesh.position.z);
group.add(mesh1);
group.rotation.set(...);
scene.add(group);
(function onLoad() {
var container, camera, scene, renderer, orbitControls;
init();
animate();
function init() {
container = document.getElementById('container');
renderer = new THREE.WebGLRenderer({
canvas: my_canvas,
antialias: true,
alpha: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
//container.appendChild(renderer.domElement);
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(0, 200, -400);
camera.lookAt( 0, 0, 0 );
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
scene.add(camera);
window.onresize = function() {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
orbitControls = new THREE.OrbitControls(camera, container);
createModel();
}
var group;
function createModel() {
var material = new THREE.MeshPhongMaterial({color:'#ff0000'});
var material1 = new THREE.MeshPhongMaterial({color:'#000000'});
let height = 151.02648774304458;
let height1 = 158.8741640418605;
var geometry = new THREE.CylinderGeometry(10, 10, height, 20, 1, false);
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(1, 75.5, 1);
scene.add(mesh);
var material1 = new THREE.MeshBasicMaterial({ color: 0xff0000 });
var geometry1 = new THREE.CylinderGeometry(10, 10, height1, 20, 1, false);
var mesh1 = new THREE.Mesh(geometry1, material1);
mesh1.position.set(0, height1/2, 0);
group = new THREE.Group();
group.position.set(mesh.position.x, mesh.position.y + height/2, mesh.position.z);
group.add(mesh1);
//group.rotation.set(2, 151, 2);
scene.add(group);
}
var rotate = 0.0;
function animate() {
group.rotation.set(0, 0, rotate);
rotate += 0.01;
requestAnimationFrame(animate);
orbitControls.update();
render();
}
function render() {
renderer.render(scene, camera);
}
})();
<script src="https://cdn.jsdelivr.net/npm/three#0.115/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.115/examples/js/controls/OrbitControls.js"></script>
<div id="container"><canvas id="my_canvas"> </canvas></div>
To set a specific rotation by a specific vector, I recommend to set the rotation by a .setRotationFromQuaternion.
The Quaternion defines how to rotate from the upwards direction (0, 1, 0) to the target direction. The Target direction is the vector form the joint to the endpoint of the upper cylinder (-62-1, 283-151, 61-1):
For instance:
let upVector = new THREE.Vector3(0, 1, 0);
let targetVector = new THREE.Vector3(-62 - 1, 283 - height, 61 - 1);
let quaternion = new THREE.Quaternion().setFromUnitVectors(
upVector, targetVector.normalize());
group.setRotationFromQuaternion(quaternion)

Three js enabling shadow render slow

I am loading a building model to the scene using GLTFLoader and apply some texture, also Adding two PointLight source with shadow enabled. I am using self shadow for the building, that is the building itself should create shadow from light source.
But when I load the page, I am having some performance issue withe page, the frame rate is too slow on status and entire system behave hang.
But if disable the shadow everything work as expected. Is this expected or I can improve it on coding.
Here is the working fiddle
http://jsfiddle.net/n9eg3kox/
var camera, scene, renderer, stats;
var mesh;
var controls;
var BuildingObj;
var OutFloor;
var enableShadow = true; // if I make it false the code work fine
var pointLight2, pointLight3;
function init() {
var webglEl = document.getElementById('webgl');
if (!Detector.webgl) {
Detector.addGetWebGLMessage(webglEl);
alert("WebGL no Support");
return;
}
THREE.ImageUtils.crossOrigin = '';
renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
renderer.setPixelRatio(window.devicePixelRatio * 1.5);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.physicallyCorrectLights = true;
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMap.enabled = enableShadow;
renderer.toneMapping = THREE.ReinhardToneMapping;
webglEl.appendChild(renderer.domElement);
renderer.setClearColor(0x555555, 1);
var width = window.innerWidth, height = window.innerHeight;
camera = new THREE.PerspectiveCamera(45, width / height, 0.01, 2000);
camera.position.x = 0;
camera.position.y = 4;
camera.position.z = 30;
scene = new THREE.Scene();
var axesHelper = new THREE.AxesHelper(100);
scene.add(axesHelper);
var intensity = 5;
var distance = 40;
var decay = 1.0;
pointLight2 = new THREE.PointLight(0xFFFFFF, intensity);
pointLight2.add(new THREE.Mesh(new THREE.SphereBufferGeometry(3, 16, 16), new THREE.MeshPhongMaterial({ color: 0xfffdfb, emissive: 0xfffdfb, emissiveIntensity: 100 })));
pointLight2.position.set(-60, 80, 40);
pointLight2.castShadow = enableShadow;
pointLight2.visible = true;
pointLight2.shadow.mapSize.width = 1024;
pointLight2.shadow.mapSize.height = 1024;
scene.add(pointLight2);
pointLight3 = new THREE.PointLight(0xFFFFFF, intensity);
pointLight3.add(new THREE.Mesh(new THREE.SphereBufferGeometry(3, 16, 16), new THREE.MeshPhongMaterial({ color: 0xfffdfb, emissive: 0xfffdfb, emissiveIntensity: 100 })));
pointLight3.position.set(60, 80, 40);
pointLight3.castShadow = enableShadow;
pointLight3.shadow.mapSize.width = 1024;
pointLight3.shadow.mapSize.height = 1024;
pointLight3.visible = true;
scene.add(pointLight3);
//var light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 21 );
//scene.add( light );
controls = new THREE.OrbitControls(camera, webglEl);
stats = new Stats();
webglEl.appendChild(stats.dom);
loadObject();
animate();
}
function animate() {
controls.update();
stats.update();
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
function loadObject() {
var loader = new THREE.GLTFLoader();
loader.load(
//'./Model/GLTF/test.glb',
'./test/test.glb',
function (gltf) {
gltf.scene.traverse(function (node) {
if (node.isGroup) {
if (node.name === "Building") {
BuildingObj = node;
} else if (node.name === "Cube") {
OutFloor = node;
}
}
});
scene.add(OutFloor);
scene.add(BuildingObj);
applyMaterialToObject();
},
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
function (error) {
console.log('An error happened---' + error);
}
);
}
function applyMaterialToObject(object) {
for (var i = 0; i < BuildingObj.children.length; i++) {
var obj = BuildingObj.children[i];
var material = new THREE.MeshStandardMaterial({ roughness: 0.8, metalness: 0.3, bumpScale: - 0.05, color: 0xffffff, });
loadTexturesToMaterial(BuildingObj.children[i], material, "./test/brick.jpg", "./test/brick_b.jpg", "./test/brick_r.jpg", 25, 70, Math.PI / 2);
}
for (var i = 0; i < OutFloor.children.length; i++) {
var obj = OutFloor.children[i];
var material = new THREE.MeshStandardMaterial({ roughness: 0.5, metalness: 0.8, bumpScale: - 0.05, color: 0xffffff });
loadTexturesToMaterial(obj, material, "./test/tile2.jpg", "./test/tile2_b.jpg", "./test/tile2_r.jpg", 35, 100, Math.PI / 2);
}
}
function loadTexturesToMaterial(obj, material, map_img, bumpMap_img, roughnessMap_img, v_count, h_count, rotation) {
obj.receiveShadow = enableShadow;
obj.castShadow = enableShadow;
obj.material = material;
obj.material.side = THREE.DoubleSide;
var textureLoader = new THREE.TextureLoader();
textureLoader.load(map_img, function (map) {
map.wrapS = THREE.RepeatWrapping;
map.wrapT = THREE.RepeatWrapping;
map.rotation = rotation;
map.repeat.set(v_count, h_count);
obj.material.map = map;
obj.material.needsUpdate = true;
});
textureLoader.load(bumpMap_img, function (map) {
map.wrapS = THREE.RepeatWrapping;
map.wrapT = THREE.RepeatWrapping;
map.rotation = rotation;
map.repeat.set(v_count, h_count);
obj.material.bumpMap = map;
obj.material.needsUpdate = true;
});
textureLoader.load(roughnessMap_img, function (map) {
map.wrapS = THREE.RepeatWrapping;
map.wrapT = THREE.RepeatWrapping;
map.rotation = rotation;
map.repeat.set(v_count, h_count);
obj.material.roughnessMap = map;
obj.material.needsUpdate = true;
});
}
Note: I have created the model using blender.
Edit: Texture and model link
https://github.com/SourceCodeZone/3D

How to rotate a 3D object on axis

Here I'm looking to rotate only the object using camera instead of rotating the whole camera around the object. First, the center origin point of the object remains the same where it works properly, but once I pan the object the center of the origin differs and rotates the camera around the object.
https://jsfiddle.net/1ax8hf07/
var scene, renderer, camera;
var cube;
var controls;
var containerWidth = window.innerWidth,
containerHeight = window.innerHeight;
var isDragging = false;
var previousMousePosition = {
x: 0,
y: 0
};
init();
animate();
function init() {
configureRenderer();
scene = new THREE.Scene();
configureCube();
configureCamera();
configureLight();
configureControls();
}
function configureRenderer() {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.onresize = function () {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
if (controls)
controls.handleResize();
}
}
function configureCube() {
var cubeGeometry = new THREE.BoxGeometry(20, 20, 20);
var cubeMaterial = new THREE.MeshLambertMaterial({
color: 0xff0000
});
cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.set(50, 0, 0);
scene.add(cube);
cubeGeometry.center();
}
function configureCamera() {
camera = new THREE.PerspectiveCamera(45, containerWidth / containerHeight, 1, 1000);
camera.position.set(0, 160, 400);
camera.lookAt(scene);
}
function configureLight() {
pointLight = new THREE.PointLight(0xffffff, 1.0, 100000);
pointLight.position.set(0, 300, 200);
scene.add(pointLight);
}
function configureControls() {
controls = new THREE.TrackballControls(camera, renderer.domElement);
// controls.enabled = false;
controls.update();
controls.object.up.set(0, 0, 1);
}
function animate() {
controls.update();
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
I don't know if there is a simpler method but personally when i need to move or rotate something i do it by my self.
In your case i suggest to track the mouse movement and add the rotation to the transformation matrix.
This is how it will be on your code
var scene, renderer, camera;
var cube;
var controls;
var containerWidth = window.innerWidth,
containerHeight = window.innerHeight;
var isDragging = false;
var previousMousePosition = {
x: 0,
y: 0
};
init();
animate();
function init() {
configureRenderer();
scene = new THREE.Scene();
configureCube();
configureCamera();
configureLight();
configureControls();
}
function configureRenderer() {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.onresize = function() {
renderer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
if (controls) controls.handleResize();
};
}
function configureCube() {
var cubeGeometry = new THREE.BoxGeometry(20, 20, 20);
var cubeMaterial = new THREE.MeshLambertMaterial({
color: 0xff0000
});
cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
cube.position.set(50, 0, 0);
scene.add(cube);
cubeGeometry.center();
}
function configureCamera() {
camera = new THREE.PerspectiveCamera(
45,
containerWidth / containerHeight,
1,
1000
);
camera.position.set(0, 160, 400);
camera.lookAt(scene);
}
function configureLight() {
pointLight = new THREE.PointLight(0xffffff, 1.0, 100000);
pointLight.position.set(0, 300, 200);
scene.add(pointLight);
}
function configureControls() {
controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.enabled = false;
controls.update();
document.addEventListener("mousedown", onMouseDown, false);
document.addEventListener("mouseup", onMouseUp, false);
}
function onMouseDown() {
previousMousePosition.x = event.clientX;
previousMousePosition.y = event.clientY;
document.addEventListener("mousemove", onMouseMove, false);
}
function onMouseMove(event) {
var rotationX = event.clientX - previousMousePosition.x;
var rotationY = event.clientY - previousMousePosition.y;
previousMousePosition.x = event.clientX;
previousMousePosition.y = event.clientY;
if (rotationX || rotationY) {
rotateAroundWorldAxis(cube, new THREE.Vector3(0, 1, 0), rotationX * 0.01);
rotateAroundWorldAxis(cube, new THREE.Vector3(1, 0, 0), rotationY * 0.01);
}
}
function onMouseUp() {
document.removeEventListener("mousemove", onMouseMove, false);
}
function rotateAroundWorldAxis(object, axis, radians) {
var rotationMatrix = new THREE.Matrix4();
rotationMatrix.makeRotationAxis(axis.normalize(), radians);
rotationMatrix.multiply(object.matrix);
object.matrix = rotationMatrix;
object.rotation.setFromRotationMatrix(object.matrix);
}
function animate() {
controls.update();
requestAnimationFrame(animate);
renderer.render(scene, camera);
}

Custom plane does not cast/ receive shadows in THREE js

I am trying to create a box (a wall) using six planes. I have created planes but shadows are not there.
This is how I create custom planes.
function createWall(vertices) {
var geometry = new THREE.Geometry(), i;
for (i = 0; i < vertices.length; i = i + 1) {
geometry.vertices.push(vertices[i]);
}
geometry.faces.push(new THREE.Face3(0, 1, 2));
geometry.faces.push(new THREE.Face3(0, 2, 3));
geometry.computeVertexNormals();
geometry.computeFaceNormals();
var material = new THREE.MeshStandardMaterial({
emissive: 0x708090,
emissiveIntensity: 1,
side: THREE.DoubleSide,
color: 0xD3D3D3
});
var mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
Here is the complete code.
var camera, scene, renderer;
function addFloor() {
var material = new THREE.MeshStandardMaterial({
roughness: 0.8,
color: 0x696969,
metalness: 0.2,
bumpScale: 0.0005
});
var geometry = new THREE.PlaneBufferGeometry(2000, 2000);
var mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
mesh.rotation.x = -Math.PI / 2.0;
scene.add(mesh);
}
function createWall(vertices) {
var geometry = new THREE.Geometry(), i;
for (i = 0; i < vertices.length; i = i + 1) {
geometry.vertices.push(vertices[i]);
}
geometry.faces.push(new THREE.Face3(0, 1, 2));
geometry.faces.push(new THREE.Face3(0, 2, 3));
geometry.computeVertexNormals();
geometry.computeFaceNormals();
var material = new THREE.MeshStandardMaterial({
emissive: 0x708090,
emissiveIntensity: 1,
side: THREE.DoubleSide,
color: 0xD3D3D3
});
var mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function addBulb(location) {
var geometry = new THREE.SphereGeometry(2, 20, 20);
var light = new THREE.PointLight(0xffffff, 1, 100, 2);
var material = new THREE.MeshStandardMaterial({
emissive: 0xffffee,
emissiveIntensity: 1,
color: 0x000000
});
light.add(new THREE.Mesh(geometry, material));
light.position.set(location.x, location.y, location.z);
light.shadow.camera.near = 0.0001;
light.castShadow = true;
//light.shadow.darkness = 0.5;
//light.shadow.camera.vsible = true;
return light;
}
function addWalls() {
var wall1 = createWall([
new THREE.Vector3(0, 0, 0), //vertex0
new THREE.Vector3(200, 0, 0), //1
new THREE.Vector3(200, 100, 0), //2
new THREE.Vector3(0, 100, 0) //3
]);
var wall2 = createWall([
new THREE.Vector3(0, 0, 5), //vertex0
new THREE.Vector3(200, 0, 5), //1
new THREE.Vector3(200, 100, 5), //2
new THREE.Vector3(0, 100, 5) //3
]);
scene.add(wall1);
scene.add(wall2);
}
function addCamera() {
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(50, 100, 300);
scene.add(camera);
}
function init() {
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMap.renderSingleSided = false;
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xffffff, 1);
document.body.appendChild(renderer.domElement);
addCamera();
addFloor();
addWalls();
scene.add(addBulb({x: 100, y: 50, z: 25}));
var ambientLight = new THREE.AmbientLight(0x999999, 0.6);
scene.add(ambientLight);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
}
function animate() {
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
init();
animate();
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
I may have done something wrong while creating custom plane. I do not understand what is wrong here.
UPDATED:
renderer.shadowMap.renderSingleSided = false;
It seems shadows are working but lighting has strange square effect.
Here I have tried BoxGeometry which has little depth as suggested in three-js-plane-doesnt-cast-shadow ,
As I noted this occurs only for small values for depth. (depth < 1)
var camera, scene, renderer;
function addFloor() {
var material = new THREE.MeshStandardMaterial({
roughness: 0.9,
color: 0xffffff,
metalness: 0.1,
bumpScale: 0.0005
});
var geometry = new THREE.PlaneBufferGeometry(2000, 2000);
var mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
mesh.rotation.x = -Math.PI / 2.0;
scene.add(mesh);
}
function createWall(location) {
var geometry = new THREE.BoxGeometry(200, 100, 0.1);
geometry.translate((location.x1 + location.x2) / 2, 150 / 2, location.z);
var material = new THREE.MeshStandardMaterial({
emissive: 0x708090,
emissiveIntensity: 1,
side: THREE.DoubleSide,
color: 0xD3D3D3,
roughness: 0.9,
metalness: 0.1
});
var mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function addBulb(options) {
var geometry = new THREE.SphereGeometry(2, 20, 20);
var light = new THREE.PointLight(options.color, 1, 500, 2);
var material = new THREE.MeshStandardMaterial({
emissive: options.color,
emissiveIntensity: 1,
color: options.color
});
light.add(new THREE.Mesh(geometry, material));
light.position.set(options.x, options.y, options.z);
light.shadow.camera.near = 0.0001;
light.castShadow = true;
light.shadow.darkness = 0.5;
light.shadow.camera.vsible = true;
return light;
}
function addWalls() {
var wall1 = createWall({ x1: 0, x2: 200, z: 0});
var wall2 = createWall({ x1: 0, x2: 200, z: 5});
scene.add(wall1);
//scene.add(wall2);
}
function addCamera() {
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(100, 100, 300);
scene.add(camera);
}
function init() {
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMap.renderSingleSided = false;
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xffffff, 1);
document.body.appendChild(renderer.domElement);
addCamera();
addFloor();
addWalls();
scene.add(addBulb({x: 0, y: 100, z: 25, color: 0xff0000 }));
scene.add(addBulb({x: 100, y: 100, z: 25, color: 0x00ff00 }));
scene.add(addBulb({x: 200, y: 100, z: 25, color: 0x0000ff }));
var ambientLight = new THREE.AmbientLight(0x999999, 0.6);
scene.add(ambientLight);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
}
function animate() {
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
init();
animate();
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
You're facing Z fighting. Since the thickness of the wall is so small, the 2 faces are nearly touching each other, so they cast shadows on each other.
You can either remove the casting/receiving of shadows on the wall or, better, increase the z value in the geometry, like so:
var geometry = new THREE.BoxGeometry(200, 100, 1);
Also, since you changed to a box from a plane, the line side: THREE.DoubleSide, in the wall material is no longer needed. In fact, it's part of the self-shadowing problem. Changing those two lines should solve your problem.
Here's a working Fiddle.

Resources