-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter.js
More file actions
475 lines (384 loc) · 11.6 KB
/
Copy pathinterpreter.js
File metadata and controls
475 lines (384 loc) · 11.6 KB
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
class GlobalSettings {
static ARG_ORDER = ["w", "h", "bg", "bga"]
static ARGS = {
"w" : acceptNumber,
"h" : acceptNumber,
"bg" : acceptRGBString,
"bga" : acceptNumberZeroToOne,
}
constructor(w, h, background, alpha) {
this.w = w;
this.h = h;
this.background = background;
this.alpha = alpha;
}
}
class MSymbol {
static ARG_ORDER = []
static ARGS = {}
constructor() {}
hasArg(name) {
return Object.hasOwn(this.ARGS, name);
}
}
class NonTerminal extends MSymbol {
static ARG_ORDER = ["x", "y", "s", "r", "c", "a", "cc", "ca"]
static ARGS = {
"x" : acceptNumber,
"y" : acceptNumber,
"s" : acceptPositiveNumberOrZero,
"r" : acceptNumber,
"c" : acceptRGBString,
"a" : acceptNumberZeroToOne,
"cc" : acceptRGBDiffString,
"ca" : acceptNumber,
}
constructor(id, cx = 0, cy = 0, csize = 1, r = 0, color = null, alpha = null, ccolor = [0, 0, 0], calpha = 0) {
super();
this.id = id;
this.cx = cx;
this.cy = cy;
this.csize = csize;
this.r = r;
this.color = color;
this.alpha = alpha;
this.ccolor = ccolor;
this.calpha = calpha;
}
}
class Terminal extends MSymbol {
static ARG_ORDER = ["x", "y", "s", "c", "r", "a"]
static ARGS = {
"x" : acceptNumber,
"y" : acceptNumber,
"s" : acceptPositiveNumberOrZero,
"c" : acceptRGBString,
"r" : acceptNumber,
"a" : acceptNumberZeroToOne,
}
constructor(x, y, size, color, r, alpha) {
super();
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.r = r;
this.alpha = alpha;
}
}
class Square extends Terminal {
static ARG_ORDER = [...Terminal.ARG_ORDER]
static ARGS = Object.assign({}, Terminal.ARGS)
constructor(x = 0, y = 0, size = 1, color = null, r = 0, alpha = null) {
super(x, y, size, color, r, alpha);
}
}
class Circle extends Terminal {
static ARG_ORDER = [...Terminal.ARG_ORDER]
static ARGS = Object.assign({}, Terminal.ARGS)
constructor(x = 0, y = 0, size = 1, color = null, r = 0, alpha = null) {
super(x, y, size, color, r, alpha);
}
}
class Rule {
constructor(name, descendants = [], weight = 1) {
this.name = name;
this.descendants = descendants;
this.weight = weight;
this.cweight = null;
}
pushDescendant(descendant) {
this.descendants.push(descendant);
}
setCWeight(val) {
this.cweight = val;
}
isEmpty() {
return descendant.length == 0;
}
}
class Grammar {
constructor(rules = {}, entryPoint = null, settings = {}) {
this.rules = rules;
this.rulesAreNormalized = false;
this.entryPoint = entryPoint;
this.settings = settings;
}
hasRule(name) {
return Object.hasOwn(this.rules, name);
}
addNewRule(name, rule) {
this.rulesAreNormalized = false;
if(this.hasRule(name)) {
this.rules[name].push(rule);
return true;
}
else {
this.rules[name] = Array(rule);
return false;
}
}
normalizeRules() {
for (const [_name, ruleList] of Object.entries(this.rules)) {
let totalWeight = ruleList.reduce((acc, ruleObj) => acc + ruleObj.weight, 0);
ruleList.sort((r1, r2) => r2.weight - r1.weight );
// Conversion to cummulative weight
let cWeight = 0;
for (let index = 0; index < ruleList.length; index++) {
let ruleObj = ruleList[index];
if (index + 1 == ruleList.length) {
ruleObj.cweight = 1.0;
}
else {
cWeight += ruleObj.weight;
ruleObj.cweight = cWeight / totalWeight;
}
}
};
this.rulesAreNormalized = true;
}
pickNext(name) {
if(!this.rulesAreNormalized) {
throw new Error("Internal error! Rules have to be normalized!");
}
if(!this.hasRule(name)) {
throw new Error(`Rule ${name} is not defined!`);
}
// Random roullete algorithm
let r = Math.random();
let selected = null;
for (let index = 0; selected === null && index < this.rules[name].length; index++) {
const rule = this.rules[name][index];
selected = r <= rule.cweight ? rule : null;
}
// Because there may be problem with approximation errors -> pick the last one
// if nothing was selected
if(selected === null) {
selected = this.rules[name][this.rules[name].length - 1];
}
return selected;
}
}
class InitialCtx {
constructor(x, y, size, color, r, alpha) {
this.x = x;
this.y = y;
this.size = size;
this.color = color;
this.r = r;
this.alpha = alpha;
}
}
class SymbolCtx extends InitialCtx {
constructor(rule, x = 0, y = 0, size = 1, color = [0, 0, 0], r = 0, alpha = 1) {
super(x, y, size, color, r, alpha);
this.rule = rule;
}
}
class Interpreter {
SPF = 5; // Steps per frame
constructor(initialCtx, canvasElement, defaultSettings = {w: 500, h: 600, background: [255, 255, 255], alpha: 1}) {
this.initialCtx = initialCtx;
this.contextsQueue = [];
this.history = [];
this.grammar = null;
this.canvasElement = canvasElement[0];
this.canvasElementCtx = canvasElement[0].getContext("2d");
this.isRunning = false;
this.defaultSettings = defaultSettings;
if(this.canvasElementCtx === null) {
throw new Error("Unable to get context of canvas!");
}
}
_colorSum(c1, c2) {
let result = [];
for (let index = 0; index < c1.length; index++) {
result.push(clipSum(c1[index], c2[index], 0, 255));
}
return result;
}
_alphaSum(a1, a2) {
return clipSum(a1, a2, 0, 1);
}
static _canvasFill(canvasCtx, w, h, background, alpha) {
canvasCtx.fillStyle = background;
canvasCtx.globalAlpha = alpha;
canvasCtx.fillRect(0, 0, w, h);
}
static _circle(canvasCtx, x, y, size, color, alpha) {
canvasCtx.fillStyle = channelsToRGB(color);
canvasCtx.globalAlpha = alpha;
canvasCtx.beginPath();
canvasCtx.arc(x, y, size * 0.5, 0, 2 * Math.PI);
canvasCtx.fill();
}
static _square(canvasCtx, x, y, cornerX, cornerY, size, rads, color, alpha) {
canvasCtx.save();
canvasCtx.translate(cornerX, cornerY);
canvasCtx.rotate(rads);
canvasCtx.translate(-cornerX, -cornerY);
canvasCtx.fillStyle = channelsToRGB(color);
canvasCtx.globalAlpha = alpha;
canvasCtx.fillRect(x, y, size, size);
canvasCtx.restore();
}
static deg2Rads(deg) {
return (Math.PI / 180) * deg;
}
static rotateCoordinates(x, y, rad, origX = 0, origY = 0) {
let tX = x - origX;
let tY = y - origY;
let rX = tX * Math.cos(rad) - tY * Math.sin(rad);
let rY = tX * Math.sin(rad) + tY * Math.cos(rad);
let fX = rX + origX;
let fY = rY + origY;
return [fX, fY];
}
isFinished() {
return this.contextsQueue.length == 0;
}
hasGrammar() {
return this.grammar !== null;
}
setGrammar(grammar) {
this.grammar = grammar;
}
run() {
this.isRunning = true;
if(!this.isFinished()) {
requestAnimationFrame(() => {
this.makeStepUntilEnd();
});
}
}
reset() {
this.isRunning = false;
this.contextsQueue = [];
}
init() {
this.grammar.normalizeRules();
this.setupCanvas();
let centeredInitialCtx = Object.assign(
Object.fromEntries(Object.entries(this.initialCtx)), // Deep copy of initial context
{
x: this.canvasElement.width * 0.5 + this.initialCtx.x,
y: this.canvasElement.height * 0.5 + this.initialCtx.y,
},
);
const initialRule = this.grammar.pickNext(this.grammar.entryPoint);
let ctx = Object.assign(new SymbolCtx(initialRule), centeredInitialCtx);
this.contextsQueue.push(ctx);
}
setupCanvas() {
let defaultSettings = this.defaultSettings;
let grammarSettings = this.grammar.settings;
function defaultIfNotDefined(settingName) {
if(Object.hasOwn(grammarSettings, settingName) &&
grammarSettings[settingName] !== undefined) {
return grammarSettings[settingName];
}
else {
return defaultSettings[settingName];
}
}
this.canvasElement.width = defaultIfNotDefined("w");
this.canvasElement.height = defaultIfNotDefined("h");
let bg = channelsToRGB(defaultIfNotDefined("background"));
let alpha = defaultIfNotDefined("alpha");
Interpreter._canvasFill(
this.canvasElementCtx,
this.canvasElement.width,
this.canvasElement.height,
bg,
alpha
);
this.history.push([Interpreter._canvasFill, [this.canvasElement.width, this.canvasElement.height, bg, alpha]]);
}
step() {
this.isRunning = false;
if(!this.isFinished()) {
requestAnimationFrame(() => {
this.makeStep();
});
}
}
stop() {
this.isRunning = false;
}
makeStepUntilEnd(_time) {
let finished = false;
//console.log(this.SPF);
for (let i = 0; i < this.SPF && !finished; i++) {
finished &= this.makeStep();
}
if(!finished && this.isRunning) {
requestAnimationFrame(() => {
this.makeStepUntilEnd();
});
}
}
makeStep() {
if(this.isFinished()) {
return true;
}
const currentCtx = this.contextsQueue.shift();
currentCtx.rule.descendants.forEach(child => {
switch (child.constructor) {
case NonTerminal:
const newRule = this.grammar.pickNext(child.id);
const r = currentCtx.r + child.r;
let rads = Interpreter.deg2Rads(r);
let [rotX, rotY] = Interpreter.rotateCoordinates(child.cx, child.cy, rads);
const size = currentCtx.size * child.csize;
const x = currentCtx.x + rotX * size;
const y = currentCtx.y + rotY * size;
const color = child.color !== null ? child.color : (this._colorSum(currentCtx.color, child.ccolor));
const alpha = child.alpha !== null ? child.alpha : (this._alphaSum(currentCtx.alpha, child.calpha));
let newCtx = new SymbolCtx(newRule, x, y, size, color, r, alpha);
this.contextsQueue.push(newCtx);
break;
case Square:
this.drawSquare(currentCtx, child);
break;
case Circle:
this.drawCircle(currentCtx, child);
break;
default:
break;
}
});
return false;
}
drawSquare(ctx, squareObject) {
let size = ctx.size * squareObject.size;
let r = ctx.r + squareObject.r;
let rads = Interpreter.deg2Rads(r);
let [rotX, rotY] = Interpreter.rotateCoordinates(squareObject.x, squareObject.y, rads);
let cornerX = ctx.x + rotX * ctx.size;
let cornerY = ctx.y + rotY * ctx.size;
let x = cornerX - size * 0.5;
let y = cornerY - size * 0.5;
let color = squareObject.color !== null ? squareObject.color : ctx.color;
let alpha = squareObject.alpha !== null ? squareObject.alpha : ctx.alpha;
Interpreter._square(this.canvasElementCtx, x, y, cornerX, cornerY, size, rads, color, alpha);
this.history.push([Interpreter._square, [x, y, cornerX, cornerY, size, rads, color, alpha]]);
}
drawCircle(ctx, squareObject) {
let size = ctx.size * squareObject.size;
let r = ctx.r + squareObject.r;
let rads = Interpreter.deg2Rads(r);
let [rotX, rotY] = Interpreter.rotateCoordinates(squareObject.x, squareObject.y, rads);
let cornerX = ctx.x + rotX * ctx.size;
let cornerY = ctx.y + rotY * ctx.size;
let x = cornerX;
let y = cornerY;
let color = squareObject.color !== null ? squareObject.color : ctx.color;
let alpha = squareObject.alpha !== null ? squareObject.alpha : ctx.alpha;
Interpreter._circle(this.canvasElementCtx, x, y, size, color, alpha);
this.history.push([Interpreter._circle, [x, y, size, color, alpha]]);
}
clear() {
this.canvasElementCtx.clearRect(0, 0, this.canvasElement.width, this.canvasElement.height);
this.history = [];
}
}