abstract office building

can you spot the kitchen?

Log in to post a comment.

const randomSeed = 123

// 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();

// helpers

function avg(items) {
    return items.reduce((acc, curr) => acc + curr, 0) / items.length
}

function map(v, min, max, omin, omax) {
    return omin + (v - min) / (max - min) * (omax - omin)
}

function clamp(v, min, max) {
    return Math.max(Math.min(v, max), min)
}

function lerp(a, b, fract) {
    return a + (b - a) * fract
}

function randomFrom(arr) {
    return arr[Math.floor(Random.random() * arr.length)]
}

function isWithin(x, min, max) {
    return min <= x && x <= max
}

// vector

class Vec2 {
    constructor(x, y) {
        this.x = x
        this.y = y
    }

    rotate(angle) {
        return new Vec2(
            this.x * Math.cos(angle) - this.y * Math.sin(angle),
            this.x * Math.sin(angle) + this.y * Math.cos(angle)
        )
    }
    
    multn(n) {
        return new Vec2(this.x * n, this.y * n)
    }

    add(pt) {
        return new Vec2(this.x + pt.x, this.y + pt.y)
    }

    sub(pt) {
        return new Vec2(this.x - pt.x, this.y - pt.y)
    }
    
    index(size) {
        return Math.floor(this.x) + Math.floor(this.y) * size
    }

    equals(pt) {
        return this.x === pt.x && this.y === pt.y
    }
    
    distance(pt) {
        return Math.sqrt((this.x - pt.x) ** 2 + (this.y - pt.y) ** 2)
    }
    
    floor(pt) {
        return new Vec2(Math.floor(this.x), Math.floor(this.y))
    }

    addX(x) {
        return new Vec2(this.x + x, this.y)
    }

    addY(y) {
        return new Vec2(this.x, this.y + y)
    }    

    length() {
        return this.distance(new Vec2(0, 0))
    }

    normalize() {
        const length = this.length()
        return new Vec2(this.x / length, this.y / length)
    }
    
    angle() {
        return Math.atan2(this.y, this.x)
    }

    static lerp(a, b, fract) {
        return new Vec2(lerp(a.x, b.x, fract), lerp(a.y, b.y, fract))
    }
}

class LineSegment {
    constructor(a, b, source) {
        this.a = a
        this.b = b
        this.source = source
    }

    intersection(seg) {
        const int = segment_intersect2([this.a.x, this.a.y], [this.b.x, this.b.y], [seg.a.x, seg.a.y], [seg.b.x, seg.b.y])
        if (int) {
            return new Vec2(int[0], int[1])
        }
        else {
            return false
        }
    }

    length() {
        return this.a.distance(this.b)
    }
}

// vec2 functions
const equal2=(a,b)=>0.001>dist_sqr2(a,b);
const scale2=(a,b)=>[a[0]*b,a[1]*b];
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 dot2=(a,b)=>a[0]*b[0]+a[1]*b[1];
const dist_sqr2=(a,b)=>(a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1]);
const segment_intersect2=(a,b,d,c)=>{
    const e=(c[1]-d[1])*(b[0]-a[0])-(c[0]-d[0])*(b[1]-a[1]);
    if(0==e)return false;
    c=((c[0]-d[0])*(a[1]-d[1])-(c[1]-d[1])*(a[0]-d[0]))/e;
    d=((b[0]-a[0])*(a[1]-d[1])-(b[1]-a[1])*(a[0]-d[0]))/e;
    return 0<=c&&1>=c&&0<=d&&1>=d?[a[0]+c*(b[0]-a[0]),a[1]+c*(b[1]-a[1])]:false;
}

const fronts = []
const lineSegments = []
const newFrontCounts = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
const newFrontCountsOnHit = [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]

