Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Computer Graphics with WebGL / Homework 07 - The cradle / Homework.html
diff options
context:
space:
mode:
Commita5ef7ce97cf5a167d19d1ee8b833f33909b7e5b3 (patch)
Author
 Syndamia <kamen@syndamia.com>
2022-11-27 21:07:48 +0200
Committer
 Syndamia <kamen@syndamia.com>
2022-11-27 21:07:48 +0200
Filesab319c225e13d5d1d842848f7504b6f97922dfb8 /Year 2/Computer Graphics with WebGL/Homework 07 - The cradle/Homework.html
uni-projects-a5ef7ce97cf5a167d19d1ee8b833f33909b7e5b3.tar
uni-projects-a5ef7ce97cf5a167d19d1ee8b833f33909b7e5b3.tar.gz
uni-projects-a5ef7ce97cf5a167d19d1ee8b833f33909b7e5b3.zip
Parent38073887653bef0506df8ffe88e982e5a404153f (diff)
[WGL/HW07] Solved 7th homework
1 files changed, 265 insertions, 0 deletions
-rw-r--r--Year 2/Computer Graphics with WebGL/Homework 07 - The cradle/Homework.html265
diff --git a/Year 2/Computer Graphics with WebGL/Homework 07 - The cradle/Homework.html b/Year 2/Computer Graphics with WebGL/Homework 07 - The cradle/Homework.html
new file mode 100644
index 0000000..18ccfad
--- /dev/null
+++ b/Year 2/Computer Graphics with WebGL/Homework 07 - The cradle/Homework.html
@@ -0,0 +1,265 @@
+<!DOCTYPE html>
+
+<head>
+ <meta charset="utf-8"/>
+ <title>Люлката</title>
+
+ <script src="webgl-fmi.js"></script>
+
+ <script id="vshader" type="x-shader/x-vertex">
+ uniform mat4 uProjectionMatrix;
+ uniform mat4 uViewMatrix;
+ uniform mat4 uModelMatrix;
+
+ uniform bool uUseAmbient;
+ uniform vec3 uAmbientColor;
+
+ uniform bool uUseDiffuse;
+ uniform vec3 uDiffuseColor;
+
+ uniform vec3 uLightDir;
+
+ attribute vec3 aXYZ; // координати на връх
+ attribute vec3 aColor; // цвят на връх
+ attribute vec3 aNormal; // нормален вектор на връх
+
+ varying vec3 vNormal;
+ varying vec3 vColor;
+ varying vec3 vPos;
+
+ void main ()
+ {
+ mat4 mvMatrix = uViewMatrix * uModelMatrix;
+ vec4 pos = mvMatrix * vec4(aXYZ,1);
+ gl_Position = uProjectionMatrix * pos;
+
+ // околна светлина
+ vColor = aColor;
+ if (uUseAmbient)
+ vColor *= uAmbientColor;
+
+ // дифузно отражение
+ vec3 normal = vec3(normalize(mvMatrix*vec4(aNormal,0)));
+ vec3 light = normalize(-uLightDir);
+ if (uUseDiffuse)
+ vColor += aColor*uDiffuseColor*max(dot(normal,light),0.0);
+
+ vPos = pos.xyz/pos.w;
+ vNormal = normal;
+ }
+ </script>
+
+ <script id="fshader" type="x-shader/x-fragment">
+ precision mediump float;
+
+ // преместено тук от другия шейдър
+ uniform highp vec3 uLightDir;
+ uniform bool uUseSpecular;
+ uniform vec3 uSpecularColor;
+
+ varying vec3 vNormal;
+ varying vec3 vColor;
+ varying vec3 vPos;
+
+ void main( )
+ {
+ vec3 light = normalize(-uLightDir);
+
+ // намиране на отразения лъч
+ vec3 reflectedLight = normalize(reflect(light,normalize(vNormal)));
+
+ // в локалната координатна система "окото" на гледащия е в (0,0,0)
+ // а вектора от точката до "окото" е pos-(0,0,0) = pos
+ vec3 viewDir = normalize(vPos);
+
+ // готови сме да сметнем лъскавината
+ float cosa = abs(dot(reflectedLight,viewDir));
+ vec3 specularColor = vec3(pow(cosa,4.0));
+
+ gl_FragColor = vec4(vColor+specularColor,1);
+ }
+ </script>
+
+ <script>
+ function start( )
+ {
+ var canvas = document.getElementById("picasso");
+ canvas.addEventListener('webglcontextlost',function(event){event.preventDefault();},false);
+ canvas.addEventListener('webglcontextrestored',function(){init();},false);
+
+ init();
+ drawFrame();
+ }
+
+ function init()
+ {
+ gl = getContext("picasso");
+ glprog = getProgram("vshader","fshader");
+
+
+ aXYZ = gl.getAttribLocation(glprog,"aXYZ");
+ uProjectionMatrix = gl.getUniformLocation(glprog,"uProjectionMatrix");
+ uViewMatrix = gl.getUniformLocation(glprog,"uViewMatrix");
+ uModelMatrix = gl.getUniformLocation(glprog,"uModelMatrix");
+
+ aColor = gl.getAttribLocation(glprog,"aColor");
+ uAmbientColor = gl.getUniformLocation(glprog,"uAmbientColor");
+ uUseAmbient = gl.getUniformLocation(glprog,"uUseAmbient");
+
+ aNormal = gl.getAttribLocation(glprog,"aNormal");
+ uDiffuseColor = gl.getUniformLocation(glprog,"uDiffuseColor");
+ uUseDiffuse = gl.getUniformLocation(glprog,"uUseDiffuse");
+ uUseSpecular = gl.getUniformLocation(glprog,"uUseSpecular");
+ uLightDir = gl.getUniformLocation(glprog,"uLightDir");
+
+ gl.enable(gl.DEPTH_TEST);
+ gl.clearColor(0.8,0.9,0.7,1);
+
+ identity();
+ perspective(30,gl.canvas.width/gl.canvas.height,1,40000);
+
+ gl.uniform3f(uAmbientColor,0.7,0.7,0.7);
+ gl.uniform1i(uUseAmbient,true);
+
+ gl.uniform3f(uDiffuseColor,1,1,1);
+ gl.uniform1i(uUseDiffuse,true);
+
+ gl.uniform3f(uLightDir,0,-1,-0.3);
+
+ // обектите, съставящи люлката на Нютон
+ cradleStand = [];
+ cradleStand.push(new Cuboid([0,0,-10], [14, 20, 1]));
+ cradleStand[0].color = [0.4, 0.4, 0.4];
+ cradleStand.push(new Cylinder([-6.5,7,0], 0.4, 17));
+ cradleStand.push(new Cylinder([6.5,7,0], 0.4, 17));
+ cradleStand.push(new Cylinder([-6.5,-7,0], 0.4, 17));
+ cradleStand.push(new Cylinder([6.5,-7,0], 0.4, 17));
+ for (var i = 1; i < 5; i++) cradleStand[i].color = [0.9,0.9,0.9];
+ cradleStand.push(new Cylinder([-6.5,-9.5,-10.5], 1, 2));
+ cradleStand.push(new Cylinder([-6.5, 9.5,-10.5], 1, 2));
+ cradleStand.push(new Cylinder([ 6.5,-9.5,-10.5], 1, 2));
+ cradleStand.push(new Cylinder([ 6.5, 9.5,-10.5], 1, 2));
+ for (var i = 5; i < 9; i++) cradleStand[i].color = [0.2,0.1,0.1];
+ }
+
+ var frame = 0;
+
+ /*
+ * Предварително се извинявам за малоумщините в кода, твърде съм изморен за да ги оправям
+ */
+
+ // поради дебилния начин по който съм направил индексирането на топките, тази стойност винаги трябва да е четна и винаги ще бъдат нечетен брой топки
+ var n = 8; // брой топки
+ const cradleStandBarAngle = 35;
+ const ballDepth = 5; // за предпочитане да не се променя, не ми се мислеха математики и има хардкоуднати неща
+ const ballSize = 1;
+ const ballRotationFrames = 170; // брой кадри в които една топка от краищата се върти
+ const ballPropFrames = 20; // брой кадри вътрешните топки се удрят една в друга
+
+ var animationDuration = 2 * ballRotationFrames + 1.5 * ballPropFrames;
+
+ function smoothOffsetting(frame, duration, peaks) {
+ return Math.sin((frame % duration) / duration * Math.PI) * peaks;
+ }
+
+ function rotateEndBall(frame) {
+ return smoothOffsetting(frame, ballRotationFrames, 90);
+ }
+
+ function hitPropagation(frame, ballIndex) {
+ if (ballIndex % 2 == 0) ballIndex = (n - ballIndex) / 2 - 1;
+ else ballIndex = (ballIndex - 1) / 2 + 5;
+
+ return smoothOffsetting(frame, ballPropFrames, ballIndex / n * 15);
+ }
+
+ function between(value, a, b) {
+ return a <= value && value <= b;
+ }
+
+ var stringLength = Math.sqrt(7 * 7 + ballDepth * ballDepth);
+ var peakHeight = Math.sqrt(17 * 17 + 10 * 10);
+ var ballRotation = Math.asin(ballSize / (ballDepth + ballSize / 2)) * 180 / Math.PI;
+ function drawFrame()
+ {
+ frame++;
+ gl.clear(gl.COLOR_BUFFER_BIT+gl.DEPTH_BUFFER_BIT);
+
+ lookAt([55*Math.cos(frame/300),55*Math.sin(frame/300),0], [0,0,0], [0,0,1]);
+
+
+ // рисуване на стойката
+ cradleStand[0].draw();
+ pushMatrix();
+ translate([0,0,-13]);
+ pushMatrix();
+ translate([0,4,0]);
+ xRotate(-cradleStandBarAngle);
+ cradleStand[1].draw();
+ cradleStand[2].draw();
+ popMatrix();
+ pushMatrix();
+ translate([0,-4,0]);
+ xRotate(cradleStandBarAngle);
+ cradleStand[3].draw();
+ cradleStand[4].draw();
+ popMatrix();
+ popMatrix();
+ for (var i = 5; i < 9; i++) cradleStand[i].draw();
+
+ // рисуване на n топки
+ for (var i=0; i<n; i++)
+ {
+ var lString = new Cone([-7 / 2,0,-ballDepth / 2], 0.1, stringLength);
+ lString.color = [0,0,0];
+ var rString = new Cone([7 / 2,0,-ballDepth / 2], 0.1, stringLength);
+ rString.color = [0,0,0];
+ var ball = new Sphere([0,0,-ballSize * 0.53], ballSize);
+
+ pushMatrix();
+ var rot = ballRotation * ((i % 2 === 0) ? -i+1 : i) - ballRotation;
+ if (between(frame % animationDuration, 0, ballRotationFrames) && i === n - 1) { // left ball
+ rot += rotateEndBall(frame % animationDuration);
+ }
+ else if (between(frame % animationDuration, ballRotationFrames + 1, ballRotationFrames + ballPropFrames)
+ && !(between(frame % animationDuration, ballRotationFrames + ballPropFrames / 2, ballRotationFrames + ballPropFrames) && i === n - 2)) { // balls go right
+ rot -= hitPropagation(frame % animationDuration - (ballRotationFrames + 1), n - i - 1);
+ }
+ else if (between(frame % animationDuration, ballRotationFrames + ballPropFrames / 2 + 1, ballRotationFrames * 2 + ballPropFrames / 2)
+ && i === n - 2) { // right ball
+ rot -= rotateEndBall(frame % animationDuration - (ballRotationFrames + ballPropFrames - ballPropFrames / 2));
+ }
+ else if (between(frame % animationDuration, ballRotationFrames * 2 + ballPropFrames / 2 + 1, animationDuration)
+ && !(between(frame % animationDuration, ballRotationFrames * 2 + ballPropFrames, animationDuration) && i === n - 1)) { // balls go left
+ rot += hitPropagation(frame % animationDuration - (ballRotationFrames * 2 + ballPropFrames / 2 + 1), i);
+ }
+
+ translate([0,0,ballDepth]); xRotate(rot); translate([0,0,-ballDepth]);
+ pushMatrix();
+ translate([0,0,stringLength / 2.5]); yRotate(-45);
+ lString.draw();
+ popMatrix();
+ pushMatrix();
+ translate([0,0,stringLength / 2.5]); yRotate(45);
+ rString.draw();
+ popMatrix();
+ ball.draw();
+ popMatrix();
+ }
+
+ requestAnimationFrame(drawFrame);
+ }
+ </script>
+</head>
+
+<body onload="start()">
+ <h2>Люлката</h2>
+
+ <noscript>
+ Искаме JavaScript, но няма!
+ </noscript>
+
+ <canvas id="picasso" width="600" height="400" style="border: solid;">
+ Искаме canvas, но няма!
+ </canvas>
+</body>