voxel/region.js

97 lines
2.8 KiB
JavaScript

export const Region =
{
I(inX, inY, inZ)
{
return inX + inY*16 + inZ*256;
},
XYZ(inI)
{
let zWhole = Math.floor(inI / 256);
let zPart = inI % 256;
let yWhole = Math.floor(zPart / 16);
let yPart = zPart % 16;
return [yPart, yWhole, zWhole];
},
Surface(inVoxels)
{
function Vert(a)
{
var vertPointer = voxPointVert[a]
if(vertPointer === undefined)
{
let vert = Region.XYZ(a);
vertPointer = vertices.length;
voxPointVert[a] = vertPointer;
vertPointNeighbors.push([]);
vertices.push(vert);
}
return vertPointer;
}
function Face(a, b, c, d)
{
let p1 = Vert(a);
let p2 = Vert(b);
let p3 = Vert(c);
let p4 = Vert(d);
triPointVert.push(p1, p2, p3, p3, p4, p1);
vertPointNeighbors[p1].push(p2);
vertPointNeighbors[p2].push(p1);
vertPointNeighbors[p2].push(p3);
vertPointNeighbors[p3].push(p2);
vertPointNeighbors[p3].push(p4);
vertPointNeighbors[p4].push(p3);
vertPointNeighbors[p4].push(p1);
vertPointNeighbors[p1].push(p2);
}
var vertices = [];
var voxPointVert = [];
var triPointVert = [];
var vertPointNeighbors = [];
var i;
var BA, BU, BC, BR, TA, TU, TC, TR, CL, CD, CB;
for(i=0; i<inVoxels.length; i++)
{
if(inVoxels[i])
{
let [x, y, z] = Region.XYZ(i);
console.log("at", x, y, z);
// 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); }
if(!inVoxels[BR]){ Face(BC, BR, TR, TC); }
if(!inVoxels[TA]){ Face(TA, TU, TC, TR); }
if(!inVoxels[CL]){ Face(BA, BU, TU, TA); }
if(!inVoxels[CD]){ Face(BR, BA, TA, TR); }
if(!inVoxels[CB]){ Face(BA, BU, BC, BR); }
}
}
return {vert:new Float32Array(vertices.flat()), voxPointVert, triPointVert, vertPointNeighbors};
}
};