hello i want to create multiple cubes with different textures for each cube.
to have the best performances i've created a single mesh with merged geometries. but i have a problem with the textures because until now i must have a draw call per texture.
i want to know if exist a method to have a single merged texture like the geometry, in this way i can create a one big texturized mesh with only one draw call.
my actual code is this.
var geometry = new THREE.Geometry();
var materials = [];
for(var p: number = 0; p < 1000; p++){
var height = Math.floor((Math.random() * 100) + 50);
var box = new THREE.BoxGeometry(10, 5, 10);
box.translate(
Math.floor((Math.random() * 100) + 50),
Math.floor((Math.random() * 100) + 50),
Math.floor((Math.random() * 100) + 50));
var texture = new THREE.MeshLambertMaterial({ map: new THREE.TextureLoader().load(textures[p])});
texture.needsUpdate = true;
geometry.merge(box);
materials.push(texture);
}
var mesh = new THREE.Mesh(geometry, materials);
el.setObject3D("mesh", mesh);
i think the way is to have a texture per geometry or to create different textures to merge in a single texture.
every advice is well accepted thanks in advance.
i use a-frame v.0.7.1 but in this case i think is more a threejs problem
You can merge all of your texture images into a single texture atlas. And then modify per geometry the UVs to point to the desired texture.
https://solutiondesign.com/blog/-/blogs/webgl-and-three-js-texture-mappi-1
Snippet from that guide:
var texture = new THREE.MeshLambertMaterial({ map: new THREE.TextureLoader().load('textureatlas.png')});
var bricks = [
new THREE.Vector2(0, .666),
new THREE.Vector2(.5, .666),
new THREE.Vector2(.5, 1),
new THREE.Vector2(0, 1)
];
geometry.faceVertexUvs[0] = [];
geometry.faceVertexUvs[0][0] = [ bricks[0], bricks[1], bricks[3] ];
geometry.faceVertexUvs[0][1] = [ bricks[1], bricks[2], bricks[3] ];
Since you are merging the geometries, just need to make sure the UVs transfer over (perhaps they do automatically).
Related
I have to calculate the volume of an STL file, I successfully got the sizes of the model with
var box = new THREE.Box3().setFromObject( mesh );
var sizes = box.getSize();
but I just can't wrap my head around the concept of calculating it. I load the model with
var loader = new THREE.STLLoader();
loader.load(stlFileURL, function ( geometry ) {});
Can someone help me out and point me in the right direction? I'm doing it with javascript.
You can find it with the algorithm from my comment.
In the code snippet, the volume is computed without scaling.
Also, I've added a simple check that the algorithm calculates correctly by finding the volume of a hollow cylinder. As THREE.STLLoader() returns a non-indexed geometry, I've casted the geometry of the cylinder to non-indexed too.
Related forum topic
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.01, 1000);
camera.position.setScalar(20);
var renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0x404040);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var loader = new THREE.STLLoader();
loader.load('https://threejs.org/examples/models/stl/binary/pr2_head_pan.stl', function(geometry) {
var mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
color: 0xff00ff,
wireframe: true
}));
mesh.rotation.set(-Math.PI / 2, 0, 0);
mesh.scale.setScalar(100);
scene.add(mesh);
console.log("stl volume is " + getVolume(geometry));
});
// check with known volume:
var hollowCylinderGeom = new THREE.LatheBufferGeometry([
new THREE.Vector2(1, 0),
new THREE.Vector2(2, 0),
new THREE.Vector2(2, 2),
new THREE.Vector2(1, 2),
new THREE.Vector2(1, 0)
], 90).toNonIndexed();
console.log("pre-computed volume of a hollow cylinder (PI * (R^2 - r^2) * h): " + Math.PI * (Math.pow(2, 2) - Math.pow(1, 2)) * 2);
console.log("computed volume of a hollow cylinder: " + getVolume(hollowCylinderGeom));
function getVolume(geometry) {
let position = geometry.attributes.position;
let faces = position.count / 3;
let sum = 0;
let p1 = new THREE.Vector3(),
p2 = new THREE.Vector3(),
p3 = new THREE.Vector3();
for (let i = 0; i < faces; i++) {
p1.fromBufferAttribute(position, i * 3 + 0);
p2.fromBufferAttribute(position, i * 3 + 1);
p3.fromBufferAttribute(position, i * 3 + 2);
sum += signedVolumeOfTriangle(p1, p2, p3);
}
return sum;
}
function signedVolumeOfTriangle(p1, p2, p3) {
return p1.dot(p2.cross(p3)) / 6.0;
}
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/loaders/STLLoader.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
This is a pretty tricky problem. One way is to decompose the object into a bunch of convex polyhedra and sum the volumes of those...
Another way is to voxelize it, and add up the voxels on the inside to get an estimate whos accuracy is limited by the resolution of your voxelization.
Edit: prisoner849 has a rad solution!
I'm also looking for a solution to this, And didn't have any implementation so far.
But extending from the voxelization idea like #manthrax mentioned.
I think we can voxelized into the octree structure.
If the cube still intersects with multiple triangles then voxelized deeper octree.
Until we reached the level of a single triangle cut through,
Then we calculate the volume of the cube using this method:
https://math.stackexchange.com/questions/454583/volume-of-cube-section-above-intersection-with-plane
After understood prisoner849's solution,
This idea is no more valid compared to his solution.
I have a scene which contains multiple meshes, each of varying shapes and sizes.
I have looped through each Mesh and using geometry.merge() I have been able to create a new mesh from the geometries in the scene.
I want to mask the entire mesh with an alphaMask, however, each geometry has the material applied to it separately.
An example of this can be seen here - https://codepen.io/danlong/pen/KXOObr
function addObjects(scene) {
// merged geomoetry & material
var mergedGeometry = new THREE.Geometry();
var mergedMaterial = new THREE.MeshStandardMaterial({ color: "#444", transparent: true, side: THREE.DoubleSide, alphaTest: 0.5, opacity: 1, roughness: 1 });
// multiple meshes
var geometry = new THREE.IcosahedronGeometry(30, 5);
var material = new THREE.MeshStandardMaterial({ color: "#444" });
var geo1 = new THREE.IcosahedronGeometry(30, 5);
var mesh1 = new THREE.Mesh( geo1, material );
mesh1.position.x = 10;
mesh1.position.y = 10;
mesh1.position.z = 0;
var geo2 = new THREE.IcosahedronGeometry(30, 5);
var mesh2 = new THREE.Mesh( geo2, material );
mesh2.position.x = 20;
mesh2.position.y = 20;
mesh2.position.z = 0;
var geo3 = new THREE.IcosahedronGeometry(30, 5);
var mesh3 = new THREE.Mesh( geo3, material );
mesh3.position.x = 30;
mesh3.position.y = 30;
mesh3.position.z = 0;
// scene.add(mesh1, mesh2, mesh3);
mesh1.updateMatrix();
mergedGeometry.merge(mesh1.geometry, mesh1.matrix);
mesh2.updateMatrix();
mergedGeometry.merge(mesh2.geometry, mesh2.matrix);
mesh3.updateMatrix();
mergedGeometry.merge(mesh3.geometry, mesh3.matrix);
// alpha texture
var image = document.createElement('img');
var alphaMap = new THREE.Texture(image);
image.onload = function() {
alphaMap.needsUpdate = true;
};
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAGUlEQVQoU2NkYGD4z4AHMP7//x+/gmFhAgCXphP14bko/wAAAABJRU5ErkJggg==';
mergedMaterial.alphaMap = alphaMap;
mergedMaterial.alphaMap.magFilter = THREE.NearestFilter;
mergedMaterial.alphaMap.wrapT = THREE.RepeatWrapping;
mergedMaterial.alphaMap.repeat.y = 1;
// merged geometry with alpha mask
merge1 = new THREE.Mesh(mergedGeometry, mergedMaterial);
merge1.rotation.z = -Math.PI/4;
// merge geometry without alpha mask
var merge2 = new THREE.Mesh(mergedGeometry, material);
merge2.position.x = -100;
merge2.rotation.z = -Math.PI/4;
scene.add(merge1, merge2);
return mesh;
}
The mesh on the left is the merged geometries which I want to apply the alphaMask to. The mesh on the right is the outcome of this and instead of the map being applied to the mesh as a whole, each of the geometries has the map applied.
Is there a way to mask the entire mesh and not each geometry?
--
three.js r86
EDIT:
I've tried to apply a clipping plane to my mesh but it's not the effect I'm looking for. I want to be able to apply an alphaMask across the whole mesh and reveal it however I make my mask image. Something like this effect - https://codepen.io/supah/pen/zwJxdb
Is it something to do with the UV's being preserved from the original geometries? Do I need to change these in some way?
I think what you really want is an overlaid mask. This can be accomplished by rendering a single plane that has the alpha map applied, on top of the scene rendering. Using an orthographic camera, and controlling certain renderer settings, such as disabling automatic clearing of color.
My display has a resolution of 7680x4320 pixels. I want to display up to 4 million different colored squares. And I want to change the number of squares with a slider. If have currently two versions. One with canvas-fillRect which looks somethink like this:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
for (var i = 0; i < num_squares; i ++) {
ctx.fillStyle = someColor;
ctx.fillRect(pos_x, pos_y, pos_x + square_width, pos_y + square_height);
// set pos_x and pos_y for next square
}
And one with webGL and three.js. Same loop, but I create a box geometry and a mesh for every square:
var geometry = new THREE.BoxGeometry( width_height, width_height, 0);
for (var i = 0; i < num_squares; i ++) {
var material = new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } );
material.emissive = new THREE.Color( Math.random(), Math.random(), Math.random() );
var object = new THREE.Mesh( geometry, material );
}
They both work quite fine for a few thousand squares. The first version can do up to one million squares, but everything over a million is just awful slow. I want to update the color and the number of squares dynamically.
Does anyone has tips on how to be more efficient with three.js/ WebGL/ Canvas?
EDIT1: Second version: This is what I do at the beginning and when the slider has changed:
// Remove all objects from scene
var obj, i;
for ( i = scene.children.length - 1; i >= 0 ; i -- ) {
obj = scene.children[ i ];
if ( obj !== camera) {
scene.remove(obj);
}
}
// Fill scene with new objects
num_squares = gui_dat.squareNum;
var window_pixel = window.innerWidth * window.innerHeight;
var pixel_per_square = window_pixel / num_squares;
var width_height = Math.floor(Math.sqrt(pixel_per_square));
var geometry = new THREE.BoxGeometry( width_height, width_height, 0);
var pos_x = width_height/2;
var pos_y = width_height/2;
for (var i = 0; i < num_squares; i ++) {
//var object = new THREE.Mesh( geometry, );
var material = new THREE.Material()( { color: Math.random() * 0xffffff } );
material.emissive = new THREE.Color( Math.random(), Math.random(), Math.random() );
var object = new THREE.Mesh( geometry, material );
object.position.x = pos_x;
object.position.y = pos_y;
pos_x += width_height;
if (pos_x > window.innerWidth) {
pos_x = width_height/2;
pos_y += width_height;
}
scene.add( object );
}
The fastest way to draw squares is to use the gl.POINTS primitive and then setting gl_PointSize to the pixel size.
In three.js, gl.POINTS is wrapped inside the THREE.PointCloud object.
You'll have to create a geometry object with one position for each point and pass that to the PointCloud constructor.
Here is an example of THREE.PointCloud in action:
http://codepen.io/seanseansean/pen/EaBZEY
geometry = new THREE.Geometry();
for (i = 0; i < particleCount; i++) {
var vertex = new THREE.Vector3();
vertex.x = Math.random() * 2000 - 1000;
vertex.y = Math.random() * 2000 - 1000;
vertex.z = Math.random() * 2000 - 1000;
geometry.vertices.push(vertex);
}
...
materials[i] = new THREE.PointCloudMaterial({size:size});
particles = new THREE.PointCloud(geometry, materials[i]);
I didn't dig through all the code but I've set the particle count to 2m and from my understanding, 5 point clouds are generated so 2m*5 = 10m particles and I'm getting around 30fps.
The highest number of individual points I've seen so far was with potree.
http://potree.org/, https://github.com/potree
Try some demo, I was able to observe 5 millions of points in 3D at 20-30fps. I believe this is also current technological limit.
I didn't test potree on my own, so I cant say much about this tech. But there is data convertor and viewer (threejs based) so should only figure out how to convert the data.
Briefly about your question
The best way handle large data is group them as quad-tree (2d) or oct-tree (3d). This will allow you to not bother program with part that is too far from camera or not visible at all.
On the other hand, program doesnt like when you do too many webgl calls. Try to understand it like this, you want to do create ~60 images each second. But each time you set some parameter for GPU, program must do some sync. Spliting data means you will need to do more setup so tree must not be too detialed.
Last thing, someone said:
You'll probably want to pass an array of values as one of the shader uniforms
I dont suggest it, bad idea. Texture lookup is quite fast, but attributes are always faster. If we are talking about 4M points, you cant afford reading data from uniforms.
Sorry I cant help you with the code, I could do it without threejs, Im not threejs expert :)
I would recommend trying pixi framework( as mentioned in above comments ).
It has webgl renderer and some benchmarks are very promising.
http://www.goodboydigital.com/pixijs/bunnymark_v3/
It can handle allot of animated sprites.
If your app only displays the squares, and doesnt animate, and they are very simple sprites( only one color ) then it would give better performance than the demo link above.
This is my second time using three.js and I've been playing around for at least 3 hours. I cannot seem to find a direction.
What I should build is something like this:
https://www.g-star.com/nl_nl/newdenimarrivals
I created the scene and everything, but I cannot seem to find a formula or anything on how to arrange the products like that (not to mention that I have to handle click events afterwards and move the camera to that product).
Do you guys have any leads or anything?
EDIT:
This is how I try to arrange the products.
arrangeProducts: function () {
var self = this;
this.products.forEach(function (element, index) {
THREE.ImageUtils.crossOrigin = '';
element.image = 'http://i.imgur.com/CSyFaYS.jpg';
//texture
var texture = THREE.ImageUtils.loadTexture(element.image, null);
texture.magFilter = THREE.LinearMipMapLinearFilter;
texture.minFilter = THREE.LinearMipMapLinearFilter;
//material
var material = new THREE.MeshBasicMaterial({
map: texture
});
//plane geometry
var geometry = new THREE.PlaneGeometry(element.width, element.height);
//plane
var plane = new THREE.Mesh(geometry, material);
plane.overdraw = true;
//set the random locations
/*plane.position.x = Math.random() * (self.container.width - element.width);
plane.position.y = Math.random() * (self.container.height - element.height);*/
plane.position.z = -2500 + (Math.random() * 50) * 50;
plane.position.x = Math.random() * self.container.width - self.container.width / 2;
plane.position.y = Math.random() * 200 - 100;
//add the plane to the scene
self.scene.add(plane);
});
},
EDIT 2:
I figured out: I need to add about 5 transparent concentric cilinders and put the products on each (random location) and have the camera in the center of all the cilinders and just rotate. Buut, how do I put the images on the cilinider randomly? I really have a blockout on that
On the three.js website you find a whole bunch of examples that can show you what is possible and how to do it. Don't expect to be an expert in only 3 hours.
I'm trying to create a long corridor with a repeating texture. How do I add a repeating texture and rotate a object (in this case a plane) at right angles to create the corridor wall's and ceiling?
var texture, material, plane;
texture = THREE.ImageUtils.loadTexture( "../img/texture.jpg" );
texture.wrapT = THREE.RepeatWrapping; // This doesn't seem to work;
material = new THREE.MeshLambertMaterial({ map : texture });
plane = new THREE.Mesh(new THREE.PlaneGeometry(400, 3500), material);
plane.doubleSided = true;
plane.position.x = 100;
plane.rotation.z = 2; // Not sure what this number represents.
scene.add(plane);
For an example of a repeating texture, check out the source of the example at:
http://stemkoski.github.com/Three.js/Texture-Repeat.html
I recommend the following changes to your code:
var texture, material, plane;
texture = THREE.ImageUtils.loadTexture( "../img/texture.jpg" );
// assuming you want the texture to repeat in both directions:
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
// how many times to repeat in each direction; the default is (1,1),
// which is probably why your example wasn't working
texture.repeat.set( 4, 4 );
material = new THREE.MeshLambertMaterial({ map : texture });
plane = new THREE.Mesh(new THREE.PlaneGeometry(400, 3500), material);
plane.material.side = THREE.DoubleSide;
plane.position.x = 100;
// rotation.z is rotation around the z-axis, measured in radians (rather than degrees)
// Math.PI = 180 degrees, Math.PI / 2 = 90 degrees, etc.
plane.rotation.z = Math.PI / 2;
scene.add(plane);
Was searching for solution without duplicating all my geometry.
Here you go ladies and gentlemen...
var materials = [new THREE.MeshBasicMaterial({map: texture, side: THREE.FrontSide}),
new THREE.MeshBasicMaterial({map: textureBack, side: THREE.BackSide})];
var geometry = new THREE.PlaneGeometry(width, height);
for (var i = 0, len = geometry.faces.length; i < len; i++) {
var face = geometry.faces[i].clone();
face.materialIndex = 1;
geometry.faces.push(face);
geometry.faceVertexUvs[0].push(geometry.faceVertexUvs[0][i].slice(0));
}
scene.add(new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials)));
BOOM a Two Faced Plane for ya, the loop will also work with geometries with more faces, replicating each face and applying the BackSide texture to it.
Enjoy!
I was looking for the same thing and you've just used the property THREE.DoubleSide on the wrong object. You should use it on the material rather than on the mesh itself:
material.side = THREE.DoubleSide;
...nothing more !
Update 2019: Imageutil.loadTexture is deprecated,
Use THREE.TextureLoader() instead
new THREE.TextureLoader().load(
WOOD,
//use texture as material Double Side
texture => {
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.offset.x = 90/(2*Math.PI);
var woodMaterial = new THREE.MeshPhongMaterial({
map: texture,
side: THREE.DoubleSide
});
// Add Ground
groundMesh = new THREE.Mesh(
new THREE.PlaneGeometry(GRID_SIZE, GRID_SIZE, 32),
woodMaterial
);
//rotate
groundMesh.rotation.x = Math.PI / 2;
this.scene.add(groundMesh);
}
);