Compare commits

..

18 Commits

Author SHA1 Message Date
c101c2f2f8 rebuild everything works 2022-04-10 18:22:48 -04:00
594c6ac8dc normals helper 2022-04-10 16:58:27 -04:00
d62a1e7357 fixed
they're now unified, but flipped :P
2022-04-10 15:55:39 -04:00
c3f29258be normals
trying to figure out whats going on with the random normal directions.
2022-04-10 15:43:43 -04:00
da9be04163 start jsdoc, reorganize 2022-04-10 12:42:24 -04:00
45a482e5e1 click-create voxels 2021-07-15 14:41:17 -04:00
b630e26cfd smoothing limiter exact clip 2021-07-12 10:40:31 -04:00
9dc5b911fa surface smoothing started 2021-07-12 09:05:15 -04:00
f77b50cac9 fixed missing neighbor bug 2021-07-11 18:28:00 -04:00
20e8d90ec3 add light to show back 2021-07-11 16:44:34 -04:00
4078e026ef fix incorrect fills 2021-07-11 10:00:38 -04:00
56147ed325 surface rendering 2021-07-11 09:24:39 -04:00
13b0384c54 face and neighbor creation 2021-07-10 11:34:01 -04:00
72e33a6256 only neighbors 2021-07-10 10:11:56 -04:00
7611192683 direct modification 2021-07-07 15:01:21 -04:00
c419dca58f constraints working 2021-07-07 12:09:52 -04:00
9e5ea8098c smoothing works 2021-07-07 07:26:21 -04:00
dc2f826688 averaging started 2021-07-07 07:00:50 -04:00
5 changed files with 420 additions and 180 deletions

170
app.js Normal file
View File

@ -0,0 +1,170 @@
// @ts-check
import * as T from 'three';
import { VertexNormalsHelper } from 'three/examples/jsm/helpers/VertexNormalsHelper.js';
import { Scene } from './scene.js';
import Region from "./region.js";
let voxels = [];
voxels[Region.I(0, 0, 0)] = true;
voxels[Region.I(1, 0, 0)] = true;
voxels[Region.I(1, 1, 0)] = true;
voxels[Region.I(1, 2, 0)] = true;
let surfaceCubeGeometry = new T.BufferGeometry();
surfaceCubeGeometry.setAttribute("position", new T.BufferAttribute(new Float32Array(), 3));
let surfaceCubeObject = new T.Mesh(
surfaceCubeGeometry,
new T.MeshPhongMaterial({color:0x666666, wireframe:false, flatShading:false, side:T.BackSide})
);
let surfaceCubeNormalHelper;
let rebuildSurface = inVoxels =>
{
let { pos, ind } = Region.Surface(inVoxels);
let surfaceCubePositions = new T.BufferAttribute(pos, 3);
surfaceCubePositions.setUsage( T.DynamicDrawUsage );
surfaceCubeGeometry.dispose();
surfaceCubeGeometry = new T.BufferGeometry();
surfaceCubeGeometry.setAttribute("position", surfaceCubePositions);
surfaceCubeGeometry.setIndex(ind);
surfaceCubeGeometry.computeVertexNormals();
surfaceCubeObject.geometry = surfaceCubeGeometry;
};
rebuildSurface(voxels);
surfaceCubeNormalHelper = new VertexNormalsHelper( surfaceCubeObject, -0.2 );
const hitHelper = new T.Mesh
(
new T.BoxGeometry( 0.2, 0.2, 0.2 ),
new T.MeshBasicMaterial( {color: 0x00ff00} )
);
Scene({
DOM:"canvas",
Init(inScene)
{
let light = new T.PointLight(0xffffff, 1, 100)
light.position.set(5, 5, -5);
inScene.add(light);
inScene.add(surfaceCubeObject);
//inScene.add(new T.GridHelper(10, 10));
inScene.add(new T.AxesHelper( 5 ));
inScene.add( hitHelper );
inScene.add( surfaceCubeNormalHelper );
},
Update(inScene, inScreen, inDelta)
{
var i, hits, hit, index;
if(inScreen.Drag > 0)
{
hits = inScreen.Ray.intersectObject(surfaceCubeObject);
if(hits.length)
{
hit = hits[0];
for(i=1; i<hits.length; i++)
{
if(hits[i].distance < hit.distance)
{
hit = hits[i];
}
}
index = Region.I(Math.floor(hit.point.x), Math.floor(hit.point.y), Math.floor(hit.point.z));
voxels[index] = true;
rebuildSurface(voxels);
inScene.remove(surfaceCubeNormalHelper);
surfaceCubeNormalHelper = new VertexNormalsHelper( surfaceCubeObject, -0.2 );
inScene.add(surfaceCubeNormalHelper);
hitHelper.position.set(hit.point.x, hit.point.y, hit.point.z);
console.log(index, hit);
}
}
}
});
/* old smoothng functions
let limit = (x, y, z, ax, ay, az) =>
{
let centerX = Math.round(x);
let centerY = Math.round(y);
let centerZ = Math.round(z);
let deltaX = ax-centerX;
let deltaY = ay-centerY;
let deltaZ = az-centerZ;
let absDeltaX = Math.abs(deltaX);
let absDeltaY = Math.abs(deltaY);
let absDeltaZ = Math.abs(deltaZ);
let max = absDeltaX;
if(absDeltaY > max){ max = absDeltaY; }
if(absDeltaZ > max){ max = absDeltaZ; }
let lerp = 0.49/max;
if(lerp <= 1)
{
return [
centerX + deltaX*lerp,
centerY + deltaY*lerp,
centerZ + deltaZ*lerp
];
}
else
{
return [ax, ay, az];
}
}
let average = (inArray, inPointInd, inOthersIndArray) =>
{
let sum = [0, 0, 0];
for(let i=0; i<inOthersIndArray.length; i++)
{
let otherInd = inOthersIndArray[i]*3;
sum[0] += inArray[otherInd+0];
sum[1] += inArray[otherInd+1];
sum[2] += inArray[otherInd+2];
}
let pointX = inPointInd*3 + 0;
let pointY = inPointInd*3 + 1;
let pointZ = inPointInd*3 + 2;
let reducer = inOthersIndArray.length;
let limited = limit(inArray[pointX], inArray[pointY], inArray[pointZ], sum[0]/reducer, sum[1]/reducer, sum[2]/reducer);
inArray[pointX] = limited[0];
inArray[pointY] = limited[1];
inArray[pointZ] = limited[2];
};
let smooth = (inVertsArray, inNeighborsArray, inTimes) =>
{
let count = inVertsArray.length/3;
for(let t=0; t<inTimes; t++)
{
for(let i=0; i<count; i++)
{
average(inVertsArray, i, inNeighborsArray[i]);
}
}
return inVertsArray;
}
*/

