PCB 💻

Using Truchet tiles placed with an implementation of the Wave Function Collapse algorithm

en.wikipedia.org/wiki/truchet_tiles
en.wikipedia.org/wiki/wave_function_collapse

Not included a.k.a todo:
- backtracking (fall back to latest random pick and pick new if an invalid state occurs)
- configurable tile type probability on random selection

Log in to post a comment.

const showcaseTiles = 0; //min=0 max=1 step=1 (No, Yes)
const grid = 70; //min=2 max=100 step=1
const below = 0; //min=0 max=0 step=1 (Below you can set which tile types to include in the set)
const CHIP = 1; //min=0 max=1 step=1 (No, Yes)
const LEAD = 1; //min=0 max=1 step=1 (No, Yes)
const LEAD_DIAGONAL = 1; //min=0 max=1 step=1 (No, Yes)
const LEAD_DIAGONAL2 = 0; //min=0 max=1 step=1 (No, Yes)
const LEAD_JOINT = 0; //min=0 max=1 step=1 (No, Yes)
const LEAD_JOINT_DIAGONAL = 0; //min=0 max=1 step=1 (No, Yes)

// You can find the Turtle API reference here: https://turtletoy.net/syntax
Canvas.setpenopacity(1);

// Global code will be evaluated once.
const turtle = new Turtle();
const polygons = new Polygons();

const normalize2 = (a) => scale2(a, 1/len2(a));
const length2 = (a) => Math.sqrt(lengthSquared2(a));
const lengthSquared2 = (a) => dot2(a,a);
const rotationMatrix2 = (radians) => [Math.cos(radians), -Math.sin(radians), Math.sin(radians), Math.cos(radians)];
const transform2 = (matrix, a) => [matrix[0]*a[0]+matrix[2]*a[1], matrix[1]*a[0]+matrix[3]*a[1]];
const scale2 = (a, scalar) => [a[0]*scalar,a[1]*scalar];
const add2 = (a,b) => [a[0]+b[0],a[1]+b[1]];
const sub2 = (a,b) => [a[0]-b[0],a[1]-b[1]];
const dist2 = (a,b) => Math.hypot(...sub2(a,b));
const lerp2 = (a,b,t) => [a[0]*(1-t)+b[0]*t,a[1]*(1-t)+b[1]*t];
const dot2 = (a,b) => a[0]*b[0]+a[1]*b[1];

const TYPE_CONFIGURATIONS = {
    CLEAR: [0, 0, 0, 0],
    CONNECTOR: [2, 0, 0, 0]
};
if(CHIP === 1) {
    TYPE_CONFIGURATIONS['CHIP'] = [1, 1, 1, 1];
    TYPE_CONFIGURATIONS['CHIP_MOUNT'] = [2, 3, 1, 4];
    TYPE_CONFIGURATIONS['CHIP_CORNER'] = [3, 4, 0, 0];
}
if(LEAD === 1) TYPE_CONFIGURATIONS['LEAD'] = [2, 0, 2, 0];
if(LEAD_DIAGONAL === 1) TYPE_CONFIGURATIONS['LEAD_DIAGONAL'] = [2, 2, 0, 0];
if(LEAD_DIAGONAL2 === 1) TYPE_CONFIGURATIONS['LEAD_DIAGONAL_DOUBLE'] = [2, 2, 2, 2];
if(LEAD_JOINT === 1) TYPE_CONFIGURATIONS['LEAD_JOINT'] = [2, 2, 0, 2];
if(LEAD_JOINT_DIAGONAL === 1) TYPE_CONFIGURATIONS['LEAD_JOINT_DIAGONAL'] = [2, 2, 0, 2];

const TYPE_EDGES_ASYMMETRIC = [[3, 4]];

