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