ThreeJS: Find neighbor faces in PlaneBufferGeometry - javascript

I'm looking for a better/faster way to find the neighbor faces (that share the same edge) in my PlaneBufferGeometry. Currently my THREE.Raycaster intersects fine with my object (using intersectObject). But I need to find all surrounding faces.
At this moment I use the following dirty way to find the 'next door' faces. It works well in my scenario, but doesn't feel right:
let rc = new THREE.Raycaster();
let intersects = [];
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
let v = new THREE.Vector3(x + i, y, z + j);
rc.set(v, new THREE.Vector3(0, -1, 0));
rc.near = 0;
rc.far = 2;
let subIntersects = rc.intersectObject(mesh);
for (let n = 0; n < subIntersects.length; n++) {
intersects.push(subIntersects[n]);
}
}
}
Is there for instance a way to quickly find these faces in the mesh.geometry.attributes.position.array?
Any suggestions are welcome. Thanks in advance!

You mentioned 50k items in the position array. That doens't seem too slow to me. This example is only 10x10 so 100 items in the array so it's easy to see it's working, but I had it set to 200x200 which is 40k items and it seemed fast enough?
'use strict';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 60;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 200;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 1;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#444');
scene.add(camera);
const planeGeometry = new THREE.PlaneBufferGeometry(1, 1, 20, 20);
const material = new THREE.MeshBasicMaterial({color: 'blue'});
const plane = new THREE.Mesh(planeGeometry, material);
scene.add(plane);
const edgeGeometry = new THREE.BufferGeometry();
const positionNumComponents = 3;
edgeGeometry.setAttribute('position', planeGeometry.getAttribute('position'));
edgeGeometry.setIndex([]);
const edgeMaterial = new THREE.MeshBasicMaterial({
color: 'yellow',
wireframe: true,
depthTest: false,
});
const edges = new THREE.Mesh(edgeGeometry, edgeMaterial);
scene.add(edges);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
class PickHelper {
constructor() {
this.raycaster = new THREE.Raycaster();
}
pick(normalizedPosition, scene, camera, time) {
// cast a ray through the frustum
this.raycaster.setFromCamera(normalizedPosition, camera);
// get the list of objects the ray intersected
const intersectedObjects = this.raycaster.intersectObjects(scene.children, [plane]);
if (intersectedObjects.length) {
// pick the first object. It's the closest one
const intersection = intersectedObjects[0];
const faceIndex = intersection.faceIndex;
const indexAttribute = planeGeometry.getIndex();
const indices = indexAttribute.array;
const vertIds = indices.slice(faceIndex * 3, faceIndex * 3 + 3);
const neighbors = []; // note: self will be added to list
for (let i = 0; i < indices.length; i += 3) {
for (let j = 0; j < 3; ++j) {
const p0Ndx = indices[i + j];
const p1Ndx = indices[i + (j + 1) % 3];
if ((p0Ndx === vertIds[0] && p1Ndx === vertIds[1]) ||
(p0Ndx === vertIds[1] && p1Ndx === vertIds[0]) ||
(p0Ndx === vertIds[1] && p1Ndx === vertIds[2]) ||
(p0Ndx === vertIds[2] && p1Ndx === vertIds[1]) ||
(p0Ndx === vertIds[2] && p1Ndx === vertIds[0]) ||
(p0Ndx === vertIds[0] && p1Ndx === vertIds[2])) {
neighbors.push(...indices.slice(i, i + 3));
break;
}
}
}
const edgeIndices = edgeGeometry.getIndex();
edgeIndices.array = new Uint16Array(neighbors);
edgeIndices.count = neighbors.length;
edgeIndices.needsUpdate = true;
}
}
}
const pickPosition = {x: 0, y: 0};
const pickHelper = new PickHelper();
clearPickPosition();
function render(time) {
time *= 0.001; // convert to seconds;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
pickHelper.pick(pickPosition, scene, camera, time);
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top,
};
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
}
function clearPickPosition() {
// unlike the mouse which always has a position
// if the user stops touching the screen we want
// to stop picking. For now we just pick a value
// unlikely to pick something
pickPosition.x = -100000;
pickPosition.y = -100000;
}
window.addEventListener('mousemove', setPickPosition);
window.addEventListener('mouseout', clearPickPosition);
window.addEventListener('mouseleave', clearPickPosition);
window.addEventListener('touchstart', (event) => {
// prevent the window from scrolling
event.preventDefault();
setPickPosition(event.touches[0]);
}, {passive: false});
window.addEventListener('touchmove', (event) => {
setPickPosition(event.touches[0]);
});
window.addEventListener('touchend', clearPickPosition);
}
main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r112/build/three.js"></script>
<canvas id="c"></canvas>
Like I mentioned in the comment. If you know it's PlaneBufferGeometry then you can look in the three.js code and see the exact layout of faces so given a faceIndex you can just compute the neighbors directly. The code above is generic, at least for BufferGeometry with an index.
Looking at the code I'm pretty sure it's
// it looks like this is the grid order for PlaneBufferGeometry
//
// b --c
// |\\1|
// |0\\|
// a-- d
const facesAcrossRow = planeGeometry.parameters.widthSegments * 2;
const col = faceIndex % facesAcrossRow
const row = faceIndex / facesAcrossRow | 0;
const neighboringFaceIndices = [];
// check left face
if (col > 0) {
neighboringFaceIndices.push(row * facesAcrossRow + col - 1);
}
// check right face
if (col < facesAcrossRow - 1) {
neighboringFaceIndices.push(row * facesAcrossRow + col + 1);
}
// check up. there can only be one up if we're in an odd triangle (b,c,d)
if (col % 2 && row < planeGeometry.parameters.heightSegments) {
// add the even neighbor in the next row
neighboringFaceIndices.push((row + 1) * facesAcrossRow + col - 1);
}
// check down. there can only be one down if we're in an even triangle (a,b,d)
if (col % 2 === 0 && row > 0) {
// add the odd neighbor in the previous row
neighboringFaceIndices.push((row - 1) * facesAcrossRow + col + 1);
}
Trying that out
'use strict';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 60;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 200;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 1;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#444');
scene.add(camera);
const planeGeometry = new THREE.PlaneBufferGeometry(1, 1, 20, 20);
const material = new THREE.MeshBasicMaterial({color: 'blue'});
const plane = new THREE.Mesh(planeGeometry, material);
scene.add(plane);
const edgeGeometry = new THREE.BufferGeometry();
const positionNumComponents = 3;
edgeGeometry.setAttribute('position', planeGeometry.getAttribute('position'));
edgeGeometry.setIndex([]);
const edgeMaterial = new THREE.MeshBasicMaterial({
color: 'yellow',
wireframe: true,
depthTest: false,
});
const edges = new THREE.Mesh(edgeGeometry, edgeMaterial);
scene.add(edges);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
class PickHelper {
constructor() {
this.raycaster = new THREE.Raycaster();
}
pick(normalizedPosition, scene, camera, time) {
// cast a ray through the frustum
this.raycaster.setFromCamera(normalizedPosition, camera);
// get the list of objects the ray intersected
const intersectedObjects = this.raycaster.intersectObjects(scene.children, [plane]);
if (intersectedObjects.length) {
// pick the first object. It's the closest one
const intersection = intersectedObjects[0];
const faceIndex = intersection.faceIndex;
const indexAttribute = planeGeometry.getIndex();
const indices = indexAttribute.array;
// it looks like this is the grid order for PlaneBufferGeometry
//
// b --c
// |\\1|
// |0\\|
// a-- d
const facesAcrossRow = planeGeometry.parameters.widthSegments * 2;
const col = faceIndex % facesAcrossRow
const row = faceIndex / facesAcrossRow | 0;
const neighboringFaceIndices = [];
// check left face
if (col > 0) {
neighboringFaceIndices.push(row * facesAcrossRow + col - 1);
}
// check right face
if (col < facesAcrossRow - 1) {
neighboringFaceIndices.push(row * facesAcrossRow + col + 1);
}
// check up. there can only be one up if we're in an odd triangle (b,c,d)
if (col % 2 && row < planeGeometry.parameters.heightSegments) {
// add the even neighbor in the next row
neighboringFaceIndices.push((row + 1) * facesAcrossRow + col - 1);
}
// check down. there can only be one down if we're in an even triangle (a,b,d)
if (col % 2 === 0 && row > 0) {
// add the odd neighbor in the previous row
neighboringFaceIndices.push((row - 1) * facesAcrossRow + col + 1);
}
const neighbors = [];
for (const faceIndex of neighboringFaceIndices) {
neighbors.push(...indices.slice(faceIndex * 3, faceIndex * 3 + 3));
}
const edgeIndices = edgeGeometry.getIndex();
edgeIndices.array = new Uint16Array(neighbors);
edgeIndices.count = neighbors.length;
edgeIndices.needsUpdate = true;
}
}
}
const pickPosition = {x: 0, y: 0};
const pickHelper = new PickHelper();
clearPickPosition();
function render(time) {
time *= 0.001; // convert to seconds;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
pickHelper.pick(pickPosition, scene, camera, time);
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top,
};
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
}
function clearPickPosition() {
// unlike the mouse which always has a position
// if the user stops touching the screen we want
// to stop picking. For now we just pick a value
// unlikely to pick something
pickPosition.x = -100000;
pickPosition.y = -100000;
}
window.addEventListener('mousemove', setPickPosition);
window.addEventListener('mouseout', clearPickPosition);
window.addEventListener('mouseleave', clearPickPosition);
window.addEventListener('touchstart', (event) => {
// prevent the window from scrolling
event.preventDefault();
setPickPosition(event.touches[0]);
}, {passive: false});
window.addEventListener('touchmove', (event) => {
setPickPosition(event.touches[0]);
});
window.addEventListener('touchend', clearPickPosition);
}
main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r112/build/three.js"></script>
<canvas id="c"></canvas>
For something more complex than a PlaneBufferGeometry
you could also pre-generate a map of faceIndexs to neighbors if the code at the top is too slow.