function init(count) {
    for (let i = 0; i < count; i++) {
        const start = new Vec2(1, 0).rotate(Random.random() * Math.PI * 2).multn(Random.random() * 45)
        // const angle = map(Random.random(), 0, 1, 0, Math.PI * 2)
        const angle = map(Random.random(), 0, 1, Math.PI / 4, Math.PI * 3 / 4)
        const speed = map(Random.random(), 0, 1, 0.5, 1)
        const dir = new Vec2(1, 0).rotate(angle).multn(speed)
        fronts.push(new Front(start, dir))
    }
}

function step(dt) {
    const lineSegmentsCount = lineSegments.length
    steppingFronts().forEach(front => front.step(dt))
    return lineSegments.slice(lineSegmentsCount)
}

function steppingFronts() {
    return fronts.filter(front => front.stepping)
}

class Front {
    constructor(start, dir, parent, minDistForSplit) {
        this.pt = this.start = start
        this.dir = dir
        this.parent = parent
        this.minDistForSplit = minDistForSplit || 8
        this.stepping = true
        this.distSinceSplit = 0
    }
    
    step(dt) {
        const pt = this.pt.add(this.dir.multn(dt))
        const line = new LineSegment(this.pt, pt, this)
        let minLength = Infinity
        let minInt = null
        let intLine = null
        for (let i = 0; i < lineSegments.length; i++) {
            const test = lineSegments[i]
            if (test.source === this) continue
            if (test.source === this.parent) continue
            const int = line.intersection(test)
            if (int && int.distance(this.start) > 0.01) {
                const len = int.distance(this.pt)
                if (len < minLength) {
                    minLength = len
                    minInt = int
                    intLine = test
                }
            }
        }
        if (minInt) {
            lineSegments.push(new LineSegment(this.pt, minInt, this))
            this.stepping = false
            const newFronts = Random.random() < 0.5//randomFrom(newFrontCountsOnHit)
            for (let i = 0; i < newFronts; i++) {
                const newSpeed = clamp(this.dir.length() * map(Random.random(), 0, 1, 0.5, 1.5), 0.5, 1)
                // const offsAngle = map(Random.random(), 0, 1, Math.PI / 2, 3 * Math.PI / 2)
                // const offsAngle = Math.PI / 2 * (Random.random() < 0.5 ? 1 : -1)
                const offsAngle = randomFrom([Math.PI / 3, 2 / 3 * Math.PI]) * (Random.random() < 0.5 ? 1 : -1)
                const newDir = this.dir.rotate(offsAngle).normalize().multn(newSpeed)
                fronts.push(new Front(minInt, newDir, this))
            }
        }
        else {
            lineSegments.push(line)
            this.distSinceSplit += line.length()
            const split = this.distSinceSplit > this.minDistForSplit && Random.random() < 0.2 //map(Random.random(), 0, 1, 1, 5) < this.start.distance(pt)
            if (split) {
                this.distSinceSplit = 0
                this.stepping = Random.random() < 0.8
                const newFronts = Math.max(randomFrom(newFrontCounts), this.stepping ? 0 : 1)
                for (let i = 0; i < newFronts; i++) {
                    const newSpeed = clamp(this.dir.length() * map(Random.random(), 0, 1, 0.5, 1.5), 0.5, 1)
                    // const offsAngle = map(Random.random(), 0, 1, Math.PI / 4, Math.PI * 3 / 4) * (Random.random() < 0.5 ? 1 : -1)
                    // const offsAngle = Math.PI / 2 * (Random.random() < 0.5 ? 1 : -1)
                    const offsAngle = randomFrom([Math.PI / 3, 2 / 3 * Math.PI]) * (Random.random() < 0.5 ? 1 : -1)
                    const newDir = this.dir.rotate(offsAngle).normalize().multn(newSpeed)
                    const minDistForSplit = Math.abs(this.dir.x) > Math.abs(this.dir.y) ? 24 : 8
                    // const minDistForSplit = Random.random() < 0.5 ? 40 : 4
                    fronts.push(new Front(pt, newDir, this, minDistForSplit))
                }
            }
            if (!isWithin(pt.x, -90, 90) || !isWithin(pt.y, -90, 90)) {
                this.stepping = false
            }
            this.pt = pt
        }
    }
}

