Log in to post a comment.
// Voxel Ray Caster. Created by Reinder Nijhoff 2020 - @reindernijhoff // The MIT License // // https://turtletoy.net/turtle/d9ae1fb0bd // // A Utility class to collect and sort all (partially) visible faces of a voxel world. // In this turtle, the faces are drawn using the Polygon Clipping utility code from // https://turtletoy.net/turtle/a5befa1f8d. // // Note that the raycaster shoots rays at a fixed sample density, so small faces can be missed. // const turtle = new Turtle(); const addHatching = 1; // min=0, max=1, step=1 (No, Yes) const drawCubeEdges = 0; // min=0, max=1, step=1 (No, Yes) const ro = [43.2,40,-41.1]; // camera origin const ta = [-4,-4.5,2]; // camera target const voxelRayCaster = new VoxelRayCaster(ro, ta, .3); // The voxel caster will cast rays into a scene that is defined by a function that // returns true for all solid cells ([x,y,z]): function map(p) { const x = Math.abs(p[0]), y = Math.abs(p[1]), z = Math.abs(p[2]); return (x%15 === 0 && (y%15 === 0 || z%15 === 0)) || (y%15 === 0 && z%15 === 0) || ((x%15 < 2 || x%15 > 13) && (y%15 < 2 || y%15 > 13) && (z%15 < 2 || z%15 > 13)); } function walk(i) { const tiles = 10; const x = i % tiles, y = (i/tiles)|0; const lt = [x*200/tiles-100, y*200/tiles-100]; // Left top of tile const rb = [(x+1)*200/tiles-100, (y+1)*200/tiles-100]; // Right bottom of tile const faces = voxelRayCaster.collectFaces(map, lt, rb, 2000, 0.3); const polys = new Polygons(); // Create a polygon for this tile to clip all faces const viewPort = polys.create(); viewPort.addPoints(lt, [lt[0], rb[1]], rb, [rb[0], lt[1]]); faces.forEach(face => { const p = polys.create(); p.addPoints(...face.points); if (drawCubeEdges) { p.addOutline(); } else { face.edges.forEach((e, i) => e && p.addSegments(p.cp[i], p.cp[(i+1)%4])); } if (addHatching && Math.abs(face.normal[2]) > .5) { p.addHatching(-Math.PI/3, .5); } // Clip face against viewport of this tile p.boolean(viewPort, false); // Draw face polys.draw(turtle, p); }); return i < tiles*tiles - 1; } //////////////////////////////////////////////////////////////// // Voxel Ray Caster utility code. Created by Reinder Nijhoff 2020 // https://turtletoy.net/turtle/d9ae1fb0bd // Based on: https://turtletoy.net/turtle/d9ae1fb0bd //////////////////////////////////////////////////////////////// function VoxelRayCaster(ro, ta, cr=0, w=1.5) { const faceId = (p, n) => p[0].toFixed(0) + '_' + p[1].toFixed(0) + '_' + p[2].toFixed(0) + n[0].toFixed(0) + '_' + n[1].toFixed(0) + '_' + n[2].toFixed(0); const neg = (a) => [-a[0], -a[1], -a[2]]; const scale = (a,b) => [a[0]*b, a[1]*b, a[2]*b]; const len = (a) => Math.sqrt(a[0]**2 + a[1]**2 + a[2]**2); const norm = (a) => scale(a,1/len(a)); const add = (a,b) => [a[0]+b[0], a[1]+b[1], a[2]+b[2]]; const sub = (a,b) => [a[0]-b[0], a[1]-b[1], a[2]-b[2]]; const cross = (a,b) => [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]]; const trans = (a,b) => a.map((e, c) => b[c]*a[0] + b[c+3]*a[1] + b[c+6]*a[2]); const transInv = (a,b) => a.map((e, c) => b[c*3+0]*a[0] + b[c*3+1]*a[1] + b[c*3+2]*a[2]); class VoxelFace { constructor(p, n, dist, map) { this.id = faceId(p,n); this.pos = p; this.normal = n; this.b = [n[1],n[2],n[0]]; this.t = cross(this.normal, this.b); this.dist = dist; this.center = add(this.pos, [.5,.5,.5]); } projectVertex(p, ca) { const cp = transInv(p, ca), s = w * 100 / cp[2]; return [cp[0] * s, cp[1] * -s]; } projectVertices(ro, ca) { const nh = scale(this.normal, .5), t=scale(this.t, .5), b=scale(this.b, .5); this.points = [add(neg(t), neg(b)), add(t, neg(b)), add(t, b), add(neg(t), b)] .map(c => this.projectVertex(sub(add(add(c, nh), this.center), ro), ca)); } calculateEdges(map) { const t=this.t, b=this.b, p=this.pos, n=this.normal; this.edges = [neg(b), t, b, neg(t)].map(o => !map(add(p, o)) || map(add(add(p, o), n))); } } class VoxelRayCaster { constructor(ro, ta, cr=0, w=1.5) { this.ro = ro; this.ta = ta; this.w = w; this.ca = this.setupCamera(ro, ta, cr); } setupCamera(ro, ta, cr) { const cw = norm(sub(ta, ro)); const cp = [Math.sin(cr), Math.cos(cr), 0]; const cu = norm(cross(cw,cp)); const cv = (cross(cu,cw)); return [...cu, ...cv, ...cw]; } castRay(ro, rd, map, maxSteps) { const ps = ro.map(e => Math.floor(e)); const ri = rd.map(e => Math.abs(e) > 1e-16 ? 1/e : 1e32); const rs = ri.map(e => Math.sign(e)); const ra = ri.map(e => Math.abs(e)); const ds = ps.map((p, i) => (p-ro[i]+.5+.5*rs[i]) * ri[i]); for (let j=0; j<maxSteps; j++) { const i = ds[0] <= ds[1] && ds[0] <= ds[2] ? 0 : ds[1] <= ds[0] && ds[1] <= ds[2] ? 1 : 2; ds[i] += ra[i]; ps[i] += rs[i]; if (map(ps)) { const n = [0,0,0]; n[i] = -rs[i]; return [ps, n]; } } return false; } collectFaces(map, tl=[-100,-100], br=[100,100], maxSteps=200, res=0.25) { const faces = []; for (let x=tl[0]; x<=br[0]; x+=res) { for (let y=tl[1]; y<=br[1]; y+=res) { const rd = trans(norm([x/100, -y/100, this.w]), this.ca); const hit = this.castRay(ro, rd, map, maxSteps); if (hit) { const id = faceId(hit[0], hit[1]); if (!faces.find(a => a.id === id)) { const face = new VoxelFace(hit[0], hit[1], len(sub(hit[0], this.ro))); face.projectVertices(this.ro, this.ca); face.calculateEdges(map); faces.push(face); } } } } return faces.sort((a, b) => a.dist - b.dist); } } return new VoxelRayCaster(ro, ta, cr, w); } //////////////////////////////////////////////////////////////// // Polygon Clipping utility code - Created by Reinder Nijhoff 2019 // https://turtletoy.net/turtle/a5befa1f8d //////////////////////////////////////////////////////////////// function Polygons() { let polygonList = []; const Polygon = class { constructor() { this.cp = []; // clip path: array of [x,y] pairs this.dp = []; // 2d lines [x0,y0],[x1,y1] to draw this.aabb = []; // AABB bounding box } addPoints(...points) { // add point to clip path and update bounding box let xmin = 1e5, xmax = -1e5, ymin = 1e5, ymax = -1e5; (this.cp = [...this.cp, ...points]).forEach( p => { xmin = Math.min(xmin, p[0]), xmax = Math.max(xmax, p[0]); ymin = Math.min(ymin, p[1]), ymax = Math.max(ymax, p[1]); }); this.aabb = [(xmin+xmax)/2, (ymin+ymax)/2, (xmax-xmin)/2, (ymax-ymin)/2]; } addSegments(...points) { // add segments (each a pair of points) points.forEach(p => this.dp.push(p)); } addOutline() { for (let i = 0, l = this.cp.length; i < l; i++) { this.dp.push(this.cp[i], this.cp[(i + 1) % l]); } } draw(t) { for (let i = 0, l = this.dp.length; i < l; i+=2) { t.jump(this.dp[i]), t.goto(this.dp[i + 1]); } } addHatching(a, d) { const tp = new Polygon(); tp.cp.push([-1e5,-1e5],[1e5,-1e5],[1e5,1e5],[-1e5,1e5]); const dx = Math.sin(a) * d, dy = Math.cos(a) * d; const cx = Math.sin(a) * 200, cy = Math.cos(a) * 200; for (let i = 0.5; i < 150 / d; i++) { tp.dp.push([dx * i + cy, dy * i - cx], [dx * i - cy, dy * i + cx]); tp.dp.push([-dx * i + cy, -dy * i - cx], [-dx * i - cy, -dy * i + cx]); } tp.boolean(this, false); this.dp = [...this.dp, ...tp.dp]; } inside(p) { let int = 0; // find number of i ntersection points from p to far away for (let i = 0, l = this.cp.length; i < l; i++) { if (this.segment_intersect(p, [0.13, -1000], this.cp[i], this.cp[(i + 1) % l])) { int++; } } return int & 1; // if even your outside } boolean(p, diff = true) { // bouding box optimization by ge1doot. if (diff && Math.abs(this.aabb[0] - p.aabb[0]) - (p.aabb[2] + this.aabb[2]) >= 0 && Math.abs(this.aabb[1] - p.aabb[1]) - (p.aabb[3] + this.aabb[3]) >= 0) return this.dp.length > 0; // polygon diff algorithm (narrow phase) const ndp = []; for (let i = 0, l = this.dp.length; i < l; i+=2) { const ls0 = this.dp[i]; const ls1 = this.dp[i + 1]; // find all intersections with clip path const int = []; for (let j = 0, cl = p.cp.length; j < cl; j++) { const pint = this.segment_intersect(ls0, ls1, p.cp[j], p.cp[(j + 1) % cl]); if (pint !== false) { int.push(pint); } } if (int.length === 0) { // 0 intersections, inside or outside? if (diff === !p.inside(ls0)) { ndp.push(ls0, ls1); } } else { int.push(ls0, ls1); // order intersection points on line ls.p1 to ls.p2 const cmpx = ls1[0] - ls0[0]; const cmpy = ls1[1] - ls0[1]; int.sort( (a,b) => (a[0] - ls0[0]) * cmpx + (a[1] - ls0[1]) * cmpy - (b[0] - ls0[0]) * cmpx - (b[1] - ls0[1]) * cmpy); for (let j = 0; j < int.length - 1; j++) { if ((int[j][0] - int[j+1][0])**2 + (int[j][1] - int[j+1][1])**2 >= 0.001) { if (diff === !p.inside([(int[j][0]+int[j+1][0])/2,(int[j][1]+int[j+1][1])/2])) { ndp.push(int[j], int[j+1]); } } } } } return (this.dp = ndp).length > 0; } //port of http://paulbourke.net/geometry/pointlineplane/Helpers.cs segment_intersect(l1p1, l1p2, l2p1, l2p2) { const d = (l2p2[1] - l2p1[1]) * (l1p2[0] - l1p1[0]) - (l2p2[0] - l2p1[0]) * (l1p2[1] - l1p1[1]); if (d === 0) return false; const n_a = (l2p2[0] - l2p1[0]) * (l1p1[1] - l2p1[1]) - (l2p2[1] - l2p1[1]) * (l1p1[0] - l2p1[0]); const n_b = (l1p2[0] - l1p1[0]) * (l1p1[1] - l2p1[1]) - (l1p2[1] - l1p1[1]) * (l1p1[0] - l2p1[0]); const ua = n_a / d; const ub = n_b / d; if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) { return [l1p1[0] + ua * (l1p2[0] - l1p1[0]), l1p1[1] + ua * (l1p2[1] - l1p1[1])]; } return false; } }; return { list: () => polygonList, create: () => new Polygon(), draw: (turtle, p, addToVisList=true) => { for (let j = 0; j < polygonList.length && p.boolean(polygonList[j]); j++); p.draw(turtle); if (addToVisList) polygonList.push(p); } }; }