View File

@ -19,123 +19,12 @@
</head>
<body>
<canvas></canvas>
<script type="module">
import * as T from 'http://esm.sh/three';
import { OrbitControls } from 'http://esm.sh/three/examples/jsm/controls/OrbitControls.js';
import { Region, Kernel } from "./region.js";
const renderer = new T.WebGLRenderer({canvas:document.querySelector("canvas")});
const scene = new T.Scene();
const camera = new T.PerspectiveCamera(80, 2, 0.1, 10);
const light = new T.DirectionalLight(0xFFFFFF, 1);
const geometry = new T.BoxGeometry(0.8, 0.8, 0.8);
const shader = new T.MeshPhongMaterial({color:0xFFCC00});
const shaderBlue = new T.MeshPhongMaterial({color:0x0033FF});
const object = new T.Mesh(geometry, shader);
const controls = new OrbitControls(camera, renderer.domElement);
controls.update();
scene.add(light);
scene.add(object);
scene.add(new T.GridHelper(10, 10));
const geoBuff = new T.BufferGeometry();
geoBuff.setAttribute("position", new T.BufferAttribute(new Float32Array(
[
0, 0, 0,
1, 0, 0,
1, 1, 0,
0, 1, 0,
2, 0, 1,
2, 1, 1
]
), 3));
geoBuff.setIndex(
[
0, 1, 2,
2, 3, 0,
1, 4, 5,
5, 2, 1
]
);
geoBuff.computeVertexNormals();
const geoObj = new T.Mesh(geoBuff, shader);
shader.shading = T.FlatShading;
scene.add(geoObj);
/*
let r = Region.Create();
let filler = (x, y, z) =>
{
r.Voxels[Region.CoordsToIndex(x, y, z)] = true;
};
filler(1, 1, 1);
Kernel.Loop(Kernel.Corners, [1, 1, 1], filler);
Kernel.Loop(Kernel.Cardinal, [1, 1, 1], filler);
Region.Update(r);
r.Filled.forEach((inIndexMap) =>
{
let coords = Region.IndexToCoords(inIndexMap);
let cube = new T.Mesh(geometry, shader);
cube.position.set(...coords);
scene.add(cube);
});
r.Surface.forEach((inIndexMap) =>
{
let coords = Region.IndexToCoords(inIndexMap);
let cube = new T.Mesh(geometry, shaderBlue);
cube.position.set(...coords);
scene.add(cube);
});
*/
light.position.set(-1, 2, 4);
camera.position.set(0, 0, 2);
let dirty = false;
const update = inTime =>
{
let timeNew = new Date();
let timeDelta = timeNew - inTime;
let delta = timeDelta * 0.001;
object.rotation.x += delta;
controls.update();
dirty = true;
setTimeout(()=>update(timeNew), 100);
}
const render = inTime =>
{
if(dirty)
{
renderer.render(scene, camera);
dirty = false;
}
requestAnimationFrame(render);
}
const resize = () =>
{
let canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
};
window.addEventListener("resize", resize);
resize();
render(0);
update(new Date());
</script>
<script type="importmap">
{"imports": {
"three": "https://esm.sh/three",
"three/": "https://esm.sh/three/"
}}
</script>
<script type="module" src="app.js"></script>
</body>
</html>