Related

Raycaster malfunctioning in three.js

I am creating a game where players can move around from first-person perspective, where the ground is generated with Perlin noise and therefore uneven. I would like to simulate gravity in the game. Hence, a raycasting thing has been implemented, which is supposed to find the player's distance from the ground and stop them from falling when they hit the ground. Here is my code (if the snipper is unclear visit https://3d.211368e.repl.co):
const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000000000000), renderer = new THREE.WebGLRenderer(), canvas = renderer.domElement;
camera.rotation.order = "YXZ";
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
document.body.appendChild(canvas);
const light = new THREE.DirectionalLight( 0xffffff, 1);
light.position.set(0, 10000, 0);
light.castShadow = true;
light.shadow.camera.top = 10000;
light.shadow.camera.right = 10000;
light.shadow.camera.bottom = -10000;
light.shadow.camera.left = -10000;
light.shadow.camera.far = 100000;
wwwww
scene.add(light);
var sky = new THREE.Mesh(new THREE.SphereGeometry(100000, 3, 3, 0, Math.PI, 0, Math.PI), new THREE.MeshBasicMaterial({color: 0x579ebb}));
sky.material.side = THREE.BackSide;
sky.rotateX(-Math.PI / 2);
scene.add(sky);
class Vector2{
constructor(x, y){
this.x = x;
this.y = y;
}
dot(other){
return this.x * other.x + this.y * other.y;
}
}
function Shuffle(tab){
for(let e = tab.length-1; e > 0; e--){
let index = Math.round(Math.random() * (e-1)),
temp = tab[e];
tab[e] = tab[index];
tab[index] = temp;
}
}
function MakePermutation(){
let P = [];
for(let i = 0; i < 256; i++){
P.push(i);
}
Shuffle(P);
for(let i = 0; i < 256; i++){
P.push(P[i]);
}
return P;
}
let P = MakePermutation();
function GetConstantVector(v){
let h = v & 3;
if(h == 0) return new Vector2(1.0, 1.0);
if(h == 1) return new Vector2(-1.0, 1.0);
if(h == 2) return new Vector2(-1.0, -1.0);
return new Vector2(1.0, -1.0);
}
function Fade(t){
return ((6 * t - 15) * t + 10) * t ** 3;
}
function Lerp(t, a1, a2){
return a1 + t*(a2-a1);
}
function Noise2D(x, y){
let X = Math.floor(x) & 255;
let Y = Math.floor(y) & 255;
let xf = x - Math.floor(x);
let yf = y - Math.floor(y);
let topRight = new Vector2(xf - 1, yf - 1);
let topLeft = new Vector2(xf, yf - 1);
let bottomRight = new Vector2(xf - 1, yf);
let bottomLeft = new Vector2(xf, yf);
let valueTopRight = P[P[X+1]+Y+1];
let valueTopLeft = P[P[X]+Y+1];
let valueBottomRight = P[P[X+1]+Y];
let valueBottomLeft = P[P[X]+Y];
let dotTopRight = topRight.dot(GetConstantVector(valueTopRight));
let dotTopLeft = topLeft.dot(GetConstantVector(valueTopLeft));
let dotBottomRight = bottomRight.dot(GetConstantVector(valueBottomRight));
let dotBottomLeft = bottomLeft.dot(GetConstantVector(valueBottomLeft));
let u = Fade(xf);
let v = Fade(yf);
return Lerp(u, Lerp(v, dotBottomLeft, dotTopLeft), Lerp(v, dotBottomRight, dotTopRight));
}
const plane = new THREE.Mesh(new THREE.PlaneGeometry(10000, 10000, 500, 500), new THREE.MeshPhongMaterial({color: 0x00aa00}));
plane.rotateX(-Math.PI / 2 + 0.00001);
plane.receiveShadow = true;
for (let y = 0, i = 0; y < 501; y++){
for(let x = 0; x < 501; x++, i++){
let n = 0.0, a = 1.0, f = 0.005;
for (let o = 0; o < 3; o++){
let v = a*Noise2D(x*f, y*f);
n += v;
a *= 0.5;
f *= 2.0;
}
n += 1;
n /= 2;
plane.geometry.vertices[i].z = n * 1000;
}
}
scene.add(plane);
const point = plane.geometry.vertices[Math.floor(Math.random() * 1000)];
camera.position.set(point.x, point.z + 2, point.y);
const geo = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshBasicMaterial({color: 0xff0000}));
geo.castShadow = true;
scene.add(geo);
const render = () => {
requestAnimationFrame(render);
const below = new THREE.Vector3(camera.position.x, -1000000, camera.position.y), cast = new THREE.Raycaster(camera.position, below), intersect = cast.intersectObject(plane);
if (intersect.length > 0){
if (intersect[0].distance < 3) camera.translateY(-1);
}else{
camera.translateY(-1);
}
renderer.render(scene, camera);
}
render();
onmousemove = () => {
if (camera.rotation._x > -0.8 || camera.rotation._y > -0.8){
camera.rotateX(-Math.atan(event.movementY / 300));
camera.rotateY(-Math.atan(event.movementX / 300));
}else{
if (Math.atan(event.movementY / 300) < 0) camera.rotateX(-Math.atan(event.movementY / 300));
if (Math.atan(event.movementX / 300) < 0) camera.rotateY(-Math.atan(event.movementX / 300));
}
camera.rotation.z = 0;
}
onresize = () => {
renderer.setSize(window.innerWidth, window.innerHeight);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
onkeydown = (event) => {
if (event.key == "w") camera.translateZ(-10);
if (event.key == "a") camera.translateX(-1);
if (event.key == "s") camera.translateZ(1);
if (event.key == "d") camera.translateX(1);
if (event.key == "ArrowUp") camera.translateY(1);
if (event.key == "ArrowDown") camera.translateY(-1);
}
body{
margin: 0;
background-color: black;
overflow: hidden;
}
canvas{
border: none;
}
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/utils/SceneUtils.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/libs/dat.gui.min.js"></script>
If the ground is not detected at least 3 units below the camera, the player will continue falling. However, sometimes nothing is spotted below the camera, while the player is clearly hovering over the ground. This is extremely frustrating. Is there any reliable alternative method to solve this problem, such as using something other than raycasting? Or is there a bug in the code? TIA
See the Raycaster documentation. The constructor takes the origin, the direction and near and far parameters. So you could do:
const gravityDirection = new THREE.Vector3(0, -1, 0);
cast = new THREE.Raycaster(camera.position, gravityDirection, 0, 3);
and this also makes the distance check redundant, as the far parameter already filters out hits further away than 3 units.

Pixi.js How to remove sprite after its render , how to rotate sprite

Im trying to clone this website : https://art4globalgoals.com/
Well, I've implement scratch card as below, but I can't figure out how to automatically
trigger dragging event on screen, and erase it. I've read Pixi document about renderer or sprite, but couldn't find idea about it....
I'll be very grateful if you guys give any hint or suggestion or examples about it..
Also, I want to rotate my brush depending of my movement of mouse.
The idea was to create a vector of my mouse movement, and make a dot product with vector of (1,0) then get the angle, then apply rotation by angle. but whenever I apply angle to it, result seems chaotic.
below , is my code, and results(without rotation applied , with rotation applied)
import * as PIXI from 'pixi.js';
import { Point } from '#pixi/math';
let currentVector = new Point(1, 0);
currentVector = currentVector.set(1, 0);
const screenSize = {
width: window.innerWidth,
height: window.innerHeight
};
let brushWidth = (window.innerHeight / window.innerWidth) * 150;
let brushHeight = (window.innerHeight / window.innerWidth) * 200;
const app = new PIXI.Application({
width: window.innerWidth,
height: window.innerHeight,
resolution: window.devicePixelRatio,
autoDensity: true
});
document.body.appendChild(app.view);
app.loader
.add('background', '/jpeg/mask.jpeg')
.add('mask', '/png/effel-gray.png')
.add('bristle1', '/png/brush6.png')
.add('bristle2', '/png/bristle2.png')
.load(() => {
setup();
});
const setup = () => {
const brushTexture = app.loader.resources.bristle1.texture;
// const brushTexture2 = app.loader.resources.bristle2.texture;
const brush = new PIXI.Sprite(brushTexture);
// const brush2 = new PIXI.Sprite(brushTexture2);
brush.width = brushWidth;
brush.height = brushHeight;
brush.anchor.set(0.5, 0.5);
// brush2.width = brushWidth;
// brush2.height = brushHeight;
const backgroundTexture = app.loader.resources.background.texture;
const maskTexture = app.loader.resources.mask.texture;
const background = new PIXI.Sprite(backgroundTexture);
background.x = app.renderer.screen.width / 2;
background.y = app.renderer.screen.height / 2;
background.anchor.x = 0.5;
background.anchor.y = 0.5;
background.width = window.innerWidth;
background.height = window.innerHeight;
const mask = new PIXI.Sprite(maskTexture);
mask.width = app.renderer.screen.width;
mask.height = app.renderer.screen.height;
mask.x = app.renderer.screen.width / 2;
mask.y = app.renderer.screen.height / 2;
mask.anchor.x = 0.5;
mask.anchor.y = 0.5;
mask.width = window.innerWidth;
mask.height = window.innerHeight;
app.stage.addChild(mask);
app.stage.addChild(background);
const renderTexture = PIXI.RenderTexture.create(app.screen.width, app.screen.height);
const renderTextureSprite = new PIXI.Sprite(renderTexture);
app.stage.addChild(renderTextureSprite);
background.mask = renderTextureSprite;
app.stage.interactive = true;
app.stage.on('pointerdown', pointerDown);
app.stage.on('pointerup', pointerUp);
app.stage.on('pointermove', pointerMove);
let dragging = false;
let bristle2Render = false;
let vector;
function pointerMove(event) {
if (dragging) {
brush.position.copyFrom(event.data.global);
brush.width += 1;
const vx = event.data.global.x - currentVector.x;
const vy = event.data.global.y - currentVector.y;
vector = new Point(vx, vy);
vector = vector.set(vx, vy);
const dotProd = vector.x;
const magnitude = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
const angle = Math.acos(dotProd / magnitude);
currentVector = currentVector.set(event.data.global.x, event.data.global.y);
app.renderer.render(
brush,
{
renderTexture,
transform: new PIXI.Matrix().rotate(angle),
clear: false
},
false,
null,
false
);
// if (bristle2Render) {
// brush2.position.copyFrom(event.data.global);
// app.renderer.render(brush2, renderTexture, false, null, false);
// }
// if (brush.width === 100) {
// dragging = false;
// brushWidth = 0;
// }
}
}
function pointerDown(event) {
dragging = true;
pointerMove(event);
}
function pointerUp(event) {
dragging = false;
bristle2Render = false;
brush.width = brushWidth;
}
window.addEventListener('resize', () => {
screenSize.width = window.innerWidth;
screenSize.height = window.innerHeight;
app.renderer.resize(window.innerWidth, window.innerHeight);
app.renderer.stage.width = window.innerWidth;
app.renderer.stage.height = window.innerHeight;
});
};

What is the best approach to make procedural world generation in three.js?

I have the function CreateChunk(x,z) that creates a "chunk" of terrain in the specified coordinates x and z that is a plane, whose vertex heights are modified with Perlin noise and then painted based on their height (a layer of water is added too) as you see below :
A single chunk
Everything works fine until I try to make more chunks:
Many chunks
I know this is how it should work and there is nothing wrong, but, what can I do to "synchronize" them so where one ends, the other starts? While keeping a procedural generation.
If you need the code tell me, but I was just asking for an idea to follow.
You need to know what tile you want to build and what density of noise you want to have on the tiles.
For some ideas, have a look at this forum post: https://discourse.threejs.org/t/help-getting-the-actual-position-of-a-vertices-in-a-buffer-geometry/29649/4
And I'll leave the snippet here. Maybe it will be helpful for other seekers :)
body{
overflow: hidden;
margin: 0;
}
<script type="module">
import * as THREE from "https://cdn.skypack.dev/three#0.135.0";
import {OrbitControls} from "https://cdn.skypack.dev/three#0.135.0/examples/jsm/controls/OrbitControls";
import {ImprovedNoise} from "https://cdn.skypack.dev/three#0.135.0/examples/jsm/math/ImprovedNoise";
THREE.BufferGeometry.prototype.toQuads = ToQuads;
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 1000);
camera.position.set(0, 8, 13);
let renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(innerWidth, innerHeight);
renderer.setClearColor(0x404040);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
})
const perlin = new ImprovedNoise();
let controls = new OrbitControls(camera, renderer.domElement);
let step = 20;
for(let z = -4; z <= 4; z ++){
for(let x = -4; x <= 4; x++){
let p = createPlane(step, Math.random() * 0x7f7f7f + 0x7f7f7f);
setNoise(p.geometry, new THREE.Vector2(x, z), 2, 5);
p.geometry.rotateX(Math.PI * 0.5);
p.position.set(x, 0, z).multiplyScalar(step);
scene.add(p);
}
}
renderer.setAnimationLoop( _ => {
renderer.render(scene, camera);
})
function createPlane( step, color){
let g = new THREE.PlaneGeometry(step, step, 25, 25).toQuads();
let m = new THREE.LineBasicMaterial({color: color});
let l = new THREE.LineSegments(g, m);
return l;
}
function setNoise(g, uvShift, multiplier, amplitude){
let pos = g.attributes.position;
let uv = g.attributes.uv;
let vec2 = new THREE.Vector2();
for(let i = 0; i < pos.count; i++){
vec2.fromBufferAttribute(uv, i).add(uvShift).multiplyScalar(multiplier);
pos.setZ(i, perlin.noise(vec2.x, vec2.y, 0) * amplitude );
}
}
function ToQuads() {
let g = this;
let p = g.parameters;
let segmentsX = (g.type == "TorusBufferGeometry" ? p.tubularSegments : p.radialSegments) || p.widthSegments || p.thetaSegments || (p.points.length - 1) || 1;
let segmentsY = (g.type == "TorusBufferGeometry" ? p.radialSegments : p.tubularSegments) || p.heightSegments || p.phiSegments || p.segments || 1;
let indices = [];
for (let i = 0; i < segmentsY + 1; i++) {
let index11 = 0;
let index12 = 0;
for (let j = 0; j < segmentsX; j++) {
index11 = (segmentsX + 1) * i + j;
index12 = index11 + 1;
let index21 = index11;
let index22 = index11 + (segmentsX + 1);
indices.push(index11, index12);
if (index22 < ((segmentsX + 1) * (segmentsY + 1) - 1)) {
indices.push(index21, index22);
}
}
if ((index12 + segmentsX + 1) <= ((segmentsX + 1) * (segmentsY + 1) - 1)) {
indices.push(index12, index12 + segmentsX + 1);
}
}
g.setIndex(indices);
return g;
}
</script>

