three.js Particles closer to camera appears larger in Orthographic Camera - three.js

It seems that with OrthographicCamera, if a particle (Points) is closer to the camera it will just appear to be larger. While, for example, BoxGeometrys with same size will always be in the same size, regardless of their distances to the camera.
See the sample below, where the green & red cubes have the same size but different distances to camera, so do the two white particles:
var container, camera, controls, scene, renderer;
init();
animate();
function init() {
var container = document.getElementById('container');
camera =
new THREE.OrthographicCamera(-window.innerWidth / 2,
window.innerWidth / 2, -window.innerHeight / 2,
window.innerHeight / 2, 1, 400);
camera.position.z = 200;
controls = new THREE.OrthographicTrackballControls(camera);
controls.addEventListener('change', render);
scene = new THREE.Scene();
var light = new THREE.DirectionalLight()
light.position.set(1, 5, 10)
scene.add(light);
var light = new THREE.DirectionalLight(0xaaaaaa)
light.position.set(-10, -1, -5)
scene.add(light);
var light = new THREE.AmbientLight(0x555555)
scene.add(light);
var pGeo = new THREE.Geometry()
var pVec1 = new THREE.Vector3
var pVec2 = new THREE.Vector3
var a = 80
pGeo.vertices.push(pVec1.fromArray([-a, -a, -a]));
pGeo.vertices.push(pVec2.fromArray([a, a, a]));
scene.add(new THREE.Points(pGeo, new THREE.PointsMaterial({
size: 80
})))
var cGeo = new THREE.BoxGeometry(80, 80, 80);
var MPG1 = new THREE.MeshPhongMaterial({
color: 0xff0000
});
var cMesh1 = new THREE.Mesh(cGeo, MPG1);
cMesh1.position.set(a, -a, -a);
cMesh1.updateMatrix();
scene.add(cMesh1);
var MPG2 = new THREE.MeshPhongMaterial({
color: 0x00ff00
});
var cMesh2 = new THREE.Mesh(cGeo, MPG2);
cMesh2.position.set(-a, a, a);
cMesh2.updateMatrix();
scene.add(cMesh2);
// renderer
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
renderer.render(scene, camera)
render()
}
function animate() {
requestAnimationFrame(animate);
controls.update();
}
function render() {
renderer.render(scene, camera);
}
<script src="http://threejs.org/build/three.min.js"></script>
<script src="http://threejs.org/examples/js/controls/OrthographicTrackballControls.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Particle_Orthographic</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<div id="container"></div>
</body>
</html>
I want to know, whether there is something I missed that can make particles behave in the same way as other Geometry with OrthographicCamera.
Because I am trying to visualise some aluminum matrix, OrthographicCamera is quite necessary to demonstrate the uniform crystal structure. Also the matrix would vary from 4^3 to 100^3 in volume (and number of aluminum atoms), so the scene will sort of keep changing size, and other Geometry will make it very slow.
Thanks in advance

When using THREE.PointsMaterial, to prevent the particle size from attenuating (changing size) with distance from the camera, set
material.sizeAttenuation = false;
three.js r.72

Related

Is there a way to prevent culling a line when using an orthographic camera?

