-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
654 lines (631 loc) · 25.3 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
<!DOCTYPE html>
<html><head>
<meta charset='utf-8'>
<style>
* { margin: 0; padding: 0; border: none; overflow: hidden; width:100%; height:100% }
</style>
<script type="text/javascript">
if(typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){ return this.slice(0, str.length) == str }
}
if(typeof(String.prototype.trim) != 'function') {
String.prototype.trim = function() { return String(this).replace(/^\s+|\s+$/g, '') }
}
function setupGL(canvas) {
var gl = surface.getContext("webgl") || surface.getContext("experimental-webgl")
if(!gl) throw new Error("no webgl context")
surface.gl = gl
window.onresize = function() {
var surf = getSurf()
var w = surf.clientWidth; var h = surf.clientHeight;
if(!gl.w || gl.w != w || gl.h != h) {
gl.w = w; gl.h = h
surf.width = w
surf.height = h
//console.log("resize " + w + " x " + h + " => ")
resize(gl)
step()
}
}
window.onmousemove = function(e) {
if(window.draging) {
var deltaX = e.x - window.dragX
var deltaY = e.y - window.dragY
gl.scroll(deltaX - window.deltaX, deltaY - window.deltaY)
window.deltaX = deltaX
window.deltaY = deltaY
}
}
window.onmousedown = function(e) {
window.dragX = e.x
window.dragY = e.y
window.deltaX = 0
window.deltaY = 0
window.draging = true
}
window.onmouseup = function(e) { window.draging = false }
window.onwheel = function(e) { gl.zoom(Math.sign(e.wheelDelta), e.x, e.y) }
window.onkeydown = function(e) {
switch(e.which) {
case 77: gl.zoom(-1, gl.w / 2, gl.h / 2); break;
case 80: gl.zoom( 1, gl.w / 2, gl.h / 2); break;
case 32: if(gl.content.mode == 8) gl.content.mode = 0; else gl.content.mode++; console.log(gl.content.mode); break;
default: gl.key = String.fromCharCode(e.which)
}
}
}
function getEl(id) {
var r = document.getElementById(id)
if(!r) throw new Error("element [" + id + "] not found")
return r
}
function getSurf() { return getEl("surface") }
function getGl() {
var surface = getSurf();
if(!surface.gl) setupGL(surface);
return surface.gl;
}
function getQuad(gl) {
if(!gl.quad) {
var bufId = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, bufId)
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0,0, 0,1, 1,1, 1,0]), gl.STATIC_DRAW)
gl.quad = function(posAttrib) {
gl.bindBuffer(gl.ARRAY_BUFFER, bufId)
gl.vertexAttribPointer(posAttrib, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4)
}
}
return gl.quad
}
function compile(s) {
if(!s.shader) {
var gl = getGl();
var shader;
if(s.type == "x-shader/x-vertex") shader = gl.createShader(gl.VERTEX_SHADER);
else if(s.type == "x-shader/x-fragment") shader = gl.createShader(gl.FRAGMENT_SHADER);
else return null;
var src = '';
for(c = s.firstChild; c; c = c.nextSibling) if(c.nodeType == c.TEXT_NODE) src += c.textContent;
var vars = []
src.replace(/\/\/.*$/mg, '').replace(/\/\*.*\*\//g, '').replace(/^.*#.*/mg, '').split(';').forEach(function(statement) {
var words = statement.split(/\W/)
.map(function(w) { return w.trim() })
.filter(function(w) { return w != '' })
.filter(function(w) { return ["const", "int", "float", "vec2", "vec3", "vec4", "sampler2D"].indexOf(w) < 0 })
if(["uniform", "attribute"].indexOf(words[0]) >= 0) for(var i = 1; i < words.length; i++) vars.push({
type: words[0],
name: words[i]
})
})
src = "precision mediump float;" + src.replace(/\$\w+/g, function(name) {
var raw = name[1] == '_'
var r = function(n) {
if(n.match(/\D/) == null) return parseInt(n)
switch(n) {
case 'pi': return Math.PI
case 'pi2': return Math.PI * 2
case 'half': return .5/255
case 'invWidth': return 1/config.width
case 'invHeight': return 1/config.height
case 'invSize': return "vec2(" + 1/config.width + ", " + 1/config.height + ")"
case 'action': return 16
case 'left': return 16
case 'right': return 32
case 'up': return 64
case 'down': return 128
default: return (n in config) ? config[n] : n
}
}(name.slice(raw ? 2 : 1))
if(!raw && typeof r == 'number' && r === (r|0)) {
r = (r / 255) + '';
if(r.indexOf('.') < 0) r += '.';
}
//console.log(name, r)
return r
})
gl.shaderSource(shader, src)
gl.compileShader(shader)
if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
var lines = src.split('\n'), lined = ''
for(var i = 0; i < lines.length; i++) lined += (i+1) + '\t' + lines[i] + '\n'
throw new Error("error in shader [" + s.id + "]\n" + gl.getShaderInfoLog(shader) + "\n" + lined)
}
s.shader = shader
s.vars = vars
//console.log("shader compiled: " + s.id + " => " + JSON.stringify(s.vars))
}
return s;
}
function entry() {
var gl = getGl();
gl.program = function(shaders) {
if(!gl.progCache) gl.progCache = {}
var key = shaders.toString();
if(!gl.progCache[key]) {
var prog = gl.createProgram();
var vars = []
shaders.forEach(function(s) {
var shader = compile(getEl(s));
vars = vars.concat(shader.vars)
gl.attachShader(prog, shader.shader)
})
gl.linkProgram(prog)
if(!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error("error in program [" + key + "]\n" + gl.getProgramInfoLog(prog));
gl.useProgram(prog)
prog.vars = {}
vars.forEach(function(v) {
if(v.type == 'attribute') {
prog.vars[v.name] = gl.getAttribLocation(prog, v.name)
gl.enableVertexAttribArray(prog, prog.vars[v.name]);
} else if(v.type == 'uniform') {
prog.vars[v.name] = gl.getUniformLocation(prog, v.name)
}
if(typeof(prog[v.name]) == "undefined") prog[v.name] = prog.vars[v.name]
})
//console.log("progam linked: " + key + " => " + JSON.stringify(prog.vars))
gl.progCache[key] = prog
} else gl.useProgram(gl.progCache[key])
return gl.progCache[key]
}
init(gl)
window.onresize()
}
function step() {
frame(getGl())
requestAnimationFrame(step)
//setTimeout(step, 1000)
}
var config = {
width: 1024,
height: 1024,
food_gen: 1,
initE: 40, initP: 40,
init: {
density: 0.1,
min_food: 50, max_food: 150
},
eat: 1, draw: 2, build:3, move: 4, give: 5, take: 6, clone:7, die: 9,
gainEat:1, gainDraw:6, gainBuild:1, gainGive:2,
costEat:3, costDraw:8, costBuild:2,costMove:2, costGive:3,costClone:100,
gainTake: 1, costTake: 2, taken: 10,
costNaked: 1, probaRegenerate: 1,
species : [
{ name: "plant" },
{ name: "sheep" },
{ name: "wolf" }
]
}
function init(gl) {
gl.clearColor(0,0,0,1)
gl.camera = new Float32Array([0, 0, 20])
gl.scroll = function(x,y) {
gl.camera[0] -= x
gl.camera[1] += y
}
gl.zoom = function(s, x,y) {
var m = 1.1
m = s == 0 ? 1 : s > 0 ? m : 1/m
var target = gl.camera[2] * m
if(target < 1) {
target = 1
m = target / gl.camera[2]
}
if(target > 150) {
target = 150
m = target / gl.camera[2]
}
gl.camera[2] = target
s = 1 - 1/m
gl.camera[0] += s * x
gl.camera[1] += s * (gl.canvas.height - y)
gl.camera[0] *= m
gl.camera[1] *= m
}
gl.content = {}
var n = config.width * config.height | 0
var background = new Uint8Array(new ArrayBuffer(n * 4)) // [ food, noise?, ?, action ]
var cells = new Uint8Array(new ArrayBuffer(n * 4)) // [ species, state?, energy, protect ]
var entropy = new Uint8Array(new ArrayBuffer(n * 4))
var food_min = config.init.min_food, food_delta = (config.init.max_food - config.init.min_food)
for(var i = 0; i < n; i++) {
if(Math.random() <= config.init.density) {
var c = Math.floor(Math.random() * config.species.length) | 0
cells[4*i] = c + 1 | 0
cells[4*i+2] = config.initE
cells[4*i+3] = config.initP
}
background[4*i] = food_min + Math.random() * food_delta
entropy[4*i ] = Math.random() * 256
entropy[4*i+1] = Math.random() * 256
entropy[4*i+2] = Math.random() * 256
entropy[4*i+3] = Math.random() * 256
}
function setLinear() {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
}
function setNearest() {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
}
function setRepeat() {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
}
function createTexture(data) {
var tex;
gl.bindTexture(gl.TEXTURE_2D, tex = gl.createTexture())
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, config.width, config.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data)
setNearest(); setRepeat();
return tex;
}
gl.content.entropy = createTexture(entropy)
gl.content.background = {
tex : [createTexture(background), createTexture(background)],
which : 0
}
gl.content.cells = {
tex : [createTexture(cells), createTexture(cells)],
which : 0
}
function createFBO(tex) {
var fbo;
gl.bindFramebuffer(gl.FRAMEBUFFER, fbo = gl.createFramebuffer())
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0)
if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE) throw new Error("unsupported FBO config")
return fbo;
}
function addFBO(obj) {
obj.fbo = obj.tex.map(createFBO)
obj.read = function() { return this.tex[this.which] }
obj.write = function() { return this.fbo[this.which] }
}
addFBO(gl.content.background)
addFBO(gl.content.cells)
gl.content.cycle = 0
gl.content.mode = 0
}
function resize(gl) { }
function setup(gl, shader) {
var prog = gl.program(["2d", shader])
if(prog.background) { gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, gl.content.background.read()); gl.uniform1i(prog.background, 0) }
if(prog.cells) { gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, gl.content.cells.read()); gl.uniform1i(prog.cells, 1) }
if(prog.entropy) { gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, gl.content.entropy); gl.uniform1i(prog.entropy, 2) }
if(prog.seed) gl.uniform2f(prog.seed, Math.random(), Math.random())
return prog
}
function run(gl, shader, target) {
target.which = 1 - target.which
gl.bindFramebuffer(gl.FRAMEBUFFER, target.write())
target.which = 1 - target.which
getQuad(gl)(setup(gl, shader))
target.which = 1 - target.which
}
function process(gl) {
run(gl, "decide", gl.content.background)
run(gl, "resolve", gl.content.background)
run(gl, "act", gl.content.cells)
}
function draw(gl) {
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
var prog;
if(gl.content.mode == 0) prog = setup(gl, "draw")
else {
prog = setup(gl, "debug")
gl.uniform1i(prog.channel, gl.content.mode)
}
gl.uniform3fv(prog.camera, gl.camera)
getQuad(gl)(prog.posIn)
}
function frame(gl) {
gl.viewport(0, 0, config.width, config.height)
process(gl)
if(gl.key) {
switch(gl.key) {
case 'A': run(gl, "decide", gl.content.background); break;
case 'Z': run(gl, "check", gl.content.background); break;
case 'E': run(gl, "mark", gl.content.background); break;
case 'R': run(gl, "resolve", gl.content.background); break;
case 'T': run(gl, "act", gl.content.cells); break;
}
gl.key = null
}
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height)
draw(gl)
gl.content.cycle++
}
</script>
<script type="x-shader/x-vertex" id="2d">
uniform float time;
attribute vec2 posIn;
void main(void) {
gl_Position = vec4(posIn * vec2(2) - vec2(1), vec2(0,1));
}
</script>
<script type="x-shader/x-fragment" id="draw">
uniform vec3 camera;
uniform sampler2D background, cells;
vec3 hue(float h) {
return clamp(vec3(
6. * abs(h-.5) - 1.,
2. - 6. * abs(h - .33333333333333),
2. - 6. * abs(h - .66666666666667)
), 0., 1.);
}
void main(void) {
vec2 trans = (gl_FragCoord.xy + camera.xy) / camera.z;
vec2 grid1 = step( 1. - .2/camera.z, cos(trans * $pi2) );
vec2 grid10 = step( 1. - .05/camera.z, cos(trans * .1*$pi2) );
vec2 grid100 = step( 1. - .01/camera.z, cos(trans * .01*$pi2) );
vec2 grid2 = grid100 * grid10 + grid10 * clamp(.1 * (camera.z - 4.), 0., 1.) + grid1 * clamp(.01 * (camera.z - 35.), 0., 1.);
float grid = min(1., grid2.x + grid2.y);
vec2 texCoord = trans * $invSize;
vec4 bg = texture2D(background, texCoord);
vec4 cell = texture2D(cells, texCoord);
vec3 color;
if(cell.r != 0.) { // draw cell
color = hue(fract(cell.r * 70.));
vec3 fill = color * (0.1 + 0.8 * cell.b);
if(max(abs(fract(trans.x) - .5), abs(fract(trans.y) - .5)) > (.5 - cell.a * .5)) { // border
color = mix(fill, (color + 1.) * .5, clamp((camera.z - 15. - 40. * abs(cell.a - .5)) * .03, 0., 1.));
} else { // fill
color = fill;
}
} else { // draw food
float fill = bg.r * .5;
if(camera.z > 15.) {
float pattern = mod(floor(trans.x) + floor(trans.y), 2.) == 0. ? trans.x + trans.y : trans.x - trans.y;
pattern = .5 + .5 * cos(pattern * $pi2 * 3.);
pattern = bg.r < .5 ? (.25 * step(pattern, bg.r * 2.)) : (.25 + .25 * step(pattern, bg.r * 2. - 1.));
color = vec3(mix(fill, pattern, min((camera.z - 15.) * .01, 1.)));
} else color = vec3(fill);
}
gl_FragColor = vec4(vec3(color + vec3(grid * .4)), 1);
}
</script>
<script type="x-shader/x-fragment" id="debug">
uniform vec3 camera;
uniform sampler2D background, cells;
uniform int channel;
void main(void) {
vec2 p = (gl_FragCoord.xy + camera.xy) / camera.z;
float r;
// fract(p.x * $invWidth); // test
if(channel == 1) r = texture2D(background, p * $invSize).r; else
if(channel == 2) r = texture2D(background, p * $invSize).g; else
if(channel == 3) r = texture2D(background, p * $invSize).b; else
if(channel == 4) r = texture2D(background, p * $invSize).a; else
if(channel == 5) r = texture2D(cells, p * $invSize).r; else
if(channel == 6) r = texture2D(cells, p * $invSize).g; else
if(channel == 7) r = texture2D(cells, p * $invSize).b; else
if(channel == 8) r = texture2D(cells, p * $invSize).a; else
r = 0.;
r = r * 255. / 256. + $half;
p = fract(p);
vec3 clr;
if(any(greaterThan(abs(p - .5), vec2(.45)))) clr = vec3(0., 0., .5);
else {
vec4 row = p.y > .5 ? step(.5, fract(r * vec4(128., 64., 32., 16.))) : step(.5, fract(r * vec4(8., 4., 2., 1.)));
clr = vec3(p.x < .5 ? (p.x < .25 ? row.r : row.g) : (p.x < .75 ? row.b : row.a));
}
gl_FragColor = vec4(clr, 1.);
}
</script>
<script type="x-shader/x-fragment" id="decide">
uniform sampler2D background, cells, entropy;
uniform vec2 seed;
float max(vec4 v) { vec2 m2 = max(v.rg, v.ba); return max(m2.r, m2.g); }
float min(vec4 v) { vec2 m2 = min(v.rg, v.ba); return min(m2.r, m2.g); }
int select(bvec2 candidates, float rnd) { return (candidates.x && (!candidates.y || rnd > .5)) ? 1 : 2; }
int select(bvec4 candidates, vec2 rnd) {
return any(candidates.rg) && ((!any(candidates.ba)) || (rnd.r > .5)) ? select(candidates.rg, rnd.g) : (select(candidates.ba, rnd.g) * 4);
}
ivec3 /* ( action, direction, state )*/
d1( float food, float tbd, int species, float mem, float energy, float protection,
vec4 rnd,
vec4 prox_food, vec4 prox_tbd, ivec4 prox_species, vec4 prox_mem, vec4 prox_energy, vec4 prox_protect
){
bvec4 vacancies = equal(prox_species, ivec4(0));
bvec4 friends = equal(prox_species, ivec4(species));
bvec4 ennemies = equal( ivec4(friends) + ivec4(vacancies), ivec4(0) );
vec4 vacant_food = prox_food * vec4(vacancies);
float max_vacant_food = max(vacant_food);
bvec4 pos_vacant_food = equal(vacant_food, vec4(max_vacant_food));
if(protection < $1 && energy > ($costBuild + $1)) return ivec3($_build, 0, 0);
if(any(ennemies)) {
if(any(friends)) return ivec3($_take, select(ennemies, rnd.rg), 0);
if(any(vacancies)) {
if(rnd.r < energy) return ivec3($_take, select(ennemies, rnd.gb), 0);
else return ivec3($_move, select(vacancies, rnd.gb), 0);
}
return ivec3($_die, 0, 0);
}
if(!any(friends)) {
if(food > 2. * energy) return ivec3($_eat, 0, 0);
if(energy > ($costMove + $1) && any(vacancies) && rnd.r < .1) return ivec3($_move, select(pos_vacant_food, rnd.gb), 0);
return ivec3($_eat, 0, 0);
} else {
float min_friend = min(prox_energy + vec4(not(friends)));
if(energy > 2. * min_friend) return ivec3($_give, select(equal(prox_energy + vec4(not(friends)), vec4(min_friend)) , rnd.rg), 0);
if(energy > 2. * protection) return ivec3($_build, 0, 0);
if(energy > ($costClone + $1) && any(vacancies)) return ivec3($_clone, select(vacancies, rnd.rg), 0);
if(rnd.r < .1 && (!any(friends.rgb) || !any(friends.gba) || !any(friends.rba) || !any(friends.rga)) && max_vacant_food > 2. * food)
return ivec3($_move, select(pos_vacant_food, rnd.ba), 0);
return ivec3($_eat, 0, 0);
}
}
void main(void) {
// fetch data here
vec2 pos = gl_FragCoord.xy * $invSize;
vec4 bg = texture2D(background, pos);
vec4 cell = texture2D(cells, pos);
// regenerate food
vec4 rnd = texture2D(entropy, pos + seed);
if(texture2D(entropy, pos + seed).r < $probaRegenerate) bg.r += $1;
if(cell.r != 0.) {
// fetch proximity data
vec2 bg_left = texture2D(background, pos + vec2(-$invWidth, 0.)).rg;
vec2 bg_right = texture2D(background, pos + vec2( $invWidth, 0.)).rg;
vec2 bg_up = texture2D(background, pos + vec2(0.,-$invHeight)).rg;
vec2 bg_down = texture2D(background, pos + vec2(0., $invHeight)).rg;
vec4 ce_left = texture2D(cells, pos + vec2(-$invWidth, 0.));
vec4 ce_right = texture2D(cells, pos + vec2( $invWidth, 0.));
vec4 ce_up = texture2D(cells, pos + vec2(0., -$invHeight));
vec4 ce_down = texture2D(cells, pos + vec2(0., $invHeight));
// transpose proximity
vec4 food = vec4(bg_left.r, bg_right.r, bg_up.r, bg_down.r);
ivec4 species = ivec4( vec4(ce_left.r, ce_right.r, ce_up.r, ce_down.r) * 256. );
vec4 tbd = vec4(bg_left.g, bg_right.g, bg_up.g, bg_down.g);
vec4 mems = vec4(ce_left.g, ce_right.g, ce_up.g, ce_down.g);
vec4 energy = vec4(ce_left.b, ce_right.b, ce_up.b, ce_down.b);
vec4 protection = vec4(ce_left.a, ce_right.a, ce_up.a, ce_down.a);
// call decision function
float f = bg.r; // food
float t = bg.g; // tbd
int s = int(cell.r * 256.); // species
float m = cell.g; // memory
float e = cell.b; // energy
float p = cell.a; // protection
ivec3 decision;
/*
if(s == 1) decision = d1(bg.rg, cell, rnd, food, tbd, species, states, energy, protection); else
if(s == 2) decision = d2(bg.rg, cell, rnd, food, tbd, species, states, energy, protection); else
decision = ivec3(0);*/
decision = d1(f, t, s, m, e, p, rnd, food, tbd, species, mems, energy, protection);
// die if trying a too expensive action /// TODO: not all or nothing for draw/build
if((decision.r == $_draw && cell.a < $costDraw)
|| (decision.r == $_build && cell.b < $costBuild)
|| (decision.r == $_move && cell.b < $costMove)
|| (decision.r == $_give && cell.b < $costGive)
|| (decision.r == $_clone && cell.b < $costClone)
) decision = ivec3($_die, 0, 0);
// revert moves/clones towards occupied positions
else if(decision.r == $_move || decision.r == $_clone) {
if((decision.g == 1 && species.r != 0)
|| (decision.g == 2 && species.g != 0)
|| (decision.g == 4 && species.b != 0)
|| (decision.g == 8 && species.a != 0)
) decision.rg = ivec2(0);
}
// eating consumes food from background
else if(decision.r == $_eat) { if(bg.r < $costEat) decision.r = 0; else bg.r -= $costEat; }
// write results
gl_FragColor = vec4(bg.rg, float(decision.b) * $1, float(decision.r) * $1 + float(decision.g) * $16);
} else gl_FragColor = vec4(bg.rg, vec2(0.));
}
</script>
<script type="x-shader/x-fragment" id="resolve">
uniform sampler2D background, cells, entropy;
uniform vec2 seed;
float select2(bvec2 candidates, float rnd) {
if(rnd > .5) return candidates.r ? 2. : 1.;
else return candidates.g ? 1. : 2.;
}
float select4(bvec4 candidates, vec4 rnd) {
if(rnd.r > .5) return any(candidates.rg) ? select2(candidates.rg, rnd.g) : 4. * select2(candidates.ba, rnd.g);
else return any(candidates.ba) ? 4. * select2(candidates.ba, rnd.g) : select2(candidates.rg, rnd.g);
}
float select(vec4 neighborhood, vec4 rnd) {
ivec4 actions = ivec4(mod(neighborhood + $half, $16) * 255.);
actions *= ivec4(equal( ivec4(neighborhood * 16. + .5), ivec4(2, 1, 8, 4) ));
// cloning has priofity over moves
bvec4 isClone = equal(actions, ivec4($_clone));
if(any(isClone)) return select4(isClone, rnd);
bvec4 isMove = equal(actions, ivec4($_move));
if(any(isMove)) return select4(isMove, rnd);
return 0.; // no conflicting actions
}
void main(void) {
vec2 pos = gl_FragCoord.xy * $invSize;
vec4 bg = texture2D(background, pos);
vec4 cell = texture2D(cells, pos);
if(cell.r == 0.) {
gl_FragColor = vec4(bg.rgb, $16 * select(
vec4(
texture2D(background, pos + vec2(-$invWidth, 0.)).a,
texture2D(background, pos + vec2( $invWidth, 0.)).a,
texture2D(background, pos + vec2(0., -$invHeight)).a,
texture2D(background, pos + vec2(0., $invHeight)).a
),
texture2D(entropy, pos + seed)
));
} else gl_FragColor = bg;
}
</script>
<script type="x-shader/x-fragment" id="act">
uniform sampler2D background, cells, entropy;
uniform vec2 seed;
vec2 taken(float protect) { vec2 r; r.x = $taken - (r.y = min(protect, $taken)); return r; }
vec4 collateral(int action, vec4 here, vec4 source) {
if(here.a == 0.) { // create/move cell to empty position
if(action == $_move) return source - vec4(0., 0., $costMove, 0.);
if(action == $_clone) return vec4(source.r, 0., $initE, $initP);
} else { // interact between 2 cells
if(action == $_give) return here + vec4(0., 0., $gainGive, 0.);
if(action == $_take) return here - vec4(0., 0., taken(here.a));
}
return here;
}
void main(void) {
vec2 pos = gl_FragCoord.xy * $invSize;
vec4 cell = texture2D(cells, pos);
vec4 neighborhood = vec4( texture2D(background, pos + vec2(-$invWidth, 0.)).a,
texture2D(background, pos + vec2( $invWidth, 0.)).a,
texture2D(background, pos + vec2(0., -$invWidth)).a,
texture2D(background, pos + vec2(0., $invWidth)).a );
ivec4 actions = ivec4(mod(neighborhood + $half, $16) * 255.);
ivec4 directions = ivec4(neighborhood * 16. + .5);
if(cell.r != 0.) {
// set state
vec4 bg = texture2D(background, pos);
if(cell.r != 0.) cell.g = bg.b;
// revert conflicting actions that were not selected by "resolve"
int action = int(mod(bg.a + $half, $16) * 255.);
if(action == $_move || action == $_clone) {
int direction = int(bg.a * 16. + .5);
float ctrl_f;
if(direction == 1) ctrl_f = texture2D(background, pos + vec2(-$invWidth, 0.)).a; else
if(direction == 2) ctrl_f = texture2D(background, pos + vec2( $invWidth, 0.)).a; else
if(direction == 4) ctrl_f = texture2D(background, pos + vec2(0., -$invWidth)).a; else
if(direction == 8) ctrl_f = texture2D(background, pos + vec2(0., $invWidth)).a; else
ctrl_f = 0.;
if(direction != int(ctrl_f * 16.)) action = 0;
}
// apply first half of actions : on owner
if(action == $_eat) cell.b += $gainEat; else
if(action == $_draw) { cell.b += $gainDraw; cell.a -= $costDraw; } else
if(action == $_build) { cell.b -= $costBuild; cell.a += $gainDraw; } else
if(action == $_move) { cell = vec4(0.); }
if(action == $_give) { cell.b -= $costGive; } else
if(action == $_take) {
int direction = int(bg.a * 16. + .5);
vec4 other;
if(direction == 1) other = texture2D(cells, pos + vec2(-$invWidth, 0.)); else
if(direction == 2) other = texture2D(cells, pos + vec2( $invWidth, 0.)); else
if(direction == 4) other = texture2D(cells, pos + vec2(0., -$invWidth)); else
if(direction == 8) other = texture2D(cells, pos + vec2(0., $invWidth));
vec2 t = taken(other.a);
cell.b += t.x * $gainTake - t.y * $costTake;
} else
if(action == $_clone) { cell.b -= $costClone; } else
if(action == $_die) { cell = vec4(0.); }
}
// apply second half of actions : on affected neighboors
if(directions.r == 2) cell = collateral(actions.r, cell, texture2D(cells, pos + vec2(-$invWidth, 0.)));
if(directions.g == 1) cell = collateral(actions.g, cell, texture2D(cells, pos + vec2( $invWidth, 0.)));
if(directions.b == 8) cell = collateral(actions.b, cell, texture2D(cells, pos + vec2(0., -$invWidth)));
if(directions.a == 4) cell = collateral(actions.a, cell, texture2D(cells, pos + vec2(0., $invWidth)));
// final EP check
if(cell.r != 0.) {
if(cell.a < $1) cell.b -= $costNaked;
if(cell.b < $1) cell = vec4(0.);
} else cell = vec4(0.);
gl_FragColor = cell;
}
</script>
</head><body onload="entry()">
<canvas id="surface">
No WebGL!
</canvas>
</body></html>