How can I associate my Texture with my custom geometry - three.js

I'm a very green newb attempting to understand textures and geometries. I don't know what's wrong with my code, someone have one idea....
var loader = new THREE.STLLoader();
loader.load('../Programa/imagens/imagem.stl',function (geometry){
var geometria = new THREE.Geometry().fromBufferGeometry(geometry);
geometria.computeBoundingBox();
var max = geometria.boundingBox.max,
min = geometria.boundingBox.min;
var offset = new THREE.Vector2(0 - min.x, 0 - min.y);
var range = new THREE.Vector2(max.x - min.x, max.y - min.y);
var faces = geometria.faces;
geometria.faceVertexUvs[0] = [];
for(var i = 0; i < faces.length; i++){
var v1 = geometria.vertices[faces[i].a],
...``
geometria.faceVertexUvs[0].push([
new THREE.Vector2((v1.x + offset.x)/range.x, (v1.y + offset.y)/range.y),
...
]);
}
geometria.name = "Projeto 1";
var material = new THREE.MeshPhongMaterial({
map: THREE.ImageUtils.loadTexture('../Programa/imagens/uvmapping.jpg')
});
var mesh = new THREE.Mesh(geometria, material);
geometria.uvsNeedUpdate = true;
geometria.colorsNeedUpdate = true;
mesh.scale.set(0.029, 0.029, 0.029);
scene.add(geometria);
});

Related

Three.js - previous lines become invisible after cloning

I'm attempting to duplicate an array of lines, but when I do, the previous ones somehow become dark or invisible. The previous lines can still be accessed with all their properties and I tested them also having the correct location. I shift both sets of lines, and the previous ones are not visible. Does anyone know what the problem could be?
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var lines = []
currentIndex = 0;
addLines()
duplicateLines(0)
var lineColorGradientList = [
0x100FFF,
0x0F76FF,
0x0FE0FF,
0x0FFFB3,
0x0FFF4A,
0x3DFF0F,
0xA7FF0F,
0xFFED0F
]
function addLines(){
var linesArray = []
for(i=0; i<8; ++i){
var geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3(0, 0, 2),
new THREE.Vector3(3, 0, 0));
var color = lineColorGradientList[i]
var material = new THREE.LineBasicMaterial({
color: color
});
var line = new THREE.Line( geometry, material );
line.geometry.verticesNeedUpdate = true;
line.material.needsUpdate = true
linesArray.push(line)
}
linesArray.forEach(function(line) {
line.frustumCulled = false;
scene.add(line);
});
lines.push(linesArray)
}
function duplicateLines(selectedIndex){
currentIndex += 1
var linesArray = []
for(i=0; i<8; ++i){
var line = lines[selectedIndex][i].clone()
line.geometry.verticesNeedUpdate = true;
line.material.needsUpdate = true
linesArray.push(line)
}
lines.push(linesArray)
lines[currentIndex].forEach(function(line) {
line.frustumCulled = false;
scene.add(line);
});
}
You also need to clone the geometry in order for it to work.
My corrected duplicateLinesFunction:
function duplicateLines(selectedIndex){
currentIndex += 1
var linesArray = []
for(i=0; i<8; ++i){
var line = lines[selectedIndex][i].clone()
line.geometry = lines[selectedIndex][i].geometry.clone()
line.geometry.verticesNeedUpdate = true;
line.material = lines[selectedIndex][i].material.clone()
line.material.needsUpdate = true
linesArray.push(line)
}
lines.push(linesArray)
lines[currentIndex].forEach(function(line) {
line.frustumCulled = false;
scene.add(line);
});
}

THREE js : Simplify a mesh to optimize performance

