pax_global_header00006660000000000000000000000064132216122100014500gustar00rootroot0000000000000052 comment=d4a5ff4496796b2567edf701d174baf4a5cf7a6b stl_cmd-1.1/000077500000000000000000000000001322161221000127665ustar00rootroot00000000000000stl_cmd-1.1/.gitignore000066400000000000000000000000201322161221000147460ustar00rootroot00000000000000*.swp bin/ man/ stl_cmd-1.1/CHANGES000066400000000000000000000006061322161221000137630ustar00rootroot00000000000000* v1.1 Fixed Makefile to properly install stl_boolean * v1.0 release with the following commands * stl_empty * stl_cube * stl_sphere * stl_cylinder * stl_cone * stl_torus * stl_threads * stl_header * stl_count * stl_normals * stl_bbox * stl_convex * stl_borders * stl_spreadsheet * stl_merge * stl_transform * stl_boolean stl_cmd-1.1/LICENSE000066400000000000000000001063151322161221000140010ustar00rootroot00000000000000stl_cmd - a set of commands for manipulating binary STL files Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ========================================================================== GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . stl_cmd-1.1/Makefile000066400000000000000000000032261322161221000144310ustar00rootroot00000000000000prefix?=/usr/local target=$(DESTDIR)$(prefix) VERSION=1.1 DOCS_DIR := man BIN_DIR := bin CMDS := $(addprefix $(BIN_DIR)/,stl_header stl_merge stl_transform stl_count stl_bbox stl_cube stl_sphere stl_cylinder stl_cone stl_torus stl_empty stl_threads stl_normals stl_convex stl_borders stl_spreadsheet) CSGJS_CMDS := $(addprefix $(BIN_DIR)/,stl_boolean) ALL_CMDS := $(CSGJS_CMDS) $(CMDS) CC := g++ #FLAGS=-Og -g -std=c++11 FLAGS=-O3 -std=c++11 all: $(CMDS) bin/stl_boolean $(BIN_DIR)/%: src/%.cpp src/stl_util.h $(CC) $(FLAGS) $(CPPFLAGS) $(CFLAGS) $(CXXFLAGS) $(LDFLAGS) $(OUTPUT_OPTION) $< $(BIN_DIR)/stl_boolean: src/stl_boolean.cpp src/csgjs/*.cpp src/csgjs/math/*.cpp src/csgjs/math/*.h src/csgjs/*.h $(CC) $(FLAGS) $(CPPFLAGS) $(CFLAGS) $(CXXFLAGS) $(LDFLAGS) src/stl_boolean.cpp src/csgjs/*.cpp src/csgjs/math/*.cpp -Isrc -o bin/stl_boolean $(CMDS): | $(BIN_DIR) $(BIN_DIR): mkdir $(BIN_DIR) clean: rm -rf $(BIN_DIR) $(DOCS_DIR): mkdir $(DOCS_DIR) docs: $(DOCS_DIR) $(CMDS) for cmd in $(ALL_CMDS); do \ help2man $$cmd --name="$$($$cmd --help 2>&1 | head --lines=1)" --no-discard-stderr --version-string="v$(VERSION)" --no-info > $(DOCS_DIR)/$$(basename $$cmd).1; \ done installDocs: docs install -d $(target)/share/man/man1 for cmd in $(ALL_CMDS); do \ gzip -c -9 $(DOCS_DIR)/$$(basename $$cmd).1 > $(target)/share/man/man1/$$(basename $$cmd).1.gz; \ done uninstallDocs: for cmd in $(ALL_CMDS); do \ rm $(target)/share/man/man1/$$(basename $$cmd).1.gz; \ done install: all install -d $(target)/bin for cmd in $(ALL_CMDS); do \ install $$cmd $(target)/$$cmd; \ done uninstall: for cmd in $(ALL_CMDS); do \ rm $(target)/$$cmd; \ done stl_cmd-1.1/README.md000066400000000000000000000233421322161221000142510ustar00rootroot00000000000000stl_cmd ======= 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. Getting started --------------- git clone https://github.com/frknsweetapps/stl_cmd.git cd stl_cmd make make install # will install to /usr/local/bin by default make prefix=/some/other/path install # will install to /some/other/path/bin make DESTDIR=/some/other/path install # will install to /some/other/path/usr/local/bin make DESTDIR=/some/other/path prefix=/usr # will install to /some/other/path/usr/bin 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. Examples -------- You have an STL file specified in inches and you want to convert it to mm. stl_transform -s 25.4 my_file_inches.stl my_file_mm.stl Discard stored normals and calculate them based on vertex ordering (can fix some broken stl files). stl_normals -c my_file.stl my_fixed_file.stl Count the number of triangles in an STL file. stl_count my_file.stl Set the header of your STL file to contain copyright information. stl_header -s "My File. Copyright 2014." my_file.stl STL Commands ------------ ## Geometry Generators The following commands create STL files. ### stl_empty stl_empty Outputs an empty binary STL file. Can be useful to initialize an empty STL file when merging several files together. ### stl_cube stl_cube [ -w ] [ ] Outputs a binary STL file of a cube with the provided width. If no output file is provided, data is sent to stdout. ### stl_sphere stl_sphere [-r ] [ -s ] [ -t ] [ ] Outputs an stl file of a sphere with the provided radius and number of segments. 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. ### stl_cylinder stl_cylinder [-r ] [-h ] [ -s ] [ ] Outputs an stl file of a cylinder with the provided radius, height and number of segments. 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. ### stl_cone stl_cone [-r ] [-t ] [-h ] [ -s ] [ ] Outputs an stl file of a cone with the provided radius, top radius, height and number of segments. 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. ### stl_torus stl_torus [-o ] [-i ] [ -s ] [ -c ] [ ] Outputs an stl file of a torus with the provided inner radius, outter radius, and number of segments. 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. ### stl_threads stl_threads [ -f ] [ -D ] [ -P ] [ -a ] [ -h ] [ -s ] Outputs an stl file with male or female screw threads per the [ISO metric screw thread standard](http://en.wikipedia.org/wiki/ISO_metric_screw_thread). -f - Outputs female threads (defaults to male). -D - Changes to major diameter of the threads. -P - Changes the height of a single thread, aka the pitch per the ISO metric standard. -h - Changes the total height of the threads. -a - Changes the thread angle (degrees). The standard (and default) is 60 degrees. For 3D printing this can cause overhang issues as 60 degrees results in a 30 degree angle with the ground plane. Setting to 90 degrees results in a 45 degree angle with the ground plane. -s - Changes the resolution of the generated STL file. More segments yields finer resolution. is the number of segments to approximate a circle. Defaults to 72 (every 5 degrees). ## Informational The following commands display information about STL files. In some cases, they make modifications to the STL files related to that information. ### stl_header stl_header [-s
] [-o ] 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. ### stl_count stl_count [ ] Prints the number of triangles in the provided binary STL file. If no input file is provided, data is read from stdin. ### stl_normals stl_normals [ -v ] [ -c ] [ -r ] [ ] [ ] 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. ### stl_bbox stl_bbox Prints bounding box information about the provided binary STL file. ### stl_convex stl_convex [ -v ] Determines whether an STL file is a convex polyheda by calculating Euler's characteristic. Prints convex if the STL file is convex, or not convex otherwise. If the -v flag is used a verbose message is printed that shows the calculation. ### stl_borders stl_borders 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. ### stl_spreadsheet stl_spreadsheet 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. ## Modifiers These commands modify existing STL files. ### stl_merge stl_merge [ -o ] [ ... ] Combines binary STL files into a single one. If no output file is provided, data is written to stdout. ### stl_transform stl_transform [[ ] ...] Performs any number of transformations in the order listed on the command line. Transformations include: -rx - rotates degrees about the x-axis -ry - rotates degrees about the y-axis -rz - rotates degrees about the z-axis -s - uniformly scales x, y and z by (cannot be 0) -sx - scales by in x (cannot be 0) -sy - scales by in y (cannot be 0) -sz - scales by in z (cannot be 0) -tx - translates units in x -ty - translates units in y -tz - translates units in z ### stl_boolean stl_boolean -a -b [ -i ] [ -u ] [ -d ] 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 perform the union of A and B. -d will perform the difference of A and B. Future commands --------------- These are ideas for future commands that may make it into the stl_cmd suite. ### stl_hull Compute the convex hull of the input STL files. ### stl_area Calculate the surface area of STL files (could be used for price or print time approximations) ### stl_volume Calculate the volume of STL files (could used for price or print time approximations) ### stl_layout Layout a number of stl files on the Z = 0 plane, possibly even attempting to find the flattest side to place each file on. ### stl_zero or stl_center Centers the STL file, with options to put the bottom of the model on the Z = 0 plane. ### stl_segments Extrude a circle or sweep a sphere along a piecewise linear curve. ### stl_bezier 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). ### stl_decimate Simplify an STL file while preserving its shape. ### stl_twist Deform an STL file by twisting it. ### stl_bend Deform an STL file by bending it. ### stl_noise Deform an STL file by displacing vertices using noise. Teaching -------- 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. 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. Copyright 2014 Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) stl_cmd-1.1/src/000077500000000000000000000000001322161221000135555ustar00rootroot00000000000000stl_cmd-1.1/src/csgjs/000077500000000000000000000000001322161221000146665ustar00rootroot00000000000000stl_cmd-1.1/src/csgjs/CSG.cpp000066400000000000000000000377401322161221000160210ustar00rootroot00000000000000#include "CSG.h" #include "Trees.h" #include #include namespace csgjs { CSG::CSG() : _boundingBoxCacheValid(false) {} CSG::CSG(const std::vector &p) : _polygons(p), _boundingBoxCacheValid(false) { } CSG::CSG(std::vector &&p) : _polygons(p), _boundingBoxCacheValid(false) { } std::vector CSG::toPolygons() const { return _polygons; } CSG CSG::csgUnion(const CSG &csg) const { if(!mayOverlap(csg)) { return unionForNonIntersecting(csg); } Tree A(_polygons); Tree B(csg._polygons); A.clipTo(B); B.clipTo(A); B.invert(); B.clipTo(A); B.invert(); std::vector aPolys(A.toPolygons()); std::vector bPolys(B.toPolygons()); aPolys.insert(aPolys.end(), bPolys.begin(), bPolys.end()); return CSG(std::move(aPolys)); } CSG CSG::csgIntersect(const CSG &csg) const { if(!mayOverlap(csg)) { return CSG(); } Tree A(_polygons); Tree B(csg._polygons); A.invert(); B.clipTo(A); B.invert(); A.clipTo(B); B.clipTo(A); A.addPolygons(B.toPolygons()); A.invert(); std::vector aPolys(A.toPolygons()); return CSG(std::move(aPolys)); } CSG CSG::csgSubtract(const CSG &csg) const { if(!mayOverlap(csg)) { return *this; } Tree A(_polygons); Tree B(csg._polygons); A.invert(); A.clipTo(B); B.clipTo(A, true); A.addPolygons(B.toPolygons()); A.invert(); std::vector aPolys(A.toPolygons()); return CSG(std::move(aPolys)); } CSG CSG::unionForNonIntersecting(const CSG &csg) const { std::vector all_polys; all_polys.reserve(_polygons.size()+csg._polygons.size()); all_polys.insert(all_polys.end(), _polygons.begin(), _polygons.end()); all_polys.insert(all_polys.end(), csg._polygons.begin(), csg._polygons.end()); return CSG(std::move(all_polys)); } bool CSG::mayOverlap(const CSG &csg) const { if(_polygons.size() == 0 || csg._polygons.size() == 0) { return false; } else { std::pair bounds = getBounds(); std::pair otherBounds = csg.getBounds(); if(bounds.second.x < otherBounds.first.x) return false; if(bounds.first.x > otherBounds.second.x) return false; if(bounds.second.y < otherBounds.first.y) return false; if(bounds.first.y > otherBounds.second.y) return false; if(bounds.second.z < otherBounds.first.z) return false; if(bounds.first.z > otherBounds.second.z) return false; return true; } } std::pair CSG::getBounds() const { if(!_boundingBoxCacheValid) { std::vector::const_iterator itr = _polygons.begin(); while(itr != _polygons.end()) { std::pair bounds = itr->boundingBox(); if(itr == _polygons.begin()) { _boundingBoxCache.first = bounds.first; _boundingBoxCache.second = bounds.second; } else { _boundingBoxCache.first = _boundingBoxCache.first.min(bounds.first); _boundingBoxCache.second = _boundingBoxCache.second.max(bounds.second); } ++itr; } _boundingBoxCacheValid = true; } return _boundingBoxCache; } CSG CSG::transform(const Matrix4x4 &mat) { std::vector newPolygons(_polygons); std::vector::iterator itr = newPolygons.begin(); while(itr != newPolygons.end()) { *itr = itr->transform(mat); ++itr; } return CSG(std::move(newPolygons)); } void CSG::findUnmatchedEdges(std::unordered_map &unmatchedEdges) { std::vector::iterator polyItr = _polygons.begin(); while(polyItr != _polygons.end()) { std::vector::iterator vertexItr = polyItr->vertices.begin(); while(vertexItr != polyItr->vertices.end()) { std::vector::iterator nextVertexItr = vertexItr+1; if(nextVertexItr == polyItr->vertices.end()) { nextVertexItr = polyItr->vertices.begin(); } EdgeKey edgeKey(vertexItr->pos, nextVertexItr->pos); EdgeKey reversedKey = edgeKey.reversed(); if(unmatchedEdges.count(reversedKey) == 0) { unmatchedEdges[edgeKey] = PolygonEdgeData(&(*polyItr), vertexItr->pos, nextVertexItr->pos); } else { unmatchedEdges.erase(reversedKey); } ++vertexItr; } ++polyItr; } } void CSG::canonicalize() { std::unordered_map vertexLookup; std::vector::iterator polyItr = _polygons.begin(); while(polyItr != _polygons.end()) { std::vector::iterator vertexItr = polyItr->vertices.begin(); while(vertexItr != polyItr->vertices.end()) { Vector3 v = vertexItr->pos; VertexKey k(v); if(vertexLookup.count(k) > 0) { v = vertexLookup[k]; } else { vertexLookup[k] = v; } vertexItr->pos = v; ++vertexItr; } ++polyItr; } } void CSG::makeManifold() { // 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. // This will leave only edges that don't have a matching edge (a neighboring polygon, with the same edge). // 2. Add all colinear edges in unmatchedEdges to its own list // 3. Iterate over each set of edges, creating a lookup table of start and end vertices for each edge. // Also, keep a sorted list of vertices based on their position along the line. // 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. // 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. // 1. E = unmatchedEdges std::unordered_map unmatchedEdges; findUnmatchedEdges(unmatchedEdges); // 2. Add all colinear edges in unmatchedEdges to its own list std::unordered_map> edgesPerLine; std::unordered_map::iterator edgeItr = unmatchedEdges.begin(); while(edgeItr != unmatchedEdges.end()) { LineKey lineKey(Line::fromPoints(edgeItr->first.first, edgeItr->first.second)); edgesPerLine[lineKey].push_back(&(edgeItr->second)); ++edgeItr; } // 3. std::unordered_map>::iterator lineItr = edgesPerLine.begin(); int lineNum = 0; //std::cout << edgesPerLine.size() << " lines" << std::endl; while(lineItr != edgesPerLine.end()) { //std::cout << lineNum << " " << lineItr->first.line << " " << lineItr->second.size() << std::endl; // for each line // create lookup tables for the start and end of each edge based on vertex position std::unordered_map > startVertex2PolygonEdgeData; std::unordered_map > endVertex2PolygonEdgeData; // keep a sorted set of vertices based on the position along the line std::set vertices; // keep track of the polygons that we need to insert them in reverse order std::unordered_set insertForward; std::unordered_set insertReversed; // for each edge on line std::vector::iterator edgeDataItr = lineItr->second.begin(); while(edgeDataItr != lineItr->second.end()) { // insert into start and end lookup tables based on the order we'll encounter them // while iterating over the vertices from lowest to highest VertexKey firstKey = VertexKey((*edgeDataItr)->first); VertexKey secondKey = VertexKey((*edgeDataItr)->second); csgjs_real firstDist = lineItr->first.line.distanceToPointOnLine(firstKey.v); csgjs_real secondDist = lineItr->first.line.distanceToPointOnLine(secondKey.v); vertices.insert(VertexKeyDist(firstKey,firstDist)); vertices.insert(VertexKeyDist(secondKey,secondDist)); if(firstDist < secondDist) { startVertex2PolygonEdgeData[firstKey].push_back(*edgeDataItr); endVertex2PolygonEdgeData[secondKey].push_back(*edgeDataItr); insertForward.insert((*edgeDataItr)->polygon); } else { startVertex2PolygonEdgeData[secondKey].push_back(*edgeDataItr); endVertex2PolygonEdgeData[firstKey].push_back(*edgeDataItr); insertReversed.insert((*edgeDataItr)->polygon); } ++edgeDataItr; } #ifdef CSGJS_DEBUG std::cout << "all vertices" << std::endl; std::set::iterator testItr = vertices.begin(); while(testItr != vertices.end()) { std::cout << testItr->key.hash << " " << testItr->key.v << " " << testItr->dist << std::endl; ++testItr; } std::cout << "starting vertices " << std::endl; std::unordered_map >::iterator startItr = startVertex2PolygonEdgeData.begin(); while(startItr != startVertex2PolygonEdgeData.end()) { std::cout << startItr->first.hash << " " << startItr->first.v << " starts " << startItr->second.size() << " edges" << std::endl; ++startItr; } std::cout << "ending vertices " << std::endl; std::unordered_map >::iterator endItr = endVertex2PolygonEdgeData.begin(); while(endItr != endVertex2PolygonEdgeData.end()) { std::cout << endItr->first.hash << " " << endItr->first.v << " ends " << endItr->second.size() << " edges" << std::endl; ++endItr; } #endif // keep track of vertices to add to each polygon, after we're done we'll iterate over this to actually insert them std::unordered_map > > verticesToInsert; // keep track of which edges are active, which means we've encountered their start vertex, but not their end vertex std::unordered_set activeEdges; std::set::iterator vertexItr = vertices.begin(); while(vertexItr != vertices.end()) { if(endVertex2PolygonEdgeData.count(vertexItr->key) > 0) { // we've encountered an end vertex, so remove all edges that ended from the activeEdges set std::vector::iterator endingItr = endVertex2PolygonEdgeData[vertexItr->key].begin(); while(endingItr != endVertex2PolygonEdgeData[vertexItr->key].end()) { activeEdges.erase(*endingItr); ++endingItr; } } // loop over all activeEdges and indicate that we want to add the current vertex to its polygon std::unordered_set::iterator activeItr = activeEdges.begin(); while(activeItr != activeEdges.end()) { PolygonEdgeData *edgeData = *activeItr; //std::cout << "indicating we want to insert " << vertexItr->key.v << " after " << edgeData->first << std::endl; verticesToInsert[edgeData->polygon].push_back(std::make_pair(vertexItr->key.v, edgeData->first)); ++activeItr; } // add all edges that start on this vertex to the active edges set std::vector::iterator startingItr = startVertex2PolygonEdgeData[vertexItr->key].begin(); while(startingItr != startVertex2PolygonEdgeData[vertexItr->key].end()) { activeEdges.insert(*startingItr); ++startingItr; } ++vertexItr; } #ifdef CSGJS_DEBUG if(activeEdges.size() > 0) { std::cout << "still have " << activeEdges.size() << " edges in active list" << std::endl; std::unordered_set::iterator itr = activeEdges.begin(); while(itr != activeEdges.end()) { std::cout << (*itr)->first << " " << (*itr)->second << std::endl; ++itr; } std::cout << "active edges set wasn't empty" << std::endl; throw new std::runtime_error("active edges set wasn't empty"); } #endif // insert vertices into polygons that were encountered in forward order std::unordered_set::iterator forwardItr = insertForward.begin(); while(forwardItr != insertForward.end()) { Polygon* polygon = *forwardItr; //std::cout << "inserting " << verticesToInsert[polygon].size() << " extra vertices" << std::endl; std::vector >::iterator insertItr = verticesToInsert[polygon].begin(); //while(insertItr != verticesToInsert[polygon].end()) { //std::cout << *polygon << std::endl; // //std::cout << "inserting" << insertItr->first << " after " << insertItr->second << std::endl; // ++insertItr; //} //insertItr = verticesToInsert[polygon].begin(); //std::cout << polygon->vertices << std::endl; std::vector::iterator vertexItr = polygon->vertices.begin(); std::vector newVertices; while(vertexItr != polygon->vertices.end()) { newVertices.push_back(*vertexItr); while(insertItr != verticesToInsert[polygon].end() && vertexItr->pos == insertItr->second) { newVertices.push_back(Vertex(insertItr->first)); ++insertItr; } ++vertexItr; } //std::cout << "replacing " << polygon->vertices.size() << " vertices with " << newVertices.size() << " vertices" << std::endl; polygon->vertices = std::move(newVertices); //std::cout << polygon->vertices << std::endl; ++forwardItr; } // insert vertices into polygons that were encountered in reverse order std::unordered_set::iterator reverseItr = insertReversed.begin();; while(reverseItr != insertReversed.end()) { Polygon* polygon = *reverseItr; //std::cout << "rev inserting " << verticesToInsert[polygon].size() << " extra vertices" << std::endl; std::vector >::reverse_iterator insertItr = verticesToInsert[polygon].rbegin(); std::vector::iterator vertexItr = polygon->vertices.begin(); std::vector newVertices; while(vertexItr != polygon->vertices.end()) { newVertices.push_back(*vertexItr); while(insertItr != verticesToInsert[polygon].rend() && vertexItr->pos == insertItr->second) { newVertices.push_back(Vertex(insertItr->first)); ++insertItr; } ++vertexItr; } //std::cout << "rev replacing " << polygon->vertices.size() << " vertices with " << newVertices.size() << " vertices" << std::endl; polygon->vertices = std::move(newVertices); ++reverseItr; } ++lineItr; ++lineNum; } #ifdef CSGJS_DEBUG std::unordered_map stillUnmatched; findUnmatchedEdges(stillUnmatched); if(stillUnmatched.size() > 0) { std::cout << "still " << stillUnmatched.size() << " unmatched edges" << std::endl; std::unordered_map::iterator itr = stillUnmatched.begin(); while(itr != stillUnmatched.end()) { LineKey lineKey(Line::fromPoints(itr->first.first, itr->first.second)); std::cout << itr->first.hash << " " << itr->second.first << " " << itr->second.second << " " << lineKey.hash << " " << lineKey.line << std::endl; ++itr; } std::cout << "still " << stillUnmatched.size() << " unmatched edges" << std::endl; throw new std::runtime_error("still unmatched edges"); } #endif } std::ostream& operator<<(std::ostream& os, const CSG &csg) { std::vector::const_iterator itr = csg._polygons.begin(); os << "CSG {" << std::endl; while(itr != csg._polygons.end()) { os << *itr; ++itr; if(itr != csg._polygons.end()) { os << ","; } os << std::endl; } os << "}"; return os; } } stl_cmd-1.1/src/csgjs/CSG.h000066400000000000000000000020761322161221000154600ustar00rootroot00000000000000#ifndef __CSGJS__CSG__ #define __CSGJS__CSG__ #include "csgjs/math/Polygon3.h" #include "csgjs/math/Matrix4x4.h" #include #include #include "csgjs/math/HashKeys.h" #include namespace csgjs { class CSG { private: std::vector _polygons; bool _isManifold; mutable bool _boundingBoxCacheValid; mutable std::pair _boundingBoxCache; CSG unionForNonIntersecting(const CSG &csg) const; void findUnmatchedEdges(std::unordered_map &u); public: CSG(); CSG(const std::vector &p); CSG(std::vector &&p); std::vector toPolygons() const; CSG csgUnion(const CSG &csg) const; CSG csgIntersect(const CSG &csg) const; CSG csgSubtract(const CSG &csg) const; bool mayOverlap(const CSG &csg) const; std::pair getBounds() const; CSG transform(const Matrix4x4 &m); void canonicalize(); void makeManifold(); friend std::ostream& operator<<(std::ostream& os, const CSG &csg); }; } #endif stl_cmd-1.1/src/csgjs/README.md000066400000000000000000000015161322161221000161500ustar00rootroot00000000000000C++ port of CSG.js ================== This a C++ port of CSG.js used in OpenJSCAD (https://github.com/jscad/csg.js). OpenJSCAD's CSG.js has significant performance improvements over the original CSG.js (https://github.com/evanw/csg.js/), which was ported to C++ here (https://github.com/dabroz/csgjs-cpp). The speed of OpenJSCAD's CSG.js implmented in JavaScript is faster than the original C++ port, so the idea is to get those gains and more by implementing OpenJSCAD's CSG.js in C++. So far just the bare minimum is implemented, with the ability to do CSG operations without the retessellation feature of CSG.js (reduces the number of polygons in the end result). The stl_boolean command leverages this implementation to be able to do CSG operations on two STL files. Without the overhead of JavaScript, a single operation runs very quickly. stl_cmd-1.1/src/csgjs/Trees.cpp000066400000000000000000000334361322161221000164650ustar00rootroot00000000000000#include "csgjs/Trees.h" namespace csgjs { Node::Node() : parent(NULL), front(NULL), back(NULL) { } Node::Node(Node *p) : parent(p), front(NULL), back(NULL) { } void Node::invert() { plane = plane.flipped(); if(front != NULL) { front->invert(); } if(back != NULL) { back->invert(); } Node *n = front; front = back; back = n; } void Node::addPolygonTreeNodes(const std::vector &polyTreeNodes) { std::vector frontNodes; std::vector backNodes; if(polyTreeNodes.size() > 0) { int pick = fastRandom(polyTreeNodes.size()); // int pick = 0; plane = polyTreeNodes[pick]->getPolygon().plane; } std::vector::const_iterator itr = polyTreeNodes.begin(); while(itr != polyTreeNodes.end()) { // why is backNodes set to both coplanarBacknodes and backnodes? (*itr)->splitByPlane(plane, polygonTreeNodes, backNodes, frontNodes, backNodes); ++itr; } // CSG.js did this iteratively rather than recursively. Probably safer to do iteratively, but starting with a recursive // solution for ease of implementation. If it leads to stack overflows, will refactor. May see a performance improvement // when implemented iteratively, so it might be worth trying. if(frontNodes.size() > 0) { front = new Node(this); front->addPolygonTreeNodes(frontNodes); } if(backNodes.size() > 0) { back = new Node(this); back->addPolygonTreeNodes(backNodes); } } bool Node::isRootNode() const { return parent == NULL; } void Node::clipTo(Tree &tree, bool alsoRemoveCoplanarFront) { if(polygonTreeNodes.size() > 0) { tree.rootnode.clipPolygons(polygonTreeNodes, alsoRemoveCoplanarFront); } if(front != NULL) { front->clipTo(tree, alsoRemoveCoplanarFront); } if(back != NULL) { back->clipTo(tree, alsoRemoveCoplanarFront); } } void Node::clipPolygons(std::vector &polyTreeNodes, bool alsoRemoveCoplanarFront) { std::vector frontNodes; std::vector backNodes; std::vector::iterator itr = polyTreeNodes.begin(); while(itr != polyTreeNodes.end()) { PolygonTreeNode *node = (*itr); if(!node->isRemoved()) { node->splitByPlane(plane, alsoRemoveCoplanarFront ? backNodes : frontNodes, backNodes, frontNodes, backNodes); } ++itr; } if(front != NULL && frontNodes.size() > 0) { front->clipPolygons(frontNodes); } if(back != NULL && backNodes.size() > 0) { back->clipPolygons(backNodes); } else { std::vector::iterator backItr = backNodes.begin(); while(backItr != backNodes.end()) { (*backItr)->remove(); ++backItr; } } } Tree::Tree(const std::vector &polygons) { addPolygons(polygons); } void Tree::addPolygons(const std::vector &polygons) { std::vector::const_iterator itr = polygons.begin(); std::vector polyTreeNodes; polyTreeNodes.reserve(polygons.size()); while(itr != polygons.end()) { polyTreeNodes.push_back(polygonTree.addChild(*itr)); ++itr; } rootnode.addPolygonTreeNodes(polyTreeNodes); } void Tree::invert() { polygonTree.invert(); rootnode.invert(); } void Tree::clipTo(Tree &tree, bool alsoRemoveCoplanarFront) { rootnode.clipTo(tree, alsoRemoveCoplanarFront); } std::vector Tree::toPolygons() { std::vector polygons; polygonTree.getPolygons(polygons); return polygons; } PolygonTreeNode::PolygonTreeNode() : parent(NULL), removed(false), valid(false) {} PolygonTreeNode::PolygonTreeNode(PolygonTreeNode *p, const Polygon &poly) : parent(p), polygon(poly), removed(false), valid(true) {} PolygonTreeNode::~PolygonTreeNode() { std::vector::iterator itr = children.begin(); while(itr != children.end()) { delete *itr; ++itr; } } void PolygonTreeNode::invalidate() { valid = false; if(parent != NULL) { parent->invalidate(); } } void PolygonTreeNode::remove() { #ifdef CSGJS_DEBUG if(isRootNode()) { throw std::runtime_error("trying to delete root node"); } if(children.size() > 0) { throw std::runtime_error("trying to delete node with children"); } #endif invalidate(); // 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 // Maybe use some kind of smart pointer so we can remove them here //parent->children.erase(std::remove(parent->children.begin(), parent->children.end(), this), parent->children.end()); //delete this; } PolygonTreeNode* PolygonTreeNode::addChild(const Polygon &polygon) { PolygonTreeNode *child = new PolygonTreeNode(this, polygon); children.push_back(child); return child; } bool PolygonTreeNode::isRootNode() const { return parent == NULL; } bool PolygonTreeNode::isRemoved() const { return removed; } Polygon& PolygonTreeNode::getPolygon() { return polygon; } // Like addPolygonTreeNodes, this was implemented iteratively in CSG.js, but we're doing it recursively here. // Might be worth revisiting. void PolygonTreeNode::splitByPlane(const Plane &plane, std::vector &coplanarFrontNodes, std::vector &coplanarBackNodes, std::vector &frontNodes, std::vector &backNodes) { if(children.size() > 0) { std::vector::iterator itr = children.begin(); while(itr != children.end()) { (*itr)->splitByPlane(plane, coplanarFrontNodes, coplanarBackNodes, frontNodes, backNodes); ++itr; } } else { if(valid) { splitLeafByPlane(plane, coplanarFrontNodes, coplanarBackNodes, frontNodes, backNodes); } } } void PolygonTreeNode::splitLeafByPlane(const Plane &plane, std::vector &coplanarFrontNodes, std::vector &coplanarBackNodes, std::vector &frontNodes, std::vector &backNodes) { #ifdef CSGJS_DEBUG if(children.size() > 0) { throw std::runtime_error("trying to split non-leaf node"); } #endif std::pair bound = polygon.boundingSphere(); csgjs_real sphereRadius = bound.second; Vector3 sphereCenter = bound.first; Vector3 planeNormal = plane.normal; csgjs_real d = planeNormal.dot(sphereCenter) - plane.w; if(d > sphereRadius) { frontNodes.push_back(this); } else if(d < -sphereRadius) { backNodes.push_back(this); } else { splitPolygonByPlane(plane, coplanarFrontNodes, coplanarBackNodes, frontNodes, backNodes); } } void PolygonTreeNode::invertRecurse() { if(valid) { polygon = polygon.flipped(); } std::vector::iterator itr = children.begin(); while(itr != children.end()) { (*itr)->invertRecurse(); ++itr; } } void PolygonTreeNode::invert() { #ifdef CSGJS_DEBUG if(!isRootNode()) { throw std::runtime_error("can only call invert on root node"); } #endif invertRecurse(); } void PolygonTreeNode::splitPolygonByPlane(const Plane &plane, std::vector &coplanarFrontNodes, std::vector &coplanarBackNodes, std::vector &frontNodes, std::vector &backNodes) { if(plane == polygon.plane) { // if the polygon's plane is exactly the same as the cutting plane it as a coplanar front coplanarFrontNodes.push_back(this); } else { std::vector vertexIsBack; vertexIsBack.reserve(polygon.vertices.size()); std::vector::iterator itr = polygon.vertices.begin(); bool hasFront = false; bool hasBack = false; while(itr != polygon.vertices.end()) { csgjs_real t = plane.normal.dot(itr->pos)-plane.w; bool isBack = t < 0; vertexIsBack.push_back(isBack); if(t > EPS) { hasFront = true; } if(t < NEG_EPS) { hasBack = true; } ++itr; } if(!hasFront && !hasBack) { if(plane.normal.dot(polygon.plane.normal) >= 0) { // if the polygon's plane is in the same direction as the cutting plane // and all of our vertices were within tolerance of being on the plane coplanarFrontNodes.push_back(this); } else { // if the polygon's plane is in the opposite direction as the cutting plane // and all of our vertices were within tolerance of being on the plane coplanarBackNodes.push_back(this); } } else if(!hasBack) { // if the polygon only has vertices in front of the cutting plane frontNodes.push_back(this); } else if(!hasFront) { // if the polygon only has vertices behind the cutting plane backNodes.push_back(this); } else { // the polygon crosses the cutting plane and needs to be divided into a front and back polygon std::vector frontVertices; std::vector backVertices; int numVertices = polygon.vertices.size(); for(int i = 0; i < numVertices; i++) { int nextI = i == (numVertices-1) ? 0 : i+1; Vertex vertex = polygon.vertices[i]; Vertex nextVertex = polygon.vertices[nextI]; bool isBack = vertexIsBack[i]; bool nextIsBack = vertexIsBack[nextI]; if(isBack == nextIsBack) { // line segment is entirely on one side of the plane if(isBack) { backVertices.push_back(vertex); } else { frontVertices.push_back(vertex); } } else { // line segment intersects plane Vector3 pos = vertex.pos; Vector3 nextPos = nextVertex.pos; Vertex intersectionV(plane.splitLineBetweenPoints(pos, nextPos)); if(isBack) { backVertices.push_back(vertex); backVertices.push_back(intersectionV); frontVertices.push_back(intersectionV); } else { frontVertices.push_back(vertex); frontVertices.push_back(intersectionV); backVertices.push_back(intersectionV); } } } if(backVertices.size() >= 3) { int numBackVertices = backVertices.size(); Vertex prevVertex = backVertices[numBackVertices-1]; std::vector::iterator backVertsItr = backVertices.begin(); while(backVertsItr != backVertices.end()) { Vertex v = *backVertsItr; if(v.pos.distanceTo(prevVertex.pos) < EPS) { backVertsItr = backVertices.erase(backVertsItr); } else { prevVertex = v; ++backVertsItr; } } } if(frontVertices.size() >= 3) { int numFrontVertices = frontVertices.size(); Vertex prevVertex = frontVertices[numFrontVertices-1]; std::vector::iterator frontVertsItr = frontVertices.begin(); while(frontVertsItr != frontVertices.end()) { Vertex v = *frontVertsItr; if(v.pos.distanceTo(prevVertex.pos) < EPS) { frontVertsItr = frontVertices.erase(frontVertsItr); } else { prevVertex = v; ++frontVertsItr; } } } if(frontVertices.size() >= 3) { PolygonTreeNode *node = addChild(Polygon(std::move(frontVertices), polygon.plane)); frontNodes.push_back(node); } if(backVertices.size() >= 3) { PolygonTreeNode *node = addChild(Polygon(std::move(backVertices), polygon.plane)); backNodes.push_back(node); } } } } void PolygonTreeNode::getPolygons(std::vector &polygons) const { if(valid) { polygons.push_back(polygon); } else { std::vector::const_iterator itr = children.begin(); while(itr != children.end()) { (*itr)->getPolygons(polygons); ++itr; } } } int PolygonTreeNode::countNodes() const { int count = 1; std::vector::const_iterator itr = children.begin(); while(itr != children.end()) { count += (*itr)->countNodes(); ++itr; } return count; } std::ostream& operator<<(std::ostream& os, const Tree &tree) { // os << tree.rootnode << std::endl; os << tree.polygonTree.countNodes() << std::endl; return os; } std::ostream& indentChildNodes(std::ostream& os, const PolygonTreeNode *node, int level) { for(int i = 0; i < level; i++) { os << " "; } os << node->polygon; if(node->children.size() > 0) { os << "Children: "; os << std::endl; std::vector::const_iterator itr = node->children.begin(); while(itr != node->children.end()) { indentChildNodes(os, *itr, level+1); ++itr; } } else { os << std::endl; } return os; } std::ostream& operator<<(std::ostream& os, const PolygonTreeNode &node) { return indentChildNodes(os, &node, 0); } } stl_cmd-1.1/src/csgjs/Trees.h000066400000000000000000000062451322161221000161300ustar00rootroot00000000000000#ifndef __CSGJS_TREES__ #define __CSGJS_TREES__ #include "csgjs/util.h" #include #include "csgjs/math/Plane.h" #include "csgjs/math/Polygon3.h" namespace csgjs { class PolygonTreeNode { private: PolygonTreeNode *parent; std::vector children; Polygon polygon; bool valid; bool removed; void splitLeafByPlane(const Plane &plane, std::vector &coplanarFrontNodes, std::vector &coplanarBackNodes, std::vector &frontNodes, std::vector &backNodes); void splitPolygonByPlane(const Plane &plane, std::vector &coplanarFrontNodes, std::vector &coplanarBackNodes, std::vector &frontNodes, std::vector &backNodes); void invertRecurse(); public: PolygonTreeNode(); PolygonTreeNode(const Polygon &polygon); PolygonTreeNode(PolygonTreeNode *parent, const Polygon &polygon); ~PolygonTreeNode(); PolygonTreeNode* addChild(const Polygon &polygon); void getPolygons(std::vector &polygons) const; void invalidate(); void remove(); void invert(); bool isRootNode() const; bool isRemoved() const; int countNodes() const; Polygon& getPolygon(); void splitByPlane(const Plane &plane, std::vector &coplanarFrontNodes, std::vector &coplanarBackNodes, std::vector &frontNodes, std::vector &backNodes); friend std::ostream& indentChildNodes(std::ostream& os, const PolygonTreeNode *node, int level); friend std::ostream& operator<<(std::ostream& os, const PolygonTreeNode &polygonTreeNode); }; class Tree; class Node { private: Plane plane; Node* front; Node* back; Node* parent; std::vector polygonTreeNodes; public: Node(); Node(Node* p); bool isRootNode() const; void invert(); void clipTo(Tree &tree, bool alsoRemoveCoplanarFront=false); void clipPolygons(std::vector &polyTreeNodes, bool alsoRemoveCoplanarFront=false); void addPolygonTreeNodes(const std::vector &polyTreeNodes); }; // Root node of the CSG tree and PolygonTree class Tree { private: Node rootnode; PolygonTreeNode polygonTree; public: Tree(const std::vector &polygons); void addPolygons(const std::vector &polygons); void clipTo(Tree &tree, bool alsoRemoveCoplanarFront=false); void invert(); std::vector toPolygons(); friend std::ostream& operator<<(std::ostream& os, const Tree &tree); friend class Node; }; } #endif stl_cmd-1.1/src/csgjs/constants.h000066400000000000000000000003331322161221000170520ustar00rootroot00000000000000#ifndef __CSGJS_CONSTANTS__ #define __CSGJS_CONSTANTS__ typedef double csgjs_real; //#define CSGJS_DEBUG const csgjs_real EPS = .00001; const csgjs_real NEG_EPS = -EPS; const csgjs_real EPS_SQUARED = EPS*EPS; #endif stl_cmd-1.1/src/csgjs/math/000077500000000000000000000000001322161221000156175ustar00rootroot00000000000000stl_cmd-1.1/src/csgjs/math/HashKeys.cpp000066400000000000000000000110301322161221000200350ustar00rootroot00000000000000#include "csgjs/math/HashKeys.h" namespace csgjs { LineKey::LineKey(const Line& l) { // A point and direction define a line. We want any equal Line to have the same hash value, so we need // a consistent way to represent a line, such that any Line we pass to this constructor will yield the // same point and direction. We'll store the point that intersects the plane that intersects the origin, // whose normal is the same as the direction of the line. We'll compare the direction of the line to // Vector(0,0,1) to determine a consistent direction (store the direction that points in roughly the // same direction as Vector(0,0,1)) // We eliminate floating point errors by rounding to integers after scaling up by 1./EPS Vector3 d = l.direction.unit(); Vector3 point = l.point-d*(d.dot(l.point)); float dotZ = d.dot(Vector3(0,0,1)); if(dotZ > EPS) { line = Line(point, d); } else if(dotZ < -EPS) { line = Line(point, -d); } else { float dotY = d.dot(Vector3(0,1,0)); if(dotY > EPS) { line = Line(point, d); } else if(dotY < -EPS) { line = Line(point, -d); } else { float dotX = d.dot(Vector3(1,0,0)); if(dotX > EPS) { line = Line(point, d); } else { line = Line(point, -d); } } } long int x = (long int)(std::round(line.direction.x/(10*EPS))); long int y = (long int)(std::round(line.direction.y/(10*EPS))); long int z = (long int)(std::round(line.direction.z/(10*EPS))); long int x2 = (long int)(std::round(line.point.x/(10*EPS))); long int y2 = (long int)(std::round(line.point.y/(10*EPS))); long int z2 = (long int)(std::round(line.point.z/(10*EPS))); // hash = (((std::hash()(x) ^ (std::hash()(y) << 1)) >> 1) ^ (std::hash()(z) << 1)) ^ // (((std::hash()(x2) ^ (std::hash()(y2) << 1)) >> 1) ^ (std::hash()(z2) << 1)); hash = (std::hash()(x) ^ std::hash()(y) ^ std::hash()(z)) ^ (std::hash()(x2) ^ std::hash()(y2) ^ std::hash()(z2)); } bool LineKey::operator==(const LineKey &l) const { return l.line == line; } EdgeKey::EdgeKey(const Vector3 &a, const Vector3 &b) { first = a; second = b; long int x = (long int)(std::round(first.x/(10*EPS))); long int y = (long int)(std::round(first.y/(10*EPS))); long int z = (long int)(std::round(first.z/(10*EPS))); long int x2 = (long int)(std::round(second.x/(10*EPS))); long int y2 = (long int)(std::round(second.y/(10*EPS))); long int z2 = (long int)(std::round(second.z/(10*EPS))); // hash = (((std::hash()(x) ^ (std::hash()(y) << 1)) >> 1) ^ (std::hash()(z) << 1)) ^ // (((std::hash()(x2) ^ (std::hash()(y2) << 1)) >> 1) ^ (std::hash()(z2) << 1)); hash = (std::hash()(x) ^ std::hash()(y) ^ std::hash()(z)) ^ (std::hash()(x2) ^ std::hash()(y2) ^ std::hash()(z2)); } EdgeKey EdgeKey::reversed() const { return EdgeKey(second, first); } bool EdgeKey::operator==(const EdgeKey &k) const { return (k.first-first).length() < EPS && (k.second-second).length() < EPS; } VertexKey::VertexKey(const Vector3 &a) : v(a) { long int x = (long int)(std::round(v.x/(10*EPS))); long int y = (long int)(std::round(v.y/(10*EPS))); long int z = (long int)(std::round(v.z/(10*EPS))); // hash = (((std::hash()(x) ^ (std::hash()(y) << 1)) >> 1) ^ (std::hash()(z) << 1)); hash = (std::hash()(x) ^ std::hash()(y) ^ std::hash()(z)); } bool VertexKey::operator==(const VertexKey &a) const { return (a.v-v).length() < EPS; } VertexKeyDist::VertexKeyDist(const VertexKey &k, csgjs_real b) : key(k), dist(b) { } bool VertexKeyDist::operator<(const VertexKeyDist &k) const { return dist-k.dist < -EPS; } bool VertexKeyDist::operator==(const VertexKeyDist &k) const { return key == k.key; } } std::size_t std::hash::operator()(const csgjs::LineKey& l) const { return l.hash; } std::size_t std::hash::operator()(const csgjs::EdgeKey& e) const { return e.hash; } std::size_t std::hash::operator()(const csgjs::VertexKey& v) const { return v.hash; } std::size_t std::hash::operator()(const csgjs::VertexKeyDist& v) const { return v.key.hash; } stl_cmd-1.1/src/csgjs/math/HashKeys.h000066400000000000000000000024441322161221000175130ustar00rootroot00000000000000#ifndef __CSGJS_HASHKEYS__ #define __CSGJS_HASHKEYS__ #include "csgjs/math/Line3.h" namespace csgjs { struct LineKey { std::size_t hash; Line line; LineKey(const Line &l); bool operator==(const LineKey &l) const; }; struct EdgeKey { std::size_t hash; Vector3 first; Vector3 second; EdgeKey(const Vector3 &a, const Vector3 &b); bool operator==(const EdgeKey &k) const; EdgeKey reversed() const; }; struct VertexKey { std::size_t hash; Vector3 v; VertexKey(const Vector3 &a); bool operator==(const VertexKey &k) const; }; struct VertexKeyDist { VertexKey key; csgjs_real dist; VertexKeyDist(const VertexKey &a, csgjs_real b); bool operator<(const VertexKeyDist &k) const; bool operator==(const VertexKeyDist &k) const; }; } namespace std { template <> struct hash { std::size_t operator()(const csgjs::LineKey& l) const; }; template <> struct hash { std::size_t operator()(const csgjs::EdgeKey& e) const; }; template <> struct hash { std::size_t operator()(const csgjs::VertexKey& e) const; }; template <> struct hash { std::size_t operator()(const csgjs::VertexKeyDist& e) const; }; } #endif stl_cmd-1.1/src/csgjs/math/Line3.cpp000066400000000000000000000017631322161221000173040ustar00rootroot00000000000000#include "csgjs/math/Line3.h" #include namespace csgjs { Line::Line() : point(Vector3(0,0,0)), direction(Vector3(0,0,0)) { // point and direction } Line::Line(const Vector3 &p, const Vector3 &d) : point(p), direction(d) { // point and direction } csgjs_real Line::distanceToPointOnLine(const Vector3 &p) const { return (p-point).dot(direction); } Vector3 Line::closestPointOnLine(const Vector3 &p) const { return point+direction*(p-point).dot(direction); } csgjs_real Line::distanceToPoint(const Vector3 &p) const { return (p-closestPointOnLine(p)).length(); } bool Line::operator==(const Line &l) const { return (l.direction-direction).length() <= EPS && (l.point-point).length() <= EPS; } Line Line::fromPoints(const Vector3 &p1, const Vector3 &p2) { return Line(p1, p2-p1); } std::ostream& operator<<(std::ostream& os, const Line &line) { os << "Line - point: " << line.point << ", direction: " << line.direction; return os; } } stl_cmd-1.1/src/csgjs/math/Line3.h000066400000000000000000000011361322161221000167430ustar00rootroot00000000000000#ifndef __CSGJS_LINE3__ #define __CSGJS_LINE3__ #include "csgjs/math/Vector3.h" #include namespace csgjs { struct Line { Vector3 direction; Vector3 point; Line(); Line(const Vector3 &p, const Vector3 &d); Vector3 closestPointOnLine(const Vector3 &p) const; csgjs_real distanceToPoint(const Vector3 &p) const; csgjs_real distanceToPointOnLine(const Vector3 &p) const; bool operator==(const Line &l) const; static Line fromPoints(const Vector3 &p1, const Vector3 &p2); }; std::ostream& operator<<(std::ostream& os, const Line &line); } #endif stl_cmd-1.1/src/csgjs/math/Matrix4x4.cpp000066400000000000000000000113471322161221000201350ustar00rootroot00000000000000#include "csgjs/math/Matrix4x4.h" #include "csgjs/math/Vector3.h" namespace csgjs { Matrix4x4::Matrix4x4() { // identity matrix m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = 1; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = 1; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; } // mrc - m 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) { // identity matrix m[0] = m00; m[1] = m01; m[2] = m02; m[3] = m03; m[4] = m10; m[5] = m11; m[6] = m12; m[7] = m13; m[8] = m20; m[9] = m21; m[10] = m22; m[11] = m23; m[12] = m30; m[13] = m31; m[14] = m32; m[15] = m33; } // this seems more consistent with how transforms are applied // but I transposed from what was in CSG.js, would // love for someone to tell me if I'm wrong or if it doesn't matter bool Matrix4x4::isMirroring() const { Vector3 u(m[0], m[1], m[2]); Vector3 v(m[4], m[5], m[6]); Vector3 w(m[8], m[9], m[10]); return u.cross(v).dot(w) < 0; } Matrix4x4 Matrix4x4::operator+(const Matrix4x4 &mat) const { return Matrix4x4(m[0]+mat.m[0], m[1]+mat.m[1], m[2]+mat.m[2], m[3]+mat.m[3], m[4]+mat.m[4], m[5]+mat.m[5], m[6]+mat.m[6], m[7]+mat.m[7], m[8]+mat.m[8], m[9]+mat.m[9], m[10]+mat.m[10], m[11]+mat.m[11], m[12]+mat.m[12], m[13]+mat.m[13], m[14]+mat.m[14], m[15]+mat.m[15]); } Matrix4x4 Matrix4x4::operator-(const Matrix4x4 &mat) const { return Matrix4x4(m[0]-mat.m[0], m[1]-mat.m[1], m[2]-mat.m[2], m[3]-mat.m[3], m[4]-mat.m[4], m[5]-mat.m[5], m[6]-mat.m[6], m[7]-mat.m[7], m[8]-mat.m[8], m[9]-mat.m[9], m[10]-mat.m[10], m[11]-mat.m[11], m[12]-mat.m[12], m[13]-mat.m[13], m[14]-mat.m[14], m[15]-mat.m[15]); } Matrix4x4 Matrix4x4::operator*(const Matrix4x4 &mat) const { const csgjs_real a00 = m[0]; const csgjs_real a01 = m[1]; const csgjs_real a02 = m[2]; const csgjs_real a03 = m[3]; const csgjs_real a10 = m[4]; const csgjs_real a11 = m[5]; const csgjs_real a12 = m[6]; const csgjs_real a13 = m[7]; const csgjs_real a20 = m[8]; const csgjs_real a21 = m[9]; const csgjs_real a22 = m[10]; const csgjs_real a23 = m[11]; const csgjs_real a30 = m[12]; const csgjs_real a31 = m[13]; const csgjs_real a32 = m[14]; const csgjs_real a33 = m[15]; const csgjs_real b00 = mat.m[0]; const csgjs_real b01 = mat.m[1]; const csgjs_real b02 = mat.m[2]; const csgjs_real b03 = mat.m[3]; const csgjs_real b10 = mat.m[4]; const csgjs_real b11 = mat.m[5]; const csgjs_real b12 = mat.m[6]; const csgjs_real b13 = mat.m[7]; const csgjs_real b20 = mat.m[8]; const csgjs_real b21 = mat.m[9]; const csgjs_real b22 = mat.m[10]; const csgjs_real b23 = mat.m[11]; const csgjs_real b30 = mat.m[12]; const csgjs_real b31 = mat.m[13]; const csgjs_real b32 = mat.m[14]; const csgjs_real b33 = mat.m[15]; return Matrix4x4(a00*b00+a01*b10+a02*b20+a03*b30, a00*b01+a01*b11+a02*b21+a03*b31, a00*b02+a01*b12+a02*b22+a03*b32, a00*b03+a01*b13+a02*b23+a03*b33, a10*b00+a11*b10+a12*b20+a13*b30, a10*b01+a11*b11+a12*b21+a13*b31, a10*b02+a11*b12+a12*b22+a13*b32, a10*b03+a11*b13+a12*b23+a13*b33, a20*b00+a21*b10+a22*b20+a23*b30, a20*b01+a21*b11+a22*b21+a23*b31, a20*b02+a21*b12+a22*b22+a23*b32, a20*b03+a21*b13+a22*b23+a23*b33, a30*b00+a31*b10+a32*b20+a33*b30, a30*b01+a31*b11+a32*b21+a33*b31, a30*b02+a31*b12+a32*b22+a33*b32, a30*b03+a31*b13+a32*b23+a33*b33); } Matrix4x4 Matrix4x4::translate(csgjs_real x, csgjs_real y, csgjs_real z) { return Matrix4x4(1,0,0,0, 0,1,0,0, 0,0,1,0, x,y,z,1); } } stl_cmd-1.1/src/csgjs/math/Matrix4x4.h000066400000000000000000000022061322161221000175740ustar00rootroot00000000000000#ifndef __CSGJS_MATRIX4x4__ #define __CSGJS_MATRIX4x4__ #include "csgjs/constants.h" // row major implmentation of 4x4 matrix // i.e. values stored as [ a b c d e f g h i j k l m n o p ] // represent: // | a b c d | // | e f g h | // | i j k l | // | m n o p | // // This means that you left multiply to transform a point/vector: // // [ 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 ] // | yx yy yz 0 | // | zx zy zz 0 | // | tx ty tz 1 | // namespace csgjs { struct Vector3; struct Matrix4x4 { csgjs_real m[16]; 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); bool isMirroring() const; Matrix4x4 operator+(const Matrix4x4 &mat) const; Matrix4x4 operator-(const Matrix4x4 &mat) const; Matrix4x4 operator*(const Matrix4x4 &mat) const; static Matrix4x4 translate(csgjs_real x, csgjs_real y, csgjs_real z); }; } #endif stl_cmd-1.1/src/csgjs/math/Plane.h000066400000000000000000000044401322161221000170310ustar00rootroot00000000000000#ifndef __CSGJS_PLANE__ #define __CSGJS_PLANE__ #include "csgjs/math/Vector3.h" #include "csgjs/constants.h" namespace csgjs { class Plane; inline std::ostream& operator<<(std::ostream& os, const Plane &plane); struct Plane { Vector3 normal; csgjs_real w; Plane() : normal(), w(0) {} Plane(const Vector3 &n, const csgjs_real ww) : normal(n), w(ww) {} Plane flipped() const { return Plane(-normal, -w); } Plane transform(const Matrix4x4 &m) const { bool ismirror = m.isMirroring(); Vector3 r = normal.nonParallelVector(); Vector3 u = normal.cross(r); Vector3 v = normal.cross(u); Vector3 p1 = normal*w; Vector3 p2 = p1+u; Vector3 p3 = p1+v; Plane newPlane = Plane::fromVector3s(p1,p2,p3); if(ismirror) { newPlane = newPlane.flipped(); } return newPlane; } Vector3 splitLineBetweenPoints(const Vector3 &p1, const Vector3 &p2) const { Vector3 dir = p2-p1; csgjs_real dot = normal.dot(dir); csgjs_real lambda = 0; if(dot > EPS || dot < NEG_EPS) { lambda = (w-normal.dot(p1))/dot; } if(lambda > 1) { lambda = 1; } if(lambda < 0) { lambda = 0; } Vector3 inter = p1+dir*lambda; return p1+dir*lambda; } bool operator==(const Plane &p) const { return normal == p.normal && w == p.w; } static Plane fromVector3s(const Vector3 &a, const Vector3 &b, const Vector3 &c) { Vector3 n = ((b-a).cross(c-a)).unit(); return Plane(n, n.dot(a)); } static Plane anyPlaneFromVector3s(const Vector3 &a, const Vector3 &b, const Vector3 &c) { Vector3 v1 = b-a; Vector3 v2 = c-a; if(v1.length() < EPS) { v1 = v2.nonParallelVector(); } if(v2.length() < EPS) { v2 = v1.nonParallelVector(); } Vector3 normal = v1.cross(v2); if(normal.length() < EPS) { // this means that v1 == -v2 v2 = v1.nonParallelVector(); normal = v1.cross(v2); } normal = normal.unit(); return Plane(normal, normal.dot(a)); } static Plane fromNormalAndPoint(const Vector3 &n, const Vector3 &p) { Vector3 normal = n.unit(); csgjs_real w = p.dot(normal); return Plane(normal, w); } }; inline std::ostream& operator<<(std::ostream& os, const Plane &plane) { os << plane.normal << ", " << plane.w; return os; } } #endif stl_cmd-1.1/src/csgjs/math/Polygon3.cpp000066400000000000000000000124031322161221000200350ustar00rootroot00000000000000#include "csgjs/math/Polygon3.h" #include namespace csgjs { Polygon::Polygon(const std::vector &v, const Plane &p) : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false), vertices(v), plane(p) { #ifdef CSGJS_DEBUG if(!checkIfConvex()) { std::cout << *this << std::endl; throw std::runtime_error("Not convex!"); } #endif } Polygon::Polygon(std::vector &&v, const Plane &p) : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false), vertices(v), plane(p) { #ifdef CSGJS_DEBUG if(!checkIfConvex()) { std::cout << *this << std::endl; throw std::runtime_error("Not convex!"); } #endif } Polygon::Polygon(const std::vector &v) : vertices(v), _boundingSphereCacheValid(false), _boundingBoxCacheValid(false) { plane = Plane::fromVector3s(vertices[0].pos, vertices[1].pos, vertices[2].pos); #ifdef CSGJS_DEBUG if(!checkIfConvex()) { std::cout << *this << std::endl; throw std::runtime_error("Not convex!"); } #endif } Polygon::Polygon() : _boundingSphereCacheValid(false), _boundingBoxCacheValid(false) {} Polygon Polygon::flipped() const { std::vector newVertices; Plane newPlane = plane.flipped(); std::vector::const_reverse_iterator itr = vertices.rbegin(); while(itr != vertices.rend()) { newVertices.push_back(itr->flipped()); ++itr; } return Polygon(std::move(newVertices), newPlane); } bool Polygon::checkIfConvex() const { int numVertices = vertices.size(); if(numVertices > 2) { Vector3 prevprevpos = vertices[numVertices-2].pos; Vector3 prevpos = vertices[numVertices-1].pos; for(int i = 0; i < numVertices; i++) { Vector3 pos = vertices[i].pos; if(!Polygon::isConvexPoint(prevprevpos, prevpos, pos, plane.normal)) { return false; } prevprevpos = prevpos; prevpos = pos; } } return true; } Polygon Polygon::transform(const Matrix4x4 &m) const { std::vector verts(vertices); std::vector::iterator itr = verts.begin(); while(itr != verts.end()) { *itr = itr->transform(m); ++itr; } if(m.isMirroring()) { std::reverse(verts.begin(), verts.end()); } return Polygon(std::move(verts), plane.transform(m)); } bool Polygon::isConvexPoint(const Vector3 &prevpoint, const Vector3 &point, const Vector3 &nextpoint, const Vector3 normal) { Vector3 crossproduct = (point-prevpoint).cross(nextpoint-point); csgjs_real crossdotnormal = crossproduct.dot(normal); return crossdotnormal >= 0; } // seems like this caching scheme could be an unnecessary optimization, but // this is how it was done in CSG.js, maybe try calculating the bounding box and sphere // in the constructor to avoid any branching (it probably makes sense in JavaScript, // but I question the benefit in C++). It would come down to how often polygons are // constructed without ever needing a bounding box or sphere, which I'm not sure about. std::pair Polygon::boundingBox() const { if(!_boundingBoxCacheValid) { std::vector::const_iterator itr = vertices.begin(); if(itr != vertices.end()) { _boundingBoxCache.first = itr->pos; _boundingBoxCache.second = itr->pos; while(itr != vertices.end()) { _boundingBoxCache.first = _boundingBoxCache.first.min(itr->pos); _boundingBoxCache.second = _boundingBoxCache.second.max(itr->pos); ++itr; } _boundingBoxCacheValid = true; } else { _boundingBoxCache.first = Vector3(0,0,0); _boundingBoxCache.second = Vector3(0,0,0); _boundingBoxCacheValid = true; } } return _boundingBoxCache; } std::pair Polygon::boundingSphere() const { if(!_boundingSphereCacheValid) { std::pair box = boundingBox(); _boundingSphereCache.first = .5*(box.first+box.second); _boundingSphereCache.second = (box.second-_boundingSphereCache.first).length(); _boundingSphereCacheValid = true; } return _boundingSphereCache; } PolygonEdgeData::PolygonEdgeData() : polygon(NULL) { } PolygonEdgeData::PolygonEdgeData(Polygon *p, const Vector3 &a, const Vector3 &b) : polygon(p), first(a), second(b) { } std::ostream& operator<<(std::ostream& os, const Polygon &poly) { os << "Polygon - vertices: { "; std::vector::const_iterator itr = poly.vertices.begin(); while(itr != poly.vertices.end()) { os << *itr; ++itr; if(itr != poly.vertices.end()) { os << ", "; } } os << " }, plane: { " << poly.plane << " }"; return os; } std::ostream& operator<<(std::ostream& os, const std::pair &bounds) { os << bounds.first << " - " << bounds.second; return os; } std::ostream& operator<<(std::ostream& os, const std::pair &bounds) { os << bounds.first << " - " << bounds.second; return os; } std::ostream& operator<<(std::ostream& os, const std::vector &vertices) { std::vector::const_iterator itr = vertices.begin(); while(itr != vertices.end()) { os << itr->pos << " "; ++itr; } return os; } } stl_cmd-1.1/src/csgjs/math/Polygon3.h000066400000000000000000000030071322161221000175020ustar00rootroot00000000000000#ifndef __CSGJS_POLYGON3__ #define __CSGJS_POLYGON3__ #include "csgjs/math/Vector3.h" #include "csgjs/math/Vertex3.h" #include "csgjs/math/Plane.h" #include #include namespace csgjs { class Polygon { public: std::vector vertices; Plane plane; Polygon(std::vector &&v, const Plane &p); Polygon(const std::vector &v, const Plane &p); Polygon(const std::vector &v); Polygon(); bool checkIfConvex() const; std::pair boundingSphere() const; std::pair boundingBox() const; Polygon flipped() const; Polygon transform(const Matrix4x4 &m) const; static bool isConvexPoint(const Vector3 &prevpoint, const Vector3 &point, const Vector3 &nextpoint, const Vector3 normal); private: mutable bool _boundingSphereCacheValid; mutable std::pair _boundingSphereCache; mutable bool _boundingBoxCacheValid; mutable std::pair _boundingBoxCache; }; struct PolygonEdgeData { Polygon *polygon; Vector3 first; Vector3 second; PolygonEdgeData(); PolygonEdgeData(Polygon *p, const Vector3 &a, const Vector3 &b); }; std::ostream& operator<<(std::ostream& os, const Polygon &poly); std::ostream& operator<<(std::ostream& os, const std::pair &bounds); std::ostream& operator<<(std::ostream& os, const std::pair &bounds); std::ostream& operator<<(std::ostream& os, const std::vector &vertices); } #endif stl_cmd-1.1/src/csgjs/math/Vector3.cpp000066400000000000000000000064401322161221000176540ustar00rootroot00000000000000#include "csgjs/math/Vector3.h" namespace csgjs { Vector3::Vector3() : x(0), y(0), z(0) {} Vector3::Vector3(csgjs_real xx, csgjs_real yy, csgjs_real zz) : x(xx), y(yy), z(zz) {} Vector3 Vector3::operator-() const { return Vector3(-x, -y, -z); } Vector3 Vector3::operator+(const Vector3 &b) const { return Vector3(x+b.x, y+b.y, z+b.z); } Vector3 Vector3::operator-(const Vector3 &b) const { return Vector3(x-b.x, y-b.y, z-b.z); } Vector3 Vector3::operator*(const csgjs_real m) const { return Vector3(m*x, m*y, m*z); } Vector3 Vector3::operator/(const csgjs_real m) const { return Vector3(x/m, y/m, z/m); } csgjs_real Vector3::dot(const Vector3 &b) const { return x*b.x+y*b.y+z*b.z; } Vector3 Vector3::lerp(const Vector3 &b, csgjs_real t) const { return (*this)+(b-*this)*t; } csgjs_real Vector3::lengthSquared() const { return this->dot(*this); } csgjs_real Vector3::length() const { return sqrt(this->lengthSquared()); } Vector3 Vector3::unit() const { return (*this)/this->length(); } Vector3 Vector3::cross(const Vector3 &a) const { return Vector3(y*a.z-z*a.y, z*a.x-x*a.z, x*a.y-y*a.x); } csgjs_real Vector3::distanceTo(const Vector3 &a) const { return ((*this)-a).length(); } csgjs_real Vector3::distanceToSquared(const Vector3 &a) const { return ((*this)-a).lengthSquared(); } bool Vector3::operator==(const Vector3 &a) const { return x == a.x && y == a.y && z == a.z; } Vector3 Vector3::transform(const Matrix4x4 &m, csgjs_real w) const { const csgjs_real xx = m.m[0]; const csgjs_real xy = m.m[1]; const csgjs_real xz = m.m[2]; const csgjs_real xw = m.m[3]; const csgjs_real yx = m.m[4]; const csgjs_real yy = m.m[5]; const csgjs_real yz = m.m[6]; const csgjs_real yw = m.m[7]; const csgjs_real zx = m.m[8]; const csgjs_real zy = m.m[9]; const csgjs_real zz = m.m[10]; const csgjs_real zw = m.m[11]; const csgjs_real tx = m.m[12]; const csgjs_real ty = m.m[13]; const csgjs_real tz = m.m[14]; const csgjs_real tw = m.m[15]; csgjs_real newX = x*xx+y*yx+z*zx+w*tx; csgjs_real newY = x*xy+y*yy+z*zy+w*ty; csgjs_real newZ = x*xz+y*yz+z*zz+w*tz; csgjs_real newW = x*xw+y*yw+z*zw+w*tw; if(newW != 1) { csgjs_real invW = 1.0/newW; newX *= invW; newY *= invW; newZ *= invW; } return Vector3( newX, newY, newZ ); } Vector3 Vector3::abs() const { return Vector3(std::abs(x), std::abs(y), std::abs(z)); } Vector3 Vector3::nonParallelVector() const { Vector3 abs = this->abs(); if(abs.x <= abs.y && abs.x <= abs.z) { return Vector3(1,0,0); } else if(abs.y <= abs.x && abs.y <= abs.z) { return Vector3(0,1,0); } else { return Vector3(0,0,1); } } Vector3 Vector3::min(const Vector3 &v) const { return Vector3(std::min(x, v.x), std::min(y, v.y), std::min(z, v.z)); } Vector3 Vector3::max(const Vector3 &v) const { return Vector3(std::max(x, v.x), std::max(y, v.y), std::max(z, v.z)); } Vector3 operator*(const csgjs_real m, const Vector3 &v) { return Vector3(m*v.x, m*v.y, m*v.z); } std::ostream& operator<<(std::ostream& os, const Vector3 &v) { os << "(" << v.x << ", " << v.y << ", " << v.z << ")"; return os; } } stl_cmd-1.1/src/csgjs/math/Vector3.h000066400000000000000000000023111322161221000173120ustar00rootroot00000000000000#ifndef __CSGJS_VECTOR3__ #define __CSGJS_VECTOR3__ #include #include #include #include "csgjs/math/Matrix4x4.h" namespace csgjs { struct Vector3 { csgjs_real x; csgjs_real y; csgjs_real z; Vector3(); Vector3(csgjs_real xx, csgjs_real yy, csgjs_real zz); Vector3 operator-() const; Vector3 operator+(const Vector3 &b) const; Vector3 operator-(const Vector3 &b) const; Vector3 operator*(const csgjs_real m) const; Vector3 operator/(const csgjs_real m) const; csgjs_real dot(const Vector3 &b) const; Vector3 lerp(const Vector3 &b, csgjs_real t) const; csgjs_real lengthSquared() const; csgjs_real length() const; Vector3 unit() const; Vector3 cross(const Vector3 &a) const; csgjs_real distanceTo(const Vector3 &a) const; csgjs_real distanceToSquared(const Vector3 &a) const; bool operator==(const Vector3 &a) const; Vector3 transform(const Matrix4x4 &m, csgjs_real w=1) const; Vector3 abs() const; Vector3 nonParallelVector() const; Vector3 min(const Vector3 &v) const; Vector3 max(const Vector3 &v) const; }; Vector3 operator*(const csgjs_real m, const Vector3 &v); std::ostream& operator<<(std::ostream& os, const Vector3 &v); } #endif stl_cmd-1.1/src/csgjs/math/Vertex3.h000066400000000000000000000013301322161221000173250ustar00rootroot00000000000000#ifndef __CSGJS_VERTEX3__ #define __CSGJS_VERTEX3__ #include "csgjs/constants.h" #include "csgjs/math/Vector3.h" #include namespace csgjs { struct Vertex { Vector3 pos; Vertex() : pos() { } Vertex(const Vector3 &p) : pos(p) {} // if vertex had normal data or something like that, flip it here Vertex flipped() const { return *this; } Vertex interpolate(Vertex other, csgjs_real t) const { return Vertex(pos.lerp(other.pos, t)); } Vertex transform(const Matrix4x4 &m) const { return Vertex(pos.transform(m)); } }; inline std::ostream& operator<<(std::ostream& os, const Vertex &v) { os << "pos: " << v.pos; return os; } } #endif stl_cmd-1.1/src/csgjs/util.cpp000066400000000000000000000073251322161221000163560ustar00rootroot00000000000000#ifndef __CSGJS_UTIL__ #define __CSGJS_UTIL__ #include "csgjs/math/Polygon3.h" #include "stl_util.h" #include #include #include #include "csgjs/math/HashKeys.h" namespace csgjs { std::vector ReadSTLFile(const char* filename) { std::vector polys; std::vector verts; verts.reserve(3); FILE *f; f = fopen(filename, "rb"); if(!f) { fprintf(stderr, "Can't read file: %s\n", filename); exit(2); } fseek(f, 80, SEEK_SET); uint32_t num_tris; size_t readBytes = fread(&num_tris, 4, 1, f); vec p1; vec p2; vec p3; for(int i = 0; i < num_tris; i++) { fseek(f, 12, SEEK_CUR); // normal readBytes = fread(&p1, 1, 12,f); readBytes = fread(&p2, 1, 12,f); readBytes = fread(&p3, 1, 12,f); fseek(f, 2, SEEK_CUR); verts.clear(); verts.push_back(Vertex(Vector3(p1.x, p1.y, p1.z))); verts.push_back(Vertex(Vector3(p2.x, p2.y, p2.z))); verts.push_back(Vertex(Vector3(p3.x, p3.y, p3.z))); polys.push_back(Polygon(verts)); } fclose(f); return std::move(polys); } void WriteSTLFile(const char* filename, const std::vector polygons) { FILE *outf = fopen(filename, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", filename); } char header[81] = {0}; snprintf(header, 81, "Created with stl_cmd"); fwrite(header, 80, 1, outf); uint32_t num_tris = 0; std::vector::const_iterator itr = polygons.begin(); while(itr != polygons.end()) { num_tris += itr->vertices.size()-2; ++itr; } std::unordered_map vertexLookup; fwrite(&num_tris, 4, 1, outf); uint16_t abc = 0; itr = polygons.begin(); while(itr != polygons.end()) { vec normal; vec p0; vec p1; Vector3 vertex0 = itr->vertices[0].pos; Vector3 vertex1 = itr->vertices[1].pos; VertexKey key0(vertex0); VertexKey key1(vertex1); if(vertexLookup.count(key0) > 0) { vertex0 = vertexLookup[key0]; } else { vertexLookup[key0] = vertex0; } if(vertexLookup.count(key1) > 0) { vertex1 = vertexLookup[key1]; } else { vertexLookup[key1] = vertex1; } normal.x = (float)itr->plane.normal.x; normal.y = (float)itr->plane.normal.y; normal.z = (float)itr->plane.normal.z; p0.x = (float)vertex0.x; p0.y = (float)vertex0.y; p0.z = (float)vertex0.z; p1.x = (float)vertex1.x; p1.y = (float)vertex1.y; p1.z = (float)vertex1.z; int numVertices = itr->vertices.size(); for(int i = 2; i < numVertices; i++) { fwrite(&normal, 1, 12, outf); vec p2; Vector3 vertex2 = itr->vertices[i].pos; VertexKey key2(vertex2); if(vertexLookup.count(key2) > 0) { vertex2 = vertexLookup[key2]; } else { vertexLookup[key2] = vertex2; } p2.x = (float)vertex2.x; p2.y = (float)vertex2.y; p2.z = (float)vertex2.z; fwrite(&p0, 1, 12, outf); fwrite(&p1, 1, 12, outf); fwrite(&p2, 1, 12, outf); fwrite(&abc, 1, 2,outf); p1 = p2; } ++itr; } fclose(outf); } // from https://stackoverflow.com/questions/1640258/need-a-fast-random-generator-for-c static unsigned long x=123456789, y=362436069, z=521288629; unsigned long xorshf96(void) { //period 2^96-1 unsigned long t; x ^= x << 16; x ^= x >> 5; x ^= x << 1; t = x; x = y; y = z; z = t ^ x ^ y; return z; } int fastRandom(int max) { return xorshf96() % max; } } #endif stl_cmd-1.1/src/csgjs/util.h000066400000000000000000000005251322161221000160160ustar00rootroot00000000000000#ifndef __CSGJS_UTIL__ #define __CSGJS_UTIL__ #include "math/Polygon3.h" #include #include namespace csgjs { std::vector ReadSTLFile(const char* filename); void WriteSTLFile(const char* filename, const std::vector polygons); unsigned long xorshf96(void); int fastRandom(int max); } #endif stl_cmd-1.1/src/stl_bbox.cpp000066400000000000000000000054011322161221000160750ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_bbox prints bounding box information about an STL file.\n\n"); fprintf(stderr, "usage: stl_bbox \n"); fprintf(stderr, " Prints bounding box information for the given binary STL file.\n"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } char *file = argv[1]; if(!is_valid_binary_stl(file)) { fprintf(stderr, "%s is not a binary stl file.\n", file); exit(2); } FILE *f; f = fopen(file, "rb"); if(!f) { fprintf(stderr, "Can't read file: %s\n", file); exit(2); } fseek(f, 80, SEEK_SET); uint32_t num_tris; size_t readBytes = fread(&num_tris, 4, 1, f); vec point; point.w = 1; vec min; vec max; for(int i = 0; i < num_tris; i++) { fseek(f, 12, SEEK_CUR); // normal for(int j = 0; j < 3; j++) { readBytes = fread(&point, 1, 12,f); if(i == 0 && j == 0) { min.x = point.x; min.y = point.y; min.z = point.z; max.x = point.x; max.y = point.y; max.z = point.z; } else { if(min.x > point.x) min.x = point.x; if(min.y > point.y) min.y = point.y; if(min.z > point.z) min.z = point.z; if(max.x < point.x) max.x = point.x; if(max.y < point.y) max.y = point.y; if(max.z < point.z) max.z = point.z; } } fseek(f, 2, SEEK_CUR); } fclose(f); printf("Extents: (%f, %f, %f) - (%f, %f, %f)\n", min.x, min.y, min.z, max.x, max.y, max.z); printf("Dimensions: (%f, %f, %f)\n", max.x-min.x, max.y-min.y, max.z-min.z); return 0; } stl_cmd-1.1/src/stl_boolean.cpp000066400000000000000000000077511322161221000165740ustar00rootroot00000000000000/* Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include "csgjs/CSG.h" #include "csgjs/util.h" void print_usage() { fprintf(stderr, "stl_boolean performs CSG operations on two STL files.\n\n"); fprintf(stderr, "usage: stl_boolean -a -b [ -i ] [ -u ] [ -d ] \n"); fprintf(stderr, " Performs a mesh CSG boolean operation on STL files A and B using BSP trees.\n" " -i - performs the intersection of A and B\n" " -u - performs the union of A and B (default)\n" " -d - performs the difference of A and B\n"); } int main(int argc, char **argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; char *a_file; char *b_file; int a_set = 0; int b_set = 0; int unionAB = 0; int intersection = 0; int difference = 0; int c; while((c = getopt(argc, argv, "a:b:iud")) != -1) { switch(c) { case 'a': a_set = 1; a_file = optarg; break; case 'b': b_set = 1; b_file = optarg; break; case 'i': intersection = 1; if(unionAB || difference) { fprintf(stderr, "intersection option provided when union or difference already specified.\n"); unionAB = 0; difference = 0; } break; case 'u': unionAB = 1; if(intersection || difference) { fprintf(stderr, "union option provided when intersection or difference already specified.\n"); intersection = 0; difference = 0; } break; case 'd': difference = 1; if(intersection || unionAB) { fprintf(stderr, "difference option provided when intersection or union already specified.\n"); intersection = 0; unionAB = 0; } break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(!unionAB && !intersection && !difference) { unionAB = 1; } if(errflg || !(a_set && b_set) || optind >= argc) { print_usage(); exit(2); } char *out_filename = argv[optind]; csgjs::CSG A(csgjs::ReadSTLFile(a_file)); csgjs::CSG B(csgjs::ReadSTLFile(b_file)); if(unionAB) { csgjs::CSG csg = A.csgUnion(B); csg.canonicalize(); csg.makeManifold(); csgjs::WriteSTLFile(out_filename, csg.toPolygons()); } if(intersection) { csgjs::CSG csg = A.csgIntersect(B); csg.canonicalize(); csg.makeManifold(); csgjs::WriteSTLFile(out_filename, csg.toPolygons()); } if(difference) { csgjs::CSG csg = A.csgSubtract(B); csg.canonicalize(); csg.makeManifold(); csgjs::WriteSTLFile(out_filename, csg.toPolygons()); } } stl_cmd-1.1/src/stl_borders.cpp000066400000000000000000000113621322161221000166060ustar00rootroot00000000000000/* Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #include #include #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_borders prints how many border edges there are in a given STL file.\n\n"); fprintf(stderr, "usage: stl_borders [ ]\n"); fprintf(stderr, " Prints how many border edges there are. For a watertight, manifold model, it will be 0.\n"); } struct VertexKey { int x; int y; int z; VertexKey() : x(0), y(0), z(0) {} VertexKey(float xx, float yy, float zz) { x = (int)(std::round((double)xx/EPSILON)); y = (int)(std::round((double)yy/EPSILON)); z = (int)(std::round((double)zz/EPSILON)); } bool operator==(const VertexKey& k) const { return x == k.x && y == k.y && z == k.z; } }; namespace std { template <> struct hash { std::size_t operator()(const VertexKey& k) const { return ((std::hash()(k.x) ^ (std::hash()(k.y) << 1)) >> 1) ^ (hash()(k.z) << 1); } }; } struct EdgeKey { VertexKey v1; VertexKey v2; EdgeKey(const VertexKey &a, const VertexKey &b) { if(a.x < b.x) { v1 = a; v2 = b; } else if(a.x > b.x) { v2 = a; v1 = b; } else { if(a.y < b.y) { v1 = a; v2 = b; } else if(a.y > b.y) { v2 = a; v1 = b; } else { if(a.z < b.z) { v1 = a; v2 = b; } else if(a.z > b.z) { v2 = a; v1 = b; } else { v1 = a; v2 = b; } } } } bool operator==(const EdgeKey &k) const { return (v1 == k.v1 && v2 == k.v2); } }; namespace std { template<> struct hash { std::size_t operator()(const EdgeKey& k) const { return ((std::hash()(k.v1) ^ (std::hash()(k.v2) << 1)) >> 1); } }; } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; int c; while((c = getopt(argc, argv, "")) != -1) { switch(c) { case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(errflg) { print_usage(); exit(2); } FILE *f; if(optind == argc-1) { char *file = argv[optind]; f = fopen(file, "rb"); if(!f) { fprintf(stderr, "Can't read file: %s\n", file); exit(2); } } else { f = stdin; } fseek(f, 80, SEEK_SET); uint32_t num_tris; uint16_t abc = 0; // attribute byte count size_t readBytes = fread(&num_tris, 4, 1, f); std::unordered_map edgeCounts; for(int i = 0; i < num_tris; i++) { vec normal; vec p0; vec p1; vec p2; readBytes = fread(&normal, 1, 12,f); readBytes = fread(&p0, 1, 12,f); readBytes = fread(&p1, 1, 12,f); readBytes = fread(&p2, 1, 12,f); readBytes = fread(&abc, 1, 2,f); VertexKey v0(p0.x, p0.y, p0.z); VertexKey v1(p1.x, p1.y, p1.z); VertexKey v2(p2.x, p2.y, p2.z); EdgeKey e0(v0,v1); EdgeKey e1(v1,v2); EdgeKey e2(v2,v0); if(edgeCounts.count(e0)) { edgeCounts[e0] = edgeCounts[e0] + 1; } else { edgeCounts[e0] = 1; } if(edgeCounts.count(e1)) { edgeCounts[e1] = edgeCounts[e1] + 1; } else { edgeCounts[e1] = 1; } if(edgeCounts.count(e2)) { edgeCounts[e2] = edgeCounts[e2] + 1; } else { edgeCounts[e2] = 1; } } std::unordered_map::iterator itr = edgeCounts.begin(); uint32_t borderEdges = 0; while(itr != edgeCounts.end()) { if(itr->second == 1) { borderEdges++; } ++itr; } std::cout << borderEdges << std::endl; return 0; } stl_cmd-1.1/src/stl_cone.cpp000066400000000000000000000137061322161221000160760ustar00rootroot00000000000000/* Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_cone outputs an STL file of a single cone.\n\n"); fprintf(stderr, "usage: stl_cone [ -r ] [ -t ] [ -h ] [ -s ] [ ]\n"); 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"); 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"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; int c; float radius = 1; float topRadius = 0; float height = 1; int segments = 32; while((c = getopt(argc, argv, "r:h:s:t:")) != -1) { switch(c) { case 'r': radius = atof(optarg); break; case 't': topRadius = atof(optarg); break; case 'h': height = atof(optarg); break; case 's': segments = atoi(optarg); break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(errflg) { print_usage(); exit(2); } FILE *outf; if(optind == argc-1) { char *file = argv[optind]; outf = fopen(file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", file); exit(2); } } else { outf = stdout; } char header[81] = {0}; snprintf(header, 81, "Cone with radius %.4f, top radius %.4f and height %.4f", radius, topRadius, height); fwrite(header, 80, 1, outf); uint32_t num_tris; uint16_t abc = 0; // attribute byte count vec p0; vec p1; vec p2; vec p3; if(topRadius > 0) { // caps sides num_tris = 2*(segments-2)+2*segments; fwrite(&num_tris, 4, 1, outf); for(int i = 0; i < segments; i++) { float angle = 2*M_PI*i/segments; float angle2 = 2*M_PI*(i+1)/segments; if(i == segments-1) { angle2 = 0; } float cosa = cos(angle); float sina = sin(angle); float cosa2 = cos(angle2); float sina2 = sin(angle2); p0.x = topRadius*cosa; p0.y = topRadius*sina; p0.z = height*.5; p1.x = radius*cosa; p1.y = radius*sina; p1.z = -height*.5; p2.x = radius*cosa2; p2.y = radius*sina2; p2.z = -height*.5; p3.x = topRadius*cosa2; p3.y = topRadius*sina2; p3.z = height*.5; write_quad(outf, &p0, &p1, &p2, &p3, 0); } for(int i = 1; i < segments-1; i++) { float angle = 2*M_PI*i/segments; float angle2 = 2*M_PI*(i+1)/segments; float cosa = cos(angle); float sina = sin(angle); float cosa2 = cos(angle2); float sina2 = sin(angle2); p0.x = topRadius; p0.y = 0; p0.z = height*.5; p1.x = topRadius*cosa; p1.y = topRadius*sina; p1.z = height*.5; p2.x = topRadius*cosa2; p2.y = topRadius*sina2; p2.z = height*.5; write_tri(outf, &p0, &p1, &p2, 0); p0.x = radius; p0.y = 0; p0.z = -height*.5; p1.x = radius*cosa; p1.y = radius*sina; p1.z = -height*.5; p2.x = radius*cosa2; p2.y = radius*sina2; p2.z = -height*.5; write_tri(outf, &p0, &p1, &p2, 1); } } else { // cap side num_tris = (segments-2)+segments; fwrite(&num_tris, 4, 1, outf); for(int i = 0; i < segments; i++) { float angle = 2*M_PI*i/segments; float angle2 = 2*M_PI*(i+1)/segments; float cosa = cos(angle); float sina = sin(angle); float cosa2 = cos(angle2); float sina2 = sin(angle2); p0.x = 0; p0.y = 0; p0.z = height*.5; p1.x = radius*cosa; p1.y = radius*sina; p1.z = -height*.5; p2.x = radius*cosa2; p2.y = radius*sina2; p2.z = -height*.5; write_tri(outf, &p0, &p1, &p2, 0); } for(int i = 1; i < segments-1; i++) { float angle = 2*M_PI*i/segments; float angle2 = 2*M_PI*(i+1)/segments; float cosa = cos(angle); float sina = sin(angle); float cosa2 = cos(angle2); float sina2 = sin(angle2); p0.x = radius; p0.y = 0; p0.z = -height*.5; p1.x = radius*cosa; p1.y = radius*sina; p1.z = -height*.5; p2.x = radius*cosa2; p2.y = radius*sina2; p2.z = -height*.5; write_tri(outf, &p0, &p1, &p2, 1); } } return 0; } stl_cmd-1.1/src/stl_convex.cpp000066400000000000000000000123311322161221000164450ustar00rootroot00000000000000/* Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #include #include #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_convex prints whether an STL file is a convex polyhedron.\n\n"); fprintf(stderr, "usage: stl_convex [ -v ] [ ]\n"); 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"); 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"); } struct VertexKey { int x; int y; int z; VertexKey() : x(0), y(0), z(0) {} VertexKey(float xx, float yy, float zz) { x = (int)(std::round((double)xx/EPSILON)); y = (int)(std::round((double)yy/EPSILON)); z = (int)(std::round((double)zz/EPSILON)); } bool operator==(const VertexKey& k) const { return x == k.x && y == k.y && z == k.z; } }; namespace std { template <> struct hash { std::size_t operator()(const VertexKey& k) const { return ((std::hash()(k.x) ^ (std::hash()(k.y) << 1)) >> 1) ^ (hash()(k.z) << 1); } }; } struct EdgeKey { VertexKey v1; VertexKey v2; EdgeKey(const VertexKey &a, const VertexKey &b) { if(a.x < b.x) { v1 = a; v2 = b; } else if(a.x > b.x) { v2 = a; v1 = b; } else { if(a.y < b.y) { v1 = a; v2 = b; } else if(a.y > b.y) { v2 = a; v1 = b; } else { if(a.z < b.z) { v1 = a; v2 = b; } else if(a.z > b.z) { v2 = a; v1 = b; } else { v1 = a; v2 = b; } } } } bool operator==(const EdgeKey &k) const { return (v1 == k.v1 && v2 == k.v2); } }; namespace std { template<> struct hash { std::size_t operator()(const EdgeKey& k) const { return ((std::hash()(k.v1) ^ (std::hash()(k.v2) << 1)) >> 1); } }; } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; int c; int verbose = 0; while((c = getopt(argc, argv, "v")) != -1) { switch(c) { case 'v': verbose = 1; break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(errflg) { print_usage(); exit(2); } FILE *f; if(optind == argc-1) { char *file = argv[optind]; f = fopen(file, "rb"); if(!f) { fprintf(stderr, "Can't read file: %s\n", file); exit(2); } } else { f = stdin; } fseek(f, 80, SEEK_SET); uint32_t num_tris; uint16_t abc = 0; // attribute byte count size_t readBytes = fread(&num_tris, 4, 1, f); std::unordered_set vertsSeen; std::unordered_set edgesSeen; for(int i = 0; i < num_tris; i++) { vec normal; vec p0; vec p1; vec p2; readBytes = fread(&normal, 1, 12,f); readBytes = fread(&p0, 1, 12,f); readBytes = fread(&p1, 1, 12,f); readBytes = fread(&p2, 1, 12,f); readBytes = fread(&abc, 1, 2,f); VertexKey v0(p0.x, p0.y, p0.z); VertexKey v1(p1.x, p1.y, p1.z); VertexKey v2(p2.x, p2.y, p2.z); vertsSeen.insert(v0); vertsSeen.insert(v1); vertsSeen.insert(v2); edgesSeen.insert(EdgeKey(v0, v1)); edgesSeen.insert(EdgeKey(v1, v2)); edgesSeen.insert(EdgeKey(v2, v0)); } int V = vertsSeen.size(); int E = edgesSeen.size(); int F = num_tris; int euler_characteristic = V - E + F; if(verbose) { std::cout << "V = " << V << std::endl; std::cout << "E = " << E << std::endl; std::cout << "F = " << F << std::endl; std::cout << "V - E + F = " << euler_characteristic << std::endl; } if(euler_characteristic == 2) { std::cout << "convex" << std:: endl; } else { std::cout << "not convex" << std:: endl; } return 0; } stl_cmd-1.1/src/stl_count.cpp000066400000000000000000000060261322161221000162770ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_count prints the number of triangles in an STL file.\n\n"); fprintf(stderr, "usage: stl_count [ ]\n"); 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"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } if(argc == 2) { FILE *f; char* filename = argv[1]; if(!is_valid_binary_stl(filename)) { fprintf(stderr, "stl_count only accepts binary stl files.\n"); exit(2); } f = fopen(filename, "r+b"); if(!f) { fprintf(stderr, "Can't read file: %s\n", filename); exit(2); } fseek(f, 80, SEEK_SET); uint32_t num_tris; if(fread(&num_tris, 1, 4, f) < 4) { fprintf(stderr, "invalid binary stl file\n"); exit(2); } fclose(f); printf("%d\n", num_tris); } else if(argc > 2) { print_usage(); exit(2); } else { off_t bights_read = 0; while(bights_read < 80 && getc(stdin) != EOF) { bights_read++; } if(bights_read < 80) { fprintf(stderr, "invalid binary stl file\n"); exit(2); } // got through header bights_read = 0; uint8_t buff[4]; int c; // now read num_tris while(bights_read < 4 && (c = getc(stdin)) != EOF) { buff[bights_read] = c; bights_read++; } if(bights_read < 4) { fprintf(stderr, "invalid binary stl file\n"); exit(2); } uint32_t num_tris = *((uint32_t*)buff); // read the rest of the file while(bights_read < num_tris*16 && getc(stdin) != EOF) { bights_read++; } if(bights_read < num_tris*16) { fprintf(stderr, "invalid binary stl file\n"); exit(2); } printf("%d\n", num_tris); } return 0; } stl_cmd-1.1/src/stl_cube.cpp000066400000000000000000000107041322161221000160630ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_cube outputs an STL file of a single cube.\n\n"); fprintf(stderr, "usage: stl_cube [-w ] [ ]\n"); fprintf(stderr, " Outputs an stl file of a cube with the provided width. "); fprintf(stderr, " If the width is omitted, it defaults to 1. If no output file is provided, data is sent to stdout. \n"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; int c; float width = 1; while((c = getopt(argc, argv, "w:")) != -1) { switch(c) { case 'w': width = atof(optarg); break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(errflg) { print_usage(); exit(2); } FILE *outf; if(optind == argc-1) { char *file = argv[optind]; outf = fopen(file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", file); exit(2); } } else { outf = stdout; } char header[81] = {0}; snprintf(header, 81, "Cube of width %.4f", width); fwrite(header, 80, 1, outf); uint32_t num_tris = 12; fwrite(&num_tris, 4, 1, outf); uint16_t abc = 0; // attribute byte count float tris[12][3][3] = { // Top { { 1, 1, 1 }, { 1, 1, -1 }, { -1, 1, -1 } }, { { -1, 1, -1 }, { -1, 1, 1 }, { 1, 1, 1 } }, // Bottom { { -1, -1, 1 }, { 1, -1, -1 }, { 1, -1, 1 } }, { { -1, -1, 1 }, { -1, -1, -1 }, { 1, -1, -1 } }, // Right { { 1, -1, 1 }, { 1, -1, -1 }, { 1, 1, -1 } }, { { 1, 1, -1 }, { 1, 1, 1 }, { 1, -1, 1 } }, // Left { { -1, -1, 1 }, { -1, 1, 1 }, { -1, 1, -1 } }, { { -1, 1, -1 }, { -1, -1, -1 }, { -1, -1, 1 } }, // Near { { 1, 1, 1 }, { -1, 1, 1 }, { -1, -1, 1 } }, { { -1, -1, 1 }, { 1, -1, 1 }, { 1, 1, 1 } }, // Far { { 1, -1, -1 }, { -1, -1, -1 }, { -1, 1, -1 } }, { { -1, 1, -1 }, { 1, 1, -1 }, { 1, -1, -1 } } }; float normals[12][3] = { // Top { 0, 1, 0 }, { 0, 1, 0 }, // Bottom { 0, -1, 0 }, { 0, -1, 0 }, // Right { 1, 0, 0 }, { 1, 0, 0 }, // Left { -1, 0, 0 }, { -1, 0, 0 }, // Near { 0, 0, 1 }, { 0, 0, 1 }, // Far { 0, 0, -1 }, { 0, 0, -1 } }; for(int i = 0; i < num_tris; i++) { fwrite(normals[i], 1, 12, outf); for(int j = 0; j < 3; j++) { for(int k = 0; k < 3; k++) { tris[i][j][k] *= .5*width; } } fwrite(tris[i], 1, 36, outf); fwrite(&abc, 1, 2,outf); } return 0; } stl_cmd-1.1/src/stl_cylinder.cpp000066400000000000000000000102721322161221000167560ustar00rootroot00000000000000/* Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_cylinder outputs an STL file of a single cylinder.\n\n"); fprintf(stderr, "usage: stl_cylinder [ -r ] [ -h ] [ -s ] [ ]\n"); fprintf(stderr, " Outputs an stl file of a cylinder with the provided radius, height and number of segments to approximate a circle.\n"); 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"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; int c; float radius = 1; float height = 1; int segments = 32; while((c = getopt(argc, argv, "r:h:s:")) != -1) { switch(c) { case 'r': radius = atof(optarg); break; case 'h': height = atof(optarg); break; case 's': segments = atoi(optarg); break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(errflg) { print_usage(); exit(2); } FILE *outf; if(optind == argc-1) { char *file = argv[optind]; outf = fopen(file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", file); exit(2); } } else { outf = stdout; } char header[81] = {0}; snprintf(header, 81, "Cylinder of radius %.4f and height %.4f", radius, height); fwrite(header, 80, 1, outf); // caps tube uint32_t num_tris = 2*(segments-2)+2*segments; fwrite(&num_tris, 4, 1, outf); uint16_t abc = 0; // attribute byte count vec p0; vec p1; vec p2; vec p3; for(int i = 0; i < segments; i++) { float angle = 2*M_PI*i/segments; float angle2 = 2*M_PI*(i+1)/segments; if(i == segments-1) { angle2 = 0; } float cosa = cos(angle); float sina = sin(angle); float cosa2 = cos(angle2); float sina2 = sin(angle2); p0.x = radius*cosa; p0.y = radius*sina; p0.z = height*.5; p1.x = radius*cosa; p1.y = radius*sina; p1.z = -height*.5; p2.x = radius*cosa2; p2.y = radius*sina2; p2.z = -height*.5; p3.x = radius*cosa2; p3.y = radius*sina2; p3.z = height*.5; write_quad(outf, &p0, &p1, &p2, &p3, 0); } for(int i = 1; i < segments-1; i++) { float angle = 2*M_PI*i/segments; float angle2 = 2*M_PI*(i+1)/segments; float cosa = cos(angle); float sina = sin(angle); float cosa2 = cos(angle2); float sina2 = sin(angle2); p0.x = radius; p0.y = 0; p0.z = height*.5; p1.x = radius*cosa; p1.y = radius*sina; p1.z = height*.5; p2.x = radius*cosa2; p2.y = radius*sina2; p2.z = height*.5; write_tri(outf, &p0, &p1, &p2, 0); p0.z = -height*.5; p1.z = -height*.5; p2.z = -height*.5; write_tri(outf, &p0, &p1, &p2, 1); } return 0; } stl_cmd-1.1/src/stl_empty.cpp000066400000000000000000000034351322161221000163060ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_empty outputs an empty STL file.\n\n"); fprintf(stderr, "usage: stl_empty \n"); fprintf(stderr, " Outputs a properly formatted, but empty stl file (just an 80 byte header and a 0 indicating no triangles). "); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } if(argc != 2) { print_usage(); exit(2); } char *file = argv[1]; FILE *outf; outf = fopen(file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", file); exit(2); } char header[81] = {0}; snprintf(header, 81, "Empty STL file"); fwrite(header, 80, 1, outf); uint32_t num_tris = 0; fwrite(&num_tris, 4, 1, outf); fclose(outf); return 0; } stl_cmd-1.1/src/stl_header.cpp000066400000000000000000000066471322161221000164100ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_header inspects and modifies the header section of an STL file.\n\n"); fprintf(stderr, "usage: stl_header [-s
] [-o ] \n"); 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"); fprintf(stderr, " then the header is set on the input file. If neither -o nor -s is specified,\n"); fprintf(stderr, " the header of the model is output to the terminal.\n"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int c; int errflg = 0; char *set_header; char *out_file; int setflag = 0; int outflag = 0; while((c = getopt(argc, argv, "s:o:")) != -1) { switch(c) { case 'o': outflag = 1; out_file = optarg; break; case 's': setflag = 1; set_header = optarg; break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(errflg || optind >= argc) { print_usage(); exit(2); } char* filename = argv[optind]; char header[80]; if(!is_valid_binary_stl(filename)) { fprintf(stderr, "stl_header only accepts binary stl files.\n"); exit(2); } FILE *f; f = fopen(filename, "r+b"); if(!f) { fprintf(stderr, "Can't read file: %s\n", filename); exit(2); } if(setflag && outflag) { strncpy(header, set_header, 80); FILE *outf; outf = fopen(out_file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", out_file); exit(2); } fwrite(header, 80, 1, outf); fseek(f, 80, SEEK_SET); char buffer[BUFFER_SIZE]; int r; while((r = fread(buffer, 1, BUFFER_SIZE, f))) { fwrite(buffer, 1, r, outf); } fclose(f); fclose(outf); } else if(setflag) { strncpy(header, set_header, 80); fwrite(header, 80, 1, f); fclose(f); } else { size_t readBytes = fread(header, 80, 1, f); fclose(f); for(int i = 0; i < 80; i++) { printf("%c", header[i]); } printf("\n"); } return 0; } stl_cmd-1.1/src/stl_merge.cpp000066400000000000000000000071251322161221000162470ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 // TODO Add options for layouting out merged files in a row or grid // rather than just merging. void print_usage() { fprintf(stderr, "stl_merge concatenates multiple STL files.\n\n"); fprintf(stderr, "usage: stl_merge [ -o ] [ ... ]\n"); fprintf(stderr, " Merges binary stl files into a single file. If no out file is provided, data is output to stdout.\n"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int c; int errflg = 0; char *out_file; int outflag = 0; while((c = getopt(argc, argv, "o:")) != -1) { switch(c) { case 'o': outflag = 1; out_file = optarg; break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(errflg) { print_usage(); exit(2); } uint32_t num_tris = 0; for(int i = optind; i < argc; i++) { char* file = argv[i]; char name[100]; snprintf(name, sizeof(name), "%s", file); if(!is_valid_binary_stl(file)) { fprintf(stderr, "%s is not a binary stl file.\n", name); exit(2); } FILE *f; f = fopen(file, "rb"); if(!f) { fprintf(stderr, "Can't read file: %s\n", name); exit(2); } fseek(f, 80, SEEK_SET); uint32_t nt; size_t readBytes = fread(&nt, 4, 1, f); num_tris += nt; fclose(f); } FILE *outf; if(outflag) { outf = fopen(out_file, "wb"); char name[100]; snprintf(name, sizeof(name), "%s", out_file); if(!outf) { fprintf(stderr, "Can't open out file: %s\n", name); exit(2); } } else { outf = stdout; } char header[81] = {0}; // include an extra char for terminating \0 of snprintf char base1[50]; char base2[50]; snprintf(header, 81, "Merged using stl_merge."); fwrite(header, 80, 1, outf); fwrite(&num_tris, 4, 1, outf); char buffer[BUFFER_SIZE]; for(int i = optind; i < argc; i++) { char* file = argv[i]; char name[100]; snprintf(name, sizeof(name), "%s", file); FILE *f; f = fopen(file, "rb"); if(!f) { fprintf(stderr, "Can't read file: %s\n", name); exit(2); } fseek(f, 84, SEEK_SET); int r; while((r = fread(buffer, 1, BUFFER_SIZE, f))) { fwrite(buffer, 1, r, outf); } fclose(f); } return 0; } stl_cmd-1.1/src/stl_normals.cpp000066400000000000000000000134121322161221000166170ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_normals inspects and modifies normal data of an STL file.\n\n"); fprintf(stderr, "usage: stl_normals [ -c ] [ -r ] [ -v ] [ ]\n"); fprintf(stderr, " Checks the stored normals against calculated normals based on ordering of vertices.\n" " -c - if present will ignore the present normal values and calculate them based on the vertex ordering.\n" " -r - if present will reverse the winding order of the vertices.\n" " -v - be verboze when printing out differing normals\n"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int c; int errflg = 0; char *out_file; char *in_file; int calc = 0; int reverse = 0; int needs_out = 0; int verbose = 0; if(argc == 1) { print_usage(); exit(2); } while((c = getopt(argc, argv, "vcr")) != -1) { switch(c) { case 'c': calc = 1; needs_out = 1; break; case 'v': verbose = 1; break; case 'r': reverse = 1; needs_out = 1; break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(errflg) { print_usage(); exit(2); } FILE *inf; FILE *outf; if(optind < argc) { in_file = argv[optind]; char name[100]; snprintf(name, sizeof(name), "%s", in_file); if(!is_valid_binary_stl(in_file)) { fprintf(stderr, "%s is not a binary stl file.\n", name); exit(2); } inf = fopen(in_file, "rb"); if(!inf) { fprintf(stderr, "Can't read file: %s\n", name); exit(2); } fseek(inf, 80, SEEK_SET); // skip header if(optind+1 < argc) { out_file = argv[optind+1]; snprintf(name, sizeof(name), "%s", out_file); outf = fopen(out_file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", name); } } else { outf = stdout; } } else { print_usage(); exit(2); } fseek(inf, 0, SEEK_SET); char header[80] = {0}; size_t readBytes = fread(header, 1, 80, inf); uint16_t zero = 0; uint16_t abc; uint32_t num_tris; readBytes = fread(&num_tris, 4, 1, inf); if(needs_out) { fwrite(header, 1, 80, outf); fwrite(&num_tris, 1, 4, outf); } vec p1,p2,p3; vec n,cn; vec diff; p1.w = 1; p2.w = 1; p3.w = 1; n.w = 0; cn.w = 0; vec d1,d2; d1.w = 0; d2.w = 0; int match = 1; if(verbose) { fprintf(stderr, "reading %d triangles and normals\n", num_tris); } for(int i = 0; i < num_tris; i++) { readBytes = fread(&n, 1, 12, inf); readBytes = fread(&p1, 1, 12, inf); readBytes = fread(&p2, 1, 12, inf); readBytes = fread(&p3, 1, 12, inf); readBytes = fread(&abc, 1, 2, inf); vec_sub(&p2, &p1, &d1); vec_sub(&p3, &p1, &d2); vec_cross(&d1, &d2, &cn); if(cn.x != 0 || cn.y != 0 || cn.z != 0) { vec_normalize(&cn, &cn); } vec_sub(&cn, &n, &diff); if(!(diff.x < EPSILON && diff.x > -EPSILON && diff.y < EPSILON && diff.y > -EPSILON && diff.z < EPSILON && diff.z > -EPSILON)) { match = 0; if(verbose) { fprintf(stderr, "calculated normal %d different than input normal\n", i); fprintf(stderr, "calculated: %f, %f, %f\n", cn.x, cn.y, cn.z); fprintf(stderr, "input: %f, %f, %f\n", n.x, n.y, n.z); } } if(needs_out) { if(calc) { if(reverse) { cn.x *= -1; cn.y *= -1; cn.z *= -1; } fwrite(&cn, 1, 12, outf); } else { fwrite(&n, 1, 12, outf); } if(reverse) { fwrite(&p3, 1, 12, outf); fwrite(&p2, 1, 12, outf); fwrite(&p1, 1, 12, outf); } else { fwrite(&p1, 1, 12, outf); fwrite(&p2, 1, 12, outf); fwrite(&p3, 1, 12, outf); } fwrite(&abc, 1, 2, outf); } } if(!needs_out) { if(match) { fprintf(stderr, "Normals match calculated normals.\n"); } else { fprintf(stderr, "Normals do NOT match calculated normals.\n"); } } return 0; } stl_cmd-1.1/src/stl_sphere.cpp000066400000000000000000000125321322161221000164340ustar00rootroot00000000000000/* Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" void print_usage() { fprintf(stderr, "stl_sphere outputs an STL file of a single sphere.\n\n"); fprintf(stderr, "usage: stl_sphere [-r ] [-s ] [-t ] [ ]\n"); fprintf(stderr, " Outputs an stl file of a sphere with the provided radius and number of segments. "); 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"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; int c; float radius = 1; int s_segments = 32; int t_segments = 16; int set_t_segments = 0; while((c = getopt(argc, argv, "r:s:t:")) != -1) { switch(c) { case 'r': radius = atof(optarg); break; case 's': s_segments = atoi(optarg); break; case 't': s_segments = atoi(optarg); set_t_segments = 1; break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(!set_t_segments) { t_segments = s_segments >> 1; // divide by 2 } if(t_segments < 3) { t_segments = 3; } if(s_segments < 3) { s_segments = 3; } if(errflg) { print_usage(); exit(2); } FILE *outf; if(optind == argc-1) { char *file = argv[optind]; outf = fopen(file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", file); exit(2); } } else { outf = stdout; } char header[81] = {0}; snprintf(header, 81, "Sphere with radius %.4f", radius); fwrite(header, 80, 1, outf); uint32_t num_tris = 2*s_segments*(t_segments-1); fwrite(&num_tris, 4, 1, outf); uint16_t abc = 0; // attribute byte count for(int i = 0; i < s_segments; i++) { float ti = (float)i/s_segments; float ti_next = (float)(i+1)/s_segments; float theta = ti*M_PI*2; float theta_next = ti_next*M_PI*2; float cos_theta = cos(theta); float sin_theta = sin(theta); float cos_theta_next = cos(theta_next); float sin_theta_next = sin(theta_next); for(int j = 0; j < t_segments; j++) { float tj = (float)j/t_segments; float tj_next = (float)(j+1)/t_segments; float phi = tj*M_PI; float phi_next = tj_next*M_PI; float cos_phi = cos(phi); float sin_phi = sin(phi); float cos_phi_next = cos(phi_next); float sin_phi_next = sin(phi_next); vec p1, p2, p3, p4; if(j == 0) { p1.x = radius*cos_theta*sin_phi; p1.y = radius*sin_theta*sin_phi; p1.z = radius*cos_phi; p2.x = radius*cos_theta_next*sin_phi_next; p2.y = radius*sin_theta_next*sin_phi_next; p2.z = radius*cos_phi_next; p3.x = radius*cos_theta*sin_phi_next; p3.y = radius*sin_theta*sin_phi_next; p3.z = radius*cos_phi_next; write_tri(outf, &p1, &p2, &p3, 1); } else if(j == t_segments-1) { p1.x = radius*cos_theta*sin_phi; p1.y = radius*sin_theta*sin_phi; p1.z = radius*cos_phi; p2.x = radius*cos_theta_next*sin_phi; p2.y = radius*sin_theta_next*sin_phi; p2.z = radius*cos_phi; p3.x = radius*cos_theta*sin_phi_next; p3.y = radius*sin_theta*sin_phi_next; p3.z = radius*cos_phi_next; write_tri(outf, &p1, &p2, &p3, 1); } else { p1.x = radius*cos_theta*sin_phi; p1.y = radius*sin_theta*sin_phi; p1.z = radius*cos_phi; p2.x = radius*cos_theta_next*sin_phi; p2.y = radius*sin_theta_next*sin_phi; p2.z = radius*cos_phi; p3.x = radius*cos_theta_next*sin_phi_next; p3.y = radius*sin_theta_next*sin_phi_next; p3.z = radius*cos_phi_next; p4.x = radius*cos_theta*sin_phi_next; p4.y = radius*sin_theta*sin_phi_next; p4.z = radius*cos_phi_next; write_quad(outf, &p1, &p2, &p3, &p4, 1); } } } return 0; } stl_cmd-1.1/src/stl_spreadsheet.cpp000066400000000000000000000046701322161221000174610ustar00rootroot00000000000000/* Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #include void print_usage() { fprintf(stderr, "stl_spreadsheet outputs an STL file in a tab delimited text format.\n\n"); fprintf(stderr, "usage: stl_spreadsheet \n"); 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"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } if(argc != 2) { print_usage(); exit(2); } char *file = argv[1]; if(!is_valid_binary_stl(file)) { fprintf(stderr, "%s is not a binary stl file.\n", file); exit(2); } FILE *f; f = fopen(file, "rb"); if(!f) { fprintf(stderr, "Can't read file: %s\n", file); exit(2); } fseek(f, 80, SEEK_SET); uint32_t num_tris; size_t readBytes = fread(&num_tris, 4, 1, f); vec normal; vec point; 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; for(int i = 0; i < num_tris; i++) { readBytes = fread(&normal, 1, 12,f); std::cout << normal.x << "\t" << normal.y << "\t" << normal.z; for(int j = 0; j < 3; j++) { readBytes = fread(&point, 1, 12,f); std::cout << "\t" << point.x << "\t" << point.y << "\t" << point.z; } std::cout << std::endl; fseek(f, 2, SEEK_CUR); } fclose(f); return 0; } stl_cmd-1.1/src/stl_threads.cpp000066400000000000000000000776501322161221000166140ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" // TODO make output file optional, if not specified output // to stdout. Requires calculating how many tris are necessary // before outputting any. Currently, we write all our tris, then // fseek back to byte 80 to set the number of tris in the file. That // won't work with stdout. void print_usage() { fprintf(stderr, "stl_threads outputs an STL file with male or female threads per the ISO metric screw thread standard.\n\n"); fprintf(stderr, "usage: stl_threads [ -f ] [ -D ] [ -P ] [ -a ]\n" " [ -h ] [ -s ] \n"); fprintf(stderr, " Outputs an stl file with male or female screw threads per the ISO metric \n" " screw thread standard (http://en.wikipedia.org/wiki/ISO_metric_screw_thread).\n" "\n" " -f - Outputs female threads (defaults to male).\n" " -D - Changes to major diameter of the threads.\n" " -P - Changes the height of a single thread, aka the pitch per the\n" " ISO metric standard.\n" " -h - Changes the total height of the threads.\n" " -a - Changes the thread angle (degrees). The standard (and default)\n" " is 60 degrees. For 3D printing this can cause overhang issues \n" " as 60 degrees results in a 30 degree angle with the ground\n" " plane. Setting to 90 degrees results in a 45 degree angle with\n" " the ground plane.\n" " -s - Changes the resolution of the generated STL file. More\n" " segments yields finer resolution. is the number\n" " of segments to approximate a circle. Defaults to 72 (every\n" " 5 degrees).\n" " -o - When generating female threads, this is the\n" " outer diameter. Must be greater than .\n"); } void print_normal(vec *p1, vec *p2, vec *p3, int rev) { if(rev) { vec *tmp = p1; p1 = p3; p3 = tmp; } vec n1; vec v1,v2; vec_sub(p2,p1,&v1); vec_sub(p3,p1,&v2); vec_cross(&v1,&v2,&n1); vec_normalize(&n1,&n1); printf("%f, %f, %f\n", n1.x, n1.y, n1.z); } void write_poly(FILE *f, vec *poly, int num_pts, int rev) { for(int i = 1; i < num_pts-1; i++) { write_tri(f, &poly[0], &poly[i], &poly[i+1], rev); } } typedef enum { ABOVE, BELOW, ON } point_state_t; point_state_t point_state(vec *pt, vec *p, vec *n) { // return whether pt is above, below or on the plane defined by p and n point_state_t state; vec tmp; float dot; vec_sub(pt,p,&tmp); dot = vec_dot(&tmp,n); if(dot > EPSILON) { state = ABOVE; } else if(dot < -EPSILON) { state = BELOW; } else { state = ON; } return state; } void tri_normal(vec *p1, vec *p2, vec *p3, int rev, vec *out) { if(rev) { vec *tmp = p1; p1 = p3; p3 = tmp; } vec v1,v2; vec_sub(p2,p1,&v1); vec_sub(p3,p1,&v2); vec_cross(&v1,&v2,out); vec_normalize(out,out); } // returns true if triangle intersects plane, int1 and int2 will be set // to the intersection points // returns false if all points are above or below the plane int write_sliced_tri(FILE *f, vec *p1, vec *p2, vec *p3, int rev, vec *p, // point that lies in the slicing plane vec *n, // normal of slicing plane, keep points in the direction of normal vec *int1, // output, intersecting pt1, returned only if intersection occurs vec *int2, // output, intersecting pt2, returned only if intersection occurs int *tris) // output, number of tris written { vec trin; tri_normal(p1,p2,p3,rev,&trin); point_state_t state1; point_state_t state2; point_state_t state3; state1 = point_state(p1,p,n); state2 = point_state(p2,p,n); state3 = point_state(p3,p,n); if((state1 == ABOVE || state1 == ON) && (state2 == ABOVE || state2 == ON) && (state3 == ABOVE || state3 == ON)) { // all points are above or on plane, write tri normally write_tri(f,p1,p2,p3,rev); *tris = 1; return 0; } else if((state1 == BELOW || state1 == ON) && (state2 == BELOW || state2 == ON) && (state3 == BELOW || state3 == ON)) { // all points are below or on plane, cull entire tri *tris = 0; return 0; } else { // triangle intersects plane if(state1 == ON) { vec tmp1,tmp2; float r; vec_copy(p1, int1); vec_sub(p2,p3,&tmp1); vec_sub(p,p3,&tmp2); r = vec_dot(n,&tmp2)/vec_dot(n,&tmp1); int2->x = p3->x + r*tmp1.x; int2->y = p3->y + r*tmp1.y; int2->z = p3->z + r*tmp1.z; if(state2 == ABOVE) { write_tri(f,p1,p2,int2,rev); } else { write_tri(f,p1,int2,p3,rev); } *tris = 1; return 1; } if(state2 == ON) { vec tmp1,tmp2; float r; vec_copy(p2, int1); vec_sub(p1,p3,&tmp1); vec_sub(p,p3,&tmp2); r = vec_dot(n,&tmp2)/vec_dot(n,&tmp1); int2->x = p3->x + r*tmp1.x; int2->y = p3->y + r*tmp1.y; int2->z = p3->z + r*tmp1.z; if(state1 == ABOVE) { write_tri(f,p1,p2,int2,rev); } else { write_tri(f,p2,p3,int2,rev); } *tris = 1; return 1; } if(state3 == ON) { vec tmp1,tmp2; float r; vec_copy(p3, int2); vec_sub(p1,p2,&tmp1); vec_sub(p,p2,&tmp2); r = vec_dot(n,&tmp2)/vec_dot(n,&tmp1); int1->x = p2->x + r*tmp1.x; int1->y = p2->y + r*tmp1.y; int1->z = p2->z + r*tmp1.z; if(state1 == ABOVE) { write_tri(f,p1,int1,p3,rev); } else { write_tri(f,int1,p2,p3,rev); } *tris = 1; return 1; } if((state1 == ABOVE && state2 == ABOVE) || (state1 == BELOW && state2 == BELOW)) { vec tmp1,tmp2,tmp3; float r1,r2; vec_sub(p2,p3,&tmp1); vec_sub(p1,p3,&tmp2); vec_sub(p,p3,&tmp3); r1 = vec_dot(n,&tmp3)/vec_dot(n,&tmp1); r2 = vec_dot(n,&tmp3)/vec_dot(n,&tmp2); int1->x = p3->x + r1*tmp1.x; int1->y = p3->y + r1*tmp1.y; int1->z = p3->z + r1*tmp1.z; int2->x = p3->x + r2*tmp2.x; int2->y = p3->y + r2*tmp2.y; int2->z = p3->z + r2*tmp2.z; if(state3 == ABOVE) { write_tri(f,int1,p3,int2,rev); *tris = 1; } else { write_quad(f,p1,p2,int1,int2,rev); *tris = 2; } return 1; } if((state2 == ABOVE && state3 == ABOVE) || (state2 == BELOW && state3 == BELOW)) { vec tmp1,tmp2,tmp3; float r1,r2; vec_sub(p2,p1,&tmp1); vec_sub(p3,p1,&tmp2); vec_sub(p,p1,&tmp3); r1 = vec_dot(n,&tmp3)/vec_dot(n,&tmp1); r2 = vec_dot(n,&tmp3)/vec_dot(n,&tmp2); int1->x = p1->x + r1*tmp1.x; int1->y = p1->y + r1*tmp1.y; int1->z = p1->z + r1*tmp1.z; int2->x = p1->x + r2*tmp2.x; int2->y = p1->y + r2*tmp2.y; int2->z = p1->z + r2*tmp2.z; if(state1 == ABOVE) { write_tri(f,p1,int1,int2,rev); *tris = 1; } else { write_quad(f,int1,p2,p3,int2,rev); *tris = 2; } return 1; } if((state1 == ABOVE && state3 == ABOVE) || (state1 == BELOW && state3 == BELOW)) { vec tmp1,tmp2,tmp3; float r1,r2; vec_sub(p1,p2,&tmp1); vec_sub(p3,p2,&tmp2); vec_sub(p,p2,&tmp3); r1 = vec_dot(n,&tmp3)/vec_dot(n,&tmp1); r2 = vec_dot(n,&tmp3)/vec_dot(n,&tmp2); int1->x = p2->x + r1*tmp1.x; int1->y = p2->y + r1*tmp1.y; int1->z = p2->z + r1*tmp1.z; int2->x = p2->x + r2*tmp2.x; int2->y = p2->y + r2*tmp2.y; int2->z = p2->z + r2*tmp2.z; if(state2 == ABOVE) { write_tri(f,int1,p2,int2,rev); *tris = 1; } else { write_quad(f,p1,int1,int2,p3,rev); *tris = 2; } return 1; } } *tris = 0; return 0; } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int c; int errflg = 0; int male = 1; float D = 9.0; // default value, can be changed as a command line argument float P = 2; // default value, can be changed as a command line argument float theta = M_PI/3; // 60 degrees, the standard, can be changed as a command line argument float screwHeight = 20; // height of entire screw (without a head) // TODO maybe add ability to add a head float outerDiameter = -1; int segments = 72; // number of segments to approximate a circle, // higher the number, higher the resolution // (and file size) of the stl file while((c = getopt(argc, argv, "fP:D:a:h:s:o:")) != -1) { switch(c) { case 'f': male = 0; break; case 'P': P = atof(optarg); break; case 'D': D = atof(optarg); break; case 'a': theta = atof(optarg)*M_PI/180; break; case 'h': screwHeight = atof(optarg); break; case 's': segments = atoi(optarg); break; case 'o': outerDiameter = atof(optarg); break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(outerDiameter <= D) { outerDiameter = D+1; } if(errflg || optind >= argc) { print_usage(); exit(2); } char *file = argv[optind]; FILE *outf; outf = fopen(file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", file); exit(2); } char header[81] = {0}; // TODO add some settings summary to header string snprintf(header, 81, "Created with stl_threads."); fwrite(header, 80, 1, outf); // writing 0 to num_tris for now, will update it at the end. uint32_t num_tris = 0; fwrite(&num_tris, 4, 1, outf); // ISO metric screw thread standard designates screw threads // as M followed by diameter D, a multiplication sign, and then // the pitch P (e.g. M8x1.25). Other standards designate standard // pitches for a given diameter (e.g. M8 means the same as M8x1.25). // // See http://en.wikipedia.org/wiki/ISO_metric_screw_thread // // The standard assumes a theta of 60 degrees, but we allow // theta to change, for ease of manufacturing. Certain 3D printers // may not be able to print without drooping at 60 degrees. int female = !male; // equations vary from wikipedia because we're not assuming a 60 degree theta // and we're allowing cutting off different amounts than H/8 // and H/4 from the tip and troughs float tantheta_2 = tan(theta/2); float H = P/(2*tantheta_2); float Htip = H/8; float Htrough = H/4; float Hdiff = H-Htip-Htrough; float Pdiff = Hdiff*tantheta_2; float Ptip = 2*Htip*tantheta_2; float Ptrough = 2*Htrough*tantheta_2; float Dmin = D-2*Hdiff; float Dmin_2 = Dmin/2; float D_2 = D/2; float fD = outerDiameter/2; /* // my ascii representation of image at // (http://en.wikipedia.org/wiki/ISO_metric_screw_thread) // with my own added variables |<--H->| | | | | | |-------------. pt5| ------ // pt5 is the same as pt1 one cycle later | ^ |/| | ^ | | . | | Ptrough | | \| | v | | . pt4| ------ | | \ | | | ( \ | | ( . pt3 ------ | P ( |\ ^ | theta | . Ptip | | ( |/ v | | ( . pt2 ------ | | ( / ^ | v / | Pdiff |-------------. pt1 ------ | /| | | . | | |<---Dmin/2-->| | | | | | |<-----D/2------>| */ vec pt1,pt2,pt3,pt4,pt5; pt1.x = Dmin_2; pt1.y = 0; pt1.z = 0; pt1.w = 1; pt2.x = D_2; pt2.y = 0; pt2.z = Pdiff; pt2.w = 1; pt3.x = D_2; pt3.y = 0; pt3.z = Pdiff+Ptip; pt3.w = 1; pt4.x = Dmin_2; pt4.y = 0; pt4.z = 2*Pdiff+Ptip; pt4.w = 1; pt5.x = Dmin_2; // not used, instead pt1 one full cycle later is used pt5.y = 0; // to avoid floating point errors pt5.z = P; pt5.w = 1; int total_segments = (screwHeight/P-1)*segments; vec origin = {0}; vec top = {0}; top.z = screwHeight; vec up = {0}; up.z = 1; vec down = {0}; down.z = -1; float anginc = (float)360/segments; vec sliced8Int; int needsExtraTris = 0; for(int i = -segments; i < total_segments+segments; i++) { vec p1,p2,p3,p4,p5; vec p1n,p2n,p3n,p4n,p5n; vec ob1,ob1n; vec ot1,ot1n; float ango = (float)360*((i+segments)%segments)/segments; float angno = (float)360*((i+segments)%segments+1)/segments; float cosao = cos(ango*M_PI/180); float sinao = sin(ango*M_PI/180); float cosano = cos(angno*M_PI/180); float sinano = sin(angno*M_PI/180); ob1.x = fD*cosao; ob1.y = fD*sinao; ob1.z = 0; ob1n.x = fD*cosano; ob1n.y = fD*sinano; ob1n.z = 0; ot1.x = fD*cosao; ot1.y = fD*sinao; ot1.z = screwHeight; ot1n.x = fD*cosano; ot1n.y = fD*sinano; ot1n.z = screwHeight; float ang = (float)360*i/segments; float angn = (float)360*(i+1)/segments; float angc = (float)360*(i+segments)/segments; float angnc = (float)360*(i+1+segments)/segments; float cosa = cos(ang*M_PI/180); float sina = sin(ang*M_PI/180); float cosan = cos(angn*M_PI/180); float sinan = sin(angn*M_PI/180); float cosanc = cos(angnc*M_PI/180); float sinanc = sin(angnc*M_PI/180); float cosac = cos(angc*M_PI/180); float sinac = sin(angc*M_PI/180); float z = P*ang/360; float zn = P*angn/360; float zc = P*angc/360; float znc = P*angnc/360; mat t; mat tn; mat tc; mat tnc; t.xx = cosa; t.xy = sina; t.xz = 0; t.xw = 0; t.yx = -sina; t.yy = cosa; t.yz = 0; t.yw = 0; t.zx = 0; t.zy = 0; t.zz = 1; t.zw = 0; t.tx = 0; t.ty = 0; t.tz = z; t.tw = 1; tn.xx = cosan; tn.xy = sinan; tn.xz = 0; tn.xw = 0; tn.yx = -sinan; tn.yy = cosan; tn.yz = 0; tn.yw = 0; tn.zx = 0; tn.zy = 0; tn.zz = 1; tn.zw = 0; tn.tx = 0; tn.ty = 0; tn.tz = zn; tn.tw = 1; tnc.xx = cosanc; tnc.xy = sinanc; tnc.xz = 0; tnc.xw = 0; tnc.yx = -sinanc; tnc.yy = cosanc; tnc.yz = 0; tnc.yw = 0; tnc.zx = 0; tnc.zy = 0; tnc.zz = 1; tnc.zw = 0; tnc.tx = 0; tnc.ty = 0; tnc.tz = znc; tnc.tw = 1; tc.xx = cosac; tc.xy = sinac; tc.xz = 0; tc.xw = 0; tc.yx = -sinac; tc.yy = cosac; tc.yz = 0; tc.yw = 0; tc.zx = 0; tc.zy = 0; tc.zz = 1; tc.zw = 0; tc.tx = 0; tc.ty = 0; tc.tz = zc; tc.tw = 1; vec_mat_mult(&pt1, &t, &p1); vec_mat_mult(&pt2, &t, &p2); vec_mat_mult(&pt3, &t, &p3); vec_mat_mult(&pt4, &t, &p4); vec_mat_mult(&pt1, &tc, &p5); // using pt1 with a transform of 1 // full cycle around to avoid // floating point roundoff errors vec_mat_mult(&pt1, &tn, &p1n); vec_mat_mult(&pt2, &tn, &p2n); vec_mat_mult(&pt3, &tn, &p3n); vec_mat_mult(&pt4, &tn, &p4n); vec_mat_mult(&pt1, &tnc, &p5n); // using pt1 with a transform of 1 // full cycle around to avoid // floating point roundoff errors if(i < 0) { int wrote_outer_tri = 0; vec int1,int2; int tris_written; if(write_sliced_tri(outf, &p1,&p1n,&p2n,female,&origin,&up,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int2,&origin,&int1,0); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ob1,0); num_tris += 1; } else { write_tri(outf,&int1,&ob1n,&ob1,0); write_tri(outf,&int2,&int1,&ob1,0); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p1,&p2n,&p2,female,&origin,&up,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int2,&origin,&int1,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ob1,0); num_tris += 1; } else { write_tri(outf,&int1,&ob1n,&ob1,0); write_tri(outf,&int2,&int1,&ob1,0); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p2,&p2n,&p3n,female,&origin,&up,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int2,&origin,&int1,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ob1,0); num_tris += 1; } else { write_tri(outf,&int1,&ob1n,&ob1,0); write_tri(outf,&int2,&int1,&ob1,0); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p2,&p3n,&p3,female,&origin,&up,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int2,&origin,&int1,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ob1,0); num_tris += 1; } else { write_tri(outf,&int1,&ob1n,&ob1,0); write_tri(outf,&int2,&int1,&ob1,0); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p3,&p3n,&p4n,female,&origin,&up,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int2,&origin,&int1,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ob1,0); num_tris += 1; } else { write_tri(outf,&int1,&ob1n,&ob1,0); write_tri(outf,&int2,&int1,&ob1,0); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p3,&p4n,&p4,female,&origin,&up,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int2,&origin,&int1,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ob1,0); num_tris += 1; } else { write_tri(outf,&int1,&ob1n,&ob1,0); write_tri(outf,&int2,&int1,&ob1,0); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p4,&p4n,&p5n,female,&origin,&up,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int2,&origin,&int1,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ob1,0); num_tris += 1; } else { write_tri(outf,&int1,&ob1n,&ob1,0); write_tri(outf,&int2,&int1,&ob1,0); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p4,&p5n,&p5,female,&origin,&up,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int2,&origin,&int1,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ob1,0); num_tris += 1; } else { write_tri(outf,&int1,&ob1n,&ob1,0); write_tri(outf,&int2,&int1,&ob1,0); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; } else if(i >= total_segments) { int wrote_outer_tri = 0; vec int1,int2; int tris_written; if(write_sliced_tri(outf, &p1,&p1n,&p2n,female,&top,&down,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int1,&top,&int2,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ot1,1); num_tris += 1; } else { write_tri(outf,&int1,&ot1n,&ot1,1); write_tri(outf,&int2,&int1,&ot1,1); wrote_outer_tri = 1; num_tris += 2; } } if(i == total_segments+segments-1 && needsExtraTris) { write_tri(outf, &int1,&p1n,&sliced8Int,female); num_tris += 1; if(male) { write_tri(outf, &int1,&sliced8Int,&top,female); num_tris += 1; } else { write_tri(outf, &int1,&sliced8Int,&ot1n,female); num_tris += 1; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p1,&p2n,&p2,female,&top,&down,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int1,&top,&int2,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ot1,1); num_tris += 1; } else { write_tri(outf,&int1,&ot1n,&ot1,1); write_tri(outf,&int2,&int1,&ot1,1); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p2,&p2n,&p3n,female,&top,&down,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int1,&top,&int2,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ot1,1); num_tris += 1; } else { write_tri(outf,&int1,&ot1n,&ot1,1); write_tri(outf,&int2,&int1,&ot1,1); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p2,&p3n,&p3,female,&top,&down,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int1,&top,&int2,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ot1,1); num_tris += 1; } else { write_tri(outf,&int1,&ot1n,&ot1,1); write_tri(outf,&int2,&int1,&ot1,1); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p3,&p3n,&p4n,female,&top,&down,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int1,&top,&int2,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ot1,1); num_tris += 1; } else { write_tri(outf,&int1,&ot1n,&ot1,1); write_tri(outf,&int2,&int1,&ot1,1); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p3,&p4n,&p4,female,&top,&down,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int1,&top,&int2,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ot1,1); num_tris += 1; } else { write_tri(outf,&int1,&ot1n,&ot1,1); write_tri(outf,&int2,&int1,&ot1,1); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p4,&p4n,&p5n,female,&top,&down,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int1,&top,&int2,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ot1,1); num_tris += 1; } else { write_tri(outf,&int1,&ot1n,&ot1,1); write_tri(outf,&int2,&int1,&ot1,1); wrote_outer_tri = 1; num_tris += 2; } } } num_tris += tris_written; if(write_sliced_tri(outf, &p4,&p5n,&p5,female,&top,&down,&int1,&int2,&tris_written)) { if(male) { write_tri(outf,&int1,&top,&int2,female); num_tris += 1; } else { if(wrote_outer_tri) { write_tri(outf,&int2,&int1,&ot1,1); num_tris += 1; } else { write_tri(outf,&int1,&ot1n,&ot1,1); write_tri(outf,&int2,&int1,&ot1,1); wrote_outer_tri = 1; num_tris += 2; } } if(i == total_segments && !vec_equals(&int2,&p5)) { needsExtraTris = 1; vec_copy(&int2,&sliced8Int); } } num_tris += tris_written; } else { write_quad(outf, &p1,&p1n,&p2n,&p2,female); write_quad(outf, &p2,&p2n,&p3n,&p3,female); write_quad(outf, &p3,&p3n,&p4n,&p4,female); write_quad(outf, &p4,&p4n,&p5n,&p5,female); num_tris += 8; } } if(female) { for(int i = 0; i < segments; i++) { vec ob1,ob1n; vec ot1,ot1n; float ang = (float)360*i/segments; float angn = (float)360*(i+1)/segments; float cosa = cos(ang*M_PI/180); float sina = sin(ang*M_PI/180); float cosan = cos(angn*M_PI/180); float sinan = sin(angn*M_PI/180); ob1.x = fD*cosa; ob1.y = fD*sina; ob1.z = 0; ob1n.x = fD*cosan; ob1n.y = fD*sinan; ob1n.z = 0; ot1.x = fD*cosa; ot1.y = fD*sina; ot1.z = screwHeight; ot1n.x = fD*cosan; ot1n.y = fD*sinan; ot1n.z = screwHeight; write_quad(outf,&ob1,&ob1n,&ot1n,&ot1,0); num_tris += 2; } } fseek(outf, 80, SEEK_SET); fwrite(&num_tris, 4, 1, outf); fclose(outf); return 0; } stl_cmd-1.1/src/stl_torus.cpp000066400000000000000000000114361322161221000163240ustar00rootroot00000000000000/* Copyright 2017 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 void print_usage() { fprintf(stderr, "stl_torus outputs an STL file of a single torus.\n\n"); fprintf(stderr, "usage: stl_torus [ -o ] [ -i ] [ -s ] [ -c ] [ ]\n"); fprintf(stderr, " Outputs an stl file of a torus with the provided outer radius, inner radius and number of segments.\n"); fprintf(stderr, " If the inner radius is omitted, it defaults to .5. If the outer radius is omitted, it defaults to 1.\n"); fprintf(stderr, " If segments is omitted, it defaults to 32. If cross sectional segments is omitted, it defaults to half the segments.\n"); fprintf(stderr, " If no output file is provided, data is sent to stdout. \n"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; int c; float innerRadius = .5; float outerRadius = 1; int segments = 32; int minorSegments = 16; int minorSegmentsSet = 0; while((c = getopt(argc, argv, "i:o:s:c:")) != -1) { switch(c) { case 'i': innerRadius = atof(optarg); break; case 'o': outerRadius = atof(optarg); break; case 's': segments = atoi(optarg); break; case 'c': minorSegments = atoi(optarg); minorSegmentsSet = 1; break; case '?': fprintf(stderr, "Unrecognized option: '-%c'\n", optopt); errflg++; break; } } if(!minorSegmentsSet) { minorSegments = segments/2; } if(errflg) { print_usage(); exit(2); } FILE *outf; if(optind == argc-1) { char *file = argv[optind]; outf = fopen(file, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", file); exit(2); } } else { outf = stdout; } char header[81] = {0}; snprintf(header, 81, "Torus with inner radius %.4f and outer radius %.4f", innerRadius, outerRadius); fwrite(header, 80, 1, outf); uint32_t num_tris = 2*segments*minorSegments; fwrite(&num_tris, 4, 1, outf); uint16_t abc = 0; // attribute byte count vec p0; vec p1; vec p2; vec p3; float majorRadius = (outerRadius+innerRadius)*.5; float minorRadius = (outerRadius-innerRadius)*.5; for(int i = 0; i < segments; i++) { float i_angle = 2*M_PI*i/segments; float i_angle2 = 2*M_PI*(i+1)/segments; if(i == segments-1) { i_angle2 = 0; } float i_cosa = cos(i_angle); float i_sina = sin(i_angle); float i_cosa2 = cos(i_angle2); float i_sina2 = sin(i_angle2); for(int j = 0; j < minorSegments; j++) { float j_angle = 2*M_PI*j/minorSegments; float j_angle2 = 2*M_PI*(j+1)/minorSegments; if(j == minorSegments-1) { j_angle2 = 0; } float j_cosa = cos(j_angle); float j_sina = sin(j_angle); float j_cosa2 = cos(j_angle2); float j_sina2 = sin(j_angle2); p0.x = i_cosa*(majorRadius+minorRadius*j_cosa); p0.y = i_sina*(majorRadius+minorRadius*j_cosa); p0.z = minorRadius*j_sina; p1.x = i_cosa2*(majorRadius+minorRadius*j_cosa); p1.y = i_sina2*(majorRadius+minorRadius*j_cosa); p1.z = minorRadius*j_sina; p2.x = i_cosa2*(majorRadius+minorRadius*j_cosa2); p2.y = i_sina2*(majorRadius+minorRadius*j_cosa2); p2.z = minorRadius*j_sina2; p3.x = i_cosa*(majorRadius+minorRadius*j_cosa2); p3.y = i_sina*(majorRadius+minorRadius*j_cosa2); p3.z = minorRadius*j_sina2; write_quad(outf, &p0, &p1, &p2, &p3, 0); } } return 0; } stl_cmd-1.1/src/stl_transform.cpp000066400000000000000000000220731322161221000171620ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #include #include #include #include #include #include #include "stl_util.h" #define BUFFER_SIZE 4096 // TODO make input and output file optional, if not specified read from // stdin and write to stdout. Add to other stl_cmds as well. This will // allow for piping between stl_cmds which could elimate some temporary files: // stl_cube -w 1 | stl_transform -tx 10 > cube.stl // stl_cube -w 2 | stl_transform -tx 20 > cube2.stl // stl_merge *.stl | transform -s 10 > all_cubes_scaled.stl void print_usage() { fprintf(stderr, "stl_transform performs any number of transformations to an STL file.\n\n"); fprintf(stderr, "usage: stl_transform [[ ] ...] \n"); fprintf(stderr, " Performs any number of the following transformations in\n"); fprintf(stderr, " the order they are listed on the command line:\n"); fprintf(stderr, " -rx - rotates degrees about the x-axis\n"); fprintf(stderr, " -ry - rotates degrees about the y-axis\n"); fprintf(stderr, " -rz - rotates degrees about the z-axis\n"); fprintf(stderr, " -s - uniformly scales x, y and z by (cannot be 0)\n"); fprintf(stderr, " -sx - scales by in x (cannot be 0)\n"); fprintf(stderr, " -sy - scales by in y (cannot be 0)\n"); fprintf(stderr, " -sz - scales by in z (cannot be 0)\n"); fprintf(stderr, " -tx - translates units in x\n"); fprintf(stderr, " -ty - translates units in y\n"); fprintf(stderr, " -tz - translates units in z\n"); } int main(int argc, char** argv) { if(argc >= 2) { if(strcmp(argv[1], "--help") == 0) { print_usage(); exit(2); } } int errflg = 0; int did_scale = 0; mat tmp; mat tmp2; mat combined; mat inv_combined; mat inv_transpose; init_identity_mat(&combined); init_identity_mat(&inv_combined); int index; float arg; // TODO better arg handling so better errors can be displayed for(index = 1; index < argc; index++) { if(strcmp("-rx", argv[index]) == 0) { index++; if(index >= argc) break; arg = atof(argv[index]); init_rx_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_rx_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } else if(strcmp("-ry", argv[index]) == 0) { index++; if(index >= argc) break; arg = atof(argv[index]); init_ry_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_ry_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } else if(strcmp("-rz", argv[index]) == 0) { index++; if(index >= argc) break; arg = atof(argv[index]); init_rz_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_rz_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } else if(strcmp("-s", argv[index]) == 0) { index++; if(index >= argc) break; did_scale = 1; arg = atof(argv[index]); if(arg == 0) { errflg++; } else { init_s_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_s_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } } else if(strcmp("-sx", argv[index]) == 0) { index++; if(index >= argc) break; did_scale = 1; arg = atof(argv[index]); if(arg == 0) { errflg++; } else { init_sx_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_sx_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } } else if(strcmp("-sy", argv[index]) == 0) { index++; if(index >= argc) break; did_scale = 1; arg = atof(argv[index]); if(arg == 0) { errflg++; } else { init_sy_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_sy_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } } else if(strcmp("-sz", argv[index]) == 0) { index++; if(index >= argc) break; did_scale = 1; arg = atof(argv[index]); if(arg == 0) { errflg++; } else { init_sz_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_sz_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } } else if(strcmp("-tx", argv[index]) == 0) { index++; if(index >= argc) break; arg = atof(argv[index]); init_tx_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_tx_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } else if(strcmp("-ty", argv[index]) == 0) { index++; if(index >= argc) break; arg = atof(argv[index]); init_ty_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_ty_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } else if(strcmp("-tz", argv[index]) == 0) { index++; if(index >= argc) break; arg = atof(argv[index]); init_tz_mat(&tmp, arg); mat_copy(&combined, &tmp2); mat_mult(&tmp2, &tmp, &combined); init_inv_tz_mat(&tmp, arg); mat_copy(&inv_combined, &tmp2); mat_mult(&tmp, &tmp2, &inv_combined); } else { break; } } if(errflg || index+1 >= argc) { print_usage(); exit(2); } char *file = argv[index]; char *outfile = argv[index+1]; if(!is_valid_binary_stl(file)) { fprintf(stderr, "%s is not a binary stl file.\n", file); exit(2); } mat_transpose(&inv_combined, &inv_transpose); FILE *f; FILE *outf; f = fopen(file, "rb"); if(!f) { fprintf(stderr, "Can't read file: %s\n", file); exit(2); } outf = fopen(outfile, "wb"); if(!outf) { fprintf(stderr, "Can't write to file: %s\n", outfile); exit(2); } fseek(f, 80, SEEK_SET); uint32_t num_tris; size_t readBytes = fread(&num_tris, 4, 1, f); char header[81] = {0}; // include an extra char for terminating \0 of snprintf snprintf(header, 81, "Transformed copy of %s", basename(file)); fwrite(header, 80, 1, outf); fwrite(&num_tris, 4, 1, outf); uint16_t abc = 0; // attribute byte count vec tmp_vec; vec normal; vec point; normal.w = 0; point.w = 1; for(int i = 0; i < num_tris; i++) { readBytes = fread(&normal, 1, 12,f); vec_mat_mult(&normal, &inv_transpose, &tmp_vec); if(did_scale) { vec_normalize(&tmp_vec, &normal); fwrite(&normal, 1, 12, outf); } else { fwrite(&tmp_vec, 1, 12, outf); } for(int j = 0; j < 3; j++) { readBytes = fread(&point, 1, 12,f); vec_mat_mult(&point, &combined, &tmp_vec); fwrite(&tmp_vec, 1, 12, outf); } readBytes = fread(&abc, 1, 2,f); fwrite(&abc, 1, 2,outf); } fclose(f); fclose(outf); return 0; } stl_cmd-1.1/src/stl_util.h000066400000000000000000000323521322161221000155720ustar00rootroot00000000000000/* Copyright 2014 by Freakin' Sweet Apps, LLC (stl_cmd@freakinsweetapps.com) This file is part of stl_cmd. stl_cmd is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ #ifndef ___STL_UTIL_H___ #include #include #include #ifndef M_PI #define M_PI 3.141592653589793 #endif #define EPSILON 0.0001f int is_valid_binary_stl(char* filename) { FILE *f; f = fopen(filename, "rb"); if(f) { struct stat st; fstat(fileno(f), &st); off_t size = st.st_size; if(size >= 84) { fseek(f, 80, SEEK_SET); uint32_t num_tris; size_t readBytes = fread(&num_tris, 4, 1, f); uint64_t calced_size = 84+(4*12+2)*num_tris; if(size != calced_size) { // fprintf(stderr, " actual size: %10lld\n", size); // fprintf(stderr, " num triangles: %10d\n", num_tris); // fprintf(stderr, "calculated size: %10lld\n", calced_size); return 0; } } else { return 0; } } return 1; } typedef struct { float xx; float xy; float xz; float xw; float yx; float yy; float yz; float yw; float zx; float zy; float zz; float zw; float tx; float ty; float tz; float tw; } mat; typedef struct { float x; float y; float z; float w; } vec; void mat_print(mat *m) { printf("%f %f %f %f\n", m->xx, m->xy, m->xz, m->xw); printf("%f %f %f %f\n", m->yx, m->yy, m->yz, m->yw); printf("%f %f %f %f\n", m->zx, m->zy, m->zz, m->zw); printf("%f %f %f %f\n", m->tx, m->ty, m->tz, m->tw); } void init_identity_mat(mat *m) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_s_mat(mat *m, float s) { m->xx = s; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = s; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = s; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_sx_mat(mat *m, float s) { m->xx = s; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_sy_mat(mat *m, float s) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = s; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_sz_mat(mat *m, float s) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = s; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_rx_mat(mat *m, float angle) { angle *= M_PI/180; // convert to radians float cosa = cos(angle); float sina = sin(angle); m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = cosa; m->yz = sina; m->yw = 0; m->zx = 0; m->zy = -sina; m->zz = cosa; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_ry_mat(mat *m, float angle) { angle *= M_PI/180; // convert to radians float cosa = cos(angle); float sina = sin(angle); m->xx = cosa; m->xy = 0; m->xz = -sina; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = sina; m->zy = 0; m->zz = cosa; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_rz_mat(mat *m, float angle) { angle *= M_PI/180; // convert to radians float cosa = cos(angle); float sina = sin(angle); m->xx = cosa; m->xy = sina; m->xz = 0; m->xw = 0; m->yx = -sina; m->yy = cosa; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_tx_mat(mat *m, float t) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = t; m->ty = 0; m->tz = 0; m->tw = 1; } void init_ty_mat(mat *m, float t) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = t; m->tz = 0; m->tw = 1; } void init_tz_mat(mat *m, float t) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = t; m->tw = 1; } void init_inv_s_mat(mat *m, float s) { m->xx = 1./s; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1./s; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1./s; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_inv_sx_mat(mat *m, float s) { m->xx = 1./s; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_inv_sy_mat(mat *m, float s) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1./s; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_inv_sz_mat(mat *m, float s) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1./s; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = 0; m->tw = 1; } void init_inv_rx_mat(mat *m, float angle) { angle *= M_PI/180; // convert to radians float cosa = cos(angle); float sina = sin(angle); m->xx = 1; m->yx = 0; m->zx = 0; m->tx = 0; m->xy = 0; m->yy = cosa; m->zy = sina; m->ty = 0; m->xz = 0; m->yz = -sina; m->zz = cosa; m->tz = 0; m->xw = 0; m->yw = 0; m->zw = 0; m->tw = 1; } void init_inv_ry_mat(mat *m, float angle) { angle *= M_PI/180; // convert to radians float cosa = cos(angle); float sina = sin(angle); m->xx = cosa; m->yx = 0; m->zx = -sina; m->tx = 0; m->xy = 0; m->yy = 1; m->zy = 0; m->ty = 0; m->xz = sina; m->yz = 0; m->zz = cosa; m->tz = 0; m->xw = 0; m->yw = 0; m->zw = 0; m->tw = 1; } void init_inv_rz_mat(mat *m, float angle) { angle *= M_PI/180; // convert to radians float cosa = cos(angle); float sina = sin(angle); m->xx = cosa; m->yx = sina; m->zx = 0; m->tx = 0; m->xy = -sina; m->yy = cosa; m->zy = 0; m->ty = 0; m->xz = 0; m->yz = 0; m->zz = 1; m->tz = 0; m->xw = 0; m->yw = 0; m->zw = 0; m->tw = 1; } void init_inv_tx_mat(mat *m, float t) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = -t; m->ty = 0; m->tz = 0; m->tw = 1; } void init_inv_ty_mat(mat *m, float t) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = -t; m->tz = 0; m->tw = 1; } void init_inv_tz_mat(mat *m, float t) { m->xx = 1; m->xy = 0; m->xz = 0; m->xw = 0; m->yx = 0; m->yy = 1; m->yz = 0; m->yw = 0; m->zx = 0; m->zy = 0; m->zz = 1; m->zw = 0; m->tx = 0; m->ty = 0; m->tz = -t; m->tw = 1; } void mat_transpose(mat *m, mat *out) { out->xx = m->xx; out->xy = m->yx; out->xz = m->zx; out->xw = m->tx; out->yx = m->xy; out->yy = m->yy; out->yz = m->zy; out->yw = m->ty; out->zx = m->xz; out->zy = m->yz; out->zz = m->zz; out->zw = m->tz; out->tx = m->xw; out->ty = m->yw; out->tz = m->zw; out->tw = m->tw; } void mat_mult(mat *m1, mat *m2, mat *out) { out->xx = m1->xx*m2->xx+m1->xy*m2->yx+m1->xz*m2->zx+m1->xw*m2->tx; out->xy = m1->xx*m2->xy+m1->xy*m2->yy+m1->xz*m2->zy+m1->xw*m2->ty; out->xz = m1->xx*m2->xz+m1->xy*m2->yz+m1->xz*m2->zz+m1->xw*m2->tz; out->xw = m1->xx*m2->xw+m1->xy*m2->yw+m1->xz*m2->zw+m1->xw*m2->tw; out->yx = m1->yx*m2->xx+m1->yy*m2->yx+m1->yz*m2->zx+m1->yw*m2->tx; out->yy = m1->yx*m2->xy+m1->yy*m2->yy+m1->yz*m2->zy+m1->yw*m2->ty; out->yz = m1->yx*m2->xz+m1->yy*m2->yz+m1->yz*m2->zz+m1->yw*m2->tz; out->yw = m1->yx*m2->xw+m1->yy*m2->yw+m1->yz*m2->zw+m1->yw*m2->tw; out->zx = m1->zx*m2->xx+m1->zy*m2->yx+m1->zz*m2->zx+m1->zw*m2->tx; out->zy = m1->zx*m2->xy+m1->zy*m2->yy+m1->zz*m2->zy+m1->zw*m2->ty; out->zz = m1->zx*m2->xz+m1->zy*m2->yz+m1->zz*m2->zz+m1->zw*m2->tz; out->zw = m1->zx*m2->xw+m1->zy*m2->yw+m1->zz*m2->zw+m1->zw*m2->tw; out->tx = m1->tx*m2->xx+m1->ty*m2->yx+m1->tz*m2->zx+m1->tw*m2->tx; out->ty = m1->tx*m2->xy+m1->ty*m2->yy+m1->tz*m2->zy+m1->tw*m2->ty; out->tz = m1->tx*m2->xz+m1->ty*m2->yz+m1->tz*m2->zz+m1->tw*m2->tz; out->tw = m1->tx*m2->xw+m1->ty*m2->yw+m1->tz*m2->zw+m1->tw*m2->tw; } void vec_mat_mult(vec *v, mat *m, vec *out) { out->x = v->x*m->xx+v->y*m->yx+v->z*m->zx+v->w*m->tx; out->y = v->x*m->xy+v->y*m->yy+v->z*m->zy+v->w*m->ty; out->z = v->x*m->xz+v->y*m->yz+v->z*m->zz+v->w*m->tz; out->w = v->x*m->xw+v->y*m->yw+v->z*m->zw+v->w*m->tw; } float vec_magnitude(vec *v) { return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); } void vec_normalize(vec *v, vec *out) { float invmag = 1./vec_magnitude(v); out->x = v->x*invmag; out->y = v->y*invmag; out->z = v->z*invmag; } int vec_equals(vec *v, vec *v2) { return fabs(v->x-v2->x) < EPSILON && fabs(v->y-v2->y) < EPSILON && fabs(v->z-v2->z) < EPSILON; } int vec_equals_exact(vec *v, vec *v2) { return v->x-v2->x == 0 && v->y-v2->y == 0 && v->z-v2->z == 0; } void vec_copy(vec *v, vec *out) { out->x = v->x; out->y = v->y; out->z = v->z; out->w = v->w; } void mat_copy(mat *m1, mat *out) { out->xx = m1->xx; out->xy = m1->xy; out->xz = m1->xz; out->xw = m1->xw; out->yx = m1->yx; out->yy = m1->yy; out->yz = m1->yz; out->yw = m1->yw; out->zx = m1->zx; out->zy = m1->zy; out->zz = m1->zz; out->zw = m1->zw; out->tx = m1->tx; out->ty = m1->ty; out->tz = m1->tz; out->tw = m1->tw; } void vec_cross(vec *a, vec *b, vec *out) { out->x = a->y*b->z-a->z*b->y; out->y = a->z*b->x-a->x*b->z; out->z = a->x*b->y-a->y*b->x; } void vec_sub(vec *a, vec *b, vec *out) { out->x = a->x-b->x; out->y = a->y-b->y; out->z = a->z-b->z; } float vec_dot(vec *a, vec *b) { return a->x*b->x+a->y*b->y+a->z*b->z; } void write_tri(FILE *f, vec *p1, vec *p2, vec *p3, int rev) { if(rev) { vec *tmp = p1; p1 = p3; p3 = tmp; } vec n1; vec v1,v2; vec_sub(p2,p1,&v1); vec_sub(p3,p1,&v2); vec_cross(&v1,&v2,&n1); vec_normalize(&n1,&n1); uint16_t abc = 0; fwrite(&n1, 1, 12, f); fwrite(p1, 1, 12, f); fwrite(p2, 1, 12, f); fwrite(p3, 1, 12, f); fwrite(&abc,1, 2, f); } void write_quad(FILE *f, vec *p1, vec *p2, vec *p3, vec *p4,int rev) { //write two triangles 1,2,3 and 1,3,4 if(rev) { vec *tmp = p1; p1 = p4; p4 = tmp; tmp = p2; p2 = p3; p3 = tmp; } vec n1,n2; vec v1,v2,v3; vec_sub(p2,p1,&v1); vec_sub(p3,p1,&v2); vec_sub(p4,p1,&v3); vec_cross(&v1,&v2,&n1); vec_normalize(&n1,&n1); vec_cross(&v2,&v3,&n2); vec_normalize(&n2,&n2); uint16_t abc = 0; fwrite(&n1, 1, 12, f); fwrite(p1, 1, 12, f); fwrite(p2, 1, 12, f); fwrite(p3, 1, 12, f); fwrite(&abc,1, 2, f); fwrite(&n2, 1, 12, f); fwrite(p1, 1, 12, f); fwrite(p3, 1, 12, f); fwrite(p4, 1, 12, f); fwrite(&abc,1, 2, f); } #endif