-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
1477 lines (1301 loc) · 59.6 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
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chromatography</title>
<style>
html {
font-family: sans-serif;
}
.blotting-paper {
border-width: 1px;
border-color: lightgrey;
border-style: solid;
box-shadow: 10px 10px 5px #888888;
background-color: white;
}
#myCanvas { // make them canvas pixels bigger. Assuming the canvas is 100x100, the pixels become 4x4
width: 90vh;
height: 90vh;
}
.remove {
display:none;
}
#configparams form table td {
border: 1px solid lightgrey;
}
</style>
<script src="assets/cellauto.min.js"></script>
<script>
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
</script>
<script>
const Chroma = (function(){
const DYES = [
{
name: 'red',
Rf: 0.8, // propensity to go with the flow
Rd: 0.007, // propensity to 'bleed' if no flow
RGBPattern: [1.0, 0, 0], // how to read it's value from/to RGB triple
CMYKPattern: [100, 0, 0, 0],
},
{
name: 'green',
Rf: 0.85,
Rd: 0.0075,
RGBPattern: [0, 1.0, 0],
CMYKPattern: [0, 100, 0, 0],
},
{
name: 'blue',
Rf: 0.9,
Rd: 0.006,
RGBPattern: [0, 0, 1.0],
CMYKPattern: [0, 0, 100, 0],
},
];
{
// check internal consistency of Rf and Rd
let numDirections = 8;
for( let dye of DYES ){
if (dye.Rf > 1 || dye.Rf < 0) {
throw new Error(`ERROR: Rf out of bounds: dye: ${JSON.stringify(dye)}`);
}
if (dye.Rd > 1 || dye.Rd < 0) {
throw new Error(`ERROR: Rd out of bounds: dye: ${JSON.stringify(dye)}`);
}
}
}
DYES.RGBMaximum = 253;
DYES.newEmptyDyeAmounts = function() {
return new Array(this.length).fill(0);
}
DYES.cloneAmounts = function(from) {
return from.slice(0);
}
DYES.copyAmounts = function(from, to){
for (var i = 0; i < this.length; i++) {
to[i] = from[i];
}
}
DYES.addAmounts = function(from, to){
for (var i = 0; i < this.length; i++) {
to[i] = to[i] + from[i];
}
}
DYES.subtractAmounts = function(from, to){
for (var i = 0; i < this.length; i++) {
to[i] = to[i] - from[i];
}
}
DYES.combineDyesIntoRgbaPixel = function(dyeAmounts) {
// return [R, G, B, A]
// assume no dyes => full white
// calc 0-1.0 range, then convert to 0-255 later
var rgba01 = new Array(3).fill(0);
for (var d = 0; d < this.length; d++) {
for (var i = 0; i < 3; i++) {
rgba01[i] = rgba01[i] + (dyeAmounts[d] * this[d].RGBPattern[i]);
}
}
var maxRGB01 = Math.max.apply(null, rgba01);
if (maxRGB01 > 1.0) {
rgba01 = rgba01.map(c => {return c/maxRGB01});
maxRGB01 = 1.0;
}
rgba01.push(maxRGB01);
if (maxRGB01 == 0) {
rgba01.fill(1.0);
}
var rgba = rgba01.map(c => {return (c>1.0)? 255 : Math.floor(c * 255);});
return rgba;
}
DYES.CMYKtoRGB = function (cmyk, a=255){
// input array of 4 x 0-100 (CMYK)
// output array of 3 x 0-255 (RGB)
var rgb = new Array(4).fill(0);
rgb[3] = a;
c = cmyk[0] / 100;
m = cmyk[1] / 100;
y = cmyk[2] / 100;
k = cmyk[3] / 100;
rgb[0] = 1 - Math.min( 1, c * ( 1 - k ) + k );
rgb[1] = 1 - Math.min( 1, m * ( 1 - k ) + k );
rgb[2] = 1 - Math.min( 1, y * ( 1 - k ) + k );
rgb[0] = Math.round( rgb[0] * 255 );
rgb[1] = Math.round( rgb[1] * 255 );
rgb[2] = Math.round( rgb[2] * 255 );
return rgb;
},
function getMaxOfArray(numArray) {
return Math.max.apply(null, numArray);
}
DYES.combineCMYDyesIntoRgbaPixel = function(dyeAmounts) {
// return [R, G, B, A]
// assume no dyes => full white
// assume ammount==1 corresponds to 100% of the CMYK colour,
// clip at 1,
const cmykTotals = new Array(4).fill(0);
for (var d = 0; d < this.length; d++) {
for (var i = 0; i < 3; i++) {
cmykTotals[i] = cmykTotals[i] + (dyeAmounts[d] * this[d].CMYKPattern[i]);
}
}
const cmykScaled = cmykTotals.map(t => { return t / 40; });
const cmykClippedToPercentage = cmykScaled.map(t => { return 100 * ((t>1.0)? 1.0 : t); });
const rgba= DYES.CMYKtoRGB( cmykClippedToPercentage, 255 );
return rgba;
}
DYES.writeGridOfDyeAmountsToImageData = function(grid, imageData, dyeSpace){
if ((imageData.width !== grid.length) || (imageData.height !== grid[0].length)) {
throw new Error(`Error: mismatch found between size of grid and imageData`);
}
// const combineDyesToRgbaFn = (dyeSpace == 'cmyk')? this['combineCMYDyesIntoRgbaPixel'] : this['combineDyesIntoRgbaPixel'];
const data = imageData.data;
for (var x=0; x<imageData.width; x++) {
for (var y=0; y<imageData.height; y++) {
var dyeAmounts = grid[x][y];
var rgba = (dyeSpace == 'cmyk')? this.combineCMYDyesIntoRgbaPixel(dyeAmounts) : this.combineDyesIntoRgbaPixel(dyeAmounts);
var dataCellIndex = 4 * (x + (y * imageData.width));
for (var i = 0; i < 4; i++) {
data[dataCellIndex+i] = rgba[i];
}
}
}
return imageData;
}
//------------
var PaperSpot = function(dyeAmounts, waterAmount=0, configs={}){
this.dyeAmounts = (dyeAmounts)? dyeAmounts.slice(0) : DYES.newEmptyDyeAmounts();
this.waterAmount = waterAmount;
this._configs = configs;
for (c of Object.keys(this._defaultConfigs)) {
this[c] = (configs.hasOwnProperty(c))? configs[c] : this._defaultConfigs[c];
}
}
PaperSpot.prototype = (function () {
/* private members */
let _defaultConfigs = {
MaxWaterCapacity : 1,
WaterAbsorptionRate : 0.1,
};
/* public members */
return {
_defaultConfigs : _defaultConfigs,
clone: function(){ return new PaperSpot(this.dyeAmounts, this.waterAmount, this._configs); },
stringify: function(){ return JSON.stringify(this); },
copy: function(from){
this.waterAmount = from.waterAmount;
DYES.copyAmounts(from.dyeAmounts, this.dyeAmounts);
},
addDroplet: function(drop){
this.waterAmount = Math.min(this.waterAmount + drop.waterAmount, this.MaxWaterCapacity);
for (var i = 0; i < this.dyeAmounts.length; i++) {
this.dyeAmounts[i] = this.dyeAmounts[i] + drop.dyeAmounts[i];
}
return this;
},
};
})();
//------------
var WaterSpot = function(waterAmount, dyeAmounts, configs={}){
this.waterAmount = (waterAmount)? waterAmount : 0;
this.dyeAmounts = (dyeAmounts)? dyeAmounts.slice(0) : DYES.newEmptyDyeAmounts();
this._configs = configs;
for (c of Object.keys(this._defaultConfigs)) {
this[c] = (configs.hasOwnProperty(c))? configs[c] : this._defaultConfigs[c];
}
}
WaterSpot.prototype = (function(){
/* private members */
let _defaultConfigs = {
SpreadMinAmountToGoToDryFactor : 1,
};
/* public members */
return {
_defaultConfigs : _defaultConfigs,
clone: function() { return new WaterSpot(this.waterAmount, this.dyeAmounts, this._configs); },
addDroplet: function(drop){
this.waterAmount = this.waterAmount + drop.waterAmount;
for (var i = 0; i < this.dyeAmounts.length; i++) {
this.dyeAmounts[i] = this.dyeAmounts[i] + drop.dyeAmounts[i];
}
return this;
},
divideBy: function(n){
this.waterAmount = this.waterAmount/n;
for (var i = 0; i < this.dyeAmounts.length; i++) {
this.dyeAmounts[i] = this.dyeAmounts[i] / n;
}
return this;
},
stringify: function(){ return JSON.stringify(this); },
copy: function(from){
this.waterAmount = from.waterAmount;
DYES.copyAmounts(from.dyeAmounts, this.dyeAmounts);
},
};
})();
WaterSpot.createBigRedDrop = function() {
const waterAmount = 1000.0;
const dyeAmounts = DYES.newEmptyDyeAmounts();
dyeAmounts[0] = 3000.0;
const drop = new WaterSpot(waterAmount, dyeAmounts);
return drop;
}
WaterSpot.createBigRandomDrop = function(volume=1, dilution=1) {
const waterAmount = volume;
const dyeAmounts = DYES.newEmptyDyeAmounts();
for (var i = 0; i < dyeAmounts.length; i++) {
dyeAmounts[i] = volume*Math.random()*dilution;
}
const drop = new WaterSpot(waterAmount, dyeAmounts);
return drop;
}
//------------
var CellSpot = function(paperSpot, waterSpot, spotConfigs={}){
this.paperSpot = (paperSpot)? paperSpot.clone() : new PaperSpot(null, 0, spotConfigs);
this.waterSpot = (waterSpot)? waterSpot.clone() : new WaterSpot(0, null, spotConfigs);
this.spotConfigs = spotConfigs;
}
CellSpot.prototype = (function(){
/* private members */
/* public members */
return {
clone: function(){ return new CellSpot(this.paperSpot, this.waterSpot, this.spotConfigs); },
addDroplet: function(drop){ this.waterSpot.addDroplet(drop); },
stringify: function(){ return JSON.stringify(this); },
copy: function(from){
this.paperSpot.copy(from.paperSpot);
this.waterSpot.copy(from.waterSpot);
},
};
})();
//------------
// accept a list of { x: , y: , droplet: }
// loop over the list, reset each cell and add to the cell.next (because reset happens before process)
CAWorld.prototype.addDroplets = function(spotsWithCoords) {
for (spot of spotsWithCoords) {
var cell = this.grid[spot.y][spot.x];
if (! cell) {
console.log(`DEBUG: CAWorld.prototype.addDroplets: spot.x=${spot.x}, spot.y=${spot.y}, this.height=${this.height}, this.width=${this.width}`);
}
// cell.reset();
var cellSpot = cell.next;
cellSpot.addDroplet(spot.droplet);
this.waterDropletsAddedToSurface.addDroplet(spot.droplet);
this.SurfaceWaterAmount = this.SurfaceWaterAmount + spot.droplet.waterAmount;
}
};
//------------
// accept a centre x,y of a drop of radius r, containing full WaterSpot of ink+water.
// expand into a call to addDroplets
CAWorld.prototype.addBigDrop = function(centreX, centreY, r, v, d) {
const fromX = Math.floor( Math.max(centreX - r, 0));
const toX = Math.floor( Math.min(centreX + r, this.height-1));
const fromY = Math.floor( Math.max(centreY - r, 0));
const toY = Math.floor( Math.min(centreY + r, this.width-1));
const spotsWithCoords = [];
// record any x,y that is within the radius of the centre
for (var x=fromX; x<=toX; x++) {
for (var y=fromY; y<=toY; y++) {
const dx = x - centreX;
const dy = y - centreY;
if ((dx*dx + dy*dy) <= r*r) {
spotsWithCoords.push({ x:x, y:y });
}
}
}
// assume waterSpot is divided equally between droplets
const numDroplets = spotsWithCoords.length;
const droplet = WaterSpot.createBigRandomDrop(v, d);
spotsWithCoords.forEach(swc => {
swc.droplet = droplet.clone();
});
this.addDroplets(spotsWithCoords);
};
//------------
// add a stepCount
CAWorld.prototype.stepWithCount = function() {
if( !this.stepCount ){ this.stepCount = 0; }
this.stepCount = this.stepCount + 1;
this.stepThroughAllProcesses();
};
CAWorld.prototype.resetGrid = function() {
let surfaceWaterAmount = 0;
let grid = this.grid;
let y, x;
for (y=0; y<this.height; y++) {
for (x=0; x<this.width; x++) {
grid[y][x].reset();
surfaceWaterAmount = surfaceWaterAmount + grid[x][y].value.waterSpot.waterAmount;
}
}
this.SurfaceWaterAmount = surfaceWaterAmount;
}
CAWorld.prototype.addProcessTiming = function(name, timing) {
if (! this.processTimings.hasOwnProperty(name)) {
this.processTimings[name] = [];
}
this.processTimings[name].push(timing);
}
var neighborhood = [null, null, null, null, null, null, null, null];
CAWorld.prototype.stepThroughProcess = function(processName) {
const skipBecauseSurfaceDry = (
this.SurfaceWaterAmount <= 0
&&
this.processesInvolvingOnlySurfaceWater.includes(processName)
);
if(! skipBecauseSurfaceDry){
const startGridMillis = Date.now();
this.resetGrid();
const endGridMillis = Date.now();
this.addProcessTiming('resetGrid', endGridMillis - startGridMillis);
}
{
const startProcessMillis = Date.now();
if (! skipBecauseSurfaceDry) {
// bottom up, left to right processing
for (y=this.height-1; y>=0; y--) {
for (x=this.width-1; x>=0; x--) {
this.fillNeighbors(neighborhood, x, y);
var cell = this.grid[y][x];
cell[processName](neighborhood);
// perform any delays
for (var i=0; i<cell.delays.length; i++) {
cell.delays[i].steps--;
if (cell.delays[i].steps <= 0) {
// perform action and remove delay
cell.delays[i].action(cell);
cell.delays.splice(i, 1);
i--;
}
}
}
}
}
const endProcessMillis = Date.now();
this.addProcessTiming(processName, endProcessMillis - startProcessMillis);
}
};
CAWorld.prototype.stepThroughAllProcesses = function() {
this.Processes.forEach( name => {
this.stepThroughProcess(name);
});
}
CAWorld.ARBITRARY_MAX = 1000;
CAWorld.DefaultConfig = {
EvaporationFromPaperRate : {
value : 0.001,
range : [0, CAWorld.ARBITRARY_MAX],
description : 'max amount of absorbed water which will evaporate from the paper',
},
EvaporationFromSurfaceRate : {
value : 0.0005,
range : [0, CAWorld.ARBITRARY_MAX],
description : 'max amount of surface water which will evaoprate from the paper',
},
SpreadMinAmountToGoToDry : {
value : 1,
range : [0, CAWorld.ARBITRARY_MAX],
description : "cell needs this min amount of surface water before spreading to a dry cell"
},
DownhillTipRatio : {
value : 3,
range : [1, CAWorld.ARBITRARY_MAX],
description : "if there's a slope, the downhill SpreadMinAmountToGoToDry is multiplied by this factor"
},
DownhillTipRatioPartialDivisor : {
value : Math.SQRT2,
range : [1, CAWorld.ARBITRARY_MAX],
description : "divide DownhillTipRatio by this factor for the corner nhrs"
},
ScaleForFlowToWet : {
value : 1,
range : [0, 2],
description : "speed or slow the flow from wet to wet surface"
},
ScaleForFlowToDry : {
value : 1,
range : [0, 2],
description : "speed or slow the flow from wet to dry surface"
},
PaperAbsorptionFactor : {
value : 0.5,
range : [0, 1],
description : 'modify the water absorption rate across the whole paper'
},
PaperCapillaryFactor : {
value : 1,
range : [0, 1],
description : 'modify the capillary flow rate across the whole paper'
},
PaperDiffusionFactor : {
value : 0.5,
range : [0, 1],
description : 'modify the diffusion flow rate across the whole paper'
},
WaterDiffusionFactor : {
value : 0.5,
range : [0, 1],
description : 'modify the diffusion flow rate across the whole paper surface'
},
WaterDiffusionFactor : {
value : 0.5,
range : [0, 1],
description : 'modify the diffusion flow rate across the whole paper surface'
},
Processes : {
value : ['surfaceFlow', 'absorption', 'surfaceFlow', 'capillaryFlow', 'diffusion', 'evaporation', 'sanityCheckValue'],
known : ['absorption', 'surfaceFlow', 'capillaryFlow', 'diffusion', 'evaporation', 'sanityCheckValue'],
description : 'the sequence of physical processes to run in turn on the grid',
},
PaperSpotMaxWaterCapacityRange : {
value : [0.9,1.1],
range : [0, CAWorld.ARBITRARY_MAX],
type : 'range',
description : "range of possible values for each PaperSpot's max water capacity (chosen at random when each spot is first created)",
},
PaperSpotWaterAbsorptionRateRange : {
value : [0.09,0.11],
range : [0, CAWorld.ARBITRARY_MAX],
type : 'range',
description : "range of possible values for each PaperSpot's waterAbsorptionRate (chosen at random when each spot is first created)",
},
PaperSpotSpreadMinAmountToGoToDryFactorRange : {
value : [0.5,2],
range : [0, CAWorld.ARBITRARY_MAX],
type : 'range',
description : "range of possible values for each PaperSpot's waterSpreadfactor, changing the threshold before water flows from this spot to a dry neighbour, as a factor of the paper default. 0 means no threshold, 1 means the paper default, >1 means more than the paper default (chosen at random when each spot is first created)",
},
};
CAWorld.prototype.importConfig = function(config) {
// create and load up this.config with the default values, and then override them as and when
this.config = {};
// loop over keys of DefaultConfig, looking for overrides in config,
for( let key of Object.keys(CAWorld.DefaultConfig) ) {
const details = CAWorld.DefaultConfig[key];
if (details.hasOwnProperty('value')) {
let value = details.value;
if (config != undefined) {
value = config[key]; // assume configs have already been checked
}
this.config[key] = value; // add to world config map, for documentation
world[key] = value; // push into world instance directly
}
}
console.log(`world configs=${JSON.stringify(this.config, null, " ")}`);
}
//------------
function createWorldOfBlottingPaperAndDyes(width, height, config={}) {
world = new CAWorld({
width: Math.floor(width),
height: Math.floor(height),
});
world.directions = [world.LEFT, world.RIGHT, world.BOTTOM, world.TOP, world.TOPLEFT, world.TOPRIGHT, world.BOTTOMLEFT, world.BOTTOMRIGHT];
// tracking loss/gain of substance (rather than moved between cells)
world.waterSpotLost = new WaterSpot();
world.waterEvaporationFromPaper = new WaterSpot();
world.waterEvaporationFromSurface = new WaterSpot();
world.waterDropletsAddedToSurface = new WaterSpot(); // to be subtracted from the final totals
// processname -> [timings]
world.processTimings = {};
world.processesInvolvingOnlySurfaceWater = ['absorption', 'surfaceFlow'];
world.importConfig( config );
world.registerCellType('paper', {
getCellValue: function () {
return this.value;
},
getCellNextValue: function () {
return this.next;
},
sanityCheckValue: function() {
const thisValueWaterSpot = this.value.waterSpot;
const thisValuePaperSpot = this.value.paperSpot;
function thisError(msg){
throw new Error(`ERROR: (${this.x}, ${this.y}): ${msg}`);
}
if (thisValuePaperSpot.waterAmount < 0) { thisError(`thisValuePaperSpot.waterAmount < 0, ${thisValuePaperSpot.waterAmount}`); }
if (thisValueWaterSpot.waterAmount < 0) { thisError(`thisValueWaterSpot.waterAmount < 0, ${thisValueWaterSpot.waterAmount}`); }
for (var d = 0; d < DYES.length; d++) {
if (thisValuePaperSpot.dyeAmounts[d] < 0) { thisError(`thisValuePaperSpot.dyeAmounts[${d}]<0, ${thisValuePaperSpot.dyeAmounts[d]}`); }
if (thisValueWaterSpot.dyeAmounts[d] < 0) { thisError(`thisValueWaterSpot.dyeAmounts[${d}]<0, ${thisValueWaterSpot.dyeAmounts[d]}`); }
}
},
absorption: function (neighbors) {
// - some of the current surface water (plus the associated dyes) get absorbed
// - capacity of paper
// - Rf for the dyes? Dyes get concentrated in remaining/reducing surface water?
// - some dyes get absorbed 'deeper' into the paper?
const thisNextWaterSpot = this.next.waterSpot;
const thisNextPaperSpot = this.next.paperSpot;
const thisValueWaterSpot = this.value.waterSpot;
const thisValuePaperSpot = this.value.paperSpot;
if (thisValueWaterSpot.waterAmount > 0) {
const remainingPaperWaterCapacity = thisValuePaperSpot.MaxWaterCapacity - thisValuePaperSpot.waterAmount;
if (remainingPaperWaterCapacity > 0) {
const waterAmountToBeAbsorbed = Math.min(thisValueWaterSpot.waterAmount, thisValuePaperSpot.WaterAbsorptionRate, remainingPaperWaterCapacity) * world.PaperAbsorptionFactor;
const proportionWaterAmountToBeAbsorbed = (waterAmountToBeAbsorbed / thisValueWaterSpot.waterAmount);
// transfer water: add to paper, remove from water
thisNextPaperSpot.waterAmount = thisNextPaperSpot.waterAmount + waterAmountToBeAbsorbed;
thisNextWaterSpot.waterAmount = thisNextWaterSpot.waterAmount - waterAmountToBeAbsorbed;
// transfer dyes: add to paper, remove from water
for (var d = 0; d < DYES.length; d++) {
const flowProportion = (proportionWaterAmountToBeAbsorbed == 1)? 1 : proportionWaterAmountToBeAbsorbed * DYES[d].Rf;
const flowAmount = flowProportion * thisValueWaterSpot.dyeAmounts[d];
thisNextPaperSpot.dyeAmounts[d] = thisNextPaperSpot.dyeAmounts[d] + flowAmount;
thisNextWaterSpot.dyeAmounts[d] = thisNextWaterSpot.dyeAmounts[d] - flowAmount;
}
}
}
return true;
},
surfaceFlow: function (neighbors) {
// - remaining surface water can flow (and splodge) from/to here, taking into account
// - when both cells are wet, flow towards midpoint of water amounts
// - when both cells are dry, nothing happens
// - when one cell is wet, the other dry, the wet one flows into the dry one if there is a min amount
// - if there is a slope,
// the min amount is adjusted accordingly (down for downhill, up for uphill),
// the resultant water amounts are also adjusted (large for downhill)
// - dividing any amounts by 8
// - surface characteristics? could adjust the min height amount...
// - dyes flow in the same proportion as the water
const thisNextWaterSpot = this.next.waterSpot;
const thisNextPaperSpot = this.next.paperSpot;
const thisValueWaterSpot = this.value.waterSpot;
const thisValuePaperSpot = this.value.paperSpot;
function flowWithNhbr(direction, downhillTipRatio){
// downhillTipRatio is factor when calculated from this cell.
// -- to multiply world.SpreadMinAmountToGoToDry
// -- Invert if from nhbr.
// -- ==1 for level
// -- >1 for here is downhill side
// -- <1 for here is uphill sides
// -- always > 0
// return as soon as we work out no flow will happen
const nhbr = neighbors[direction.index];
let nhbrValueWaterSpot;
let nhbrValueWaterSpotWaterAmount = 0;
if (nhbr) {
nhbrValueWaterSpot = nhbr.value.waterSpot;
nhbrValueWaterSpotWaterAmount = nhbrValueWaterSpot.waterAmount;
}
// skip if both cells are dry (including if there is no nhbr)
if ((thisValueWaterSpot.waterAmount == 0) && (nhbrValueWaterSpotWaterAmount == 0)) {
return;
}
// return if either nhbr is empty, and the other is not wet enough
if (thisValueWaterSpot.waterAmount == 0) {
if (nhbrValueWaterSpotWaterAmount <= (nhbrValueWaterSpot.SpreadMinAmountToGoToDryFactor * world.SpreadMinAmountToGoToDry * downhillTipRatio)) {
return;
}
} else if (nhbrValueWaterSpotWaterAmount == 0) {
if (thisValueWaterSpot.waterAmount <= (thisValueWaterSpot.SpreadMinAmountToGoToDryFactor * world.SpreadMinAmountToGoToDry / downhillTipRatio) ) {
return;
}
}
// assume that once the SpreadMinAmountToGoToDry threshold is breached,
// water flows to the same levels as if both sides had started with water.
// calc target amounts
const totalAmounts = thisValueWaterSpot.waterAmount + nhbrValueWaterSpotWaterAmount;
const thisTargetAmount = totalAmounts * downhillTipRatio / (downhillTipRatio + 1);
const nhbrTargetAmount = totalAmounts * 1 / (downhillTipRatio + 1);
const nhbrWaterDelta = nhbrTargetAmount - nhbrValueWaterSpotWaterAmount; // +ve means from here, -ve from nhbr.
const scaleForFlowToWetOrDry = (thisValueWaterSpot.waterAmount > 0 && nhbrValueWaterSpotWaterAmount > 0)? world.ScaleForFlowToWet : world.ScaleForFlowToDry;
const waterAmountFlowing = nhbrWaterDelta * scaleForFlowToWetOrDry / 8; // divided by 8 because is only one of 8 different here<->nhbr interactions.
if (waterAmountFlowing == 0) {
return;
} else if (waterAmountFlowing > 0) { // from this cell to nhbr, so only record loss from this cell if there is no nhbr
const proportionWaterAmountFlowing = waterAmountFlowing / thisValueWaterSpot.waterAmount;
thisNextWaterSpot.waterAmount = thisNextWaterSpot.waterAmount - waterAmountFlowing;
if(!nhbr) { world.waterSpotLost.waterAmount = world.waterSpotLost.waterAmount + waterAmountFlowing; }
// transfer dyes: in water
for (var d = 0; d < DYES.length; d++) {
const dyeAmountFlowing = thisValueWaterSpot.dyeAmounts[d] * proportionWaterAmountFlowing;
thisNextWaterSpot.dyeAmounts[d] = thisNextWaterSpot.dyeAmounts[d] - dyeAmountFlowing;
if(!nhbr){ world.waterSpotLost.dyeAmounts[d] = world.waterSpotLost.dyeAmounts[d] + dyeAmountFlowing; }
}
} else { // waterAmountFlowing < 0, flowing from nhbr to this cell
const waterAmountFlowingFromNhbr = - waterAmountFlowing;
thisNextWaterSpot.waterAmount = thisNextWaterSpot.waterAmount + waterAmountFlowingFromNhbr;
// transfer dyes: in water
const proportionWaterAmountFlowing = waterAmountFlowingFromNhbr / nhbrValueWaterSpotWaterAmount;
for (var d = 0; d < DYES.length; d++) {
const dyeAmountFlowing = nhbrValueWaterSpot.dyeAmounts[d] * proportionWaterAmountFlowing;
thisNextWaterSpot.dyeAmounts[d] = thisNextWaterSpot.dyeAmounts[d] + dyeAmountFlowing;
}
}
}
// assume
// - LEFT+RIGHT flow does not feel effect of slope
// - DOWN feels full effect slope
// - UP feels inverse of full effect of slope
// - DOWN LEFT+RIGHT feels partial effect of slope
// - UP LEFT+RIGHT feels inverse of partial effect of slope
const DownhillTipRatioPartial = world.DownhillTipRatio / world.DownhillTipRatioPartialDivisor;
flowWithNhbr(world.LEFT , 1 );
flowWithNhbr(world.RIGHT , 1 );
flowWithNhbr(world.TOP , world.DownhillTipRatio ); // TOP is down
flowWithNhbr(world.TOPLEFT , DownhillTipRatioPartial );
flowWithNhbr(world.TOPRIGHT , DownhillTipRatioPartial );
flowWithNhbr(world.BOTTOM , 1 / world.DownhillTipRatio ); // BOTTOM is up
flowWithNhbr(world.BOTTOMLEFT , 1 / DownhillTipRatioPartial );
flowWithNhbr(world.BOTTOMRIGHT, 1 / DownhillTipRatioPartial );
return true;
},
capillaryFlow: function (neighbors) {
// - water in paper will flow by capillary action, from high moisture to low
// - taking with it some dyes
// - only flows from/to a extant nhbr
const thisNextPaperSpot = this.next.paperSpot;
const thisValuePaperSpot = this.value.paperSpot;
const remainingPaperWaterCapacity = thisValuePaperSpot.MaxWaterCapacity - thisValuePaperSpot.waterAmount;
for (direction of world.directions) {
let nhbr = neighbors[direction.index];
if (!nhbr) { continue; }
let nhbrValuePaperSpot = nhbr.value.paperSpot;
let deltaWaterAmount = (thisValuePaperSpot.waterAmount - nhbrValuePaperSpot.waterAmount);
let deltaWaterAmountScaled = deltaWaterAmount / (2 * 8);
// +ve means from here, -ve from nhbr
if (remainingPaperWaterCapacity > 0 && deltaWaterAmountScaled < 0) {
let waterFlowAmount = Math.min(( - deltaWaterAmountScaled), remainingPaperWaterCapacity) * world.PaperCapillaryFactor;
thisNextPaperSpot.waterAmount = thisNextPaperSpot.waterAmount + waterFlowAmount;
let waterFlowProportion = waterFlowAmount / nhbrValuePaperSpot.waterAmount;
for (var d = 0; d < DYES.length; d++) {
let dyeFlowAmount = waterFlowProportion * DYES[d].Rf * nhbrValuePaperSpot.dyeAmounts[d];
thisNextPaperSpot.dyeAmounts[d] = thisNextPaperSpot.dyeAmounts[d] + dyeFlowAmount;
}
} else if(deltaWaterAmountScaled > 0) {
let nhbrRemainingPaperWaterCapacity = nhbrValuePaperSpot.MaxWaterCapacity - nhbrValuePaperSpot.waterAmount;
if (nhbrRemainingPaperWaterCapacity > 0) {
let waterFlowAmount = Math.min(deltaWaterAmountScaled, nhbrRemainingPaperWaterCapacity) * world.PaperCapillaryFactor;
thisNextPaperSpot.waterAmount = thisNextPaperSpot.waterAmount - waterFlowAmount;
let waterFlowProportion = waterFlowAmount / thisValuePaperSpot.waterAmount;
for (var d = 0; d < DYES.length; d++) {
let dyeFlowAmount = waterFlowProportion * DYES[d].Rf * thisValuePaperSpot.dyeAmounts[d];
thisNextPaperSpot.dyeAmounts[d] = thisNextPaperSpot.dyeAmounts[d] - dyeFlowAmount;
}
}
}
}
return true;
},
diffusion: function (neighbors) {
// - ink will diffuse, in wet paper
// - assume is related to relative concentrations, flowing from high to low (where both sides are wet)
// within wet paper, and on wet surface
for (let params of [
// [spotType, diffusionFactor]
['paperSpot', world.PaperDiffusionFactor],
['waterSpot', world.WaterDiffusionFactor]
]) {
const spotType = params[0];
const diffusionFactor = params[1];
if (diffusionFactor <= 0) { continue; }
const thisValueSpot = this.value[spotType];
const thisNextSpot = this.next[spotType];
if (thisValueSpot.waterAmount > 0) {
for (direction of world.directions) {
let nhbr = neighbors[direction.index];
if (!nhbr) { continue; }
let nhbrValueSpot = nhbr.value[spotType];
if (nhbrValueSpot.waterAmount <= 0) { continue; }
for (var d = 0; d < DYES.length; d++) {
let thisValueConcentration = thisValueSpot.dyeAmounts[d] / thisValueSpot.waterAmount;
let nhbrValueConcentration = nhbrValueSpot.dyeAmounts[d] / nhbrValueSpot.waterAmount;
let deltaConcentration = nhbrValueConcentration - thisValueConcentration;
if (deltaConcentration > 0) { // dye comes to here
let dyeFlowAmount = diffusionFactor * DYES[d].Rd * (deltaConcentration / nhbrValueConcentration) * nhbrValueSpot.dyeAmounts[d] / 8;
thisNextSpot.dyeAmounts[d] = thisNextSpot.dyeAmounts[d] + dyeFlowAmount;
} else if (deltaConcentration < 0) { // dye goes from here
let dyeFlowAmount = diffusionFactor * DYES[d].Rd * (deltaConcentration / thisValueConcentration) * thisValueSpot.dyeAmounts[d] / 8;
thisNextSpot.dyeAmounts[d] = thisNextSpot.dyeAmounts[d] + dyeFlowAmount;
}
}
}
}
}
return true;
},
evaporation: function (neighbors) {
// - paper will dry out as water evaporates
// - assume will not evaporate from paper if water on surface
// - for simplicity, apply evaporation to computed Next, otherwise needs to be included in all other calculations
// - handle when there are dyes in surface water which fully evaporates
const thisNextWaterSpot = this.next.waterSpot;
const thisNextPaperSpot = this.next.paperSpot;
const thisValueWaterSpot = this.value.waterSpot;
const thisValuePaperSpot = this.value.paperSpot;
if (thisValueWaterSpot.waterAmount > 0) {
let evapAmount = Math.min(thisValueWaterSpot.waterAmount, world.EvaporationFromSurfaceRate);
if (evapAmount > 0) {
thisNextWaterSpot.waterAmount = thisNextWaterSpot.waterAmount - evapAmount;
world.waterEvaporationFromSurface.waterAmount = world.waterEvaporationFromSurface.waterAmount + evapAmount;
if (thisNextWaterSpot.waterAmount == 0) {
thisNextPaperSpot.addDroplet(thisNextWaterSpot);
thisNextWaterSpot.dyeAmounts.fill(0);
}
}
}
else
if (thisValuePaperSpot.waterAmount > 0) {
let evapAmount = Math.min(thisValuePaperSpot.waterAmount, world.EvaporationFromPaperRate);
thisNextPaperSpot.waterAmount = thisNextPaperSpot.waterAmount - evapAmount;
world.waterEvaporationFromPaper.waterAmount = world.waterEvaporationFromPaper.waterAmount + evapAmount;
}
return true;
},
reset: function () {
let oldPrev = this.prev; // don't discard the old value
this.prev = this.value;
this.value = this.next;
this.next = oldPrev;
this.next.copy(this.value); // so adds and deletes happen in the .next value
return true;
}
}, function (x,y) {
//init
const spotConfig = {
MaxWaterCapacity : randomWithinRange(world.PaperSpotMaxWaterCapacityRange),
WaterAbsorptionRate : randomWithinRange(world.PaperSpotWaterAbsorptionRateRange),
SpreadMinAmountToGoToDryFactor : randomWithinRange(world.PaperSpotSpreadMinAmountToGoToDryFactorRange),
}
this.value = new CellSpot(null, 0, spotConfig);
this.prev = this.value.clone(); // NB, clone so inherits config characteristics
this.next = this.value.clone();
this.x = x;
this.y = y;
});
world.initialize([
{ name: 'paper', distribution: 100 }
]);
return world;
}
//------------
function randomWithinRange(range){
return range[0] + (range[1] - range[0]) * Math.random();
}
function writeWorldWaterAmountsToImageData(world, imageData){
var worldGrid = world.grid;
if ((imageData.width !== worldGrid.length) || (imageData.height !== worldGrid[0].length)) {
throw new Error(`Error: mismatch found between size of grid and imageData`);
}
const data = imageData.data;
for (var x=0; x<imageData.width; x++) {
for (var y=0; y<imageData.height; y++) {
const cellValue = worldGrid[y][x].getCellValue();
var rgba = [
(cellValue.waterSpot.waterAmount)*255,
(cellValue.paperSpot.waterAmount) * 255,
0,
255
];
var dataCellIndex = 4 * (x + (y * imageData.width));
for (var i = 0; i < 4; i++) {
data[dataCellIndex+i] = rgba[i];
}
}
}
return imageData;
}
//------------
function convertWorldGridToGridOfDyeAmounts(world, spotType='paperSpot'){
var worldGrid = world.grid;
var gridOfDyeAmounts = [];
// imageData reads from top left to bottom right
// world reads from bottom left to top right (I think)
for (var x = 0; x < world.width; x++) {
var col = [];
gridOfDyeAmounts.push(col);
for (var y = 0; y < world.height; y++) {
const cellValue = worldGrid[y][x].getCellValue();
let dyeAmounts;
if (spotType == 'paperSpot' || spotType == 'waterSpot') {
dyeAmounts = cellValue[spotType].dyeAmounts;
} else {
dyeAmounts = DYES.cloneAmounts(cellValue.paperSpot.dyeAmounts);
DYES.addAmounts(cellValue.waterSpot.dyeAmounts, dyeAmounts);
}
col.push( dyeAmounts );
}
}
return gridOfDyeAmounts;
}
function calcDyeAndWaterTotalsInWorld(world){
const worldGrid = world.grid;
const dyeAmountsInPaper = DYES.newEmptyDyeAmounts();
const dyeAmountsInWater = DYES.newEmptyDyeAmounts();
let waterAmountInPaper = 0;
let waterAmountOnSurface = 0;
for (var x = 0; x < world.width; x++) {
for (var y = 0; y < world.height; y++) {
let cell = worldGrid[y][x].getCellNextValue();
DYES.addAmounts(cell.paperSpot.dyeAmounts, dyeAmountsInPaper);
DYES.addAmounts(cell.waterSpot.dyeAmounts, dyeAmountsInWater);
waterAmountInPaper = waterAmountInPaper + cell.paperSpot.waterAmount;
waterAmountOnSurface = waterAmountOnSurface + cell.waterSpot.waterAmount;
}
}
const dyeAmountsTotal = DYES.newEmptyDyeAmounts();
DYES.addAmounts(dyeAmountsInPaper, dyeAmountsTotal);
DYES.addAmounts(dyeAmountsInWater, dyeAmountsTotal);
DYES.addAmounts(world.waterSpotLost.dyeAmounts, dyeAmountsTotal);
DYES.subtractAmounts(world.waterDropletsAddedToSurface.dyeAmounts, dyeAmountsTotal);
const dyeAmountTotal = dyeAmountsTotal.reduce( (prev, curr) => prev + curr );
const waterAmountTotal = [
waterAmountInPaper,
waterAmountOnSurface,
world.waterSpotLost.waterAmount,
world.waterEvaporationFromPaper.waterAmount,
world.waterEvaporationFromSurface.waterAmount
].reduce( (prev, curr) => prev + curr ) - world.waterDropletsAddedToSurface.waterAmount;
return {
waterAmountTotal : waterAmountTotal,
waterAmountInPaper : waterAmountInPaper,
waterAmountOnSurface: waterAmountOnSurface,
waterAmountInPaperOrOnSurface: waterAmountInPaper + waterAmountOnSurface,
waterAmountLost : world.waterSpotLost.waterAmount,
waterAmountEvaporationFromPaper : world.waterEvaporationFromPaper.waterAmount,
waterAmountEvaporationFromSurface : world.waterEvaporationFromSurface.waterAmount,
waterDropletsAddedToSurface : world.waterDropletsAddedToSurface.waterAmount,
dyeAmountTotal : dyeAmountTotal,
dyeAmountsTotal : dyeAmountsTotal,
dyeAmountsInPaper : dyeAmountsInPaper,
dyeAmountsInWater : dyeAmountsInWater,
dyeAmountsLost : world.waterSpotLost.dyeAmounts,
stepCount : (world.stepCount === undefined)? 0 : world.stepCount,
}
}