Can I export point cloud in three js to ply format?

I am using Three js to generate point cloud from depth image, but I'm not able to export this point cloud in ply format. Can someone help me, this is the code.
I tried to add it with the html of this from the library of three js to export in ply but I didn't have a good result.
Please Someone can help me.
<canvas></canvas>
<style>
body {
margin: 0;
}
canvas {
width: 100vw;
height: 100vh;
display: block;
}
</style>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r94/three.min.js"></script>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r94/js/controls/OrbitControls.js"></script>
<script>
'use strict';
/* global THREE */
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = (e) => { resolve(img); };
img.onerror = reject;
img.src = url;
});
}
function getImageData(img) {
const ctx = document.createElement("canvas").getContext("2d");
ctx.canvas.width = img.width;
ctx.canvas.height = img.height;
ctx.drawImage(img, 0, 0);
return ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
}
// return the pixel at UV coordinates (0 to 1) in 0 to 1 values
function getPixel(imageData, u, v) {
const x = u * (imageData.width - 1) | 0;
const y = v * (imageData.height - 1) | 0;
if (x < 0 || x >= imageData.width || y < 0 || y >= imageData.height) {
return [0, 0, 0, 0];
} else {
const offset = (y * imageData.width + x) * 4;
return Array.from(imageData.data.slice(offset, offset + 4)).map(v => v / 255);
}
}
async function main() {
const images = await Promise.all([
loadImage("https://i.imgur.com/UKBsvV0.jpg"), // RGB
loadImage("https://i.imgur.com/arPMCZl.jpg"), // Depth
]);
const data = images.map(getImageData);
const canvas = document.querySelector('canvas');
const renderer = new THREE.WebGLRenderer({ canvas: canvas });
const fov = 75;
const aspect = 2; // the canvas default
const near = 1;
const far = 4000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2000;
const controls = new THREE.OrbitControls(camera, canvas);
controls.target.set(0, 0, 0);
controls.update();
const scene = new THREE.Scene();
const rgbData = data[0];
const depthData = data[1];
const skip = 20;
const across = Math.ceil(rgbData.width / skip);
const down = Math.ceil(rgbData.height / skip);
const positions = [];
const colors = [];
const color = new THREE.Color();
const spread = 1000;
const depthSpread = 1000;
const imageAspect = rgbData.width / rgbData.height;
for (let y = 0; y < down; ++y) {
const v = y / (down - 1); for (let x = 0; x < across; ++x) {
const u = x /
(across - 1); const rgb = getPixel(rgbData, u, v); const depth = 1 - getPixel(depthData, u, v)[0];
positions.push((u * 2 - 1) * spread * imageAspect, (v * -2 + 1) * spread, depth * depthSpread,);
colors.push(...rgb.slice(0, 3));
}
} const geometry = new THREE.BufferGeometry();
geometry.addAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
geometry.addAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
geometry.computeBoundingSphere(); const material = new THREE.PointsMaterial({
size: 15, vertexColors:
THREE.VertexColors
}); const points = new THREE.Points(geometry, material); scene.add(points); function
resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement; const
width = canvas.clientWidth; const height = canvas.clientHeight; const needResize = canvas.width !== width ||
canvas.height !== height; if (needResize) { renderer.setSize(width, height, false); } return needResize;
} function render(time) {
time *= 0.001; if (resizeRendererToDisplaySize(renderer)) {
const
canvas = renderer.domElement; camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
} renderer.render(scene, camera); requestAnimationFrame(render);
}
requestAnimationFrame(render);
} main(); </script>

