/* nt3d - Javascript library for doing some 3D stuff. * Copyright (C) 2012 Scott Worley * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ nt3d = { triangle: function(a, b, c) { return [a, b, c]; }, quad: function(a, b, c, d) { return this.triangle(a, b, c).concat( this.triangle(c, d, a)); }, trianglefan: function(fan) { var result = []; for (var i = 2; i < fan.length; i++) { result.push(fan[0], fan[i-1], fan[i]); } return result; }, closed_trianglefan: function(fan) { return this.trianglefan(fan.concat([fan[1]])); }, quadstrip: function(strip) { if (strip.length % 2 != 0) { alert("quadstrip length not divisble by 2!"); } var result = []; for (var i = 2; i < strip.length; i += 2) { result = result.concat(this.quad(strip[i-2], strip[i-1], strip[i+1], strip[i])); } return result; }, closed_quadstrip: function(strip) { return this.quadstrip(strip.concat([strip[0], strip[1]])); }, circle: function(r, n) { var points = []; for (var i = 0; i < n; i++) { points.push([r*Math.cos(2*Math.PI*i/n), r*Math.sin(2*Math.PI*i/n), 0]); } return points; }, cone: function(base_center, apex, radius, steps) { var base = this.circle(radius, steps); base = this.rotate_onto(base, [0,0,1], this.sub(apex, base_center)); base = this.translate(base, base_center); return this.closed_trianglefan([apex].concat(base)).concat( this.trianglefan(base.reverse())); }, sphere: function(center, radius, latitude_steps, longitude_steps) { return this.oriented_sphere(center, radius, [0,0,1], [1,0,0], latitude_steps, longitude_steps); }, oriented_sphere: function(center, radius, north, greenwich, latitude_steps, longitude_steps) { var unit_north = this.unit(north); var north_pole = this.translate_point(this.scale(unit_north, radius), center); var south_pole = this.translate_point(this.scale(unit_north, -radius), center); return this.spheroid(north_pole, south_pole, radius, greenwich, latitude_steps, longitude_steps); }, spheroid: function(north_pole, south_pole, radius, greenwich, latitude_steps, longitude_steps) { var delta = this.sub(north_pole, south_pole); var path = []; for (var i = 0; i < latitude_steps-1; i++) { path.push(this.translate_point(south_pole, this.scale(delta, (1-Math.cos(Math.PI*i/(latitude_steps-1)))/2))); } path.push(north_pole); function shape(i) { return nt3d.circle(radius*Math.sin(Math.PI*i/(latitude_steps-1)), longitude_steps); } return this.extrude(path, shape, delta, greenwich); }, shapenormals_from_closed_path: function(path) { return function(i) { var prev = (i == 0) ? path.length-1 : i-1; var next = (i == path.length-1) ? 0 : i+1; return nt3d.sub(path[next], path[prev]); }; }, shapenormals_from_path_and_extra_points: function(path, first_point, last_point) { return function(i) { var prev = (i == 0) ? first_point : path[i-1]; var next = (i == path.length-1) ? last_point : path[i+1]; return nt3d.sub(next, prev); }; }, shapenormals_from_path_and_first_and_last_normals: function(path, first_normal, last_normal) { return function(i) { if (i == 0) { return first_normal; } if (i == path.length-1) { return last_normal; } return nt3d.sub(path[i+1], path[i-1]); }; }, pathnormals_from_point: function(path, p) { // Use this with any point that is not on any path tangent line var pathnormals = []; for (var i = 0; i < path.length; i++) { pathnormals.push(this.sub(path[i], p)); } return pathnormals; }, to_function: function(thing, make_indexer) { // If thing is a point, just yield thing every time. // If thing is a list of points && make_indexer, index into thing. // If thing is already a function, just return it. if (({}).toString.call(thing) === "[object Function]") { return thing; // Already a function } if (make_indexer && Array.isArray(thing[0])) { // Looks like a list of points. return function(i) { return thing[i]; } } return function() { return thing; } }, extrude: function(path, shape, shapenormals, pathnormals) { var guts_result = this._extrude_guts(path, shape, shapenormals, pathnormals); // Add the end-caps // XXX: This doesn't work if shape is not convex return guts_result.points.concat( this.trianglefan(guts_result.first_loop.reverse()), this.trianglefan(guts_result.last_loop)); }, closed_extrude: function(path, shape, shapenormals, pathnormals) { var guts_result = this._extrude_guts(path, shape, shapenormals, pathnormals); // Stitch the ends together return guts_result.points.concat( this.closed_quadstrip(this.zip(guts_result.first_loop, guts_result.last_loop))); }, _extrude_guts: function(path, shape, shapenormals, pathnormals) { var shape_fun = this.to_function(shape, false); var shapenormal_fun = this.to_function(shapenormals, true); var pathnormal_fun = this.to_function(pathnormals, true); var result = { points: [] }; var prev_loop; for (var i = 0; i < path.length; i++) { var shapenormali = shapenormal_fun(i, path[i]); var pathnormali = pathnormal_fun(i, path[i], shapenormali); // Fix pathnormali to be perfectly perpendicular to // shapenormali. pathnormali must be perpendicular to // shapenormali or the second rotation will take loop // back out of the shapenormali plane that the first // rotation so carefully placed it in. But, letting // callers be sloppy with the pathnormals can greatly // simplify generating them -- so much so that you can // often just pass a constant to use the same value // along the whole path. pathnormali = this.project_to_orthogonal(shapenormali, pathnormali); var shapei = shape_fun(i, path[i], shapenormali, pathnormali); // loop is shapei in 3d with (0,0) at path[i], shape's // z axis in the direction of shapenormali, and shape's // x axis in the direction of pathnormali. We tack // [1,0,0] onto the end as a hack to see where it ends // up after the first rotation. This is removed later. var loop = shapei.concat([[1,0,0]]); // This is done in three steps: // 1. Rotate shape out of the xy plane so that [0,0,1] // becomes shapenormali. This puts the shape in // the correct plane, but does not constrain its // rotation about shapenormali. loop = this.rotate_onto(loop, [0,0,1], shapenormali); var shapex = loop.pop(); // 2. Rotate around shapenormali so that [1,0,0] // becomes pathnormali. if (!this.opposite(shapex, pathnormali)) { loop = this.rotate_onto(loop, shapex, pathnormali); } else { // Rare edge case: When shapex and pathnormali are // opposite, rotate_onto cannot cross them to get // an axis of rotation. In this case, we (extrude) // already know what to do -- just rotate PI around // shapenormali! loop = this.rotate_about_origin(loop, shapenormali, Math.PI); } // (This would probably be faster and more numerically stable // if the two rotations were applied as one combined operation // rather than separate steps.) // 3. Translate to path[i]. loop = this.translate(loop, path[i]); if (i == 0) { result.first_loop = loop; } else { result.points = result.points.concat(this.closed_quadstrip(this.zip(loop, prev_loop))); } prev_loop = loop; } result.last_loop = prev_loop; return result; }, zip: function(a, b) { var result = []; if (a.length != b.length) { alert("Zip over different-sized inputs"); } for (var i = 0; i < a.length; i++) { result.push(a[i], b[i]); } return result; }, magnitude: function(a) { return Math.sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]); }, unit: function(a) { return this.scale(a, 1 / this.magnitude(a)); }, sub: function(a, b) { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; }, neg: function(a) { return [-a[0], -a[1], -a[2]]; }, dot: function(a, b) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; }, scale: function(v, s) { // Scale vector v by scalar s return [s*v[0], s*v[1], s*v[2]]; }, cross: function(a, b) { return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]; }, normal: function(a, b, c) { return this.cross(this.sub(a, b), this.sub(b, c)); }, project: function(a, b) { // Project b onto a var a_magnitude = this.magnitude(a); return this.scale(a, this.dot(a, b) / (a_magnitude * a_magnitude)); }, project_to_orthogonal: function(a, b) { // The nearest thing to b that is orthogonal to a return this.sub(b, this.project(a, b)); }, translate: function(points, offset) { var translated = []; for (var i = 0; i < points.length; i++) { translated[i] = this.translate_point(points[i], offset); } return translated; }, translate_point: function(point, offset) { return [point[0] + offset[0], point[1] + offset[1], point[2] + offset[2]]; }, angle_between: function(a, b) { // a and b must be unit vectors var the_dot = this.dot(a, b); if (the_dot <= -1) { return Math.PI; } if (the_dot >= 1) { return 0; } return Math.acos(the_dot); }, rotate_about_origin: function(points, axis, angle) { // axis must be a unit vector // From http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ var cosangle = Math.cos(angle); var sinangle = Math.sin(angle); var rotated = []; for (var i = 0; i < points.length; i++) { var p = points[i]; var tmp = this.dot(p, axis) * (1 - cosangle); rotated[i] = [ axis[0]*tmp + p[0]*cosangle + (-axis[2]*p[1] + axis[1]*p[2])*sinangle, axis[1]*tmp + p[1]*cosangle + ( axis[2]*p[0] - axis[0]*p[2])*sinangle, axis[2]*tmp + p[2]*cosangle + (-axis[1]*p[0] + axis[0]*p[1])*sinangle]; } return rotated; }, angle_epsilon: 1e-7, opposite: function(a, b) { // Do a and b point in exactly opposite directions? return Math.abs(this.angle_between(this.unit(a), this.unit(b)) - Math.PI) < this.angle_epsilon; }, rotate_onto: function(points, a, b) { // Rotate points such that a (in points-space) maps onto b // by crossing a and b to get a rotation axis and using // angle_between to get a rotation angle. var angle = this.angle_between(this.unit(a), this.unit(b)); var abs_angle = Math.abs(angle); if (Math.abs(angle) < this.angle_epsilon) { // No significant rotation to perform. Bail to avoid // NaNs and numerical error return points; } var axis; if (Math.abs(abs_angle - Math.PI) < this.angle_epsilon) { // a and b point in opposite directions, so // we cannot cross them. So just pick something. // If the caller wishes to avoid this behaviour, // they should check with this.opposite() first. axis = this.project_to_orthogonal(a, [1,0,0]); console.log("rotate_onto: a and b are opposite! If you carefully chose them to meet some other constraint, you will be sad! Arbitrarily using axis [1,0,0] ->", axis); if (this.magnitude(axis) < this.angle_epsilon) { // Oh, double bad luck! Our arbitrary choice // lines up too! A second, orthogonal arbitrary // choice is now guaranteed to succeed. axis = this.project_to_orthogonal(a, [0,1,0]); console.log("rotate_onto: Double bad luck! Arbitrarily using axis [0,1,0] ->", axis); } } else { axis = this.unit(this.cross(a, b)); } return this.rotate_about_origin(points, axis, angle); }, rotate: function(points, center, axis, angle) { // axis must be a unit vector return this.translate( this.rotate_about_origin( this.translate(points, this.neg(center)), axis, angle), center); }, point_equal: function(a, b, epsilon) { return Math.abs(a[0] - b[0]) < epsilon && Math.abs(a[1] - b[1]) < epsilon && Math.abs(a[2] - b[2]) < epsilon; }, degenerate_face_epsilon: 1e-10, is_degenerate: function(a, b, c) { return this.point_equal(a, b, this.degenerate_face_epsilon) || this.point_equal(b, c, this.degenerate_face_epsilon) || this.point_equal(c, a, this.degenerate_face_epsilon); }, validate: function(points) { // Do a little validation if (points.length % 3 != 0) { alert("Points list length not divisble by 3!"); } var nan_count = 0; var nan_point_count = 0; var nan_face_count = 0; for (var i = 0; i < points.length/3; i++) { var nan_in_face = false; for (var j = 0; j < 3; j++) { var nan_in_point = false; for (var k = 0; k < 3; k++) { if (isNaN(points[i*3+j][k])) { nan_count++; nan_in_point = true; nan_in_face = true; } } if (nan_in_point) nan_point_count ++; } if (nan_in_face) nan_face_count ++; } if (nan_count != 0) { alert(nan_count + " NaNs in " + nan_point_count + " points in " + nan_face_count + " faces (" + (100 * nan_face_count / (points.length/3)) + "% of faces)."); } }, remove_degenerate_faces: function(points) { // Note: This modifies points var degenerate_face_count = 0; for (var i = 0; i < points.length/3; i++) { if (this.is_degenerate(points[i*3+0], points[i*3+1], points[i*3+2])) { points.splice(i*3, 3); i--; degenerate_face_count ++; } } if (degenerate_face_count != 0) { console.log("Removed " + degenerate_face_count + " degenerate faces"); } return points; }, to_stl: function(points, name) { var stl = "solid " + name + "\n"; for (var i = 0; i < points.length/3; i++) { var a = points[i*3+0]; var b = points[i*3+1]; var c = points[i*3+2]; var normal = this.normal(a, b, c); stl += "facet normal " + normal[0] + " " + normal[1] + " " + normal[2] + "\n" + "outer loop\n" + "vertex " + a[0] + " " + a[1] + " " + a[2] + "\n"+ "vertex " + b[0] + " " + b[1] + " " + b[2] + "\n"+ "vertex " + c[0] + " " + c[1] + " " + c[2] + "\n"+ "endloop\n" + "endfacet\n"; } stl += "endsolid " + name + "\n"; return stl; }, go: function() { // Remove any previous download links var old_download_link = document.getElementById("nt3d_download"); if (old_download_link) { old_download_link.parentNode.removeChild(old_download_link); } // Continue in a callback, so that there's not a stale download // link hanging around while we process. setTimeout(function() { // Get params from form var params = {}; for (var i = 0; i < this.user_params.length; i++) { var as_string = this.form.elements["param"+i].value; var as_num = +as_string; params[this.user_params[i][0]] = isNaN(as_num) ? as_string : as_num; } this.points = this.user_function.call(null, params); this.validate(this.points); this.remove_degenerate_faces(this.points); this.stl = this.to_stl(this.points, this.user_function.name); // Offer result as download var download_link = document.createElement("a"); download_link.appendChild(document.createTextNode("Download!")); download_link.setAttribute("id", "nt3d_download"); download_link.setAttribute("style", "background-color: blue"); download_link.setAttribute("download", this.user_function.name + ".stl"); download_link.setAttribute("href", "data:application/sla," + encodeURIComponent(this.stl)); this.ui.appendChild(download_link); 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); }.bind(this), 0); // (We were in a callback this whole time, remember?) }, framework: function (f, params) { this.user_function = f; this.user_params = params; // Make the UI this.ui = document.getElementById("nt3dui"); if (!this.ui) { this.ui = document.createElement("div"); this.ui.setAttribute("id", "nt3dui"); document.body.appendChild(this.ui); } this.form = document.createElement("form"); this.form.setAttribute("onsubmit", "nt3d.go(); return false"); this.ui.appendChild(this.form); var table = document.createElement("table"); this.form.appendChild(table); var tr = document.createElement("tr"); table.appendChild(tr); var th = document.createElement("th"); th.appendChild(document.createTextNode("Variable")); tr.appendChild(th); th = document.createElement("th"); th.appendChild(document.createTextNode("Value")); tr.appendChild(th); for (var i = 0; i < params.length; i++) { tr = document.createElement("tr"); table.appendChild(tr); var td = document.createElement("td"); var description; if (params[i].length > 2) { description = params[i][2]; } else { description = params[i][0]; description = description[0].toUpperCase() + description.substr(1); description = description.replace(/_(.)/g, function(_, c) { return " " + c.toUpperCase(); }); description = description.replace("Num ", "Number of "); } td.appendChild(document.createTextNode(description)); tr.appendChild(td); td = document.createElement("td"); var input = document.createElement("input"); input.setAttribute("name", "param" + i); input.setAttribute("value", params[i][1]); td.appendChild(input); tr.appendChild(td); } var go = document.createElement("input"); go.setAttribute("type", "button"); go.setAttribute("value", "Go!"); go.setAttribute("onclick", "nt3d.go()"); this.form.appendChild(go); } };