let lineSegmentsDrawn = []

// polygon functions
function LineSegment2(p1, p2) {
    this.p1 = p1;
    this.p2 = p2;
}
LineSegment2.prototype.unique = function() {
    for (let i=0, l=lineSegmentsDrawn.length; i<l; i++) {
        const ls = lineSegmentsDrawn[i];
        if ( (equal2(this.p1, ls.p1) && equal2(this.p2, ls.p2)) ||
             (equal2(this.p1, ls.p2) && equal2(this.p2, ls.p1)) ){
            return false;
        }
    }
    lineSegmentsDrawn.push(this);
    return true;
}

function Polygon() {
    this.cp = []; // clip path: array of [x,y] pairs
    this.dp = []; // 2d line to draw: array of linesegments
}
Polygon.prototype.clone = function() {
    const p = new Polygon()
    p.cp = [...this.cp]
    p.dp = [...this.dp]
    return p
}
Polygon.prototype.addOutline = function(s=0) {
    for (let i=s, l=this.cp.length; i<l; i++) {
        this.dp.push(new LineSegment2(this.cp[i], this.cp[(i+1)%l]));
    }
}
Polygon.prototype.createPoly = function(x,y,c,r,a) {
    this.cp = [];
    for (let i=0; i<c; i++) {
        this.cp.push( [x + Math.sin(i*Math.PI*2/c+a) * r, y + Math.cos(i*Math.PI*2/c+a) * r] );
    }
}
Polygon.prototype.addHatching = function(a,d) {
    // todo, create a tight bounding polygon, for now fill screen
    const tp = new Polygon();
    tp.createPoly(0,0,4,200,Math.PI*.5);
    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 = .5; i<150/d; i++) {
        tp.dp.push(new LineSegment2([dx*i+cy,dy*i-cx], [dx*i-cy,dy*i+cx]));
        tp.dp.push(new LineSegment2([-dx*i+cy,-dy*i-cx], [-dx*i-cy,-dy*i+cx]));
    }
    tp.boolean(this, false);
    this.dp = this.dp.concat(tp.dp);
}
Polygon.prototype.draw = function(t) {
    if (this.dp.length ==0) {
        return;
    }
    for (let i=0, l=this.dp.length; i<l; i++) {
        const d = this.dp[i];
        if (d.unique()) {
            if (!equal2(d.p1, t.pos())) {
                t.penup();
                t.goto(d.p1);
                t.pendown();   
            }
            t.goto(d.p2);
        }
    }
}
Polygon.prototype.inside = function(p) {
    // find number of intersections from p to far away - if even you're outside
    const p1 = [0, -1000];
    let int = 0;
    for (let i=0, l=this.cp.length; i<l; i++) {
        if (segment_intersect2(p, p1, this.cp[i], this.cp[(i+1)%l])) {
            int ++;
        }    
    }
    return int & 1;
}
Polygon.prototype.boolean = function(p, diff = true) {
    // very naive polygon diff algorithm - made this up myself
    const ndp = [];
    for (let i=0, l=this.dp.length; i<l; i++) {
        const ls = this.dp[i];
        
        // find all intersections with clip path
        const int = [];
        for (let j=0, cl=p.cp.length; j<cl; j++) {
            const pint = segment_intersect2(ls.p1,ls.p2,p.cp[j],p.cp[(j+1)%cl]);
            if (pint) {
                int.push(pint);
            }
        }
        if (int.length == 0) { // 0 intersections, inside or outside?
            if (diff != p.inside(ls.p1)) {
                ndp.push(ls);
            }
        } else {
            int.push(ls.p1); int.push(ls.p2);
            // order intersection points on line ls.p1 to ls.p2
            const cmp = sub2(ls.p2,ls.p1);
            int.sort((a,b) => dot2(sub2(a,ls.p1),cmp)-dot2(sub2(b,ls.p1),cmp));
            
            for (let j=0; j<int.length-1; j++) {
                if (!equal2(int[j], int[j+1]) && 
                    diff != p.inside(scale2(add2(int[j],int[j+1]),.5))) {
                    ndp.push(new LineSegment2(int[j], int[j+1]));
                }
            }
        }
    }
    this.dp = ndp;
    return this.dp.length > 0;
}