I have a mesh (image 1) and a parallelepipede, I add the intersection result of this 2 objects in a scene and I move the parallelepipede along my mesh repeating the same process to "cut" my mesh and get an exploded view of my mesh (image 2).
Problem is that the process time is more than 2 mins... I have tryed to reduce the mesh with meshmixxer but it's not enough... Does someone has another idea ?
function FirstCut() {
var scene, camera, renderer, controls;
//stl loader from https://threejs.org/examples/webgl_loader_stl.html
// cf example https://stemkoski.github.io/Three.js/CSG.html
//with obj
init();
animate();
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
camera = new THREE.PerspectiveCamera(75, 800 / 500, 1, 2000);
//camera.position.set(50, 500, 0);
camera.position.x = 50;
camera.position.y = 500;
camera.position.z = 0;
//var axeX = new THREE.Vector3(1, 0, 0);
//camera.rotateOnAxis(axeX, -1);
camera.lookAt(new THREE.Vector3(0, 500, 0));
controls = new THREE.OrbitControls(camera);
//les valeurs de min and max distance sont choisies pour que le filet ne disparaisse pas quand on le fait tourner
controls.minDistance = 0;
controls.maxDistance = 1000;
//scene
//var ambient = new THREE.AmbientLight(0x101030);
//scene.add(ambient);
//scene.add(new THREE.GridHelper(1000, 20));
//var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
//directionalLight.position.set(0, 1, 0);
//scene.add(directionalLight);
var widthH = parseInt(document.getElementById("wdthH").value) || 0; // H for Head
var widthT = parseInt(document.getElementById("wdthT").value) || 0; // T for tail
var height = parseInt(document.getElementById("hght").value) || 0; // flank
//création du pavé
var EmportePieceH = new THREE.BoxGeometry(300, 60, widthH);
var EmportePieceT = new THREE.BoxGeometry(300, 60, widthT);
var EmportePieceB = new THREE.BoxGeometry(height, 60, 520);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage et material
var EmportePieceMeshH = new THREE.Mesh(EmportePieceH, paveMaterial);
var EmportePieceMeshT = new THREE.Mesh(EmportePieceT, paveMaterial);
var paveMeshB = new THREE.Mesh(EmportePieceB, paveMaterial);
var zH = 247 - widthH / 2;
var zT = -247 + widthT / 2;
EmportePieceMeshH.position.set(0, 30, zH);
EmportePieceMeshT.position.set(0, 30, zT);
paveMeshB.position.set(-95 + height / 2, 30, 0);
var EmportePieceBSPH = new ThreeBSP(EmportePieceMeshH);
var EmportePieceBSPT = new ThreeBSP(EmportePieceMeshT);
var paveBSPB = new ThreeBSP(paveMeshB);
//scene.add(EmportePieceMeshH);
//scene.add(EmportePieceMeshT);
//scene.add(paveMeshB);
// 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('/Scan/filet_1kg500-reposition-reduit_material_0.jpg', function (image) {
texture.image = image;
texture.needsUpdate = true;
});
var width = parseInt(document.getElementById("wdth").value) || 0;
//création du pavé
var paveGeom = new THREE.BoxGeometry(250, 250, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage parallélépipède avec material
var paveMesh = new THREE.Mesh(paveGeom, paveMaterial);
var z0 = -247 + widthH;
paveMesh.position.set(0, 0, z0);
var paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
//tableau des volumes
var tabVolumes = new Array();
// model
var loader = new THREE.OBJLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit.obj', function (object) {
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
var geo = new THREE.Geometry().fromBufferGeometry(child.geometry);
var filetMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
var filetMesh = new THREE.Mesh(geo, filetMaterial);
//scene.add(filetMesh);
var newBSPH, newBSPT, newBSPB, newBSP2, newBSP1, filletBSP
var filetBSP = new ThreeBSP(filetMesh);
newBSPH = filetBSP.intersect(EmportePieceBSPH);
newBSPT = filetBSP.intersect(EmportePieceBSPT);
newBSPB = filetBSP.intersect(paveBSPB);
newBSP2 = filetBSP.subtract(EmportePieceBSPH);
newBSP1 = newBSP2.subtract(paveBSPB);
filletBSP = newBSP1.subtract(EmportePieceBSPT);
////////////////////subtract//////////////////////////////
var newFilet = new THREE.Geometry();
newFilet = filletBSP.toGeometry();
var newFilletMesh = new THREE.Mesh(newFilet, new THREE.MeshBasicMaterial({ map: texture }));
newFilletMesh.position.set(0, 0, 0);
///////////////////////////////////création morceaux découpés///////////////////////////////////////////
var HeadFillet = new THREE.Geometry();
var TailFillet = new THREE.Geometry();
var degraissageFillet = new THREE.Geometry();
HeadFillet = newBSPH.toGeometry();
TailFillet = newBSPT.toGeometry();
degraissageFillet = newBSPB.toGeometry();
/////////////////////////////////calcul des volumes des 1ers morceaux/////////////////////////////////////////
if (widthH != 0) {
tabVolumes[0] = calculateVolume2(HeadFillet);
} else { tabVolumes[0] = 0;}
if (widthT != 0) {
//alert(tabVolumes[0]);
tabVolumes[1] = calculateVolume2(TailFillet);
} else { tabVolumes[1] = 0; }
if (height != 0) {
tabVolumes[2] = calculateVolume2(degraissageFillet);
} else { tabVolumes[2] = 0; }
var ind = 3;
var HeadFilletMesh = new THREE.Mesh(HeadFillet, new THREE.MeshBasicMaterial({ map: texture }));
var TailFilletMesh = new THREE.Mesh(TailFillet, new THREE.MeshBasicMaterial({ map: texture }));
var degraissageFilletMesh = new THREE.Mesh(degraissageFillet, new THREE.MeshBasicMaterial({ map: texture }));
HeadFilletMesh.position.set(0, 0, 20);
degraissageFilletMesh.position.set(-20, 0, 0);
TailFilletMesh.position.set(0, 0, -20);
scene.add(HeadFilletMesh);
scene.add(TailFilletMesh);
scene.add(degraissageFilletMesh);
//scene.add(newFilletMesh);
var cloneHeadFilletMesh = HeadFilletMesh.clone();
var cloneTailFilletMesh = TailFilletMesh.clone();
var clonedegraissageFilletMesh = degraissageFilletMesh.clone();
var mesh_decoupe = new THREE.Object3D;
mesh_decoupe.add(cloneHeadFilletMesh);
mesh_decoupe.add(cloneTailFilletMesh);
mesh_decoupe.add(clonedegraissageFilletMesh);
if (width != 0) {
var paveGeom = new THREE.BoxGeometry(300, 300, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
var fillet2BSP = new ThreeBSP(newFilletMesh);
var intersectionPave = new THREE.Geometry();
intersectionPave = fillet2BSP.intersect(paveBSP);
var geometryPave = new THREE.Geometry();
geometryPave = intersectionPave.toGeometry();
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
//alert(geometryPave.faces.length);
while (geometryPave.faces.length != 0) {
var z = paveMesh.position.z + width + 5;
paveMesh.position.set(0, 0, z);
paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
fillet2BSP = new ThreeBSP(newFilletMesh);
intersectionPave = filletBSP.intersect(paveBSP);
geometryPave = intersectionPave.toGeometry();
tabVolumes[ind] = calculateVolume2(geometryPave);
ind = ind + 1;
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
newMesh.position.set(0, 0, newMesh.position.z);
scene.add(newMesh);
var meshSave = newMesh.clone();
mesh_decoupe.add(meshSave);
}
document.body.style.cursor = '';
} else {
scene.add(newFilletMesh);
document.body.style.cursor = '';
tabVolumes[3] = 0;
tabVolumes[4] = calculateVolume2(newFilet);
}
// }
//}
//else {
// scene.add(newFilletMesh);
// tabVolumes[ind] = calculateVolume2(newFilet);
//}
//alert(calculateVolume2(newBSP.toGeometry()));
//afficher les volumes dans la textarea
var txtVolume = document.getElementById("txtVolume");
txtVolume.value = tabVolumes.join("\n");
//var exporter = new THREE.OBJExporter();
//var result = exporter.parse(mesh_decoupe);
//var blob = new Blob([result], { type: 'text/plain' });
//saveAs(blob, 'dechets.obj');
}
});
//scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 500, false);
document.getElementById('canvas3D').innerHTML = "";
document.getElementById('canvas3D').appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
camin();
renderer.render(scene, camera);
}
function camin() {
camera.position.y -= .1;
}
function volumeOfT(p1, p2, p3) {
var v321 = p3.x * p2.y * p1.z;
var v231 = p2.x * p3.y * p1.z;
var v312 = p3.x * p1.y * p2.z;
var v132 = p1.x * p3.y * p2.z;
var v213 = p2.x * p1.y * p3.z;
var v123 = p1.x * p2.y * p3.z;
return (-v321 + v231 + v312 - v132 - v213 + v123) / 6.0;
}
function calculateVolume2(object) {
var volumes = 0.0;
for (var i = 0; i < object.faces.length; i++) {
var Pi = object.faces[i].a;
var Qi = object.faces[i].b;
var Ri = object.faces[i].c;
//alert (Pi);
var P = new THREE.Vector3(object.vertices[Pi].x, object.vertices[Pi].y, object.vertices[Pi].z);
//alert(object.vertices[Pi].x);
var Q = new THREE.Vector3(object.vertices[Qi].x, object.vertices[Qi].y, object.vertices[Qi].z);
var R = new THREE.Vector3(object.vertices[Ri].x, object.vertices[Ri].y, object.vertices[Ri].z);
volumes += volumeOfT(P, Q, R);
}
return Math.abs(volumes);
}
}
function FirstCut() {
var scene, camera, renderer, controls;
//stl loader from https://threejs.org/examples/webgl_loader_stl.html
// cf example https://stemkoski.github.io/Three.js/CSG.html
//with obj
init();
animate();
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
camera = new THREE.PerspectiveCamera(75, 800 / 500, 1, 2000);
//camera.position.set(50, 500, 0);
camera.position.x = 50;
camera.position.y = 500;
camera.position.z = 0;
//var axeX = new THREE.Vector3(1, 0, 0);
//camera.rotateOnAxis(axeX, -1);
camera.lookAt(new THREE.Vector3(0, 500, 0));
controls = new THREE.OrbitControls(camera);
//les valeurs de min and max distance sont choisies pour que le filet ne disparaisse pas quand on le fait tourner
controls.minDistance = 0;
controls.maxDistance = 1000;
//scene
//var ambient = new THREE.AmbientLight(0x101030);
//scene.add(ambient);
//scene.add(new THREE.GridHelper(1000, 20));
//var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
//directionalLight.position.set(0, 1, 0);
//scene.add(directionalLight);
var widthH = parseInt(document.getElementById("wdthH").value) || 0; // H for Head
var widthT = parseInt(document.getElementById("wdthT").value) || 0; // T for tail
var height = parseInt(document.getElementById("hght").value) || 0; // flank
//création du pavé
var EmportePieceH = new THREE.BoxGeometry(300, 60, widthH);
var EmportePieceT = new THREE.BoxGeometry(300, 60, widthT);
var EmportePieceB = new THREE.BoxGeometry(height, 60, 520);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage et material
var EmportePieceMeshH = new THREE.Mesh(EmportePieceH, paveMaterial);
var EmportePieceMeshT = new THREE.Mesh(EmportePieceT, paveMaterial);
var paveMeshB = new THREE.Mesh(EmportePieceB, paveMaterial);
var zH = 247 - widthH / 2;
var zT = -247 + widthT / 2;
EmportePieceMeshH.position.set(0, 30, zH);
EmportePieceMeshT.position.set(0, 30, zT);
paveMeshB.position.set(-95 + height / 2, 30, 0);
var EmportePieceBSPH = new ThreeBSP(EmportePieceMeshH);
var EmportePieceBSPT = new ThreeBSP(EmportePieceMeshT);
var paveBSPB = new ThreeBSP(paveMeshB);
//scene.add(EmportePieceMeshH);
//scene.add(EmportePieceMeshT);
//scene.add(paveMeshB);
// 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('/Scan/filet_1kg500-reposition-reduit_material_0.jpg', function (image) {
texture.image = image;
texture.needsUpdate = true;
});
var width = parseInt(document.getElementById("wdth").value) || 0;
//création du pavé
var paveGeom = new THREE.BoxGeometry(250, 250, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage parallélépipède avec material
var paveMesh = new THREE.Mesh(paveGeom, paveMaterial);
var z0 = -247 + widthH;
paveMesh.position.set(0, 0, z0);
var paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
//tableau des volumes
var tabVolumes = new Array();
// model
var loader = new THREE.OBJLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit.obj', function (object) {
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
var geo = new THREE.Geometry().fromBufferGeometry(child.geometry);
var filetMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
var filetMesh = new THREE.Mesh(geo, filetMaterial);
//scene.add(filetMesh);
var newBSPH, newBSPT, newBSPB, newBSP2, newBSP1, filletBSP
var filetBSP = new ThreeBSP(filetMesh);
newBSPH = filetBSP.intersect(EmportePieceBSPH);
newBSPT = filetBSP.intersect(EmportePieceBSPT);
newBSPB = filetBSP.intersect(paveBSPB);
newBSP2 = filetBSP.subtract(EmportePieceBSPH);
newBSP1 = newBSP2.subtract(paveBSPB);
filletBSP = newBSP1.subtract(EmportePieceBSPT);
////////////////////subtract//////////////////////////////
var newFilet = new THREE.Geometry();
newFilet = filletBSP.toGeometry();
var newFilletMesh = new THREE.Mesh(newFilet, new THREE.MeshBasicMaterial({ map: texture }));
newFilletMesh.position.set(0, 0, 0);
///////////////////////////////////création morceaux découpés///////////////////////////////////////////
var HeadFillet = new THREE.Geometry();
var TailFillet = new THREE.Geometry();
var degraissageFillet = new THREE.Geometry();
HeadFillet = newBSPH.toGeometry();
TailFillet = newBSPT.toGeometry();
degraissageFillet = newBSPB.toGeometry();
/////////////////////////////////calcul des volumes des 1ers morceaux/////////////////////////////////////////
if (widthH != 0) {
tabVolumes[0] = calculateVolume2(HeadFillet);
} else { tabVolumes[0] = 0;}
if (widthT != 0) {
//alert(tabVolumes[0]);
tabVolumes[1] = calculateVolume2(TailFillet);
} else { tabVolumes[1] = 0; }
if (height != 0) {
tabVolumes[2] = calculateVolume2(degraissageFillet);
} else { tabVolumes[2] = 0; }
var ind = 3;
var HeadFilletMesh = new THREE.Mesh(HeadFillet, new THREE.MeshBasicMaterial({ map: texture }));
var TailFilletMesh = new THREE.Mesh(TailFillet, new THREE.MeshBasicMaterial({ map: texture }));
var degraissageFilletMesh = new THREE.Mesh(degraissageFillet, new THREE.MeshBasicMaterial({ map: texture }));
HeadFilletMesh.position.set(0, 0, 20);
degraissageFilletMesh.position.set(-20, 0, 0);
TailFilletMesh.position.set(0, 0, -20);
scene.add(HeadFilletMesh);
scene.add(TailFilletMesh);
scene.add(degraissageFilletMesh);
//scene.add(newFilletMesh);
var cloneHeadFilletMesh = HeadFilletMesh.clone();
var cloneTailFilletMesh = TailFilletMesh.clone();
var clonedegraissageFilletMesh = degraissageFilletMesh.clone();
var mesh_decoupe = new THREE.Object3D;
mesh_decoupe.add(cloneHeadFilletMesh);
mesh_decoupe.add(cloneTailFilletMesh);
mesh_decoupe.add(clonedegraissageFilletMesh);
if (width != 0) {
var paveGeom = new THREE.BoxGeometry(300, 300, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
var fillet2BSP = new ThreeBSP(newFilletMesh);
var intersectionPave = new THREE.Geometry();
intersectionPave = fillet2BSP.intersect(paveBSP);
var geometryPave = new THREE.Geometry();
geometryPave = intersectionPave.toGeometry();
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
//alert(geometryPave.faces.length);
while (geometryPave.faces.length != 0) {
var z = paveMesh.position.z + width + 5;
paveMesh.position.set(0, 0, z);
paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
fillet2BSP = new ThreeBSP(newFilletMesh);
intersectionPave = filletBSP.intersect(paveBSP);
geometryPave = intersectionPave.toGeometry();
tabVolumes[ind] = calculateVolume2(geometryPave);
ind = ind + 1;
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
newMesh.position.set(0, 0, newMesh.position.z);
scene.add(newMesh);
var meshSave = newMesh.clone();
mesh_decoupe.add(meshSave);
}
document.body.style.cursor = '';
} else {
scene.add(newFilletMesh);
document.body.style.cursor = '';
tabVolumes[3] = 0;
tabVolumes[4] = calculateVolume2(newFilet);
}
// }
//}
//else {
// scene.add(newFilletMesh);
// tabVolumes[ind] = calculateVolume2(newFilet);
//}
//alert(calculateVolume2(newBSP.toGeometry()));
//afficher les volumes dans la textarea
var txtVolume = document.getElementById("txtVolume");
txtVolume.value = tabVolumes.join("\n");
//var exporter = new THREE.OBJExporter();
//var result = exporter.parse(mesh_decoupe);
//var blob = new Blob([result], { type: 'text/plain' });
//saveAs(blob, 'dechets.obj');
}
});
//scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 500, false);
document.getElementById('canvas3D').innerHTML = "";
document.getElementById('canvas3D').appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
camin();
renderer.render(scene, camera);
}
function camin() {
camera.position.y -= .1;
}
function volumeOfT(p1, p2, p3) {
var v321 = p3.x * p2.y * p1.z;
var v231 = p2.x * p3.y * p1.z;
var v312 = p3.x * p1.y * p2.z;
var v132 = p1.x * p3.y * p2.z;
var v213 = p2.x * p1.y * p3.z;
var v123 = p1.x * p2.y * p3.z;
return (-v321 + v231 + v312 - v132 - v213 + v123) / 6.0;
}
function calculateVolume2(object) {
var volumes = 0.0;
for (var i = 0; i < object.faces.length; i++) {
var Pi = object.faces[i].a;
var Qi = object.faces[i].b;
var Ri = object.faces[i].c;
//alert (Pi);
var P = new THREE.Vector3(object.vertices[Pi].x, object.vertices[Pi].y, object.vertices[Pi].z);
//alert(object.vertices[Pi].x);
var Q = new THREE.Vector3(object.vertices[Qi].x, object.vertices[Qi].y, object.vertices[Qi].z);
var R = new THREE.Vector3(object.vertices[Ri].x, object.vertices[Ri].y, object.vertices[Ri].z);
volumes += volumeOfT(P, Q, R);
}
return Math.abs(volumes);
}
}

