Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Computer Graphics with WebGL / Homework 06 - The knot / Homework.html
blob: 348947b32d1f5d789c05d81256342fb16699c6a4 (plain) (blame)
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
<!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;
			gl_PointSize = 10.0;
		}
	</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 = max(dot(reflectedLight,viewDir),0.0);
			vec3 specularColor = vec3(pow(cosa,5.0));
			gl_FragColor = vec4(vColor+specularColor,1);
		}
	</script>

	<script>
		function vectorSum(x, y) {
			return [ x[0] + y[0], x[1] + y[1], x[2] + y[2] ];
		}
		function dotProduct(x, y) {
			return x[0] * y[0] + x[1] * y[1] + x[2] * y[2];
		}
		function euNorm(x) {
			return Math.sqrt(x[0] * x[0] + x[1] * x[1] + x[2] * x[2]);
		}
		function matVecMult(a, x) {
			return [dotProduct(a.slice(0, 3), x), dotProduct(a.slice(4, 7), x), dotProduct(a.slice(8, 11), x)];
		}

		var TREFOIL_POINTS = 100;
		var TREFOIL_SIDES = 3;
		var TREFOIL_RAD = 0.05;
		// трилистен възел - конструктор
		TrefoilKnot = function(center,size)
		{
			this.center = center;
			this.size = size;

			function vertex(t) {
				// https://en.wikipedia.org//wiki/Trefoil_knot#Descriptions
				return [Math.cos(t) + 2 * Math.cos(2 * t),
				        Math.sin(t) - 2 * Math.sin(2 * t),
				        -Math.sin(3 * t)];
			}

			const pointStepSize = 1 / TREFOIL_SIDES;
			var sectionCircle = [];
			for (var point = 0; point < TREFOIL_SIDES; point++) {
				sectionCircle.push([Math.sin(2 * Math.PI * point / TREFOIL_SIDES), 0, Math.cos(2 * Math.PI * point / TREFOIL_SIDES)]);
			}
			function alternateInsertEnd(points) {
				for (var i = 0, j = data.length - points.length * 3 + 3; i < points.length; i++, j += 6) {
					data.splice(j, 0, ...points[i]);
				}
			}

			function section(ver, vp) {
				var out = sectionCircle.slice(0);

				var yAng = Math.acos(dotProduct(unitVector([vp[0], vp[1], 0]), [0,1,0]));
				var xAng = Math.acos(dotProduct(unitVector([vp[0], 0, vp[2]]), [1,0,0]));
				var zRot = zRotateMatrix(yAng / Math.PI * 180);
				var yRot = yRotateMatrix(xAng / Math.PI * 180);
				out = out.map((point) => {
					point = matVecMult(zRot, point);
					point = matVecMult(yRot, point);
					point = vectorSum(point, ver);
					return point;
				});

				return out;
			}

			var data = [];

			const stepSize = 2 * Math.PI / TREFOIL_POINTS;
			for (var t = 0; t < Math.PI * 2; t += stepSize) {
				var ver = vertex(t);
				// var hue = t;
				var vec = vectorPoints(ver, vertex(t + stepSize));
				alternateInsertEnd(section(ver, vec));
				// section(ver, vec).forEach((point) => {
				// 	data.push(...point);
				// });
				// data.push(...ver);
			}

			var buf = gl.createBuffer();
			gl.bindBuffer(gl.ARRAY_BUFFER, buf);
			gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(data), gl.STATIC_DRAW);

			this.buf = buf;
			this.TREFOIL_POINTS = TREFOIL_POINTS;
			this.TREFOIL_SIDES = TREFOIL_SIDES;
		}

		// трилистен възел - метод за рисуване
		TrefoilKnot.prototype.draw = function()
		{
			pushMatrix();
			gl.vertexAttrib3fv(aColor, [1,1,1]);

			translate(this.center);
			scale([this.size, this.size, this.size]);
			useMatrix();

			gl.bindBuffer(gl.ARRAY_BUFFER, this.buf);
			// върхове
			gl.enableVertexAttribArray(aXYZ);
			gl.vertexAttribPointer(aXYZ, 3, gl.FLOAT, false, 3 * FLOATS,0);
			gl.drawArrays(gl.TRIANGLE_STRIP, 0, this.TREFOIL_POINTS * this.TREFOIL_SIDES);

			popMatrix();
		}

		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");
			uLightDir = gl.getUniformLocation(glprog,"uLightDir");

			gl.enable(gl.DEPTH_TEST);
			gl.clearColor(0,0,0,1);

			identity();
			perspective(30,gl.canvas.width/gl.canvas.height,1,40000);

			gl.uniform3f(uAmbientColor,0.4,0.4,0.4);
			gl.uniform1i(uUseAmbient,true);

			gl.uniform3f(uDiffuseColor,1,1,1);
			gl.uniform1i(uUseDiffuse,true);
			
			gl.uniform3f(uLightDir,0,0,-1);

			// създаваме трилистния възел
			s = new TrefoilKnot([0,0,0],1);
		}
		
		var frame = 0;
	
		function drawFrame()
		{
			frame++;
			gl.clear(gl.COLOR_BUFFER_BIT+gl.DEPTH_BUFFER_BIT);

			lookAt([15*Math.sin(frame/100),0,-15*Math.cos(frame/100)], [0,0,0], [0,-1,1]);
			xRotate(0.5);

			// рисуване на трилистния възел
			s.draw();

			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>