├── .gitignore ├── src ├── csgjs │ ├── constants.h │ ├── util.h │ ├── math │ │ ├── Line3.h │ │ ├── Vertex3.h │ │ ├── Line3.cpp │ │ ├── Matrix4x4.h │ │ ├── Vector3.h │ │ ├── Polygon3.h │ │ ├── HashKeys.h │ │ ├── Plane.h │ │ ├── Vector3.cpp │ │ ├── HashKeys.cpp │ │ ├── Matrix4x4.cpp │ │ └── Polygon3.cpp │ ├── README.md │ ├── CSG.h │ ├── Trees.h │ ├── util.cpp │ ├── Trees.cpp │ └── CSG.cpp ├── stl_empty.cpp ├── stl_volume.cpp ├── stl_area.cpp ├── stl_bbox.cpp ├── stl_spreadsheet.cpp ├── stl_decimate.cpp ├── stl_count.cpp ├── stl_ascii.cpp ├── stl_binary.cpp ├── stl_header.cpp ├── stl_bcylinder.cpp ├── stl_merge.cpp ├── stl_boolean.cpp ├── stl_cylinder.cpp ├── stl_cube.cpp ├── stl_flat.cpp ├── stl_torus.cpp ├── stl_zero.cpp ├── stl_sphere.cpp ├── stl_borders.cpp ├── stl_cone.cpp ├── stl_normals.cpp ├── stl_cylinders.cpp ├── stl_convex.cpp └── stl_transform.cpp ├── CHANGES ├── Makefile └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | bin/ 3 | man/ 4 | -------------------------------------------------------------------------------- /src/csgjs/constants.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_CONSTANTS__ 2 | #define __CSGJS_CONSTANTS__ 3 | 4 | typedef double csgjs_real; 5 | 6 | //#define CSGJS_DEBUG 7 | const csgjs_real EPS = .00001; 8 | const csgjs_real NEG_EPS = -EPS; 9 | const csgjs_real EPS_SQUARED = EPS*EPS; 10 | 11 | #endif 12 | -------------------------------------------------------------------------------- /src/csgjs/util.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_UTIL__ 2 | #define __CSGJS_UTIL__ 3 | 4 | #include "math/Polygon3.h" 5 | #include 6 | #include 7 | 8 | namespace csgjs { 9 | 10 | std::vector ReadSTLFile(const char* filename); 11 | void WriteSTLFile(const char* filename, const std::vector polygons); 12 | 13 | unsigned long xorshf96(void); 14 | int fastRandom(int max); 15 | } 16 | 17 | #endif 18 | -------------------------------------------------------------------------------- /CHANGES: -------------------------------------------------------------------------------- 1 | * v1.2 Updated help text of stl_boolean. Added more commands. 2 | * stl_area 3 | * stl_ascii 4 | * stl_bcylinder 5 | * stl_binary 6 | * stl_cylinders 7 | * stl_decimate 8 | * stl_flat 9 | * stl_volume 10 | * stl_zero 11 | * v1.1 Fixed Makefile to properly install stl_boolean 12 | * v1.0 release with the following commands 13 | * stl_empty 14 | * stl_cube 15 | * stl_sphere 16 | * stl_cylinder 17 | * stl_cone 18 | * stl_torus 19 | * stl_threads 20 | * stl_header 21 | * stl_count 22 | * stl_normals 23 | * stl_bbox 24 | * stl_convex 25 | * stl_borders 26 | * stl_spreadsheet 27 | * stl_merge 28 | * stl_transform 29 | * stl_boolean 30 | -------------------------------------------------------------------------------- /src/csgjs/math/Line3.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_LINE3__ 2 | #define __CSGJS_LINE3__ 3 | 4 | #include "csgjs/math/Vector3.h" 5 | #include 6 | 7 | namespace csgjs { 8 | 9 | struct Line { 10 | Vector3 direction; 11 | Vector3 point; 12 | 13 | Line(); 14 | Line(const Vector3 &p, const Vector3 &d); 15 | 16 | Vector3 closestPointOnLine(const Vector3 &p) const; 17 | csgjs_real distanceToPoint(const Vector3 &p) const; 18 | csgjs_real distanceToPointOnLine(const Vector3 &p) const; 19 | bool operator==(const Line &l) const; 20 | 21 | static Line fromPoints(const Vector3 &p1, const Vector3 &p2); 22 | }; 23 | 24 | 25 | std::ostream& operator<<(std::ostream& os, const Line &line); 26 | 27 | } 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /src/csgjs/README.md: -------------------------------------------------------------------------------- 1 | C++ port of CSG.js 2 | ================== 3 | This a C++ port of CSG.js used in OpenJSCAD (https://github.com/jscad/csg.js). OpenJSCAD's CSG.js has significant performance 4 | improvements over the original CSG.js (https://github.com/evanw/csg.js/), which was ported to C++ here (https://github.com/dabroz/csgjs-cpp). 5 | The speed of OpenJSCAD's CSG.js implmented in JavaScript is faster than the original C++ port, so the idea is 6 | to get those gains and more by implementing OpenJSCAD's CSG.js in C++. 7 | 8 | So far just the bare minimum is implemented, with the ability to do CSG operations without the retessellation feature of CSG.js (reduces 9 | the number of polygons in the end result). The stl_boolean command leverages this implementation to be able to do CSG operations on 10 | two STL files. Without the overhead of JavaScript, a single operation runs very quickly. 11 | -------------------------------------------------------------------------------- /src/csgjs/math/Vertex3.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_VERTEX3__ 2 | #define __CSGJS_VERTEX3__ 3 | 4 | #include "csgjs/constants.h" 5 | #include "csgjs/math/Vector3.h" 6 | #include 7 | 8 | namespace csgjs { 9 | struct Vertex { 10 | Vector3 pos; 11 | 12 | Vertex() : pos() { 13 | } 14 | 15 | Vertex(const Vector3 &p) : pos(p) {} 16 | 17 | // if vertex had normal data or something like that, flip it here 18 | Vertex flipped() const { 19 | return *this; 20 | } 21 | 22 | Vertex interpolate(Vertex other, csgjs_real t) const { 23 | return Vertex(pos.lerp(other.pos, t)); 24 | } 25 | 26 | Vertex transform(const Matrix4x4 &m) const { 27 | return Vertex(pos.transform(m)); 28 | } 29 | 30 | 31 | }; 32 | 33 | inline std::ostream& operator<<(std::ostream& os, const Vertex &v) { 34 | os << "pos: " << v.pos; 35 | return os; 36 | } 37 | } 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /src/csgjs/math/Line3.cpp: -------------------------------------------------------------------------------- 1 | #include "csgjs/math/Line3.h" 2 | #include 3 | 4 | namespace csgjs { 5 | Line::Line() : point(Vector3(0,0,0)), direction(Vector3(0,0,0)) { // point and direction 6 | } 7 | 8 | Line::Line(const Vector3 &p, const Vector3 &d) : point(p), direction(d) { // point and direction 9 | } 10 | 11 | csgjs_real Line::distanceToPointOnLine(const Vector3 &p) const { 12 | return (p-point).dot(direction); 13 | } 14 | 15 | Vector3 Line::closestPointOnLine(const Vector3 &p) const { 16 | return point+direction*(p-point).dot(direction); 17 | } 18 | 19 | csgjs_real Line::distanceToPoint(const Vector3 &p) const { 20 | return (p-closestPointOnLine(p)).length(); 21 | } 22 | 23 | bool Line::operator==(const Line &l) const { 24 | return (l.direction-direction).length() <= EPS && (l.point-point).length() <= EPS; 25 | } 26 | 27 | Line Line::fromPoints(const Vector3 &p1, const Vector3 &p2) { 28 | return Line(p1, p2-p1); 29 | } 30 | 31 | std::ostream& operator<<(std::ostream& os, const Line &line) { 32 | os << "Line - point: " << line.point << ", direction: " << line.direction; 33 | return os; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/csgjs/CSG.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS__CSG__ 2 | #define __CSGJS__CSG__ 3 | 4 | #include "csgjs/math/Polygon3.h" 5 | #include "csgjs/math/Matrix4x4.h" 6 | #include 7 | #include 8 | #include "csgjs/math/HashKeys.h" 9 | #include 10 | 11 | namespace csgjs { 12 | 13 | class CSG { 14 | private: 15 | std::vector _polygons; 16 | bool _isManifold; 17 | 18 | mutable bool _boundingBoxCacheValid; 19 | mutable std::pair _boundingBoxCache; 20 | 21 | CSG unionForNonIntersecting(const CSG &csg) const; 22 | 23 | void findUnmatchedEdges(std::unordered_map &u); 24 | 25 | public: 26 | CSG(); 27 | CSG(const std::vector &p); 28 | CSG(std::vector &&p); 29 | 30 | std::vector toPolygons() const; 31 | CSG csgUnion(const CSG &csg) const; 32 | CSG csgIntersect(const CSG &csg) const; 33 | CSG csgSubtract(const CSG &csg) const; 34 | bool mayOverlap(const CSG &csg) const; 35 | std::pair getBounds() const; 36 | 37 | CSG transform(const Matrix4x4 &m); 38 | 39 | void canonicalize(); 40 | void makeManifold(); 41 | 42 | friend std::ostream& operator<<(std::ostream& os, const CSG &csg); 43 | }; 44 | 45 | } 46 | #endif 47 | -------------------------------------------------------------------------------- /src/csgjs/math/Matrix4x4.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_MATRIX4x4__ 2 | #define __CSGJS_MATRIX4x4__ 3 | 4 | #include "csgjs/constants.h" 5 | 6 | // row major implmentation of 4x4 matrix 7 | // i.e. values stored as [ a b c d e f g h i j k l m n o p ] 8 | // represent: 9 | // | a b c d | 10 | // | e f g h | 11 | // | i j k l | 12 | // | m n o p | 13 | // 14 | // This means that you left multiply to transform a point/vector: 15 | // 16 | // [ x y z 1 ] * | xx xy xz 0 | = [ x*xx+y*yx+z*zx+tx, x*xy+y*yy+z*zy+ty, x*xz+y*yz+z*zz+tz ] 17 | // | yx yy yz 0 | 18 | // | zx zy zz 0 | 19 | // | tx ty tz 1 | 20 | // 21 | 22 | namespace csgjs { 23 | 24 | struct Vector3; 25 | 26 | struct Matrix4x4 { 27 | csgjs_real m[16]; 28 | 29 | Matrix4x4(); 30 | Matrix4x4(csgjs_real m00, csgjs_real m01, csgjs_real m02, csgjs_real m03, csgjs_real m10, csgjs_real m11, csgjs_real m12, csgjs_real m13, csgjs_real m20, csgjs_real m21, csgjs_real m22, csgjs_real m23, csgjs_real m30, csgjs_real m31, csgjs_real m32, csgjs_real m33); 31 | 32 | bool isMirroring() const; 33 | 34 | Matrix4x4 operator+(const Matrix4x4 &mat) const; 35 | Matrix4x4 operator-(const Matrix4x4 &mat) const; 36 | Matrix4x4 operator*(const Matrix4x4 &mat) const; 37 | static Matrix4x4 translate(csgjs_real x, csgjs_real y, csgjs_real z); 38 | static Matrix4x4 rotate(const Vector3 &axis, csgjs_real angle); 39 | }; 40 | 41 | } 42 | 43 | #endif 44 | -------------------------------------------------------------------------------- /src/csgjs/math/Vector3.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_VECTOR3__ 2 | #define __CSGJS_VECTOR3__ 3 | 4 | #include 5 | #include 6 | #include 7 | #include "csgjs/math/Matrix4x4.h" 8 | 9 | namespace csgjs { 10 | 11 | struct Vector3 { 12 | csgjs_real x; 13 | csgjs_real y; 14 | csgjs_real z; 15 | 16 | Vector3(); 17 | Vector3(csgjs_real xx, csgjs_real yy, csgjs_real zz); 18 | 19 | Vector3 operator-() const; 20 | Vector3 operator+(const Vector3 &b) const; 21 | Vector3 operator-(const Vector3 &b) const; 22 | Vector3 operator*(const csgjs_real m) const; 23 | Vector3 operator/(const csgjs_real m) const; 24 | csgjs_real dot(const Vector3 &b) const; 25 | Vector3 lerp(const Vector3 &b, csgjs_real t) const; 26 | csgjs_real lengthSquared() const; 27 | csgjs_real length() const; 28 | Vector3 unit() const; 29 | Vector3 cross(const Vector3 &a) const; 30 | csgjs_real distanceTo(const Vector3 &a) const; 31 | csgjs_real distanceToSquared(const Vector3 &a) const; 32 | bool operator==(const Vector3 &a) const; 33 | Vector3 transform(const Matrix4x4 &m, csgjs_real w=1) const; 34 | Vector3 abs() const; 35 | Vector3 nonParallelVector() const; 36 | Vector3 min(const Vector3 &v) const; 37 | Vector3 max(const Vector3 &v) const; 38 | bool isZero() const; 39 | }; 40 | 41 | Vector3 operator*(const csgjs_real m, const Vector3 &v); 42 | std::ostream& operator<<(std::ostream& os, const Vector3 &v); 43 | } 44 | 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /src/csgjs/math/Polygon3.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_POLYGON3__ 2 | #define __CSGJS_POLYGON3__ 3 | 4 | #include "csgjs/math/Vector3.h" 5 | #include "csgjs/math/Vertex3.h" 6 | #include "csgjs/math/Plane.h" 7 | #include 8 | #include 9 | 10 | namespace csgjs { 11 | 12 | class Polygon { 13 | public: 14 | std::vector vertices; 15 | Plane plane; 16 | 17 | Polygon(std::vector &&v, const Plane &p); 18 | Polygon(const std::vector &v, const Plane &p); 19 | Polygon(const std::vector &v); 20 | Polygon(); 21 | 22 | bool checkIfDegenerateTriangle() const; // checks if polygon has 3 vertices and if they're a degenerate triangle 23 | bool checkIfConvex() const; 24 | std::pair boundingSphere() const; 25 | std::pair boundingBox() const; 26 | 27 | Polygon flipped() const; 28 | Polygon transform(const Matrix4x4 &m) const; 29 | 30 | static bool isConvexPoint(const Vector3 &prevpoint, const Vector3 &point, const Vector3 &nextpoint, const Vector3 normal); 31 | 32 | private: 33 | mutable bool _boundingSphereCacheValid; 34 | mutable std::pair _boundingSphereCache; 35 | 36 | mutable bool _boundingBoxCacheValid; 37 | mutable std::pair _boundingBoxCache; 38 | }; 39 | 40 | struct PolygonEdgeData { 41 | Polygon *polygon; 42 | 43 | Vector3 first; 44 | Vector3 second; 45 | 46 | PolygonEdgeData(); 47 | PolygonEdgeData(Polygon *p, const Vector3 &a, const Vector3 &b); 48 | }; 49 | 50 | 51 | std::ostream& operator<<(std::ostream& os, const Polygon &poly); 52 | std::ostream& operator<<(std::ostream& os, const std::pair &bounds); 53 | std::ostream& operator<<(std::ostream& os, const std::pair &bounds); 54 | 55 | std::ostream& operator<<(std::ostream& os, const std::vector &vertices); 56 | 57 | } 58 | 59 | #endif 60 | -------------------------------------------------------------------------------- /src/csgjs/math/HashKeys.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_HASHKEYS__ 2 | #define __CSGJS_HASHKEYS__ 3 | 4 | #include "csgjs/math/Line3.h" 5 | #include "csgjs/math/Plane.h" 6 | 7 | namespace csgjs { 8 | struct PlaneKey { 9 | std::size_t hash; 10 | Plane plane; 11 | 12 | PlaneKey(const Plane &p); 13 | bool operator==(const PlaneKey &k) const; 14 | }; 15 | 16 | struct LineKey { 17 | std::size_t hash; 18 | Line line; 19 | 20 | LineKey(const Line &l); 21 | bool operator==(const LineKey &l) const; 22 | }; 23 | 24 | struct EdgeKey { 25 | std::size_t hash; 26 | 27 | Vector3 first; 28 | Vector3 second; 29 | 30 | EdgeKey(const Vector3 &a, const Vector3 &b); 31 | bool operator==(const EdgeKey &k) const; 32 | EdgeKey reversed() const; 33 | }; 34 | 35 | struct VertexKey { 36 | std::size_t hash; 37 | 38 | Vector3 v; 39 | 40 | VertexKey(const Vector3 &a); 41 | bool operator==(const VertexKey &k) const; 42 | }; 43 | 44 | struct VertexKeyDist { 45 | VertexKey key; 46 | csgjs_real dist; 47 | 48 | VertexKeyDist(const VertexKey &a, csgjs_real b); 49 | 50 | bool operator<(const VertexKeyDist &k) const; 51 | bool operator==(const VertexKeyDist &k) const; 52 | }; 53 | } 54 | 55 | namespace std { 56 | template <> 57 | struct hash { 58 | std::size_t operator()(const csgjs::PlaneKey& l) const; 59 | }; 60 | 61 | template <> 62 | struct hash { 63 | std::size_t operator()(const csgjs::LineKey& l) const; 64 | }; 65 | 66 | template <> 67 | struct hash { 68 | std::size_t operator()(const csgjs::EdgeKey& e) const; 69 | }; 70 | 71 | template <> 72 | struct hash { 73 | std::size_t operator()(const csgjs::VertexKey& e) const; 74 | }; 75 | 76 | template <> 77 | struct hash { 78 | std::size_t operator()(const csgjs::VertexKeyDist& e) const; 79 | }; 80 | } 81 | 82 | #endif 83 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | prefix?=/usr/local 2 | target=$(DESTDIR)$(prefix) 3 | 4 | VERSION=1.2 5 | DOCS_DIR := man 6 | BIN_DIR := bin 7 | CMDS := $(addprefix $(BIN_DIR)/,stl_header stl_merge stl_transform stl_count stl_bbox stl_cube stl_sphere stl_cylinder stl_cylinders stl_cone stl_torus stl_empty stl_threads stl_normals stl_convex stl_borders stl_spreadsheet stl_area stl_volume stl_bcylinder stl_binary stl_ascii stl_zero) 8 | CSGJS_CMDS := $(addprefix $(BIN_DIR)/,stl_boolean stl_flat stl_decimate) 9 | 10 | ALL_CMDS := $(CSGJS_CMDS) $(CMDS) 11 | 12 | CC := g++ 13 | #FLAGS=-Og -g -std=c++11 14 | FLAGS=-O3 -std=c++11 15 | 16 | all: $(CMDS) $(CSGJS_CMDS) 17 | 18 | $(CMDS): $(BIN_DIR)/%: src/%.cpp src/stl_util.h 19 | $(CC) $(FLAGS) $(CPPFLAGS) $(CFLAGS) $(CXXFLAGS) $(LDFLAGS) $(OUTPUT_OPTION) $< 20 | 21 | $(CSGJS_CMDS): $(BIN_DIR)/%: src/%.cpp src/csgjs/*.cpp src/csgjs/math/*.cpp src/csgjs/math/*.h src/csgjs/*.h src/Simplify.h 22 | $(CC) $(FLAGS) $(CPPFLAGS) $(CFLAGS) $(CXXFLAGS) $(LDFLAGS) src/csgjs/*.cpp src/csgjs/math/*.cpp -Isrc $(OUTPUT_OPTION) $< 23 | 24 | $(CMDS): | $(BIN_DIR) 25 | 26 | $(BIN_DIR): 27 | mkdir $(BIN_DIR) 28 | 29 | clean: 30 | rm -rf $(BIN_DIR) 31 | 32 | $(DOCS_DIR): 33 | mkdir $(DOCS_DIR) 34 | 35 | docs: $(DOCS_DIR) $(CMDS) 36 | for cmd in $(ALL_CMDS); do \ 37 | help2man $$cmd --name="$$($$cmd --help 2>&1 | head --lines=1)" --no-discard-stderr --version-string="v$(VERSION)" --no-info > $(DOCS_DIR)/$$(basename $$cmd).1; \ 38 | done 39 | 40 | installDocs: docs 41 | install -d $(target)/share/man/man1 42 | for cmd in $(ALL_CMDS); do \ 43 | gzip -c -9 $(DOCS_DIR)/$$(basename $$cmd).1 > $(target)/share/man/man1/$$(basename $$cmd).1.gz; \ 44 | done 45 | 46 | uninstallDocs: 47 | for cmd in $(ALL_CMDS); do \ 48 | rm $(target)/share/man/man1/$$(basename $$cmd).1.gz; \ 49 | done 50 | 51 | install: all 52 | install -d $(target)/bin 53 | for cmd in $(ALL_CMDS); do \ 54 | install $$cmd $(target)/$$cmd; \ 55 | done 56 | 57 | uninstall: 58 | for cmd in $(ALL_CMDS); do \ 59 | rm $(target)/$$cmd; \ 60 | done 61 | -------------------------------------------------------------------------------- /src/stl_empty.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | void print_usage() { 32 | fprintf(stderr, "stl_empty outputs an empty STL file.\n\n"); 33 | fprintf(stderr, "usage: stl_empty \n"); 34 | fprintf(stderr, " Outputs a properly formatted, but empty stl file (just an 80 byte header and a 0 indicating no triangles). "); 35 | } 36 | 37 | int main(int argc, char** argv) { 38 | if(argc >= 2) { 39 | if(strcmp(argv[1], "--help") == 0) { 40 | print_usage(); 41 | exit(2); 42 | } 43 | } 44 | if(argc != 2) { 45 | print_usage(); 46 | exit(2); 47 | } 48 | 49 | char *file = argv[1]; 50 | FILE *outf; 51 | 52 | outf = fopen(file, "wb"); 53 | if(!outf) { 54 | fprintf(stderr, "Can't write to file: %s\n", file); 55 | exit(2); 56 | } 57 | 58 | char header[81] = {0}; 59 | snprintf(header, 81, "Empty STL file"); 60 | 61 | fwrite(header, 80, 1, outf); 62 | 63 | uint32_t num_tris = 0; 64 | 65 | fwrite(&num_tris, 4, 1, outf); 66 | 67 | fclose(outf); 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /src/stl_volume.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2020 by Allwine Designs, LLC (stl_cmd@allwinedesigns.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | void print_usage() { 30 | fprintf(stderr, "stl_volume prints the total volume of an STL file.\n\n"); 31 | fprintf(stderr, "usage: stl_volume \n"); 32 | fprintf(stderr, " Prints the total volume of an STL file.\n"); 33 | } 34 | 35 | int main(int argc, char** argv) { 36 | if(argc >= 2) { 37 | if(strcmp(argv[1], "--help") == 0) { 38 | print_usage(); 39 | exit(2); 40 | } 41 | } 42 | 43 | char *file = argv[1]; 44 | 45 | if(!is_valid_binary_stl(file)) { 46 | fprintf(stderr, "%s is not a binary stl file.\n", file); 47 | exit(2); 48 | } 49 | 50 | FILE *f; 51 | 52 | f = fopen(file, "rb"); 53 | if(!f) { 54 | fprintf(stderr, "Can't read file: %s\n", file); 55 | exit(2); 56 | } 57 | 58 | fseek(f, 80, SEEK_SET); 59 | 60 | uint32_t num_tris; 61 | size_t readBytes = fread(&num_tris, 4, 1, f); 62 | 63 | float volume = 0; 64 | 65 | for(int i = 0; i < num_tris; i++) { 66 | fseek(f, 12, SEEK_CUR); // normal 67 | 68 | vec pt1, pt2, pt3; 69 | 70 | readBytes = fread(&pt1, 1, 12,f); 71 | readBytes = fread(&pt2, 1, 12,f); 72 | readBytes = fread(&pt3, 1, 12,f); 73 | 74 | vec cross; 75 | 76 | vec_cross(&pt1, &pt2, &cross); 77 | 78 | volume += vec_dot(&cross, &pt3); 79 | 80 | fseek(f, 2, SEEK_CUR); 81 | } 82 | 83 | fclose(f); 84 | 85 | volume = fabs(volume/6.0f); 86 | 87 | printf("%f\n", volume); 88 | 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /src/stl_area.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2018 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | void print_usage() { 30 | fprintf(stderr, "stl_area prints surface area of an STL file.\n\n"); 31 | fprintf(stderr, "usage: stl_area \n"); 32 | fprintf(stderr, " Prints the total surface area of all the triangles in an STL file.\n"); 33 | } 34 | 35 | int main(int argc, char** argv) { 36 | if(argc >= 2) { 37 | if(strcmp(argv[1], "--help") == 0) { 38 | print_usage(); 39 | exit(2); 40 | } 41 | } 42 | 43 | char *file = argv[1]; 44 | 45 | if(!is_valid_binary_stl(file)) { 46 | fprintf(stderr, "%s is not a binary stl file.\n", file); 47 | exit(2); 48 | } 49 | 50 | FILE *f; 51 | 52 | f = fopen(file, "rb"); 53 | if(!f) { 54 | fprintf(stderr, "Can't read file: %s\n", file); 55 | exit(2); 56 | } 57 | 58 | fseek(f, 80, SEEK_SET); 59 | 60 | uint32_t num_tris; 61 | size_t readBytes = fread(&num_tris, 4, 1, f); 62 | 63 | float area = 0; 64 | 65 | for(int i = 0; i < num_tris; i++) { 66 | fseek(f, 12, SEEK_CUR); // normal 67 | 68 | vec pt1, pt2, pt3; 69 | 70 | readBytes = fread(&pt1, 1, 12,f); 71 | readBytes = fread(&pt2, 1, 12,f); 72 | readBytes = fread(&pt3, 1, 12,f); 73 | 74 | vec a,b; 75 | 76 | vec_sub(&pt2, &pt1, &a); 77 | vec_sub(&pt3, &pt1, &b); 78 | 79 | vec cross; 80 | 81 | vec_cross(&a, &b, &cross); 82 | 83 | float triArea = vec_magnitude(&cross)*.5; 84 | 85 | area += triArea; 86 | 87 | fseek(f, 2, SEEK_CUR); 88 | } 89 | 90 | fclose(f); 91 | 92 | printf("%f\n", area); 93 | 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /src/stl_bbox.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | void print_usage() { 32 | fprintf(stderr, "stl_bbox prints bounding box information about an STL file.\n\n"); 33 | fprintf(stderr, "usage: stl_bbox [ ...]\n"); 34 | fprintf(stderr, " Prints bounding box information for the given STL file.\n"); 35 | fprintf(stderr, " If '-' is given as a file name, stdin is read.\n"); 36 | } 37 | 38 | int main(int argc, char** argv) { 39 | if (argc == 1 || (argc >= 2 && strcmp(argv[1], "--help") == 0)) { 40 | print_usage(); 41 | exit(2); 42 | } 43 | 44 | int failed = 0; 45 | for (int arg = 1; arg < argc; arg++) { 46 | char *file_name = argv[arg]; 47 | FILE* f = (strcmp(file_name, "-") == 0) ? stdin : fopen(file_name, "rb"); 48 | if (!f) { 49 | fprintf(stderr, "Can't read file: %s\n", file_name); 50 | failed++; 51 | } else { 52 | int is_ascii = is_valid_ascii_stl(f); 53 | if (!is_ascii && !is_valid_binary_stl(f)) { 54 | fprintf(stderr, "%s is not an STL file.\n", file_name); 55 | failed++; 56 | } else { 57 | bounds_t b; 58 | get_bounds(f, &b, is_ascii); 59 | printf("File: %s Extents: (%f, %f, %f) - (%f, %f, %f)\n", file_name, b.min.x, b.min.y, b.min.z, b.max.x, b.max.y, b.max.z); 60 | printf("File: %s Dimensions: (%f, %f, %f)\n", file_name, b.max.x-b.min.x, b.max.y-b.min.y, b.max.z-b.min.z); 61 | } 62 | } 63 | if (f && f != stdin) { 64 | fclose(f); 65 | } 66 | } 67 | if (failed) { 68 | exit(2); 69 | } 70 | return 0; 71 | } 72 | 73 | -------------------------------------------------------------------------------- /src/stl_spreadsheet.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | #include 29 | 30 | void print_usage() { 31 | fprintf(stderr, "stl_spreadsheet outputs an STL file in a tab delimited text format.\n\n"); 32 | fprintf(stderr, "usage: stl_spreadsheet \n"); 33 | fprintf(stderr, " Prints vertex and normal information for every triangle in STL file in a tab delimited format that can be opened as a spreadsheet.\n"); 34 | } 35 | 36 | int main(int argc, char** argv) { 37 | if(argc >= 2) { 38 | if(strcmp(argv[1], "--help") == 0) { 39 | print_usage(); 40 | exit(2); 41 | } 42 | } 43 | if(argc != 2) { 44 | print_usage(); 45 | exit(2); 46 | } 47 | 48 | char *file = argv[1]; 49 | 50 | if(!is_valid_binary_stl(file)) { 51 | fprintf(stderr, "%s is not a binary stl file.\n", file); 52 | exit(2); 53 | } 54 | 55 | FILE *f; 56 | 57 | f = fopen(file, "rb"); 58 | if(!f) { 59 | fprintf(stderr, "Can't read file: %s\n", file); 60 | exit(2); 61 | } 62 | 63 | fseek(f, 80, SEEK_SET); 64 | 65 | uint32_t num_tris; 66 | size_t readBytes = fread(&num_tris, 4, 1, f); 67 | 68 | vec normal; 69 | vec point; 70 | 71 | std::cout << "normal.x\tnormal.y\tnormal.z\tpoint1.x\tpoint1.y\tpoint1.z\tpoint2.x\tpoint2.y\tpoint2.z\tpoint3.x\tpoint3.y\tpoint3.z" << std::endl; 72 | 73 | for(int i = 0; i < num_tris; i++) { 74 | readBytes = fread(&normal, 1, 12,f); 75 | 76 | std::cout << normal.x << "\t" << normal.y << "\t" << normal.z; 77 | 78 | for(int j = 0; j < 3; j++) { 79 | readBytes = fread(&point, 1, 12,f); 80 | std::cout << "\t" << point.x << "\t" << point.y << "\t" << point.z; 81 | } 82 | std::cout << std::endl; 83 | fseek(f, 2, SEEK_CUR); 84 | } 85 | 86 | fclose(f); 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /src/csgjs/math/Plane.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_PLANE__ 2 | #define __CSGJS_PLANE__ 3 | 4 | #include "csgjs/math/Vector3.h" 5 | #include "csgjs/constants.h" 6 | 7 | namespace csgjs { 8 | 9 | class Plane; 10 | inline std::ostream& operator<<(std::ostream& os, const Plane &plane); 11 | 12 | struct Plane { 13 | Vector3 normal; 14 | csgjs_real w; 15 | 16 | Plane() : normal(), w(0) {} 17 | Plane(const Vector3 &n, const csgjs_real ww) : normal(n), w(ww) {} 18 | 19 | Plane flipped() const { 20 | return Plane(-normal, -w); 21 | } 22 | 23 | Plane transform(const Matrix4x4 &m) const { 24 | bool ismirror = m.isMirroring(); 25 | 26 | Vector3 r = normal.nonParallelVector(); 27 | Vector3 u = normal.cross(r); 28 | Vector3 v = normal.cross(u); 29 | 30 | Vector3 p1 = normal*w; 31 | Vector3 p2 = p1+u; 32 | Vector3 p3 = p1+v; 33 | 34 | Plane newPlane = Plane::fromVector3s(p1,p2,p3); 35 | if(ismirror) { 36 | newPlane = newPlane.flipped(); 37 | } 38 | 39 | return newPlane; 40 | } 41 | 42 | Vector3 splitLineBetweenPoints(const Vector3 &p1, const Vector3 &p2) const { 43 | Vector3 dir = p2-p1; 44 | csgjs_real dot = normal.dot(dir); 45 | csgjs_real lambda = 0; 46 | if(dot > EPS || dot < NEG_EPS) { 47 | lambda = (w-normal.dot(p1))/dot; 48 | } 49 | if(lambda > 1) { 50 | lambda = 1; 51 | } 52 | 53 | if(lambda < 0) { 54 | lambda = 0; 55 | } 56 | 57 | Vector3 inter = p1+dir*lambda; 58 | 59 | return p1+dir*lambda; 60 | } 61 | 62 | bool operator==(const Plane &p) const { 63 | return normal == p.normal && w == p.w; 64 | } 65 | 66 | bool isEqualWithinTolerance(const Plane &p) const { 67 | csgjs_real wDiff = p.w-w; 68 | return (p.normal-normal).isZero() && wDiff < EPS && wDiff > NEG_EPS; 69 | } 70 | 71 | static Plane fromVector3s(const Vector3 &a, const Vector3 &b, const Vector3 &c) { 72 | Vector3 n = ((b-a).cross(c-a)).unit(); 73 | return Plane(n, n.dot(a)); 74 | } 75 | 76 | static Plane anyPlaneFromVector3s(const Vector3 &a, const Vector3 &b, const Vector3 &c) { 77 | Vector3 v1 = b-a; 78 | Vector3 v2 = c-a; 79 | if(v1.length() < EPS) { 80 | v1 = v2.nonParallelVector(); 81 | } 82 | if(v2.length() < EPS) { 83 | v2 = v1.nonParallelVector(); 84 | } 85 | 86 | Vector3 normal = v1.cross(v2); 87 | if(normal.length() < EPS) { 88 | // this means that v1 == -v2 89 | v2 = v1.nonParallelVector(); 90 | normal = v1.cross(v2); 91 | } 92 | normal = normal.unit(); 93 | return Plane(normal, normal.dot(a)); 94 | } 95 | 96 | static Plane fromNormalAndPoint(const Vector3 &n, const Vector3 &p) { 97 | Vector3 normal = n.unit(); 98 | csgjs_real w = p.dot(normal); 99 | return Plane(normal, w); 100 | } 101 | 102 | }; 103 | 104 | inline std::ostream& operator<<(std::ostream& os, const Plane &plane) { 105 | os << plane.normal << ", " << plane.w; 106 | return os; 107 | } 108 | 109 | 110 | } 111 | 112 | #endif 113 | -------------------------------------------------------------------------------- /src/stl_decimate.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2019 by Allwine Designs, LLC (stl_cmd@allwinedesigns.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "Simplify.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | void print_usage() { 32 | fprintf(stderr, "stl_decimate simplifies the provided STL file using Sven Forstmann's implementation of Fast Quadric Mesh Simplification: https://github.com/sp4cerat/Fast-Quadric-Mesh-Simplification\n\n"); 33 | fprintf(stderr, "usage: stl_decimate [ -t ] [ -p ] \n"); 34 | fprintf(stderr, " Outputs a simplified version of the input mesh. \n"); 35 | fprintf(stderr, " -t is used to specifiy an exact triangle count (an integer). \n"); 36 | fprintf(stderr, " -p is used to specifiy a fraction of the starting triangle count (a floating point number between 0 and 1). \n"); 37 | fprintf(stderr, " If both -t and -p are used, the smaller number of triangles is used. \n"); 38 | fprintf(stderr, " If neither are provided, -p defaults to .5. \n"); 39 | } 40 | 41 | int main(int argc, char** argv) { 42 | if(argc == 2) { 43 | if(strcmp(argv[1], "--help") == 0) { 44 | print_usage(); 45 | exit(2); 46 | } 47 | } 48 | int errflg = 0; 49 | int c; 50 | 51 | int target_count = -1; 52 | float percentage = -1; 53 | bool verbose = false; 54 | 55 | while((c = getopt(argc, argv, "t:p:v")) != -1) { 56 | switch(c) { 57 | case 'v': 58 | verbose = true; 59 | break; 60 | case 't': 61 | target_count = atoi(optarg); 62 | break; 63 | case 'p': 64 | percentage = atof(optarg); 65 | break; 66 | case '?': 67 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 68 | errflg++; 69 | break; 70 | } 71 | } 72 | 73 | if(errflg || 74 | optind+1 >= argc) { 75 | print_usage(); 76 | exit(2); 77 | } 78 | 79 | Simplify::load_stl(argv[optind]); 80 | 81 | if(percentage > -1 && target_count > -1) { 82 | target_count = min(percentage*Simplify::triangles.size(), target_count); 83 | } else if(percentage > -1) { 84 | target_count = percentage*Simplify::triangles.size(); 85 | } else if(target_count > -1) { 86 | target_count = min(Simplify::triangles.size(), target_count); 87 | } else { 88 | target_count = .5*Simplify::triangles.size(); 89 | } 90 | 91 | Simplify::simplify_mesh(target_count, 7, verbose); 92 | Simplify::write_stl(argv[optind+1]); 93 | 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /src/stl_count.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "stl_util.h" 27 | 28 | #define BUFFER_SIZE 4096 29 | 30 | void print_usage() { 31 | fprintf(stderr, "stl_count prints the number of triangles in an STL file.\n\n"); 32 | fprintf(stderr, "usage: stl_count [ ]\n"); 33 | fprintf(stderr, " Prints the number of triangles in the provided binary STL file. If no input file is specified, data is read from stdin.\n"); 34 | } 35 | 36 | int main(int argc, char** argv) { 37 | if(argc >= 2) { 38 | if(strcmp(argv[1], "--help") == 0) { 39 | print_usage(); 40 | exit(2); 41 | } 42 | } 43 | if(argc == 2) { 44 | FILE *f; 45 | char* filename = argv[1]; 46 | 47 | if(!is_valid_binary_stl(filename)) { 48 | fprintf(stderr, "stl_count only accepts binary stl files.\n"); 49 | exit(2); 50 | } 51 | f = fopen(filename, "r+b"); 52 | if(!f) { 53 | fprintf(stderr, "Can't read file: %s\n", filename); 54 | exit(2); 55 | } 56 | fseek(f, 80, SEEK_SET); 57 | 58 | uint32_t num_tris; 59 | 60 | if(fread(&num_tris, 1, 4, f) < 4) { 61 | fprintf(stderr, "invalid binary stl file\n"); 62 | exit(2); 63 | } 64 | 65 | fclose(f); 66 | printf("%d\n", num_tris); 67 | } else if(argc > 2) { 68 | print_usage(); 69 | exit(2); 70 | } else { 71 | off_t bights_read = 0; 72 | while(bights_read < 80 && getc(stdin) != EOF) { 73 | bights_read++; 74 | } 75 | if(bights_read < 80) { 76 | fprintf(stderr, "invalid binary stl file\n"); 77 | exit(2); 78 | } 79 | // got through header 80 | 81 | bights_read = 0; 82 | uint8_t buff[4]; 83 | 84 | int c; 85 | // now read num_tris 86 | while(bights_read < 4 && (c = getc(stdin)) != EOF) { 87 | buff[bights_read] = c; 88 | bights_read++; 89 | } 90 | 91 | if(bights_read < 4) { 92 | fprintf(stderr, "invalid binary stl file\n"); 93 | exit(2); 94 | } 95 | 96 | uint32_t num_tris = *((uint32_t*)buff); 97 | 98 | // read the rest of the file 99 | while(bights_read < num_tris*16 && getc(stdin) != EOF) { 100 | bights_read++; 101 | } 102 | 103 | if(bights_read < num_tris*16) { 104 | fprintf(stderr, "invalid binary stl file\n"); 105 | exit(2); 106 | } 107 | 108 | printf("%d\n", num_tris); 109 | } 110 | 111 | return 0; 112 | } 113 | -------------------------------------------------------------------------------- /src/csgjs/Trees.h: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_TREES__ 2 | #define __CSGJS_TREES__ 3 | 4 | #include "csgjs/util.h" 5 | #include 6 | #include "csgjs/math/Plane.h" 7 | #include "csgjs/math/Polygon3.h" 8 | 9 | namespace csgjs { 10 | 11 | class PolygonTreeNode { 12 | private: 13 | PolygonTreeNode *parent; 14 | std::vector children; 15 | Polygon polygon; 16 | bool valid; 17 | bool removed; 18 | 19 | void splitLeafByPlane(const Plane &plane, std::vector &coplanarFrontNodes, 20 | std::vector &coplanarBackNodes, 21 | std::vector &frontNodes, 22 | std::vector &backNodes); 23 | 24 | void splitPolygonByPlane(const Plane &plane, std::vector &coplanarFrontNodes, 25 | std::vector &coplanarBackNodes, 26 | std::vector &frontNodes, 27 | std::vector &backNodes); 28 | 29 | void invertRecurse(); 30 | 31 | public: 32 | PolygonTreeNode(); 33 | PolygonTreeNode(const Polygon &polygon); 34 | PolygonTreeNode(PolygonTreeNode *parent, const Polygon &polygon); 35 | ~PolygonTreeNode(); 36 | 37 | PolygonTreeNode* addChild(const Polygon &polygon); 38 | 39 | void getPolygons(std::vector &polygons) const; 40 | void invalidate(); 41 | void remove(); 42 | void invert(); 43 | bool isRootNode() const; 44 | bool isRemoved() const; 45 | int countNodes() const; 46 | Polygon& getPolygon(); 47 | void splitByPlane(const Plane &plane, std::vector &coplanarFrontNodes, 48 | std::vector &coplanarBackNodes, 49 | std::vector &frontNodes, 50 | std::vector &backNodes); 51 | 52 | friend std::ostream& indentChildNodes(std::ostream& os, const PolygonTreeNode *node, int level); 53 | friend std::ostream& operator<<(std::ostream& os, const PolygonTreeNode &polygonTreeNode); 54 | }; 55 | 56 | 57 | class Tree; 58 | 59 | class Node { 60 | private: 61 | Plane plane; 62 | Node* front; 63 | Node* back; 64 | Node* parent; 65 | std::vector polygonTreeNodes; 66 | 67 | public: 68 | Node(); 69 | Node(Node* p); 70 | 71 | bool hasFrontNodes(const Plane &p) const; 72 | bool isRootNode() const; 73 | void invert(); 74 | void clipTo(Tree &tree, bool alsoRemoveCoplanarFront=false); 75 | void clipPolygons(std::vector &polyTreeNodes, bool alsoRemoveCoplanarFront=false); 76 | void addPolygonTreeNodes(const std::vector &polyTreeNodes); 77 | }; 78 | 79 | // Root node of the CSG tree and PolygonTree 80 | class Tree { 81 | private: 82 | Node rootnode; 83 | PolygonTreeNode polygonTree; 84 | 85 | public: 86 | Tree(const std::vector &polygons); 87 | 88 | void addPolygons(const std::vector &polygons); 89 | 90 | bool hasPolygonsInFront(const Plane &p) const; 91 | void clipTo(Tree &tree, bool alsoRemoveCoplanarFront=false); 92 | void invert(); 93 | std::vector toPolygons(); 94 | 95 | friend std::ostream& operator<<(std::ostream& os, const Tree &tree); 96 | friend class Node; 97 | }; 98 | } 99 | 100 | #endif 101 | -------------------------------------------------------------------------------- /src/stl_ascii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include "stl_util.h" 29 | 30 | #define BUFFER_SIZE 4096 31 | 32 | void print_usage() { 33 | fprintf(stderr, "stl_ascii converts a binary STL file to ASCII.\n\n"); 34 | fprintf(stderr, "usage: stl_ascii [ [] ]\n"); 35 | fprintf(stderr, " Outputs an ASCII stl file given a binary STL file. "); 36 | fprintf(stderr, " If no input file is provided, data is read from stdin. If no output file is provided, data is sent to stdout. \n"); 37 | } 38 | 39 | int main(int argc, char** argv) { 40 | if (argc > 1 && strcmp(argv[1], "--help") == 0) { 41 | print_usage(); 42 | exit(2); 43 | } 44 | FILE *in_file = stdin; 45 | const char* in_file_name = "stdin"; 46 | FILE *out_file = stdout; 47 | const char* out_file_name = "stdout"; 48 | if (argc >= 2) { 49 | in_file_name = argv[1]; 50 | in_file = fopen(in_file_name, "rb"); 51 | if (!in_file) { 52 | fprintf(stderr, "Can't read from file: %s\n", in_file_name); 53 | } 54 | } 55 | if (argc >= 3) { 56 | out_file_name = argv[2]; 57 | out_file = fopen(out_file_name, "w"); 58 | if (!out_file) { 59 | fprintf(stderr, "Can't write to file: %s\n", out_file_name); 60 | fclose(in_file); 61 | } 62 | } 63 | char name[BUFFER_SIZE]; 64 | memset(name, 0x00, BUFFER_SIZE); 65 | facet_t facet; 66 | uint32_t facet_count = 0; 67 | 68 | if (is_valid_ascii_stl(in_file)) { 69 | read_header(in_file, name, BUFFER_SIZE, NULL, 1); 70 | write_header(out_file, name, facet_count, 1); 71 | while (read_facet(in_file, &facet, 1)) { 72 | write_facet(out_file, &facet, 1); 73 | facet_count++; 74 | } 75 | read_final(in_file, 1); 76 | write_final(out_file, name, facet_count, 1); 77 | } else if (is_valid_binary_stl(in_file)) { 78 | read_header(in_file, name, BUFFER_SIZE, &facet_count, 0); 79 | write_header(out_file, name, facet_count, 1); 80 | for (int i = 0; i < facet_count; i++) { 81 | read_facet(in_file, &facet, 0); 82 | write_facet(out_file, &facet, 1); 83 | } 84 | read_final(in_file, 0); 85 | write_final(out_file, name, facet_count, 1); 86 | } else { 87 | fprintf(stderr, "Invalid STL file: %s\n", in_file_name); 88 | if (in_file != stdin) { 89 | fclose(in_file); 90 | } 91 | if (out_file != stdout) { 92 | fclose(out_file); 93 | } 94 | exit(2); 95 | } 96 | if (in_file != stdin) { 97 | fclose(in_file); 98 | } 99 | if (out_file != stdout) { 100 | fclose(out_file); 101 | } 102 | return 0; 103 | } 104 | -------------------------------------------------------------------------------- /src/stl_binary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include "stl_util.h" 29 | 30 | #define BUFFER_SIZE 4096 31 | 32 | void print_usage() { 33 | fprintf(stderr, "stl_binary converts an ASCII STL file to binary.\n\n"); 34 | fprintf(stderr, "usage: stl_binary [ [] ]\n"); 35 | fprintf(stderr, " Outputs a binary stl file given an ascii STL file. "); 36 | fprintf(stderr, " If no input file is provided, data is read from stdin. If no output file is provided, data is sent to stdout. \n"); 37 | } 38 | 39 | int main(int argc, char** argv) { 40 | if (argc > 1 && strcmp(argv[1], "--help") == 0) { 41 | print_usage(); 42 | exit(2); 43 | } 44 | FILE *in_file = stdin; 45 | const char* in_file_name = "stdin"; 46 | FILE *out_file = stdout; 47 | const char* out_file_name = "stdout"; 48 | if (argc >= 2) { 49 | in_file_name = argv[1]; 50 | in_file = fopen(in_file_name, "rb"); 51 | if (!in_file) { 52 | fprintf(stderr, "Can't read from file: %s\n", in_file_name); 53 | } 54 | } 55 | if (argc >= 3) { 56 | out_file_name = argv[2]; 57 | out_file = fopen(out_file_name, "wb"); 58 | if (!out_file) { 59 | fprintf(stderr, "Can't write to file: %s\n", out_file_name); 60 | fclose(in_file); 61 | } 62 | } 63 | char name[BUFFER_SIZE]; 64 | memset(name, 0x00, BUFFER_SIZE); 65 | facet_t facet; 66 | uint32_t facet_count = 0; 67 | 68 | if (is_valid_ascii_stl(in_file)) { 69 | read_header(in_file, name, BUFFER_SIZE, NULL, 1); 70 | write_header(out_file, name, facet_count, 0); 71 | while (read_facet(in_file, &facet, 1)) { 72 | write_facet(out_file, &facet, 0); 73 | facet_count++; 74 | } 75 | read_final(in_file, 1); 76 | write_final(out_file, name, facet_count, 0); 77 | } else if (is_valid_binary_stl(in_file)) { 78 | read_header(in_file, name, BUFFER_SIZE, &facet_count, 0); 79 | write_header(out_file, name, facet_count, 0); 80 | for (int i = 0; i < facet_count; i++) { 81 | read_facet(in_file, &facet, 0); 82 | write_facet(out_file, &facet, 0); 83 | } 84 | read_final(in_file, 0); 85 | write_final(out_file, name, facet_count, 0); 86 | } else { 87 | fprintf(stderr, "Invalid STL file: %s\n", in_file_name); 88 | if (in_file != stdin) { 89 | fclose(in_file); 90 | } 91 | if (out_file != stdout) { 92 | fclose(out_file); 93 | } 94 | exit(2); 95 | } 96 | if (in_file != stdin) { 97 | fclose(in_file); 98 | } 99 | if (out_file != stdout) { 100 | fclose(out_file); 101 | } 102 | return 0; 103 | } 104 | -------------------------------------------------------------------------------- /src/stl_header.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include "stl_util.h" 26 | 27 | #define BUFFER_SIZE 4096 28 | 29 | void print_usage() { 30 | fprintf(stderr, "stl_header inspects and modifies the header section of an STL file.\n\n"); 31 | fprintf(stderr, "usage: stl_header [-s
] [-o ] \n"); 32 | fprintf(stderr, " If both -s and -o flags are specified is copied to and its header is set to
. If -o is not specified and -s is\n"); 34 | fprintf(stderr, " then the header is set on the input file. If neither -o nor -s is specified,\n"); 35 | fprintf(stderr, " the header of the model is output to the terminal.\n"); 36 | } 37 | 38 | int main(int argc, char** argv) { 39 | if(argc >= 2) { 40 | if(strcmp(argv[1], "--help") == 0) { 41 | print_usage(); 42 | exit(2); 43 | } 44 | } 45 | int c; 46 | int errflg = 0; 47 | char *set_header; 48 | char *out_file; 49 | int setflag = 0; 50 | int outflag = 0; 51 | 52 | while((c = getopt(argc, argv, "s:o:")) != -1) { 53 | switch(c) { 54 | case 'o': 55 | outflag = 1; 56 | out_file = optarg; 57 | break; 58 | case 's': 59 | setflag = 1; 60 | set_header = optarg; 61 | break; 62 | case '?': 63 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 64 | errflg++; 65 | break; 66 | } 67 | } 68 | 69 | if(errflg || optind >= argc) { 70 | print_usage(); 71 | exit(2); 72 | } 73 | 74 | char* filename = argv[optind]; 75 | char header[80]; 76 | 77 | if(!is_valid_binary_stl(filename)) { 78 | fprintf(stderr, "stl_header only accepts binary stl files.\n"); 79 | exit(2); 80 | } 81 | 82 | FILE *f; 83 | f = fopen(filename, "r+b"); 84 | if(!f) { 85 | fprintf(stderr, "Can't read file: %s\n", filename); 86 | exit(2); 87 | } 88 | 89 | if(setflag && outflag) { 90 | strncpy(header, set_header, 80); 91 | FILE *outf; 92 | outf = fopen(out_file, "wb"); 93 | if(!outf) { 94 | fprintf(stderr, "Can't write to file: %s\n", out_file); 95 | exit(2); 96 | } 97 | fwrite(header, 80, 1, outf); 98 | fseek(f, 80, SEEK_SET); 99 | 100 | char buffer[BUFFER_SIZE]; 101 | 102 | int r; 103 | while((r = fread(buffer, 1, BUFFER_SIZE, f))) { 104 | fwrite(buffer, 1, r, outf); 105 | } 106 | fclose(f); 107 | fclose(outf); 108 | } else if(setflag) { 109 | strncpy(header, set_header, 80); 110 | fwrite(header, 80, 1, f); 111 | fclose(f); 112 | } else { 113 | size_t readBytes = fread(header, 80, 1, f); 114 | fclose(f); 115 | 116 | for(int i = 0; i < 80; i++) { 117 | printf("%c", header[i]); 118 | } 119 | printf("\n"); 120 | } 121 | 122 | return 0; 123 | } 124 | -------------------------------------------------------------------------------- /src/csgjs/math/Vector3.cpp: -------------------------------------------------------------------------------- 1 | #include "csgjs/math/Vector3.h" 2 | 3 | namespace csgjs { 4 | 5 | Vector3::Vector3() : x(0), y(0), z(0) {} 6 | Vector3::Vector3(csgjs_real xx, csgjs_real yy, csgjs_real zz) : x(xx), y(yy), z(zz) {} 7 | 8 | Vector3 Vector3::operator-() const { 9 | return Vector3(-x, -y, -z); 10 | } 11 | 12 | Vector3 Vector3::operator+(const Vector3 &b) const { 13 | return Vector3(x+b.x, y+b.y, z+b.z); 14 | } 15 | 16 | Vector3 Vector3::operator-(const Vector3 &b) const { 17 | return Vector3(x-b.x, y-b.y, z-b.z); 18 | } 19 | 20 | Vector3 Vector3::operator*(const csgjs_real m) const { 21 | return Vector3(m*x, m*y, m*z); 22 | } 23 | 24 | Vector3 Vector3::operator/(const csgjs_real m) const { 25 | return Vector3(x/m, y/m, z/m); 26 | } 27 | 28 | csgjs_real Vector3::dot(const Vector3 &b) const { 29 | return x*b.x+y*b.y+z*b.z; 30 | } 31 | 32 | Vector3 Vector3::lerp(const Vector3 &b, csgjs_real t) const { 33 | return (*this)+(b-*this)*t; 34 | } 35 | 36 | csgjs_real Vector3::lengthSquared() const { 37 | return this->dot(*this); 38 | } 39 | 40 | csgjs_real Vector3::length() const { 41 | return sqrt(this->lengthSquared()); 42 | } 43 | 44 | bool Vector3::isZero() const { 45 | return x < EPS && x > NEG_EPS && y < EPS && y > NEG_EPS && z < EPS && z > NEG_EPS; 46 | } 47 | 48 | Vector3 Vector3::unit() const { 49 | return (*this)/this->length(); 50 | } 51 | 52 | Vector3 Vector3::cross(const Vector3 &a) const { 53 | return Vector3(y*a.z-z*a.y, z*a.x-x*a.z, x*a.y-y*a.x); 54 | } 55 | 56 | csgjs_real Vector3::distanceTo(const Vector3 &a) const { 57 | return ((*this)-a).length(); 58 | } 59 | 60 | csgjs_real Vector3::distanceToSquared(const Vector3 &a) const { 61 | return ((*this)-a).lengthSquared(); 62 | } 63 | 64 | bool Vector3::operator==(const Vector3 &a) const { 65 | return x == a.x && y == a.y && z == a.z; 66 | } 67 | 68 | Vector3 Vector3::transform(const Matrix4x4 &m, csgjs_real w) const { 69 | const csgjs_real xx = m.m[0]; 70 | const csgjs_real xy = m.m[1]; 71 | const csgjs_real xz = m.m[2]; 72 | const csgjs_real xw = m.m[3]; 73 | 74 | const csgjs_real yx = m.m[4]; 75 | const csgjs_real yy = m.m[5]; 76 | const csgjs_real yz = m.m[6]; 77 | const csgjs_real yw = m.m[7]; 78 | 79 | const csgjs_real zx = m.m[8]; 80 | const csgjs_real zy = m.m[9]; 81 | const csgjs_real zz = m.m[10]; 82 | const csgjs_real zw = m.m[11]; 83 | 84 | const csgjs_real tx = m.m[12]; 85 | const csgjs_real ty = m.m[13]; 86 | const csgjs_real tz = m.m[14]; 87 | const csgjs_real tw = m.m[15]; 88 | 89 | csgjs_real newX = x*xx+y*yx+z*zx+w*tx; 90 | csgjs_real newY = x*xy+y*yy+z*zy+w*ty; 91 | csgjs_real newZ = x*xz+y*yz+z*zz+w*tz; 92 | csgjs_real newW = x*xw+y*yw+z*zw+w*tw; 93 | 94 | if(newW != 1) { 95 | csgjs_real invW = 1.0/newW; 96 | newX *= invW; 97 | newY *= invW; 98 | newZ *= invW; 99 | } 100 | 101 | return Vector3( newX, newY, newZ ); 102 | } 103 | 104 | Vector3 Vector3::abs() const { 105 | return Vector3(std::abs(x), std::abs(y), std::abs(z)); 106 | } 107 | 108 | Vector3 Vector3::nonParallelVector() const { 109 | Vector3 abs = this->abs(); 110 | if(abs.x <= abs.y && abs.x <= abs.z) { 111 | return Vector3(1,0,0); 112 | } else if(abs.y <= abs.x && abs.y <= abs.z) { 113 | return Vector3(0,1,0); 114 | } else { 115 | return Vector3(0,0,1); 116 | } 117 | } 118 | 119 | Vector3 Vector3::min(const Vector3 &v) const { 120 | return Vector3(std::min(x, v.x), std::min(y, v.y), std::min(z, v.z)); 121 | } 122 | 123 | Vector3 Vector3::max(const Vector3 &v) const { 124 | return Vector3(std::max(x, v.x), std::max(y, v.y), std::max(z, v.z)); 125 | } 126 | 127 | Vector3 operator*(const csgjs_real m, const Vector3 &v) { 128 | return Vector3(m*v.x, m*v.y, m*v.z); 129 | } 130 | 131 | std::ostream& operator<<(std::ostream& os, const Vector3 &v) { 132 | os << "(" << v.x << ", " << v.y << ", " << v.z << ")"; 133 | return os; 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /src/stl_bcylinder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2018 Allwine Designs, LLC (stl_cmd@allwinedesigns.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | void print_usage() { 32 | fprintf(stderr, "stl_bcylinder prints bounding cylinder information about an STL file.\n\n"); 33 | fprintf(stderr, "usage: stl_bcylinder \n"); 34 | fprintf(stderr, " Prints bounding cylinder information for the given binary STL file.\n"); 35 | } 36 | 37 | int main(int argc, char** argv) { 38 | if(argc >= 2) { 39 | if(strcmp(argv[1], "--help") == 0) { 40 | print_usage(); 41 | exit(2); 42 | } 43 | } 44 | 45 | char *file = argv[1]; 46 | 47 | if(!is_valid_binary_stl(file)) { 48 | fprintf(stderr, "%s is not a binary stl file.\n", file); 49 | exit(2); 50 | } 51 | 52 | FILE *f; 53 | 54 | f = fopen(file, "rb"); 55 | if(!f) { 56 | fprintf(stderr, "Can't read file: %s\n", file); 57 | exit(2); 58 | } 59 | 60 | fseek(f, 80, SEEK_SET); 61 | 62 | uint32_t num_tris; 63 | size_t readBytes = fread(&num_tris, 4, 1, f); 64 | 65 | vec point; 66 | point.w = 1; 67 | 68 | vec min; 69 | vec max; 70 | 71 | for(int i = 0; i < num_tris; i++) { 72 | fseek(f, 12, SEEK_CUR); // normal 73 | 74 | for(int j = 0; j < 3; j++) { 75 | readBytes = fread(&point, 1, 12,f); 76 | if(i == 0 && j == 0) { 77 | min.x = point.x; 78 | min.y = point.y; 79 | min.z = point.z; 80 | max.x = point.x; 81 | max.y = point.y; 82 | max.z = point.z; 83 | } else { 84 | if(min.x > point.x) min.x = point.x; 85 | if(min.y > point.y) min.y = point.y; 86 | if(min.z > point.z) min.z = point.z; 87 | if(max.x < point.x) max.x = point.x; 88 | if(max.y < point.y) max.y = point.y; 89 | if(max.z < point.z) max.z = point.z; 90 | } 91 | } 92 | fseek(f, 2, SEEK_CUR); 93 | } 94 | 95 | vec center; 96 | vec pointOnCylinder; 97 | 98 | center.x = .5*(max.x+min.x); 99 | center.y = .5*(max.y+min.y); 100 | center.z = .5*(max.z+min.z); 101 | 102 | float maxR = 0; 103 | 104 | fseek(f, 84, SEEK_SET); 105 | 106 | for(int i = 0; i < num_tris; i++) { 107 | fseek(f, 12, SEEK_CUR); // normal 108 | 109 | for(int j = 0; j < 3; j++) { 110 | readBytes = fread(&point, 1, 12,f); 111 | 112 | vec R; 113 | 114 | R.x = point.x-center.x; 115 | R.y = 0; 116 | R.z = point.z-center.z; 117 | 118 | float rMag = vec_magnitude(&R); 119 | 120 | if(rMag > maxR) { 121 | maxR = rMag; 122 | pointOnCylinder.x = point.x; 123 | pointOnCylinder.y = point.y; 124 | pointOnCylinder.z = point.z; 125 | } 126 | } 127 | fseek(f, 2, SEEK_CUR); 128 | } 129 | 130 | fclose(f); 131 | 132 | printf("Center: (%f, %f, %f)\n", center.x, center.y, center.z); 133 | printf("Point On Cylinder: (%f, %f, %f)\n", pointOnCylinder.x, pointOnCylinder.y, pointOnCylinder.z); 134 | printf("R: %f\n", maxR); 135 | printf("H: %f\n", max.y-min.y); 136 | 137 | return 0; 138 | } 139 | -------------------------------------------------------------------------------- /src/stl_merge.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "stl_util.h" 27 | 28 | #define BUFFER_SIZE 4096 29 | 30 | // TODO Add options for layouting out merged files in a row or grid 31 | // rather than just merging. 32 | 33 | void print_usage() { 34 | fprintf(stderr, "stl_merge concatenates multiple STL files.\n\n"); 35 | fprintf(stderr, "usage: stl_merge [ -o ] [ ... ]\n"); 36 | fprintf(stderr, " Merges binary stl files into a single file. If no out file is provided, data is output to stdout.\n"); 37 | } 38 | 39 | int main(int argc, char** argv) { 40 | if(argc >= 2) { 41 | if(strcmp(argv[1], "--help") == 0) { 42 | print_usage(); 43 | exit(2); 44 | } 45 | } 46 | int c; 47 | int errflg = 0; 48 | char *out_file; 49 | int outflag = 0; 50 | 51 | while((c = getopt(argc, argv, "o:")) != -1) { 52 | switch(c) { 53 | case 'o': 54 | outflag = 1; 55 | out_file = optarg; 56 | break; 57 | case '?': 58 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 59 | errflg++; 60 | break; 61 | } 62 | } 63 | 64 | if(errflg) { 65 | print_usage(); 66 | exit(2); 67 | } 68 | 69 | uint32_t num_tris = 0; 70 | 71 | for(int i = optind; i < argc; i++) { 72 | char* file = argv[i]; 73 | 74 | char name[100]; 75 | snprintf(name, sizeof(name), "%s", file); 76 | 77 | if(!is_valid_binary_stl(file)) { 78 | 79 | fprintf(stderr, "%s is not a binary stl file.\n", name); 80 | exit(2); 81 | } 82 | 83 | FILE *f; 84 | f = fopen(file, "rb"); 85 | if(!f) { 86 | fprintf(stderr, "Can't read file: %s\n", name); 87 | exit(2); 88 | } 89 | fseek(f, 80, SEEK_SET); 90 | 91 | uint32_t nt; 92 | size_t readBytes = fread(&nt, 4, 1, f); 93 | 94 | num_tris += nt; 95 | fclose(f); 96 | } 97 | 98 | 99 | FILE *outf; 100 | 101 | if(outflag) { 102 | outf = fopen(out_file, "wb"); 103 | 104 | char name[100]; 105 | snprintf(name, sizeof(name), "%s", out_file); 106 | 107 | if(!outf) { 108 | fprintf(stderr, "Can't open out file: %s\n", name); 109 | exit(2); 110 | } 111 | } else { 112 | outf = stdout; 113 | } 114 | 115 | char header[81] = {0}; // include an extra char for terminating \0 of snprintf 116 | char base1[50]; 117 | char base2[50]; 118 | snprintf(header, 81, "Merged using stl_merge."); 119 | 120 | fwrite(header, 80, 1, outf); 121 | fwrite(&num_tris, 4, 1, outf); 122 | 123 | char buffer[BUFFER_SIZE]; 124 | 125 | for(int i = optind; i < argc; i++) { 126 | char* file = argv[i]; 127 | 128 | char name[100]; 129 | snprintf(name, sizeof(name), "%s", file); 130 | 131 | FILE *f; 132 | f = fopen(file, "rb"); 133 | if(!f) { 134 | fprintf(stderr, "Can't read file: %s\n", name); 135 | exit(2); 136 | } 137 | fseek(f, 84, SEEK_SET); 138 | 139 | int r; 140 | while((r = fread(buffer, 1, BUFFER_SIZE, f))) { 141 | fwrite(buffer, 1, r, outf); 142 | } 143 | fclose(f); 144 | } 145 | 146 | return 0; 147 | } 148 | -------------------------------------------------------------------------------- /src/stl_boolean.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | #include "csgjs/CSG.h" 28 | #include "csgjs/util.h" 29 | 30 | void print_usage() { 31 | fprintf(stderr, "stl_boolean performs CSG operations on two STL files.\n\n"); 32 | fprintf(stderr, "usage: stl_boolean -a -b [ -i ] [ -u ] [ -d ] \n"); 33 | fprintf(stderr, " Performs a mesh CSG boolean operation on STL files A and B using BSP trees.\n" 34 | " -i - performs the intersection of A and B\n" 35 | " -u - performs the union of A and B (default)\n" 36 | " -d - performs 'A minus B', produces the volume present in A but not present in B\n"); 37 | } 38 | 39 | int main(int argc, char **argv) 40 | { 41 | if(argc >= 2) { 42 | if(strcmp(argv[1], "--help") == 0) { 43 | print_usage(); 44 | exit(2); 45 | } 46 | } 47 | int errflg = 0; 48 | char *a_file; 49 | char *b_file; 50 | int a_set = 0; 51 | int b_set = 0; 52 | 53 | int unionAB = 0; 54 | int intersection = 0; 55 | int difference = 0; 56 | 57 | int c; 58 | 59 | while((c = getopt(argc, argv, "a:b:iud")) != -1) { 60 | switch(c) { 61 | case 'a': 62 | a_set = 1; 63 | a_file = optarg; 64 | break; 65 | case 'b': 66 | b_set = 1; 67 | b_file = optarg; 68 | break; 69 | case 'i': 70 | intersection = 1; 71 | if(unionAB || difference) { 72 | fprintf(stderr, "intersection option provided when union or difference already specified.\n"); 73 | unionAB = 0; 74 | difference = 0; 75 | } 76 | break; 77 | case 'u': 78 | unionAB = 1; 79 | if(intersection || difference) { 80 | fprintf(stderr, "union option provided when intersection or difference already specified.\n"); 81 | intersection = 0; 82 | difference = 0; 83 | } 84 | break; 85 | case 'd': 86 | difference = 1; 87 | if(intersection || unionAB) { 88 | fprintf(stderr, "difference option provided when intersection or union already specified.\n"); 89 | intersection = 0; 90 | unionAB = 0; 91 | } 92 | break; 93 | case '?': 94 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 95 | errflg++; 96 | break; 97 | } 98 | } 99 | 100 | if(!unionAB && !intersection && !difference) { 101 | unionAB = 1; 102 | } 103 | 104 | if(errflg || !(a_set && b_set) || optind >= argc) { 105 | print_usage(); 106 | exit(2); 107 | } 108 | 109 | char *out_filename = argv[optind]; 110 | 111 | csgjs::CSG A(csgjs::ReadSTLFile(a_file)); 112 | csgjs::CSG B(csgjs::ReadSTLFile(b_file)); 113 | 114 | if(unionAB) { 115 | csgjs::CSG csg = A.csgUnion(B); 116 | csg.canonicalize(); 117 | csg.makeManifold(); 118 | csgjs::WriteSTLFile(out_filename, csg.toPolygons()); 119 | } 120 | if(intersection) { 121 | csgjs::CSG csg = A.csgIntersect(B); 122 | csg.canonicalize(); 123 | csg.makeManifold(); 124 | csgjs::WriteSTLFile(out_filename, csg.toPolygons()); 125 | } 126 | if(difference) { 127 | csgjs::CSG csg = A.csgSubtract(B); 128 | csg.canonicalize(); 129 | csg.makeManifold(); 130 | csgjs::WriteSTLFile(out_filename, csg.toPolygons()); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/csgjs/util.cpp: -------------------------------------------------------------------------------- 1 | #ifndef __CSGJS_UTIL__ 2 | #define __CSGJS_UTIL__ 3 | 4 | #include "csgjs/math/Polygon3.h" 5 | #include "stl_util.h" 6 | #include 7 | #include 8 | #include 9 | #include "csgjs/math/HashKeys.h" 10 | 11 | namespace csgjs { 12 | 13 | std::vector ReadSTLFile(const char* filename) { 14 | std::vector polys; 15 | std::vector verts; 16 | verts.reserve(3); 17 | 18 | FILE *f; 19 | 20 | f = fopen(filename, "rb"); 21 | if(!f) { 22 | fprintf(stderr, "Can't read file: %s\n", filename); 23 | exit(2); 24 | } 25 | 26 | fseek(f, 80, SEEK_SET); 27 | 28 | uint32_t num_tris; 29 | size_t readBytes = fread(&num_tris, 4, 1, f); 30 | 31 | vec p1; 32 | vec p2; 33 | vec p3; 34 | 35 | for(int i = 0; i < num_tris; i++) { 36 | fseek(f, 12, SEEK_CUR); // normal 37 | 38 | readBytes = fread(&p1, 1, 12,f); 39 | readBytes = fread(&p2, 1, 12,f); 40 | readBytes = fread(&p3, 1, 12,f); 41 | fseek(f, 2, SEEK_CUR); 42 | 43 | verts.clear(); 44 | verts.push_back(Vertex(Vector3(p1.x, p1.y, p1.z))); 45 | verts.push_back(Vertex(Vector3(p2.x, p2.y, p2.z))); 46 | verts.push_back(Vertex(Vector3(p3.x, p3.y, p3.z))); 47 | 48 | Polygon p(verts); 49 | 50 | if(p.checkIfDegenerateTriangle()) { 51 | // std::cout << "found degenerate triangle, ignoring" << std::endl; 52 | } else { 53 | polys.push_back(Polygon(verts)); 54 | } 55 | } 56 | 57 | fclose(f); 58 | 59 | return std::move(polys); 60 | } 61 | 62 | void WriteSTLFile(const char* filename, const std::vector polygons) { 63 | FILE *outf = fopen(filename, "wb"); 64 | if(!outf) { 65 | fprintf(stderr, "Can't write to file: %s\n", filename); 66 | } 67 | 68 | char header[81] = {0}; 69 | snprintf(header, 81, "Created with stl_cmd"); 70 | fwrite(header, 80, 1, outf); 71 | 72 | uint32_t num_tris = 0; 73 | std::vector::const_iterator itr = polygons.begin(); 74 | while(itr != polygons.end()) { 75 | num_tris += itr->vertices.size()-2; 76 | ++itr; 77 | } 78 | 79 | std::unordered_map vertexLookup; 80 | 81 | fwrite(&num_tris, 4, 1, outf); 82 | 83 | uint16_t abc = 0; 84 | 85 | itr = polygons.begin(); 86 | while(itr != polygons.end()) { 87 | vec normal; 88 | vec p0; 89 | vec p1; 90 | 91 | Vector3 vertex0 = itr->vertices[0].pos; 92 | Vector3 vertex1 = itr->vertices[1].pos; 93 | 94 | VertexKey key0(vertex0); 95 | VertexKey key1(vertex1); 96 | 97 | if(vertexLookup.count(key0) > 0) { 98 | vertex0 = vertexLookup[key0]; 99 | } else { 100 | vertexLookup[key0] = vertex0; 101 | } 102 | if(vertexLookup.count(key1) > 0) { 103 | vertex1 = vertexLookup[key1]; 104 | } else { 105 | vertexLookup[key1] = vertex1; 106 | } 107 | 108 | normal.x = (float)itr->plane.normal.x; 109 | normal.y = (float)itr->plane.normal.y; 110 | normal.z = (float)itr->plane.normal.z; 111 | 112 | p0.x = (float)vertex0.x; 113 | p0.y = (float)vertex0.y; 114 | p0.z = (float)vertex0.z; 115 | 116 | p1.x = (float)vertex1.x; 117 | p1.y = (float)vertex1.y; 118 | p1.z = (float)vertex1.z; 119 | 120 | int numVertices = itr->vertices.size(); 121 | for(int i = 2; i < numVertices; i++) { 122 | fwrite(&normal, 1, 12, outf); 123 | 124 | vec p2; 125 | 126 | Vector3 vertex2 = itr->vertices[i].pos; 127 | VertexKey key2(vertex2); 128 | if(vertexLookup.count(key2) > 0) { 129 | vertex2 = vertexLookup[key2]; 130 | } else { 131 | vertexLookup[key2] = vertex2; 132 | } 133 | 134 | p2.x = (float)vertex2.x; 135 | p2.y = (float)vertex2.y; 136 | p2.z = (float)vertex2.z; 137 | 138 | fwrite(&p0, 1, 12, outf); 139 | fwrite(&p1, 1, 12, outf); 140 | fwrite(&p2, 1, 12, outf); 141 | fwrite(&abc, 1, 2,outf); 142 | 143 | p1 = p2; 144 | } 145 | 146 | ++itr; 147 | } 148 | 149 | fclose(outf); 150 | } 151 | 152 | 153 | // from https://stackoverflow.com/questions/1640258/need-a-fast-random-generator-for-c 154 | static unsigned long x=123456789, y=362436069, z=521288629; 155 | 156 | unsigned long xorshf96(void) { //period 2^96-1 157 | unsigned long t; 158 | x ^= x << 16; 159 | x ^= x >> 5; 160 | x ^= x << 1; 161 | 162 | t = x; 163 | x = y; 164 | y = z; 165 | z = t ^ x ^ y; 166 | 167 | return z; 168 | } 169 | 170 | int fastRandom(int max) { 171 | return xorshf96() % max; 172 | } 173 | 174 | } 175 | 176 | #endif 177 | -------------------------------------------------------------------------------- /src/stl_cylinder.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | void print_usage() { 32 | fprintf(stderr, "stl_cylinder outputs an STL file of a single cylinder.\n\n"); 33 | fprintf(stderr, "usage: stl_cylinder [ -r ] [ -h ] [ -s ] [ ]\n"); 34 | fprintf(stderr, " Outputs an stl file of a cylinder with the provided radius, height and number of segments to approximate a circle.\n"); 35 | fprintf(stderr, " If the radius or height are omitted, they default to 1. If segments is omitted, it defaults to 32. If no output file is provided, data is sent to stdout. \n"); 36 | } 37 | 38 | int main(int argc, char** argv) { 39 | if(argc >= 2) { 40 | if(strcmp(argv[1], "--help") == 0) { 41 | print_usage(); 42 | exit(2); 43 | } 44 | } 45 | int errflg = 0; 46 | int c; 47 | 48 | float radius = 1; 49 | float height = 1; 50 | int segments = 32; 51 | 52 | while((c = getopt(argc, argv, "r:h:s:")) != -1) { 53 | switch(c) { 54 | 55 | case 'r': 56 | radius = atof(optarg); 57 | break; 58 | case 'h': 59 | height = atof(optarg); 60 | break; 61 | case 's': 62 | segments = atoi(optarg); 63 | break; 64 | case '?': 65 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 66 | errflg++; 67 | break; 68 | } 69 | } 70 | 71 | if(errflg) { 72 | print_usage(); 73 | exit(2); 74 | } 75 | 76 | FILE *outf; 77 | 78 | if(optind == argc-1) { 79 | char *file = argv[optind]; 80 | 81 | outf = fopen(file, "wb"); 82 | if(!outf) { 83 | fprintf(stderr, "Can't write to file: %s\n", file); 84 | exit(2); 85 | } 86 | } else { 87 | outf = stdout; 88 | } 89 | 90 | char header[81] = {0}; 91 | snprintf(header, 81, "Cylinder of radius %.4f and height %.4f", radius, height); 92 | 93 | fwrite(header, 80, 1, outf); 94 | 95 | // caps tube 96 | uint32_t num_tris = 2*(segments-2)+2*segments; 97 | 98 | fwrite(&num_tris, 4, 1, outf); 99 | 100 | uint16_t abc = 0; // attribute byte count 101 | 102 | 103 | vec p0; 104 | vec p1; 105 | vec p2; 106 | vec p3; 107 | for(int i = 0; i < segments; i++) { 108 | float angle = 2*M_PI*i/segments; 109 | float angle2 = 2*M_PI*(i+1)/segments; 110 | if(i == segments-1) { 111 | angle2 = 0; 112 | } 113 | float cosa = cos(angle); 114 | float sina = sin(angle); 115 | 116 | float cosa2 = cos(angle2); 117 | float sina2 = sin(angle2); 118 | 119 | p0.x = radius*cosa; 120 | p0.y = radius*sina; 121 | p0.z = height*.5; 122 | 123 | p1.x = radius*cosa; 124 | p1.y = radius*sina; 125 | p1.z = -height*.5; 126 | 127 | p2.x = radius*cosa2; 128 | p2.y = radius*sina2; 129 | p2.z = -height*.5; 130 | 131 | p3.x = radius*cosa2; 132 | p3.y = radius*sina2; 133 | p3.z = height*.5; 134 | 135 | write_quad(outf, &p0, &p1, &p2, &p3, 0); 136 | } 137 | 138 | for(int i = 1; i < segments-1; i++) { 139 | float angle = 2*M_PI*i/segments; 140 | float angle2 = 2*M_PI*(i+1)/segments; 141 | float cosa = cos(angle); 142 | float sina = sin(angle); 143 | 144 | float cosa2 = cos(angle2); 145 | float sina2 = sin(angle2); 146 | 147 | p0.x = radius; 148 | p0.y = 0; 149 | p0.z = height*.5; 150 | 151 | p1.x = radius*cosa; 152 | p1.y = radius*sina; 153 | p1.z = height*.5; 154 | 155 | p2.x = radius*cosa2; 156 | p2.y = radius*sina2; 157 | p2.z = height*.5; 158 | 159 | write_tri(outf, &p0, &p1, &p2, 0); 160 | 161 | p0.z = -height*.5; 162 | p1.z = -height*.5; 163 | p2.z = -height*.5; 164 | 165 | write_tri(outf, &p0, &p1, &p2, 1); 166 | } 167 | 168 | return 0; 169 | } 170 | -------------------------------------------------------------------------------- /src/stl_cube.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | void print_usage() { 32 | fprintf(stderr, "stl_cube outputs an STL file of a single cube.\n\n"); 33 | fprintf(stderr, "usage: stl_cube [-w ] [ ]\n"); 34 | fprintf(stderr, " Outputs an stl file of a cube with the provided width. "); 35 | fprintf(stderr, " If the width is omitted, it defaults to 1. If no output file is provided, data is sent to stdout. \n"); 36 | } 37 | 38 | int main(int argc, char** argv) { 39 | if(argc >= 2) { 40 | if(strcmp(argv[1], "--help") == 0) { 41 | print_usage(); 42 | exit(2); 43 | } 44 | } 45 | int errflg = 0; 46 | int c; 47 | 48 | float width = 1; 49 | 50 | while((c = getopt(argc, argv, "w:")) != -1) { 51 | switch(c) { 52 | case 'w': 53 | width = atof(optarg); 54 | break; 55 | case '?': 56 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 57 | errflg++; 58 | break; 59 | } 60 | } 61 | 62 | if(errflg) { 63 | print_usage(); 64 | exit(2); 65 | } 66 | 67 | FILE *outf; 68 | 69 | if(optind == argc-1) { 70 | char *file = argv[optind]; 71 | 72 | outf = fopen(file, "wb"); 73 | if(!outf) { 74 | fprintf(stderr, "Can't write to file: %s\n", file); 75 | exit(2); 76 | } 77 | } else { 78 | outf = stdout; 79 | } 80 | 81 | char header[81] = {0}; 82 | snprintf(header, 81, "Cube of width %.4f", width); 83 | 84 | fwrite(header, 80, 1, outf); 85 | 86 | uint32_t num_tris = 12; 87 | 88 | fwrite(&num_tris, 4, 1, outf); 89 | 90 | uint16_t abc = 0; // attribute byte count 91 | 92 | float tris[12][3][3] = { 93 | // Top 94 | { 95 | { 1, 1, 1 }, 96 | { 1, 1, -1 }, 97 | { -1, 1, -1 } 98 | }, 99 | { 100 | { -1, 1, -1 }, 101 | { -1, 1, 1 }, 102 | { 1, 1, 1 } 103 | }, 104 | // Bottom 105 | { 106 | { -1, -1, 1 }, 107 | { 1, -1, -1 }, 108 | { 1, -1, 1 } 109 | }, 110 | { 111 | { -1, -1, 1 }, 112 | { -1, -1, -1 }, 113 | { 1, -1, -1 } 114 | }, 115 | // Right 116 | { 117 | { 1, -1, 1 }, 118 | { 1, -1, -1 }, 119 | { 1, 1, -1 } 120 | }, 121 | { 122 | { 1, 1, -1 }, 123 | { 1, 1, 1 }, 124 | { 1, -1, 1 } 125 | }, 126 | // Left 127 | { 128 | { -1, -1, 1 }, 129 | { -1, 1, 1 }, 130 | { -1, 1, -1 } 131 | }, 132 | { 133 | { -1, 1, -1 }, 134 | { -1, -1, -1 }, 135 | { -1, -1, 1 } 136 | }, 137 | // Near 138 | { 139 | { 1, 1, 1 }, 140 | { -1, 1, 1 }, 141 | { -1, -1, 1 } 142 | }, 143 | { 144 | { -1, -1, 1 }, 145 | { 1, -1, 1 }, 146 | { 1, 1, 1 } 147 | }, 148 | // Far 149 | { 150 | { 1, -1, -1 }, 151 | { -1, -1, -1 }, 152 | { -1, 1, -1 } 153 | }, 154 | { 155 | { -1, 1, -1 }, 156 | { 1, 1, -1 }, 157 | { 1, -1, -1 } 158 | } 159 | }; 160 | 161 | float normals[12][3] = { 162 | // Top 163 | { 0, 1, 0 }, 164 | { 0, 1, 0 }, 165 | // Bottom 166 | { 0, -1, 0 }, 167 | { 0, -1, 0 }, 168 | // Right 169 | { 1, 0, 0 }, 170 | { 1, 0, 0 }, 171 | // Left 172 | { -1, 0, 0 }, 173 | { -1, 0, 0 }, 174 | // Near 175 | { 0, 0, 1 }, 176 | { 0, 0, 1 }, 177 | // Far 178 | { 0, 0, -1 }, 179 | { 0, 0, -1 } 180 | }; 181 | 182 | for(int i = 0; i < num_tris; i++) { 183 | fwrite(normals[i], 1, 12, outf); 184 | for(int j = 0; j < 3; j++) { 185 | for(int k = 0; k < 3; k++) { 186 | tris[i][j][k] *= .5*width; 187 | } 188 | } 189 | fwrite(tris[i], 1, 36, outf); 190 | fwrite(&abc, 1, 2,outf); 191 | } 192 | 193 | return 0; 194 | } 195 | -------------------------------------------------------------------------------- /src/stl_flat.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2018 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include "csgjs/util.h" 22 | #include "csgjs/Trees.h" 23 | #include "csgjs/math/Matrix4x4.h" 24 | #include "csgjs/math/HashKeys.h" 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #ifndef M_PI 31 | #define M_PI 3.141592653589 32 | #endif 33 | 34 | using namespace csgjs; 35 | 36 | void print_usage() { 37 | fprintf(stderr, "stl_flat orients an STL file so the plane with the largest surface area of triangles that doesn't have any triangles in front of it is facing down.\n\n"); 38 | fprintf(stderr, "usage: stl_flat [ ]\n"); 39 | fprintf(stderr, " Orients the STL file so the plane with the largest surface area of triangles that doesn't have any triangles in front of it is facing down.\n"); 40 | } 41 | 42 | typedef struct { 43 | std::unordered_map area; 44 | bool operator() (PlaneKey a, PlaneKey b) { 45 | return area[a] > area[b]; 46 | } 47 | } SortPlanesByArea; 48 | 49 | int main(int argc, char** argv) { 50 | if(argc >= 2) { 51 | if(strcmp(argv[1], "--help") == 0) { 52 | print_usage(); 53 | exit(2); 54 | } 55 | } 56 | 57 | char *in_filename; 58 | if(argc > 1) { 59 | in_filename = argv[1]; 60 | } else { 61 | print_usage(); 62 | exit(2); 63 | } 64 | 65 | char *out_filename; 66 | if(argc > 2) { 67 | out_filename = argv[2]; 68 | } else { 69 | print_usage(); 70 | exit(2); 71 | } 72 | 73 | SortPlanesByArea areaSorter; 74 | 75 | std::vector polys = ReadSTLFile(in_filename); 76 | 77 | std::vector::iterator polyItr = polys.begin(); 78 | while(polyItr != polys.end()) { 79 | PlaneKey key(polyItr->plane); 80 | 81 | Vector3 a = polyItr->vertices[1].pos-polyItr->vertices[0].pos; 82 | Vector3 b = polyItr->vertices[2].pos-polyItr->vertices[0].pos; 83 | 84 | areaSorter.area[key] += a.cross(b).length()*.5; 85 | 86 | ++polyItr; 87 | } 88 | 89 | std::vector planes; 90 | std::unordered_map::iterator aItr = areaSorter.area.begin(); 91 | while(aItr != areaSorter.area.end()) { 92 | planes.push_back(aItr->first); 93 | ++aItr; 94 | } 95 | 96 | std::sort(planes.begin(), planes.end(), areaSorter); 97 | 98 | // once quickhull is implemented for use in stl_hull, using the convex hull rather than the 99 | // actual model would probably go much faster for large models 100 | // potentially using an unordered_map to look up planes in the convex hull rather than needing the 101 | // binary space partitioning tree at all 102 | Tree tree(polys); 103 | 104 | std::vector::iterator pItr = planes.begin(); 105 | while(pItr != planes.end()) { 106 | if(!tree.hasPolygonsInFront(pItr->plane)) { 107 | std::cout << "Orienting to plane with total surface area of " << areaSorter.area[*pItr] << std::endl; 108 | csgjs_real dotWithNegativeZ = pItr->plane.normal.dot(Vector3(0,0,-1)); 109 | if(1-dotWithNegativeZ < EPS && 1-dotWithNegativeZ > NEG_EPS) { 110 | // plane is already aligned, no transform necessary 111 | WriteSTLFile(out_filename, polys); 112 | exit(0); 113 | } else if(-1-dotWithNegativeZ < EPS && -1-dotWithNegativeZ > NEG_EPS) { 114 | // plane is oriented 180 degrees 115 | Vector3 axis = Vector3(1,0,0); 116 | csgjs_real angle = M_PI; 117 | 118 | Matrix4x4 xform = Matrix4x4::rotate(axis, angle); 119 | std::vector transformedPolys; 120 | std::vector::iterator polyItr = polys.begin(); 121 | while(polyItr != polys.end()) { 122 | transformedPolys.push_back(polyItr->transform(xform)); 123 | ++polyItr; 124 | } 125 | WriteSTLFile(out_filename, transformedPolys); 126 | exit(0); 127 | } else { 128 | // plane needs to be aligned 129 | Vector3 axis = pItr->plane.normal.cross(Vector3(0,0,-1)).unit(); 130 | csgjs_real angle = acos(pItr->plane.normal.dot(Vector3(0,0,-1))); 131 | 132 | Matrix4x4 xform = Matrix4x4::rotate(axis, angle); 133 | std::vector transformedPolys; 134 | std::vector::iterator polyItr = polys.begin(); 135 | while(polyItr != polys.end()) { 136 | transformedPolys.push_back(polyItr->transform(xform)); 137 | ++polyItr; 138 | } 139 | WriteSTLFile(out_filename, transformedPolys); 140 | exit(0); 141 | } 142 | } 143 | ++pItr; 144 | } 145 | 146 | return 0; 147 | } 148 | -------------------------------------------------------------------------------- /src/stl_torus.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | void print_usage() { 32 | fprintf(stderr, "stl_torus outputs an STL file of a single torus.\n\n"); 33 | fprintf(stderr, "usage: stl_torus [ -o ] [ -i ] [ -s ] [ -c ] [ ]\n"); 34 | fprintf(stderr, " Outputs an stl file of a torus with the provided outer radius, inner radius and number of segments.\n"); 35 | fprintf(stderr, " If the inner radius is omitted, it defaults to .5. If the outer radius is omitted, it defaults to 1.\n"); 36 | fprintf(stderr, " If segments is omitted, it defaults to 32. If cross sectional segments is omitted, it defaults to half the segments.\n"); 37 | fprintf(stderr, " If no output file is provided, data is sent to stdout. \n"); 38 | } 39 | 40 | int main(int argc, char** argv) { 41 | if(argc >= 2) { 42 | if(strcmp(argv[1], "--help") == 0) { 43 | print_usage(); 44 | exit(2); 45 | } 46 | } 47 | int errflg = 0; 48 | int c; 49 | 50 | float innerRadius = .5; 51 | float outerRadius = 1; 52 | int segments = 32; 53 | int minorSegments = 16; 54 | 55 | int minorSegmentsSet = 0; 56 | 57 | while((c = getopt(argc, argv, "i:o:s:c:")) != -1) { 58 | switch(c) { 59 | case 'i': 60 | innerRadius = atof(optarg); 61 | break; 62 | case 'o': 63 | outerRadius = atof(optarg); 64 | break; 65 | case 's': 66 | segments = atoi(optarg); 67 | break; 68 | case 'c': 69 | minorSegments = atoi(optarg); 70 | minorSegmentsSet = 1; 71 | break; 72 | case '?': 73 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 74 | errflg++; 75 | break; 76 | } 77 | } 78 | 79 | if(!minorSegmentsSet) { 80 | minorSegments = segments/2; 81 | } 82 | 83 | if(errflg) { 84 | print_usage(); 85 | exit(2); 86 | } 87 | 88 | FILE *outf; 89 | 90 | if(optind == argc-1) { 91 | char *file = argv[optind]; 92 | 93 | outf = fopen(file, "wb"); 94 | if(!outf) { 95 | fprintf(stderr, "Can't write to file: %s\n", file); 96 | exit(2); 97 | } 98 | } else { 99 | outf = stdout; 100 | } 101 | 102 | char header[81] = {0}; 103 | snprintf(header, 81, "Torus with inner radius %.4f and outer radius %.4f", innerRadius, outerRadius); 104 | 105 | fwrite(header, 80, 1, outf); 106 | 107 | uint32_t num_tris = 2*segments*minorSegments; 108 | 109 | fwrite(&num_tris, 4, 1, outf); 110 | 111 | uint16_t abc = 0; // attribute byte count 112 | 113 | vec p0; 114 | vec p1; 115 | vec p2; 116 | vec p3; 117 | float majorRadius = (outerRadius+innerRadius)*.5; 118 | float minorRadius = (outerRadius-innerRadius)*.5; 119 | for(int i = 0; i < segments; i++) { 120 | float i_angle = 2*M_PI*i/segments; 121 | float i_angle2 = 2*M_PI*(i+1)/segments; 122 | if(i == segments-1) { 123 | i_angle2 = 0; 124 | } 125 | float i_cosa = cos(i_angle); 126 | float i_sina = sin(i_angle); 127 | 128 | float i_cosa2 = cos(i_angle2); 129 | float i_sina2 = sin(i_angle2); 130 | 131 | for(int j = 0; j < minorSegments; j++) { 132 | float j_angle = 2*M_PI*j/minorSegments; 133 | float j_angle2 = 2*M_PI*(j+1)/minorSegments; 134 | if(j == minorSegments-1) { 135 | j_angle2 = 0; 136 | } 137 | float j_cosa = cos(j_angle); 138 | float j_sina = sin(j_angle); 139 | 140 | float j_cosa2 = cos(j_angle2); 141 | float j_sina2 = sin(j_angle2); 142 | 143 | p0.x = i_cosa*(majorRadius+minorRadius*j_cosa); 144 | p0.y = i_sina*(majorRadius+minorRadius*j_cosa); 145 | p0.z = minorRadius*j_sina; 146 | 147 | p1.x = i_cosa2*(majorRadius+minorRadius*j_cosa); 148 | p1.y = i_sina2*(majorRadius+minorRadius*j_cosa); 149 | p1.z = minorRadius*j_sina; 150 | 151 | p2.x = i_cosa2*(majorRadius+minorRadius*j_cosa2); 152 | p2.y = i_sina2*(majorRadius+minorRadius*j_cosa2); 153 | p2.z = minorRadius*j_sina2; 154 | 155 | p3.x = i_cosa*(majorRadius+minorRadius*j_cosa2); 156 | p3.y = i_sina*(majorRadius+minorRadius*j_cosa2); 157 | p3.z = minorRadius*j_sina2; 158 | 159 | write_quad(outf, &p0, &p1, &p2, &p3, 0); 160 | } 161 | } 162 | 163 | return 0; 164 | } 165 | -------------------------------------------------------------------------------- /src/stl_zero.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include "stl_util.h" 29 | 30 | #define BUFFER_SIZE 4096 31 | 32 | void print_usage() { 33 | fprintf(stderr, "stl_zero centres an STL file.\n\n"); 34 | fprintf(stderr, "usage: stl_zero [-base] [ [] ]\n"); 35 | fprintf(stderr, " Center an STL file around the origin. "); 36 | fprintf(stderr, " If no input file is provided, data is read from stdin. If no output file is provided, data is sent to stdout. \n"); 37 | fprintf(stderr, " -base - If this is specified, set the lowest point in the design to z = 0. \n"); 38 | } 39 | 40 | int main(int argc, char** argv) { 41 | FILE *in_file = stdin; 42 | const char* in_file_name = "stdin"; 43 | FILE *out_file = stdout; 44 | const char* out_file_name = "stdout"; 45 | int do_base = 0; 46 | int done_flags = 0; 47 | 48 | for (int arg = 1; arg < argc; arg++) { 49 | if (!done_flags) { 50 | if (argv[arg][0] == '-') { 51 | if (strcmp(argv[arg], "--help") == 0) { 52 | print_usage(); 53 | exit(2); 54 | } else if (strcmp(argv[arg], "--") == 0) { 55 | done_flags = 1; 56 | continue; 57 | } else if (strcmp(argv[arg], "-base") == 0) { 58 | do_base = 1; 59 | continue; 60 | } else { 61 | fprintf(stderr, "Unrecognized argument: %s\n", argv[arg]); 62 | print_usage(); 63 | exit(2); 64 | } 65 | } else { 66 | done_flags = 1; 67 | } 68 | } 69 | 70 | if (in_file == stdin) { 71 | in_file_name = argv[arg]; 72 | in_file = fopen(in_file_name, "rb"); 73 | if (!in_file) { 74 | fprintf(stderr, "Can't read from file: %s\n", in_file_name); 75 | exit(2); 76 | } 77 | } else if (out_file == stdout) { 78 | out_file_name = argv[arg]; 79 | out_file = fopen(out_file_name, "w"); 80 | if (!out_file) { 81 | fprintf(stderr, "Can't write to file: %s\n", out_file_name); 82 | fclose(in_file); 83 | exit(2); 84 | } 85 | } else { 86 | fprintf(stderr, "Too many arguments!\n"); 87 | print_usage(); 88 | if (in_file != stdin) { 89 | fclose(in_file); 90 | } 91 | if (out_file != stdout) { 92 | fclose(out_file); 93 | } 94 | exit(2); 95 | } 96 | } 97 | 98 | int failed = 0; 99 | int is_ascii = is_valid_ascii_stl(in_file); 100 | if (!is_ascii && !is_valid_binary_stl(in_file)) { 101 | fprintf(stderr, "%s is not an STL file.\n", in_file_name); 102 | failed++; 103 | } else { 104 | bounds_t b; 105 | get_bounds(in_file, &b, is_ascii); 106 | double x_centre = (b.min.x + b.max.x) / 2.0; 107 | double y_centre = (b.min.y + b.max.y) / 2.0; 108 | double z_centre = (b.min.z + b.max.z) / 2.0; 109 | vec translation; 110 | translation.x = -x_centre; 111 | translation.y = -y_centre; 112 | translation.z = do_base ? -b.min.z : -z_centre; 113 | translation.w = 0; 114 | 115 | fseek(in_file, 0, SEEK_SET); 116 | char name[BUFFER_SIZE]; 117 | memset(name, 0x00, BUFFER_SIZE); 118 | facet_t facet; 119 | facet_t translated_facet; 120 | uint32_t facet_count = 0; 121 | 122 | read_header(in_file, name, BUFFER_SIZE, &facet_count, is_ascii); 123 | write_header(out_file, name, facet_count, is_ascii); 124 | for (int i = 0; is_ascii || i < facet_count; i++) { 125 | if (read_facet(in_file, &facet, is_ascii)) { 126 | translated_facet.normal = facet.normal; 127 | for (int j = 0; j < 3; j++) { 128 | vec_add(&facet.vertices[j], &translation, &translated_facet.vertices[j]); 129 | } 130 | write_facet(out_file, &translated_facet, is_ascii); 131 | if (is_ascii) { 132 | facet_count++; 133 | } 134 | } else { 135 | break; 136 | } 137 | } 138 | read_final(in_file, is_ascii); 139 | write_final(out_file, name, facet_count, is_ascii); 140 | } 141 | if (in_file != stdin) { 142 | fclose(in_file); 143 | } 144 | if (out_file != stdout) { 145 | fclose(out_file); 146 | } 147 | if (failed) { 148 | exit(2); 149 | } 150 | return 0; 151 | } 152 | -------------------------------------------------------------------------------- /src/csgjs/math/HashKeys.cpp: -------------------------------------------------------------------------------- 1 | #include "csgjs/math/HashKeys.h" 2 | 3 | namespace csgjs { 4 | PlaneKey::PlaneKey(const Plane &p) { 5 | plane = p; 6 | 7 | long int x = (long int)(std::round(plane.normal.x/(10*EPS))); 8 | long int y = (long int)(std::round(plane.normal.y/(10*EPS))); 9 | long int z = (long int)(std::round(plane.normal.z/(10*EPS))); 10 | 11 | long int w = (long int)(std::round(plane.w/(10*EPS))); 12 | 13 | hash = (((std::hash()(x) ^ (std::hash()(y) << 1)) >> 1) ^ (std::hash()(z) << 1)) ^ std::hash()(w); 14 | } 15 | 16 | bool PlaneKey::operator==(const PlaneKey &k) const { 17 | return k.plane.isEqualWithinTolerance(plane); 18 | } 19 | 20 | LineKey::LineKey(const Line& l) { 21 | // A point and direction define a line. We want any equal Line to have the same hash value, so we need 22 | // a consistent way to represent a line, such that any Line we pass to this constructor will yield the 23 | // same point and direction. We'll store the point that intersects the plane that intersects the origin, 24 | // whose normal is the same as the direction of the line. We'll compare the direction of the line to 25 | // Vector(0,0,1), then Vector(0,1,0), then Vector(1,0,0) and pick the first one that isn't perpendicular 26 | // to the line and set the direction so it's dot product with the chosen vector is positive. 27 | 28 | // We eliminate floating point errors by rounding to integers after scaling up by 1./EPS 29 | Vector3 d = l.direction.unit(); 30 | 31 | Vector3 point = l.point-d*(d.dot(l.point)); 32 | 33 | float dotZ = d.dot(Vector3(0,0,1)); 34 | if(dotZ > EPS) { 35 | line = Line(point, d); 36 | } else if(dotZ < -EPS) { 37 | line = Line(point, -d); 38 | } else { 39 | float dotY = d.dot(Vector3(0,1,0)); 40 | if(dotY > EPS) { 41 | line = Line(point, d); 42 | } else if(dotY < -EPS) { 43 | line = Line(point, -d); 44 | } else { 45 | float dotX = d.dot(Vector3(1,0,0)); 46 | if(dotX > EPS) { 47 | line = Line(point, d); 48 | } else { 49 | line = Line(point, -d); 50 | } 51 | } 52 | } 53 | 54 | long int x = (long int)(std::round(line.direction.x/(10*EPS))); 55 | long int y = (long int)(std::round(line.direction.y/(10*EPS))); 56 | long int z = (long int)(std::round(line.direction.z/(10*EPS))); 57 | 58 | long int x2 = (long int)(std::round(line.point.x/(10*EPS))); 59 | long int y2 = (long int)(std::round(line.point.y/(10*EPS))); 60 | long int z2 = (long int)(std::round(line.point.z/(10*EPS))); 61 | 62 | // hash = (((std::hash()(x) ^ (std::hash()(y) << 1)) >> 1) ^ (std::hash()(z) << 1)) ^ 63 | // (((std::hash()(x2) ^ (std::hash()(y2) << 1)) >> 1) ^ (std::hash()(z2) << 1)); 64 | hash = (std::hash()(x) ^ std::hash()(y) ^ std::hash()(z)) ^ 65 | (std::hash()(x2) ^ std::hash()(y2) ^ std::hash()(z2)); 66 | } 67 | 68 | bool LineKey::operator==(const LineKey &l) const { 69 | return l.line == line; 70 | } 71 | 72 | EdgeKey::EdgeKey(const Vector3 &a, const Vector3 &b) { 73 | first = a; 74 | second = b; 75 | 76 | long int x = (long int)(std::round(first.x/(10*EPS))); 77 | long int y = (long int)(std::round(first.y/(10*EPS))); 78 | long int z = (long int)(std::round(first.z/(10*EPS))); 79 | 80 | long int x2 = (long int)(std::round(second.x/(10*EPS))); 81 | long int y2 = (long int)(std::round(second.y/(10*EPS))); 82 | long int z2 = (long int)(std::round(second.z/(10*EPS))); 83 | 84 | // hash = (((std::hash()(x) ^ (std::hash()(y) << 1)) >> 1) ^ (std::hash()(z) << 1)) ^ 85 | // (((std::hash()(x2) ^ (std::hash()(y2) << 1)) >> 1) ^ (std::hash()(z2) << 1)); 86 | hash = (std::hash()(x) ^ std::hash()(y) ^ std::hash()(z)) ^ 87 | (std::hash()(x2) ^ std::hash()(y2) ^ std::hash()(z2)); 88 | } 89 | 90 | EdgeKey EdgeKey::reversed() const { 91 | return EdgeKey(second, first); 92 | } 93 | 94 | bool EdgeKey::operator==(const EdgeKey &k) const { 95 | return (k.first-first).length() < EPS && (k.second-second).length() < EPS; 96 | } 97 | 98 | VertexKey::VertexKey(const Vector3 &a) : v(a) { 99 | long int x = (long int)(std::round(v.x/(10*EPS))); 100 | long int y = (long int)(std::round(v.y/(10*EPS))); 101 | long int z = (long int)(std::round(v.z/(10*EPS))); 102 | 103 | // hash = (((std::hash()(x) ^ (std::hash()(y) << 1)) >> 1) ^ (std::hash()(z) << 1)); 104 | hash = (std::hash()(x) ^ std::hash()(y) ^ std::hash()(z)); 105 | } 106 | 107 | bool VertexKey::operator==(const VertexKey &a) const { 108 | return (a.v-v).length() < EPS; 109 | } 110 | 111 | VertexKeyDist::VertexKeyDist(const VertexKey &k, csgjs_real b) : key(k), dist(b) { 112 | } 113 | 114 | bool VertexKeyDist::operator<(const VertexKeyDist &k) const { 115 | return dist-k.dist < -EPS; 116 | } 117 | 118 | bool VertexKeyDist::operator==(const VertexKeyDist &k) const { 119 | return key == k.key; 120 | } 121 | } 122 | 123 | std::size_t std::hash::operator()(const csgjs::PlaneKey& p) const { 124 | return p.hash; 125 | } 126 | 127 | std::size_t std::hash::operator()(const csgjs::LineKey& l) const { 128 | return l.hash; 129 | } 130 | 131 | std::size_t std::hash::operator()(const csgjs::EdgeKey& e) const { 132 | return e.hash; 133 | } 134 | 135 | std::size_t std::hash::operator()(const csgjs::VertexKey& v) const { 136 | return v.hash; 137 | } 138 | 139 | std::size_t std::hash::operator()(const csgjs::VertexKeyDist& v) const { 140 | return v.key.hash; 141 | } 142 | -------------------------------------------------------------------------------- /src/stl_sphere.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | void print_usage() { 30 | fprintf(stderr, "stl_sphere outputs an STL file of a single sphere.\n\n"); 31 | fprintf(stderr, "usage: stl_sphere [-r ] [-s ] [-t ] [ ]\n"); 32 | fprintf(stderr, " Outputs an stl file of a sphere with the provided radius and number of segments. "); 33 | fprintf(stderr, " If the radius is omitted, it defaults to 1. If longitudinal segments is omitted, it defaults to 32. If latitudinal segments is omitted, it defaults to half the longitudinal segments. If no output file is provided, data is sent to stdout. \n"); 34 | } 35 | 36 | int main(int argc, char** argv) { 37 | if(argc >= 2) { 38 | if(strcmp(argv[1], "--help") == 0) { 39 | print_usage(); 40 | exit(2); 41 | } 42 | } 43 | int errflg = 0; 44 | int c; 45 | 46 | float radius = 1; 47 | int s_segments = 32; 48 | int t_segments = 16; 49 | 50 | int set_t_segments = 0; 51 | 52 | while((c = getopt(argc, argv, "r:s:t:")) != -1) { 53 | switch(c) { 54 | case 'r': 55 | radius = atof(optarg); 56 | break; 57 | case 's': 58 | s_segments = atoi(optarg); 59 | break; 60 | case 't': 61 | s_segments = atoi(optarg); 62 | set_t_segments = 1; 63 | break; 64 | case '?': 65 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 66 | errflg++; 67 | break; 68 | } 69 | } 70 | 71 | if(!set_t_segments) { 72 | t_segments = s_segments >> 1; // divide by 2 73 | } 74 | 75 | if(t_segments < 3) { 76 | t_segments = 3; 77 | } 78 | 79 | if(s_segments < 3) { 80 | s_segments = 3; 81 | } 82 | 83 | if(errflg) { 84 | print_usage(); 85 | exit(2); 86 | } 87 | 88 | FILE *outf; 89 | 90 | if(optind == argc-1) { 91 | char *file = argv[optind]; 92 | 93 | outf = fopen(file, "wb"); 94 | if(!outf) { 95 | fprintf(stderr, "Can't write to file: %s\n", file); 96 | exit(2); 97 | } 98 | } else { 99 | outf = stdout; 100 | } 101 | 102 | char header[81] = {0}; 103 | snprintf(header, 81, "Sphere with radius %.4f", radius); 104 | 105 | fwrite(header, 80, 1, outf); 106 | 107 | uint32_t num_tris = 2*s_segments*(t_segments-1); 108 | 109 | fwrite(&num_tris, 4, 1, outf); 110 | 111 | uint16_t abc = 0; // attribute byte count 112 | 113 | for(int i = 0; i < s_segments; i++) { 114 | float ti = (float)i/s_segments; 115 | float ti_next = (float)(i+1)/s_segments; 116 | float theta = ti*M_PI*2; 117 | float theta_next = ti_next*M_PI*2; 118 | 119 | float cos_theta = cos(theta); 120 | float sin_theta = sin(theta); 121 | 122 | float cos_theta_next = cos(theta_next); 123 | float sin_theta_next = sin(theta_next); 124 | 125 | for(int j = 0; j < t_segments; j++) { 126 | float tj = (float)j/t_segments; 127 | float tj_next = (float)(j+1)/t_segments; 128 | float phi = tj*M_PI; 129 | float phi_next = tj_next*M_PI; 130 | 131 | float cos_phi = cos(phi); 132 | float sin_phi = sin(phi); 133 | 134 | float cos_phi_next = cos(phi_next); 135 | float sin_phi_next = sin(phi_next); 136 | 137 | vec p1, p2, p3, p4; 138 | if(j == 0) { 139 | p1.x = radius*cos_theta*sin_phi; 140 | p1.y = radius*sin_theta*sin_phi; 141 | p1.z = radius*cos_phi; 142 | 143 | p2.x = radius*cos_theta_next*sin_phi_next; 144 | p2.y = radius*sin_theta_next*sin_phi_next; 145 | p2.z = radius*cos_phi_next; 146 | 147 | p3.x = radius*cos_theta*sin_phi_next; 148 | p3.y = radius*sin_theta*sin_phi_next; 149 | p3.z = radius*cos_phi_next; 150 | 151 | write_tri(outf, &p1, &p2, &p3, 1); 152 | } else if(j == t_segments-1) { 153 | p1.x = radius*cos_theta*sin_phi; 154 | p1.y = radius*sin_theta*sin_phi; 155 | p1.z = radius*cos_phi; 156 | 157 | p2.x = radius*cos_theta_next*sin_phi; 158 | p2.y = radius*sin_theta_next*sin_phi; 159 | p2.z = radius*cos_phi; 160 | 161 | p3.x = radius*cos_theta*sin_phi_next; 162 | p3.y = radius*sin_theta*sin_phi_next; 163 | p3.z = radius*cos_phi_next; 164 | 165 | write_tri(outf, &p1, &p2, &p3, 1); 166 | } else { 167 | p1.x = radius*cos_theta*sin_phi; 168 | p1.y = radius*sin_theta*sin_phi; 169 | p1.z = radius*cos_phi; 170 | 171 | p2.x = radius*cos_theta_next*sin_phi; 172 | p2.y = radius*sin_theta_next*sin_phi; 173 | p2.z = radius*cos_phi; 174 | 175 | p3.x = radius*cos_theta_next*sin_phi_next; 176 | p3.y = radius*sin_theta_next*sin_phi_next; 177 | p3.z = radius*cos_phi_next; 178 | 179 | p4.x = radius*cos_theta*sin_phi_next; 180 | p4.y = radius*sin_theta*sin_phi_next; 181 | p4.z = radius*cos_phi_next; 182 | 183 | write_quad(outf, &p1, &p2, &p3, &p4, 1); 184 | } 185 | } 186 | } 187 | 188 | return 0; 189 | } 190 | -------------------------------------------------------------------------------- /src/csgjs/math/Matrix4x4.cpp: -------------------------------------------------------------------------------- 1 | #include "csgjs/math/Matrix4x4.h" 2 | #include "csgjs/math/Vector3.h" 3 | 4 | namespace csgjs { 5 | 6 | Matrix4x4::Matrix4x4() { 7 | // identity matrix 8 | m[0] = 1; 9 | m[1] = 0; 10 | m[2] = 0; 11 | m[3] = 0; 12 | 13 | m[4] = 0; 14 | m[5] = 1; 15 | m[6] = 0; 16 | m[7] = 0; 17 | 18 | m[8] = 0; 19 | m[9] = 0; 20 | m[10] = 1; 21 | m[11] = 0; 22 | 23 | m[12] = 0; 24 | m[13] = 0; 25 | m[14] = 0; 26 | m[15] = 1; 27 | } 28 | // mrc - m 29 | Matrix4x4::Matrix4x4(csgjs_real m00, csgjs_real m01, csgjs_real m02, csgjs_real m03, csgjs_real m10, csgjs_real m11, csgjs_real m12, csgjs_real m13, csgjs_real m20, csgjs_real m21, csgjs_real m22, csgjs_real m23, csgjs_real m30, csgjs_real m31, csgjs_real m32, csgjs_real m33) { 30 | // identity matrix 31 | m[0] = m00; 32 | m[1] = m01; 33 | m[2] = m02; 34 | m[3] = m03; 35 | 36 | m[4] = m10; 37 | m[5] = m11; 38 | m[6] = m12; 39 | m[7] = m13; 40 | 41 | m[8] = m20; 42 | m[9] = m21; 43 | m[10] = m22; 44 | m[11] = m23; 45 | 46 | m[12] = m30; 47 | m[13] = m31; 48 | m[14] = m32; 49 | m[15] = m33; 50 | } 51 | 52 | // this seems more consistent with how transforms are applied 53 | // but I transposed from what was in CSG.js, would 54 | // love for someone to tell me if I'm wrong or if it doesn't matter 55 | bool Matrix4x4::isMirroring() const { 56 | Vector3 u(m[0], m[1], m[2]); 57 | Vector3 v(m[4], m[5], m[6]); 58 | Vector3 w(m[8], m[9], m[10]); 59 | 60 | return u.cross(v).dot(w) < 0; 61 | } 62 | 63 | Matrix4x4 Matrix4x4::operator+(const Matrix4x4 &mat) const { 64 | return Matrix4x4(m[0]+mat.m[0], 65 | m[1]+mat.m[1], 66 | m[2]+mat.m[2], 67 | m[3]+mat.m[3], 68 | m[4]+mat.m[4], 69 | m[5]+mat.m[5], 70 | m[6]+mat.m[6], 71 | m[7]+mat.m[7], 72 | m[8]+mat.m[8], 73 | m[9]+mat.m[9], 74 | m[10]+mat.m[10], 75 | m[11]+mat.m[11], 76 | m[12]+mat.m[12], 77 | m[13]+mat.m[13], 78 | m[14]+mat.m[14], 79 | m[15]+mat.m[15]); 80 | } 81 | 82 | Matrix4x4 Matrix4x4::operator-(const Matrix4x4 &mat) const { 83 | return Matrix4x4(m[0]-mat.m[0], 84 | m[1]-mat.m[1], 85 | m[2]-mat.m[2], 86 | m[3]-mat.m[3], 87 | m[4]-mat.m[4], 88 | m[5]-mat.m[5], 89 | m[6]-mat.m[6], 90 | m[7]-mat.m[7], 91 | m[8]-mat.m[8], 92 | m[9]-mat.m[9], 93 | m[10]-mat.m[10], 94 | m[11]-mat.m[11], 95 | m[12]-mat.m[12], 96 | m[13]-mat.m[13], 97 | m[14]-mat.m[14], 98 | m[15]-mat.m[15]); 99 | } 100 | 101 | Matrix4x4 Matrix4x4::operator*(const Matrix4x4 &mat) const { 102 | const csgjs_real a00 = m[0]; 103 | const csgjs_real a01 = m[1]; 104 | const csgjs_real a02 = m[2]; 105 | const csgjs_real a03 = m[3]; 106 | const csgjs_real a10 = m[4]; 107 | const csgjs_real a11 = m[5]; 108 | const csgjs_real a12 = m[6]; 109 | const csgjs_real a13 = m[7]; 110 | const csgjs_real a20 = m[8]; 111 | const csgjs_real a21 = m[9]; 112 | const csgjs_real a22 = m[10]; 113 | const csgjs_real a23 = m[11]; 114 | const csgjs_real a30 = m[12]; 115 | const csgjs_real a31 = m[13]; 116 | const csgjs_real a32 = m[14]; 117 | const csgjs_real a33 = m[15]; 118 | 119 | const csgjs_real b00 = mat.m[0]; 120 | const csgjs_real b01 = mat.m[1]; 121 | const csgjs_real b02 = mat.m[2]; 122 | const csgjs_real b03 = mat.m[3]; 123 | const csgjs_real b10 = mat.m[4]; 124 | const csgjs_real b11 = mat.m[5]; 125 | const csgjs_real b12 = mat.m[6]; 126 | const csgjs_real b13 = mat.m[7]; 127 | const csgjs_real b20 = mat.m[8]; 128 | const csgjs_real b21 = mat.m[9]; 129 | const csgjs_real b22 = mat.m[10]; 130 | const csgjs_real b23 = mat.m[11]; 131 | const csgjs_real b30 = mat.m[12]; 132 | const csgjs_real b31 = mat.m[13]; 133 | const csgjs_real b32 = mat.m[14]; 134 | const csgjs_real b33 = mat.m[15]; 135 | 136 | return Matrix4x4(a00*b00+a01*b10+a02*b20+a03*b30, 137 | a00*b01+a01*b11+a02*b21+a03*b31, 138 | a00*b02+a01*b12+a02*b22+a03*b32, 139 | a00*b03+a01*b13+a02*b23+a03*b33, 140 | a10*b00+a11*b10+a12*b20+a13*b30, 141 | a10*b01+a11*b11+a12*b21+a13*b31, 142 | a10*b02+a11*b12+a12*b22+a13*b32, 143 | a10*b03+a11*b13+a12*b23+a13*b33, 144 | a20*b00+a21*b10+a22*b20+a23*b30, 145 | a20*b01+a21*b11+a22*b21+a23*b31, 146 | a20*b02+a21*b12+a22*b22+a23*b32, 147 | a20*b03+a21*b13+a22*b23+a23*b33, 148 | a30*b00+a31*b10+a32*b20+a33*b30, 149 | a30*b01+a31*b11+a32*b21+a33*b31, 150 | a30*b02+a31*b12+a32*b22+a33*b32, 151 | a30*b03+a31*b13+a32*b23+a33*b33); 152 | } 153 | 154 | Matrix4x4 Matrix4x4::translate(csgjs_real x, csgjs_real y, csgjs_real z) { 155 | return Matrix4x4(1,0,0,0, 156 | 0,1,0,0, 157 | 0,0,1,0, 158 | x,y,z,1); 159 | } 160 | 161 | Matrix4x4 Matrix4x4::rotate(const Vector3 &axis, csgjs_real angle) { 162 | csgjs_real cos_angle = cos(angle); 163 | csgjs_real one_minus_cos_angle = 1-cos_angle; 164 | csgjs_real sin_angle = sin(angle); 165 | 166 | return Matrix4x4( 167 | // x 168 | cos_angle+axis.x*axis.x*one_minus_cos_angle, 169 | axis.y*axis.x*one_minus_cos_angle+axis.z*sin_angle, 170 | axis.z*axis.x*one_minus_cos_angle-axis.y*sin_angle, 171 | 0, 172 | 173 | // y 174 | axis.x*axis.y*one_minus_cos_angle-axis.z*sin_angle, 175 | cos_angle+axis.y*axis.y*one_minus_cos_angle, 176 | axis.z*axis.y*one_minus_cos_angle+axis.x*sin_angle, 177 | 0, 178 | 179 | // z 180 | axis.x*axis.z*one_minus_cos_angle+axis.y*sin_angle, 181 | axis.y*axis.z*one_minus_cos_angle-axis.x*sin_angle, 182 | cos_angle+axis.z*axis.z*one_minus_cos_angle, 183 | 0, 184 | 185 | // t 186 | 0, 0, 0, 1 187 | ); 188 | } 189 | 190 | } 191 | -------------------------------------------------------------------------------- /src/stl_borders.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | #include 29 | #include 30 | 31 | #define BUFFER_SIZE 4096 32 | 33 | void print_usage() { 34 | fprintf(stderr, "stl_borders prints how many border edges there are in a given STL file.\n\n"); 35 | fprintf(stderr, "usage: stl_borders [ -e ] [ -i ] [ ]\n"); 36 | fprintf(stderr, " Prints how many border edges there are. For a watertight, manifold model, it will be 0.\n"); 37 | fprintf(stderr, " -e - will use the vertices exactly as stored rather than consolidating vertices that are very close together\n"); 38 | fprintf(stderr, " -i - ignore degenerate triangles (those with area very near or exactly 0)."); 39 | } 40 | 41 | struct VertexKey { 42 | float x; 43 | float y; 44 | float z; 45 | VertexKey() : x(0), y(0), z(0) {} 46 | VertexKey(float xx, float yy, float zz, bool exact = false) { 47 | if(exact) { 48 | x = xx; 49 | y = yy; 50 | z = zz; 51 | } else { 52 | x = (float)(int)(std::round((double)xx/EPSILON)); 53 | y = (float)(int)(std::round((double)yy/EPSILON)); 54 | z = (float)(int)(std::round((double)zz/EPSILON)); 55 | } 56 | } 57 | 58 | bool operator==(const VertexKey& k) const { 59 | return x == k.x && y == k.y && z == k.z; 60 | } 61 | }; 62 | 63 | namespace std { 64 | template <> 65 | struct hash { 66 | std::size_t operator()(const VertexKey& k) const { 67 | return ((std::hash()(k.x) ^ (std::hash()(k.y) << 1)) >> 1) ^ (hash()(k.z) << 1); 68 | } 69 | }; 70 | } 71 | 72 | struct EdgeKey { 73 | VertexKey v1; 74 | VertexKey v2; 75 | 76 | EdgeKey(const VertexKey &a, const VertexKey &b) { 77 | v1 = a; 78 | v2 = b; 79 | } 80 | 81 | bool operator==(const EdgeKey &k) const { 82 | return (v1 == k.v1 && v2 == k.v2); 83 | } 84 | }; 85 | 86 | namespace std { 87 | template<> 88 | struct hash { 89 | std::size_t operator()(const EdgeKey& k) const { 90 | return ((std::hash()(k.v1) ^ (std::hash()(k.v2) << 1)) >> 1); 91 | } 92 | }; 93 | } 94 | 95 | 96 | int main(int argc, char** argv) { 97 | if(argc >= 2) { 98 | if(strcmp(argv[1], "--help") == 0) { 99 | print_usage(); 100 | exit(2); 101 | } 102 | } 103 | int errflg = 0; 104 | int c; 105 | bool exactKeys = false; 106 | bool ignoreDegenerateFaces = false; 107 | 108 | while((c = getopt(argc, argv, "ei")) != -1) { 109 | switch(c) { 110 | case 'i': 111 | ignoreDegenerateFaces = true; 112 | break; 113 | case 'e': 114 | exactKeys = true; 115 | break; 116 | case '?': 117 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 118 | errflg++; 119 | break; 120 | } 121 | } 122 | 123 | if(errflg) { 124 | print_usage(); 125 | exit(2); 126 | } 127 | 128 | FILE *f; 129 | 130 | if(optind == argc-1) { 131 | char *file = argv[optind]; 132 | 133 | f = fopen(file, "rb"); 134 | if(!f) { 135 | fprintf(stderr, "Can't read file: %s\n", file); 136 | exit(2); 137 | } 138 | } else { 139 | f = stdin; 140 | } 141 | 142 | fseek(f, 80, SEEK_SET); 143 | uint32_t num_tris; 144 | uint16_t abc = 0; // attribute byte count 145 | 146 | size_t readBytes = fread(&num_tris, 4, 1, f); 147 | 148 | std::unordered_map edgeCounts; 149 | 150 | int ignoredFaces = 0; 151 | for(int i = 0; i < num_tris; i++) { 152 | vec normal; 153 | vec p0; 154 | vec p1; 155 | vec p2; 156 | 157 | readBytes = fread(&normal, 1, 12,f); 158 | readBytes = fread(&p0, 1, 12,f); 159 | readBytes = fread(&p1, 1, 12,f); 160 | readBytes = fread(&p2, 1, 12,f); 161 | readBytes = fread(&abc, 1, 2,f); 162 | 163 | if(ignoreDegenerateFaces) { 164 | vec vec1; 165 | vec vec2; 166 | 167 | vec1.x = p1.x-p0.x; 168 | vec1.y = p1.y-p0.y; 169 | vec1.z = p1.z-p0.z; 170 | 171 | vec2.x = p2.x-p0.x; 172 | vec2.y = p2.y-p0.y; 173 | vec2.z = p2.z-p0.z; 174 | 175 | vec cross; 176 | 177 | vec_cross(&vec1, &vec2, &cross); 178 | float area = .5*vec_magnitude(&cross); 179 | if(area < EPSILON) { 180 | ignoredFaces++; 181 | continue; 182 | } 183 | } 184 | 185 | VertexKey v0(p0.x, p0.y, p0.z, exactKeys); 186 | VertexKey v1(p1.x, p1.y, p1.z, exactKeys); 187 | VertexKey v2(p2.x, p2.y, p2.z, exactKeys); 188 | 189 | EdgeKey e0(v0,v1); 190 | EdgeKey e1(v1,v2); 191 | EdgeKey e2(v2,v0); 192 | 193 | if(edgeCounts.count(e0)) { 194 | edgeCounts[e0] = edgeCounts[e0] + 1; 195 | } else { 196 | edgeCounts[e0] = 1; 197 | } 198 | 199 | if(edgeCounts.count(e1)) { 200 | edgeCounts[e1] = edgeCounts[e1] + 1; 201 | } else { 202 | edgeCounts[e1] = 1; 203 | } 204 | 205 | if(edgeCounts.count(e2)) { 206 | edgeCounts[e2] = edgeCounts[e2] + 1; 207 | } else { 208 | edgeCounts[e2] = 1; 209 | } 210 | } 211 | 212 | std::unordered_map::iterator itr = edgeCounts.begin(); 213 | 214 | uint32_t borderEdges = 0; 215 | while(itr != edgeCounts.end()) { 216 | VertexKey v1 = itr->first.v1; 217 | VertexKey v2 = itr->first.v2; 218 | EdgeKey reverseKey(v2, v1); 219 | if(!edgeCounts.count(reverseKey) || itr->second > edgeCounts[reverseKey]) { 220 | if(edgeCounts.count(reverseKey)) { 221 | borderEdges += itr->second-edgeCounts[reverseKey]; 222 | } else { 223 | borderEdges += itr->second; 224 | } 225 | } 226 | ++itr; 227 | } 228 | 229 | std::cout << borderEdges << std::endl; 230 | 231 | return 0; 232 | } 233 | -------------------------------------------------------------------------------- /src/csgjs/math/Polygon3.cpp: -------------------------------------------------------------------------------- 1 | #include "csgjs/math/Polygon3.h" 2 | 3 | #include 4 | 5 | namespace csgjs { 6 | Polygon::Polygon(const std::vector &v, const Plane &p) : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false), vertices(v), plane(p) { 7 | #ifdef CSGJS_DEBUG 8 | if(!checkIfConvex()) { 9 | std::cout << "not convex " << *this << std::endl; 10 | // throw std::runtime_error("Not convex!"); 11 | } 12 | #endif 13 | } 14 | 15 | Polygon::Polygon(std::vector &&v, const Plane &p) : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false), vertices(v), plane(p) { 16 | #ifdef CSGJS_DEBUG 17 | if(!checkIfConvex()) { 18 | std::cout << "not convex " << *this << std::endl; 19 | // throw std::runtime_error("Not convex!"); 20 | } 21 | #endif 22 | } 23 | 24 | Polygon::Polygon(const std::vector &v) : vertices(v), _boundingSphereCacheValid(false), _boundingBoxCacheValid(false) { 25 | plane = Plane::fromVector3s(vertices[0].pos, vertices[1].pos, vertices[2].pos); 26 | #ifdef CSGJS_DEBUG 27 | if(!checkIfConvex()) { 28 | std::cout << "not convex " << *this << std::endl; 29 | // throw std::runtime_error("Not convex!"); 30 | } 31 | #endif 32 | } 33 | 34 | Polygon::Polygon() : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false) {} 35 | 36 | Polygon Polygon::flipped() const { 37 | std::vector newVertices; 38 | Plane newPlane = plane.flipped(); 39 | 40 | std::vector::const_reverse_iterator itr = vertices.rbegin(); 41 | while(itr != vertices.rend()) { 42 | newVertices.push_back(itr->flipped()); 43 | ++itr; 44 | } 45 | 46 | return Polygon(std::move(newVertices), newPlane); 47 | } 48 | 49 | bool Polygon::checkIfDegenerateTriangle() const { 50 | int numVertices = vertices.size(); 51 | if(numVertices == 3) { 52 | Vector3 v1 = (vertices[2].pos-vertices[0].pos); 53 | Vector3 v2 = (vertices[1].pos-vertices[0].pos); 54 | Vector3 v3 = (vertices[2].pos-vertices[1].pos); 55 | 56 | double a = v1.length(); 57 | double b = v2.length(); 58 | double c = v3.length(); 59 | 60 | if(a > c) { 61 | double tmp = c; 62 | c = a; 63 | a = tmp; 64 | } 65 | 66 | if(a > b) { 67 | double tmp = b; 68 | b = a; 69 | a = tmp; 70 | } 71 | 72 | if(b > c) { 73 | double tmp = c; 74 | c = b; 75 | b = tmp; 76 | } 77 | 78 | double d = a+b-c; 79 | 80 | return (d < EPS); 81 | } 82 | return false; 83 | } 84 | 85 | bool Polygon::checkIfConvex() const { 86 | int numVertices = vertices.size(); 87 | if(numVertices > 2) { 88 | Vector3 prevprevpos = vertices[numVertices-2].pos; 89 | Vector3 prevpos = vertices[numVertices-1].pos; 90 | for(int i = 0; i < numVertices; i++) { 91 | Vector3 pos = vertices[i].pos; 92 | if(!Polygon::isConvexPoint(prevprevpos, prevpos, pos, plane.normal)) { 93 | return false; 94 | } 95 | prevprevpos = prevpos; 96 | prevpos = pos; 97 | } 98 | } 99 | return true; 100 | } 101 | 102 | Polygon Polygon::transform(const Matrix4x4 &m) const { 103 | std::vector verts(vertices); 104 | std::vector::iterator itr = verts.begin(); 105 | while(itr != verts.end()) { 106 | *itr = itr->transform(m); 107 | ++itr; 108 | } 109 | 110 | if(m.isMirroring()) { 111 | std::reverse(verts.begin(), verts.end()); 112 | } 113 | 114 | return Polygon(std::move(verts), plane.transform(m)); 115 | } 116 | 117 | bool Polygon::isConvexPoint(const Vector3 &prevpoint, const Vector3 &point, const Vector3 &nextpoint, const Vector3 normal) { 118 | Vector3 crossproduct = (point-prevpoint).cross(nextpoint-point); 119 | csgjs_real crossdotnormal = crossproduct.dot(normal); 120 | return crossdotnormal >= 0; 121 | } 122 | 123 | // seems like this caching scheme could be an unnecessary optimization, but 124 | // this is how it was done in CSG.js, maybe try calculating the bounding box and sphere 125 | // in the constructor to avoid any branching (it probably makes sense in JavaScript, 126 | // but I question the benefit in C++). It would come down to how often polygons are 127 | // constructed without ever needing a bounding box or sphere, which I'm not sure about. 128 | std::pair Polygon::boundingBox() const { 129 | if(!_boundingBoxCacheValid) { 130 | std::vector::const_iterator itr = vertices.begin(); 131 | 132 | if(itr != vertices.end()) { 133 | _boundingBoxCache.first = itr->pos; 134 | _boundingBoxCache.second = itr->pos; 135 | 136 | while(itr != vertices.end()) { 137 | _boundingBoxCache.first = _boundingBoxCache.first.min(itr->pos); 138 | _boundingBoxCache.second = _boundingBoxCache.second.max(itr->pos); 139 | ++itr; 140 | } 141 | _boundingBoxCacheValid = true; 142 | 143 | } else { 144 | _boundingBoxCache.first = Vector3(0,0,0); 145 | _boundingBoxCache.second = Vector3(0,0,0); 146 | _boundingBoxCacheValid = true; 147 | } 148 | } 149 | 150 | return _boundingBoxCache; 151 | } 152 | 153 | std::pair Polygon::boundingSphere() const { 154 | if(!_boundingSphereCacheValid) { 155 | std::pair box = boundingBox(); 156 | _boundingSphereCache.first = .5*(box.first+box.second); 157 | _boundingSphereCache.second = (box.second-_boundingSphereCache.first).length(); 158 | _boundingSphereCacheValid = true; 159 | } 160 | 161 | return _boundingSphereCache; 162 | } 163 | 164 | PolygonEdgeData::PolygonEdgeData() : polygon(NULL) { 165 | } 166 | 167 | PolygonEdgeData::PolygonEdgeData(Polygon *p, const Vector3 &a, const Vector3 &b) : polygon(p), first(a), second(b) { 168 | } 169 | 170 | std::ostream& operator<<(std::ostream& os, const Polygon &poly) { 171 | os << "Polygon - vertices: { "; 172 | 173 | std::vector::const_iterator itr = poly.vertices.begin(); 174 | while(itr != poly.vertices.end()) { 175 | os << *itr; 176 | ++itr; 177 | 178 | if(itr != poly.vertices.end()) { 179 | os << ", "; 180 | } 181 | } 182 | os << " }, plane: { " << poly.plane << " }"; 183 | 184 | return os; 185 | } 186 | 187 | std::ostream& operator<<(std::ostream& os, const std::pair &bounds) { 188 | os << bounds.first << " - " << bounds.second; 189 | return os; 190 | } 191 | 192 | std::ostream& operator<<(std::ostream& os, const std::pair &bounds) { 193 | os << bounds.first << " - " << bounds.second; 194 | return os; 195 | } 196 | 197 | std::ostream& operator<<(std::ostream& os, const std::vector &vertices) { 198 | std::vector::const_iterator itr = vertices.begin(); 199 | while(itr != vertices.end()) { 200 | os << itr->pos << " "; 201 | ++itr; 202 | } 203 | return os; 204 | } 205 | } 206 | 207 | -------------------------------------------------------------------------------- /src/stl_cone.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | void print_usage() { 32 | fprintf(stderr, "stl_cone outputs an STL file of a single cone.\n\n"); 33 | fprintf(stderr, "usage: stl_cone [ -r ] [ -t ] [ -h ] [ -s ] [ ]\n"); 34 | fprintf(stderr, " Outputs an stl file of a cone with the provided radius, top radius, height and number of segments to approximate a circle.\n"); 35 | fprintf(stderr, " If the radius or height are omitted, they default to 1. The top radius defaults to 0. If top radius is greater than 0, will output a truncated code. If segments is omitted, it defaults to 32. If no output file is provided, data is sent to stdout. \n"); 36 | } 37 | 38 | int main(int argc, char** argv) { 39 | if(argc >= 2) { 40 | if(strcmp(argv[1], "--help") == 0) { 41 | print_usage(); 42 | exit(2); 43 | } 44 | } 45 | int errflg = 0; 46 | int c; 47 | 48 | float radius = 1; 49 | float topRadius = 0; 50 | float height = 1; 51 | int segments = 32; 52 | 53 | while((c = getopt(argc, argv, "r:h:s:t:")) != -1) { 54 | switch(c) { 55 | case 'r': 56 | radius = atof(optarg); 57 | break; 58 | case 't': 59 | topRadius = atof(optarg); 60 | break; 61 | case 'h': 62 | height = atof(optarg); 63 | break; 64 | case 's': 65 | segments = atoi(optarg); 66 | break; 67 | case '?': 68 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 69 | errflg++; 70 | break; 71 | } 72 | } 73 | 74 | if(errflg) { 75 | print_usage(); 76 | exit(2); 77 | } 78 | 79 | FILE *outf; 80 | 81 | if(optind == argc-1) { 82 | char *file = argv[optind]; 83 | 84 | outf = fopen(file, "wb"); 85 | if(!outf) { 86 | fprintf(stderr, "Can't write to file: %s\n", file); 87 | exit(2); 88 | } 89 | } else { 90 | outf = stdout; 91 | } 92 | 93 | char header[81] = {0}; 94 | snprintf(header, 81, "Cone with radius %.4f, top radius %.4f and height %.4f", radius, topRadius, height); 95 | 96 | fwrite(header, 80, 1, outf); 97 | uint32_t num_tris; 98 | uint16_t abc = 0; // attribute byte count 99 | vec p0; 100 | vec p1; 101 | vec p2; 102 | vec p3; 103 | 104 | if(topRadius > 0) { 105 | // caps sides 106 | num_tris = 2*(segments-2)+2*segments; 107 | 108 | fwrite(&num_tris, 4, 1, outf); 109 | 110 | for(int i = 0; i < segments; i++) { 111 | float angle = 2*M_PI*i/segments; 112 | float angle2 = 2*M_PI*(i+1)/segments; 113 | if(i == segments-1) { 114 | angle2 = 0; 115 | } 116 | float cosa = cos(angle); 117 | float sina = sin(angle); 118 | 119 | float cosa2 = cos(angle2); 120 | float sina2 = sin(angle2); 121 | 122 | p0.x = topRadius*cosa; 123 | p0.y = topRadius*sina; 124 | p0.z = height*.5; 125 | 126 | p1.x = radius*cosa; 127 | p1.y = radius*sina; 128 | p1.z = -height*.5; 129 | 130 | p2.x = radius*cosa2; 131 | p2.y = radius*sina2; 132 | p2.z = -height*.5; 133 | 134 | p3.x = topRadius*cosa2; 135 | p3.y = topRadius*sina2; 136 | p3.z = height*.5; 137 | 138 | write_quad(outf, &p0, &p1, &p2, &p3, 0); 139 | } 140 | 141 | for(int i = 1; i < segments-1; i++) { 142 | float angle = 2*M_PI*i/segments; 143 | float angle2 = 2*M_PI*(i+1)/segments; 144 | float cosa = cos(angle); 145 | float sina = sin(angle); 146 | 147 | float cosa2 = cos(angle2); 148 | float sina2 = sin(angle2); 149 | 150 | p0.x = topRadius; 151 | p0.y = 0; 152 | p0.z = height*.5; 153 | 154 | p1.x = topRadius*cosa; 155 | p1.y = topRadius*sina; 156 | p1.z = height*.5; 157 | 158 | p2.x = topRadius*cosa2; 159 | p2.y = topRadius*sina2; 160 | p2.z = height*.5; 161 | 162 | write_tri(outf, &p0, &p1, &p2, 0); 163 | 164 | p0.x = radius; 165 | p0.y = 0; 166 | p0.z = -height*.5; 167 | 168 | p1.x = radius*cosa; 169 | p1.y = radius*sina; 170 | p1.z = -height*.5; 171 | 172 | p2.x = radius*cosa2; 173 | p2.y = radius*sina2; 174 | p2.z = -height*.5; 175 | 176 | write_tri(outf, &p0, &p1, &p2, 1); 177 | } 178 | } else { 179 | // cap side 180 | num_tris = (segments-2)+segments; 181 | 182 | fwrite(&num_tris, 4, 1, outf); 183 | 184 | for(int i = 0; i < segments; i++) { 185 | float angle = 2*M_PI*i/segments; 186 | float angle2 = 2*M_PI*(i+1)/segments; 187 | float cosa = cos(angle); 188 | float sina = sin(angle); 189 | 190 | float cosa2 = cos(angle2); 191 | float sina2 = sin(angle2); 192 | 193 | p0.x = 0; 194 | p0.y = 0; 195 | p0.z = height*.5; 196 | 197 | p1.x = radius*cosa; 198 | p1.y = radius*sina; 199 | p1.z = -height*.5; 200 | 201 | p2.x = radius*cosa2; 202 | p2.y = radius*sina2; 203 | p2.z = -height*.5; 204 | 205 | write_tri(outf, &p0, &p1, &p2, 0); 206 | } 207 | 208 | for(int i = 1; i < segments-1; i++) { 209 | float angle = 2*M_PI*i/segments; 210 | float angle2 = 2*M_PI*(i+1)/segments; 211 | float cosa = cos(angle); 212 | float sina = sin(angle); 213 | 214 | float cosa2 = cos(angle2); 215 | float sina2 = sin(angle2); 216 | 217 | p0.x = radius; 218 | p0.y = 0; 219 | p0.z = -height*.5; 220 | 221 | p1.x = radius*cosa; 222 | p1.y = radius*sina; 223 | p1.z = -height*.5; 224 | 225 | p2.x = radius*cosa2; 226 | p2.y = radius*sina2; 227 | p2.z = -height*.5; 228 | 229 | write_tri(outf, &p0, &p1, &p2, 1); 230 | } 231 | } 232 | 233 | return 0; 234 | } 235 | -------------------------------------------------------------------------------- /src/stl_normals.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include "stl_util.h" 27 | 28 | #define BUFFER_SIZE 4096 29 | 30 | void print_usage() { 31 | fprintf(stderr, "stl_normals inspects and modifies normal data of an STL file.\n\n"); 32 | fprintf(stderr, "usage: stl_normals [ -c ] [ -r ] [ -v ] [ ]\n"); 33 | fprintf(stderr, " Checks the stored normals against calculated normals based on ordering of vertices.\n" 34 | " -c - if present will ignore the present normal values and calculate them based on the vertex ordering.\n" 35 | " -r - if present will reverse the winding order of the vertices.\n" 36 | " -w - if present will correct the winding order of the vertices based on the direction of the stored normal.\n" 37 | " -v - be verboze when printing out differing normals\n"); 38 | } 39 | 40 | int main(int argc, char** argv) { 41 | if(argc >= 2) { 42 | if(strcmp(argv[1], "--help") == 0) { 43 | print_usage(); 44 | exit(2); 45 | } 46 | } 47 | int c; 48 | int errflg = 0; 49 | char *out_file; 50 | char *in_file; 51 | int calc = 0; 52 | int reverse = 0; 53 | int needs_out = 0; 54 | int verbose = 0; 55 | int calc_winding = 0; 56 | 57 | if(argc == 1) { 58 | print_usage(); 59 | exit(2); 60 | } 61 | 62 | while((c = getopt(argc, argv, "vcrw")) != -1) { 63 | switch(c) { 64 | case 'c': 65 | calc = 1; 66 | needs_out = 1; 67 | break; 68 | case 'v': 69 | verbose = 1; 70 | break; 71 | case 'r': 72 | reverse = 1; 73 | needs_out = 1; 74 | break; 75 | case 'w': 76 | calc_winding = 1; 77 | needs_out = 1; 78 | break; 79 | case '?': 80 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 81 | errflg++; 82 | break; 83 | } 84 | } 85 | 86 | if(errflg) { 87 | print_usage(); 88 | exit(2); 89 | } 90 | 91 | FILE *inf; 92 | FILE *outf; 93 | 94 | if(optind < argc) { 95 | in_file = argv[optind]; 96 | 97 | char name[100]; 98 | snprintf(name, sizeof(name), "%s", in_file); 99 | 100 | if(!is_valid_binary_stl(in_file)) { 101 | fprintf(stderr, "%s is not a binary stl file.\n", name); 102 | exit(2); 103 | } 104 | 105 | inf = fopen(in_file, "rb"); 106 | if(!inf) { 107 | fprintf(stderr, "Can't read file: %s\n", name); 108 | exit(2); 109 | } 110 | fseek(inf, 80, SEEK_SET); // skip header 111 | 112 | if(optind+1 < argc) { 113 | out_file = argv[optind+1]; 114 | 115 | snprintf(name, sizeof(name), "%s", out_file); 116 | 117 | outf = fopen(out_file, "wb"); 118 | if(!outf) { 119 | fprintf(stderr, "Can't write to file: %s\n", name); 120 | } 121 | } else { 122 | outf = stdout; 123 | } 124 | } else { 125 | print_usage(); 126 | exit(2); 127 | } 128 | 129 | fseek(inf, 0, SEEK_SET); 130 | 131 | char header[80] = {0}; 132 | size_t readBytes = fread(header, 1, 80, inf); 133 | 134 | uint16_t zero = 0; 135 | uint16_t abc; 136 | uint32_t num_tris; 137 | readBytes = fread(&num_tris, 4, 1, inf); 138 | 139 | if(needs_out) { 140 | fwrite(header, 1, 80, outf); 141 | fwrite(&num_tris, 1, 4, outf); 142 | } 143 | 144 | vec p1,p2,p3; 145 | vec n,cn; 146 | p1.w = 1; 147 | p2.w = 1; 148 | p3.w = 1; 149 | n.w = 0; 150 | cn.w = 0; 151 | 152 | vec d1,d2; 153 | d1.w = 0; 154 | d2.w = 0; 155 | 156 | int match = 1; 157 | 158 | if(verbose) { 159 | fprintf(stderr, "reading %d triangles and normals\n", num_tris); 160 | } 161 | for(int i = 0; i < num_tris; i++) { 162 | readBytes = fread(&n, 1, 12, inf); 163 | readBytes = fread(&p1, 1, 12, inf); 164 | readBytes = fread(&p2, 1, 12, inf); 165 | readBytes = fread(&p3, 1, 12, inf); 166 | readBytes = fread(&abc, 1, 2, inf); 167 | 168 | vec_sub(&p2, &p1, &d1); 169 | vec_sub(&p3, &p1, &d2); 170 | vec_cross(&d1, &d2, &cn); 171 | if(cn.x != 0 || 172 | cn.y != 0 || 173 | cn.z != 0) { 174 | vec_normalize(&cn, &cn); 175 | } 176 | if(vec_dot(&cn, &n) < 0) { 177 | match = 0; 178 | if(verbose) { 179 | fprintf(stderr, "calculated normal %d different than input normal\n", i); 180 | fprintf(stderr, "calculated: %f, %f, %f\n", cn.x, cn.y, cn.z); 181 | fprintf(stderr, "input: %f, %f, %f\n", n.x, n.y, n.z); 182 | } 183 | } 184 | 185 | const float dot = vec_dot(&cn, &n); 186 | 187 | if(needs_out) { 188 | if(calc) { 189 | if(reverse || 190 | (calc_winding && dot <= 0)) { 191 | cn.x *= -1; 192 | cn.y *= -1; 193 | cn.z *= -1; 194 | } 195 | fwrite(&cn, 1, 12, outf); 196 | } else { 197 | fwrite(&n, 1, 12, outf); 198 | } 199 | 200 | if(reverse) { 201 | fwrite(&p3, 1, 12, outf); 202 | fwrite(&p2, 1, 12, outf); 203 | fwrite(&p1, 1, 12, outf); 204 | } else if(calc_winding) { 205 | if(dot > 0) { 206 | fwrite(&p1, 1, 12, outf); 207 | fwrite(&p2, 1, 12, outf); 208 | fwrite(&p3, 1, 12, outf); 209 | } else { 210 | fwrite(&p3, 1, 12, outf); 211 | fwrite(&p2, 1, 12, outf); 212 | fwrite(&p1, 1, 12, outf); 213 | } 214 | } else { 215 | fwrite(&p1, 1, 12, outf); 216 | fwrite(&p2, 1, 12, outf); 217 | fwrite(&p3, 1, 12, outf); 218 | } 219 | fwrite(&abc, 1, 2, outf); 220 | } 221 | } 222 | 223 | if(!needs_out) { 224 | if(match) { 225 | fprintf(stderr, "Normals match calculated normals.\n"); 226 | } else { 227 | fprintf(stderr, "Normals do NOT match calculated normals.\n"); 228 | } 229 | } 230 | 231 | return 0; 232 | } 233 | -------------------------------------------------------------------------------- /src/stl_cylinders.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2020 by Allwine Designs (stl_cmd@allwinedesigns.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include "stl_util.h" 29 | 30 | #define BUFFER_SIZE 4096 31 | 32 | void print_usage() { 33 | fprintf(stderr, "stl_cylinders outputs an STL file with multiple cylinders defined by a custom binary input file.\n\n"); 34 | fprintf(stderr, "usage: stl_cylinders [ -r ] [ -s ] \n"); 35 | fprintf(stderr, " Outputs an stl file made up of N cylinders defined by start and end points in the input file each with the specified\n"); 36 | fprintf(stderr, " radius and number of segments provided on the command line. The first 4 bytes of the input file represent how many \n"); 37 | fprintf(stderr, " cylinders to generate, N. The rest of the input file defines start and end points that define a line segment of the\n"); 38 | fprintf(stderr, " the central axis of the cylinder. Each segment is defined by 6, 4 byte floats. The first three are the X,Y,Z values\n"); 39 | fprintf(stderr, " of the start point and the second three are the X,Y,Z values of the end point.\n"); 40 | fprintf(stderr, " If the radius is omitted, it defaults to 1. If segments is omitted, it defaults to 32.\n"); 41 | } 42 | 43 | void write_cylinder(FILE *outf, const vec &pt1, const vec &pt2, float radius, int segments) { 44 | vec p0; 45 | vec p1; 46 | vec p2; 47 | vec p3; 48 | 49 | vec dp; 50 | vec x; 51 | vec y; 52 | vec z; 53 | 54 | dp.x = pt2.x-pt1.x; 55 | dp.y = pt2.y-pt1.y; 56 | dp.z = pt2.z-pt1.z; 57 | 58 | vec_normalize(&dp, &z); 59 | 60 | vec up = { 0, 1, 0 }; 61 | vec_cross(&up, &z, &x); 62 | 63 | float magX = vec_magnitude(&x); 64 | 65 | if(magX < .0001) { 66 | x.x = 1; 67 | x.y = 0; 68 | x.z = 0; 69 | 70 | z.x = 0; 71 | z.y = 1; 72 | z.z = 0; 73 | } else { 74 | vec_normalize(&x, &x); 75 | } 76 | vec_cross(&z, &x, &y); 77 | 78 | for(int i = 0; i < segments; i++) { 79 | float angle = 2*M_PI*i/segments; 80 | float angle2 = 2*M_PI*(i+1)/segments; 81 | if(i == segments-1) { 82 | angle2 = 0; 83 | } 84 | float cosa = cos(angle); 85 | float sina = sin(angle); 86 | 87 | float cosa2 = cos(angle2); 88 | float sina2 = sin(angle2); 89 | 90 | float circleX = radius*cosa*x.x+radius*sina*y.x; 91 | float circleY = radius*cosa*x.y+radius*sina*y.y; 92 | float circleZ = radius*cosa*x.z+radius*sina*y.z; 93 | 94 | float circleX2 = radius*cosa2*x.x+radius*sina2*y.x; 95 | float circleY2 = radius*cosa2*x.y+radius*sina2*y.y; 96 | float circleZ2 = radius*cosa2*x.z+radius*sina2*y.z; 97 | 98 | p0.x = circleX+pt2.x; 99 | p0.y = circleY+pt2.y; 100 | p0.z = circleZ+pt2.z; 101 | 102 | p1.x = circleX+pt1.x; 103 | p1.y = circleY+pt1.y; 104 | p1.z = circleZ+pt1.z; 105 | 106 | p2.x = circleX2+pt1.x; 107 | p2.y = circleY2+pt1.y; 108 | p2.z = circleZ2+pt1.z; 109 | 110 | p3.x = circleX2+pt2.x; 111 | p3.y = circleY2+pt2.y; 112 | p3.z = circleZ2+pt2.z; 113 | 114 | write_quad(outf, &p0, &p1, &p2, &p3, 0); 115 | } 116 | 117 | for(int i = 1; i < segments-1; i++) { 118 | float angle = 2*M_PI*i/segments; 119 | float angle2 = 2*M_PI*(i+1)/segments; 120 | float cosa = cos(angle); 121 | float sina = sin(angle); 122 | 123 | float cosa2 = cos(angle2); 124 | float sina2 = sin(angle2); 125 | 126 | float circleX = radius*cosa*x.x+radius*sina*y.x; 127 | float circleY = radius*cosa*x.y+radius*sina*y.y; 128 | float circleZ = radius*cosa*x.z+radius*sina*y.z; 129 | 130 | float circleX2 = radius*cosa2*x.x+radius*sina2*y.x; 131 | float circleY2 = radius*cosa2*x.y+radius*sina2*y.y; 132 | float circleZ2 = radius*cosa2*x.z+radius*sina2*y.z; 133 | 134 | p0.x = radius*x.x+pt2.x; 135 | p0.y = radius*x.y+pt2.y; 136 | p0.z = radius*x.z+pt2.z; 137 | 138 | p1.x = circleX+pt2.x; 139 | p1.y = circleY+pt2.y; 140 | p1.z = circleZ+pt2.z; 141 | 142 | p2.x = circleX2+pt2.x; 143 | p2.y = circleY2+pt2.y; 144 | p2.z = circleZ2+pt2.z; 145 | 146 | write_tri(outf, &p0, &p1, &p2, 0); 147 | 148 | p0.x = radius*x.x+pt1.x; 149 | p0.y = radius*x.y+pt1.y; 150 | p0.z = radius*x.z+pt1.z; 151 | 152 | p1.x = circleX+pt1.x; 153 | p1.y = circleY+pt1.y; 154 | p1.z = circleZ+pt1.z; 155 | 156 | p2.x = circleX2+pt1.x; 157 | p2.y = circleY2+pt1.y; 158 | p2.z = circleZ2+pt1.z; 159 | 160 | write_tri(outf, &p0, &p1, &p2, 1); 161 | } 162 | } 163 | 164 | int main(int argc, char** argv) { 165 | if(argc >= 2) { 166 | if(strcmp(argv[1], "--help") == 0) { 167 | print_usage(); 168 | exit(2); 169 | } 170 | } 171 | int errflg = 0; 172 | int c; 173 | 174 | float radius = 1; 175 | int segments = 32; 176 | 177 | while((c = getopt(argc, argv, "r:h:s:")) != -1) { 178 | switch(c) { 179 | 180 | case 'r': 181 | radius = atof(optarg); 182 | break; 183 | case 's': 184 | segments = atoi(optarg); 185 | break; 186 | case '?': 187 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 188 | errflg++; 189 | break; 190 | } 191 | } 192 | 193 | if(errflg) { 194 | print_usage(); 195 | exit(2); 196 | } 197 | 198 | FILE *inf; 199 | FILE *outf; 200 | 201 | if(optind == argc-2) { 202 | char *file = argv[optind]; 203 | 204 | inf = fopen(file, "rb"); 205 | if(!inf) { 206 | fprintf(stderr, "Can't read file: %s\n", file); 207 | exit(2); 208 | } 209 | 210 | file = argv[optind+1]; 211 | 212 | outf = fopen(file, "wb"); 213 | if(!outf) { 214 | fprintf(stderr, "Can't write to file: %s\n", file); 215 | exit(2); 216 | } 217 | } else { 218 | print_usage(); 219 | exit(2); 220 | } 221 | 222 | char header[81] = {0}; 223 | snprintf(header, 81, "stl_cylinders"); 224 | 225 | fwrite(header, 80, 1, outf); 226 | 227 | uint32_t num_cylinders; 228 | size_t readBytes = fread(&num_cylinders, 4, 1, inf); 229 | 230 | // caps tube 231 | uint32_t num_tris = num_cylinders*(2*(segments-2)+2*segments); 232 | 233 | fwrite(&num_tris, 4, 1, outf); 234 | 235 | uint16_t abc = 0; // attribute byte count 236 | 237 | vec p1; 238 | vec p2; 239 | 240 | for(uint32_t i = 0; i < num_cylinders; i++) { 241 | readBytes = fread(&p1.x, 4, 1, inf); 242 | readBytes = fread(&p1.y, 4, 1, inf); 243 | readBytes = fread(&p1.z, 4, 1, inf); 244 | readBytes = fread(&p2.x, 4, 1, inf); 245 | readBytes = fread(&p2.y, 4, 1, inf); 246 | readBytes = fread(&p2.z, 4, 1, inf); 247 | write_cylinder(outf, p1, p2, radius, segments); 248 | } 249 | 250 | return 0; 251 | } 252 | 253 | -------------------------------------------------------------------------------- /src/stl_convex.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #define BUFFER_SIZE 4096 34 | 35 | void print_usage() { 36 | fprintf(stderr, "stl_convex prints whether an STL file is a convex polyhedron.\n\n"); 37 | fprintf(stderr, "usage: stl_convex [ -v ] [ ]\n"); 38 | fprintf(stderr, " Prints whether the input file is a convex polyhedron. If no input file is specified, data is read from stdin. If -v is specified, prints out the Euler characteristic in addition to whether the mesh is convex.\n"); 39 | fprintf(stderr, "The Euler characteristic of a polyhedral surface is defined as V - E + F, where V is the number of vertices, E is the number of edges, and F is the number of faces. All convex polyhedra will have an Euler characteristic of 2.\n"); 40 | } 41 | 42 | #define EPS .000001 43 | struct VertexKey { 44 | int x; 45 | int y; 46 | int z; 47 | VertexKey() : x(0), y(0), z(0) {} 48 | VertexKey(float xx, float yy, float zz) { 49 | x = (int)(std::round((double)xx/EPS)); 50 | y = (int)(std::round((double)yy/EPS)); 51 | z = (int)(std::round((double)zz/EPS)); 52 | } 53 | 54 | bool operator==(const VertexKey& k) const { 55 | return x == k.x && y == k.y && z == k.z; 56 | } 57 | }; 58 | 59 | namespace std { 60 | template <> 61 | struct hash { 62 | std::size_t operator()(const VertexKey& k) const { 63 | return ((std::hash()(k.x) ^ (std::hash()(k.y) << 1)) >> 1) ^ (hash()(k.z) << 1); 64 | } 65 | }; 66 | } 67 | 68 | struct EdgeKey { 69 | VertexKey v1; 70 | VertexKey v2; 71 | 72 | EdgeKey(const VertexKey &a, const VertexKey &b) { 73 | if(a.x < b.x) { 74 | v1 = a; 75 | v2 = b; 76 | } else if(a.x > b.x) { 77 | v2 = a; 78 | v1 = b; 79 | } else { 80 | if(a.y < b.y) { 81 | v1 = a; 82 | v2 = b; 83 | } else if(a.y > b.y) { 84 | v2 = a; 85 | v1 = b; 86 | } else { 87 | if(a.z < b.z) { 88 | v1 = a; 89 | v2 = b; 90 | } else if(a.z > b.z) { 91 | v2 = a; 92 | v1 = b; 93 | } else { 94 | v1 = a; 95 | v2 = b; 96 | } 97 | } 98 | } 99 | } 100 | 101 | bool operator==(const EdgeKey &k) const { 102 | return (v1 == k.v1 && v2 == k.v2); 103 | } 104 | }; 105 | 106 | namespace std { 107 | template<> 108 | struct hash { 109 | std::size_t operator()(const EdgeKey& k) const { 110 | return ((std::hash()(k.v1) ^ (std::hash()(k.v2) << 1)) >> 1); 111 | } 112 | }; 113 | } 114 | 115 | 116 | int main(int argc, char** argv) { 117 | if(argc >= 2) { 118 | if(strcmp(argv[1], "--help") == 0) { 119 | print_usage(); 120 | exit(2); 121 | } 122 | } 123 | int errflg = 0; 124 | int c; 125 | 126 | int verbose = 0; 127 | 128 | while((c = getopt(argc, argv, "v")) != -1) { 129 | switch(c) { 130 | case 'v': 131 | verbose = 1; 132 | break; 133 | case '?': 134 | fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); 135 | errflg++; 136 | break; 137 | } 138 | } 139 | 140 | if(errflg) { 141 | print_usage(); 142 | exit(2); 143 | } 144 | 145 | FILE *f; 146 | 147 | if(optind == argc-1) { 148 | char *file = argv[optind]; 149 | 150 | f = fopen(file, "rb"); 151 | if(!f) { 152 | fprintf(stderr, "Can't read file: %s\n", file); 153 | exit(2); 154 | } 155 | } else { 156 | f = stdin; 157 | } 158 | 159 | fseek(f, 80, SEEK_SET); 160 | uint32_t num_tris; 161 | uint16_t abc = 0; // attribute byte count 162 | 163 | size_t readBytes = fread(&num_tris, 4, 1, f); 164 | 165 | std::unordered_map> verts2normals; 166 | std::unordered_map> verts2edges; 167 | std::unordered_set edgesSeen; 168 | 169 | for(int i = 0; i < num_tris; i++) { 170 | vec normal; 171 | vec p0; 172 | vec p1; 173 | vec p2; 174 | 175 | readBytes = fread(&normal, 1, 12,f); 176 | readBytes = fread(&p0, 1, 12,f); 177 | readBytes = fread(&p1, 1, 12,f); 178 | readBytes = fread(&p2, 1, 12,f); 179 | readBytes = fread(&abc, 1, 2,f); 180 | 181 | VertexKey v0(p0.x, p0.y, p0.z); 182 | VertexKey v1(p1.x, p1.y, p1.z); 183 | VertexKey v2(p2.x, p2.y, p2.z); 184 | 185 | verts2normals[v0].push_back(normal); 186 | verts2normals[v1].push_back(normal); 187 | verts2normals[v2].push_back(normal); 188 | 189 | vec e; 190 | 191 | e.x = p1.x-p0.x; 192 | e.y = p1.y-p0.y; 193 | e.z = p1.z-p0.z; 194 | 195 | verts2edges[v0].push_back(e); 196 | 197 | e.x = p2.x-p0.x; 198 | e.y = p2.y-p0.y; 199 | e.z = p2.z-p0.z; 200 | 201 | verts2edges[v0].push_back(e); 202 | 203 | e.x = p0.x-p1.x; 204 | e.y = p0.y-p1.y; 205 | e.z = p0.z-p1.z; 206 | 207 | verts2edges[v1].push_back(e); 208 | 209 | e.x = p2.x-p1.x; 210 | e.y = p2.y-p1.y; 211 | e.z = p2.z-p1.z; 212 | 213 | verts2edges[v1].push_back(e); 214 | 215 | e.x = p0.x-p2.x; 216 | e.y = p0.y-p2.y; 217 | e.z = p0.z-p2.z; 218 | 219 | verts2edges[v2].push_back(e); 220 | 221 | e.x = p1.x-p2.x; 222 | e.y = p1.y-p2.y; 223 | e.z = p1.z-p2.z; 224 | 225 | verts2edges[v2].push_back(e); 226 | 227 | edgesSeen.insert(EdgeKey(v0, v1)); 228 | edgesSeen.insert(EdgeKey(v1, v2)); 229 | edgesSeen.insert(EdgeKey(v2, v0)); 230 | } 231 | 232 | int V = verts2normals.size(); 233 | int E = edgesSeen.size(); 234 | int F = num_tris; 235 | 236 | int euler_characteristic = V - E + F; 237 | 238 | if(verbose) { 239 | std::cout << "V = " << V << std::endl; 240 | std::cout << "E = " << E << std::endl; 241 | std::cout << "F = " << F << std::endl; 242 | std::cout << "V - E + F = " << euler_characteristic << std::endl; 243 | } 244 | 245 | if(euler_characteristic == 2) { 246 | if(verbose) { 247 | std::cout << "Euler characteristic of 2... possibly convex" << std::endl; 248 | } 249 | 250 | std::unordered_map>::iterator itr = verts2edges.begin(); 251 | while(itr != verts2edges.end()) { 252 | std::vector::iterator nItr = verts2normals[itr->first].begin(); 253 | while(nItr != verts2normals[itr->first].end()) { 254 | std::vector::iterator vItr = itr->second.begin(); 255 | while(vItr != itr->second.end()) { 256 | if(vec_dot(&(*vItr), &(*nItr)) > EPSILON) { 257 | if(verbose) { 258 | std::cout << "found vertex with non convex edge" << std::endl; 259 | } 260 | std::cout << "not convex" << std:: endl; 261 | exit(0); 262 | } 263 | ++vItr; 264 | } 265 | ++nItr; 266 | } 267 | ++itr; 268 | 269 | } 270 | 271 | std::cout << "convex" << std:: endl; 272 | } else { 273 | if(verbose) { 274 | std::cout << "Euler characteristic of " << euler_characteristic << "..." << std::endl; 275 | } 276 | std::cout << "not convex" << std:: endl; 277 | } 278 | 279 | return 0; 280 | } 281 | -------------------------------------------------------------------------------- /src/stl_transform.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 4 | 5 | This file is part of stl_cmd. 6 | 7 | stl_cmd is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along with this program. If not, see . 19 | 20 | */ 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include "stl_util.h" 28 | 29 | #define BUFFER_SIZE 4096 30 | 31 | // TODO make input and output file optional, if not specified read from 32 | // stdin and write to stdout. Add to other stl_cmds as well. This will 33 | // allow for piping between stl_cmds which could elimate some temporary files: 34 | // stl_cube -w 1 | stl_transform -tx 10 > cube.stl 35 | // stl_cube -w 2 | stl_transform -tx 20 > cube2.stl 36 | // stl_merge *.stl | transform -s 10 > all_cubes_scaled.stl 37 | 38 | void print_usage() { 39 | fprintf(stderr, "stl_transform performs any number of transformations to an STL file.\n\n"); 40 | fprintf(stderr, "usage: stl_transform [[ ] ...] \n"); 41 | fprintf(stderr, " Performs any number of the following transformations in\n"); 42 | fprintf(stderr, " the order they are listed on the command line:\n"); 43 | fprintf(stderr, " -rx - rotates degrees about the x-axis\n"); 44 | fprintf(stderr, " -ry - rotates degrees about the y-axis\n"); 45 | fprintf(stderr, " -rz - rotates degrees about the z-axis\n"); 46 | fprintf(stderr, " -s - uniformly scales x, y and z by (cannot be 0)\n"); 47 | fprintf(stderr, " -sx - scales by in x (cannot be 0)\n"); 48 | fprintf(stderr, " -sy - scales by in y (cannot be 0)\n"); 49 | fprintf(stderr, " -sz - scales by in z (cannot be 0)\n"); 50 | fprintf(stderr, " -tx - translates units in x\n"); 51 | fprintf(stderr, " -ty - translates units in y\n"); 52 | fprintf(stderr, " -tz - translates units in z\n"); 53 | } 54 | 55 | int main(int argc, char** argv) { 56 | if(argc >= 2) { 57 | if(strcmp(argv[1], "--help") == 0) { 58 | print_usage(); 59 | exit(2); 60 | } 61 | } 62 | int errflg = 0; 63 | int did_scale = 0; 64 | 65 | mat tmp; 66 | mat tmp2; 67 | mat combined; 68 | mat inv_combined; 69 | mat inv_transpose; 70 | 71 | init_identity_mat(&combined); 72 | init_identity_mat(&inv_combined); 73 | 74 | int index; 75 | float arg; 76 | // TODO better arg handling so better errors can be displayed 77 | for(index = 1; index < argc; index++) { 78 | if(strcmp("-rx", argv[index]) == 0) { 79 | index++; 80 | if(index >= argc) break; 81 | arg = atof(argv[index]); 82 | init_rx_mat(&tmp, arg); 83 | mat_copy(&combined, &tmp2); 84 | mat_mult(&tmp2, &tmp, &combined); 85 | 86 | init_inv_rx_mat(&tmp, arg); 87 | mat_copy(&inv_combined, &tmp2); 88 | mat_mult(&tmp, &tmp2, &inv_combined); 89 | } else if(strcmp("-ry", argv[index]) == 0) { 90 | index++; 91 | if(index >= argc) break; 92 | arg = atof(argv[index]); 93 | init_ry_mat(&tmp, arg); 94 | mat_copy(&combined, &tmp2); 95 | mat_mult(&tmp2, &tmp, &combined); 96 | 97 | init_inv_ry_mat(&tmp, arg); 98 | mat_copy(&inv_combined, &tmp2); 99 | mat_mult(&tmp, &tmp2, &inv_combined); 100 | } else if(strcmp("-rz", argv[index]) == 0) { 101 | index++; 102 | if(index >= argc) break; 103 | arg = atof(argv[index]); 104 | init_rz_mat(&tmp, arg); 105 | mat_copy(&combined, &tmp2); 106 | mat_mult(&tmp2, &tmp, &combined); 107 | 108 | init_inv_rz_mat(&tmp, arg); 109 | mat_copy(&inv_combined, &tmp2); 110 | mat_mult(&tmp, &tmp2, &inv_combined); 111 | } else if(strcmp("-s", argv[index]) == 0) { 112 | index++; 113 | if(index >= argc) break; 114 | did_scale = 1; 115 | arg = atof(argv[index]); 116 | if(arg == 0) { 117 | errflg++; 118 | } else { 119 | init_s_mat(&tmp, arg); 120 | mat_copy(&combined, &tmp2); 121 | mat_mult(&tmp2, &tmp, &combined); 122 | 123 | init_inv_s_mat(&tmp, arg); 124 | mat_copy(&inv_combined, &tmp2); 125 | mat_mult(&tmp, &tmp2, &inv_combined); 126 | } 127 | } else if(strcmp("-sx", argv[index]) == 0) { 128 | index++; 129 | if(index >= argc) break; 130 | did_scale = 1; 131 | arg = atof(argv[index]); 132 | if(arg == 0) { 133 | errflg++; 134 | } else { 135 | init_sx_mat(&tmp, arg); 136 | mat_copy(&combined, &tmp2); 137 | mat_mult(&tmp2, &tmp, &combined); 138 | 139 | init_inv_sx_mat(&tmp, arg); 140 | mat_copy(&inv_combined, &tmp2); 141 | mat_mult(&tmp, &tmp2, &inv_combined); 142 | } 143 | } else if(strcmp("-sy", argv[index]) == 0) { 144 | index++; 145 | if(index >= argc) break; 146 | did_scale = 1; 147 | arg = atof(argv[index]); 148 | if(arg == 0) { 149 | errflg++; 150 | } else { 151 | init_sy_mat(&tmp, arg); 152 | mat_copy(&combined, &tmp2); 153 | mat_mult(&tmp2, &tmp, &combined); 154 | 155 | init_inv_sy_mat(&tmp, arg); 156 | mat_copy(&inv_combined, &tmp2); 157 | mat_mult(&tmp, &tmp2, &inv_combined); 158 | } 159 | } else if(strcmp("-sz", argv[index]) == 0) { 160 | index++; 161 | if(index >= argc) break; 162 | did_scale = 1; 163 | arg = atof(argv[index]); 164 | if(arg == 0) { 165 | errflg++; 166 | } else { 167 | init_sz_mat(&tmp, arg); 168 | mat_copy(&combined, &tmp2); 169 | mat_mult(&tmp2, &tmp, &combined); 170 | 171 | init_inv_sz_mat(&tmp, arg); 172 | mat_copy(&inv_combined, &tmp2); 173 | mat_mult(&tmp, &tmp2, &inv_combined); 174 | } 175 | } else if(strcmp("-tx", argv[index]) == 0) { 176 | index++; 177 | if(index >= argc) break; 178 | arg = atof(argv[index]); 179 | init_tx_mat(&tmp, arg); 180 | mat_copy(&combined, &tmp2); 181 | mat_mult(&tmp2, &tmp, &combined); 182 | 183 | init_inv_tx_mat(&tmp, arg); 184 | mat_copy(&inv_combined, &tmp2); 185 | mat_mult(&tmp, &tmp2, &inv_combined); 186 | } else if(strcmp("-ty", argv[index]) == 0) { 187 | index++; 188 | if(index >= argc) break; 189 | arg = atof(argv[index]); 190 | init_ty_mat(&tmp, arg); 191 | mat_copy(&combined, &tmp2); 192 | mat_mult(&tmp2, &tmp, &combined); 193 | 194 | init_inv_ty_mat(&tmp, arg); 195 | mat_copy(&inv_combined, &tmp2); 196 | mat_mult(&tmp, &tmp2, &inv_combined); 197 | } else if(strcmp("-tz", argv[index]) == 0) { 198 | index++; 199 | if(index >= argc) break; 200 | arg = atof(argv[index]); 201 | init_tz_mat(&tmp, arg); 202 | mat_copy(&combined, &tmp2); 203 | mat_mult(&tmp2, &tmp, &combined); 204 | 205 | init_inv_tz_mat(&tmp, arg); 206 | mat_copy(&inv_combined, &tmp2); 207 | mat_mult(&tmp, &tmp2, &inv_combined); 208 | } else { 209 | break; 210 | } 211 | } 212 | 213 | if(errflg || index+1 >= argc) { 214 | print_usage(); 215 | exit(2); 216 | } 217 | 218 | char *file = argv[index]; 219 | char *outfile = argv[index+1]; 220 | 221 | if(!is_valid_binary_stl(file)) { 222 | fprintf(stderr, "%s is not a binary stl file.\n", file); 223 | exit(2); 224 | } 225 | 226 | mat_transpose(&inv_combined, &inv_transpose); 227 | 228 | FILE *f; 229 | FILE *outf; 230 | 231 | f = fopen(file, "rb"); 232 | if(!f) { 233 | fprintf(stderr, "Can't read file: %s\n", file); 234 | exit(2); 235 | } 236 | 237 | outf = fopen(outfile, "wb"); 238 | if(!outf) { 239 | fprintf(stderr, "Can't write to file: %s\n", outfile); 240 | exit(2); 241 | } 242 | 243 | fseek(f, 80, SEEK_SET); 244 | 245 | uint32_t num_tris; 246 | 247 | size_t readBytes = fread(&num_tris, 4, 1, f); 248 | 249 | char header[81] = {0}; // include an extra char for terminating \0 of snprintf 250 | snprintf(header, 81, "Transformed copy of %s", basename(file)); 251 | 252 | fwrite(header, 80, 1, outf); 253 | fwrite(&num_tris, 4, 1, outf); 254 | 255 | uint16_t abc = 0; // attribute byte count 256 | 257 | vec tmp_vec; 258 | vec normal; 259 | vec point; 260 | 261 | normal.w = 0; 262 | point.w = 1; 263 | 264 | for(int i = 0; i < num_tris; i++) { 265 | readBytes = fread(&normal, 1, 12,f); 266 | 267 | vec_mat_mult(&normal, &inv_transpose, &tmp_vec); 268 | if(did_scale) { 269 | vec_normalize(&tmp_vec, &normal); 270 | fwrite(&normal, 1, 12, outf); 271 | } else { 272 | fwrite(&tmp_vec, 1, 12, outf); 273 | } 274 | 275 | for(int j = 0; j < 3; j++) { 276 | readBytes = fread(&point, 1, 12,f); 277 | vec_mat_mult(&point, &combined, &tmp_vec); 278 | fwrite(&tmp_vec, 1, 12, outf); 279 | } 280 | readBytes = fread(&abc, 1, 2,f); 281 | fwrite(&abc, 1, 2,outf); 282 | } 283 | 284 | fclose(f); 285 | fclose(outf); 286 | 287 | return 0; 288 | } 289 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | stl_cmd 2 | ======= 3 | 4 | The goal of each stl_cmd is to provide a simple command line interface for manipulating binary STL files. stl_cmd aims to be easy to set up, and is geared towards teaching basic terminal usage and programming skills in the 3D printing space. 5 | 6 | Getting started 7 | --------------- 8 | 9 | git clone https://github.com/AllwineDesigns/stl_cmd.git 10 | cd stl_cmd 11 | make 12 | make install # will install to /usr/local/bin by default 13 | 14 | make prefix=/some/other/path install # will install to /some/other/path/bin 15 | make DESTDIR=/some/other/path install # will install to /some/other/path/usr/local/bin 16 | make DESTDIR=/some/other/path prefix=/usr # will install to /some/other/path/usr/bin 17 | 18 | The stl_cmds will be compiled and placed in the bin/ directory in the root of the stl_cmd repo. Add it to your path and you can perform the following commands. 19 | 20 | stl_cmd releases are now a part of Debian! You can install them using apt-get. 21 | 22 | # on Debian unstable or Ubuntu bionic 23 | sudo apt-get install stlcmd 24 | 25 | Examples 26 | -------- 27 | 28 | You have an STL file specified in inches and you want to convert it to mm. 29 | 30 | stl_transform -s 25.4 my_file_inches.stl my_file_mm.stl 31 | 32 | Discard stored normals and calculate them based on vertex ordering (can fix some broken stl files). 33 | 34 | stl_normals -c my_file.stl my_fixed_file.stl 35 | 36 | Count the number of triangles in an STL file. 37 | 38 | stl_count my_file.stl 39 | 40 | Set the header of your STL file to contain copyright information. 41 | 42 | stl_header -s "My File. Copyright 2014." my_file.stl 43 | 44 | STL Commands 45 | ------------ 46 | 47 | ## Geometry Generators 48 | 49 | The following commands create STL files. 50 | 51 | ### stl_empty 52 | 53 | stl_empty 54 | 55 | Outputs an empty binary STL file. Can be useful to initialize an empty STL file when merging several files together. 56 | 57 | ### stl_cube 58 | 59 | stl_cube [ -w ] [ ] 60 | 61 | Outputs a binary STL file of a cube with the provided width. If no output file is provided, data is sent to stdout. 62 | 63 | ### stl_sphere 64 | 65 | stl_sphere [-r ] [ -s ] [ -t ] [ ] 66 | 67 | Outputs an stl file of a sphere with the provided radius and number of segments. 68 | If the radius is omitted, it defaults to 1. If longitudinal segments is omitted, it defaults to 32. If latitudinal segments is omitted, it defaults to half the longitudinal segments. If no output file is provided, data is sent to stdout. 69 | 70 | ### stl_cylinder 71 | 72 | stl_cylinder [-r ] [-h ] [ -s ] [ ] 73 | 74 | Outputs an stl file of a cylinder with the provided radius, height and number of segments. 75 | If the radius or height are omitted, they default to 1. If segments is omitted, it defaults to 32. If no output file is provided, data is sent to stdout. 76 | 77 | ### stl_cone 78 | 79 | stl_cone [-r ] [-t ] [-h ] [ -s ] [ ] 80 | 81 | Outputs an stl file of a cone with the provided radius, top radius, height and number of segments. 82 | If the radius or height are omitted, they default to 1. If top radius is omittted, it defaults to 0. If top radius is greater than 0, it outputs a truncated cone. If segments is omitted, it defaults to 32. If no output file is provided, data is sent to stdout. 83 | 84 | ### stl_torus 85 | 86 | stl_torus [-o ] [-i ] [ -s ] [ -c ] [ ] 87 | 88 | Outputs an stl file of a torus with the provided inner radius, outter radius, and number of segments. 89 | If the inner radius is omitted, it defaults to .5. If outer radius is omittted, it defaults to 1. If segments is omitted, it defaults to 32. If cross sectional segments is omitted, it defaults to half the segments. If no output file is provided, data is sent to stdout. 90 | 91 | ### stl_threads 92 | 93 | stl_threads [ -f ] [ -D ] [ -P ] [ -a ] 94 | [ -h ] [ -s ] 95 | 96 | Outputs an stl file with male or female screw threads per the [ISO metric 97 | screw thread standard](http://en.wikipedia.org/wiki/ISO_metric_screw_thread). 98 | 99 | -f - Outputs female threads (defaults to male). 100 | -D - Changes to major diameter of the threads. 101 | -P - Changes the height of a single thread, aka the pitch per 102 | the ISO metric standard. 103 | -h - Changes the total height of the threads. 104 | -a - Changes the thread angle (degrees). The standard (and 105 | default) is 60 degrees. For 3D printing this can cause 106 | overhang issues as 60 degrees results in a 30 degree 107 | angle with the ground plane. Setting to 90 degrees 108 | results in a 45 degree angle with the ground plane. 109 | -s - Changes the resolution of the generated STL file. More 110 | segments yields finer resolution. is the 111 | number of segments to approximate a circle. Defaults to 112 | 72 (every 5 degrees). 113 | 114 | ## Informational 115 | 116 | The following commands display information about STL files. In some cases, they 117 | make modifications to the STL files related to that information. 118 | 119 | ### stl_header 120 | 121 | stl_header [-s
] [-o ] 122 | 123 | Prints or sets the data in the header section of a binary STL file. The header section is rarely used, but can store a small amount of data (80 characters). Copyright info or a very brief description are some possibilities. 124 | 125 | ### stl_count 126 | 127 | stl_count [ ] 128 | 129 | Prints the number of triangles in the provided binary STL file. If no input file is provided, data is read from stdin. 130 | 131 | ### stl_normals 132 | 133 | stl_normals [ -v ] [ -c ] [ -r ] [ ] [ ] 134 | 135 | Compares normals stored in input file with normals calculated from the vertex ordering. Provided flags can tell stl_normals to fix the normals or reverse the point ordering. 136 | 137 | ### stl_bbox 138 | 139 | stl_bbox 140 | 141 | Prints bounding box information about the provided binary STL file. 142 | 143 | ### stl_convex 144 | 145 | stl_convex [ -v ] 146 | 147 | Determines whether an STL file is a convex polyheda by calculating Euler's characteristic. 148 | Prints convex if the STL file is convex, or not convex otherwise. If the -v flag is used 149 | a verbose message is printed that shows the calculation. 150 | 151 | ### stl_borders 152 | 153 | stl_borders 154 | 155 | Outputs the number of border edges in the STL files. This should be 0 for manifold meshes. If the output is greater than 0, the mesh has holes in it or has non-manifold edges. 156 | 157 | ### stl_spreadsheet 158 | 159 | stl_spreadsheet 160 | 161 | Outputs normal and position data for every triangle (normal, point1, point2 and point3 specified per row) in a tab delimited format that can be opened as a spreadsheet. 162 | 163 | ## Modifiers 164 | 165 | These commands modify existing STL files. 166 | 167 | ### stl_merge 168 | 169 | stl_merge [ -o ] [ ... ] 170 | 171 | Combines binary STL files into a single one. If no output file is provided, data is written to stdout. 172 | 173 | ### stl_transform 174 | 175 | stl_transform [[ ] ...] 176 | 177 | Performs any number of transformations in the order listed on the command line. Transformations include: 178 | 179 | -rx - rotates degrees about the x-axis 180 | -ry - rotates degrees about the y-axis 181 | -rz - rotates degrees about the z-axis 182 | -s - uniformly scales x, y and z by (cannot be 0) 183 | -sx - scales by in x (cannot be 0) 184 | -sy - scales by in y (cannot be 0) 185 | -sz - scales by in z (cannot be 0) 186 | -tx - translates units in x 187 | -ty - translates units in y 188 | -tz - translates units in z 189 | 190 | ### stl_boolean 191 | 192 | stl_boolean -a -b [ -i ] [ -u ] [ -d ] 193 | 194 | Performs a CSG boolean operation on STL files A and B using BSP trees. -i will perform the intersection of A and B. -u will 195 | perform the union of A and B. -d will perform the difference of A and B. 196 | 197 | Future commands 198 | --------------- 199 | 200 | These are ideas for future commands that may make it into the stl_cmd suite. 201 | 202 | ### stl_hull 203 | 204 | Compute the convex hull of the input STL files. 205 | 206 | ### stl_area 207 | 208 | Calculate the surface area of STL files (could be used for price or print time approximations) 209 | 210 | ### stl_volume 211 | 212 | Calculate the volume of STL files (could used for price or print time approximations) 213 | 214 | ### stl_layout 215 | 216 | Layout a number of stl files on the Z = 0 plane, possibly even attempting to find the flattest side to place each file on. 217 | 218 | ### stl_zero or stl_center 219 | 220 | Centers the STL file, with options to put the bottom of the model on the Z = 0 plane. 221 | 222 | ### stl_segments 223 | 224 | Extrude a circle or sweep a sphere along a piecewise linear curve. 225 | 226 | ### stl_bezier 227 | 228 | Extrude a circle or sweep a sphere along a Bezier curve (would probably approximate the Bezier with some number of linear segments and use the same algorithm as stl_segments). 229 | 230 | ### stl_decimate 231 | 232 | Simplify an STL file while preserving its shape. 233 | 234 | ### stl_twist 235 | 236 | Deform an STL file by twisting it. 237 | 238 | ### stl_bend 239 | 240 | Deform an STL file by bending it. 241 | 242 | ### stl_noise 243 | 244 | Deform an STL file by displacing vertices using noise. 245 | 246 | Teaching 247 | -------- 248 | 249 | The goal of this project is to be a resource for teaching terminal usage and some basic programming concepts in the 3D printing space. Imagine an assignment which involves building a brick wall. Students would need to use a combination of stl_cube, stl_transform and stl_merge. The commands could be combined in a bash or <insert favorite scripting language> script with for and while loops, could accept input and use conditionals to affect the attributes of the wall. 250 | 251 | The terminal is an important tool to learn when programming, but can be boring to learn when just making text based programs. stl_cmd aims to make the intro level terminal usage and programming more interesting by creating 3D printable models. As more commands are added more creative assignments are possible. I hope to grow the suite of commands included in stl_cmd with that goal in mind. 252 | 253 | Copyright 2014 Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) 254 | -------------------------------------------------------------------------------- /src/csgjs/Trees.cpp: -------------------------------------------------------------------------------- 1 | #include "csgjs/Trees.h" 2 | #include 3 | 4 | namespace csgjs { 5 | Node::Node() : parent(NULL), front(NULL), back(NULL) { 6 | } 7 | 8 | Node::Node(Node *p) : parent(p), front(NULL), back(NULL) { 9 | } 10 | 11 | void Node::invert() { 12 | plane = plane.flipped(); 13 | 14 | if(front != NULL) { 15 | front->invert(); 16 | } 17 | 18 | if(back != NULL) { 19 | back->invert(); 20 | } 21 | 22 | Node *n = front; 23 | front = back; 24 | back = n; 25 | } 26 | 27 | void Node::addPolygonTreeNodes(const std::vector &polyTreeNodes) { 28 | std::vector frontNodes; 29 | std::vector backNodes; 30 | 31 | if(polyTreeNodes.size() > 0) { 32 | int pick = fastRandom(polyTreeNodes.size()); 33 | // int pick = 0; 34 | 35 | plane = polyTreeNodes[pick]->getPolygon().plane; 36 | } 37 | 38 | std::vector::const_iterator itr = polyTreeNodes.begin(); 39 | while(itr != polyTreeNodes.end()) { 40 | (*itr)->splitByPlane(plane, polygonTreeNodes, backNodes, frontNodes, backNodes); 41 | ++itr; 42 | } 43 | 44 | // CSG.js did this iteratively rather than recursively. Probably safer to do iteratively, but starting with a recursive 45 | // solution for ease of implementation. If it leads to stack overflows, will refactor. May see a performance improvement 46 | // when implemented iteratively, so it might be worth trying. 47 | if(frontNodes.size() > 0) { 48 | front = new Node(this); 49 | front->addPolygonTreeNodes(frontNodes); 50 | } 51 | 52 | if(backNodes.size() > 0) { 53 | back = new Node(this); 54 | back->addPolygonTreeNodes(backNodes); 55 | } 56 | } 57 | 58 | bool Node::isRootNode() const { 59 | return parent == NULL; 60 | } 61 | 62 | void Node::clipTo(Tree &tree, bool alsoRemoveCoplanarFront) { 63 | if(polygonTreeNodes.size() > 0) { 64 | tree.rootnode.clipPolygons(polygonTreeNodes, alsoRemoveCoplanarFront); 65 | } 66 | if(front != NULL) { 67 | front->clipTo(tree, alsoRemoveCoplanarFront); 68 | } 69 | if(back != NULL) { 70 | back->clipTo(tree, alsoRemoveCoplanarFront); 71 | } 72 | } 73 | 74 | // Returns true if any triangles exist on the front side of the triangle 75 | // 76 | // breadth first search for provided plane, then check if any front nodes exist 77 | bool Node::hasFrontNodes(const Plane &p) const { 78 | std::list queue; 79 | 80 | queue.push_back(this); 81 | 82 | while(!queue.empty()) { 83 | const Node* curNode = queue.front(); 84 | queue.pop_front(); 85 | 86 | if(curNode->plane.isEqualWithinTolerance(p)) { 87 | if(curNode->front != NULL) { 88 | return true; 89 | } 90 | } else { 91 | if(curNode->front != NULL) { 92 | queue.push_back(curNode->front); 93 | } 94 | if(curNode->back != NULL) { 95 | queue.push_back(curNode->back); 96 | } 97 | } 98 | } 99 | return false; 100 | } 101 | 102 | void Node::clipPolygons(std::vector &polyTreeNodes, bool alsoRemoveCoplanarFront) { 103 | std::vector frontNodes; 104 | std::vector backNodes; 105 | 106 | std::vector::iterator itr = polyTreeNodes.begin(); 107 | 108 | while(itr != polyTreeNodes.end()) { 109 | PolygonTreeNode *node = (*itr); 110 | if(!node->isRemoved()) { 111 | node->splitByPlane(plane, alsoRemoveCoplanarFront ? backNodes : frontNodes, backNodes, frontNodes, backNodes); 112 | } 113 | ++itr; 114 | } 115 | 116 | if(front != NULL && frontNodes.size() > 0) { 117 | front->clipPolygons(frontNodes); 118 | } 119 | 120 | if(back != NULL && backNodes.size() > 0) { 121 | back->clipPolygons(backNodes); 122 | } else { 123 | std::vector::iterator backItr = backNodes.begin(); 124 | 125 | while(backItr != backNodes.end()) { 126 | (*backItr)->remove(); 127 | ++backItr; 128 | } 129 | } 130 | } 131 | 132 | Tree::Tree(const std::vector &polygons) { 133 | addPolygons(polygons); 134 | } 135 | 136 | bool Tree::hasPolygonsInFront(const Plane &p) const { 137 | return rootnode.hasFrontNodes(p); 138 | } 139 | 140 | void Tree::addPolygons(const std::vector &polygons) { 141 | std::vector::const_iterator itr = polygons.begin(); 142 | 143 | std::vector polyTreeNodes; 144 | polyTreeNodes.reserve(polygons.size()); 145 | 146 | while(itr != polygons.end()) { 147 | polyTreeNodes.push_back(polygonTree.addChild(*itr)); 148 | ++itr; 149 | } 150 | 151 | rootnode.addPolygonTreeNodes(polyTreeNodes); 152 | } 153 | 154 | void Tree::invert() { 155 | polygonTree.invert(); 156 | rootnode.invert(); 157 | } 158 | 159 | void Tree::clipTo(Tree &tree, bool alsoRemoveCoplanarFront) { 160 | rootnode.clipTo(tree, alsoRemoveCoplanarFront); 161 | } 162 | 163 | std::vector Tree::toPolygons() { 164 | std::vector polygons; 165 | 166 | polygonTree.getPolygons(polygons); 167 | 168 | return polygons; 169 | } 170 | 171 | PolygonTreeNode::PolygonTreeNode() : parent(NULL), removed(false), valid(false) {} 172 | PolygonTreeNode::PolygonTreeNode(PolygonTreeNode *p, const Polygon &poly) : parent(p), polygon(poly), removed(false), valid(true) {} 173 | PolygonTreeNode::~PolygonTreeNode() { 174 | std::vector::iterator itr = children.begin(); 175 | 176 | while(itr != children.end()) { 177 | delete *itr; 178 | ++itr; 179 | } 180 | } 181 | 182 | void PolygonTreeNode::invalidate() { 183 | valid = false; 184 | 185 | if(parent != NULL) { 186 | parent->invalidate(); 187 | } 188 | } 189 | 190 | void PolygonTreeNode::remove() { 191 | #ifdef CSGJS_DEBUG 192 | if(isRootNode()) { 193 | throw std::runtime_error("trying to delete root node"); 194 | } 195 | if(children.size() > 0) { 196 | throw std::runtime_error("trying to delete node with children"); 197 | } 198 | #endif 199 | 200 | invalidate(); 201 | 202 | // Can't delete this without removing pointers in BSP Node objects as well, if we remove from parent's children vector, we'll be creating a memory leak 203 | // Maybe use some kind of smart pointer so we can remove them here 204 | //parent->children.erase(std::remove(parent->children.begin(), parent->children.end(), this), parent->children.end()); 205 | //delete this; 206 | 207 | } 208 | 209 | PolygonTreeNode* PolygonTreeNode::addChild(const Polygon &polygon) { 210 | PolygonTreeNode *child = new PolygonTreeNode(this, polygon); 211 | 212 | children.push_back(child); 213 | 214 | return child; 215 | } 216 | 217 | bool PolygonTreeNode::isRootNode() const { 218 | return parent == NULL; 219 | } 220 | 221 | bool PolygonTreeNode::isRemoved() const { 222 | return removed; 223 | } 224 | 225 | Polygon& PolygonTreeNode::getPolygon() { 226 | return polygon; 227 | } 228 | 229 | // Like addPolygonTreeNodes, this was implemented iteratively in CSG.js, but we're doing it recursively here. 230 | // Might be worth revisiting. 231 | void PolygonTreeNode::splitByPlane(const Plane &plane, std::vector &coplanarFrontNodes, 232 | std::vector &coplanarBackNodes, 233 | std::vector &frontNodes, 234 | std::vector &backNodes) { 235 | 236 | if(children.size() > 0) { 237 | std::vector::iterator itr = children.begin(); 238 | 239 | while(itr != children.end()) { 240 | (*itr)->splitByPlane(plane, coplanarFrontNodes, coplanarBackNodes, frontNodes, backNodes); 241 | ++itr; 242 | } 243 | } else { 244 | if(valid) { 245 | splitLeafByPlane(plane, coplanarFrontNodes, coplanarBackNodes, frontNodes, backNodes); 246 | } 247 | } 248 | } 249 | 250 | void PolygonTreeNode::splitLeafByPlane(const Plane &plane, std::vector &coplanarFrontNodes, 251 | std::vector &coplanarBackNodes, 252 | std::vector &frontNodes, 253 | std::vector &backNodes) { 254 | #ifdef CSGJS_DEBUG 255 | if(children.size() > 0) { 256 | throw std::runtime_error("trying to split non-leaf node"); 257 | } 258 | #endif 259 | 260 | std::pair bound = polygon.boundingSphere(); 261 | csgjs_real sphereRadius = bound.second; 262 | Vector3 sphereCenter = bound.first; 263 | 264 | Vector3 planeNormal = plane.normal; 265 | csgjs_real d = planeNormal.dot(sphereCenter) - plane.w; 266 | if(d > sphereRadius) { 267 | frontNodes.push_back(this); 268 | } else if(d < -sphereRadius) { 269 | backNodes.push_back(this); 270 | } else { 271 | splitPolygonByPlane(plane, coplanarFrontNodes, coplanarBackNodes, frontNodes, backNodes); 272 | } 273 | } 274 | 275 | void PolygonTreeNode::invertRecurse() { 276 | if(valid) { 277 | polygon = polygon.flipped(); 278 | } 279 | std::vector::iterator itr = children.begin(); 280 | while(itr != children.end()) { 281 | (*itr)->invertRecurse(); 282 | ++itr; 283 | } 284 | } 285 | 286 | void PolygonTreeNode::invert() { 287 | #ifdef CSGJS_DEBUG 288 | if(!isRootNode()) { 289 | throw std::runtime_error("can only call invert on root node"); 290 | } 291 | #endif 292 | invertRecurse(); 293 | } 294 | 295 | void PolygonTreeNode::splitPolygonByPlane(const Plane &plane, std::vector &coplanarFrontNodes, 296 | std::vector &coplanarBackNodes, 297 | std::vector &frontNodes, 298 | std::vector &backNodes) { 299 | if(plane == polygon.plane) { 300 | // if the polygon's plane is exactly the same as the cutting plane it as a coplanar front 301 | coplanarFrontNodes.push_back(this); 302 | } else { 303 | std::vector vertexIsBack; 304 | vertexIsBack.reserve(polygon.vertices.size()); 305 | 306 | std::vector::iterator itr = polygon.vertices.begin(); 307 | bool hasFront = false; 308 | bool hasBack = false; 309 | while(itr != polygon.vertices.end()) { 310 | csgjs_real t = plane.normal.dot(itr->pos)-plane.w; 311 | bool isBack = t < 0; 312 | vertexIsBack.push_back(isBack); 313 | if(t > EPS) { 314 | hasFront = true; 315 | } 316 | if(t < NEG_EPS) { 317 | hasBack = true; 318 | } 319 | ++itr; 320 | } 321 | 322 | if(!hasFront && !hasBack) { 323 | if(plane.normal.dot(polygon.plane.normal) >= 0) { 324 | // if the polygon's plane is in the same direction as the cutting plane 325 | // and all of our vertices were within tolerance of being on the plane 326 | coplanarFrontNodes.push_back(this); 327 | } else { 328 | // if the polygon's plane is in the opposite direction as the cutting plane 329 | // and all of our vertices were within tolerance of being on the plane 330 | coplanarBackNodes.push_back(this); 331 | } 332 | } else if(!hasBack) { 333 | // if the polygon only has vertices in front of the cutting plane 334 | frontNodes.push_back(this); 335 | } else if(!hasFront) { 336 | // if the polygon only has vertices behind the cutting plane 337 | backNodes.push_back(this); 338 | } else { 339 | // the polygon crosses the cutting plane and needs to be divided into a front and back polygon 340 | 341 | std::vector frontVertices; 342 | std::vector backVertices; 343 | 344 | int numVertices = polygon.vertices.size(); 345 | for(int i = 0; i < numVertices; i++) { 346 | int nextI = i == (numVertices-1) ? 0 : i+1; 347 | Vertex vertex = polygon.vertices[i]; 348 | Vertex nextVertex = polygon.vertices[nextI]; 349 | bool isBack = vertexIsBack[i]; 350 | bool nextIsBack = vertexIsBack[nextI]; 351 | if(isBack == nextIsBack) { 352 | // line segment is entirely on one side of the plane 353 | if(isBack) { 354 | backVertices.push_back(vertex); 355 | } else { 356 | frontVertices.push_back(vertex); 357 | } 358 | } else { 359 | // line segment intersects plane 360 | Vector3 pos = vertex.pos; 361 | Vector3 nextPos = nextVertex.pos; 362 | Vertex intersectionV(plane.splitLineBetweenPoints(pos, nextPos)); 363 | if(isBack) { 364 | backVertices.push_back(vertex); 365 | backVertices.push_back(intersectionV); 366 | frontVertices.push_back(intersectionV); 367 | } else { 368 | frontVertices.push_back(vertex); 369 | frontVertices.push_back(intersectionV); 370 | backVertices.push_back(intersectionV); 371 | } 372 | } 373 | } 374 | 375 | if(backVertices.size() >= 3) { 376 | int numBackVertices = backVertices.size(); 377 | Vertex prevVertex = backVertices[numBackVertices-1]; 378 | std::vector::iterator backVertsItr = backVertices.begin(); 379 | while(backVertsItr != backVertices.end()) { 380 | Vertex v = *backVertsItr; 381 | if(v.pos.distanceTo(prevVertex.pos) < EPS) { 382 | backVertsItr = backVertices.erase(backVertsItr); 383 | } else { 384 | prevVertex = v; 385 | ++backVertsItr; 386 | } 387 | } 388 | } 389 | 390 | if(frontVertices.size() >= 3) { 391 | int numFrontVertices = frontVertices.size(); 392 | Vertex prevVertex = frontVertices[numFrontVertices-1]; 393 | std::vector::iterator frontVertsItr = frontVertices.begin(); 394 | while(frontVertsItr != frontVertices.end()) { 395 | Vertex v = *frontVertsItr; 396 | if(v.pos.distanceTo(prevVertex.pos) < EPS) { 397 | frontVertsItr = frontVertices.erase(frontVertsItr); 398 | } else { 399 | prevVertex = v; 400 | ++frontVertsItr; 401 | } 402 | } 403 | } 404 | 405 | if(frontVertices.size() >= 3) { 406 | PolygonTreeNode *node = addChild(Polygon(std::move(frontVertices), polygon.plane)); 407 | frontNodes.push_back(node); 408 | } 409 | if(backVertices.size() >= 3) { 410 | PolygonTreeNode *node = addChild(Polygon(std::move(backVertices), polygon.plane)); 411 | backNodes.push_back(node); 412 | } 413 | } 414 | } 415 | } 416 | 417 | void PolygonTreeNode::getPolygons(std::vector &polygons) const { 418 | if(valid) { 419 | polygons.push_back(polygon); 420 | } else { 421 | std::vector::const_iterator itr = children.begin(); 422 | while(itr != children.end()) { 423 | (*itr)->getPolygons(polygons); 424 | ++itr; 425 | } 426 | } 427 | } 428 | 429 | int PolygonTreeNode::countNodes() const { 430 | int count = 1; 431 | 432 | std::vector::const_iterator itr = children.begin(); 433 | while(itr != children.end()) { 434 | count += (*itr)->countNodes(); 435 | ++itr; 436 | } 437 | return count; 438 | } 439 | 440 | std::ostream& operator<<(std::ostream& os, const Tree &tree) { 441 | // os << tree.rootnode << std::endl; 442 | os << tree.polygonTree.countNodes() << std::endl; 443 | return os; 444 | } 445 | 446 | std::ostream& indentChildNodes(std::ostream& os, const PolygonTreeNode *node, int level) { 447 | for(int i = 0; i < level; i++) { 448 | os << " "; 449 | } 450 | os << node->polygon; 451 | 452 | if(node->children.size() > 0) { 453 | os << "Children: "; 454 | os << std::endl; 455 | std::vector::const_iterator itr = node->children.begin(); 456 | 457 | while(itr != node->children.end()) { 458 | indentChildNodes(os, *itr, level+1); 459 | ++itr; 460 | } 461 | } else { 462 | os << std::endl; 463 | } 464 | return os; 465 | } 466 | 467 | std::ostream& operator<<(std::ostream& os, const PolygonTreeNode &node) { 468 | return indentChildNodes(os, &node, 0); 469 | } 470 | } 471 | -------------------------------------------------------------------------------- /src/csgjs/CSG.cpp: -------------------------------------------------------------------------------- 1 | #include "CSG.h" 2 | #include "Trees.h" 3 | #include 4 | #include 5 | 6 | namespace csgjs { 7 | CSG::CSG() : _boundingBoxCacheValid(false) {} 8 | CSG::CSG(const std::vector &p) : _polygons(p), _boundingBoxCacheValid(false) { } 9 | CSG::CSG(std::vector &&p) : _polygons(p), _boundingBoxCacheValid(false) { } 10 | 11 | std::vector CSG::toPolygons() const { 12 | return _polygons; 13 | } 14 | 15 | CSG CSG::csgUnion(const CSG &csg) const { 16 | if(!mayOverlap(csg)) { 17 | return unionForNonIntersecting(csg); 18 | } 19 | 20 | Tree A(_polygons); 21 | Tree B(csg._polygons); 22 | 23 | A.clipTo(B); 24 | B.clipTo(A); 25 | B.invert(); 26 | B.clipTo(A); 27 | B.invert(); 28 | 29 | std::vector aPolys(A.toPolygons()); 30 | std::vector bPolys(B.toPolygons()); 31 | 32 | aPolys.insert(aPolys.end(), bPolys.begin(), bPolys.end()); 33 | 34 | return CSG(std::move(aPolys)); 35 | } 36 | 37 | CSG CSG::csgIntersect(const CSG &csg) const { 38 | if(!mayOverlap(csg)) { 39 | return CSG(); 40 | } 41 | 42 | Tree A(_polygons); 43 | Tree B(csg._polygons); 44 | 45 | A.invert(); 46 | B.clipTo(A); 47 | B.invert(); 48 | A.clipTo(B); 49 | B.clipTo(A); 50 | A.addPolygons(B.toPolygons()); 51 | A.invert(); 52 | 53 | std::vector aPolys(A.toPolygons()); 54 | 55 | return CSG(std::move(aPolys)); 56 | } 57 | 58 | CSG CSG::csgSubtract(const CSG &csg) const { 59 | if(!mayOverlap(csg)) { 60 | return *this; 61 | } 62 | 63 | Tree A(_polygons); 64 | Tree B(csg._polygons); 65 | 66 | A.invert(); 67 | A.clipTo(B); 68 | B.clipTo(A, true); 69 | A.addPolygons(B.toPolygons()); 70 | A.invert(); 71 | 72 | std::vector aPolys(A.toPolygons()); 73 | 74 | return CSG(std::move(aPolys)); 75 | } 76 | 77 | CSG CSG::unionForNonIntersecting(const CSG &csg) const { 78 | std::vector all_polys; 79 | all_polys.reserve(_polygons.size()+csg._polygons.size()); 80 | 81 | all_polys.insert(all_polys.end(), _polygons.begin(), _polygons.end()); 82 | all_polys.insert(all_polys.end(), csg._polygons.begin(), csg._polygons.end()); 83 | return CSG(std::move(all_polys)); 84 | } 85 | 86 | bool CSG::mayOverlap(const CSG &csg) const { 87 | if(_polygons.size() == 0 || csg._polygons.size() == 0) { 88 | return false; 89 | } else { 90 | std::pair bounds = getBounds(); 91 | std::pair otherBounds = csg.getBounds(); 92 | 93 | if(bounds.second.x < otherBounds.first.x) return false; 94 | if(bounds.first.x > otherBounds.second.x) return false; 95 | 96 | if(bounds.second.y < otherBounds.first.y) return false; 97 | if(bounds.first.y > otherBounds.second.y) return false; 98 | 99 | if(bounds.second.z < otherBounds.first.z) return false; 100 | if(bounds.first.z > otherBounds.second.z) return false; 101 | 102 | return true; 103 | } 104 | } 105 | 106 | std::pair CSG::getBounds() const { 107 | if(!_boundingBoxCacheValid) { 108 | std::vector::const_iterator itr = _polygons.begin(); 109 | while(itr != _polygons.end()) { 110 | std::pair bounds = itr->boundingBox(); 111 | 112 | if(itr == _polygons.begin()) { 113 | _boundingBoxCache.first = bounds.first; 114 | _boundingBoxCache.second = bounds.second; 115 | } else { 116 | _boundingBoxCache.first = _boundingBoxCache.first.min(bounds.first); 117 | _boundingBoxCache.second = _boundingBoxCache.second.max(bounds.second); 118 | } 119 | 120 | ++itr; 121 | } 122 | 123 | _boundingBoxCacheValid = true; 124 | } 125 | return _boundingBoxCache; 126 | } 127 | 128 | CSG CSG::transform(const Matrix4x4 &mat) { 129 | std::vector newPolygons(_polygons); 130 | std::vector::iterator itr = newPolygons.begin(); 131 | while(itr != newPolygons.end()) { 132 | *itr = itr->transform(mat); 133 | ++itr; 134 | } 135 | 136 | return CSG(std::move(newPolygons)); 137 | } 138 | 139 | void CSG::findUnmatchedEdges(std::unordered_map &unmatchedEdges) { 140 | std::vector::iterator polyItr = _polygons.begin(); 141 | while(polyItr != _polygons.end()) { 142 | std::vector::iterator vertexItr = polyItr->vertices.begin(); 143 | while(vertexItr != polyItr->vertices.end()) { 144 | std::vector::iterator nextVertexItr = vertexItr+1; 145 | if(nextVertexItr == polyItr->vertices.end()) { 146 | nextVertexItr = polyItr->vertices.begin(); 147 | } 148 | EdgeKey edgeKey(vertexItr->pos, nextVertexItr->pos); 149 | EdgeKey reversedKey = edgeKey.reversed(); 150 | 151 | if(unmatchedEdges.count(reversedKey) == 0) { 152 | unmatchedEdges[edgeKey] = PolygonEdgeData(&(*polyItr), vertexItr->pos, nextVertexItr->pos); 153 | } else { 154 | unmatchedEdges.erase(reversedKey); 155 | } 156 | 157 | ++vertexItr; 158 | } 159 | 160 | ++polyItr; 161 | } 162 | } 163 | 164 | void CSG::canonicalize() { 165 | std::unordered_map vertexLookup; 166 | 167 | std::vector::iterator polyItr = _polygons.begin(); 168 | while(polyItr != _polygons.end()) { 169 | std::vector::iterator vertexItr = polyItr->vertices.begin(); 170 | while(vertexItr != polyItr->vertices.end()) { 171 | Vector3 v = vertexItr->pos; 172 | VertexKey k(v); 173 | 174 | if(vertexLookup.count(k) > 0) { 175 | v = vertexLookup[k]; 176 | } else { 177 | vertexLookup[k] = v; 178 | } 179 | 180 | vertexItr->pos = v; 181 | ++vertexItr; 182 | } 183 | 184 | ++polyItr; 185 | } 186 | 187 | 188 | } 189 | 190 | void CSG::makeManifold() { 191 | // 1. Create an empty set of edges, E. Iterate over every edge of every polygon, adding each to E if its reverse edge hasn't already been added or removing the reverse edge them if it has. 192 | // This will leave only edges that don't have a matching edge (a neighboring polygon, with the same edge). 193 | // 2. Add all colinear edges in unmatchedEdges to its own list 194 | // 3. Iterate over each set of edges, creating a lookup table of start and end vertices for each edge. 195 | // Also, keep a sorted list of vertices based on their position along the line. 196 | // 4. Keep track of active edges while iterating over each vertex in order. An active edge is one where we've encountered it's first verex, but not it's second. 197 | // 5. For each vertex we encounter, split the currently active edges into 2 (edge A-------B will be come A----V----B, AB -> AV and VB), making sure to update the edge's corresponding polygon. 198 | 199 | // 1. E = unmatchedEdges 200 | std::unordered_map unmatchedEdges; 201 | findUnmatchedEdges(unmatchedEdges); 202 | 203 | // 2. Add all colinear edges in unmatchedEdges to its own list 204 | std::unordered_map> edgesPerLine; 205 | 206 | std::unordered_map::iterator edgeItr = unmatchedEdges.begin(); 207 | while(edgeItr != unmatchedEdges.end()) { 208 | LineKey lineKey(Line::fromPoints(edgeItr->first.first, edgeItr->first.second)); 209 | 210 | edgesPerLine[lineKey].push_back(&(edgeItr->second)); 211 | 212 | ++edgeItr; 213 | } 214 | 215 | // 3. 216 | std::unordered_map>::iterator lineItr = edgesPerLine.begin(); 217 | 218 | int lineNum = 0; 219 | //std::cout << edgesPerLine.size() << " lines" << std::endl; 220 | while(lineItr != edgesPerLine.end()) { 221 | //std::cout << lineNum << " " << lineItr->first.line << " " << lineItr->second.size() << std::endl; 222 | // for each line 223 | // create lookup tables for the start and end of each edge based on vertex position 224 | std::unordered_map > startVertex2PolygonEdgeData; 225 | std::unordered_map > endVertex2PolygonEdgeData; 226 | 227 | // keep a sorted set of vertices based on the position along the line 228 | std::set vertices; 229 | 230 | // keep track of the polygons that we need to insert them in reverse order 231 | std::unordered_set insertForward; 232 | std::unordered_set insertReversed; 233 | 234 | // for each edge on line 235 | std::vector::iterator edgeDataItr = lineItr->second.begin(); 236 | while(edgeDataItr != lineItr->second.end()) { 237 | // insert into start and end lookup tables based on the order we'll encounter them 238 | // while iterating over the vertices from lowest to highest 239 | VertexKey firstKey = VertexKey((*edgeDataItr)->first); 240 | VertexKey secondKey = VertexKey((*edgeDataItr)->second); 241 | csgjs_real firstDist = lineItr->first.line.distanceToPointOnLine(firstKey.v); 242 | csgjs_real secondDist = lineItr->first.line.distanceToPointOnLine(secondKey.v); 243 | 244 | vertices.insert(VertexKeyDist(firstKey,firstDist)); 245 | vertices.insert(VertexKeyDist(secondKey,secondDist)); 246 | 247 | if(firstDist < secondDist) { 248 | startVertex2PolygonEdgeData[firstKey].push_back(*edgeDataItr); 249 | endVertex2PolygonEdgeData[secondKey].push_back(*edgeDataItr); 250 | insertForward.insert((*edgeDataItr)->polygon); 251 | } else { 252 | startVertex2PolygonEdgeData[secondKey].push_back(*edgeDataItr); 253 | endVertex2PolygonEdgeData[firstKey].push_back(*edgeDataItr); 254 | insertReversed.insert((*edgeDataItr)->polygon); 255 | } 256 | 257 | ++edgeDataItr; 258 | } 259 | 260 | #ifdef CSGJS_DEBUG 261 | std::cout << "all vertices" << std::endl; 262 | std::set::iterator testItr = vertices.begin(); 263 | while(testItr != vertices.end()) { 264 | std::cout << testItr->key.hash << " " << testItr->key.v << " " << testItr->dist << std::endl; 265 | ++testItr; 266 | } 267 | 268 | std::cout << "starting vertices " << std::endl; 269 | std::unordered_map >::iterator startItr = startVertex2PolygonEdgeData.begin(); 270 | while(startItr != startVertex2PolygonEdgeData.end()) { 271 | std::cout << startItr->first.hash << " " << startItr->first.v << " starts " << startItr->second.size() << " edges" << std::endl; 272 | ++startItr; 273 | } 274 | 275 | std::cout << "ending vertices " << std::endl; 276 | std::unordered_map >::iterator endItr = endVertex2PolygonEdgeData.begin(); 277 | while(endItr != endVertex2PolygonEdgeData.end()) { 278 | std::cout << endItr->first.hash << " " << endItr->first.v << " ends " << endItr->second.size() << " edges" << std::endl; 279 | ++endItr; 280 | } 281 | #endif 282 | 283 | // keep track of vertices to add to each polygon, after we're done we'll iterate over this to actually insert them 284 | std::unordered_map > > verticesToInsert; 285 | 286 | // keep track of which edges are active, which means we've encountered their start vertex, but not their end vertex 287 | std::unordered_set activeEdges; 288 | 289 | std::set::iterator vertexItr = vertices.begin(); 290 | while(vertexItr != vertices.end()) { 291 | if(endVertex2PolygonEdgeData.count(vertexItr->key) > 0) { 292 | // we've encountered an end vertex, so remove all edges that ended from the activeEdges set 293 | std::vector::iterator endingItr = endVertex2PolygonEdgeData[vertexItr->key].begin(); 294 | while(endingItr != endVertex2PolygonEdgeData[vertexItr->key].end()) { 295 | activeEdges.erase(*endingItr); 296 | ++endingItr; 297 | } 298 | } 299 | 300 | // loop over all activeEdges and indicate that we want to add the current vertex to its polygon 301 | std::unordered_set::iterator activeItr = activeEdges.begin(); 302 | while(activeItr != activeEdges.end()) { 303 | PolygonEdgeData *edgeData = *activeItr; 304 | //std::cout << "indicating we want to insert " << vertexItr->key.v << " after " << edgeData->first << std::endl; 305 | verticesToInsert[edgeData->polygon].push_back(std::make_pair(vertexItr->key.v, edgeData->first)); 306 | ++activeItr; 307 | } 308 | 309 | // add all edges that start on this vertex to the active edges set 310 | std::vector::iterator startingItr = startVertex2PolygonEdgeData[vertexItr->key].begin(); 311 | while(startingItr != startVertex2PolygonEdgeData[vertexItr->key].end()) { 312 | activeEdges.insert(*startingItr); 313 | ++startingItr; 314 | } 315 | 316 | ++vertexItr; 317 | } 318 | #ifdef CSGJS_DEBUG 319 | if(activeEdges.size() > 0) { 320 | std::cout << "still have " << activeEdges.size() << " edges in active list" << std::endl; 321 | std::unordered_set::iterator itr = activeEdges.begin(); 322 | while(itr != activeEdges.end()) { 323 | std::cout << (*itr)->first << " " << (*itr)->second << std::endl; 324 | ++itr; 325 | } 326 | std::cout << "active edges set wasn't empty" << std::endl; 327 | throw new std::runtime_error("active edges set wasn't empty"); 328 | } 329 | #endif 330 | 331 | // insert vertices into polygons that were encountered in forward order 332 | std::unordered_set::iterator forwardItr = insertForward.begin(); 333 | while(forwardItr != insertForward.end()) { 334 | Polygon* polygon = *forwardItr; 335 | 336 | //std::cout << "inserting " << verticesToInsert[polygon].size() << " extra vertices" << std::endl; 337 | std::vector >::iterator insertItr = verticesToInsert[polygon].begin(); 338 | //while(insertItr != verticesToInsert[polygon].end()) { 339 | //std::cout << *polygon << std::endl; 340 | // //std::cout << "inserting" << insertItr->first << " after " << insertItr->second << std::endl; 341 | // ++insertItr; 342 | //} 343 | //insertItr = verticesToInsert[polygon].begin(); 344 | 345 | //std::cout << polygon->vertices << std::endl; 346 | 347 | std::vector::iterator vertexItr = polygon->vertices.begin(); 348 | std::vector newVertices; 349 | while(vertexItr != polygon->vertices.end()) { 350 | newVertices.push_back(*vertexItr); 351 | while(insertItr != verticesToInsert[polygon].end() && vertexItr->pos == insertItr->second) { 352 | newVertices.push_back(Vertex(insertItr->first)); 353 | ++insertItr; 354 | } 355 | ++vertexItr; 356 | } 357 | 358 | //std::cout << "replacing " << polygon->vertices.size() << " vertices with " << newVertices.size() << " vertices" << std::endl; 359 | polygon->vertices = std::move(newVertices); 360 | 361 | //std::cout << polygon->vertices << std::endl; 362 | 363 | ++forwardItr; 364 | } 365 | 366 | // insert vertices into polygons that were encountered in reverse order 367 | std::unordered_set::iterator reverseItr = insertReversed.begin();; 368 | while(reverseItr != insertReversed.end()) { 369 | Polygon* polygon = *reverseItr; 370 | 371 | //std::cout << "rev inserting " << verticesToInsert[polygon].size() << " extra vertices" << std::endl; 372 | std::vector >::reverse_iterator insertItr = verticesToInsert[polygon].rbegin(); 373 | std::vector::iterator vertexItr = polygon->vertices.begin(); 374 | std::vector newVertices; 375 | while(vertexItr != polygon->vertices.end()) { 376 | newVertices.push_back(*vertexItr); 377 | while(insertItr != verticesToInsert[polygon].rend() && vertexItr->pos == insertItr->second) { 378 | newVertices.push_back(Vertex(insertItr->first)); 379 | ++insertItr; 380 | } 381 | ++vertexItr; 382 | } 383 | 384 | //std::cout << "rev replacing " << polygon->vertices.size() << " vertices with " << newVertices.size() << " vertices" << std::endl; 385 | polygon->vertices = std::move(newVertices); 386 | 387 | ++reverseItr; 388 | } 389 | 390 | ++lineItr; 391 | ++lineNum; 392 | } 393 | 394 | #ifdef CSGJS_DEBUG 395 | std::unordered_map stillUnmatched; 396 | findUnmatchedEdges(stillUnmatched); 397 | 398 | if(stillUnmatched.size() > 0) { 399 | std::cout << "still " << stillUnmatched.size() << " unmatched edges" << std::endl; 400 | std::unordered_map::iterator itr = stillUnmatched.begin(); 401 | while(itr != stillUnmatched.end()) { 402 | LineKey lineKey(Line::fromPoints(itr->first.first, itr->first.second)); 403 | std::cout << itr->first.hash << " " << itr->second.first << " " << itr->second.second << " " << lineKey.hash << " " << lineKey.line << std::endl; 404 | 405 | ++itr; 406 | } 407 | 408 | std::cout << "still " << stillUnmatched.size() << " unmatched edges" << std::endl; 409 | throw new std::runtime_error("still unmatched edges"); 410 | } 411 | #endif 412 | } 413 | 414 | std::ostream& operator<<(std::ostream& os, const CSG &csg) { 415 | std::vector::const_iterator itr = csg._polygons.begin(); 416 | os << "CSG {" << std::endl; 417 | while(itr != csg._polygons.end()) { 418 | os << *itr; 419 | 420 | ++itr; 421 | 422 | if(itr != csg._polygons.end()) { 423 | os << ","; 424 | } 425 | os << std::endl; 426 | } 427 | 428 | os << "}"; 429 | return os; 430 | } 431 | } 432 | --------------------------------------------------------------------------------