Merging line geometries in three.js - three.js

I'm having a problem merging multiple lines into one geometry. Line geometry was built using the CubicBezierCurve3:
const curve = new CubicBezierCurve3(
point1,
point2,
point3,
point4
);
const geometry = new BufferGeometry();
const points = curve.getPoints(16);
geometry.setFromPoints(points);
Then these two geometries were merged using BufferGeometryUtils:
const line = new Line(BufferGeometryUtils.mergeBufferGeometries([line1Geometry, line2Geometry], false), new LineBasicMaterial())
As a result, the desired figure turned out, but an extra line came from somewhere that connects them.
line
If I change the order when merging, then I get a different line. I don't understand how to solve this problem.
line2

You can't use THREE.Line for this use case since it represents a continuous line. So if you merge two separate lines into one, there will be no gap that separates both.
You have to use THREE.LineSegments however that means you have to pre-process your curve geometries. Try it like in the following live example:
let camera, scene, renderer;
init();
render();
function init() {
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.set(0, 0.5, 2);
scene = new THREE.Scene();
const curve1 = new THREE.CubicBezierCurve3(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(2, 0, 0),
new THREE.Vector3(1, 1, 0),
new THREE.Vector3(2, 1, 0)
);
const geometry1 = createGeometry(curve1.getPoints(32));
const curve2 = new THREE.CubicBezierCurve3(
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(-2, 0, 0),
new THREE.Vector3(-1, 1, 0),
new THREE.Vector3(-2, 1, 0)
);
const geometry2 = createGeometry(curve2.getPoints(32));
const geometry = THREE.BufferGeometryUtils.mergeBufferGeometries([geometry1, geometry2]);
const material = new THREE.LineBasicMaterial();
mesh = new THREE.LineSegments(geometry, material);
scene.add(mesh);
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function render() {
renderer.render(scene, camera);
}
function createGeometry(points) {
const vertices = [];
const segments = points.length - 1;
for (let i = 0; i < segments; i++) {
const point1 = points[i];
const point2 = points[i + 1];
vertices.push(point1.x, point1.y, point1.z);
vertices.push(point2.x, point2.y, point2.z);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
return geometry;
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.145/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.145/examples/js/utils/BufferGeometryUtils.js"></script>

Related

Rotate the camera around an object using the Buttons in ThreeJS?

I have STL model loaded in my scene.
I want to show Left, Right, Top, Bottom and Front, Back side of my model by rotating camera.
I want exactly like Reference this. Free movement of camera and set different views. another reference ThreeJS Reference Example but this code is not Open Source.
var camera, scene, renderer;
var geometry, material, mesh;
let controls;
init();
animate();
function init() {
let aspectRatio = window.innerWidth / window.innerHeight;
let frustumSize = 2;
camera = new THREE.OrthographicCamera(frustumSize * aspectRatio / -2,
frustumSize * aspectRatio / 2,
frustumSize / 2, frustumSize / -2,
-50,
50);
camera.position.z = 1;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xD3D3D3);
document.body.appendChild(renderer.domElement);
let frontlight = new THREE.DirectionalLight(0x808080, .3);
scene.add(frontlight);
ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
createControls();
loadSTL();
}
function createControls() {
controls = new THREE.TrackballControls(camera, renderer.domElement);
}
window.addEventListener('keydown', function(event) {
switch (event.keyCode) {
case 49: //Top View
// setView(new THREE.Vector3(0, 0, 1));
setView(new THREE.Vector3(0, 0, 1), new THREE.Vector3(0, 0, 0));
break;
case 50: //Bottom View
setView(new THREE.Vector3(0, 0, -1), new THREE.Vector3(Math.PI, 0, 0));
break;
case 51: //Left View
setView(new THREE.Vector3(-1, 0, 0), new THREE.Vector3(Math.PI / 2, (-Math.PI / 2), 0));
break;
case 52: //Right View
setView(new THREE.Vector3(1, 0, 0), new THREE.Vector3(Math.PI / 2, Math.PI / 2, 0));
break;
case 53: //Front View
setView(new THREE.Vector3(0, 1, 0), new THREE.Vector3(-(Math.PI / 2), 0, Math.PI));
break;
case 54: //Back View
setView(new THREE.Vector3(0, -1, 0), new THREE.Vector3(Math.PI / 2, 0, 0));
break;
}
});
function setView(offSetFactor, axisAngle) {
const offsetUnit = camera.position.length();
const offSet = new THREE.Vector3(offsetUnit * offSetFactor.x,
offsetUnit * offSetFactor.y,
offsetUnit * offSetFactor.z);
const center = new THREE.Vector3();
const finishPos = center.add(offSet);
const euler = new THREE.Euler(axisAngle.x, axisAngle.y, axisAngle.z);
const finishQuaterion = new THREE.Quaternion().copy(camera.quaternion).setFromEuler(euler);
/* let boundingBox = new THREE.Box3().setFromObject(scene);
let boxCenter = new THREE.Vector3();
boundingBox.getCenter(boxCenter); */
const duration = 400;
const start = performance.now();
const maxAlpha = 1;
function loop() {
const now = performance.now();
const delta = now - start;
const alpha = Math.min(delta / duration, maxAlpha);
camera.position.lerp(finishPos, alpha);
controls.update();
camera.quaternion.slerp(finishQuaterion, alpha);
camera.up.set(0, 1, 0);
controls.update();
if (alpha !== maxAlpha)
return requestAnimationFrame(loop)
/* camera.lookAt(boxCenter);
controls.target.set(boxCenter.x,boxCenter.y,boxCenter.z);
*/
}
loop();
}
function loadSTL() {
let material = new THREE.MeshPhongMaterial({
color: 0xffdead,
side: THREE.DoubleSide,
});
var stlLoader = new THREE.STLLoader();
stlLoader.load('https://cdn.glitch.global/3c40c6ea-d629-4a1b-8129-bd041944a124/monkey.stl?v=1659713089046',
function(geometry) {
var material = new THREE.MeshPhongMaterial({
color: 0xff5533
});
var meshSTL = new THREE.Mesh(geometry, material);
scene.add(meshSTL);
fitToScreen(scene, camera, controls);
});
}
function fitToScreen(group, camera, controls) {
let boundingBox = new THREE.Box3().setFromObject(group);
let distance = boundingBox.min.distanceTo(boundingBox.max) * 0.1;
let boxCenter = new THREE.Vector3();
boundingBox.getCenter(boxCenter);
camera.position.set(boxCenter.x, boxCenter.y, distance);
camera.lookAt(boxCenter);
controls.target.set(boxCenter.x, boxCenter.y, boxCenter.z);
camera.updateProjectionMatrix();
}
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
Here is JSFiddle link what I implemented so far use 1 to 6 keys to change Views. In am not able to set left, right and front view properly.
I am using Trackball controls and orthographic camera this is my need I cannot change camera and controls. There is one library Gizmo Library but this library work specifically for orbit controls
I want to rotate camera by clicking on button. I know once I know how to rotate camera properly I can hook up UI with this but just FYI. I will keep Six buttons to set this views.
Here is what I tried So far

Simple square using BufferGeometry

I used to have a custom square in my project that was made by using THREE.Geometry. Now after the latest update of three.js, Geometry was completely deleted and I have to get my code to work with BufferGeometry instead.
I'm kind of confused how I have to change the code to make it work. I don't really get the vertices part now. I used to have 4 vertices made of Vector3's and two faces.
So it looked like that:
let v1 = new THREE.Vector3(...,...,...)
let v2 = new THREE.Vector3(...,...,...)
let v3 = new THREE.Vector3(...,...,...)
let v4 = new THREE.Vector3(...,...,...)
obj.vertices.push(v1)
obj.vertices.push(v2)
obj.vertices.push(v3)
obj.vertices.push(v4)
let face1 = new THREE.Face3(0, 1, 2)
let face2 = new THREE.Face3(2, 3, 0)
obj.faces.push(face1)
obj.faces.push(face2)
I've read the documentation on that on the THREE website but I don't really understand how I change that to make it work with BufferGeometry. Any tips would be appreciated.
Thanks
Try it like so:
let camera, scene, renderer;
init();
render();
function init() {
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.z = 2;
scene = new THREE.Scene();
const geometry = new THREE.BufferGeometry();
const vertices = [
-1, -1, 0,
1, -1, 0,
1, 1, 0,
-1, 1, 0
];
const indices = [
0, 1, 2, // first triangle
2, 3, 0 // second triangle
];
geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
geometry.setIndex(indices);
const material = new THREE.MeshBasicMaterial();
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
}
function render() {
renderer.render(scene, camera);
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.126.1/build/three.js"></script>

Connecting two components in Three.js

I would like to build something that allows the connection of two components, kind of like a guitar cable will plug into an amp from a guitar. So I want to connect to one point, and then drag the connection to a second point and have there be some natural hang in the rope. I made this example from a previous SO question (Three.js rope / cable effect - animating thick lines), but I can't seem to get the calculation right. So the question would be, how would I be able to make a function with this signature:
function drawSpline(startPoint, endPoint, ropeLength) {
// returns a new THREE.Line object with a natural curvature for "slack" in the rope between the two points
}
This is what I have so far:
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
scene.add(camera);
camera.position.z = 10;
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
animate();
const RADIUS = 1;
const SEGMENTS = 16;
const RINGS = 16;
const sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCC0000
});
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(
RADIUS,
SEGMENTS,
RINGS),
sphereMaterial);
sphere.position.z = 0;
const pointLight =
new THREE.PointLight(0xFFFFFF);
// set its position
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
// add to the scene
scene.add(pointLight);
const shiftRatio = 7.5;
scene.add(drawSpline({x: 0, y: -3, z: 0}, {x: 6, y: 1, z: 0}, 'blue'));
function drawSpline(beginning, end, clr){
let ySign = Math.sign((end.y + beginning.y) / 2)
let appliedRatio = shiftRatio;
let midVector = new THREE.Vector3( (end.x + beginning.x) / 8, (end.y+beginning.y)/2, (end.z+beginning.z)/ 2 )
let positionVector = new THREE.Vector3(0,end.y-beginning.y,end.z-beginning.z)
let orthogVector = new THREE.Vector3(0,positionVector.z,-positionVector.y).normalize()
var curve = new THREE.CatmullRomCurve3( [
new THREE.Vector3( beginning.x, beginning.y, beginning.z ),
midVector.clone().addScaledVector(orthogVector,ySign*appliedRatio),
new THREE.Vector3( end.x, end.y, end.z ),
]);
var points = curve.getPoints( 20 );
console.log(points);
var geometry = (new THREE.BufferGeometry()).setFromPoints( points );
var material = new THREE.LineBasicMaterial( { color : clr } );
// Create the final object to add to the scene
var curveObject = new THREE.Line( geometry, material );
return curveObject;
}