When using an orthographic camera I can't see the back side of my circle when it is angled.
It's as though the circle is being treated as a disc with a face that is blocking the view of where I expect to see the circle. Is there any way to use the orthographic camera but have not do any culling at all or at the very least not do any culling on this circle?
Do a rotate on this example to see what I'm saying:
// ------------------------------------------------
// BASIC SETUP
// ------------------------------------------------
// hard code canvas dimensions
const scale = 2;
const canvasHeight = 350 * scale;
const canvasWidth = 350 * scale;
// Create an empty scene
var scene = new THREE.Scene();
// Create a basic perspective camera
//var camera = new THREE.PerspectiveCamera( 75, canvasWidth/canvasHeight, 0.1, 1000 );
var camera = new THREE.OrthographicCamera( canvasWidth / - 2, canvasWidth / 2, canvasHeight / 2, canvasHeight / - 2, 1, 1000 );
camera.position.z = 4;
// Create a renderer with Antialiasing
var renderer = new THREE.WebGLRenderer({antialias:true});
// Configure renderer clear color
renderer.setClearColor("#C3C3C3");
// Configure renderer size
renderer.setSize(canvasWidth, canvasHeight);
// Append Renderer to DOM
document.body.appendChild( renderer.domElement );
var controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.update();
setTimeout(function() {
controls.reset();
}, 5000)
// ------------------------------------------------
// FUN STARTS HERE
// ------------------------------------------------
// Render Loop
var render = function () {
requestAnimationFrame( render );
//cube.rotation.x += 0.01;
//cube.rotation.y += 0.01;
controls.update();
// Render the scene
renderer.render(scene, camera);
// console.log(visibleWidthAtZDepth(camera,))
};
render();
function drawCircle()
{
let radius = canvasWidth / 2 - 5,
segments = 64,
material = new THREE.LineBasicMaterial( { color: 0x0000ff } ),
geometry = new THREE.CircleGeometry( radius, segments );
geometry.vertices.shift();
scene.add( new THREE.LineLoop( geometry, material ) );
}
drawCircle();
<!DOCTYPE html>
<html>
<head>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta charset="utf-8"/>
</head>
<body>
</body>
<style>
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/108/three.js"></script>
<script src="https://unpkg.com/three#0.85.0/examples/js/controls/OrbitControls.js"></script>
<script src="bolt-hole-calculator.js"></script>
</html>
Set your camera further away from the origin. You are encountering the circle intersecting the near plane, because the camera is only 4 units from the origin, and the circle radius is much larger than that.
// ------------------------------------------------
// BASIC SETUP
// ------------------------------------------------
// hard code canvas dimensions
const scale = 2;
const canvasHeight = 350 * scale;
const canvasWidth = 350 * scale;
// Create an empty scene
var scene = new THREE.Scene();
// Create a basic perspective camera
//var camera = new THREE.PerspectiveCamera( 75, canvasWidth/canvasHeight, 0.1, 1000 );
var camera = new THREE.OrthographicCamera(canvasWidth / -2, canvasWidth / 2, canvasHeight / 2, canvasHeight / -2, 1, 1000);
camera.position.z = 500;
// Create a renderer with Antialiasing
var renderer = new THREE.WebGLRenderer({
antialias: true
});
// Configure renderer clear color
renderer.setClearColor("#C3C3C3");
// Configure renderer size
renderer.setSize(canvasWidth, canvasHeight);
// Append Renderer to DOM
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.update();
setTimeout(function() {
controls.reset();
}, 5000)
// ------------------------------------------------
// FUN STARTS HERE
// ------------------------------------------------
// Render Loop
var render = function() {
requestAnimationFrame(render);
//cube.rotation.x += 0.01;
//cube.rotation.y += 0.01;
controls.update();
// Render the scene
renderer.render(scene, camera);
// console.log(visibleWidthAtZDepth(camera,))
};
render();
function drawCircle() {
let radius = canvasWidth / 2 - 5,
segments = 64,
material = new THREE.LineBasicMaterial({
color: 0x0000ff
}),
geometry = new THREE.CircleGeometry(radius, segments);
geometry.vertices.shift();
scene.add(new THREE.LineLoop(geometry, material));
}
drawCircle();
// Do a rotate on this example to see what I 'm saying:
<!DOCTYPE html>
<html>
<head>
<meta name=viewport content="width=device-width,initial-scale=1">
<meta charset="utf-8" />
</head>
<body>
</body>
<style>
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/108/three.js"></script>
<script src="https://unpkg.com/three#0.85.0/examples/js/controls/OrbitControls.js"></script>
<script src="bolt-hole-calculator.js"></script>
</html>

Annotation using three.js

