Voxel Folly with AO Inverted

Based on @reinder Voxel Raycaster, but with very basic ambient occlusion

Log in to post a comment.

// Forked from "Voxel Folly with AO" by neurofuzzy
// https://turtletoy.net/turtle/6000294180

const turtle = new Turtle();
Canvas.setpenopacity(-1);

const addHatching = 1; // min=0, max=1, step=1 (No, Yes)
const drawCubeEdges = 0; // min=0, max=1, step=1 (No, Yes)

const ro = [280, 280, 280]; // camera origin
const ta = [120, 120, 120];     // camera target
const depth = 600;
const fov = 5;
const acc = 0.5;

const voxelRayCaster = new VoxelRayCaster(ro, ta, .3, fov);

// 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) {
	p = [
		Math.floor(p[0] * 0.25),
		Math.floor(p[1] * 0.25),
		Math.floor(p[2] * 0.25),
	]
	const x = Math.abs(p[0]), y = Math.abs(p[1]), z = Math.abs(p[2]);
  if (
    x > 37 ||
    y > 37 ||
    z > 37
  ) {
    return false;
  }
  if (
    x < 26 ||
    y < 26 ||
    z < 26
  ) {
    return false;
  }
	return Math.floor(x * y * z) % 7 == 0;
	return Math.floor(x * y * z) % 81 == 0;
	return Math.floor(x * y * z) % 87 == 0;
	return Math.floor(x * y * z) % 100 == 0;
	return Math.floor(x * y * z) % 119 == 0;
	return Math.floor(x * y * z) % 126 == 0;
	return Math.floor(x * y * z) % 130 == 0;
	return Math.floor(x * y * z) % 132 == 0;
	return Math.floor(x * y * z) % 155 == 0;
	return Math.floor(x * y * z) % 175 == 0;
	return Math.floor(x * y * z) % 172 == 0;
	return Math.floor(x * y * z) % 183 == 0;
	return Math.floor(x * y * z) % 184 == 0;
	return Math.floor(x * y * z) % 52 == 0;
	return Math.floor(x / y * z + z + y + x) % 57 == 0;
	return (x * y * z) % 94 == 0;
	return (x * y * z) % 69 == 0;
	return (x * y * z) % 57 == 0;
}

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, depth, acc);
    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) {
    		if (face.normal[1] > 0.5) {
    			let b = getOcclusion({
    				x:face.pos[0],
    				y:face.pos[1],
    				z:face.pos[2],
    			}, face.normal, 20, 3);
    			if (face.normal[2] > 0.5) {
    				b -= 0.25;
    			}
    			b -= (face.dist - 250) / 100;
    			if (Canvas.getopacity() < 0) b = 1 - b;
    			if (b < 1) {
    				p.addHatching(-Math.PI/4, 1, Math.floor(b * 5));
    		    }  
    		}       
        }
        
        // Clip face against viewport of this tile
        p.boolean(viewPort, false);
        
        // Draw face
        polys.draw(turtle, p);
    });

    return i < tiles*tiles - 1;
}

/**
 * 
 * @param {{ x: number, y:number, z:number }} pos
 * @param {number[]} normal 
 * @param {number} edgeBias 
 * @param {number} indirectFalloff 
 * @param {number} edgeBias
 * @param {number} gammaOffset 
 */
 function getOcclusion(pos, normal, indirectFalloff = 7, edgeBias = 0, gammaOffset = 0) {

	let f;
  let dist = Math.ceil(indirectFalloff);

	if (normal[0] < -0.5) {
		f = "left";
	}
	if (normal[0] > 0.5) {
		f = "right";
	}
	if (normal[1] > 0.5) {
		f = "front";
	}
	if (normal[1] < -0.5) {
		f = "back";
	}
	if (normal[2] > 0.5) {
		f = "top";
	}
	if (normal[2] < -0.5) {
		f = "bottom";
	}

	let facingCubes = [];

	let b = 255 + gammaOffset;
	let xmin, xmax, ymin, ymax, zmin, zmax;
	let v = pos;
	
	switch (f) {
		case "front":
			xmin = v.x - dist;
			xmax = v.x + dist;
			ymin = v.y + 1;
			ymax = v.y + dist + 1;
			zmin = v.z - dist;
			zmax = v.z + dist;
			break;
		case "back":
			xmin = v.x - dist;
			xmax = v.x + dist;
			ymin = v.y - dist - 1;
			ymax = v.y - 1;
			zmin = v.z - dist;
			zmax = v.z + dist;
			break;
		case "top":
			xmin = v.x - dist;
			xmax = v.x + dist;
			ymin = v.y - dist;
			ymax = v.y + dist;
			zmin = v.z + 1;
			zmax = v.z + dist + 1;
			break;
		case "bottom":
			xmin = v.x - dist;
			xmax = v.x + dist;
			ymin = v.y - dist;
			ymax = v.y + dist;
			zmin = v.z - dist - 1;
			zmax = v.z - 1;
			break;
		case "right":
			xmin = v.x + 1;
			xmax = v.x + dist + 1;
			ymin = v.y - dist;
			ymax = v.y + dist;
			zmin = v.z - dist;
			zmax = v.z + dist;
			break;
		case "left":
			xmin = v.x - dist - 1;
			xmax = v.x - 1;
			ymin = v.y - dist;
			ymax = v.y + dist;
			zmin = v.z - dist;
			zmax = v.z + dist;
			break;
		default:
			return 255;

	}

	for (let z = zmin; z <= zmax; z++) {
		for (let y = ymin; y <= ymax; y++) {
			for (let x = xmin; x <= xmax; x++) {	
				if (map([x, y, z])) {
					facingCubes.push({x, y, z});
				}
			}
		}
	} 

	facingCubes.forEach(c => {
		let dist = ((c.x - v.x) * (c.x - v.x) + (c.y - v.y) * (c.y - v.y) + (c.z - v.z) * (c.z - v.z)) * indirectFalloff;
		if (edgeBias) dist /= edgeBias;
		if (dist > 0) {
			b -= Math.floor(255 / dist);
			b = Math.max(0, b);
		}
	});

	return b / 255;

}



////////////////////////////////////////////////////////////////
// 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=2.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, skip = 0) {
			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;
			let num = 0;
			for (let i = 0.5; i < 150 / d; i++) {
				num++;
				if (skip > 0 && num % (5 - skip) == 0) {
					continue; 
				}
				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);
		}
	};
}