Verifying if a point is inside a cube in three.js

I have created a cube as:
var cubeGeometry = new THREE.BoxGeometry( 1, 1, 1 );
var cubeMaterial = new THREE.MeshLambertMaterial( { color:
0xffff00,wireframe: true } );
var cube = new THREE.Mesh( cubeGeometry, cubeMaterial );
cube.position.x = p.x;
cube.position.y = p.y;
cube.position.z = p.z;
scene.add(cube);
p is a input point to my function. So this code creates a cube at position p and adds it to the scene.
How can I check that some point,say A, lies inside this cube? I couldn't find any helper function like containsPoint etc for Three.Mesh. I may do some additional checks to verify, but I am looking for a Three.js function.
You can create THREE.Box3() instance, using its .setFromObject() the cube as the parameter, then call .containsPoint(), passing the point you want to check as the parameter to this method:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(2, 5, 10);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
scene.add(new THREE.GridHelper(10, 10));
var cube = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshBasicMaterial({
color: "aqua",
wireframe: true
}));
cube.position.set(0, 1, 0);
scene.add(cube);
var pointA = new THREE.Vector3(0, 1, 0);
var pointB = new THREE.Vector3(2, 1, 0);
point(pointA, 0x00ff00);
point(pointB, "yellow");
function point(point, color) {
p = new THREE.Mesh(new THREE.SphereGeometry(0.25, 4, 2), new THREE.MeshBasicMaterial({
color: color
}));
p.position.copy(point);
scene.add(p);
}
var bb = new THREE.Box3(); // for re-use
bb.setFromObject(cube);
console.log(bb);
console.log(bb.containsPoint(pointA), bb.containsPoint(pointB));
render();
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
cube.updateMatrixWorld(); //Make sure the object matrix is current with the position/rotation/scaling of the object...
var localPt = cube.worldToLocal(yourPoint.clone()); //Transform the point from world space into the objects space
if(Math.abs(localPt.x)<=0.5&&Math.abs(localPt.y)<=0.5&&Math.abs(localPt.z)<=0.5)
console.log("Point is inside!"); //Check if all the axis are within the size of the cube.. if your cube sizes arent 1,1,1, you'll have to adjust these checks to be half of width/height/depth..
Something like that?
#prisoner849
Your solution doesn't work if the box is rotated.
Here's an illustration of the problem. I render both solutions and you can see where the Box3 version breaks with the rotated cube, whereas the analytical once works.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(2, 5, 10);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
scene.add(new THREE.GridHelper(10, 10));
var boxDimensions = new THREE.Vector3(2,2,2);
var cube = new THREE.Mesh(new THREE.BoxGeometry(boxDimensions.x,boxDimensions.y,boxDimensions.z), new THREE.MeshBasicMaterial({
color: "aqua",
wireframe: true
}));
cube.position.set(0, 1, 0);
cube.rotation.y = Math.PI*0.25;
scene.add(cube);
var pointA = new THREE.Vector3(0.95, 0.95, 0.95);
var pointC = new THREE.Vector3(-0.65, 0.65, -0.65);
var pa = point(pointA, 0x00ff00);
var pc = point(pointC, 0x00ff00);
function point(point, color) {
p = new THREE.Mesh(new THREE.SphereGeometry(0.25, 4, 2), new THREE.MeshBasicMaterial({
color: color
}));
p.position.copy(point);
scene.add(p);
return p;
}
var bb = new THREE.Box3(); // for re-use
bb.setFromObject(cube);
console.log(bb);
function correctPointInBox(pt,cube,boxDim){
cube.updateMatrixWorld(); //Make sure the object matrix is current with the position/rotation/scaling of the object...
var localPt = cube.worldToLocal(pt.clone()); //Transform the point from world space into the objects space
if(Math.abs(localPt.x)<=boxDim.x*0.5&&Math.abs(localPt.y)<=boxDim.y*0.5&&Math.abs(localPt.z)<=boxDim.z*0.5)
return true;
else
return false;
}
render();
function render() {
pa.position.x = Math.sin(performance.now()*0.001)*2;
pc.position.z = Math.cos(performance.now()*0.001)*2;
if(bb.containsPoint(pa.position))
pa.material.color.set("red")
else
pa.material.color.set("green")
if(correctPointInBox(pc.position,cube,boxDimensions))
pc.material.color.set("red")
else
pc.material.color.set("green")
requestAnimationFrame(render);
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

Three.js - Create new mesh from certain faces/vertices of another mesh

I´ve been several days struggling with a particular Three.js issue, and I cannot find any way to do it. This is my case:
1) I have a floating mesh, formed by several triangled faces. This mesh is created from the geometry returned by a loader, after obtaining its vertices and faces using getAttribute('position'): How to smooth mesh triangles in STL loaded BufferGeometry
2) What I want to do now is to "project" the bottom face agains the floor.
3) Later, with this new face added, create the resulting mesh of filling the space between the 3 vertices of both faces.
I already have troubles in step 2... To create a new face I´m supossed to have its 3 vertices already added to geometry.vertices. I did it, cloning the original face vertices. I use geometry.vertices.push() results to know their new indexes, and later I use that indexes (-1) to finally create the new face. But its shape is weird, also the positions and the size. I think I´m not getting the world/scene/vector position equivalence theory right :P
I tried applying this, with no luck:
How to get the absolute position of a vertex in three.js?
Converting World coordinates to Screen coordinates in Three.js using Projection
http://barkofthebyte.azurewebsites.net/post/2014/05/05/three-js-projecting-mouse-clicks-to-a-3d-scene-how-to-do-it-and-how-it-works
I discovered that if I directly clone the full original face and simply add it to the mesh, the face is added but in the same position, so I cannot then change its vertices to place it on the floor (or at least without modifying the original face vertices!). I mean, I can change their x, y, z properties, but they are in a very small measure that doesn´t match the original mesh dimensions.
Could someone help me get this concept right?
EDIT: source code
// Create geometry
var geo = new THREE.Geometry();
var geofaces = [];
var geovertices = [];
original_geometry.updateMatrixWorld();
for(var index in original_geometry.faces){
// Get original face vertexNormals to know its 3 vertices
var face = original_geometry[index];
var vertexNormals = face.vertexNormals;
// Create 3 new vertices, add it to the array and then create a new face using the vertices indexes
var vertexIndexes = [null, null, null];
for (var i = 0, l = vertexNormals.length; i < l; i++) {
var vectorClone = vertexNormals[i].clone();
vectorClone.applyMatrix4( original_geometry.matrixWorld );
//vectorClone.unproject(camera); // JUST TESTING
//vectorClone.normalize(); // JUST TESTING
var vector = new THREE.Vector3(vectorClone.x, vectorClone.z, vectorClone.y)
//vector.normalize(); // JUST TESTING
//vector.project(camera); // JUST TESTING
//vector.unproject(camera); // JUST TESTING
vertexIndexes[i] = geovertices.push( vector ) - 1;
}
var newFace = new THREE.Face3( vertexIndexes[0], vertexIndexes[1], vertexIndexes[2] );
geofaces.push(newFace);
}
// Assign filled arrays to the geometry
geo.faces = geofaces;
geo.vertices = geovertices;
geo.mergeVertices();
geo.computeVertexNormals();
geo.computeFaceNormals();
// Create a new mesh with resulting geometry and add it to scene (in this case, to the original mesh to keep the positions)
new_mesh = new THREE.Mesh( geo, new THREE.MeshFaceMaterial(material) ); // material is defined elsewhere
new_mesh.position.set(0, -100, 0);
original_mesh.add( new_mesh );
I created a fully operational JSFiddle with the case to try things and see the problem more clear. With this STL (smaller than my local example) I cannot even see the badly cloned faces added to the scene.. Maybe they are too small or out of focus.
Take a look to the calculateProjectedMesh() function, here is where I tried to clone and place the bottom faces (already detected because they have a different materialIndex):
JSFiddle: https://jsfiddle.net/tc39sgo1/
var container;
var stlPath = 'https://dl.dropboxusercontent.com/s/p1xp4lhy4wxmf19/Handle_Tab_floating.STL';
var camera, controls, scene, renderer, model;
var mouseX = 0,
mouseY = 0;
var test = true;
var meshPlane = null, meshStl = null, meshCube = null, meshHang = null;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
/*THREE.FrontSide = 0;
THREE.BackSide = 1;
THREE.DoubleSide = 2;*/
var materials = [];
materials.push( new THREE.MeshPhongMaterial({color : 0x00FF00, side:0, shading: THREE.FlatShading, transparent: true, opacity: 0.9, overdraw : true, wireframe: false}) );
materials.push( new THREE.MeshPhongMaterial({color : 0xFF0000, transparent: true, opacity: 0.8, side:0, shading: THREE.FlatShading, overdraw : true, metal: false, wireframe: false}) );
materials.push( new THREE.MeshPhongMaterial({color : 0x0000FF, side:2, shading: THREE.FlatShading, overdraw : true, metal: false, wireframe: false}) );
var lineMaterial = new THREE.LineBasicMaterial({ color: 0x0000ff, transparent: true, opacity: 0.05 });
init();
animate();
function webglAvailable() {
try {
var canvas = document.createElement('canvas');
return !!(window.WebGLRenderingContext && (
canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
} catch (e) {
return false;
}
}
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(25, window.innerWidth / window.innerHeight, 0.1, 100000000);
camera.position.x = 1500;
camera.position.z = -2000;
camera.position.y = 1000;
controls = new THREE.OrbitControls(camera);
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight(0x101030); //0x101030
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xffffff, 2);
directionalLight.position.set(0, 3, 0).normalize();
scene.add(directionalLight);
var directionalLight = new THREE.DirectionalLight(0xffffff, 2);
directionalLight.position.set(0, 1, -2).normalize();
scene.add(directionalLight);
if (webglAvailable()) {
renderer = new THREE.WebGLRenderer();
} else {
renderer = new THREE.CanvasRenderer();
}
renderer.setClearColor( 0xCDCDCD, 1 );
// renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousemove', onDocumentMouseMove, false);
window.addEventListener('resize', onWindowResize, false);
createPlane(500, 500);
createCube(500);
loadStl();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 2;
mouseY = (event.clientY - windowHalfY) / 2;
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}
function createPlane(width, height) {
var planegeometry = new THREE.PlaneBufferGeometry(width, height, 0, 0);
var material = new THREE.MeshLambertMaterial({
color: 0xFFFFFF,
side: THREE.DoubleSide
});
planegeometry.computeBoundingBox();
planegeometry.center();
meshPlane = new THREE.Mesh(planegeometry, material);
meshPlane.rotation.x = 90 * (Math.PI/180);
//meshPlane.position.y = -height/2;
scene.add(meshPlane);
}
function createCube(size) {
var geometry = new THREE.BoxGeometry( size, size, size );
geometry.computeFaceNormals();
geometry.mergeVertices();
geometry.computeVertexNormals();
geometry.center();
var material = new THREE.MeshPhongMaterial({
color: 0xFF0000,
opacity: 0.04,
transparent: true,
wireframe: true,
side: THREE.DoubleSide
});
meshCube = new THREE.Mesh(geometry, material);
meshCube.position.y = size/2;
scene.add(meshCube);
}
function loadStl() {
var loader = new THREE.STLLoader();
loader.load( stlPath, function ( geometry ) {
// Convert BufferGeometry to Geometry
var geometry = new THREE.Geometry().fromBufferGeometry( geometry );
geometry.computeBoundingBox();
geometry.computeVertexNormals();
geometry.center();
var faces = geometry.faces;
for(var index in faces){
var face = faces[index];
var faceNormal = face.normal;
var axis = new THREE.Vector3(0,-1,0);
var angle = Math.acos(axis.dot(faceNormal));
var angleReal = (angle / (Math.PI/180));
if(angleReal <= 70){
face.materialIndex = 1;
}
else{
face.materialIndex = 0;
}
}
geometry.computeFaceNormals();
geometry.computeVertexNormals();
meshStl = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
meshStl.position.x = 0;
meshStl.position.y = 400;
scene.add( meshStl );
// Once loaded, calculate projections mesh
calculateProjectedMesh();
});
}
function calculateProjectedMesh(){
var geometry = meshStl.geometry;
var faces = geometry.faces;
var vertices = geometry.vertices;
var geometry_projected = new THREE.Geometry();
var faces_projected = [];
var vertices_projected = [];
meshStl.updateMatrixWorld();
for(var index in faces){
var face = faces[index];
// This are the faces
if(face.materialIndex == 1){
var vertexIndexes = [face.a, face.b, face.c];
for (var i = 0, l = vertexIndexes.length; i < l; i++) {
var relatedVertice = vertices[ vertexIndexes[i] ];
var vectorClone = relatedVertice.clone();
console.warn(vectorClone);
vectorClone.applyMatrix4( meshStl.matrixWorld );
////////////////////////////////////////////////////////////////
// TEST: draw line
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(vectorClone.x, vectorClone.y, vectorClone.z));
//geometry.vertices.push(new THREE.Vector3(vectorClone.x, vectorClone.y, vectorClone.z));
geometry.vertices.push(new THREE.Vector3(vectorClone.x, meshPlane.position.y, vectorClone.z));
var line = new THREE.Line(geometry, lineMaterial);
scene.add(line);
console.log("line added");
////////////////////////////////////////////////////////////////
vectorClone.y = 0;
var vector = new THREE.Vector3(vectorClone.x, vectorClone.y, vectorClone.z);
vertexIndexes[i] = vertices_projected.push( vector ) - 1;
}
var newFace = new THREE.Face3( vertexIndexes[0], vertexIndexes[1], vertexIndexes[2] );
newFace.materialIndex = 2;
faces_projected.push(newFace);
}
}
geometry_projected.faces = faces_projected;
geometry_projected.vertices = vertices_projected;
geometry_projected.mergeVertices();
console.info(geometry_projected);
meshHang = new THREE.Mesh(geometry_projected, new THREE.MeshFaceMaterial(materials));
var newY = -(2 * meshStl.position.y) + 0;
var newY = -meshStl.position.y;
meshHang.position.set(0, newY, 0);
meshStl.add( meshHang );
}
EDIT: Finally!! I got it! To clone the original faces I must access their 3 original vertices using "a", "b" and "c" properties, which are indexes referencing Vector3 instances in the "vertices" array of the original geometry.
I cloned the 3 vertices flatting the Z position to zero, use their new indexes to create the new face and add it to the projection mesh (in blue).
I´m also adding lines as a visual union between both faces. Now I´m ready for step 3, but I think this is complex enough to close this question.
Thanks for the updateMatrixWorld clue! It was vital to achieve my goal ;)
try this
original_geometry.updateMatrixWorld();
var vertexIndexes = [null, null, null];
for (var i = 0, l = vertexNormals.length; i < l; i++) {
var position = original_geometry.geometry.vertices[i].clone();
position.applyMatrix4( original_geometry.matrixWorld );
var vector = new THREE.Vector3(position.x, position.y, position.z)
vertexIndexes[i] = geovertices.push( vector ) - 1;
}

Resources