function walk(i) {
    const dt = 1
    const newLineSegments = step(dt)
    for (let i = 0; i < newLineSegments.length; i++) {
        const line = newLineSegments[i]
        turtle.penup()
        turtle.goto(line.a.x, line.a.y)
        turtle.pendown()
        turtle.goto(line.b.x, line.b.y)
    }
    const finished = steppingFronts().length === 0
    if (finished) {
        for (let i = 0; i < 30; i++) {
            const start = new Vec2(Random.random() * 180 - 90, Random.random() * 180 - 90)
            console.log('i', i, start.x, start.y)
            const lines = new Set()
            for (let angle = 0; angle < Math.PI * 2; angle += 0.1) {
                const ray = new LineSegment(start, new Vec2(1, 0).rotate(angle).multn(200).add(start))
                let minLength = Infinity
                let minInt = null
                let intLine = null
                for (let j = 0; j < lineSegments.length; j++) {
                    const test = lineSegments[j]
                    const int = ray.intersection(test)
                    if (int) {
                        const len = int.distance(start)
                        if (len < minLength) {
                            minLength = len
                            minInt = int
                            intLine = test
                        }
                    }
                }
                if (!intLine) {
                    break
                }
                lines.add(intLine)
            }
            const poly = new Polygon()
            lines.forEach((line, ind) => {
                turtle.penup()
                turtle.goto(line.a.x, line.a.y)
                turtle.pendown()
                turtle.goto(line.b.x, line.b.y)
                const a = ((line.b.angle() - line.a.angle()) + Math.PI * 2) % (Math.PI * 2)
                if (a > Math.PI) {
                    poly.cp.push([line.b.x, line.b.y], [line.a.x, line.a.y])
                }
                else {
                    poly.cp.push([line.a.x, line.a.y], [line.b.x, line.b.y])
                }
            })
            poly.addHatching(Math.PI / 3 * randomFrom([1, 2]), 1)
            poly.draw(turtle)
        }
    }
    return !finished
}

const lib = {}
;(function(lib) {
    /*
  I've wrapped Makoto Matsumoto and Takuji Nishimura's code in a namespace
  so it's better encapsulated. Now you can have multiple random number generators
  and they won't stomp all over eachother's state.
  
  If you want to use this as a substitute for Math.random(), use the random()
  method like so:
  
  var m = new MersenneTwister();
  var randomNumber = m.random();
  
  You can also call the other genrand_{foo}() methods on the instance.
  If you want to use a specific seed in order to get a repeatable random
  sequence, pass an integer into the constructor:
  var m = new MersenneTwister(123);
  and that will always produce the same random sequence.
  Sean McCullough (banksean@gmail.com)
*/

/* 
   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.
 
   Before using, initialize the state by using init_genrand(seed)  
   or init_by_array(init_key, key_length).
 
   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.                          
 
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
 
     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
 
     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
 
     3. The names of its contributors may not be used to endorse or promote 
        products derived from this software without specific prior written 
        permission.
 
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 
   Any feedback is very welcome.
   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/

var MersenneTwister = function(seed) {
  if (seed == undefined) {
    seed = new Date().getTime();
  } 
  /* Period parameters */  
  this.N = 624;
  this.M = 397;
  this.MATRIX_A = 0x9908b0df;   /* constant vector a */
  this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
  this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
 
  this.mt = new Array(this.N); /* the array for the state vector */
  this.mti=this.N+1; /* mti==N+1 means mt[N] is not initialized */

  this.init_genrand(seed);
}  
 
/* initializes mt[N] with a seed */
MersenneTwister.prototype.init_genrand = function(s) {
  this.mt[0] = s >>> 0;
  for (this.mti=1; this.mti<this.N; this.mti++) {
      var s = this.mt[this.mti-1] ^ (this.mt[this.mti-1] >>> 30);
   this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253)
  + this.mti;
      /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
      /* In the previous versions, MSBs of the seed affect   */
      /* only MSBs of the array mt[].                        */
      /* 2002/01/09 modified by Makoto Matsumoto             */
      this.mt[this.mti] >>>= 0;
      /* for >32 bit machines */
  }
}
 
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
MersenneTwister.prototype.init_by_array = function(init_key, key_length) {
  var i, j, k;
  this.init_genrand(19650218);
  i=1; j=0;
  k = (this.N>key_length ? this.N : key_length);
  for (; k; k--) {
    var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30)
    this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + ((s & 0x0000ffff) * 1664525)))
      + init_key[j] + j; /* non linear */
    this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
    i++; j++;
    if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
    if (j>=key_length) j=0;
  }
  for (k=this.N-1; k; k--) {
    var s = this.mt[i-1] ^ (this.mt[i-1] >>> 30);
    this.mt[i] = (this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941))
      - i; /* non linear */
    this.mt[i] >>>= 0; /* for WORDSIZE > 32 machines */
    i++;
    if (i>=this.N) { this.mt[0] = this.mt[this.N-1]; i=1; }
  }

  this.mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */ 
}
 