TYPE_EDGES_ASYMMETRIC.forEach((v, k) => TYPE_EDGES_ASYMMETRIC[k] = v.map(i => 2**i));
Object.keys(TYPE_CONFIGURATIONS).forEach(i => TYPE_CONFIGURATIONS[i] = TYPE_CONFIGURATIONS[i].map(j => 2**j));
const TYPES = Object.fromEntries(new Map(Object.keys(TYPE_CONFIGURATIONS).map((v, i) => [v, 2**i])));
const TYPES_ALL = 2**TYPES.length - 1;
const TYPE_CONFIGURATIONS_ASYMMETRIC = Object.fromEntries(new Map(Object.keys(TYPE_CONFIGURATIONS).map(v => [v, TYPE_CONFIGURATIONS[v]])));
TYPE_EDGES_ASYMMETRIC.forEach(tea => {
    Object.keys(TYPE_CONFIGURATIONS_ASYMMETRIC).forEach(tca => {
        TYPE_CONFIGURATIONS_ASYMMETRIC[tca] = TYPE_CONFIGURATIONS_ASYMMETRIC[tca]
            .map(c => c === tea[0]? 0: c)
            .map(c => c === tea[1]? tea[0]: c)
            .map(c => c === 0? tea[1]: c)
    })
});

const valueToType = (value) => Object.keys(TYPES).filter(i => TYPES[i] == value)[0];
const arrayRotate = (a, p) => a.filter((v, k) => k > (a.length - 1) - p).concat(a.filter((v, k) => k <= (a.length - 1) - p));

const ORIENTATION_UP = 0;
const ORIENTATION_RIGHT = 1;
const ORIENTATION_DOWN = 2;
const ORIENTATION_LEFT = 3;

const QUADRANT_UP = 1;
const QUADRANT_RIGHT = 2;
const QUADRANT_DOWN = 4;
const QUADRANT_LEFT = 8;

const COLOR = {
    BLACK: [[1, .15]],
    NEAR_BLACK: [[1, .4],[1 + (Math.PI/2), .4]],
    DARK_GREY: [[1, .4],[1 + Math.PI, .4]],
    GREY: [[1, .6],[1 + Math.PI, .6]],
    LIGHT_GREY: [[1, .7]],
    MESH: [[1, 1.5], [1 + (Math.PI/3), 1.5]],
    WHITE: []
}

class EntropyGrid {
    constructor(columns, rows, states, mirroredStates) {
        this.columns = columns;
        this.rows = rows;
        this.stateCount = states.length;

        const that = this;
        this.grid = Array.from({length: columns}, (v, column) => Array.from({length: rows}, (vv, row) => new EntropyTile(that, column, row, (column + row) % 2 == 0? states: mirroredStates))).flat();
    }
    collapse() {
        //find the minimum entropy value around the grid
        let min = this.grid
            .filter(c => !c.isCollapsed())
            .reduce((p, c) => c.getEntropy() < p? c.getEntropy(): p, this.stateCount);
        //get all the cells that have the same minimum entropy
        let valids = this.grid.filter(c => !c.isCollapsed()).filter(c => c.getEntropy() == min);
        //pick a random cell from the minimum entropy cells based on the column and row
        let cell = valids[(Math.random() * valids.length) | 0];
        //force a choice at that cell
        cell.collapse();
        //return the cell
        return cell;
    }
    getIndex(col, row) {
        return col * this.rows + row;
    }
    updateFrom(entropytile) {
        const update = [entropytile];
        while(update.length > 0) {
            entropytile = update.shift();
            
            // [deltaCol, deltaRow, fromOrientation, toOrientation]
            [[0, -1, ORIENTATION_UP, ORIENTATION_DOWN], [1, 0, ORIENTATION_RIGHT, ORIENTATION_LEFT], [0, 1, ORIENTATION_DOWN, ORIENTATION_UP], [-1, 0, ORIENTATION_LEFT, ORIENTATION_RIGHT]]
            .map(t => [entropytile.column + t[0], entropytile.row + t[1], t[2], t[3]])
            .filter(t => 0 <= t[0] && t[0] < grid && 0 <= t[1] && t[1] < grid)
            .filter(t => !this.grid[this.getIndex(t[0], t[1])].isCollapsed())
            .forEach(t => {
                const options = entropytile.getOptionsAtOrientation(t[2]);
                const testTile = this.grid[this.getIndex(t[0], t[1])];
                if(testTile.reduce(t[3], options)) {
                    update.push(testTile);
                }
            });
        }
    }
    hasUncollapsed() {
        return this.grid.filter(i => i.states.length > 1).length > 0;
    }
    consoleStatus(size = 100) { //debug function
        this.grid.forEach(c => {
            console.log('['+c.column+', '+ c.row+']', c.isCollapsed(), c.getEntropy());
            
            const topLeftLocation = [-100 + c.column * size, -100 + c.row * size];

            const tGrid = Math.ceil(Math.sqrt(this.stateCount));

            const tSize = size / tGrid;

            c.states.forEach((p, i) => {
                const ttSize = tSize * .9;
                const location = [
                    topLeftLocation[0] + tSize * (.5 + (i % tGrid)),
                    topLeftLocation[1] + tSize * (.5 + ((i / tGrid) | 0))
                ];
                
                (new Tile(
                    p[0],
                    p[1],
                    c.column,
                    c.row,
                    location,
                    ttSize
                )).draw(turtle);
            });
        })
    }
}

