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