forked from prajwalsouza/Random-Triangle-Mesh-Generation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.html
554 lines (449 loc) · 17.4 KB
/
main.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
<html>
<head>
<title> Triangle SVG Generation </title>
</head>
<body style='margin:0px; display: block;'>
<!-- change download function if you are changing the svg header -->
<svg xmlns='http://www.w3.org/2000/svg' id='polySVG' height="100%" width="100%">
<defs id="defs1337"></defs>
</svg>
<script type="text/javascript">
//configuration values for mesh generation
averagedistance = 90
radiusdeviation = 70
angledeviation = 40
//possible color schemes: 'single', 'analogous', 'complementary', 'complimentary-random'
//repeat schemes for increased chance
colorscheme = ['analogous', 'analogous', 'analogous', 'complimentary']
//get objects from document
polySVG = document.getElementById('polySVG')
def = document.getElementById('defs1337');
gradientIdCount = 0; //global counter for gradient IDs
pointsMemoryPrism = []
neighbourConnectionData = {}
creationNode = {}
// from https://stackoverflow.com/questions/22521982/js-check-if-point-inside-a-polygon
function inside(point, vs) {
// ray-casting algorithm based on (original link is down since at least 2020)
// https://web.archive.org/web/20180115151705/https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html
var x = point[0], y = point[1];
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i][0], yi = vs[i][1];
var xj = vs[j][0], yj = vs[j][1];
var intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
};
function getPossibilityRange(thepoint, mainnode) {
connectedpoints = neighbourConnectionData[thepoint[0] + ',' + thepoint[1]].slice()
pointofinterest = connectedpoints[0]
Angle1 = Math.atan2(pointofinterest[1] - thepoint[1], pointofinterest[0] - thepoint[0]) * 180 / Math.PI
if (Angle1 < 0) {
Angle1 = 360 + Angle1
}
pointofinterest = connectedpoints[1]
Angle2 = Math.atan2(pointofinterest[1] - thepoint[1], pointofinterest[0] - thepoint[0]) * 180 / Math.PI
if (Angle2 < 0) {
Angle2 = 360 + Angle2
}
Anglemain = Math.atan2(mainnode[1] - thepoint[1], mainnode[0] - thepoint[0]) * 180 / Math.PI
if (Anglemain < 0) {
Anglemain = 360 + Anglemain
}
maxvalue = Math.max(Angle1, Angle2)
minvalue = Math.min(Angle1, Angle2)
if (Anglemain < maxvalue && Anglemain > minvalue) {
possibilityrange = 360 - Math.abs(Angle2 - Angle1)
between = [Angle2, Angle1]
startingcue = -1
}
else {
possibilityrange = Math.abs(Angle2 - Angle1)
between = [Angle2, Angle1]
startingcue = 1
}
if (minvalue == Angle1) {
startingMneigh = connectedpoints[0]
endingMneigh = connectedpoints[1]
}
else {
startingMneigh = connectedpoints[1]
endingMneigh = connectedpoints[0]
}
return [possibilityrange, between, startingMneigh, endingMneigh, startingcue]
}
function pickAngleInRange(rangeLength, extremes, startingcuevalue) {
intervaldivision = parseInt(rangeLength / 50);
minvalue = Math.min(extremes[0], extremes[1])
maxvalue = Math.max(extremes[0], extremes[1])
anglevalues = []
if (startingcuevalue == 1) {
anglevalue = minvalue
for (i = 0; i < intervaldivision; i++) {
anglevalue = anglevalue + 50 + (angledeviation * (Math.random() - 0.5))
if (Math.abs(maxvalue - anglevalue) > 30) {
anglevalues.push(anglevalue)
}
}
}
else {
anglevalue = minvalue
for (i = 0; i < intervaldivision; i++) {
anglevalue = anglevalue - 50 + (angledeviation * (Math.random() - 0.5))
if (anglevalue < 0) {
anglevalue = 360 + anglevalue
}
if (Math.abs(maxvalue - anglevalue) > 30) {
anglevalues.push(anglevalue)
}
}
}
return anglevalues
}
function indexOfmin(arr) {
if (arr.length === 0) {
return -1;
}
var min = arr[0];
var minIndex = 0;
for (var i = 1; i < arr.length; i++) {
if (arr[i] < min) {
minIndex = i;
min = arr[i];
}
}
return minIndex;
}
function formPrism() {
triangleData = []
angles = pickAngleInRange(360, [0, 390], 1)
initvalue = [Math.random() * window.innerWidth, Math.random() * window.innerHeight];
currentvalue = initvalue
pointsList = []
pointsList.push[currentvalue]
currentlist = []
visitablenodes = []
for (j = 0; j < angles.length; j++) {
angle = angles[j]
radius = averagedistance + (radiusdeviation * Math.random())
xvalue = currentvalue[0] + radius * Math.cos(angle * Math.PI / 180)
yvalue = currentvalue[1] + radius * Math.sin(angle * Math.PI / 180)
if (inside([xvalue, yvalue], visitablenodes)) {
console.log("Point Outside")
}
else {
pointsList.push([xvalue, yvalue])
creationNode[xvalue + ',' + yvalue] = currentvalue
if (xvalue <= window.innerWidth * 1.2 && xvalue >= -0.2 * window.innerWidth && yvalue <= window.innerHeight * 1.2 && yvalue >= -0.2 * window.innerHeight) {
visitablenodes.push([xvalue, yvalue])
}
currentlist.push([xvalue, yvalue])
}
}
for (k = 0; k < currentlist.length; k++) {
neighbours = []
index = (k - 1)
if (index < 0) {
index = index + currentlist.length
}
if (index >= currentlist.length) {
index = index % currentlist.length
}
neighbours.push(currentlist[index])
index = (k + 1)
if (index < 0) {
index = index + currentlist.length
}
if (index >= currentlist.length) {
index = index % currentlist.length
}
neighbours.push(currentlist[index])
point = currentlist[k]
neighbourConnectionData[point[0] + ',' + point[1]] = neighbours
triangleData.push([neighbours[0], point, currentvalue])
}
ranges = []
for (m = 0; m < visitablenodes.length; m++) {
node = visitablenodes[m]
ranges.push(getPossibilityRange(node, currentvalue)[0])
}
minvalueindex = indexOfmin(ranges)
nextnode = visitablenodes[minvalueindex]
visitablenodes.splice(minvalueindex, 1);
while (visitablenodes.length != 0) {
prange = getPossibilityRange(nextnode, creationNode[nextnode[0] + ',' + nextnode[1]])
mainnodevalue = currentvalue
currentvalue = nextnode
angles = pickAngleInRange(prange[0], prange[1], prange[4])
startingMneigh = prange[2]
endingMneigh = prange[3]
currentlist = []
for (j = 0; j < angles.length; j++) {
angle = angles[j]
radius = averagedistance + (radiusdeviation * Math.random())
xvalue = currentvalue[0] + radius * Math.cos(angle * Math.PI / 180)
yvalue = currentvalue[1] + radius * Math.sin(angle * Math.PI / 180)
if (!inside([xvalue, yvalue], visitablenodes)) {
pointsList.push([xvalue, yvalue])
creationNode[xvalue + ',' + yvalue] = currentvalue
if (xvalue <= window.innerWidth * 1.2 && xvalue >= -0.2 * window.innerWidth && yvalue <= window.innerHeight * 1.2 && yvalue >= -0.2 * window.innerHeight) {
visitablenodes.push([xvalue, yvalue])
}
currentlist.push([xvalue, yvalue])
}
}
if (currentlist.length == 0) {
currneighbours = neighbourConnectionData[currentvalue[0] + ',' + currentvalue[1]]
n1 = currneighbours[0]
n1neighbours = neighbourConnectionData[n1[0] + ',' + n1[1]]
if (n1neighbours[0][0] == currentvalue[0] && n1neighbours[0][1] == currentvalue[1]) {
n1neighbours.splice(0, 1, currneighbours[1]);
}
else {
n1neighbours.splice(1, 1, currneighbours[1]);
}
n2 = currneighbours[1]
n2neighbours = neighbourConnectionData[n2[0] + ',' + n2[1]]
if (n2neighbours[0][0] == currentvalue[0] && n2neighbours[0][1] == currentvalue[1]) {
n2neighbours.splice(0, 1, currneighbours[0]);
}
else {
n2neighbours.splice(1, 1, currneighbours[0]);
}
triangleData.push([currneighbours[0], currneighbours[1], currentvalue])
}
else if (currentlist.length == 1) {
point = currentlist[0]
currneighbours = neighbourConnectionData[currentvalue[0] + ',' + currentvalue[1]]
neighbourConnectionData[point[0] + ',' + point[1]] = currneighbours
triangleData.push([currneighbours[0], point, currentvalue])
triangleData.push([currneighbours[1], point, currentvalue])
sidepoint = currneighbours[0]
ngh = neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]].slice();
if (ngh[0][0] == currentvalue[0] && ngh[0][1] == currentvalue[1]) {
ngh.splice(0, 1, point);
neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]] = ngh
}
else {
ngh.splice(1, 1, point);
neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]] = ngh
}
sidepoint = currneighbours[1]
ngh = neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]].slice();
if (ngh[0][0] == currentvalue[0] && ngh[0][1] == currentvalue[1]) {
ngh.splice(0, 1, point);
neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]] = ngh
}
else {
ngh.splice(1, 1, point);
neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]] = ngh
}
}
else {
neighbours = []
point = currentlist[0]
neighbours.push(startingMneigh)
sidepoint = startingMneigh
triangleData.push([startingMneigh, point, currentvalue])
ngh = neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]].slice();
if (ngh[0][0] == currentvalue[0] && ngh[0][1] == currentvalue[1]) {
ngh.splice(0, 1, point);
neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]] = ngh
}
else {
ngh.splice(1, 1, point);
neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]] = ngh
}
neighbours.push(currentlist[1])
neighbourConnectionData[point[0] + ',' + point[1]] = neighbours
for (k = 1; k < currentlist.length - 1; k++) {
neighbours = []
index = (k - 1)
if (index < 0) {
index = index + currentlist.length
}
if (index >= currentlist.length) {
index = index % currentlist.length
}
neighbours.push(currentlist[index])
index = (k + 1)
if (index < 0) {
index = index + currentlist.length
}
if (index >= currentlist.length) {
index = index % currentlist.length
}
neighbours.push(currentlist[index])
point = currentlist[k]
neighbourConnectionData[point[0] + ',' + point[1]] = neighbours
triangleData.push([neighbours[0], point, currentvalue])
}
triangleData.push([currentlist[currentlist.length - 2], currentlist[currentlist.length - 1], currentvalue])
neighbours = []
point = currentlist[currentlist.length - 1]
neighbours.push(endingMneigh)
sidepoint = endingMneigh
triangleData.push([endingMneigh, point, currentvalue])
ngh = neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]].slice();
if (ngh[0][0] == currentvalue[0] && ngh[0][1] == currentvalue[1]) {
ngh.splice(0, 1, point);
neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]] = ngh
}
else {
ngh.splice(1, 1, point);
neighbourConnectionData[sidepoint[0] + ',' + sidepoint[1]] = ngh
}
neighbours.push(currentlist[currentlist.length - 2])
neighbourConnectionData[point[0] + ',' + point[1]] = neighbours
}
ranges = []
for (ind = 0; ind < visitablenodes.length; ind++) {
node = visitablenodes[ind]
ranges.push(getPossibilityRange(node, creationNode[node[0] + ',' + node[1]])[0])
}
minvalueindex = indexOfmin(ranges)
prevPrange = ranges[minvalueindex]
nextnode = visitablenodes[minvalueindex]
visitablenodes.splice(minvalueindex, 1);
}
return triangleData
}
triangleData = formPrism()
function randomIntFromInterval(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
//generate random color as one option
hue1 = randomIntFromInterval(0, 360); //is second in colorconfig but the "main" color
hue2 = hue1 + randomIntFromInterval(10, 100) //slightly larger deviation than in the original color options
if (hue2 > 360) hue2 -= 360;
//base-colors: both are hue-values, no idea why they're chosen that way...
//disabled in favor of a completely random choice of base color
//colorconfig = [['blue', 290, 240], ['orange', 70, 30], ['red', 50, 3], ['violet', 335, 290], ['green', 150, 100]]
//choice = colorconfig[parseInt(Math.random() * (colorconfig.length))];
choice = ['random', hue2, hue1];
scheme = colorscheme[parseInt(Math.random() * (colorscheme.length))];
function drawPrism() {
for (i = 0; i < triangleData.length; i++) {
//create polygon element
ithTriangleSet = triangleData[i]; //get triangle data for current triangle
var polyElement = document.createElementNS("http://www.w3.org/2000/svg", 'polygon');
polypoints = ithTriangleSet[0][0] + ',' + ithTriangleSet[0][1] + ' ' + ithTriangleSet[1][0] + ',' + ithTriangleSet[1][1] + ' ' + ithTriangleSet[2][0] + ',' + ithTriangleSet[2][1];
polyElement.setAttribute('points', polypoints);
polyElement.setAttribute('id', 'triangleNo' + i);
//choose color of polygon
ithTriangleSet = ithTriangleSet.sort((a, b) => a[0] - b[0])
color = colorPick(...ithTriangleSet[0].map(Math.round));
color2 = colorPick(...ithTriangleSet[0].map(Math.round));
//create gradient
var gradient = document.createElementNS("http://www.w3.org/2000/svg", 'linearGradient');
gradient.setAttribute('id', 'grad' + gradientIdCount++);
var stop1 = document.createElementNS("http://www.w3.org/2000/svg", 'stop');
var stop2 = document.createElementNS("http://www.w3.org/2000/svg", 'stop');
stop1.setAttribute('offset', '0');
stop2.setAttribute('offset', '1');
stop1.setAttribute('stop-color', color);
stop2.setAttribute('stop-color', color2);
//attach colors to gradient and gradient to <defs> section of the svg
gradient.appendChild(stop1);
gradient.appendChild(stop2);
def.appendChild(gradient);
//attach gradient to polygon
polyElement.style.fill = 'url(#' + gradient.getAttribute('id') + ')';
polyElement.style.strokeWidth = '0.05%';
//static stroke color for visible strokes as alternative to strokes using 'fill' color:
//polyElement.style.stroke = 'rgba(255,255,255,0.3)';
polyElement.style.stroke = 'url(#' + gradient.getAttribute('id') + ')';
//attach polygon to svg
polySVG.appendChild(polyElement);
}
}
drawPrism()
function colorPick(xval, yval) {
//calculate lightness, left-->right == dark-->light (xval / window.innerWidth grows)
lvalue = 10 + ((xval / window.innerWidth) * 40) + (Math.random() - 0.5) * 20
//calculate hue-values based on different strategies
if (scheme == 'single') {
hvalue = choice[2]
}
else if (scheme == 'analogous') {
//shifts hue from top to bottom by 100°
hvalue = choice[1] - ((yval / window.innerHeight) * 100)
}
else if (scheme == 'complimentary') {
if (yval < window.innerHeight / 2) {
hvalue = choice[2] + 180
}
else {
hvalue = choice[2]
}
}
else if (scheme == 'complimentary-random') {
if (Math.random() < 0.5) {
hvalue = choice[2] + 200
}
else {
hvalue = choice[2]
}
}
svalue = 100 //always full saturation
return 'hsl(' + hvalue + ',' + svalue + '%,' + lvalue + '%)'
}
function giveColor(event) { //unused if the eventListener below is disabled
var bRect = polySVG.getBoundingClientRect();
posX = event.clientX - bRect.left;
posY = event.clientY - bRect.top;
colorchoice = colorPick(posX, posY)
event.target.style.fill = colorchoice
event.target.style.stroke = colorchoice
}
//remove comment to enable solid color-change on click:
//polySVG.addEventListener('click', giveColor);
//create URL to a blob containing the current SVG file
var svgFile = null;
makesvgFile = function (text) {
var data = new Blob([text], { type: 'image/svg+xml' });
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (svgFile !== null) {
window.URL.revokeObjectURL(svgFile);
}
svgFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return svgFile;
}
twoDigitTime = function (time) {
return ('0' + time).slice(-2)
}
//download the generated SVG instead of the webpage when pressing CTRL+S
const download = (path, filename) => {
// Create a new link
const anchor = document.createElement('a');
anchor.href = path;
anchor.download = filename;
// Append to the DOM
document.body.appendChild(anchor);
// Trigger `click` event
anchor.click();
// Remove element from DOM
document.body.removeChild(anchor);
};
document.addEventListener('keydown', function (event) {
//listen to CTRL + S
if (event.ctrlKey && event.key === 's') {
event.preventDefault(); //prevent the download web-page dialogue from appearing
date = new Date();
//build filename in format 'svg-YYMMDD-HHMMSS.svg'
filename = 'svg-' + date.getFullYear() + twoDigitTime(date.getMonth() + 1) + twoDigitTime(date.getDate()) + '-' +
twoDigitTime(date.getHours()) + twoDigitTime(date.getMinutes()) + twoDigitTime(date.getSeconds()) + '.svg';
//trigger download action and replace the height and width (100%) values of the svg with the viewport dimensions
//the replacing option is quite dirty... but it works
download(makesvgFile(polySVG.outerHTML.replace('height="100%" width="100%">', 'height="' +
window.innerHeight + '" width="' + window.innerWidth + '">')), filename);
}
});
</script>
</body>
<html>