-
Notifications
You must be signed in to change notification settings - Fork 6
/
hypersolid.js
353 lines (305 loc) · 10.9 KB
/
hypersolid.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
/*
* Hypersolid, Four-dimensional solid viewer
*
* Copyright (c) 2014 Milosz Kosmider <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
(function(Hypersolid) {
/* Begin constants. */
DEFAULT_VIEWPORT_WIDTH = 480; // Width of canvas in pixels
DEFAULT_VIEWPORT_HEIGHT = 480; // Height of canvas in pixels
DEFAULT_VIEWPORT_SCALE = 2; // Maximum distance from origin (in math units) that will be displayed on the canvas
DEFAULT_VIEWPORT_FONT = 'italic 10px sans-serif';
DEFAULT_VIEWPORT_FONT_COLOR = '#000';
DEFAULT_VIEWPORT_LINE_WIDTH = 4;
DEFAULT_VIEWPORT_LINE_JOIN = 'round';
DEFAULT_CHECKBOX_VALUES = {
perspective: { checked: true },
indices: { checked: false },
edges: { checked: true }
};
/* End constants. */
/* Begin classes. */
Hypersolid.Shape = function() {
return new Shape(Array.prototype.slice.call(arguments, 0));
};
function Shape(argv) {
var self = this,
vertices = argv[0],
edges = argv[1];
// Rotations will always be relative to the original shape to avoid rounding errors.
// This is a structure for caching the rotated vertices.
var rotatedVertices = new Array(vertices.length);
copyVertices();
// This is where we store the current rotations about each axis.
var rotations = { xy: 0, xz: 0, xw: 0, yz: 0, yw: 0, zw: 0 };
var rotationOrder = {
yz: 1,
xw: 1,
yw: 1,
zw: 1,
xy: 1,
xz: 1,
};
// Multiplication by vector rotation matrices of dimension 4
var rotateVertex = {
xy: function(v, s, c) {
tmp = c * v.x + s * v.y;
v.y = -s * v.x + c * v.y;
v.x = tmp;
},
xz: function(v, s, c) {
tmp = c * v.x + s * v.z;
v.z = -s * v.x + c * v.z;
v.x = tmp;
},
xw: function(v, s, c) {
tmp = c * v.x + s * v.w;
v.w = -s * v.x + c * v.w;
v.x = tmp;
},
yz: function(v, s, c) {
tmp = c * v.y + s * v.z;
v.z = -s * v.y + c * v.z;
v.y = tmp;
},
yw: function(v, s, c) {
tmp = c * v.y - s * v.w;
v.w = s * v.y + c * v.w;
v.y = tmp;
},
zw: function(v, s, c) {
tmp = c * v.z - s * v.w;
v.w = s * v.z + c * v.w;
v.z = tmp;
}
};
var eventCallbacks = {};
self.getOriginalVertices = function() {
return vertices;
};
self.getVertices = function() {
return rotatedVertices;
};
self.getEdges = function() {
return edges;
};
self.getRotations = function() {
return rotations;
};
// This will copy the original shape and put a rotated version into rotatedVertices
self.rotate = function(axis, theta) {
addToRotation(axis, theta);
applyRotations();
triggerEventCallbacks('rotate');
};
self.on = function(eventName, callback) {
if (eventCallbacks[eventName] === undefined) {
eventCallbacks[eventName] = [];
}
eventCallbacks[eventName].push(callback);
};
function triggerEventCallbacks(eventName) {
if (eventCallbacks[eventName] !== undefined) {
for (index in eventCallbacks[eventName]) {
eventCallbacks[eventName][index].call(self);
}
}
}
function addToRotation(axis, theta) {
rotations[axis] = (rotations[axis] + theta) % (2 * Math.PI);
}
function applyRotations() {
copyVertices();
for (var axis in rotationOrder) {
// sin and cos precomputed for efficiency
var s = Math.sin(rotations[axis]);
var c = Math.cos(rotations[axis]);
for (var i in vertices)
{
rotateVertex[axis](rotatedVertices[i], s, c);
}
}
}
function copyVertices() {
for (var i in vertices) {
var vertex = vertices[i];
rotatedVertices[i] = {
x: vertex.x,
y: vertex.y,
z: vertex.z,
w: vertex.w
};
}
}
}
Hypersolid.Viewport = function() {
return new Viewport(Array.prototype.slice.call(arguments, 0));
};
function Viewport(argv) {
var self = this,
shape = argv[0],
canvas = argv[1],
options = argv[2];
options = options || {};
var scale = options.scale || DEFAULT_VIEWPORT_SCALE;
canvas.width = options.width || DEFAULT_VIEWPORT_WIDTH;
canvas.height = options.height || DEFAULT_VIEWPORT_HEIGHT;
var bound = Math.min(canvas.width, canvas.height) / 2;
var context = canvas.getContext('2d');
context.font = options.font || DEFAULT_VIEWPORT_FONT;
context.textBaseline = 'top';
context.fillStyle = options.fontColor || DEFAULT_VIEWPORT_FONT_COLOR;
context.lineWidth = options.lineWidth || DEFAULT_VIEWPORT_LINE_WIDTH;
context.lineJoin = options.lineJoin || DEFAULT_VIEWPORT_LINE_JOIN;
var checkboxes = options.checkboxes || DEFAULT_CHECKBOX_VALUES;
var clicked = false;
var startCoords;
self.draw = function() {
var vertices = shape.getVertices();
var edges = shape.getEdges();
context.clearRect(0, 0, canvas.width, canvas.height);
var adjusted = [];
for (var i in vertices) {
if (checkboxes.perspective.checked) {
var zratio = vertices[i].z / scale;
adjusted[i] = {
x: Math.floor(canvas.width / 2 + (0.90 + zratio * 0.30) * bound * (vertices[i].x / scale)) + 0.5,
y: Math.floor(canvas.height / 2 - (0.90 + zratio * 0.30) * bound * (vertices[i].y / scale)) + 0.5,
z: 0.50 + 0.40 * zratio,
w: 121 + Math.floor(134 * vertices[i].w / scale)
};
}
else {
adjusted[i] = {
x: Math.floor(canvas.width / 2 + bound * (vertices[i].x / scale)) + 0.5,
y: Math.floor(canvas.height / 2 - bound * (vertices[i].y / scale)) + 0.5,
z: 0.50 + 0.40 * vertices[i].z / scale,
w: 121 + Math.floor(134 * vertices[i].w / scale)
};
}
}
if (checkboxes.edges.checked) {
for (var i in edges) {
var x = [adjusted[edges[i][0]].x, adjusted[edges[i][1]].x];
var y = [adjusted[edges[i][0]].y, adjusted[edges[i][1]].y];
var z = [adjusted[edges[i][0]].z, adjusted[edges[i][1]].z];
var w = [adjusted[edges[i][0]].w, adjusted[edges[i][1]].w];
context.beginPath();
context.moveTo(x[0], y[0]);
context.lineTo(x[1], y[1]);
context.closePath();
var gradient = context.createLinearGradient(x[0], y[0], x[1], y[1]); // Distance fade effect
gradient.addColorStop(0, 'rgba(' + w[0] + ',94,' + (125-Math.round(w[0]/2)) +', ' + z[0] + ')');
gradient.addColorStop(1, 'rgba(' + w[1] + ',94,' + (125-Math.round(w[0]/2)) +', ' + z[1] + ')');
context.strokeStyle = gradient;
context.stroke();
}
}
if (checkboxes.indices.checked) {
for (var i in adjusted) {
context.fillText(i.toString(), adjusted[i].x, adjusted[i].y);
}
}
};
canvas.onmousedown = function(e) {
startCoords = mouseCoords(e, canvas);
startCoords.x -= Math.floor(canvas.width / 2);
startCoords.y = Math.floor(canvas.height / 2) - startCoords.y;
clicked = true;
};
document.onmousemove = function(e) {
if (!clicked) {
return true;
}
var currCoords = mouseCoords(e, canvas);
currCoords.x -= Math.floor(canvas.width / 2);
currCoords.y = Math.floor(canvas.height / 2) - currCoords.y;
var motion = { 'x': currCoords.x - startCoords.x, 'y': currCoords.y - startCoords.y };
if (e.shiftKey && (e.altKey || e.ctrlKey)) {
shape.rotate('xy', Math.PI * motion.x / bound); // Full canvas drag ~ 2*PI
shape.rotate('zw', Math.PI * motion.y / bound);
}
else if (e.shiftKey) {
// Interpretation of this rotation varies between left- and right- brained users
shape.rotate('xw', Math.PI * motion.x / bound);
shape.rotate('yw', Math.PI * motion.y / bound);
}
else {
shape.rotate('xz', Math.PI * motion.x / bound);
shape.rotate('yz', Math.PI * motion.y / bound);
}
startCoords = currCoords;
self.draw();
};
document.onmouseup = function() {
clicked = false;
};
checkboxes.onchange = function() {
self.draw();
};
}
/* End classes. */
/* Begin methods. */
// parse ascii files from http://paulbourke.net/geometry/hyperspace/
Hypersolid.parseVEF = function(text) {
var lines = text.split("\n");
var nV = parseInt(lines[0]); // number of vertices
var nE = parseInt(lines[1+nV]); // number of edges
var nF = parseInt(lines[2+nV+nE]); // number of faces
var vertices = lines.slice(1,1+nV).map(function(line) {
var d = line.split("\t").map(parseFloat);
return {
x: d[0],
y: d[1],
z: d[2],
w: d[3],
}
});
var edges = lines.slice(2+nV,2+nV+nE).map(function(line) {
var d = line.replace("\s","").split("\t").map(function(vertex) { return parseInt(vertex); });
return [d[0], d[1]];;
});
var faces = lines.slice(3+nV+nE,3+nV+nE+nF).map(function(line) {
var d = line.replace("\s","").split("\t").map(function(edge) { return parseInt(edge); });
return d;
});
return [vertices,edges,faces]
};
/* End methods. */
/* Begin helper routines. */
function mouseCoords(e, element) { // http://answers.oreilly.com/topic/1929-how-to-use-the-canvas-and-draw-elements-in-html5/
var x;
var y;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -= element.offsetLeft;
y -= element.offsetTop;
return { 'x': x, 'y': y };
}
/* End helper routines. */
})(window.Hypersolid = window.Hypersolid || {});