-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
355 lines (290 loc) · 10.5 KB
/
app.js
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
var vertexShaderText =
`
precision mediump float;
attribute vec3 vertPosition;
attribute vec3 vertNormal;
varying vec3 fragNormal;
uniform mat4 mWorld;
uniform mat4 mView;
uniform mat4 mProj;
void main()
{
fragNormal = (mWorld * vec4(vertNormal, 0.0)).xyz;
gl_Position = mProj * mView * mWorld * vec4(vertPosition, 1.0);
}
`;
var fragmentShaderText =
`
precision mediump float;
varying vec3 fragNormal;
void main()
{
vec3 ambientLightIntensity = vec3(0.2, 0.2, 0.2);
vec3 sunlightIntensity = vec3(0.9, 0.9, 0.9);
vec3 sunlightDirection = normalize(vec3(1.0, 1.0, -2.0));
vec3 color = vec3(0.7, 0.7, 0.7);
vec3 lightIntensity = ambientLightIntensity + sunlightIntensity * max(dot(fragNormal, sunlightDirection), 0.0);
gl_FragColor = vec4(color * lightIntensity, 1.0);
}
`;
var bunny = {};
var stopDemo = false;
var initDemo = function()
{
loadBunnyObj(function(objText)
{
bunny.vertices = [];
bunny.indices = [];
bunny.normals = [];
var lines = objText.split("\n");
for (var i = 0; i < lines.length; i++)
{
if (lines[i][0] == "#")
continue;
var line = lines[i].split(/\s+/);
if (line[0] == "v")
{
line.shift();
bunny.vertices.push(line[0]);
bunny.vertices.push(line[1]);
bunny.vertices.push(line[2]);
}
else if (line[0] == "vn")
{
line.shift();
bunny.normals.push(line[0]);
bunny.normals.push(line[1]);
bunny.normals.push(line[2]);
}
else if (line[0] == "f")
{
line.shift();
for (var j = 0; j < line.length; j++)
{
var index = line[j].split("/");
bunny.indices.push(index[0] - 1);
}
}
}
runScene(bunny);
});
};
var runScene = function(bunnyMesh)
{
stopDemo = false;
var canvas = document.getElementById('webgl-surface');
var gl = canvas.getContext('webgl');
if (!gl)
{
console.log('could not get webgl surface');
alert('Your browser does not support WebGL');
return;
}
gl.clearColor(0.75, 0.85, 0.8, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.CULL_FACE);
gl.frontFace(gl.CCW);
gl.cullFace(gl.BACK);
var vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderText);
var fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderText);
var program = createProgram(gl, vertexShader, fragmentShader);
var boxVertexBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, boxVertexBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(bunnyMesh.vertices), gl.STATIC_DRAW);
var boxIndexBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boxIndexBufferObject);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(bunnyMesh.indices), gl.STATIC_DRAW);
var boxNormalBufferObject = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, boxNormalBufferObject);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(bunnyMesh.normals), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, boxVertexBufferObject);
var positionAttribLocation = gl.getAttribLocation(program, 'vertPosition');
gl.vertexAttribPointer(
positionAttribLocation,
3,
gl.FLOAT,
gl.FALSE,
3 * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.enableVertexAttribArray(positionAttribLocation);
gl.bindBuffer(gl.ARRAY_BUFFER, boxNormalBufferObject);
var vertNormalAttribLocation = gl.getAttribLocation(program, 'vertNormal');
gl.vertexAttribPointer(
vertNormalAttribLocation,
3,
gl.FLOAT,
gl.TRUE,
3 * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.enableVertexAttribArray(vertNormalAttribLocation);
gl.useProgram(program);
var matWorldUniformLocation = gl.getUniformLocation(program, 'mWorld');
var matViewUniformLocation = gl.getUniformLocation(program, 'mView');
var matProjUniformLocation = gl.getUniformLocation(program, 'mProj');
var worldMatrix = new Float32Array(16);
var viewMatrix = new Float32Array(16);
var projMatrix = new Float32Array(16);
mat4.identity(worldMatrix);
mat4.lookAt(viewMatrix, [0, 3, -8], [0, 1, 0], [0, 1, 0]);
mat4.perspective(projMatrix, glMatrix.toRadian(45), canvas.width / canvas.height, 0.1, 1000.0);
gl.uniformMatrix4fv(matWorldUniformLocation, gl.FALSE, worldMatrix);
gl.uniformMatrix4fv(matViewUniformLocation, gl.FALSE, viewMatrix);
gl.uniformMatrix4fv(matProjUniformLocation, gl.FALSE, projMatrix);
// main render loop
var identityMatrix = new Float32Array(16);
mat4.identity(identityMatrix);
var angle = 0;
var loop = function ()
{
angle = performance.now() / 1000 / 6 * 2 * Math.PI;
mat4.rotate(worldMatrix, identityMatrix, angle, [0, 1, 0]);
gl.uniformMatrix4fv(matWorldUniformLocation, gl.FALSE, worldMatrix);
gl.clearColor(0.75, 0.85, 0.8, 1.0);
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
gl.drawElements(gl.TRIANGLES, bunnyMesh.indices.length, gl.UNSIGNED_SHORT, 0);
if (!stopDemo)
requestAnimationFrame(loop);
};
requestAnimationFrame(loop);
};
function createShader(gl, type, source)
{
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (success)
{
return shader;
}
console.log(gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
}
function createProgram(gl, vertexShader, fragmentShader)
{
var program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
var success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (success)
{
return program;
}
console.log(gl.getProgramInfoLog(program));
gl.deleteProgram(program);
}
function loadBunnyObj(callback)
{
var request = new XMLHttpRequest();
request.open("GET", "bunny.obj", true);
request.onload = function()
{
if (request.status == 200 && request.readyState == 4)
{
callback(request.responseText);
}
}
request.send();
}
function runSmoothing()
{
bunny.vertices = laplacianFilter(bunny.vertices, bunny.indices, 10);
stopDemo = true;
bunny.normals = recalculateNormals(bunny.vertices, bunny.indices);
runScene(bunny);
}
function laplacianFilter(vertices, indices, iterations)
{
var network = buildNetwork(indices);
for (var i = 0; i < iterations; i++)
vertices = laplacianFilterStep(network, vertices, indices);
return vertices;
}
function laplacianFilterStep(network, vertices, indices)
{
var filteredVertices = [];
for (var i = 0; i < vertices.length; i += 3)
{
var vertexNumber = i / 3;
var connections = network[vertexNumber].adjacentIndices;
var newVertex = vec3.create();
for (const index of Object.keys(connections))
{
var currentVertex = vec3.fromValues(vertices[3 * parseInt(index)], vertices[3 * parseInt(index) + 1], vertices[3 * parseInt(index) + 2]);
vec3.add(newVertex, newVertex, currentVertex);
}
var connectionsLength = Object.keys(connections).length;
filteredVertices[i] = newVertex[0] / connectionsLength;
filteredVertices[i + 1] = newVertex[1] / connectionsLength;
filteredVertices[i + 2] = newVertex[2] / connectionsLength;
}
return filteredVertices;
}
function buildNetwork(indices)
{
var network = {};
for (var i = 0; i < indices.length; i += 3)
{
var indexA = indices[i];
var indexB = indices[i + 1];
var indexC = indices[i + 2];
if (!network.hasOwnProperty(indexA))
network[indexA] = { adjacentIndices: {} };
if (!network.hasOwnProperty(indexB))
network[indexB] = { adjacentIndices: {} };
if (!network.hasOwnProperty(indexC))
network[indexC] = { adjacentIndices: {} };
network[indexA].adjacentIndices[indexB] = true;
network[indexA].adjacentIndices[indexC] = true;
network[indexB].adjacentIndices[indexA] = true;
network[indexB].adjacentIndices[indexC] = true;
network[indexC].adjacentIndices[indexA] = true;
network[indexC].adjacentIndices[indexB] = true;
}
return network;
}
function recalculateNormals(vertices, indices)
{
var faceNormals = {};
for (var i = 0; i < indices.length; i += 3)
{
var indexA = indices[i];
var indexB = indices[i + 1];
var indexC = indices[i + 2];
var vecA = vec3.fromValues(vertices[3 * indexA], vertices[3 * indexA + 1], vertices[3 * indexA + 2]);
var vecB = vec3.fromValues(vertices[3 * indexB], vertices[3 * indexB + 1], vertices[3 * indexB + 2]);
var vecC = vec3.fromValues(vertices[3 * indexC], vertices[3 * indexC + 1], vertices[3 * indexC + 2]);
var edge1 = vec3.create(); var edge2 = vec3.create();
vec3.sub(edge1, vecB, vecA);
vec3.sub(edge2, vecC, vecA);
var normal = vec3.create();
vec3.cross(normal, edge1, edge2);
vec3.normalize(normal, normal);
if (!faceNormals.hasOwnProperty(indexA))
faceNormals[indexA] = [];
if (!faceNormals.hasOwnProperty(indexB))
faceNormals[indexB] = [];
if (!faceNormals.hasOwnProperty(indexC))
faceNormals[indexC] = [];
faceNormals[indexA].push(normal);
faceNormals[indexB].push(normal);
faceNormals[indexC].push(normal);
}
var newNormals = bunny.normals;
for (var index in Object.keys(faceNormals))
{
var connectedFaceNormals = faceNormals[parseInt(index)];
var vertexNormal = vec3.create();
for (var i = 0; i < connectedFaceNormals.length; i++)
{
vec3.add(vertexNormal, vertexNormal, connectedFaceNormals[i]);
}
vec3.normalize(vertexNormal, vertexNormal);
newNormals[3 * parseInt(index)] = vertexNormal[0]; newNormals[3 * parseInt(index) + 1 ] = vertexNormal[1]; newNormals[3 * parseInt(index) + 2] = vertexNormal[2];
}
return newNormals;
}