How can I achieve an even distribution of sprites across the surface of a sphere in THREE.js?

I'm trying to make a database of words where the most important words are closer to the top of the sphere and the less important are further away. So I created a sphere with enough vertices for each word, created a list of those vertices in order of distance from the top of the sphere, and placed the text sprites at the positions of the vertices in order of that sorted list.
Video version: https://i.gyazo.com/aabaf0b4a26f4413dc6a0ebafab2b4bd.mp4
Sounded like a good plan in my head, but clearly the geometry of a sphere causes the words to be further spread out the further away from the top they are. I need a result that looks like a somewhat even distribution across the surface. It doesn't have to be perfect, just visually closer than this.
How can I achieve the desired effect?
Here are the relevant methods:
positionDb(db) {
console.log("mostRelated", db.mostRelated);
console.log("depthList", this.depthList);
let mostRelated = db.mostRelated;
let depthList = this.depthList;
for (let i = 0; i < mostRelated.length; i++) {
this.addTextNode(mostRelated[i].data, this.depthList[i].vertice, this.depthList[i].depth);
}
}
addTextNode(text, vert, distance) {
let fontSize = 0.5 * (600 / distance);
let sprite = new THREE.TextSprite({
fillStyle: '#000000',
fontFamily: '"Arial", san-serif',
fontSize: fontSize,
fontWeight: 'bold',
text: text
});
this.scene.add(sprite);
sprite.position.set(vert.x, vert.y, vert.z);
setTimeout(() => {
sprite.fontFamily = '"Roboto", san-serif';
}, 1000)
}
this.scene = scene;
this.geometry = new THREE.SphereGeometry(420, 50, 550);
var material = new THREE.MeshBasicMaterial({
color: 0x0011ff
});
var sphere = new THREE.Mesh(this.geometry, wireframe);
var wireframe = new THREE.WireframeGeometry(this.geometry);
let frontVert = {
x: 0,
y: 100,
z: 0
}
let depthList = [];
this.geometry.vertices.forEach(vertice => {
let depth = getDistance(frontVert, vertice);
if (depthList.length === 0) {
depthList.push({
depth,
vertice
});
} else {
let flag = false;
for (let i = 0; i < depthList.length; i++) {
let item = depthList[i];
if (depth < item.depth) {
flag = true;
depthList.splice(i, 0, {
depth,
vertice
});
break;
}
}
if (!flag) depthList.push({
depth,
vertice
});
}
});
Maybe a fibonacci sphere
function fibonacciSphere(numPoints, point) {
const rnd = 1;
const offset = 2 / numPoints;
const increment = Math.PI * (3 - Math.sqrt(5));
const y = ((point * offset) - 1) + (offset / 2);
const r = Math.sqrt(1 - Math.pow(y, 2));
const phi = (point + rnd) % numPoints * increment;
const x = Math.cos(phi) * r;
const z = Math.sin(phi) * r;
return new THREE.Vector3(x, y, z);
}
Example:
function fibonacciSphere(numPoints, point) {
const rnd = 1;
const offset = 2 / numPoints;
const increment = Math.PI * (3 - Math.sqrt(5));
const y = ((point * offset) - 1) + (offset / 2);
const r = Math.sqrt(1 - Math.pow(y, 2));
const phi = (point + rnd) % numPoints * increment;
const x = Math.cos(phi) * r;
const z = Math.sin(phi) * r;
return new THREE.Vector3(x, y, z);
}
function main() {
const fov = 75;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
const scene = new THREE.Scene();
function addTextNode(text, vert) {
const div = document.createElement('div');
div.className = 'label';
div.textContent = text;
div.style.marginTop = '-1em';
const label = new THREE.CSS2DObject(div);
label.position.copy(vert);
scene.add(label);
}
const renderer = new THREE.CSS2DRenderer();
const container = document.querySelector('#c');
container.appendChild(renderer.domElement);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
const numPoints = 50;
for (let i = 0; i < numPoints; ++i) {
addTextNode(`p${i}`, fibonacciSphere(numPoints, i));
}
function render(time) {
time *= 0.001;
// three's poor choice of how to hanlde size strikes again :(
renderer.setSize(container.clientWidth, container.clientHeight);
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
body {
margin: 0;
overflow: hidden;
}
#c {
width: 100vw;
height: 100vh;
display: block;
}
.label {
color: red;
}
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/build/three.min.js"></script>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/examples/js/renderers/CSS2DRenderer.js"></script>
<div id="c"></div>

Categories