THREE.JS: How to rotate object around its centre in vertex shader? - matrix

I have a simple THREE.Points object. Have to rotate it around its Y centre axis via shader (green line), as well as general object position. I have commented it by now, so it doesn't affect the rotation issue.
Now it has the wrong "orbital" rotation. Pretty sure that I need to play with tPos. Have tried without any success.
var stats, scene, renderer;
var camera, cameraControl, mesh;
if( !init() ) animate();
function init(){
renderer = new THREE.WebGLRenderer({
antialias : true,
preserveDrawingBuffer : true
});
renderer.setClearColor( 0xBBBBBB, 1 );
renderer.setSize( window.innerWidth, window.innerHeight );
document.getElementById('container').appendChild(renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set(0, 0, 5);
scene.add(camera);
var geometry = new THREE.BufferGeometry();
var vertices = new Float32Array( [
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, -1.0, 1.0
] );
geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
var material = new THREE.ShaderMaterial( {
side : THREE.DoubleSide,
uniforms: {
parentPosition: { value: new THREE.Vector3(0.0, 0.0, 0.0) },
rotation: { type: "f", value: 0.0 },
texture: { value: new THREE.TextureLoader().load( "assets/blob.png" ) }
},
vertexShader: document.getElementById( "vertexshader" ).textContent,
fragmentShader: document.getElementById( "fragmentshader" ).textContent,
alphaTest: 0.9
} );
mesh = new THREE.Mesh( geometry, material );
scene.add(mesh);
}
function animate() {
//mesh.material.uniforms.parentPosition.value.x += 0.01;
mesh.material.uniforms.rotation.value += 0.01;
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
body{ margin: 0px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/105/three.js"></script>
<!doctype html>
<html>
<head>
<title>three.js template</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<script type="x-shader/x-vertex" id="vertexshader">
uniform vec3 parentPosition;
uniform float rotation;
varying vec4 vColor;
varying mat4 vPosition;
void main() {
mat4 tPos = mat4(vec4(1.0,0.0,0.0,0.0),
vec4(0.0,1.0,0.0,0.0),
vec4(0.0,0.0,1.0,0.0),
vec4(0,0,0,1.0));
mat4 rYPos = mat4(vec4(cos(rotation),0.0,sin(rotation),0.0),
vec4(0.0,1.0,0.0,0.0),
vec4(-sin(rotation),0.0,cos(rotation),0.0),
vec4(0.0,0.0,0.0,1.0));
vPosition = tPos * rYPos;
vColor = vec4(1.0, 0.0, 1.0, 1.0);
vec3 newPosition = position + parentPosition;
vec4 mvPosition = modelViewMatrix * vPosition * vec4( newPosition, 1.0 );
gl_PointSize = 32.0 * ( 300.0 / -mvPosition.z );
gl_Position = projectionMatrix * mvPosition;
}
</script>
<script type="x-shader/x-fragment" id="fragmentshader">
uniform sampler2D texture;
varying vec4 vColor;
varying mat4 vPosition;
void main() {
gl_FragColor = vColor;
gl_FragColor = gl_FragColor * texture2D( texture, gl_PointCoord );
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
mat4 tPos = mat4(vec4(1.0,0.0,0.0,0.0),
vec4(0.0,1.0,0.0,0.0),
vec4(0.0,0.0,1.0,0.0),
vec4(0,0,0,1.0));
mat4 rYPos = mat4(vec4(cos(rotation),0.0,sin(rotation),0.0),
vec4(0.0,1.0,0.0,0.0),
vec4(-sin(rotation),0.0,cos(rotation),0.0),
vec4(0.0,0.0,0.0,1.0));
vPosition = tPos * rYPos;
vColor = vec4(1.0, 0.0, 1.0, 1.0);
vec3 newPosition = position + parentPosition;
vec4 mvPosition = modelViewMatrix * vPosition * vec4( newPosition, 1.0 );
Can someone help me?

It's my fault. The code works fine. Have to set all Z values to 0.0.
var vertices = new Float32Array( [
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
-1.0, -1.0, 0.0
] );

Related

Point cloud texture alpha blending (THREEJS)

I use ShaderMaterial to create point cloud with attribute based size and opacity.
I also need to texture map. The problem is that texture is rendered without transparency.
Looks like each texture pixel color is blended somehow with background color (white in this case);
How to avoid this this?
I use svg texture:
<div id="circle-texture" style="width: 0; height: 0; display: none">
<svg width="32" height="32" xmlns="http://www.w3.org/2000/svg" version="1.1">
<circle cx="16" cy="16" r="13" stroke="none" fill="white" fill-opacity="1" />
</svg>
</div>
Here is my fragment shader:
<script type="x-shader/x-fragment" id="point-cloud-fragment-shader">
...
uniform sampler2D texture;
varying vec3 vColor;
varying float vOpacity;
#include <clipping_planes_pars_fragment>
void main() {
#include <clipping_planes_fragment>
vec3 outgoingLight = vec3( 0.0 );
vec4 diffuseColor = vec4( diffuse, vOpacity );
if (enableTexture) {
vec4 mapTexel = texture2D( texture, gl_PointCoord );
diffuseColor *= mapTexelToLinear( mapTexel );
}
diffuseColor.rgb *= vColor;
outgoingLight = diffuseColor.rgb;
gl_FragColor = vec4( outgoingLight, diffuseColor.a );
}
Discarding fixes if:
if ( gl_FragColor.a < 0.001 ) discard;
But is it possible without discarding? (with custom blending or something else) I've played with custom blending but without success so far.
The setup that works when dealing with partially-transparent point-clouds is to turn transparent: true, depthTest: false and a blending mode if necessary. Additive or multiplicative blending look nice, depending on your use-case, and it removes the need to sort the depth of your sprites, since blending removes the need to place a color "in front" of the other:
const spriteMat = new THREE.ShaderMaterial({
uniforms: {
// List of uniforms
},
vertexShader: spriteVert,
fragmentShader: spriteFrag,
blending: THREE.AdditiveBlending,
depthTest: false,
transparent: true
});
Turning transparent: true respects the alpha channel in your fragment shader, so you'll no longer need to discard pixels.

Basic scene breaks transitioning from three.js v87 to v88 or v89

Does anyone know why the following breaks as three.min.js is updated from r87 to r88 or r89? This is just using fundamentals from three.js-related training webistes. With r87 or earlier, a cube is displayed. With r88 or r89, there's just a black canvas. I have tried this with Chrome, Firefox, & IE.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Demo</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="three.min.js"></script>
<script>
var renderer = null, scene = null, camera = null;
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
$(document).ready(function() {
var canvas = document.getElementById("webglcanvas");
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({canvas: canvas, antialias: true});
renderer.setSize(canvas.width, canvas.height);
camera = new THREE.PerspectiveCamera(60, canvas.width / canvas.height, 0.1, 400);
camera.position.set(60, 100, 100);
scene.add(camera);
camera.lookAt({"x": 50.0, "y": 50.0, "z": 50.0});
var light = new THREE.PointLight(0xffff00);
light.position.set(50, 50, 50);
scene.add(light);
var geometry = new THREE.BoxGeometry(50, 50, 50);
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
render();
});
</script>
</head>
<body>
<canvas id="webglcanvas" width="480" height="300"></canvas>
</body>
</html>
The following is not valid three.js code, and never has been valid three.js code:
camera.lookAt( { "x": 50.0, "y": 50.0, "z": 50.0 } );
Use
camera.lookAt( 50, 50, 50 );
or
camera.lookAt( myVector3 );
three.js r.90

Aligning a Cylinder to a vector

I'm having a hard time trying to get a cylinder aligned to a particular vector. I've seen and tried a number of possible solutions, but to no avail. My understanding is that all I should need to do is to position the cylinder at the center of the vector and use LookAt() to align it. Below I've attached a simple example of this where I add a line, then am attempting to align the cylinder to this line. Would anyone be able to tell me what I'm doing wrong? TIA
Roy
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000000;
margin: 0px;
overflow: hidden;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display: block;
}
a {
color: skyblue;
}
.button {
background: #999;
color: #eee;
padding: 0.2em 0.5em;
cursor: pointer;
}
.highlight {
background: orange;
color: #fff;
}
span {
display: inline-block;
width: 60px;
float: left;
text-align: center;
}
.left-panel{
position: absolute;
top:0px;
left: 0px;
height:100%;
width:220px;
background-color:white;
}
.right-panel{
position: absolute;
top:0px;
right: 0px;
height:100%;
width:220px;
background-color:white;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/threejs/r76/three.min.js"></script>
<script src="http://threejs.org/examples/js/Detector.js"></script>
<script src="http://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var camera, scene, raycaster, renderer, model, cylinder;
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var reader;
init();
function init() {
scene = new THREE.Scene();
scene.add(new THREE.AmbientLight(0x999999));
addLine();
addCylinder();
camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 500 );
// Z is up for objects intended to be 3D printed.
camera.up.set(0, 0, 1);
camera.position.set(8, -72, 20);
camera.rotateOnAxis('X', 25);
camera.rotateOnAxis('Z', 0.0025);
camera.add(new THREE.PointLight(0xffffff, 0.8));
scene.add(camera);
var grid = new THREE.GridHelper(200, 100, 0x229922, 0x222222);//grid
grid.rotateOnAxis(new THREE.Vector3(1, 0, 0), 90 * (Math.PI / 180));
grid.receiveShadow = true;
scene.add(grid);
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( 0x333399 );// scene background color
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild(renderer.domElement);
raycaster = new THREE.Raycaster();
raycaster.linePrecision = .05;
var controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.addEventListener( 'change', render );
controls.target.set( 0, 1.2, 2 );
controls.update();
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
render();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
function render() {
raycaster.setFromCamera(mouse, camera);
// calculate objects intersecting the picking ray
var intersects = raycaster.intersectObjects(scene.children);
renderer.render( scene, camera );
}
function addCylinder() {
//Mesh to align
var material = new THREE.MeshLambertMaterial({ color: 0x666666 });
cylinder = new THREE.Mesh(new THREE.CylinderGeometry(.2, .2, 7.5,8), material);
var vector = new THREE.Vector3(10, 0, 10);
cylinder.position.set(5, 0, 5);
//create a point to lookAt
var focalPoint = new THREE.Vector3(
cylinder.position.x + vector.x,
cylinder.position.y + vector.y,
cylinder.position.z + vector.z
);
//all that remains is setting the up vector (if needed) and use lookAt
//cylinder.up = new THREE.Vector3(0, 0, 1);//Z axis up
cylinder.lookAt(focalPoint);
scene.add(cylinder);
}
function addLine() {
var material = material = new THREE.LineBasicMaterial({ color: 0xff0000, linewidth: 1, fog: false });
var geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3(0,0,0),
new THREE.Vector3(10,0,10)
);
var line = new THREE.Line(geometry, material);
line.castShadow = true;
scene.add(line);
}
function onDocumentMouseMove(event) {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
render();
}
</script>
</body>
</html>
All you need to do is rotate the cylinder so it aligns with the z-axis instead of the y-axis.
cylinder = new THREE.Mesh( new THREE.CylinderGeometry( .2, .2, 7.5, 8 ), material );
cylinder.geometry.rotateX( Math.PI / 2 );
cylinder.geometry.translate( 0, 0, - 7.5 / 2 ); // optional
When you call object.lookAt( target ), the oject's local positive z-axis is oriented toward the target.
three.js r.82

How to correctly set the camera

I am having trouble knowing how the set the camera. What i have tried is using a example and just changing the OBJLoader url to my file
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - OBJLoader + MTLLoader</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
color: #fff;
margin: 0px;
overflow: hidden;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display:block;
}
#info a, .button { color: #f00; font-weight: bold; text-decoration: underline; cursor: pointer }
</style>
</head>
<body>
<div id="info">
three.js - OBJLoader + MTLLoader
</div>
<script src="../build/three.js"></script>
<script src="js/loaders/DDSLoader.js"></script>
<script src="js/loaders/MTLLoader.js"></script>
<script src="js/loaders/OBJLoader.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
<script src="js/controls/OrbitControls.js"></script>
<script>
var container, stats;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
render();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.z = -25;
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x444444 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
//directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( '140018_2.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load( '140018_2.obj', function ( object ) {
object.position.set(0, 0, 0);
console.log("loaded");
scene.add( object );
});
});
//
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.addEventListener( 'change', render ); // add this only if there is no animation loop (requestAnimationFrame)
controls.enableZoom = true;
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
</html>
It somewhat works. When i load the page i dont see anything. But when i zoom out, the object 'flies in' from the top left corner of my screen. All i really need is just for the object to be centered on the screen.
How are you guys achieving this? The OBJ is not created by me and its settings (height, width etc etc) can vary.
The fact that you say "the object 'flies in' from the top left corner" suggests to me that your .OBJ is not centred, as in, when it was exported from the 3D editor, it was not centred.
It will need to be centred in the 3D authoring program and exported again.

