-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
564 lines (459 loc) · 20 KB
/
Copy pathapp.js
File metadata and controls
564 lines (459 loc) · 20 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
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
// ─── Dom Access ────────────────────────────────────────────────────────── ✦ ─
const canvas = document.getElementById("mainCanvas");
const gl = canvas
? canvas.getContext("webgl", { premultipliedAlpha: false, alpha: true })
: null;
// ─── Constants ─────────────────────────────────────────────────────────── ✦ ─
const TEXT_COLOR = "#ffbcbcff";
const FONT_SIZE_PT = 20;
const FONT_STACK = '"HAKAZA", sans-serif';
const LINE_HEIGHT_RATIO = 1.4;
const PARAGRAPH_SPACING_RATIO = 0.9;
const MAX_WIDTH_RATIO = 0.6;
const PT_TO_PX = 96 / 72;
const PORTRAIT_WAVE_MULTIPLIER = 2.5;
const FLAG_COLUMNS = 10;
const FLAG_ROWS = 4;
// ─── Text ──────────────────────────────────────────────────────────────── ✦ ─
const paragraphs = [
"۱۲۸۵",
"برای زیستن در اتحادِ هنر و دانش،",
"به افتخار زندگی و زیبایی بینهایت آن،",
"برای جستوجوی دانش و کنجکاویِ بیکران تا واپسین دمِ زندگانی،",
"به افتخار ساختن برای بهورزیِ تمام بشرییت،",
"برای ادای احترام به بزرگان پیش از ما،",
"و برای این سیاره زیبا.",
];
// ─── Vertex Shader ─────────────────────────────────────────────────────── ✦ ─
const vertexShaderSource = `
precision mediump float;
attribute vec2 aPosition;
attribute vec2 aTexCoord;
uniform float uTime;
uniform float uPortraitMode;
uniform float uPortraitWaveMultiplier;
varying vec2 vTexCoord;
varying float vLighting;
varying float vHeight;
const float PI = 3.141592653589793;
float flagHeight(vec2 uv, float time, float waveMultiplier) {
float waveA = sin((uv.x * 4.2 + uv.y * 0.6) * PI * 2.0 + time * 1.3);
float waveB = sin(uv.y * PI * 6.0 + time * 2.1);
float waveC = sin((uv.x + uv.y * 0.4) * PI * 10.0 - time * 0.9);
return (waveA * 0.035 + waveB * 0.028 + waveC * 0.015) * waveMultiplier;
}
vec3 computeNormal(vec2 uv, float time, float waveMultiplier) {
float argA = (uv.x * 4.2 + uv.y * 0.6) * PI * 2.0 + time * 1.3;
float argB = uv.y * PI * 6.0 + time * 2.1;
float argC = (uv.x + uv.y * 0.4) * PI * 10.0 - time * 0.9;
float dA_dx = cos(argA) * 0.035 * (4.2 * PI * 2.0);
float dA_dy = cos(argA) * 0.035 * (0.6 * PI * 2.0);
float dB_dy = cos(argB) * 0.028 * (PI * 6.0);
float dC_dx = cos(argC) * 0.015 * (PI * 10.0);
float dC_dy = cos(argC) * 0.015 * (0.4 * PI * 10.0);
float dHeightDx = (dA_dx + dC_dx) * waveMultiplier;
float dHeightDy = (dA_dy + dB_dy + dC_dy) * waveMultiplier;
return normalize(vec3(-dHeightDx, -dHeightDy, 1.0));
}
void main() {
vec2 uv = aTexCoord;
float time = uTime;
float waveMultiplier = mix(1.0, uPortraitWaveMultiplier, uPortraitMode);
float height = flagHeight(uv, time, waveMultiplier);
vec3 normal = computeNormal(uv, time, waveMultiplier);
float rim = smoothstep(0.0, 0.22, 1.0 - abs(uv.x - 0.5) * 1.3);
vec3 lightDir = normalize(vec3(-0.3, 0.45, 0.85));
float diffuse = clamp(dot(normal, lightDir) * 0.7 + 0.3, 0.0, 1.0);
vLighting = mix(diffuse, 1.0, rim * 0.12);
vHeight = height;
vTexCoord = uv;
float landscape = 1.0 - uPortraitMode;
float bend = (uv.x - 0.5) * 0.08 * landscape;
vec2 displaced = aPosition;
displaced.x += height * mix(0.06, 0.22, landscape) + bend;
displaced.y += height * mix(0.05, 0.12, landscape);
float angle = radians(-10.0 * landscape);
float cosA = cos(angle);
float sinA = sin(angle);
vec2 rotated = vec2(
displaced.x * cosA - displaced.y * sinA,
displaced.x * sinA + displaced.y * cosA
);
vec2 finalPosition = mix(displaced, rotated, landscape);
float stretch = mix(1.0, 1.05, landscape);
float offset = 0.18 * landscape;
finalPosition.x = finalPosition.x * stretch + offset;
gl_Position = vec4(finalPosition, 0.0, 1.0);
}
`;
// ─── Fragment Shader ───────────────────────────────────────────────────── ✦ ─
const fragmentShaderSource = `
precision mediump float;
uniform sampler2D uTexture;
uniform float uTime;
uniform float uPortraitMode;
varying vec2 vTexCoord;
varying float vLighting;
varying float vHeight;
const float PI = 3.141592653589793;
float clothShadow(vec2 uv, float time) {
float weave = sin((uv.y * 180.0 + time * 40.0) * PI / 180.0) * 0.5 + 0.5;
float motion = sin((uv.x * 2.0 + uv.y * 1.5) * PI * 3.0 + time * 0.6) * 0.5 + 0.5;
return weave * 0.35 + motion * 0.25;
}
float flagMask(vec2 uv) {
float edgeSoftness = 0.0015;
float tailDepth = 0.15;
float shapedSpan = pow(max(0.0, 0.5 - abs(uv.y - 0.5)) * 2.0, 1.35);
float xMin = tailDepth * shapedSpan;
float left = smoothstep(xMin, xMin + edgeSoftness, uv.x);
float right = 1.0 - smoothstep(1.0 - edgeSoftness, 1.0, uv.x);
float bottom = smoothstep(0.0, edgeSoftness, uv.y);
float top = 1.0 - smoothstep(1.0 - edgeSoftness, 1.0, uv.y);
float landscapeMask = left * right * top * bottom;
return mix(1.0, landscapeMask, 1.0 - uPortraitMode);
}
void main() {
vec4 textSample = texture2D(uTexture, vTexCoord);
float time = uTime;
float shadow = clothShadow(vTexCoord, time);
float mask = flagMask(vTexCoord);
float lighting = clamp(vLighting * 0.85 + 0.2, 0.0, 1.0);
float heightInfluence = clamp(vHeight * 8.0 + 0.5, 0.0, 1.2);
float highlightWave = sin((vTexCoord.x * 6.0 + time * 0.9) * PI) * 0.5 + 0.5;
float crossWave = sin((vTexCoord.y * 4.0 - time * 0.6) * PI) * 0.5 + 0.5;
vec3 baseLow = vec3(0.192, 0.005, 0.025);
vec3 baseHigh = vec3(0.288, 0.008, 0.038);
vec3 verticalBlend = mix(baseLow, baseHigh, vTexCoord.y);
float fabricSheen = mix(highlightWave, crossWave, 0.35);
float ridgeHighlight = smoothstep(0.58, 1.18, heightInfluence);
vec3 baseTone = verticalBlend;
vec3 highlightTint = vec3(0.48, 0.09, 0.15);
float directionalSheen = lighting * 0.12 + fabricSheen * 0.08;
float windPeak = pow(clamp(heightInfluence - 0.52, 0.0, 0.6) / 0.6, 1.4);
float highlightAmount = clamp(directionalSheen * 0.25 + ridgeHighlight * 0.15 + windPeak * 0.55, 0.0, 0.38);
vec3 flagColor = mix(baseTone, highlightTint, highlightAmount);
flagColor = mix(flagColor, baseTone, 0.35);
flagColor -= vec3(0.02, 0.01, 0.01) * (1.0 - lighting) * 0.78;
flagColor += vec3(0.046, 0.018, 0.022) * (shadow * 0.18 + heightInfluence * 0.14);
flagColor = clamp(flagColor, 0.0, 0.28);
float vignette = smoothstep(0.97, 0.48, distance(vTexCoord, vec2(0.45, 0.5)));
flagColor *= mix(0.45, 1.0, vignette);
float inkHighlight = 0.9 + vLighting * 0.25;
vec3 gildedText = clamp(textSample.rgb * inkHighlight, 0.0, 1.0);
vec3 baseColor = flagColor;
vec3 finalColor = mix(baseColor, gildedText, textSample.a * mask);
gl_FragColor = vec4(finalColor, mask);
}
`;
// ─── Globals ───────────────────────────────────────────────────────────── ✦ ─
const offscreenCanvas = document.createElement("canvas");
const offscreenCtx = offscreenCanvas.getContext("2d");
let program;
let texture;
let attributeLocations;
let uniformLocations;
let mesh;
let animationFrameId;
let startTime;
let lastTimeSeconds = 0;
// ─── Compile Shader ────────────────────────────────────────────────────── ✦ ─
function compileShader(glContext, type, source) {
const shader = glContext.createShader(type);
glContext.shaderSource(shader, source);
glContext.compileShader(shader);
if (!glContext.getShaderParameter(shader, glContext.COMPILE_STATUS)) {
const info = glContext.getShaderInfoLog(shader);
glContext.deleteShader(shader);
throw new Error(`Shader compilation failed: ${info}`);
}
return shader;
}
// ─── Create Shader Program ─────────────────────────────────────────────── ✦ ─
function createProgram(glContext, vertexSource, fragmentSource) {
const vertexShader = compileShader(
glContext,
glContext.VERTEX_SHADER,
vertexSource
);
const fragmentShader = compileShader(
glContext,
glContext.FRAGMENT_SHADER,
fragmentSource
);
const glProgram = glContext.createProgram();
glContext.attachShader(glProgram, vertexShader);
glContext.attachShader(glProgram, fragmentShader);
glContext.linkProgram(glProgram);
glContext.deleteShader(vertexShader);
glContext.deleteShader(fragmentShader);
if (!glContext.getProgramParameter(glProgram, glContext.LINK_STATUS)) {
const info = glContext.getProgramInfoLog(glProgram);
glContext.deleteProgram(glProgram);
throw new Error(`Program link failed: ${info}`);
}
return glProgram;
}
// ─── Create Flag Mesh ──────────────────────────────────────────────────── ✦ ─
function createFlagMesh(columns = FLAG_COLUMNS, rows = FLAG_ROWS) {
const vertexCount = (columns + 1) * (rows + 1);
const vertices = new Float32Array(vertexCount * 4);
let offset = 0;
for (let row = 0; row <= rows; row += 1) {
const v = row / rows;
const positionY = v * 2 - 1;
for (let col = 0; col <= columns; col += 1) {
const u = col / columns;
const positionX = u * 2 - 1;
vertices[offset + 0] = positionX;
vertices[offset + 1] = positionY;
vertices[offset + 2] = u;
vertices[offset + 3] = v;
offset += 4;
}
}
const indices = new Uint16Array(columns * rows * 6);
let indexOffset = 0;
const stride = columns + 1;
for (let row = 0; row < rows; row += 1) {
for (let col = 0; col < columns; col += 1) {
const topLeft = row * stride + col;
const bottomLeft = (row + 1) * stride + col;
const topRight = topLeft + 1;
const bottomRight = bottomLeft + 1;
indices[indexOffset + 0] = topLeft;
indices[indexOffset + 1] = bottomLeft;
indices[indexOffset + 2] = topRight;
indices[indexOffset + 3] = topRight;
indices[indexOffset + 4] = bottomLeft;
indices[indexOffset + 5] = bottomRight;
indexOffset += 6;
}
}
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
return {
vertexBuffer,
indexBuffer,
indexCount: indices.length,
};
}
// ─── Create Texture ────────────────────────────────────────────────────── ✦ ─
function createTexture() {
const glTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, glTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
return glTexture;
}
// ─── Resize Canvas ─────────────────────────────────────────────────────── ✦ ─
function resizeCanvas() {
const pixelRatio = window.devicePixelRatio || 1;
const width = window.innerWidth;
const height = window.innerHeight;
const deviceWidth = Math.max(1, Math.floor(width * pixelRatio));
const deviceHeight = Math.max(1, Math.floor(height * pixelRatio));
if (canvas.width !== deviceWidth || canvas.height !== deviceHeight) {
canvas.width = deviceWidth;
canvas.height = deviceHeight;
}
const styleWidth = `${width}px`;
const styleHeight = `${height}px`;
if (canvas.style.width !== styleWidth) {
canvas.style.width = styleWidth;
}
if (canvas.style.height !== styleHeight) {
canvas.style.height = styleHeight;
}
const isPortrait = height > width;
return { pixelRatio, width, height, isPortrait };
}
// ─── Wrap Text ─────────────────────────────────────────────────────────── ✦ ─
function wrapText(paragraph, maxWidthCss, pixelRatio) {
const words = paragraph.trim().split(/\s+/);
const lines = [];
let currentLine = "";
for (const word of words) {
const testLine = currentLine ? `${currentLine} ${word}` : word;
const measuredWidth = offscreenCtx.measureText(testLine).width / pixelRatio;
if (measuredWidth <= maxWidthCss || currentLine.length === 0) {
currentLine = testLine;
} else {
lines.push(currentLine);
currentLine = word;
}
}
if (currentLine) {
lines.push(currentLine);
}
return lines;
}
// ─── Render Text To Canvas ─────────────────────────────────────────────── ✦ ─
function renderTextToCanvas(metrics) {
const { pixelRatio, width, height, isPortrait } = metrics;
const sizeMultiplier = isPortrait ? 0.75 : 1.0;
const deviceWidth = Math.max(1, Math.floor(width * pixelRatio));
const deviceHeight = Math.max(1, Math.floor(height * pixelRatio));
const fontSizeCss = FONT_SIZE_PT * PT_TO_PX * sizeMultiplier;
const lineHeightCss = fontSizeCss * LINE_HEIGHT_RATIO;
const paragraphSpacingCss = fontSizeCss * PARAGRAPH_SPACING_RATIO;
const maxTextWidthCss = width * MAX_WIDTH_RATIO;
offscreenCanvas.width = deviceWidth;
offscreenCanvas.height = deviceHeight;
offscreenCtx.clearRect(0, 0, deviceWidth, deviceHeight);
offscreenCtx.fillStyle = TEXT_COLOR;
offscreenCtx.textAlign = "center";
offscreenCtx.textBaseline = "top";
offscreenCtx.direction = "rtl";
offscreenCtx.font = `${fontSizeCss * pixelRatio}px ${FONT_STACK}`;
const wrappedParagraphs = paragraphs.map((paragraph) =>
wrapText(paragraph, maxTextWidthCss, pixelRatio)
);
const totalTextHeightCss = wrappedParagraphs.reduce((sum, lines, index) => {
const paragraphHeight = lines.length * lineHeightCss;
const spacing = index === 0 ? 0 : paragraphSpacingCss;
return sum + spacing + paragraphHeight;
}, 0);
let currentYCss = (height - totalTextHeightCss) / 2;
const centerXDevice = (width / 2) * pixelRatio;
wrappedParagraphs.forEach((lines, paragraphIndex) => {
if (paragraphIndex > 0) {
currentYCss += paragraphSpacingCss;
}
lines.forEach((line) => {
const lineYDevice = currentYCss * pixelRatio;
offscreenCtx.fillText(line, centerXDevice, lineYDevice);
currentYCss += lineHeightCss;
});
});
}
// ─── Upload Texture ────────────────────────────────────────────────────── ✦ ─
function uploadTexture() {
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
gl.RGBA,
gl.UNSIGNED_BYTE,
offscreenCanvas
);
}
// ─── Drew Scene ────────────────────────────────────────────────────────── ✦ ─
function drawScene(timeSeconds = 0) {
if (!gl || !mesh) {
return;
}
const isPortrait = canvas.height > canvas.width;
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.0, 0.0, 0.0, 0.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.useProgram(program);
gl.uniform1i(uniformLocations.texture, 0);
if (uniformLocations.time) {
gl.uniform1f(uniformLocations.time, timeSeconds);
}
if (uniformLocations.portraitMode) {
gl.uniform1f(uniformLocations.portraitMode, isPortrait ? 1.0 : 0.0);
}
if (uniformLocations.portraitWaveMultiplier) {
gl.uniform1f(
uniformLocations.portraitWaveMultiplier,
PORTRAIT_WAVE_MULTIPLIER
);
}
gl.bindBuffer(gl.ARRAY_BUFFER, mesh.vertexBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, mesh.indexBuffer);
const stride = 4 * Float32Array.BYTES_PER_ELEMENT;
gl.vertexAttribPointer(
attributeLocations.position,
2,
gl.FLOAT,
false,
stride,
0
);
gl.enableVertexAttribArray(attributeLocations.position);
gl.vertexAttribPointer(
attributeLocations.texCoord,
2,
gl.FLOAT,
false,
stride,
2 * Float32Array.BYTES_PER_ELEMENT
);
gl.enableVertexAttribArray(attributeLocations.texCoord);
gl.drawElements(gl.TRIANGLES, mesh.indexCount, gl.UNSIGNED_SHORT, 0);
}
// ─── Load Fonst ────────────────────────────────────────────────────────── ✦ ─
async function loadFonts() {
if (!document.fonts) {
return;
}
try {
await document.fonts.load(`${FONT_SIZE_PT}pt "HAKAZA"`);
await document.fonts.ready;
} catch (error) {
console.warn("Font loading failed:", error);
}
}
// ─── Initialize Webgl ──────────────────────────────────────────────────── ✦ ─
function initializeWebGL() {
program = createProgram(gl, vertexShaderSource, fragmentShaderSource);
attributeLocations = {
position: gl.getAttribLocation(program, "aPosition"),
texCoord: gl.getAttribLocation(program, "aTexCoord"),
};
uniformLocations = {
texture: gl.getUniformLocation(program, "uTexture"),
time: gl.getUniformLocation(program, "uTime"),
portraitMode: gl.getUniformLocation(program, "uPortraitMode"),
portraitWaveMultiplier: gl.getUniformLocation(
program,
"uPortraitWaveMultiplier"
),
};
mesh = createFlagMesh();
texture = createTexture();
gl.disable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
}
// ─── Update Scene ──────────────────────────────────────────────────────── ✦ ─
function updateScene() {
const metrics = resizeCanvas();
renderTextToCanvas(metrics);
uploadTexture();
drawScene(lastTimeSeconds);
}
// ─── Animate ───────────────────────────────────────────────────────────── ✦ ─
function animate(timestamp) {
if (startTime === undefined) {
startTime = timestamp;
}
lastTimeSeconds = (timestamp - startTime) / 1000;
drawScene(lastTimeSeconds);
animationFrameId = window.requestAnimationFrame(animate);
}
// ─── Initialize ────────────────────────────────────────────────────────── ✦ ─
async function initialize() {
if (!canvas || !gl || !offscreenCtx) {
console.error("WebGL canvas setup failed.");
return;
}
await loadFonts();
initializeWebGL();
updateScene();
window.addEventListener("resize", updateScene);
animationFrameId = window.requestAnimationFrame(animate);
}
initialize();