I have two cubes of .obj file.The obj file is render on the browser. I want to do is as the user click on any of the cube or anywhere on the cube one prompt box display to add annotation to that place on the cube.How to do this? I am new to three.js. Anyone can help me out?
Here is my code with.obj file
<!DOCTYPE html>
<html>
<head>
<title>Mouse Picking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="three.js"></script>
<script src="Detector.js"></script>
<script src="OrbitControls.js"></script>
<script src="OBJLoader.js"></script>
<script src="MTLLoader.js"></script>
<script src="DragControls.js"></script>
<style>
body {
overflow: hidden;
margin: 0;
padding: 0;
background: hsl(0, 0%, 10%);
}
</style>
</head>
<body>
<script>
if (!Detector.webgl) {
Detector.addGetWebGLMessage();
}
var container;
var camera, controls, scene, renderer;
var lighting, ambient, keyLight, fillLight, backLight;
var BlueCube, RedCube;
var objects = [];
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
/* Camera */
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.x = 5;
camera.position.y = 3;
camera.position.z = 7;
/* Scene */
scene = new THREE.Scene();
lighting = true;
ambient = new THREE.AmbientLight(0xffffff, 2.5);
scene.add(ambient);
keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30, 100%, 75%)'), 1.0);
keyLight.position.set(-100, 0, 100);
fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240, 100%, 75%)'), 0.75);
fillLight.position.set(100, 0, 100);
backLight = new THREE.DirectionalLight(0xffffff, 1.0);
backLight.position.set(100, 0, -100).normalize();
/* Model */
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setBaseUrl('assets/');
mtlLoader.setPath('assets/');
mtlLoader.load('mouse_picking.mtl', function (materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath('assets/');
objLoader.load('mouse_picking.obj', function (object) {
scene.add( object );
objects.push( object );
});
});
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
/* Renderer */
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(new THREE.Color("hsl(0, 0%, 10%)"));
container.appendChild(renderer.domElement);
/* Controls */
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
/* Events */
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
//selected();
requestAnimationFrame(animate);
controls.update();
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
I recommend that you subdivide the geometry of the cube mesh, and then use raycasting to determine the part of the scene (specifically, the triangle in the mesh) that was clicked. Then you could add a sprite object, which is a plane that always faces the camera, to display some text.
For more information, check out the collection of examples at http://stemkoski.github.io/Three.js/index.html - they are a little outdated, but the examples "Mouse Click" and "Sprite Text Labels" might help you to get started.

Getting current geometry of animated mesh

How does one get the current geometry of an animated mesh? Say I have a mesh that's going through some animation and I want to grab a copy of the current pose and create a new mesh using it (not necessarily skinned the same way), how would I do this?
Edit: Here is a simple example. It loads one of the three.js example animations and runs it. The loaded mesh is skinnedMesh. Every time animate() is called, a copy of the mesh is made using skinnedMesh.geometry. The copy is called newMesh, and it's created with a simple red MeshBasicMaterial and offset to one side of the original.
If you run the code, you'll see that although skinnedMesh is animated, newMesh is always a copy of the untransformed geometry. If it was doing what I wanted it to do, newMesh would be in the same pose as skinnedMesh.
Clearly this particular example is very inefficient, as I could just make another copy of skinnedMesh and animate it separately. But that's not what I want to do. I want to be able to grab the state of the animated mesh at any point in time and make a copy of the pose it happens to be in at that moment.
I hope this makes everything clearer.
<!DOCTYPE html>
<html lang="en">
<head>
<title>test</title>
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r73/three.min.js"> </script>
<script>
var container;
var camera, scene, renderer, loader, clock, light;
var skinnedMesh, animation, groundMaterial, planeGeometry, mixer;
var newMesh = null;
var loaded = false;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.set(10, 0, 10);
scene = new THREE.Scene();
loader = new THREE.JSONLoader();
clock = new THREE.Clock;
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
groundMaterial = new THREE.MeshPhongMaterial({
emissive: 0x010101
});
planeGeometry = new THREE.PlaneBufferGeometry(16000, 16000);
ground = new THREE.Mesh(planeGeometry, groundMaterial);
ground.position.set(0, -5, 0);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
light = new THREE.HemisphereLight(0x777777, 0x003300, 1);
light.position.set(-80, 500, 50);
scene.add(light);
loader.load('http://threejs.org/examples/models/skinned/simple/simple.js', function(geometry, materials) {
for (var k in materials) {
materials[k].skinning = true;
}
skinnedMesh = new THREE.SkinnedMesh(geometry, new THREE.MeshFaceMaterial(materials));
skinnedMesh.scale.set(1, 1, 1);
skinnedMesh.position.y = 0;
scene.add(skinnedMesh);
mixer = new THREE.AnimationMixer(skinnedMesh);
mixer.addAction(new THREE.AnimationAction(skinnedMesh.geometry.animations[0]));
camera.lookAt(skinnedMesh.position);
loaded = true;
});
}
function animate() {
requestAnimationFrame(animate);
if (!loaded) {
return;
}
if (mixer) mixer.update(clock.getDelta());
if (newMesh) {
scene.remove(newMesh);
}
newMesh = new THREE.Mesh(skinnedMesh.geometry,
new THREE.MeshBasicMaterial({
color: 0xff0000
})
);
newMesh.position.x = skinnedMesh.position.x - 6;
scene.add(newMesh);
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
</body>
</html>
You can directly reference the geometry property of a Mesh Object which contains an array of faces.
Manipulating the geometry ad-hoc is an adventure onto itself, but the structure should be clear enough.
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: 0xffff00
});
var mesh = new THREE.Mesh(geometry, material);
console.log(mesh.geometry)
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r77/three.min.js"></script>
Bones don't affect the geometry in memory, their matrices are being applied to geometry in a shader during the rendering and that geometry can't be accessed from JS level.
You have to bake the current pose into positions and also to normals, implementation: https://stackoverflow.com/a/66404012/696535