199
region.js
View File

@ -1,53 +1,14 @@
export const Kernel =
{
Corners:
[
[ 1, 1, -1],
[ 1, -1, -1],
[-1, 1, -1],
[-1, -1, -1],
[ 1, 1, 1],
[ 1, -1, 1],
[-1, 1, 1],
[-1, -1, 1]
],
Cardinal:
[
[ 1, 0, 0],
[ 0, 1, 0],
[-1, 0, 0],
[ 0, -1, 0],
[ 0, 0, 1],
[ 0, 0, -1]
],
//@ ts-check
Loop(inList, inVector, inHandler)
{
for(let i=0; i<inList.length; i++)
{
let delta = inList[i];
if(inHandler(inVector[0]+delta[0], inVector[1]+delta[1], inVector[2]+delta[2]))
{
return;
}
}
}
};
export const Region =
const Region =
{
Create()
{
return {
Voxels:[],
Filled:[],
Surface:[]
};
},
CoordsToIndex(inX, inY, inZ)
/** @type {Region.CoordsToIndex} */
I(inX, inY, inZ)
{
return inX + inY*16 + inZ*256;
},
IndexToCoords(inI)
/** @type {Region.IndexToCoords} */
XYZ(inI)
{
let zWhole = Math.floor(inI / 256);
let zPart = inI % 256;
@ -55,27 +16,141 @@ export const Region =
let yPart = zPart % 16;
return [yPart, yWhole, zWhole];
},
Update(inRegion)
/** @type {Region.BufferBuilder} */
Surface(inVoxels)
{
inRegion.Filled = [];
inRegion.Surface = [];
var i;
for(i=0; i<inRegion.Voxels.length; i++)
var vertices = []; // output position buffer
var triPointVert = []; // output index buffer
var vertPointNeighbors = []; // vertex array, contains arrays of integer pointers to vertices
var voxPointVert = []; // for each inVoxel; integer pointer to vertices output buffer
/*
inVoxels
|
[1 to 1]
|
voxPointVert---[optional pointers to]---> vertices <---- triPointVert
|
[1 to 1]
|
vertPointNeighbors
*/
/** @type {(voxIndex:number)=>[number, boolean]} */
function Vert(inVoxIndex)
{
if(inRegion.Voxels[i])
/*
If not preexisting, create a vertex with the coordinates of the voxel at `voxPointVert[inVoxIndex]`.
Add the new vertex to `vertices`.
Initialize empty neighbor connections.
Put the *index* of new vertex back in the voxel array at `inVoxIndex`
Return the vertex *index*, plus a flag if a vertex was already there.
Impure refs: voxPointVert, vertPointNeighbors, vertices
*/
var vertPointer = voxPointVert[inVoxIndex]
if(vertPointer === undefined)// is there no vertex for this voxel?
{
let coords = Region.IndexToCoords(i);
Kernel.Loop(Kernel.Corners, coords, (inX, inY, inZ)=>
{
let offsetIndex = Region.CoordsToIndex(inX, inY, inZ);
if(!inRegion.Voxels[offsetIndex])
{
inRegion.Surface.push(i);
return true;
}
});
vertPointer = vertices.length;
voxPointVert[inVoxIndex] = vertPointer;
vertPointNeighbors.push([]);
vertices.push(Region.XYZ(inVoxIndex));
return [vertPointer, false];
}
else
{
return [vertPointer, true];
}
}
console.log("looped over", i);
function Edge(vert1, vert1WasFull, vert2, vert2WasFull)
{
/*
Sets up neighbor relationships between vert1 and vert2.
Contains a check for if they have already been connected.
Impure refs: vertPointNeighbors
*/
let p1Neighbors = vertPointNeighbors[vert1];
let p2Neighbors = vertPointNeighbors[vert2];
// if the two verts were already filled
if((vert1WasFull && vert2WasFull))
{
// it's possible that they are already connected
if(p1Neighbors.indexOf(vert2) !== -1)
{
// quit if they are
return;
}
}
p1Neighbors.push(vert2);
p2Neighbors.push(vert1);
}
function Face(a, b, c, d /* vox indices */)
{
let [p1, p1WasFull] = Vert(a);
let [p2, p2WasFull] = Vert(b);
let [p3, p3WasFull] = Vert(c);
let [p4, p4WasFull] = Vert(d);
triPointVert.push(p1, p2, p3, p3, p4, p1);
Edge(p1, p1WasFull, p2, p2WasFull);
Edge(p2, p2WasFull, p3, p3WasFull);
Edge(p3, p3WasFull, p4, p4WasFull);
Edge(p4, p4WasFull, p1, p1WasFull);
}
var i;
var x, y, z;
var BA, BU, BC, BR, TA, TU, TC, TR, CL, CD, CB;
for(i=0; i<inVoxels.length; i++)
{
if(inVoxels[i])
{
[x, y, z] = Region.XYZ(i);
// bottom: at, "up", corner, right
BA = i;
BU = Region.I(x, y+1, z );
BC = Region.I(x+1, y+1, z );
BR = Region.I(x+1, y, z );
// top: at, "up" corner, right
TA = Region.I(x, y, z+1);
TU = Region.I(x, y+1, z+1);
TC = Region.I(x+1, y+1, z+1);
TR = Region.I(x+1, y, z+1);
// check: left, "down", below
CL = Region.I(x-1, y, z );
CD = Region.I(x, y-1, z );
CB = Region.I(x, y, z-1);
if(!inVoxels[BU]){ Face(BU, BC, TC, TU); } // XZ (away from origin)
if(!inVoxels[BR]){ Face(BC, BR, TR, TC); } // YZ (away from origin)
if(!inVoxels[TA]){ Face(TA, TU, TC, TR); } // XY (away from origin)
if(!inVoxels[CL]){ Face(BA, BU, TU, TA); } // YZ (touches the origin)
if(!inVoxels[CD]){ Face(BR, BA, TA, TR); } // XZ (touches the origin)
if(!inVoxels[CB]){ Face(BU, BA, BR, BC); } // XY (touches the origin)
}
}
return {
pos: new Float32Array(vertices.flat()),
ind: triPointVert
};
}
};
export default Region;

