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
|
<!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>
|