Putting image on a sphere using ShaderMaterial in three.js

I tried to put image on a sphere by using ShaderMaterial in three.js. But I only get a black sphere by my code below. What is the problem?
main.js
(function(){
var width = window.innerWidth;
var height = window.innerHeight;
//scene
var scene = new THREE.Scene();
//geo
var geometry = new THREE.SphereGeometry( 5, 60, 40 );
geometry.scale( -1, 1, 1);
//mesh
var textureLoader = new THREE.TextureLoader();
var texture = textureLoader.load('images/image.jpeg');
var uniforms = {
color: { type: "3v", value: new THREE.Vector3(0.3, 1.0, 1.0) },
texture: { type: "t", value: 0, texture: texture },
};
var material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: document.getElementById('vertexShader').textContent,
fragmentShader: document.getElementById('fragmentShader').textContent
});
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
//camera
var camera = new THREE.PerspectiveCamera(75, width / height, 1, 1000);
camera.position.set(0,0,30);
camera.lookAt(mesh.position);
//render
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width,height);
renderer.setClearColor(0xffffff);
document.getElementById('stage').appendChild(renderer.domElement);
renderer.render(scene,camera);
function render(){
requestAnimationFrame(render);
renderer.render(scene,camera);
}
render();
})();
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<div id="stage"></div>
<script src="lib/three.min.js"></script>
<script src="lib/OrbitControls.js"></script>
<script type="x-shader/x-vertex" id="vertexShader">
varying vec2 vUv;
void main(){
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
</script>
<script type="x-shader/x-fragment" id="fragmentShader">
uniform vec3 color;
uniform sampler2D texture;
varying vec2 vUv;
void main(){
vec4 samplerColor = texture2D(texture, vUv);
gl_FragColor = vec4(1.0) * samplerColor;
}
</script>
<script src="main.js"></script>
</body>
</html>
When I tried to use MeshBasicMaterial like below, it is OK. So I guess it is not a problem of asynchronous loading..
var material = new THREE.MeshBasicMaterial( {
map: texture
} );
Please help me

Resources