96
scene.js Normal file
View File

@ -0,0 +1,96 @@
import * as T from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
export function Scene(inSettings)
{
const renderer = new T.WebGLRenderer({canvas:document.querySelector(inSettings.DOM)});
const scene = new T.Scene();
const camera = new T.PerspectiveCamera(80, 2, 0.1, 100);
const light = new T.DirectionalLight(0xFFFFFF, 1);
const controls = new OrbitControls(camera, renderer.domElement);
let dirty = false;
const Screen = {
Dirty:false,
Drag:0,
Down:false,
Ray:new T.Raycaster(),
Mouse:new T.Vector2(),
Camera:camera,
Event:null,
Update:e=>
{
Screen.Event = e;
Screen.Dirty = true;
Screen.Mouse.x = ( e.clientX / renderer.domElement.clientWidth ) * 2 - 1;
Screen.Mouse.y = - ( e.clientY / renderer.domElement.clientHeight ) * 2 + 1;
Screen.Ray.setFromCamera( Screen.Mouse, Screen.Camera );
},
HandleMove:e=>
{
Screen.Drag = Screen.Down ? 2 : 0;
Screen.Update(e);
},
HandlePress:e=>
{
Screen.Down = true;
Screen.Drag = 1;
Screen.Update(e);
},
HandleRelease:e=>
{
Screen.Down = false;
Screen.Drag = 0;
Screen.Update(e);
}
};
renderer.domElement.addEventListener("pointermove", Screen.HandleMove);
renderer.domElement.addEventListener("pointerdown", Screen.HandlePress);
renderer.domElement.addEventListener("pointerup", Screen.HandleRelease);
const update = inTime =>
{
let timeNew = new Date();
let timeDelta = timeNew - inTime;
let delta = timeDelta * 0.001;
inSettings.Update(scene, Screen, delta);
Screen.Dirty = false;
controls.update();
dirty = true;
setTimeout(()=>update(timeNew), 50);
}
const render = inTime =>
{
if(dirty)
{
renderer.render(scene, camera);
dirty = false;
}
requestAnimationFrame(render);
}
const resize = () =>
{
let canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);
};
scene.add(light);
light.position.set(-1, 2, 4);
camera.position.set(-1, 2, -1);
camera.lookAt(new T.Vector3(0,0,0));
controls.update();
inSettings.Init(scene);
window.addEventListener("resize", resize);
resize();
render(0);
update(new Date());
};

10
types.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
module Region
{
type Voxels = Array<boolean>;
type Coords = [number, number, number]
type Index = number
type IndexToCoords = (index:Index)=> Coords
type CoordsToIndex = (x:number, y:number, z:number)=> Index
type BufferParts = { pos:Array<number>, ind:Array<number> }
type BufferBuilder = (voxels:Voxels)=>BufferParts
}