threejs : error when deleting a Geometry or BufferGeometry in combination with a Sprite/Ortho camera

I load some objects using the ctm binary loader in Threejs r69. This returns Mesh objects using a BufferGeometry internally.
I need to remove from the scene then delete one of these Meshes, including their material/texture/geometry. According to examples and google, I should use:
scene.remove(m_mesh);
m_mesh.geometry.dispose();
m_mesh.geometry = null;
m_mesh.material.dispose();
m_mesh.material = null;
m_mesh = null;
This removes the object from the scene, but the screen goes black for a second, and I've got a GL error :
Error: WebGL: drawElements: no VBO bound to enabled vertex attrib index 2!
Looks like the above sequence (ran in my render() operation, just before drawing the scene) did not clean everything, or at least I still have references to non existing VBOs somewhere.
I've spent quite some time debugging the problem and came to the conclusion that this happens only when using an orthographic camera with a Sprite and a Perspective camera, in 2 differents scenes.
Basically, I draw a flat background using a Sprite and a dedicated scene, then my 3D scene with Meshes. If I delete a mesh from the 3D scene, then the drawing of the flat background fails.
I can't figure out why. Looks like there's a side effect of deleting a Mesh on Sprites, even if attached to different scenes.
If I comment the background drawing, then the deletion of my mesh works perfectly.
I insert below a reproduction of the problem using the standard threejs distribution. Wait about 5 seconds and you should see some GL errors on the jaavscript console.
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - geometries</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="build/three.min.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
<script>
if (!Detector.webgl) Detector.addGetWebGLMessage();
var container, stats;
var camera, scene, renderer;
frame_count = 0;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.y = 400;
// I need a second camera for my 2D sprite (used as a background)
// must use another texture so that it's not destroyed when removing the first object
cameraOrtho = new THREE.OrthographicCamera(window.innerWidth / -2,
window.innerWidth / 2,
window.innerHeight / 2,
window.innerHeight / -2,
1, 10);
cameraOrtho.position.z = 10;
cameraOrtho.position.y = 400;
sceneBackground = new THREE.Scene();
var map1 = THREE.ImageUtils.loadTexture('textures/disturb.jpg');
var material1 = new THREE.SpriteMaterial({
map: map1
});
var spriteBackground = new THREE.Sprite(material1);
spriteBackground.scale.set(window.innerWidth, window.innerHeight, 1);
spriteBackground.position.set(window.innerWidth / 2,
window.innerHeight / 2);
sceneBackground.add(spriteBackground);
scene = new THREE.Scene();
var light;
my_object = null;
scene.add(new THREE.AmbientLight(0x404040));
light = new THREE.DirectionalLight(0xffffff);
light.position.set(0, 1, 0);
scene.add(light);
var map = THREE.ImageUtils.loadTexture('textures/UV_Grid_Sm.jpg');
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;
var material = new THREE.MeshLambertMaterial({
map: map,
side: THREE.DoubleSide
});
// one object is enough to demonstrate
// can't reproduce the problem with a standard SphereGeometry
// try to convert it to a BufferGeometry
var sphereGeometry = new THREE.SphereGeometry(75, 20, 10);
var bufferGeometry = new THREE.BufferGeometry().fromGeometry(sphereGeometry);
my_object = new THREE.Mesh(bufferGeometry, material);
my_object.position.set(-400, 0, 200);
scene.add(my_object);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.autoClear = false;
renderer.autoClearDepth = false;
container.appendChild(renderer.domElement);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild(stats.domElement);
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
//
function animate() {
requestAnimationFrame(animate);
render();
stats.update();
}
function render() {
frame_count++;
var timer = Date.now() * 0.0001;
camera.position.x = Math.cos(timer) * 800;
camera.position.z = Math.sin(timer) * 800;
camera.lookAt(scene.position);
//after a few frames I want to destroy completely the object
//means remove from the scene, remove texture, material, geometry
//note that here it's a Geometry, not a BufferGeometry
//may be different
if (frame_count > 60 * 5) {
if (my_object != null) {
console.log("destroy object buffer");
scene.remove(my_object);
my_object.material.map.dispose();
my_object.material.dispose();
my_object.geometry.dispose();
my_object = null;
}
}
for (var i = 0, l = scene.children.length; i < l; i++) {
var object = scene.children[i];
object.rotation.x = timer * 5;
object.rotation.y = timer * 2.5;
}
renderer.render(sceneBackground, cameraOrtho);
renderer.clearDepth();
renderer.render(scene, camera);
}
</script>
</body>
</html>
Any hints on how to fix this issue?
Thank you,
Pascal