class EntropyTile {
    constructor (grid, column, row, states) {
        this.grid = grid;
        this.column = column;
        this.row = row;
        this.states = states;
        this.tile = null;
    }
    getEntropy() {
        return this.states.length;
    }
    isCollapsed() {
        return this.tile != null;
    }
    collapse() {
        this.states = [this.states[(Math.random() * this.states.length) | 0]];

        this.tile = new Tile(
            this.states[0][0],
            this.states[0][1],
            this.column,
            this.row
        );
        
        this.grid.updateFrom(this);
    }
    getOptionsAtOrientation(orientation) {
        return this.states.reduce((p, c) => p | c[2][orientation], 0);
    }
    getTile(size) {
        this.tile.setSize(size);
        return this.tile;
    }
    reduce(orientation, options) {
        const preCount = this.states.length;
        this.states = this.states.filter(s => (s[2][orientation] & options) == s[2][orientation]);
        return preCount != this.states.length;
    }
}

const canvasSize = 200;
const size = canvasSize / grid;

const eg = new EntropyGrid(grid, grid,
    Object.keys(TYPES).map(j => Array.from({length: 4}, (vvv, iii) => [TYPES[j], iii, arrayRotate(TYPE_CONFIGURATIONS[j], iii) ])).flat(),
    Object.keys(TYPES).map(j => Array.from({length: 4}, (vvv, iii) => [TYPES[j], iii, arrayRotate(TYPE_CONFIGURATIONS_ASYMMETRIC[j], iii) ])).flat()
);

// The walk function will be called until it returns false.
function walk(i) {
    if(showcaseTiles === 1) return showcase(i);

    let collapse = eg.collapse();

    let t = collapse.getTile(size);
    t.draw(turtle);
    
    if(i == -2) {
        eg.consoleStatus();
        return false;
    }
    return eg.hasUncollapsed(); //i < grid**2 - 1;
}

function showcase(i) {
    const tGrid = Math.ceil(Math.sqrt(Object.keys(TYPE_CONFIGURATIONS).length));

    const col = i % tGrid;
    const row = (i / tGrid) | 0;

    const tSize = 200 / tGrid;

    const tName = Object.keys(TYPE_CONFIGURATIONS)[i];

    const location = [
        tSize * (.5 + (i % tGrid)) - 100,
        tSize * (.5 + ((i / tGrid) | 0)) - 100
    ];
        
    (new Tile(
        TYPES[tName],
        0,
        col,
        row,
        location,
        tSize * .9
    )).draw(turtle);

    return i < Object.keys(TYPE_CONFIGURATIONS).length - 1;
}

