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