]> git.scottworley.com Git - nt3d/blob - nt3d.js
239b03c214afed2d58de96070d8a5982870be677
[nt3d] / nt3d.js
1 /* nt3d - Javascript library for doing some 3D stuff.
2 * Copyright (C) 2012 Scott Worley <ScottWorley@ScottWorley.com>
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
13 *
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 nt3d = {
19 triangle: function(a, b, c) {
20 return [a, b, c];
21 },
22 quad: function(a, b, c, d) {
23 return this.triangle(a, b, c).concat(
24 this.triangle(c, d, a));
25 },
26 trianglefan: function(fan) {
27 var result = [];
28 for (var i = 2; i < fan.length; i++) {
29 result.push(fan[0], fan[i-1], fan[i]);
30 }
31 return result;
32 },
33 closed_trianglefan: function(fan) {
34 return this.trianglefan(fan.concat([fan[1]]));
35 },
36 quadstrip: function(strip) {
37 if (strip.length % 2 != 0) {
38 alert("quadstrip length not divisble by 2!");
39 }
40 var result = [];
41 for (var i = 2; i < strip.length; i += 2) {
42 result = result.concat(this.quad(strip[i-2], strip[i-1], strip[i+1], strip[i]));
43 }
44 return result;
45 },
46 closed_quadstrip: function(strip) {
47 return this.quadstrip(strip.concat([strip[0], strip[1]]));
48 },
49 circle: function(r, n) {
50 var points = [];
51 for (var i = 0; i < n; i++) {
52 points.push([r*Math.cos(2*Math.PI*i/n),
53 r*Math.sin(2*Math.PI*i/n),
54 0]);
55 }
56 return points;
57 },
58 cone: function(base_center, apex, radius, steps) {
59 var base = this.circle(radius, steps);
60 base = this.rotate_onto(base, [0,0,1], this.sub(apex, base_center));
61 base = this.translate(base, base_center);
62 return this.closed_trianglefan([apex].concat(base)).concat(
63 this.trianglefan(base.reverse()));
64 },
65 shapenormals_from_closed_path: function(path) {
66 return function(i) {
67 var prev = (i == 0) ? path.length-1 : i-1;
68 var next = (i == path.length-1) ? 0 : i+1;
69 return nt3d.sub(path[next], path[prev]);
70 };
71 },
72 shapenormals_from_path_and_extra_points: function(path, first_point, last_point) {
73 return function(i) {
74 var prev = (i == 0) ? first_point : path[i-1];
75 var next = (i == path.length-1) ? last_point : path[i+1];
76 return nt3d.sub(next, prev);
77 };
78 },
79 shapenormals_from_path_and_first_and_last_normals: function(path, first_normal, last_normal) {
80 return function(i) {
81 if (i == 0) { return first_normal; }
82 if (i == path.length-1) { return last_normal; }
83 return nt3d.sub(path[i+1], path[i-1]);
84 };
85 },
86 pathnormals_from_point: function(path, p) {
87 // Use this with any point that is not on any path tangent line
88 var pathnormals = [];
89 for (var i = 0; i < path.length; i++) {
90 pathnormals.push(this.sub(path[i], p));
91 }
92 return pathnormals;
93 },
94 to_function: function(thing, make_indexer) {
95 // If thing is a point, just yield thing every time.
96 // If thing is a list of points && make_indexer, index into thing.
97 // If thing is already a function, just return it.
98 if (({}).toString.call(thing) === "[object Function]") {
99 return thing; // Already a function
100 }
101 if (make_indexer && Array.isArray(thing[0])) {
102 // Looks like a list of points.
103 return function(i) { return thing[i]; }
104 }
105 return function() { return thing; }
106 },
107 extrude: function(path, shape, shapenormals, pathnormals) {
108
109 var guts_result = this._extrude_guts(path, shape, shapenormals, pathnormals);
110 // Add the end-caps
111 // XXX: This doesn't work if shape is not convex
112 return guts_result.points.concat(
113 this.trianglefan(guts_result.first_loop.reverse()),
114 this.trianglefan(guts_result.last_loop));
115
116 },
117 closed_extrude: function(path, shape, shapenormals, pathnormals) {
118 var guts_result = this._extrude_guts(path, shape, shapenormals, pathnormals);
119 // Stitch the ends together
120 return guts_result.points.concat(
121 this.closed_quadstrip(this.zip(guts_result.first_loop, guts_result.last_loop)));
122 },
123 _extrude_guts: function(path, shape, shapenormals, pathnormals) {
124 var shape_fun = this.to_function(shape, false);
125 var shapenormal_fun = this.to_function(shapenormals, true);
126 var pathnormal_fun = this.to_function(pathnormals, true);
127 var result = { points: [] };
128 var prev_loop;
129 for (var i = 0; i < path.length; i++) {
130 var shapenormali = shapenormal_fun(i, path[i]);
131 var pathnormali = pathnormal_fun(i, path[i], shapenormali);
132
133 // Fix pathnormali to be perfectly perpendicular to
134 // shapenormali. pathnormali must be perpendicular to
135 // shapenormali or the second rotation will take loop
136 // back out of the shapenormali plane that the first
137 // rotation so carefully placed it in. But, letting
138 // callers be sloppy with the pathnormals can greatly
139 // simplify generating them -- so much so that you can
140 // often just pass a constant to use the same value
141 // along the whole path.
142 pathnormali = this.project_to_orthogonal(shapenormali, pathnormali);
143
144 var shapei = shape_fun(i, path[i], shapenormali, pathnormali);
145
146 // loop is shapei in 3d with (0,0) at path[i], shape's
147 // z axis in the direction of shapenormali, and shape's
148 // x axis in the direction of pathnormali. We tack
149 // [1,0,0] onto the end as a hack to see where it ends
150 // up after the first rotation. This is removed later.
151 var loop = shapei.concat([[1,0,0]]);
152
153 // This is done in three steps:
154 // 1. Rotate shape out of the xy plane so that [0,0,1]
155 // becomes shapenormali. This puts the shape in
156 // the correct plane, but does not constrain its
157 // rotation about shapenormali.
158 loop = this.rotate_onto(loop, [0,0,1], shapenormali);
159 var shapex = loop.pop();
160
161 // 2. Rotate around shapenormali so that [1,0,0]
162 // becomes pathnormali.
163 loop = this.rotate_onto(loop, shapex, pathnormali);
164
165 // (This would probably be faster and more numerically stable
166 // if the two rotations were applied as one combined operation
167 // rather than separate steps.)
168
169 // 3. Translate to path[i].
170 loop = this.translate(loop, path[i]);
171
172 if (i == 0) {
173 result.first_loop = loop;
174 } else {
175 result.points = result.points.concat(this.closed_quadstrip(this.zip(loop, prev_loop)));
176 }
177 prev_loop = loop;
178 }
179 result.last_loop = prev_loop;
180 return result;
181 },
182 zip: function(a, b) {
183 var result = [];
184 if (a.length != b.length) {
185 alert("Zip over different-sized inputs");
186 }
187 for (var i = 0; i < a.length; i++) {
188 result.push(a[i], b[i]);
189 }
190 return result;
191 },
192 magnitude: function(a) {
193 return Math.sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]);
194 },
195 unit: function(a) {
196 return this.scale(a, 1 / this.magnitude(a));
197 },
198 sub: function(a, b) {
199 return [a[0] - b[0],
200 a[1] - b[1],
201 a[2] - b[2]];
202 },
203 neg: function(a) {
204 return [-a[0], -a[1], -a[2]];
205 },
206 dot: function(a, b) {
207 return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
208 },
209 scale: function(v, s) { // Scale vector v by scalar s
210 return [s*v[0], s*v[1], s*v[2]];
211 },
212 cross: function(a, b) {
213 return [a[1]*b[2] - a[2]*b[1],
214 a[2]*b[0] - a[0]*b[2],
215 a[0]*b[1] - a[1]*b[0]];
216 },
217 normal: function(a, b, c) {
218 return this.cross(this.sub(a, b), this.sub(b, c));
219 },
220 project: function(a, b) { // Project b onto a
221 var a_magnitude = this.magnitude(a);
222 return this.scale(a, this.dot(a, b) / (a_magnitude * a_magnitude));
223 },
224 project_to_orthogonal: function(a, b) {
225 // The nearest thing to b that is orthogonal to a
226 return this.sub(b, this.project(a, b));
227 },
228 translate: function(points, offset) {
229 var translated = [];
230 for (var i = 0; i < points.length; i++) {
231 translated[i] = this.translate_point(points[i], offset);
232 }
233 return translated;
234 },
235 translate_point: function(point, offset) {
236 return [point[0] + offset[0],
237 point[1] + offset[1],
238 point[2] + offset[2]];
239 },
240 angle_between: function(a, b) { // a and b must be unit vectors
241 return Math.acos(this.dot(a, b));
242 },
243 rotate_about_origin: function(points, axis, angle) { // axis must be a unit vector
244 // From http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/
245 var cosangle = Math.cos(angle);
246 var sinangle = Math.sin(angle);
247 var rotated = [];
248 for (var i = 0; i < points.length; i++) {
249 var p = points[i];
250 var tmp = this.dot(p, axis) * (1 - cosangle);
251 rotated[i] = [
252 axis[0]*tmp + p[0]*cosangle + (-axis[2]*p[1] + axis[1]*p[2])*sinangle,
253 axis[1]*tmp + p[1]*cosangle + ( axis[2]*p[0] - axis[0]*p[2])*sinangle,
254 axis[2]*tmp + p[2]*cosangle + (-axis[1]*p[0] + axis[0]*p[1])*sinangle];
255 }
256 return rotated;
257 },
258 rotate_onto: function(points, a, b) {
259 // Rotate points such that a (in points-space) maps onto b
260 // by crossing a and b to get a rotation axis and using
261 // angle_between to get a rotation angle.
262 var angle = this.angle_between(this.unit(a), this.unit(b));
263 if (Math.abs(angle) < 1e-15) {
264 // No siginificant rotation to perform. Bail to avoid
265 // NaNs and numerical error
266 return points;
267 }
268 var axis = this.unit(this.cross(a, b));
269 return this.rotate_about_origin(points, axis, angle);
270 },
271 rotate: function(points, center, axis, angle) { // axis must be a unit vector
272 return this.translate(
273 this.rotate_about_origin(
274 this.translate(points, this.neg(center)),
275 axis,
276 angle),
277 center);
278 },
279 go: function() {
280 // Remove any previous download links
281 var old_download_link = document.getElementById("nt3d_download");
282 if (old_download_link) {
283 old_download_link.parentNode.removeChild(old_download_link);
284 }
285
286 // Continue in a callback, so that there's not a stale download
287 // link hanging around while we process.
288 setTimeout(function(the_this) { (function() {
289
290 // Get params from form
291 var params = [];
292 for (var i = 0; i < this.user_params.length; i++) {
293 var as_string = this.form.elements["param"+i].value;
294 var as_num = +as_string;
295 params[i] = isNaN(as_num) ? as_string : as_num;
296 }
297
298 // Run user_function
299 this.points = this.user_function.apply(null, params);
300 if (this.points.length % 3 != 0) {
301 alert("Points list length not divisble by 3!");
302 }
303 var n = this.points.length / 3;
304
305 // Make STL
306 this.stl = "solid " + this.user_function.name + "\n";
307 for (var i = 0; i < n; i++) {
308 var a = this.points[i*3+0];
309 var b = this.points[i*3+1];
310 var c = this.points[i*3+2];
311 var normal = this.normal(a, b, c);
312 this.stl += "facet normal " + normal[0] + " " + normal[1] + " " + normal[2] + "\n" +
313 "outer loop\n" +
314 "vertex " + a[0] + " " + a[1] + " " + a[2] + "\n"+
315 "vertex " + b[0] + " " + b[1] + " " + b[2] + "\n"+
316 "vertex " + c[0] + " " + c[1] + " " + c[2] + "\n"+
317 "endloop\n" +
318 "endfacet\n";
319 }
320 this.stl += "endsolid " + this.user_function.name + "\n";
321
322
323 // Offer result as download
324 var download_link = document.createElement("a");
325 download_link.appendChild(document.createTextNode("Download!"));
326 download_link.setAttribute("id", "nt3d_download");
327 download_link.setAttribute("style", "background-color: blue");
328 download_link.setAttribute("download", this.user_function.name + ".stl");
329 download_link.setAttribute("href", "data:application/sla," + encodeURIComponent(this.stl));
330 this.ui.appendChild(download_link);
331 setTimeout(function() { download_link.setAttribute("style", "-webkit-transition: background-color 0.4s; -moz-transition: background-color 0.4s; -o-transition: background-color 0.4s; -ms-transition: background-color 0.4s; transition: background-color 0.4s; background-color: inherit"); }, 0);
332
333 }).call(the_this); }, 0, this); // (We were in a callback this whole time, remember?)
334 },
335 framework: function (f, params) {
336 this.user_function = f;
337 this.user_params = params;
338
339 // Make the UI
340 this.ui = document.getElementById("nt3dui");
341 if (!this.ui) {
342 this.ui = document.createElement("div");
343 this.ui.setAttribute("id", "nt3dui");
344 document.body.appendChild(this.ui);
345 }
346 this.form = document.createElement("form");
347 this.form.setAttribute("onsubmit", "nt3d.go(); return false");
348 this.ui.appendChild(this.form);
349 var table = document.createElement("table");
350 this.form.appendChild(table);
351 var tr = document.createElement("tr");
352 table.appendChild(tr);
353 var th = document.createElement("th");
354 th.appendChild(document.createTextNode("Variable"));
355 tr.appendChild(th);
356 th = document.createElement("th");
357 th.appendChild(document.createTextNode("Value"));
358 tr.appendChild(th);
359 for (var i = 0; i < params.length; i++) {
360 tr = document.createElement("tr");
361 table.appendChild(tr);
362 var td = document.createElement("td");
363 td.appendChild(document.createTextNode(params[i][0]));
364 tr.appendChild(td);
365 td = document.createElement("td");
366 var input = document.createElement("input");
367 input.setAttribute("name", "param" + i);
368 input.setAttribute("value", params[i][1]);
369 td.appendChild(input);
370 tr.appendChild(td);
371 }
372 var go = document.createElement("input");
373 go.setAttribute("type", "button");
374 go.setAttribute("value", "Go!");
375 go.setAttribute("onclick", "nt3d.go()");
376 this.form.appendChild(go);
377 }
378 };