projectVector results not between -1 and 1 (three.js)

Note: code below updated with WestLangley's fix.
I've tried several examples of projecting from 3D to 2D. However, when I try to use projectVector the result is not between -1 and 1, and so when I multiply by my window's width/height I get extravagantly large numbers (much larger than my screen resolution). Hoping that my problem is something simple. I'm using three.min.js r56, and my inner window dimensions are 1366x418.
The code below yields a projected (x,y) of: (-7.874704599380493,-13.403168320655823) for the 3D point (1200,625,100). I know I still need to multiple this result by something like half my window height and width, but the resulting (x,y) in pixels is way off the screen.
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script type="text/javascript" src="three.min.js"></script>
</head>
<body>
<canvas id='container'></canvas>
<script>
/// GLOBAL VARIABLES
var camera, scene, renderer, container, projector;
init();
function toXYCoord (object) {
var vector = projector.projectVector(object.position.clone(), camera);
return vector;
}
/// INIT
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 20000 );
scene.add(camera);
camera.position.set(0,-1500,1500);
camera.lookAt(scene.position);
camera.updateMatrixWorld(); ///////////////// THIS IS THE FIX
projector = new THREE.Projector();
// sphere
var sphere = new THREE.Mesh( new THREE.SphereGeometry( 200, 32, 16 ), new THREE.MeshBasicMaterial({ color: 0x000000 }) );
sphere.position.set(1200,625,100);
scene.add(sphere);
container = document.getElementById('container');
renderer = new THREE.WebGLRenderer( { canvas: container, antialias:true } );
renderer.setSize( window.innerWidth, window.innerHeight );
var testVector = toXYCoord(sphere);
console.log(window.innerWidth + "x" + window.innerHeight);
console.log("Got: (" + testVector.x + "," + testVector.y + ")");
renderer.render( scene, camera );
}
</script>
</body>
</html>
The renderer does some calculations for you that are normally done in the render loop.
They are not being done in your case because you have placed your single call to render() as the last line of your script.
You need to place the following line after camera.lookAt():
camera.updateMatrixWorld();
Alternatively, you can move your
renderer.render( scene, camera );
call so it occurs before your call to your toXYCoord() function.

Resources