class Tile {
    constructor(type, orientation, column, row, location = null, size = null) {
        this.type = type;
        this.orientation = orientation;
        this.column = column;
        this.row = row;
        this.location = location;
        this.size = size;
        this.rotation = rotationMatrix2(-this.orientation * Math.PI/2)
    }
    setSize(size) {
        if(this.size == null) {
            this.size = size;
        }
        if(this.location == null) {
            this.location = [-100 + (this.column + .5) * size, -100 + (this.row + .5) * size];
        }
    }
    prep(pts) {
        return pts
            .map(i => transform2(this.rotation, scale2(i, this.size)))
            .map(i => add2(i, this.location))
        ;
    }
    applyColor(polygon, color) {
        color.forEach(c => polygon.addHatching(...c));
    }
    draw(turtle) {
        const poly = (pts, color = null) => {
            const p = polygons.create();
            p.addPoints(...this.prep(pts));
            if(color !== null) this.applyColor(p, color);
            polygons.draw(turtle, p);
        }
        
        const background = (color = COLOR.DARK_GREY) => {
            poly([[.5, .5], [-.5, .5], [-.5, -.5], [.5, -.5]], color);
        }
        
        const connector = (r = .25, color = COLOR.WHITE) => {
            let pts = [];
            for(let i = 0, max = 50; i < max; i++) {
                pts.push([Math.cos(i*Math.PI*2/max) * r, Math.sin(i*Math.PI*2/max) * r]);
            }
            poly(pts, color);
        }
        
        const lead = (quadrants, color = COLOR.LIGHT_GREY) => {
            let pts = [[.15, -.5], [-.15, -.5], [-.15, 0], [.15, 0]];
            for(let i = 1; i < 16; i *= 2, pts = pts.map(j => [-j[1], j[0]])) {
                if(quadrants & i) poly(pts, color);
            }
        }
        
        let p = null;
        switch(this.type) {
            case TYPES.CHIP:
                background(COLOR.BLACK);
                return;
            case TYPES.CHIP_MOUNT:
                poly([[.5, .5], [-.5, .5], [-.5, .3], [-.25, .3], [-.25, .2], [.25, .2], [.25, .3], [.5, .3]], COLOR.BLACK);

                poly([[.125, .2], [-.125, .2], [-.125, -.07], [.125, -.07]], COLOR.GREY);

                connector()

                lead(QUADRANT_UP);
    
                background();
    
                return;
            case TYPES.CHIP_CORNER:
                poly([[.5, -.5], [.5, -.3], [.3, -.3], [.3, -.5]], COLOR.BLACK);

                background();
                return;
            case TYPES.CONNECTOR:
                connector()

                lead(QUADRANT_UP);
                
                background();
                return;
            case TYPES.LEAD:
                lead(QUADRANT_UP | QUADRANT_DOWN);
                
                background();
                return;
            case TYPES.LEAD_DIAGONAL_DOUBLE:
                poly([[-.15, .5], [.15, .5], [-.5, -.15], [-.5, .15]], COLOR.LIGHT_GREY);
            case TYPES.LEAD_DIAGONAL:
                poly([[.15, -.5], [-.15, -.5], [.5, .15], [.5, -.15]], COLOR.LIGHT_GREY);
                background();
                return;
            case TYPES.LEAD_JOINT:
                lead(QUADRANT_UP | QUADRANT_RIGHT | QUADRANT_LEFT);
                background();
                return;
            case TYPES.LEAD_JOINT_DIAGONAL:
                poly([[.15, -.5], [-.15, -.5], [.5, .15], [.5, -.15]], COLOR.LIGHT_GREY);
                poly([[.15, -.5], [-.15, -.5], [-.5, -.15], [-.5, .15]], COLOR.LIGHT_GREY);
                background();
                return;
            case TYPES.CLEAR:
            default:
                background();
                return;
        }
    }
}