/* generates a random number on [0,0xffffffff]-interval */
MersenneTwister.prototype.genrand_int32 = function() {
  var y;
  var mag01 = new Array(0x0, this.MATRIX_A);
  /* mag01[x] = x * MATRIX_A  for x=0,1 */

  if (this.mti >= this.N) { /* generate N words at one time */
    var kk;

    if (this.mti == this.N+1)   /* if init_genrand() has not been called, */
      this.init_genrand(5489); /* a default initial seed is used */

    for (kk=0;kk<this.N-this.M;kk++) {
      y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
      this.mt[kk] = this.mt[kk+this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
    }
    for (;kk<this.N-1;kk++) {
      y = (this.mt[kk]&this.UPPER_MASK)|(this.mt[kk+1]&this.LOWER_MASK);
      this.mt[kk] = this.mt[kk+(this.M-this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
    }
    y = (this.mt[this.N-1]&this.UPPER_MASK)|(this.mt[0]&this.LOWER_MASK);
    this.mt[this.N-1] = this.mt[this.M-1] ^ (y >>> 1) ^ mag01[y & 0x1];

    this.mti = 0;
  }

  y = this.mt[this.mti++];

  /* Tempering */
  y ^= (y >>> 11);
  y ^= (y << 7) & 0x9d2c5680;
  y ^= (y << 15) & 0xefc60000;
  y ^= (y >>> 18);

  return y >>> 0;
}
 
/* generates a random number on [0,0x7fffffff]-interval */
MersenneTwister.prototype.genrand_int31 = function() {
  return (this.genrand_int32()>>>1);
}
 
/* generates a random number on [0,1]-real-interval */
MersenneTwister.prototype.genrand_real1 = function() {
  return this.genrand_int32()*(1.0/4294967295.0); 
  /* divided by 2^32-1 */ 
}

/* generates a random number on [0,1)-real-interval */
MersenneTwister.prototype.random = function() {
  return this.genrand_int32()*(1.0/4294967296.0); 
  /* divided by 2^32 */
}
 
/* generates a random number on (0,1)-real-interval */
MersenneTwister.prototype.genrand_real3 = function() {
  return (this.genrand_int32() + 0.5)*(1.0/4294967296.0); 
  /* divided by 2^32 */
}
 
/* generates a random number on [0,1) with 53-bit resolution*/
MersenneTwister.prototype.genrand_res53 = function() { 
  var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6; 
  return(a*67108864.0+b)*(1.0/9007199254740992.0); 
} 

lib.MersenneTwister = MersenneTwister

/* These real versions are due to Isaku Wada, 2002/01/09 added */
})(lib)
const { MersenneTwister } = lib

const Random = new MersenneTwister(randomSeed)
init(1)