How can I use Physi.js with a complex group geometry?

I create a modle car use three.js,and now , I need use Physi.js to add physical effect . But my modle car is too complex, many examples do this work like following:
var geometry = new THREE.CubeGeometry(4, 4, 4);
var material = new Physijs.createMaterial(new THREE.MeshPhongMaterial({
color: 0x4d6dad
}));
var mesh = new Physijs.BoxMesh(geometry, material, 1);
mesh.position.set(1.5, 10, 15);
mesh.rotation.y = Math.PI / 4;
scene.add(mesh);
As you can see, we can just create shapes like cube,sphere...But my car is too complex, how can I make it has physical effect?
My car just like this:
Click here to show my car picture
And these are a part of the codes:
function ModleCar(){
var carMain = new THREE.Object3D();
var meshGray = new THREE.MeshPhongMaterial({
color:0x4F4F4F,
side:THREE.DoubleSide
});
var meshYellow = new THREE.MeshPhongMaterial({
color:new THREE.Color('#FAF808'),
side:THREE.DoubleSide
});
var meshBlue = new THREE.MeshLambertMaterial({
color:new THREE.Color('#000042')
});
var meshWhite = new THREE.MeshPhongMaterial({
color:new THREE.Color('#E8E8E8'),
side:THREE.DoubleSide
});
var meshTest = new THREE.MeshPhongMaterial({
color:0x000000,
wireframe:true
});
var meshLightFront = new THREE.MeshBasicMaterial({
color:0xffffff
});
var meshBackLight = new THREE.MeshLambertMaterial({
color:new THREE.Color('#840000')
});
var meshLicencePlate = new THREE.MeshBasicMaterial({
color:new THREE.Color('#DCBA20'),
side:THREE.DoubleSide
});
var meshBlackLine = new THREE.MeshBasicMaterial({
color:0x000000,
wireframe:true
});
var meshRed = new THREE.MeshStandardMaterial({
color:0xff0000
});
function drawCarBody(){
var shape = new THREE.Shape();
shape.moveTo(10,10);
shape.splineThru([
new THREE.Vector2(10.2,11.8),
new THREE.Vector2(12,12)
])
shape.lineTo(18,12);
shape.splineThru([
new THREE.Vector2(19.8,11.8),
new THREE.Vector2(20,10)
])
shape.lineTo(20,4);
shape.lineTo(10,4);
shape.lineTo(10,10);
return shape;
}
var optionsCarBody = {
amount:25,
bevelThickness:1,
bevelSize:1,
beveSegments:20,
steps:20,
curveSegments:20
}
var carBodyOutside = setExtMaterial(drawCarBody,optionsCarBody,meshYellow);
carBodyOutside.position.set(-10,-3,15);
carBodyOutside.rotation.y = Math.PI/2;
//carMain.add(carBodyOutside);
var carBodyInside = new THREE.Mesh(new THREE.CubeGeometry(25,6.8,11.6),meshYellow);
//carMain.add(carBodyInside);
carBodyInside.position.set(3,5.18,0)
var meshFloor = new THREE.MeshLambertMaterial({
color:new THREE.Color('#840000')
});
var carFloor = new THREE.Object3D;
var carFloor1 = new THREE.Mesh(new THREE.CubeGeometry(17.6,0.5,11.6),meshFloor);
var carFloor2 = new THREE.Mesh(new THREE.CubeGeometry(3.6,0.5,11.6),meshFloor);
var carFloor3 = new THREE.Mesh(new THREE.CubeGeometry(5,0.5,9.3),meshFloor);
carFloor.add(carFloor1);
carFloor1.translateX(-3.1);
carFloor.add(carFloor2);
carFloor2.translateX(11.3);
carFloor.add(carFloor3);
carFloor3.translateX(7.4);
carFloor3.translateZ(-1.14);
var footstep = new THREE.Mesh(new THREE.CubeGeometry(4,1,1),meshYellow);
carFloor.add(footstep);
footstep.translateX(7.6);
footstep.translateZ(4);
footstep.translateY(-1.3);
var meshChair = new THREE.MeshPhongMaterial({
color:new THREE.Color('#198DE9')
})
var meshChairHandrail = new THREE.MeshPhongMaterial({
color:new THREE.Color('#EE890C')
})
function addChair(direction){
var chairTrestle = new THREE.Mesh(new THREE.CubeGeometry(4.2,1,0.5),meshGray);
chairTrestle.translateY(0.8);
//chair座椅,单个座椅
var chair = new THREE.Object3D();
chairTrestle.add(chair);
var chairBackrest = new THREE.Mesh(new THREE.CubeGeometry(1.8,2.3,0.2),meshChair);
chair.add(chairBackrest);
chairBackrest.translateY(1.8);
chairBackrest.rotation.x = -Math.PI/15;
chairBackrest.translateZ(-1);
var chairCushion = new THREE.Mesh(new THREE.CubeGeometry(1.8,1.5,0.2),meshChair);
chair.add(chairCushion);
chairCushion.rotation.x = Math.PI/2;
chairCushion.translateZ(-0.5);
var chairBackrestTop = new THREE.Mesh(new THREE.CylinderGeometry(0.2,0.2,1.8,15,1),meshChair);
chairBackrest.add(chairBackrestTop);
chairBackrestTop.translateY(1);
chairBackrestTop.rotation.z = Math.PI/2;
chair.translateX(-1)
var chairHandrail = new THREE.Mesh(new THREE.CubeGeometry(0.26,1.5,0.2),meshChairHandrail);
chairHandrail.translateY(1.1)
chairHandrail.rotation.x = Math.PI/2;
var chairHandrailLeft = chairHandrail.clone();
chairHandrailLeft.translateX(-1.95);
var chairHandrailRight = chairHandrail.clone();
chairHandrailRight.translateX(1.95);
switch(direction){
case "l": chairTrestle.add(chairHandrailLeft);break;
default : chairTrestle.add(chairHandrailRight);
}
chairTrestle.add(chairHandrail);
var chair2 = chair.clone();
chairTrestle.add(chair2);
chair2.translateX(2);
carFloor.add(chairTrestle);
chairTrestle.rotation.y = Math.PI/2;
return chairTrestle;
}
var chairRight1 = addChair();
chairRight1.translateX(-3.6);
chairRight1.translateZ(-10);
var chairDriver = new THREE.Mesh(new THREE.CubeGeometry(1.6,1.3,1.6),meshGray)
carFloor.add(chairDriver);
chairDriver.translateX(9.3);
chairDriver.translateZ(-4);
chairDriver.translateY(1);
chairDriver.rotation.y = Math.PI/2;
var chairDriverCushion = new THREE.Mesh(new THREE.CubeGeometry(2.5,2.5,0.3),meshChair);
chairDriver.add(chairDriverCushion);
chairDriverCushion.translateY(0.52);
chairDriverCushion.rotation.x = Math.PI/2;
var chairDriverBackrest = new THREE.Mesh(new THREE.CubeGeometry(2.5,2.7,0.3),meshChair);
chairDriver.add(chairDriverBackrest);
chairDriverBackrest.translateY(1.8);
chairDriverBackrest.translateZ(-1.3);
chairDriverBackrest.rotation.x = -Math.PI/18;
var chairDriverBackrestTop = new THREE.Mesh(new THREE.CylinderGeometry(0.3,0.3,2.3,15,1),meshChair);
chairDriverBackrest.add(chairDriverBackrestTop);
chairDriverBackrestTop.translateY(1.2);
chairDriverBackrestTop.rotation.z = Math.PI/2;
var steeringWheel = new THREE.Mesh(new THREE.TorusGeometry(0.6,0.1,20,30),meshGray);
carFloor.add(steeringWheel);
steeringWheel.translateX(11.5);
steeringWheel.translateY(3);
steeringWheel.translateZ(-4);
steeringWheel.rotation.x = Math.PI/2;
steeringWheel.rotation.z = Math.PI;
steeringWheel.rotation.y = Math.PI/4;
var steeringWheelInsidBar1 = new THREE.Mesh(new THREE.CylinderGeometry(0.1,-0.1,1.2,15,1),meshGray);
steeringWheel.add(steeringWheelInsidBar1);
var steeringWheelInsidBar2 = new THREE.Mesh(new THREE.CylinderGeometry(0,0.1,0.6,30,30),meshGray);
steeringWheel.add(steeringWheelInsidBar2);
steeringWheelInsidBar2.translateX(0.2);
steeringWheelInsidBar2.rotation.z = Math.PI/2;
var steeringWheelPole = new THREE.Mesh(new THREE.CylinderGeometry(0.1,0.1,2,15,1),meshGray);
steeringWheel.add(steeringWheelPole);
steeringWheelPole.rotation.x = Math.PI/2;
steeringWheelPole.translateY(1);
carMain.add(carFloor);
carFloor.position.set(2.7,2,0);
function drawCarHeadTopHead(){
var shape = new THREE.Shape();
shape.moveTo(10,10);
shape.splineThru([
new THREE.Vector2(10.2,11.8),
new THREE.Vector2(12,12)
])
shape.lineTo(18,12);
shape.splineThru([
new THREE.Vector2(19.8,11.8),
new THREE.Vector2(20,10)
])
shape.lineTo(20,10);
shape.lineTo(10,10);
return shape;
}
var optionsCarHeadTopHead = {
amount:2,
bevelThickness:0.1,
bevelSize:1,
beveSegments:20,
steps:20,
curveSegments:20
}
var carHeadTopHead = setExtMaterial(drawCarHeadTopHead,optionsCarHeadTopHead,meshYellow);
carHeadTopHead.rotation.y = Math.PI/2;
carHeadTopHead.translateX(-15);
carHeadTopHead.translateY(-3);
carHeadTopHead.translateZ(15);
var carHeadTopHeadDel = new THREE.Mesh(new THREE.CubeGeometry(3,3,15),meshGray);
carHeadTopHeadDel.translateZ(0);
carHeadTopHeadDel.translateY(6.8);
carHeadTopHeadDel.translateX(16.3);
carHeadTopHead = subtract(carHeadTopHead,carHeadTopHeadDel,meshYellow);
//carMain.add(carHeadTopHeadDel)
carMain.add(carHeadTopHead);
function drawCarHeadBottom(){
var shape = new THREE.Shape();
shape.moveTo(10,12);
shape.bezierCurveTo(10,16,20,16,20,12);
shape.lineTo(10,12);
return shape;
}
var optionsCarHeadBottom = {
amount:2.1,
bevelThickness:0.3,
bevelSize:1,
beveSegments:60,
steps:20,
curveSegments:60
}
var wheelOutsideBR = new THREE.Object3D();
carMain.add(wheelOutsideBR);
wheelOutsideBR.add(wheelOut);
wheelOutsideBR.position.set(15,-0.2,6);
var wheelOutsideAR = wheelOutsideBR.clone();
carMain.add(wheelOutsideAR);
wheelOutsideAR.translateX(-21.1);
var wheelOutsideAL = wheelOutsideAR.clone();
carMain.add(wheelOutsideAL);
wheelOutsideAL.translateZ(-12);
wheelOutsideAL.rotation.y = Math.PI;
var wheelOutsideBL = wheelOutsideAL.clone();
carMain.add(wheelOutsideBL);
wheelOutsideBL.translateX(-21.1);
var loader = new THREE.STLLoader();
loader.load("../model/Ban.stl",function(obj){
objectSTL = new THREE.Mesh(obj,meshWheel);
objectSTL.scale.set(0.03,0.03,0.03);
var o1 = objectSTL.clone();
var o2 = o1.clone();
var o3 = o2.clone();
wheelOutsideBR.add(objectSTL);
wheelOutsideAR.add(o1);
wheelOutsideAL.add(o2);
wheelOutsideBL.add(o3);
objectSTL.translateZ(-0.3);
o1.translateZ(-0.3);
o2.translateZ(-0.3);
o3.translateZ(-0.3);
});
console.log(3);
//门窗
var meshGlass = new THREE.MeshStandardMaterial({
color:new THREE.Color('#0CF5F7'),
transparent:true,
opacity:0.4,
side:THREE.FrontSide
});
//汽车前窗户
var windowFront = new THREE.Mesh(new THREE.CubeGeometry(1,5,9),meshTest);
windowFront.position.set(16,6,0);
//添加前窗玻璃
function drawFrontGlass(){
var shape = new THREE.Shape();
shape.moveTo(20,20);
shape.quadraticCurveTo(30,30.1,40,20);
shape.moveTo(40,19.1);
shape.quadraticCurveTo(30,30.1,20,19.9);
shape.moveTo(20,20);
return shape;
}
var optionsFrontGlass = {
amount:10,
bevelThickness:0,
bevelSize:1,
beveSegments:60,
steps:1,
curveSegments:60
}
var frontGlass = setExtMaterial(drawFrontGlass,optionsFrontGlass,meshGlass);
frontGlass.scale.set(0.41,0.1,0.6);
frontGlass.translateX(14);
frontGlass.translateY(8.5);
frontGlass.translateZ(12.3);
frontGlass.rotation.x = Math.PI/2;
frontGlass.rotation.z = -Math.PI/2;
carMain.add(frontGlass);
var windowRight = new THREE.Mesh(new THREE.CubeGeometry(23,4,1),meshGray);
//carMain.add(windowRight);
windowRight.position.set(2.5,6,6);
var rightGlass = new THREE.Mesh(new THREE.CubeGeometry(17.4,4,0.1),meshGlass);
carMain.add(rightGlass);
rightGlass.translateZ(5.8);
rightGlass.translateY(6);
rightGlass.translateX(-0.5);
var rightGlassSmall = new THREE.Mesh(new THREE.CubeGeometry(1.8,4,0.1),meshGlass);
carMain.add(rightGlassSmall);
rightGlassSmall.translateZ(5.8);
rightGlassSmall.translateY(6);
rightGlassSmall.translateX(13.3);
var windowRightBar1 = new THREE.Mesh(new THREE.CubeGeometry(0.5,4,0.2),meshYellow);
carMain.add(windowRightBar1);
windowRightBar1.position.set(-3.3,6,5.9);
var windowRightBar2 = windowRightBar1.clone();
windowRightBar2.translateX(5.8);
carMain.add(windowRightBar2);
var windowRightBar3 = windowRightBar2.clone();
windowRightBar3.translateX(5.6);
carMain.add(windowRightBar3);
var windowRightBar4 = windowRightBar3.clone();
windowRightBar4.translateX(4.4);
carMain.add(windowRightBar4);
var doorRight = new THREE.Mesh(new THREE.CubeGeometry(4,7.5,3),meshGray);
//carMain.add(doorRight);
doorRight.position.set(10.3,4.28,5);
var doorcaseBody = new THREE.Object3D();
carMain.add(doorcaseBody);
doorcaseBody.position.set(10.2,7.75,5.8)
//门框
var doorcaseTop = new THREE.Mesh(new THREE.CubeGeometry(4,0.5,0.2),meshYellow);
doorcaseBody.add(doorcaseTop);
var doorcaseBottom = doorcaseTop.clone();
doorcaseBody.add(doorcaseBottom);
doorcaseBottom.translateY(-7);
var doorcaseLeft = new THREE.Mesh(new THREE.CubeGeometry(0.5,7,0.2),meshYellow);
doorcaseBody.add(doorcaseLeft);
doorcaseLeft.translateX(-1.75);
doorcaseLeft.translateY(-3.5);
var doorcaseRight = doorcaseLeft.clone();
doorcaseBody.add(doorcaseRight);
doorcaseRight.translateX(3.5);
//门玻璃
var doorGlass = new THREE.Mesh(new THREE.CubeGeometry(4,7.5,0.1),meshGlass);
doorcaseBody.add(doorGlass);
doorGlass.translateY(-3.5);
//门滑道抓手
var doorSlidewayHandTop = new THREE.Mesh(new THREE.CubeGeometry(0.1,0.1,0.8),meshWhite);
doorcaseBody.add(doorSlidewayHandTop);
doorSlidewayHandTop.translateY(0.35);
doorSlidewayHandTop.translateZ(-0.3)
var doorSlidewayHandTop2 = new THREE.Mesh(new THREE.CubeGeometry(0.1,0.1,0.1),meshWhite);
doorSlidewayHandTop.add(doorSlidewayHandTop2);
doorSlidewayHandTop2.translateZ(0.35);
doorSlidewayHandTop2.translateY(-0.05)
var doorSlidewayHandBottom = doorSlidewayHandTop.clone();
doorcaseBody.add(doorSlidewayHandBottom);
doorSlidewayHandBottom.rotation.z = Math.PI;
doorSlidewayHandBottom.translateY(7.7);
//门滑道
var doorSlidewayTop = new THREE.Mesh(new THREE.CubeGeometry(4.6,0.2,0.1),meshBlue);
carMain.add(doorSlidewayTop);
doorSlidewayTop.translateZ(6);
doorSlidewayTop.translateY(8.1);
doorSlidewayTop.translateX(8.2);
var doorSlidewayBottom = doorSlidewayTop.clone();
carMain.add(doorSlidewayBottom);
doorSlidewayBottom.translateY(-7.65);
var windowLeft = new THREE.Mesh(new THREE.CubeGeometry(18,4,1),meshGray);
//carMain.add(windowLeft);
windowLeft.position.set(0,6,6)
windowLeft.translateZ(-12);
var leftGlass = new THREE.Mesh(new THREE.CubeGeometry(18,4,0.1),meshGlass);
carMain.add(leftGlass);
leftGlass.translateZ(-5.8);
leftGlass.translateY(6);
leftGlass.translateX(0);
var windowLeftBar1 = windowRightBar1.clone();
windowLeftBar1.translateZ(-11.8);
carMain.add(windowLeftBar1);
var windowLeftBar2 = windowRightBar2.clone();
windowLeftBar2.translateZ(-11.8);
carMain.add(windowLeftBar2);
var windowLeftBar3 = windowRightBar3.clone();
windowLeftBar3.translateZ(-11.8);
windowLeftBar3.scale.x = 3.7;
carMain.add(windowLeftBar3);
function drawDoorLeft(){
var shape = new THREE.Shape();
shape.moveTo(10,7);
shape.lineTo(13,7);
shape.lineTo(13,3.2);
shape.lineTo(12,2.5)
shape.lineTo(11.7,2);
shape.lineTo(10,2);
shape.lineTo(10,7);
return shape;
}
var optionsDoorLeft = {
amount:1,
bevelThickness:0,
bevelSize:1,
beveSegments:1,
steps:1,
curveSegments:30
}
var doorLeftHole = setExtMaterial(drawDoorLeft,optionsDoorLeft,meshTest);
//carMain.add(doorLeftHole);
doorLeftHole.translateZ(-6.9);
//司机门窗户
var dirverDoorWindow = new THREE.Mesh(new THREE.CubeGeometry(4,4,1),meshChair);
//carMain.add(dirverDoorWindow);
dirverDoorWindow.position.set(11.5,5.5,-5.8)
var driverGlass = new THREE.Mesh(new THREE.CubeGeometry(4,4,0.1),meshGlass);
carMain.add(driverGlass);
driverGlass.position.set(11.5,5.5,-5.7)
//后面窗户
var windowBack = new THREE.Mesh(new THREE.CubeGeometry(3,4,9),meshTest);
//carMain.add(windowBack);
windowBack.translateX(-10);
windowBack.translateY(6.5);
var backGlass = new THREE.Mesh(new THREE.CubeGeometry(0.1,4,9),meshGlass);
carMain.add(backGlass);
backGlass.position.set(-10.8,6.5,0)
//停车指示牌
var stopIndicatePlate = new THREE.Mesh(new THREE.CylinderGeometry(0.2,0.2,1,15,1),meshWhite);
carMain.add(stopIndicatePlate);
stopIndicatePlate.translateZ(-6.2);
stopIndicatePlate.translateY(3);
stopIndicatePlate.translateX(8);
var PlatePoint = new THREE.Object3D();
stopIndicatePlate.add(PlatePoint);
var plate1 = new THREE.Mesh(new THREE.CubeGeometry(1,0.5,0.1),meshWhite);
PlatePoint.add(plate1);
plate1.translateX(-0.5);
var plate2 = new THREE.Mesh(new THREE.CircleGeometry(1,6),createImageMesh("../image/stopplatepic.png"));
var plate3 = plate2.clone();
PlatePoint.add(plate3);
PlatePoint.add(plate2);
plate3.rotation.y = Math.PI;
plate3.translateX(1.8);
plate2.translateX(-1.8);
//前面车灯
var carLightFront = new THREE.Mesh(new THREE.CylinderGeometry(1,1,2,15,1,true),meshYellow);
carMain.add(carLightFront);
carLightFront.rotation.z = Math.PI/2;
carLightFront.translateY(-17);
carLightFront.translateZ(-5);
carLightFront.translateX(1.2);
var carLightFrontInside = new THREE.Mesh(new THREE.CylinderGeometry(1,1,1.6,15,1),meshLightFront);
carLightFront.add(carLightFrontInside);
carLightFrontInside.translateZ(0.1);
//添加车灯光线
var carFrontLight = new THREE.SpotLight(new THREE.Color("#FFFF7D"));
carMain.add(carFrontLight);
carFrontLight.position.set(17.5,1,-5.5);
carFrontLight.angle = Math.PI/6;
carFrontLight.decay = 1;
carFrontLight.distance = 100;
carFrontLight.penumbra = 1;
carFrontLight.power = 10;
var carLightTarget = new THREE.Object3D();
carMain.add(carLightTarget);
carLightTarget.position.set(50,-1.8,-5.4)
carFrontLight.target = carLightTarget;
var carLightFrontRight = carLightFront.clone();
carMain.add(carLightFrontRight);
carLightFrontRight.translateZ(10);
carLightFrontRight.rotation.x = Math.PI;
var carFrontLightRight = carFrontLight.clone();
carMain.add(carFrontLightRight);
carFrontLightRight.translateZ(11);
var carLightTargetRight = carLightTarget.clone();
carMain.add(carLightTargetRight);
carFrontLightRight.target = carLightTargetRight;
carLightTargetRight.position.set(50,-1.8,5.4);
//汽车尾灯
var lightBackPoint = new THREE.Object3D();
carMain.add(lightBackPoint);
addPoint(lightBackPoint);
lightBackPoint.position.set(-9.8,2,3.8);
function drawLightBack(){
var shape = new THREE.Shape();
shape.moveTo(0,0);
//shape.quadraticCurveTo(1,1,2,2);
shape.lineTo(2,0);
shape.lineTo(2,1);
shape.lineTo(0,1);
return shape;
}
var optionsLightBack = {
amount:1,
bevelThickness:2,
bevelSize:1,
beveSegments:60,
steps:2,
curveSegments:60
}
var lightBack = setExtMaterial(drawLightBack,optionsLightBack,meshBackLight);
lightBackPoint.add(lightBack);
lightBack.scale.set(0.7,0.7,0.5);
lightBack.rotation.y = -Math.PI/2;
var lightBackLeft = lightBack.clone();
carMain.add(lightBackLeft);
lightBackLeft.translateZ(9.8);
lightBackLeft.translateX(-5);
lightBackLeft.translateY(2);
lightBack.normalsNeedUpdate = true;
//后视镜
var rearviewMirrorPoint = new THREE.Object3D();
carMain.add(rearviewMirrorPoint);
rearviewMirrorPoint.translateX(15);
rearviewMirrorPoint.translateY(6);
rearviewMirrorPoint.translateZ(-5.8);
var rearviewPointsArray = [];
rearviewPointsArray.push(new THREE.Vector3(10,3.8,0));
rearviewPointsArray.push(new THREE.Vector3(12,3.8,0));
rearviewPointsArray.push(new THREE.Vector3(12,1.5,0));
rearviewPointsArray.push(new THREE.Vector3(12,0,0));
rearviewPointsArray.push(new THREE.Vector3(10,0,0));
var rearviewTrestle = new THREE.TubeGeometry(
new THREE.SplineCurve3(rearviewPointsArray),80,0.1
)
var rearviewMesh = new THREE.Mesh(rearviewTrestle,meshGray);
rearviewMirrorPoint.add(rearviewMesh);
rearviewMesh.scale.set(1,1,1);
rearviewMesh.rotation.y = Math.PI/6;
rearviewMesh.position.set(-8.5,-2,5);
var rearviewMirror = new THREE.Mesh(new THREE.SphereGeometry(1.6,30,30,0,Math.PI*2,0,Math.PI/5),meshGray);
rearviewMirrorPoint.add(rearviewMirror);
rearviewMirror.rotation.z = -Math.PI/2;
rearviewMirror.rotation.y = Math.PI/6;
rearviewMirror.translateY(0.4);
rearviewMirror.translateZ(0);
var rearviewMirrorRight = rearviewMirrorPoint.clone();
carMain.add(rearviewMirrorRight);
rearviewMirrorRight.rotation.z = Math.PI;
rearviewMirrorRight.rotation.y = Math.PI;
rearviewMirrorRight.translateZ(-11.6);
rearviewMirrorRight.translateX(0);
rearviewMirrorRight.translateY(0.2);
//添加车头文字标识
var fontLoader = new THREE.FontLoader();
fontLoader.load('../fonts/gentilis_bold.typeface.json',function(font){
var optionsNumber = {
size:1,
height:0.5,
font:font,
weight:'normal',
style:'normal',
bevelThickness:2,
bevelSize:2,
bevelSegments:2,
bevelEnable:true,
curveSegments:12,
steps:1
}
text = new THREE.Mesh(new THREE.TextGeometry("Lison's School Bus", optionsNumber),meshRed);
carMain.add(text);
text.scale.x = 0.8;
text.rotation.y = Math.PI/2;
text.position.set(16.76,8.6,4.4);
})
//车牌
//前面车牌
var licencePlateFront = new THREE.Mesh(new THREE.CubeGeometry(4,1.4,1),meshGray);
carMain.add(licencePlateFront);
licencePlateFront.translateX(19.6);
licencePlateFront.translateY(1.2);
licencePlateFront.rotation.y = Math.PI/2;
//后车牌
var licencePlateBack = licencePlateFront.clone();
carMain.add(licencePlateBack);
licencePlateBack.translateZ(-30.3);
licencePlateBack.translateY(1);
var car = new THREE.Object3D();
car.add(carMain);
carMain.position.set(-5,1.7,0);
//扣掉汽车前窗户
// var carBody = subtract(carBodyOutside,windowFront,meshYellow);
// carBody = subtract(carBody,windowBack,meshYellow);
// //扣掉汽车内部
// carBody = subtract(carBody,carBodyInside,meshYellow);
// //扣掉窗户和门
// carBody = subtract(carBody,windowRight,meshYellow);
// carBody = subtract(carBody,doorRight,meshYellow);
// carBody = subtract(carBody,windowLeft,meshYellow);
// carBody = subtract(carBody,doorLeftHole,meshYellow);
// carBody = subtract(carBody,dirverDoorWindow,meshYellow);
//
// carMain.add(carBody)
var ModleCar = {};
ModleCar = car;
ModleCar.wheelOutsideBR = wheelOutsideBR;
ModleCar.wheelOutsideBL = wheelOutsideBL;
ModleCar.wheelOutsideAR = wheelOutsideAR;
ModleCar.wheelOutsideAL = wheelOutsideAL;
ModleCar.meshLightFront = meshLightFront;
ModleCar.meshBackLight = meshBackLight;
ModleCar.PlatePoint = PlatePoint;
ModleCar.carFrontLight = carFrontLight;
ModleCar.carFrontLightRight = carFrontLightRight;
ModleCar.doorcaseBody = doorcaseBody;
return ModleCar;
/*
//小车模型外部文件引入的代码
var car = ModleCar();
scene.add(car);
var wheelOutsideBR = car.wheelOutsideBR;
var wheelOutsideBL = car.wheelOutsideBL;
var wheelOutsideAR = car.wheelOutsideAR;
var wheelOutsideAL = car.wheelOutsideAL;
var meshBackLight = car.meshBackLight;
var PlatePoint = car.PlatePoint;
var carFrontLight = car.carFrontLight;
var carFrontLightRight = car.carFrontLightRight;
var doorcaseBody = car.doorcaseBody;
var meshLightFront = car.meshLightFront;
*/
}

