]> git.scottworley.com Git - nt3d/blob - nt3d.js
Make extrude's arguments more flexible and powerful
[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 to_function: function(thing, make_indexer) {
66 // If thing is a point, just yield thing every time.
67 // If thing is a list of points && make_indexer, index into thing.
68 // If thing is already a function, just return it.
69 if (({}).toString.call(thing) === "[object Function]") {
70 return thing; // Already a function
71 }
72 if (make_indexer && Array.isArray(thing[0])) {
73 // Looks like a list of points.
74 return function(i) { return thing[i]; }
75 }
76 return function() { return thing; }
77 },
78 extrude: function(path, shape, shapenormals, pathnormals) {
79
80 var guts_result = nt3d._extrude_guts(path, shape, shapenormals, pathnormals);
81 // Add the end-caps
82 // XXX: This doesn't work if shape is not convex
83 return guts_result.points.concat(
84 nt3d.trianglefan(guts_result.first_loop.reverse()),
85 nt3d.trianglefan(guts_result.last_loop));
86
87 },
88 closed_extrude: function(path, shape, shapenormals, pathnormals) {
89 var guts_result = nt3d._extrude_guts(path, shape, shapenormals, pathnormals);
90 // Stitch the ends together
91 return guts_result.points.concat(
92 nt3d.closed_quadstrip(nt3d.zip(guts_result.first_loop, guts_result.last_loop)));
93 },
94 _extrude_guts: function(path, shape, shapenormals, pathnormals) {
95 var shape_fun = this.to_function(shape, false);
96 var shapenormal_fun = this.to_function(shapenormals, true);
97 var pathnormal_fun = this.to_function(pathnormals, true);
98 var result = { points: [] };
99 var prev_loop;
100 for (var i = 0; i < path.length; i++) {
101 var shapenormali = shapenormal_fun(i, path[i]);
102 var pathnormali = pathnormal_fun(i, path[i], shapenormali);
103
104 // Fix pathnormali to be perfectly perpendicular to
105 // shapenormali. pathnormali must be perpendicular to
106 // shapenormali or the second rotation will take loop
107 // back out of the shapenormali plane that the first
108 // rotation so carefully placed it in. But, letting
109 // callers be sloppy with the pathnormals can greatly
110 // simplify generating them -- so much so that you can
111 // often just pass a constant to use the same value
112 // along the whole path.
113 pathnormali = this.project_to_orthogonal(shapenormali, pathnormali);
114
115 var shapei = shape_fun(i, path[i], shapenormali, pathnormali);
116
117 // loop is shapei in 3d with (0,0) at path[i], shape's
118 // z axis in the direction of shapenormali, and shape's
119 // x axis in the direction of pathnormali. We tack
120 // [1,0,0] onto the end as a hack to see where it ends
121 // up after the first rotation. This is removed later.
122 var loop = shapei.concat([[1,0,0]]);
123
124 // This is done in three steps:
125 // 1. Rotate shape out of the xy plane so that [0,0,1]
126 // becomes shapenormali. This puts the shape in
127 // the correct plane, but does not constrain its
128 // rotation about shapenormali.
129 loop = this.rotate_onto(loop, [0,0,1], shapenormali);
130 var shapex = loop.pop();
131
132 // 2. Rotate around shapenormali so that [1,0,0]
133 // becomes pathnormali.
134 loop = this.rotate_onto(loop, shapex, pathnormali);
135
136 // (This would probably be faster and more numerically stable
137 // if the two rotations were applied as one combined operation
138 // rather than separate steps.)
139
140 // 3. Translate to path[i].
141 loop = this.translate(loop, path[i]);
142
143 if (i == 0) {
144 result.first_loop = loop;
145 } else {
146 result.points = result.points.concat(nt3d.closed_quadstrip(nt3d.zip(loop, prev_loop)));
147 }
148 prev_loop = loop;
149 }
150 result.last_loop = prev_loop;
151 return result;
152 },
153 zip: function(a, b) {
154 var result = [];
155 if (a.length != b.length) {
156 alert("Zip over different-sized inputs");
157 }
158 for (var i = 0; i < a.length; i++) {
159 result.push(a[i], b[i]);
160 }
161 return result;
162 },
163 magnitude: function(a) {
164 return Math.sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]);
165 },
166 unit: function(a) {
167 return this.scale(a, 1 / this.magnitude(a));
168 },
169 sub: function(a, b) {
170 return [a[0] - b[0],
171 a[1] - b[1],
172 a[2] - b[2]];
173 },
174 neg: function(a) {
175 return [-a[0], -a[1], -a[2]];
176 },
177 dot: function(a, b) {
178 return a[0]*b[0] + a[1]*b[1] + a[2]*b[2];
179 },
180 scale: function(v, s) { // Scale vector v by scalar s
181 return [s*v[0], s*v[1], s*v[2]];
182 },
183 cross: function(a, b) {
184 return [a[1]*b[2] - a[2]*b[1],
185 a[2]*b[0] - a[0]*b[2],
186 a[0]*b[1] - a[1]*b[0]];
187 },
188 normal: function(a, b, c) {
189 return this.cross(this.sub(a, b), this.sub(b, c));
190 },
191 project: function(a, b) { // Project b onto a
192 var a_magnitude = this.magnitude(a);
193 return this.scale(a, this.dot(a, b) / a_magnitude * a_magnitude);
194 },
195 project_to_orthogonal: function(a, b) {
196 // The nearest thing to b that is orthogonal to a
197 return this.sub(b, this.project(a, b));
198 },
199 translate: function(points, offset) {
200 var translated = [];
201 for (var i = 0; i < points.length; i++) {
202 translated[i] = [points[i][0] + offset[0],
203 points[i][1] + offset[1],
204 points[i][2] + offset[2]];
205 }
206 return translated;
207 },
208 angle_between: function(a, b) { // a and b must be unit vectors
209 return Math.acos(this.dot(a, b));
210 },
211 rotate_about_origin: function(points, axis, angle) { // axis must be a unit vector
212 // From http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/
213 var cosangle = Math.cos(angle);
214 var sinangle = Math.sin(angle);
215 var rotated = [];
216 for (var i = 0; i < points.length; i++) {
217 var p = points[i];
218 var tmp = this.dot(p, axis) * (1 - cosangle);
219 rotated[i] = [
220 axis[0]*tmp + p[0]*cosangle + (-axis[2]*p[1] + axis[1]*p[2])*sinangle,
221 axis[1]*tmp + p[1]*cosangle + ( axis[2]*p[0] - axis[0]*p[2])*sinangle,
222 axis[2]*tmp + p[2]*cosangle + (-axis[1]*p[0] + axis[0]*p[1])*sinangle];
223 }
224 return rotated;
225 },
226 rotate_onto: function(points, a, b) {
227 // Rotate points such that a (in points-space) maps onto b
228 // by crossing a and b to get a rotation axis and using
229 // angle_between to get a rotation angle.
230 var angle = this.angle_between(this.unit(a), this.unit(b));
231 if (Math.abs(angle) < 1e-15) {
232 // No siginificant rotation to perform. Bail to avoid
233 // NaNs and numerical error
234 return points;
235 }
236 var axis = this.unit(this.cross(a, b));
237 return this.rotate_about_origin(points, axis, angle);
238 },
239 rotate: function(points, center, axis, angle) { // axis must be a unit vector
240 return this.translate(
241 this.rotate_about_origin(
242 this.translate(points, this.neg(center)),
243 axis,
244 angle),
245 center);
246 },
247 go: function() {
248 // Remove any previous download links
249 var old_download_link = document.getElementById("nt3d_download");
250 if (old_download_link) {
251 old_download_link.parentNode.removeChild(old_download_link);
252 }
253
254 // Continue in a callback, so that there's not a stale download
255 // link hanging around while we process.
256 setTimeout(function(the_this) { (function() {
257
258 // Get params from form
259 var params = [];
260 for (var i = 0; i < this.user_params.length; i++) {
261 var as_string = this.form.elements["param"+i].value;
262 var as_num = +as_string;
263 params[i] = isNaN(as_num) ? as_string : as_num;
264 }
265
266 // Run user_function
267 this.points = this.user_function.apply(null, params);
268 if (this.points.length % 3 != 0) {
269 alert("Points list length not divisble by 3!");
270 }
271 var n = this.points.length / 3;
272
273 // Make STL
274 this.stl = "solid " + this.user_function.name + "\n";
275 for (var i = 0; i < n; i++) {
276 var a = this.points[i*3+0];
277 var b = this.points[i*3+1];
278 var c = this.points[i*3+2];
279 var normal = this.normal(a, b, c);
280 this.stl += "facet normal " + normal[0] + " " + normal[1] + " " + normal[2] + "\n" +
281 "outer loop\n" +
282 "vertex " + a[0] + " " + a[1] + " " + a[2] + "\n"+
283 "vertex " + b[0] + " " + b[1] + " " + b[2] + "\n"+
284 "vertex " + c[0] + " " + c[1] + " " + c[2] + "\n"+
285 "endloop\n" +
286 "endfacet\n";
287 }
288 this.stl += "endsolid " + this.user_function.name + "\n";
289
290
291 // Offer result as download
292 var download_link = document.createElement("a");
293 download_link.appendChild(document.createTextNode("Download!"));
294 download_link.setAttribute("id", "nt3d_download");
295 download_link.setAttribute("style", "background-color: blue");
296 download_link.setAttribute("download", this.user_function.name + ".stl");
297 download_link.setAttribute("href", "data:application/sla," + encodeURIComponent(this.stl));
298 this.ui.appendChild(download_link);
299 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);
300
301 }).call(the_this); }, 0, this); // (We were in a callback this whole time, remember?)
302 },
303 framework: function (f, params) {
304 this.user_function = f;
305 this.user_params = params;
306
307 // Make the UI
308 this.ui = document.getElementById("nt3dui");
309 if (!this.ui) {
310 this.ui = document.createElement("div");
311 this.ui.setAttribute("id", "nt3dui");
312 document.body.appendChild(this.ui);
313 }
314 this.form = document.createElement("form");
315 this.form.setAttribute("onsubmit", "nt3d.go(); return false");
316 this.ui.appendChild(this.form);
317 var table = document.createElement("table");
318 this.form.appendChild(table);
319 var tr = document.createElement("tr");
320 table.appendChild(tr);
321 var th = document.createElement("th");
322 th.appendChild(document.createTextNode("Variable"));
323 tr.appendChild(th);
324 th = document.createElement("th");
325 th.appendChild(document.createTextNode("Value"));
326 tr.appendChild(th);
327 for (var i = 0; i < params.length; i++) {
328 tr = document.createElement("tr");
329 table.appendChild(tr);
330 var td = document.createElement("td");
331 td.appendChild(document.createTextNode(params[i][0]));
332 tr.appendChild(td);
333 td = document.createElement("td");
334 var input = document.createElement("input");
335 input.setAttribute("name", "param" + i);
336 input.setAttribute("value", params[i][1]);
337 td.appendChild(input);
338 tr.appendChild(td);
339 }
340 var go = document.createElement("input");
341 go.setAttribute("type", "button");
342 go.setAttribute("value", "Go!");
343 go.setAttribute("onclick", "nt3d.go()");
344 this.form.appendChild(go);
345 }
346 };