////////////////////////////////////////////////////////////////
// Polygon Clipping utility code - Created by Reinder Nijhoff 2019
// (Polygon binning by Lionel Lemarie 2021)
// https://turtletoy.net/turtle/a5befa1f8d
////////////////////////////////////////////////////////////////
function Polygons(){const t=[],s=25,e=Array.from({length:s**2},t=>[]),n=class{constructor(){this.cp=[],this.dp=[],this.aabb=[]}addPoints(...t){let s=1e5,e=-1e5,n=1e5,h=-1e5;(this.cp=[...this.cp,...t]).forEach(t=>{s=Math.min(s,t[0]),e=Math.max(e,t[0]),n=Math.min(n,t[1]),h=Math.max(h,t[1])}),this.aabb=[s,n,e,h]}addSegments(...t){t.forEach(t=>this.dp.push(t))}addOutline(){for(let t=0,s=this.cp.length;t<s;t++)this.dp.push(this.cp[t],this.cp[(t+1)%s])}draw(t){for(let s=0,e=this.dp.length;s<e;s+=2)t.jump(this.dp[s]),t.goto(this.dp[s+1])}addHatching(t,s){const e=new n;e.cp.push([-1e5,-1e5],[1e5,-1e5],[1e5,1e5],[-1e5,1e5]);const h=Math.sin(t)*s,o=Math.cos(t)*s,a=200*Math.sin(t),i=200*Math.cos(t);for(let t=.5;t<150/s;t++)e.dp.push([h*t+i,o*t-a],[h*t-i,o*t+a]),e.dp.push([-h*t+i,-o*t-a],[-h*t-i,-o*t+a]);e.boolean(this,!1),this.dp=[...this.dp,...e.dp]}inside(t){let s=0;for(let e=0,n=this.cp.length;e<n;e++)this.segment_intersect(t,[.1,-1e3],this.cp[e],this.cp[(e+1)%n])&&s++;return 1&s}boolean(t,s=!0){const e=[];for(let n=0,h=this.dp.length;n<h;n+=2){const h=this.dp[n],o=this.dp[n+1],a=[];for(let s=0,e=t.cp.length;s<e;s++){const n=this.segment_intersect(h,o,t.cp[s],t.cp[(s+1)%e]);!1!==n&&a.push(n)}if(0===a.length)s===!t.inside(h)&&e.push(h,o);else{a.push(h,o);const n=o[0]-h[0],i=o[1]-h[1];a.sort((t,s)=>(t[0]-h[0])*n+(t[1]-h[1])*i-(s[0]-h[0])*n-(s[1]-h[1])*i);for(let n=0;n<a.length-1;n++)(a[n][0]-a[n+1][0])**2+(a[n][1]-a[n+1][1])**2>=.001&&s===!t.inside([(a[n][0]+a[n+1][0])/2,(a[n][1]+a[n+1][1])/2])&&e.push(a[n],a[n+1])}}return(this.dp=e).length>0}segment_intersect(t,s,e,n){const h=(n[1]-e[1])*(s[0]-t[0])-(n[0]-e[0])*(s[1]-t[1]);if(0===h)return!1;const o=((n[0]-e[0])*(t[1]-e[1])-(n[1]-e[1])*(t[0]-e[0]))/h,a=((s[0]-t[0])*(t[1]-e[1])-(s[1]-t[1])*(t[0]-e[0]))/h;return o>=0&&o<=1&&a>=0&&a<=1&&[t[0]+o*(s[0]-t[0]),t[1]+o*(s[1]-t[1])]}};return{list:()=>t,create:()=>new n,draw:(n,h,o=!0)=>{reducedPolygonList=function(n){const h={},o=200/s;for(var a=0;a<s;a++){const c=a*o-100,r=[0,c,200,c+o];if(!(n[3]<r[1]||n[1]>r[3]))for(var i=0;i<s;i++){const c=i*o-100;r[0]=c,r[2]=c+o,n[0]>r[2]||n[2]<r[0]||e[i+a*s].forEach(s=>{const e=t[s];n[3]<e.aabb[1]||n[1]>e.aabb[3]||n[0]>e.aabb[2]||n[2]<e.aabb[0]||(h[s]=1)})}}return Array.from(Object.keys(h),s=>t[s])}(h.aabb);for(let t=0;t<reducedPolygonList.length&&h.boolean(reducedPolygonList[t]);t++);h.draw(n),o&&function(n){t.push(n);const h=t.length-1,o=200/s;e.forEach((t,e)=>{const a=e%s*o-100,i=(e/s|0)*o-100,c=[a,i,a+o,i+o];c[3]<n.aabb[1]||c[1]>n.aabb[3]||c[0]>n.aabb[2]||c[2]<n.aabb[0]||t.push(h)})}(h)}}}