Texture mapping from one Face4 to two Face3 on Three.js

I am playing with Three.js. I am working on a project that uses an old version of Three.js. I'm trying to replace the old library with the new one (r71). Everything is going well except the texture mapping.
In the old project we use the Face4 which is deprecated and have been removed in the newest version of Three.js. So I have created two Face3 instead of just one Face4. Now the question is: how can I make one texture to cover both Face3 as they were like a single Face4?
Old pseudo-code using Face4
numberOfFaces = 10;
function createMyGeometry(){
var geometry = new THREE.Geometry();
...
for (var i = 0; i < numberOfFaces; i++) {
var face = new THREE.Face4(v1.index, v2.index, v3.index, v4.index, [v1.clone(), v2.clone(), v3.clone(), v4.clone()]);
face.centroid.add(v1).add(v2).add(v3).add(v4).divideScalar(4);
face.normal = face.centroid.clone().normalize();
face.materialIndex = matIdx;
geometry.faces.push(face);
geometry.faceVertexUvs[0].push([uv1.clone(), uv2.clone(), uv3.clone(), uv4.clone()]);
}
...
return geometry;
}
for (var i = 0; i < numberOfFaces; i++) {
var texture = THREE.ImageUtils.loadTexture("MyImage"+ i + '.jpg');
var material = new THREE.MeshBasicMaterial();
material.map = texture;
material.side = THREE.FrontSide;
materials.push(material);
}
materials = new THREE.MeshFaceMaterial(materials);
myGeometry = new THREE.Mesh(createMyGeometry(), materials);
scene.add(myGeometry);
Pseudo-code using Face3
numberOfFaces = 10;
function createMyGeometry(){
var geometry = new THREE.Geometry();
...
for (var i = 0; i < numberOfFaces; i++) {
var face1 = new THREE.Face3(v1.index, v2.index, v3.index, [v1.clone(), v2.clone(), v3.clone()]);
var face2 = new THREE.Face3(v1.index, v3.index, v4.index, [v1.clone(), v3.clone(), v4.clone()]);
face1.materialIndex = matIdx;
face2.materialIndex = matIdx;
geometry.faces.push(face1);
geometry.faces.push(face2);
geometry.faceVertexUvs[0].push([uv1.clone(), uv2.clone(), uv3.clone(), uv4.clone()]);
}
...
return geometry;
}
for (var i = 0; i < numberOfFaces; i++) {
var texture = THREE.ImageUtils.loadTexture("MyImage"+ i + '.jpg');
var material = new THREE.MeshBasicMaterial();
material.map = texture;
material.side = THREE.FrontSide;
materials.push(material);
}
materials = new THREE.MeshFaceMaterial(materials);
myGeometry = new THREE.Mesh(createMyGeometry(), materials);
scene.add(myGeometry);
You should just do the same thing with vertex uvs as with vertices.
For example:
geometry.faceVertexUvs[0].push([uv1.clone(), uv2.clone(), uv3.clone()]);
geometry.faceVertexUvs[0].push([uv1.clone(), uv3.clone(), uv4.clone()]);

How to do collision between two cubes in cannon.js?

when i try to make collision between a platform created with cannon.js an another box... the collision depend of the position where i put this box. Sometimes the box go throught de plattform.
However if i make a collision between this platfmorm and a sphere its run pefectly.
My cuestion is,Why is happen this?
And most important... What can i do to solve its?
please excuse my posibles erros writting... my level of english is not good jeje.
Here is the code, thanks in advance:
<!DOCTYPE html>
<html>
<head>
<title>pruebas</title>
<style>canvas { width: 100%; height: 100% }
body {margin:0px; padding: 0px}
</style>
<script src="JS/ThreeJS/three.js"></script>
<script src="JS/cannon.js"></script>
</head>
<body>
<script>
//************************************** FISICA
var world = new CANNON.World();
world.gravity.set(0,-50,0);
world.broadphase = new CANNON.NaiveBroadphase();
//*************************************** RENDERER
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer( { antialias: true } );
document.body.appendChild(renderer.domElement);
renderer.setClearColor("#000000");
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;
renderer.shadowMapSoft = true;
//**************************************** LIGHT
var light = new THREE.SpotLight("white");
light.position.set(-180,100,-90);
light.castShadow = true;
light.shadowDarkness = 1;
light.intensity = 3;
scene.add(light);
//****************************************** PLATFORMS
//plane_fisic
var groundShape = new CANNON.Plane();
var groundBody = new CANNON.RigidBody(0,groundShape);
groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0),-Math.PI/2);
world.add(groundBody);
//plane_mesh
var geometry = new THREE.PlaneGeometry( 300, 300, 50, 50 );
geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
var material = new THREE.MeshLambertMaterial( { color: 0xdddddd } );
var plano = new THREE.Mesh( geometry, material );
plano.castShadow = true;
plano.receiveShadow = true;
scene.add(plano);
//box_fisic
var forma = new CANNON.Box(new CANNON.Vec3(80,5,50));
var mass = 0;
var alma_table = new CANNON.RigidBody(mass,forma);
alma_table.position.y = 35;
alma_table.useQuaternion = true;
world.add(alma_table);
//box_mesh
var floorMaterial = new THREE.MeshPhongMaterial();
var tableGeometry = new THREE.CubeGeometry(160,10,100);
var table = new THREE.Mesh(tableGeometry,floorMaterial);
table.castShadow = true;
table.receiveShadow = true;
table.ambientLightColor = true;
scene.add(table);
//************************************** OBJETS
//BOX
//fisic
var forma = new CANNON.Box(new CANNON.Vec3(8,8,8));
var mass = 2;
var box_alma = new CANNON.RigidBody(mass,forma);
box_alma.position.y = 80;
box_alma.position.x = 0;
box_alma.position.z = 0;
box_alma.useQuaternion = true;
world.add(box_alma);
//mesh
var floorMaterial = new THREE.MeshPhongMaterial();
var tableGeometry =new THREE.CubeGeometry(16,16,16);
var box = new THREE.Mesh(tableGeometry,floorMaterial);
box.castShadow = true;
box.receiveShadow = true;
box.ambientLightColor = true;
scene.add(box);
//BOX2
//fisic
var forma = new CANNON.Box(new CANNON.Vec3(8,8,8));
var mass = 2;
var box_alma2 = new CANNON.RigidBody(mass,forma);
box_alma2.position.y = 80;
box_alma2.position.x = -40;
box_alma2.position.z = +20;
box_alma2.useQuaternion = true;
world.add(box_alma2);
//mesh
var floorMaterial = new THREE.MeshPhongMaterial();
var tableGeometry =new THREE.CubeGeometry(16,16,16);
var box2 = new THREE.Mesh(tableGeometry,floorMaterial);
box2.castShadow = true;
box2.receiveShadow = true;
box2.ambientLightColor = true;
scene.add(box2);
//BOX3
//fisic
var forma = new CANNON.Box(new CANNON.Vec3(8,8,8));
var mass = 2;
var box_alma3 = new CANNON.RigidBody(mass,forma);
box_alma3.position.y = 80;
box_alma3.position.x = 50;
box_alma3.position.z = 0;
box_alma3.useQuaternion = true;
world.add(box_alma3);
//mesh
var floorMaterial = new THREE.MeshPhongMaterial();
var tableGeometry =new THREE.CubeGeometry(16,16,16);
var box3 = new THREE.Mesh(tableGeometry,floorMaterial);
box3.castShadow = true;
box3.receiveShadow = true;
box3.ambientLightColor = true;
scene.add(box3);
//****************************************************** CÁMARA
var camera = new THREE.PerspectiveCamera(40, window.innerWidth/window.innerHeight, 0.1, 150000);
camera.position.z =300;
camera.position.y=130;
camera.position.x=0;
camera.lookAt(scene.position)
update = function(){
world.step(1/60);
alma_table.position.copy(table.position);
alma_table.quaternion.copy(table.quaternion);
box_alma2.position.copy(box2.position);
box_alma2.quaternion.copy(box2.quaternion);
box_alma.position.copy(box.position);
box_alma.quaternion.copy(box.quaternion);
box_alma3.position.copy(box3.position);
box_alma3.quaternion.copy(box3.quaternion);
}
var loop = function () {
requestAnimationFrame(loop);
renderer.render(scene,camera);
update();
}
loop();
</script>
</body>
</html>
Try using the latest development version of Cannon.js. Download it here.

Resources