Repository: mfx-inria/curvislicer Branch: master Commit: 1ea03fef9432 Files: 88 Total size: 1.8 MB Directory structure: gitextract_11c6xarw/ ├── .gitignore ├── .gitmodules ├── CMakeLists.txt ├── LICENSE.md ├── README.md ├── compile_on_mingw64.sh ├── curvislice.bat ├── curvislice.sh ├── get_started_mingw64.sh ├── libs/ │ └── tclap/ │ ├── AUTHORS │ ├── COPYING │ ├── ChangeLog │ ├── INSTALL │ ├── NEWS │ ├── README │ └── include/ │ └── tclap/ │ ├── Arg.h │ ├── ArgException.h │ ├── ArgTraits.h │ ├── CmdLine.h │ ├── CmdLineInterface.h │ ├── CmdLineOutput.h │ ├── Constraint.h │ ├── DocBookOutput.h │ ├── HelpVisitor.h │ ├── IgnoreRestVisitor.h │ ├── MultiArg.h │ ├── MultiSwitchArg.h │ ├── OptionalUnlabeledTracker.h │ ├── StandardTraits.h │ ├── StdOutput.h │ ├── SwitchArg.h │ ├── UnlabeledMultiArg.h │ ├── UnlabeledValueArg.h │ ├── ValueArg.h │ ├── ValuesConstraint.h │ ├── VersionVisitor.h │ ├── Visitor.h │ ├── XorHandler.h │ └── ZshCompletionOutput.h ├── luaGenerator.bat ├── luaGenerator.sh ├── models/ │ ├── FoilCutter.stl │ ├── airfoil.stl │ ├── anklebase_small.stl │ ├── car_med.stl │ └── wing.stl ├── pack_release.bat ├── resources/ │ └── curvi/ │ ├── features.lua │ └── printer.lua ├── src/ │ ├── MeshFormat_msh.cpp │ ├── MeshFormat_msh.h │ ├── TetMesh.cpp │ ├── TetMesh.h │ ├── config.h.in │ ├── gcode.cpp │ ├── gcode.h │ ├── helpers.h │ ├── main.cpp │ ├── thicknesses.h │ └── uncurve.cpp ├── toTetmesh.bat ├── toTetmesh.sh └── tools/ ├── icesl/ │ ├── icesl-libs/ │ │ ├── icesl-deprecated_64.luac │ │ └── icesl-stdlib_64.luac │ ├── icesl-printers/ │ │ └── fff/ │ │ └── curvi/ │ │ ├── features.lua │ │ └── printer.lua │ ├── settings_curvi.xml │ ├── settings_curvi_a8.xml │ ├── settings_curvi_delta.xml │ ├── settings_curvi_fig.xml │ ├── settings_curvi_um2.xml │ └── settings_curvi_um2_no_iron.xml └── tetviz/ ├── .gitattributes ├── .gitignore ├── .gitmodules ├── CMakeLists.txt ├── libs/ │ └── CMakeLists.txt └── src/ ├── CMakeLists.txt ├── TetMesh.cpp ├── TetMesh.h ├── TetViz.cpp ├── TetViz.h ├── gcode.cpp ├── gcode.h ├── shade.fp ├── shade.vp ├── slicerror.fp └── slicerror.vp ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ bin/ build/ lib/ *.gcode *.msh *.csv models/ !models/**.stl settings.lua ================================================ FILE: .gitmodules ================================================ [submodule "libs/LibSL-small"] path = libs/LibSL-small url = https://github.com/sylefeb/LibSL-small.git branch = CurviSlice [submodule "libs/SolverWrapper"] path = libs/SolverWrapper url = https://github.com/bedela-Epitech/SolverWrapper.git branch = master ================================================ FILE: CMakeLists.txt ================================================ #################################### cmake_minimum_required(VERSION 2.6) project(curvislice) add_subdirectory(libs/SolverWrapper) add_subdirectory(libs/LibSL-small) INCLUDE_DIRECTORIES( ${PROJECT_SOURCE_DIR}/libs/tclap/include/ ${PROJECT_SOURCE_DIR}/libs/SolverWrapper/include/ ${PROJECT_SOURCE_DIR}/libs/SolverWrapper/src/ ${PROJECT_SOURCE_DIR}/libs/LibSL-small/src/ ${PROJECT_SOURCE_DIR}/libs/LibSL-small/src/LibSL/ ) SET(LibSL_small libs/LibSL-small/src/LibSL/System/System.cpp libs/LibSL-small/src/LibSL/CppHelpers/CppHelpers.cpp libs/LibSL-small/src/LibSL/StlHelpers/StlHelpers.cpp libs/LibSL-small/src/LibSL/Image/Image.cpp libs/LibSL-small/src/LibSL/Math/Vertex.cpp libs/LibSL-small/src/LibSL/Math/Math.cpp libs/LibSL-small/src/LibSL/Mesh/Mesh.cpp libs/LibSL-small/src/LibSL/Mesh/MeshFormat_stl.cpp libs/LibSL-small/src/LibSL/Mesh/VertexFormat_dynamic.cpp ) set(CMAKE_EXE_LINKER_FLAGS "-static-libgcc -static-libstdc++ -static") #################################### ADD_EXECUTABLE(curvislice_osqp src/main.cpp src/gcode.h src/gcode.cpp src/helpers.h src/TetMesh.h src/TetMesh.cpp src/thicknesses.h src/MeshFormat_msh.h src/MeshFormat_msh.cpp ${LibSL_small} ) INSTALL( TARGETS curvislice_osqp RUNTIME DESTINATION ${CMAKE_SOURCE_DIR}/bin ) INSTALL(FILES ${CMAKE_BINARY_DIR}/libs/SolverWrapper/lib/osqp/out/libosqp.dll DESTINATION ${CMAKE_SOURCE_DIR}/bin) set_target_properties(curvislice_osqp PROPERTIES CXX_STANDARD 17 CXX_EXTENSIONS OFF ) target_link_libraries(curvislice_osqp SolverWrapper) target_compile_options(curvislice_osqp PRIVATE -DOSQP) #################################### if (BUILD_WITH_GRB) ADD_EXECUTABLE(curvislice_grb src/main.cpp src/gcode.h src/gcode.cpp src/helpers.h src/TetMesh.h src/TetMesh.cpp src/thicknesses.h src/MeshFormat_msh.h src/MeshFormat_msh.cpp ) INSTALL( TARGETS curvislice_grb RUNTIME DESTINATION ${CMAKE_SOURCE_DIR}/bin ) set_target_properties(curvislice_grb PROPERTIES CXX_STANDARD 17 CXX_EXTENSIONS OFF ) target_link_libraries(curvislice_grb SolverWrapper) target_compile_options(curvislice_grb PRIVATE -DGRB) target_compile_definitions(curvislice_grb PUBLIC "-DHAS_GUROBI") endif(BUILD_WITH_GRB) #################################### ADD_EXECUTABLE(uncurve src/uncurve.cpp src/gcode.h src/gcode.cpp src/TetMesh.h src/TetMesh.cpp src/thicknesses.h src/MeshFormat_msh.h src/MeshFormat_msh.cpp ${LibSL_small} ) INSTALL( TARGETS uncurve RUNTIME DESTINATION ${CMAKE_SOURCE_DIR}/bin ) set_target_properties(uncurve PROPERTIES CXX_STANDARD 17 CXX_EXTENSIONS OFF ) target_link_libraries(uncurve SolverWrapper) if(BUILD_WITH_GRB) target_compile_options(uncurve PRIVATE -DGRB) else(BUILD_WITH_GRB) target_compile_options(uncurve PRIVATE -DOSQP) endif(BUILD_WITH_GRB) #################################### if(WIN32) if (BUILD_WITH_GRB) target_link_libraries(curvislice_grb shlwapi) endif(BUILD_WITH_GRB) target_link_libraries(curvislice_osqp shlwapi) target_link_libraries(uncurve shlwapi) endif(WIN32) ================================================ FILE: LICENSE.md ================================================ GNU Affero General Public License ================================= _Version 3, 19 November 2007_ _Copyright © 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 Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are 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. 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. Developers that use our General Public Licenses protect your rights with two steps: **(1)** assert copyright on the software, and **(2)** offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. 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 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 work with which it is combined will remain governed by version 3 of the GNU General Public License. ### 14. Revised Versions of this License The Free Software Foundation may publish revised and/or new versions of the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a “Source” link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. 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 AGPL, see <>. ================================================ FILE: README.md ================================================ # CurviSlicer CurviSlicer is research project about achieving curved printing on standard, off-the-shelf, 3-axis FDM printers. Our goal is to improve surface quality and accuracy by curving the layers not only at the top, but also throughout the part. This reduces internal porosity and fragilities, and allows to accurately position the top curved surfaces. The image below compares adaptive slicing with flat layers (top) to the same number of layers using CurviSlicer (bottom). The adaptive slicer concentrates the thin slices around the car hood (as it should) but then it has to use thick slices everywhere else. Instead, CurviSlicer outputs curved slices that nicely follow the car outlines. These are roughly the same print time. ![](resources/car.png "Comparing flat and curved layers.") The method was developed by an international team of researchers: Jimmy Etienne, Nicolas Ray, Daniele Panozzo, Samuel Hornus, Charlie C.L. Wang, Jonàs Martínez, Sara Mcmains, Marc Alexa, Brian Wyvill and Sylvain Lefebvre ; you can [find the academic paper here](https://hal.archives-ouvertes.fr/hal-02120033/document). The work finds its origin in a brainstorm session during the 2018 Computational Geometry workshop at the Bellairs Research Institute, co-organized by Sue Whitesides and Sylvain Lazard. The implementation was done by Jimmy Etienne and Sylvain Lefebvre, with guidance from colleagues. Adrien Bedel helped greatly to modify the code to support OSQP. Please don't expect high quality, production ready code, this is a research prototype. The code depends on many other great projects such as [TetWild](https://github.com/Yixin-Hu/TetWild) and [OSQP](https://github.com/oxfordcontrol/osqp). ## Important notes > **1.** The original implementation in the paper uses the [Gurobi](https://www.gurobi.com/) commercial solver. This initial implementation is in the SIGGRAPH 2019 branch. **Please use it for reproducibility of the paper results (speed and quality)**. The master branch is modified to use OSQP and while it works great, there are differences and limitations compared to the Gurobi version. > **2.** This is a research prototype. It is not polished, and has several technical limitations and glitches. # How to use (Windows) This repository is meant to be built from source, and includes Windows binaries of some required external tools. The following described the build process using MinGW/MSYS2 for Windows. ## 1- IceSL Install the latest version of [IceSL](https://icesl.loria.fr/download/). ## 2- MinGW Install [MSYS2](https://www.msys2.org/), please make sure to follow all installation steps including the update instructions. Open a MinGW64 shell (be sure to select *64* not *32*). ## 3- Get this repository locally From the shell: ```git clone --recurse-submodules https://github.com/mfx-inria/curvislicer.git``` This will automatically download other repositories: SolverWrapper (wrapper API around Gurobi and OSQP), OSQP, LibSL-small. ## 4- Install the special printer profile Copy the folder [curvi](resources/curvi) (in the /resources folder) into the IceSL printer profiles folder ; on Windows this is **%appdata%/IceSL/icesl-printers/fff/** ## 5- Build From the MinGW64 shell, enter `./get_started_mingw64.sh` > By default, the OSQP solver version will be built. If you want to use Gurobi instead, you'll have to enable the CMake flag "BUILD_WITH_GRB" and choose the "GRB_VERSION" (and quite obviously you need to have Gurobi installed with a license). ## 6- Run From the MinGW64 shell run (parameters are optional): ```./curvislice.bat [stl_filename]``` It will automagically generate a G-code file. For example, a great starting point is to simply run ```./curvislice.bat models/wing.stl``` The GCode is then found in `models/wing.gcode` > To try with your own model, place it in `models` and run the same command line. # How to use (Linux) There is not reason this would not work under Linux, but we did not have time to make the scripts and the build system for all dependencies. Contributions are welcome! You can follow the Windows procedure, but will have to manually compile dependencies (TetWild) and create shell scripts from the Windows batch files. # Printing > **Caution, this software generates complex curved trajectories that may result in collisions between the printer carriage and the print. This could damage your printer.** The produced GCode is standard Marlin style for 1.75 mm filament and 0.4 mm nozzle. Note that it has **no header and no footer**. These you will have to add manually to fit your printer. Also please make sur the produced GCode properly fits your bed as we use an 'average' print bed configuration. In our experience the GCode prints best on delta-style printers, as the Z axis is comparably efficient to the X,Y axes. On other types of printers some adaptation of flow is required ; our tool **uncurve** has some command line parameters for this purpose, but these are mostly experimental. *We are expecting a certain clearance around the nozzle, so make sure there is space around -- basically a 45 degree cone going up from the nozzle tip on at least 5 centimeters, but larger parts may require more clearance. The angle to optimize for can be controlled from the command line.* ![](https://github.com/mfx-inria/curvislicer/blob/master/resources/nozzle-clearance.jpg "Typical space required around the nozzle.") # Slicing parameters We slice with IceSL using default parameters that may not be best for your models. You can change these parameters by opening IceSL, selecting the *curvi* printer, changing parameters and slicing any object (slicing will save the settings for next time). We encourage you to play with ironing and the type of top covers (curved covers or zigzag covers). # Integrating in another slicer CurviSlicer was developed using IceSL, however it can easily be used with different slicers. The optimizer generates a model that has to be sliced 'flat'. The model is called *after.stl* and can be found in the sub-directory having the name of your model and created during processing. However the slicer has to output a special GCode format, see *printer.lua* in the *curvi* printer profile directory (in /resources). Our tool *uncurve* also needs to know how the 3D mesh spatially relates to the trajectories produced by the slicer, as well as the layer thickness. This requires two special lines at the top, here is an example: ``` o X-10.3 Y-5.7 Z0.0 t 0.2 ``` Here, it means that given a trajectory point, we have to add the offset (-10.3,-5.7,0) to locate this same point in the input 3D model space. The line starting with *t* gives the slicing layer height. You are welcome to use CurviSlicer within the scope of the license (see below). Please cite our paper in your publications and the credits of your software! ``` @article{curvislicer, author = {Etienne, Jimmy and Ray, Nicolas and Panozzo, Daniele and Hornus, Samuel and Wang, Charlie C. L. and Mart\'{\i}nez, Jon\`{a}s and McMains, Sara and Alexa, Marc and Wyvill, Brian and Lefebvre, Sylvain}, title = {CurviSlicer: Slightly Curved Slicing for 3-Axis Printers}, year = {2019}, volume = {38}, number = {4}, journal = {ACM Transactions on Graphics}, articleno = {Article 81}, numpages = {11}, } ``` ### License [Affero GPL 3.0](https://www.gnu.org/licenses/agpl-3.0.en.html) ================================================ FILE: compile_on_mingw64.sh ================================================ #!/bin/bash mkdir BUILD cd BUILD /mingw64/bin/cmake -DCMAKE_BUILD_TYPE=Release -G "MinGW Makefiles" .. mingw32-make install cd .. ================================================ FILE: curvislice.bat ================================================ REM @echo off set gurobi=0 set volumic=0 set nozzle=0.4 set layer=0.3 set filament=1.75 set ironing=0 set model= set arg=none for %%A in (%*) do call :Loop %%A goto :EndLoop :Loop if "%arg%" EQU "none" ( set arg=%1 ) else ( set %arg%=%1 set arg=none ) goto :End :EndLoop if "%arg%" EQU "none" ( echo Error in arguments exit ) set path=%arg% for %%f in ("%path%") do set model=%%~dpnf set model=%model:\=/% echo %model% echo Generate tetmesh "from %model%.stl" ... call toTetmesh.bat %model% echo Done! echo Optimize... if "%gurobi%" EQU "1" ( .\bin\curvislice_grb.exe %model%.msh -l %layer% ) else ( .\bin\curvislice_osqp.exe %model%.msh -l %layer% ) echo Done! echo Prepare lua for IceSL call luaGenerator.bat %model% %volumic% %nozzle% %layer% %filament% %ironing% if not exist %appdata%\IceSL\icesl-printers\fff\curvi ( echo Create 'curvi' printer profile for IceSL mkdir "%appdata%\IceSL\icesl-printers\fff\curvi" copy /Y resources\curvi\features.lua "%appdata%\IceSL\icesl-printers\fff\curvi\" copy /Y resources\curvi\printer.lua "%appdata%\IceSL\icesl-printers\fff\curvi\" ) set ODIR=%CD% .\tools\icesl\bin\icesl-slicer.exe settings.lua --service chdir /d %ODIR% echo Uncurve %model% .\bin\uncurve.exe -l %layer% --gcode %model% echo " echo " echo " echo " echo " ______ __ __ __ echo " / \ / | / |/ | echo "/$$$$$$ | __ __ ______ __ __ $$/ _______ $$ |$$/ _______ ______ echo "$$ | $$/ / | / | / \ / \ / |/ | / |$$ |/ | / | / \ echo "$$ | $$ | $$ |/$$$$$$ |$$ \ /$$/ $$ |/$$$$$$$/ $$ |$$ |/$$$$$$$/ /$$$$$$ | echo "$$ | __ $$ | $$ |$$ | $$/ $$ /$$/ $$ |$$ \ $$ |$$ |$$ | $$ $$ | echo "$$ \__/ |$$ \__$$ |$$ | $$ $$/ $$ | $$$$$$ |$$ |$$ |$$ \_____ $$$$$$$$/ echo "$$ $$/ $$ $$/ $$ | $$$/ $$ |/ $$/ $$ |$$ |$$ |$$ | echo " $$$$$$/ $$$$$$/ $$/ $/ $$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$$$$$$/ echo "=================================================================================== echo "==> echo " Gcode generated at: %model%.gcode echo "==> echo "=================================================================================== :End ================================================ FILE: curvislice.sh ================================================ #!/bin/bash gurobi=0 volumic=0 nozzle=0.4 layer=0.3 filament=1.75 ironing=0 model= arg="none" for elem in $* do if [ $arg = "none" ] then arg=$elem else eval "$arg=$elem" arg="none" fi done if [ $arg = "none" ] then echo Error in arguments exit fi model=${arg%.*} echo Generate tetmesh "from $model.stl" ... ./toTetmesh.sh $model echo Done! echo Optimize... if [ $gurobi = "1" ] then ./bin/curvislice_grb $model.msh -l $layer else ./bin/curvislice_osqp $model.msh -l $layer fi echo Done! echo Prepare lua for IceSL ./luaGenerator.sh $model $volumic $nozzle $layer $filament $ironing if [ -e "~/.icesl/icesl-printers/fff/curvi" ] then echo "'curvi' printer profile already exist" else echo Create 'curvi' printer profile for IceSL cp -r "./resources/curvi" "~/icesl/icesl-printers/fff/curvi" fi ./tools/icesl/bin/icesl-slicer settings.lua --service ./bin/uncurve -l $layer --gcode $model clear echo ' ______ __ __ __ ' echo ' / \ / | / |/ | ' echo '/$$$$$$ | __ __ ______ __ __ $$/ _______ $$ |$$/ _______ ______ ' echo '$$ | $$/ / | / | / \ / \ / |/ | / |$$ |/ | / | / \ ' echo '$$ | $$ | $$ |/$$$$$$ |$$ \ /$$/ $$ |/$$$$$$$/ $$ |$$ |/$$$$$$$/ /$$$$$$ |' echo '$$ | __ $$ | $$ |$$ | $$/ $$ /$$/ $$ |$$ \ $$ |$$ |$$ | $$ $$ |' echo '$$ \__/ |$$ \__$$ |$$ | $$ $$/ $$ | $$$$$$ |$$ |$$ |$$ \_____ $$$$$$$$/ ' echo '$$ $$/ $$ $$/ $$ | $$$/ $$ |/ $$/ $$ |$$ |$$ |$$ |' echo ' $$$$$$/ $$$$$$/ $$/ $/ $$/ $$$$$$$/ $$/ $$/ $$$$$$$/ $$$$$$$/ ' echo '===================================================================================' echo '==>' echo " Gcode generated at: $model.gcode" echo '==>' echo '=================================================================================== ================================================ FILE: get_started_mingw64.sh ================================================ #!/bin/bash echo "--------------------------------------------------------------------" echo "This script installs all necessary packages and compiles" echo "Please refer to the script source code to see the list of packages" echo "--------------------------------------------------------------------" read -p "Please type 'y' to go ahead, any other key to exit: " -n 1 -r if [[ ! $REPLY =~ ^[Yy]$ ]] then echo echo "Exiting." exit fi pacman -S --noconfirm --needed git echo -e "\nInstalling compilation packages for building\n" pacman -S --noconfirm --needed wget ${MINGW_PACKAGE_PREFIX}-cmake ${MINGW_PACKAGE_PREFIX}-gcc ${MINGW_PACKAGE_PREFIX}-make ./compile_on_mingw64.sh ================================================ FILE: libs/tclap/AUTHORS ================================================ original author: Michael E. Smoot invaluable contributions: Daniel Aarno more contributions: Erik Zeek more contributions: Fabien Carmagnac (Tinbergen-AM) outstanding editing: Carol Smoot ================================================ FILE: libs/tclap/COPYING ================================================ Copyright (c) 2003 Michael E. Smoot Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: libs/tclap/ChangeLog ================================================ 2011-04-10 17:08 mes5k * include/tclap/Arg.h: patch that allows arg start strings to be pound defined to easily conform to different platforms 2011-04-09 11:58 mes5k * docs/Makefile.am: being slightly more precise about what we clean 2011-04-09 11:30 mes5k * include/tclap/: DocBookOutput.h, StdOutput.h, ZshCompletionOutput.h: fixed shadow variable name problem 2011-04-09 11:05 mes5k * include/tclap/CmdLine.h: fixed minor memory leak 2011-03-15 04:26 macbishop * configure.in, config/ac_cxx_warn_effective_cxx.m4: Check if compiler supports Weffec++ and if so use it (fixes compilation issue with e.g. SunStudio compiler) 2011-01-15 09:45 macbishop * include/tclap/ArgTraits.h: Updated documentation for ArgTraits to reference StringLike and ValueLike classes. 2011-01-15 09:32 macbishop * examples/test10.cpp: Added explicit cast to supress warning about deprecated conversion from string constant to char* 2011-01-02 17:18 mes5k * docs/Makefile.am: now using a slightly different variable for doc install to support out-of-tree builds 2011-01-02 16:37 mes5k * configure.in: bumped version number to 1.2.1 2011-01-02 16:30 mes5k * docs/style.css: tweaked style so it doesn't blink 2011-01-02 16:21 mes5k * tests/: test57.out, test57.sh, test76.out: tweaked tests to reflect fix for mutually exclusive switches 2011-01-02 16:20 mes5k * include/tclap/: SwitchArg.h, XorHandler.h: finally fixed bug relating to mutually exclusive combined switched 2011-01-02 15:12 mes5k * include/tclap/Arg.h: minor reformat 2011-01-02 15:10 mes5k * include/tclap/CmdLine.h: minor reformatting 2011-01-02 12:13 mes5k * examples/Makefile.am, examples/test20.cpp, tests/Makefile.am, tests/test74.out, tests/test74.sh, tests/test75.out, tests/test75.sh, tests/test76.out, tests/test76.sh, tests/test77.out, tests/test77.sh: added failing tests for XOR error message bug 2011-01-02 11:52 mes5k * include/tclap/StandardTraits.h: applied Tom Fogal's win64 patch for size_t 2011-01-02 11:38 mes5k * docs/Makefile.am: hopefully fixed out-of-tree doc installation 2011-01-02 10:50 mes5k * include/tclap/: Arg.h, ArgTraits.h, CmdLine.h, HelpVisitor.h, MultiArg.h, ValueArg.h, ValuesConstraint.h, VersionVisitor.h, XorHandler.h, ZshCompletionOutput.h: fixed all effective c++ warnings based on patch from Andrew Marlow 2010-12-06 22:41 mes5k * configure.in: added more compiler warnings 2009-10-24 20:49 mes5k * include/tclap/SwitchArg.h, include/tclap/ValueArg.h, tests/test22.out, tests/test24.out: make error message a bit more meaningful 2009-10-23 14:42 mes5k * include/tclap/StandardTraits.h: added a check for wchar_t to deal with a potential problem with MS compilers 2009-09-28 11:28 mes5k * docs/index.html: updated for 1.2.0 2009-09-26 14:41 mes5k * docs/Makefile.am: another update to support older automake 2009-09-26 14:23 mes5k * docs/Makefile.am: removed an errant space 2009-09-26 14:15 mes5k * docs/Makefile.am: added a definition for docdir, which doesnt exist for old versions of automake 2009-09-26 14:02 mes5k * docs/Makefile.am: corrected the doc install directory structure 2009-09-26 13:55 mes5k * NEWS: updated for 1.2.0 2009-09-26 13:53 mes5k * docs/: manual.html, manual.xml: updated for 1.2.0 including text on ArgTraits 2009-08-22 12:26 mes5k * Makefile.am, configure.in, tclap.pc.in, docs/Makefile.am, examples/Makefile.am: applying patches to make gnu compiler args conditional, to install docs, and to add pkgconfig support to the installation 2009-07-28 12:49 mes5k * configure.in, tests/Makefile.am, tests/test73.out, tests/test73.sh: added test 73 based on bug reported by user 2009-07-15 08:09 mes5k * include/tclap/UnlabeledValueArg.h: updated incorrect api docs again 2009-07-15 08:04 mes5k * include/tclap/UnlabeledValueArg.h: updated incorrect api doc 2009-01-09 16:10 mes5k * AUTHORS: added author 2009-01-09 16:05 mes5k * include/tclap/: Arg.h, CmdLine.h, CmdLineInterface.h, MultiArg.h, MultiSwitchArg.h, SwitchArg.h, ValueArg.h: added support for resetting a command line 2008-11-07 12:04 mes5k * docs/manual.html, docs/manual.xml, examples/Makefile.am, examples/test19.cpp, include/tclap/Arg.h, tests/Makefile.am, tests/test29.out, tests/test29.sh, tests/test71.out, tests/test71.sh, tests/test72.out, tests/test72.sh: added support for parsing hex and octal ints as well as small fix to support gcc 4.4 2008-09-10 11:29 mes5k * docs/manual.xml: updated note on xor 2008-09-10 11:21 mes5k * docs/manual.xml: added note on xor 2008-08-19 15:18 zeekec * examples/test18.cpp, include/tclap/CmdLine.h, tests/Makefile.am, tests/test70.out, tests/test70.sh: Rethrow ExitExceptions if we're not handling exceptions. 2008-08-19 14:52 zeekec * include/tclap/Arg.h: Silence some compiler warnings. The const on return-by-value is ignored. 2008-07-21 10:20 zeekec * include/tclap/CmdLine.h, examples/Makefile.am, examples/test18.cpp, tests/Makefile.am, tests/test69.out, tests/test69.sh: Allow internal handling of parse errors to be turned off. This allows exceptions for parse errors to be propagated to the caller. Exiting the program in parse is a bad idea generally, as we have no way of knowing what cleanup needs to be done in the main program. 2008-06-17 09:48 mes5k * include/tclap/StdOutput.h: bug in while loop 2008-05-23 15:15 mes5k * include/tclap/: CmdLine.h, SwitchArg.h: added length checks to strings that can otherwise break with Metroworks compilers 2008-05-21 14:21 macbishop * examples/: Makefile.am, test17-a.cpp, test17.cpp: Added test that tclap does not define any hard symbols (bug 1907017) 2008-05-13 12:04 mes5k * include/tclap/CmdLine.h: added a new include to support exit in environments where it isnt defined 2008-05-05 23:02 mes5k * examples/test7.cpp, include/tclap/Arg.h, tests/test46.out: tweaked tests to support dashes in arg names 2008-05-05 22:28 mes5k * include/tclap/Arg.h: allowed dash char in arg names 2008-01-18 15:05 zeekec * include/tclap/Makefile.am: Added Traits files to the list of files to be installed. 2007-10-09 11:18 macbishop * examples/test14.cpp, examples/test15.cpp, examples/test16.cpp, include/tclap/Arg.h, include/tclap/ArgTraits.h, include/tclap/StandardTraits.h, configure.in, config/ac_cxx_have_long_long.m4, examples/Makefile.am: Refactoring of the arg-traits functionality. The purpose is to make it easier to make you own classes, and types defined in the standard library work well with tclap. I'll try to write up some documenation of how to achieve this as-well. 2007-10-01 23:33 mes5k * examples/test13.cpp: added attribution 2007-10-01 23:30 mes5k * examples/test13.cpp: fixed a warning message 2007-10-01 23:27 mes5k * examples/Makefile.am, examples/test13.cpp, include/tclap/SwitchArg.h, tests/Makefile.am, tests/test68.out, tests/test68.sh: a bug fix for parsing vectors of strings and making sure that combined switches dont get confused 2007-09-27 13:49 mes5k * include/tclap/OptionalUnlabeledTracker.h: added inline 2007-09-12 19:09 mes5k * include/tclap/Arg.h, tests/test42.out, tests/test54.out: fixed the delimiter in Arg::longID and Arg::shortID 2007-09-01 01:17 macbishop * examples/Makefile.am, include/tclap/Arg.h, include/tclap/DocBookOutput.h, include/tclap/ZshCompletionOutput.h: Suppress some warnings, compile with -Wextra by default 2007-06-14 14:02 macbishop * include/tclap/Arg.h, include/tclap/MultiArg.h, include/tclap/ValueArg.h, tests/runtests.sh, tests/test63.out, tests/test63.sh, tests/test64.out, tests/test64.sh, tests/test65.out, tests/test65.sh, tests/test66.out, tests/test66.sh, tests/test67.out, tests/test67.sh, tests/testCheck.sh, examples/Makefile.am, examples/test11.cpp, examples/test12.cpp: Use ArgTraits instead of ValueExtractor specialization Bug 1711487 2007-05-02 13:11 macbishop * examples/Makefile.am, examples/test10.cpp, include/tclap/CmdLine.h, include/tclap/CmdLineInterface.h: Run CmdLine::parse with argv as pointer to const pointer to const char 2007-04-20 22:28 mes5k * include/tclap/Arg.h, tests/test18.out: changed the blankChar to the bell character instead of * 2007-03-04 11:28 mes5k * examples/test4.cpp, include/tclap/DocBookOutput.h, include/tclap/Makefile.am, include/tclap/ZshCompletionOutput.h: added patches for ZSH and DocBook output 2007-03-04 11:08 mes5k * include/tclap/: CmdLine.h, CmdLineInterface.h: added a new parse method that accepts a vector 2007-02-17 06:59 macbishop * include/tclap/: MultiArg.h, MultiSwitchArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h: Supressed some warnings 2007-02-17 06:59 macbishop * include/tclap/CmdLine.h: Catch ExitException and exit. This allows all resources used during parsing to be released, bug 1662188. 2007-02-17 06:57 macbishop * include/tclap/: DocBookOutput.h, HelpVisitor.h, StdOutput.h, VersionVisitor.h: raise ExitException instead of calling exit 2007-02-17 06:54 macbishop * include/tclap/ArgException.h: Added exit-exception class 2007-02-17 06:52 macbishop * tests/testCheck.sh: Exit with exit status 1 if a test fails (required by runtests.sh) 2007-02-17 06:52 macbishop * tests/runtests.sh: Run the correct tests (not 0) 2007-02-17 06:51 macbishop * examples/: test4.cpp, test7.cpp: Supressed warnings 2007-02-07 18:12 mes5k * include/tclap/StdOutput.h: minor change to support a bug in VisualC++ 2005 2006-11-26 10:42 mes5k * docs/: README, manual.html, manual.xml: updated docs to reflect that Output must handle the exit rather than the CmdLine object 2006-11-26 10:32 mes5k * include/tclap/: CmdLine.h, DocBookOutput.h, StdOutput.h: moved exit from CmdLine to StdOutput to provide users more control over when/how the exit happens 2006-11-26 10:29 mes5k * examples/test4.cpp: added exit() to failure method 2006-11-26 10:13 mes5k * docs/: manual.html, manual.xml: fixed typo in SwitchArg constructors 2006-11-04 14:05 mes5k * include/tclap/CmdLine.h, tests/Makefile.am, tests/test10.out, tests/test17.out, tests/test4.out, tests/test51.out, tests/test62.out, tests/test62.sh: printing more useful message when missing required args and catching ArgException reference 2006-10-06 09:49 mes5k * include/tclap/SwitchArg.h, tests/Makefile.am, tests/test61.out, tests/test61.sh: made a fix for a bug where - chars were within unlabeled value args 2006-08-21 23:13 mes5k * include/tclap/StdOutput.h: minor tweak to a min function signature 2006-08-18 20:05 mes5k * docs/index.html: updated for 1.1.0 2006-08-18 20:04 mes5k * AUTHORS: new author 2006-05-14 17:55 mes5k * config/Makefile.am: so that m4 macros will be included in release files to ease incorporation of tclap in other projects 2006-05-14 17:36 mes5k * include/tclap/CmdLine.h: removed a deprecated constructor 2006-05-14 17:35 mes5k * docs/: manual.xml, manual.html: manual update 2006-05-14 13:11 mes5k * Makefile.am, configure.in: added m4 macros to help others distributing the software and updated the version number 2006-05-14 12:52 mes5k * config/bb_enable_doxygen.m4: for some reason, the AS_HELP_STRING function was messing up autoconf 2.57 -- maybe that's just an old version? We can change it back as necessary 2006-05-14 12:51 mes5k * examples/test8.cpp, include/tclap/SwitchArg.h: SwitchArg interface change 2006-04-18 03:59 macbishop * docs/: manual.html, manual.xml: Updated the example 2006-04-05 23:44 mes5k * include/tclap/ArgException.h: patch for a mem leak in ArgException 2006-03-18 11:16 mes5k * include/tclap/: CmdLineOutput.h, Visitor.h: added virtual destructors 2006-02-21 18:15 zeekec * examples/: test1.cpp, test2.cpp, test3.cpp, test4.cpp, test5.cpp, test6.cpp, test7.cpp, test8.cpp, test9.cpp: Use local header files first instead of installed headers. 2006-02-21 18:12 zeekec * Makefile.am: Added ACLOCAL_AMFLAGS for autoreconf. 2006-02-21 18:10 zeekec * config/: ac_cxx_have_sstream.m4, ac_cxx_have_strstream.m4: Moved the requires, header check, and language save and restore outside of the cache check. 2006-02-21 04:00 zeekec * config/: stamp-h.in, stamp-h1: Removed timestamp files (generated by configure). 2006-02-21 03:05 zeekec * include/tclap/Constraint.h: Added virtual destructor to silence warnings. 2006-02-21 03:01 zeekec * ChangeLog: Generated with cvs2cl. 2005-09-10 16:25 mes5k * config/stamp-h1, examples/test2.cpp, examples/test3.cpp, examples/test5.cpp, examples/test8.cpp, include/tclap/Arg.h, include/tclap/CmdLine.h, include/tclap/MultiArg.h, include/tclap/StdOutput.h, include/tclap/UnlabeledMultiArg.h, include/tclap/UnlabeledValueArg.h, include/tclap/ValueArg.h, include/tclap/XorHandler.h: added gcc warning patch 2005-07-12 20:36 zeekec * examples/Makefile.am: Set INCLUDES to top_srcdir for out of source builds. 2005-07-12 20:33 zeekec * include/tclap/: UnlabeledMultiArg.h, UnlabeledValueArg.h: Add using toString statements (for gcc >= 3.4). 2005-07-12 20:31 zeekec * config/bb_enable_doxygen.m4: Properly quote BB_ENABLE_DOXYGEN. 2005-06-29 15:04 mes5k * include/tclap/Arg.h: merged some new changes 2005-06-08 08:28 mes5k * docs/index.html: fixed spelling mistake 2005-06-02 19:35 mes5k * include/tclap/: Makefile.am, OptionalUnlabeledTracker.h, UnlabeledMultiArg.h, UnlabeledValueArg.h: fix to handle optional unlabeled args 2005-06-02 19:33 mes5k * examples/: test2.cpp, test3.cpp, test7.cpp, test8.cpp, test9.cpp: Unlabeled changes 2005-02-03 15:04 mes5k * include/tclap/: Arg.h, DocBookOutput.h, MultiArg.h: updated docbook output 2005-02-03 08:08 mes5k * include/tclap/: ValuesConstraint.h, XorHandler.h: add std:: prefix to some finds 2005-02-01 13:35 zeekec * include/tclap/CmdLine.h: Made deleteOnExit's protected to facilitate derivation. 2005-02-01 13:30 zeekec * config/config.h.in: Removed autotools generated file. 2005-01-28 13:26 zeekec * configure.in, docs/Doxyfile.in, tests/Makefile.am, tests/test1.sh, tests/test10.sh, tests/test11.sh, tests/test12.sh, tests/test13.sh, tests/test14.sh, tests/test15.sh, tests/test16.sh, tests/test17.sh, tests/test18.sh, tests/test19.sh, tests/test2.sh, tests/test20.sh, tests/test21.sh, tests/test22.sh, tests/test23.sh, tests/test24.sh, tests/test25.sh, tests/test26.sh, tests/test27.sh, tests/test28.sh, tests/test29.sh, tests/test3.sh, tests/test30.sh, tests/test31.sh, tests/test32.sh, tests/test33.sh, tests/test34.sh, tests/test35.sh, tests/test36.sh, tests/test37.sh, tests/test38.sh, tests/test39.sh, tests/test4.sh, tests/test40.sh, tests/test41.sh, tests/test42.sh, tests/test43.sh, tests/test44.sh, tests/test45.sh, tests/test46.sh, tests/test47.sh, tests/test48.sh, tests/test49.sh, tests/test5.sh, tests/test50.sh, tests/test51.sh, tests/test52.sh, tests/test53.sh, tests/test54.sh, tests/test55.sh, tests/test56.sh, tests/test57.sh, tests/test58.sh, tests/test59.sh, tests/test6.sh, tests/test60.sh, tests/test7.sh, tests/test8.sh, tests/test9.sh: Made changes to directory references to allow out of source builds. 2005-01-26 10:25 mes5k * aclocal.m4: doh 2005-01-23 19:18 mes5k * include/tclap/CmdLine.h: removed -v from version switch 2005-01-23 19:14 mes5k * include/tclap/Arg.h: removed value required 2005-01-23 19:03 mes5k * examples/: test2.cpp, test3.cpp, test6.cpp, test8.cpp, test9.cpp: UnlabeledValueArg change 2005-01-23 19:02 mes5k * tests/: test10.out, test11.out, test12.out, test15.out, test16.out, test17.out, test22.out, test23.out, test24.out, test26.out, test27.out, test28.out, test29.out, test30.out, test31.out, test32.out, test35.out, test36.out, test38.out, test39.out, test4.out, test40.out, test41.out, test42.out, test43.out, test44.out, test45.out, test46.out, test49.out, test50.out, test51.out, test52.out, test53.out, test54.out, test57.out, test59.out, test60.out, test7.out: new output for default version and value required 2005-01-23 19:01 mes5k * tests/: test59.sh, test8.sh: new style version and required UnlabeledValueArgs 2005-01-23 18:59 mes5k * tests/testCheck.sh: a script to compare test output 2005-01-23 17:54 mes5k * include/tclap/UnlabeledValueArg.h: now optionally required 2005-01-23 16:33 mes5k * tests/: test58.out, test59.out, test58.sh, test59.sh, test60.out, test60.sh, Makefile.am: tests for MultiSwitchArg 2005-01-23 16:27 mes5k * include/tclap/Makefile.am, examples/Makefile.am, examples/test9.cpp: MultiSwitchArg 2005-01-23 16:26 mes5k * include/tclap/: CmdLine.h, CmdLineInterface.h, StdOutput.h: added a bool to the constructor that allows automatic -h and -v to be turned off 2005-01-23 14:57 mes5k * docs/: manual.html, manual.xml: added MultiSwitchArg docs 2005-01-23 14:33 mes5k * include/tclap/MultiSwitchArg.h: fixed typo 2005-01-23 14:29 mes5k * include/tclap/SwitchArg.h: Fixed minor bug involving combined switch error messages: now they're consistent. 2005-01-23 14:28 mes5k * include/tclap/MultiSwitchArg.h: initial checkin 2005-01-22 20:41 mes5k * include/tclap/UnlabeledMultiArg.h: added alreadySet 2005-01-20 20:13 mes5k * tests/Makefile.am: xor test 2005-01-20 20:04 mes5k * examples/test5.cpp: change for xor bug 2005-01-20 20:04 mes5k * tests/: test20.out, runtests.sh, test20.sh, test21.out, test21.sh, test22.out, test23.out, test24.out, test25.out, test25.sh, test33.out, test33.sh, test44.out, test57.out, test57.sh: changes for xor bug 2005-01-20 20:03 mes5k * include/tclap/: Arg.h, MultiArg.h, UnlabeledMultiArg.h, XorHandler.h: fixed xor bug 2005-01-17 12:48 macbishop * include/tclap/Arg.h: Removed check on description in Arg::operator== since multiple args should be able to have the same description. 2005-01-06 20:41 mes5k * NEWS: updated for constraints 2005-01-06 20:37 mes5k * docs/: manual.html, manual.xml: updated for constraints 2005-01-06 20:05 mes5k * examples/test7.cpp: changed for constraint 2005-01-06 20:00 mes5k * include/tclap/: MultiArg.h, ValueArg.h: fixed exceptions and typeDesc for constraints 2005-01-06 19:59 mes5k * tests/: test35.out, test36.out, test38.out, test39.out: changed for constraints 2005-01-06 19:07 mes5k * examples/test6.cpp: changed to constraint 2005-01-06 19:06 mes5k * include/tclap/Makefile.am: added constraints 2005-01-06 19:05 mes5k * include/tclap/: Constraint.h, ValuesConstraint.h: initial checkin 2005-01-06 19:05 mes5k * include/tclap/StdOutput.h: comment change 2005-01-06 19:01 mes5k * include/tclap/CmdLine.h: added Constraint includes 2005-01-06 18:55 mes5k * include/tclap/: MultiArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h: Changed allowedList to Constraint 2005-01-05 16:08 mes5k * configure.in: next vers 2005-01-05 12:13 mes5k * NEWS: update 2005-01-05 10:51 mes5k * docs/: manual.html, manual.xml: fixed output override bug 2005-01-05 10:45 mes5k * tests/: test18.out, test43.out: change for output override bug 2005-01-05 10:28 mes5k * examples/test4.cpp: fixed output override bug 2005-01-05 10:22 mes5k * include/tclap/: CmdLine.h, HelpVisitor.h, VersionVisitor.h: fixed output bug 2005-01-04 14:01 mes5k * configure.in: 1.0.4 2005-01-04 13:16 mes5k * examples/test7.cpp: changed for long prog names bug 2005-01-04 13:15 mes5k * tests/: test38.out, test39.out, test46.out: changed test7 for long prog names 2005-01-04 12:31 mes5k * NEWS: updates for 1.0.3a 2005-01-04 12:21 mes5k * docs/manual.html, docs/manual.xml, include/tclap/CmdLine.h: fixed output memory leak 2004-12-08 21:10 mes5k * include/tclap/StdOutput.h: hacky fix to long prog name bug 2004-12-07 19:57 mes5k * configure.in: 1.0.3a 2004-12-07 19:53 mes5k * tests/: Makefile.am, test15.out, test16.out, test17.out, test31.out, test32.out, test13.sh, test14.sh, test15.sh, test16.sh, test17.sh, test42.out, test55.out, test55.sh, test56.out, test56.sh: updated for - arg bug 2004-12-07 19:51 mes5k * examples/test3.cpp: tweaked to support tests for '-' arg bug 2004-12-07 18:16 mes5k * include/tclap/Arg.h: fixed a bug involving blank _flags and - as an UnlabeledValueArg 2004-12-03 12:19 mes5k * docs/style.css: minor tweak for h1 2004-12-03 12:10 mes5k * NEWS: update 2004-12-03 11:39 mes5k * include/tclap/CmdLine.h: removed ostream include 2004-11-30 19:11 mes5k * include/tclap/: Arg.h, CmdLine.h, CmdLineOutput.h, StdOutput.h: cleaned up iterator names 2004-11-30 19:10 mes5k * include/tclap/DocBookOutput.h: removed ostream 2004-11-30 18:35 mes5k * configure.in, docs/Doxyfile.in: added dot check 2004-11-24 19:58 mes5k * configure.in: 1.0.3 2004-11-24 19:57 mes5k * include/tclap/: UnlabeledMultiArg.h, UnlabeledValueArg.h: removed two stage lookup ifdefs 2004-11-24 19:56 mes5k * docs/index.html: updated 2004-11-24 19:45 mes5k * docs/: manual.html, manual.xml: updates for using stuff and new output 2004-11-05 21:05 mes5k * include/tclap/: DocBookOutput.h, Makefile.am: adding docbook stuff 2004-11-04 21:07 mes5k * examples/test4.cpp: reflects new output handling 2004-11-04 21:07 mes5k * include/tclap/: Arg.h, CmdLine.h, CmdLineInterface.h, CmdLineOutput.h, HelpVisitor.h, Makefile.am, StdOutput.h, VersionVisitor.h, XorHandler.h: changed output around 2004-11-04 21:06 mes5k * include/tclap/PrintSensibly.h: subsumed by StdOutput 2004-10-31 14:13 mes5k * docs/manual.html: tweak 2004-10-30 15:58 mes5k * NEWS, README: updates 2004-10-30 15:51 mes5k * docs/Makefile.am: added manual.xml 2004-10-30 15:47 mes5k * docs/: manual.html, manual.xml, style.css: minor tweaks 2004-10-30 15:34 mes5k * configure.in: 1.0.2 2004-10-30 15:30 mes5k * docs/README: init 2004-10-30 15:30 mes5k * docs/style.css: new style 2004-10-30 15:30 mes5k * docs/: manual.html, manual.xml: manual.html is now generated from manual.xml 2004-10-30 15:26 mes5k * include/tclap/: MultiArg.h, ValueArg.h: yet another fix for HAVE_SSTREAM stuff 2004-10-30 08:42 mes5k * NEWS: 1.0.1 2004-10-30 08:03 mes5k * configure.in: new release 2004-10-28 09:41 mes5k * include/tclap/: ValueArg.h, MultiArg.h: fixed config.h problems 2004-10-27 19:44 mes5k * docs/manual.xml: manual as docbook 2004-10-22 08:56 mes5k * docs/style.css: added visited color to links 2004-10-22 07:38 mes5k * docs/index.html: fixed mailto 2004-10-21 18:58 mes5k * docs/: manual.html: minor tweaks 2004-10-21 18:13 mes5k * docs/manual.html: updated for new test1 2004-10-21 18:02 mes5k * include/tclap/CmdLine.h: catch by ref 2004-10-21 18:01 mes5k * examples/: test1.cpp, test2.cpp, test3.cpp, test4.cpp, test5.cpp, test6.cpp, test7.cpp, test8.cpp: changed test1 and now catching exceptions by ref 2004-10-21 17:38 mes5k * tests/: test1.out, test1.sh, test2.out, test3.out, test3.sh, test4.out, test40.out: changes for new test1 2004-10-21 15:50 mes5k * examples/test1.cpp: fixed includes 2004-10-21 10:03 mes5k * docs/index.html: changed link 2004-10-21 09:02 mes5k * include/tclap/: ValueArg.h, MultiArg.h: changed enum names because of alpha conflicts 2004-10-20 20:04 mes5k * include/tclap/: CmdLine.h, CmdLineInterface.h, MultiArg.h, PrintSensibly.h, SwitchArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h, XorHandler.h: cleaned up some includes and added ifdefs for sstream 2004-10-20 19:00 mes5k * examples/test5.cpp: fixed a bizarre bug 2004-10-20 18:59 mes5k * tests/: test20.out, test21.out, test25.out, test33.out: fixed a test5 bug 2004-10-20 16:17 mes5k * Makefile.am: added msc 2004-10-20 16:06 mes5k * configure.in: added msc stuff 2004-10-20 16:05 mes5k * msc/: examples/Makefile.am, Makefile.am: init 2004-10-20 16:00 mes5k * NEWS: update 2004-10-20 15:58 mes5k * msc/README: init 2004-10-20 15:47 mes5k * msc/: tclap-beta.ncb, tclap-beta.sln, tclap-beta.suo, tclap-beta.vcproj, examples/test1.vcproj, examples/test2.vcproj, examples/test3.vcproj, examples/test4.vcproj, examples/test5.vcproj, examples/test6.vcproj, examples/test7.vcproj, examples/test8.vcproj: init 2004-10-19 11:18 mes5k * docs/Makefile.am: added stylesheet 2004-10-19 10:51 mes5k * AUTHORS: more 2004-10-19 10:39 mes5k * NEWS, AUTHORS: added 1.0 notes 2004-10-14 13:04 mes5k * examples/test4.cpp: shows how to alter output 2004-10-14 13:03 mes5k * tests/test18.out: updated output 2004-10-14 12:03 mes5k * include/tclap/CmdLineInterface.h: added failure to the interface 2004-10-14 11:07 mes5k * include/tclap/ArgException.h: doh. now what() is proper 2004-10-14 10:44 mes5k * include/tclap/CmdLine.h: made destructor virtual 2004-10-14 10:20 mes5k * include/tclap/CmdLine.h: moved all output handling into separate methods 2004-10-14 10:19 mes5k * include/tclap/Arg.h: made processArg pure virtual 2004-10-14 10:19 mes5k * include/tclap/ArgException.h: fixed documentation omission 2004-10-12 14:09 mes5k * docs/style.css: tweak 2004-10-07 11:22 mes5k * docs/style.css: color change 2004-10-01 10:54 mes5k * include/tclap/ArgException.h: added type description 2004-09-30 18:16 mes5k * docs/: index.html, manual.html, style.css: added CSS style 2004-09-30 09:17 mes5k * docs/manual.html: more updates 2004-09-29 08:24 mes5k * docs/: index.html, manual.html: proofing updates 2004-09-27 14:37 mes5k * docs/: index.html, manual.html: xhtml and tidied 2004-09-27 14:36 mes5k * docs/Doxyfile.in: added dot handling 2004-09-27 14:30 mes5k * include/tclap/: Arg.h, ArgException.h, CmdLine.h, MultiArg.h, SwitchArg.h, ValueArg.h: added new Exception classes 2004-09-27 12:53 mes5k * include/tclap/ArgException.h: minor tweaks 2004-09-26 19:32 mes5k * docs/manual.html: updates yet again 2004-09-26 19:00 mes5k * docs/manual.html: updates 2004-09-26 18:50 mes5k * docs/manual.html: substantial updates 2004-09-26 16:54 mes5k * include/tclap/: Arg.h, CmdLine.h, CmdLineInterface.h, MultiArg.h, PrintSensibly.h, ValueArg.h: minor formatting 2004-09-26 15:50 mes5k * docs/manual.html: updates 2004-09-26 15:17 mes5k * tests/runtests.sh: minor fix so that we run all tests 2004-09-26 11:51 macbishop * docs/Doxyfile.in: Removed src subdir 2004-09-26 11:49 macbishop * examples/Makefile.am: Removed libtclap.a deps 2004-09-26 11:46 macbishop * configure.in: Removed creation of src/Makefile 2004-09-26 11:34 macbishop * Makefile.am: Removed src subdir 2004-09-26 11:31 macbishop * src/: Arg.cpp, CmdLine.cpp, Makefile.am, PrintSensibly.cpp, SwitchArg.cpp, XorHandler.cpp: Implementation now in header files 2004-09-26 11:27 macbishop * include/tclap/: Arg.h, ArgException.h, CmdLine.h, HelpVisitor.h, Makefile.am, MultiArg.h, PrintSensibly.h, SwitchArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h, VersionVisitor.h, XorHandler.h, CmdLineInterface.h, CommandLine.h: Moving the implementation of tclap to the header files presented me with two major problems. 1) There where static functions and variables that could cause link errors if tclap where used in different files (e.g. file1.cc and file2.cc included tclap then compiling both files would give hard symbols for some variables which would produce multiple definition when linking) 2) The dependencies of tclap was a bit strange (CmdLine depends on Args and Args depends on CmdLine for instance) The first problem I solved by removing all static variables putting them in static member functions (which are weak-symbols). So for instance every where there previously was something like x = _delimiter there now is x = delimiter() or in case of write acces delimiterRef() = x instead of _delimiter = x (I had to append the Ref because there where already functions with the same name as the variables). To solve the problem with static functions I simply inlined them. This causes the compiler to produce a weak symbol or inline if appropriate. We can put the functions inside the class declaration later to make the code look better. This worked fine in all but two cases. In the ValueArg and MultiArg classes I had to do a "hack" to work around the specialization template for extractValue. The code for this is very simple but it might look strange an stupid at first but it is only to resolve the specialisation to a weak symbol. What I did was I put the implementations of extractValue in a helper class and I could then create a specialized class instead of function and everything worked out. I think now in retrospect there might be better solutions to this but I'll think a bit more on it (maybe some type of inlining on the specialized version would suffice but I'm not sure). To handle the dependencies I had to do some rewriting. The first step was to introduce a new class CmdLineInterface that is a purely abstract base of CmdLine that specifies the functions needed by Arg and friends. Thus Arg classes now takes an CmdLineInterface object as input instead (however only CmdLine can ever be instantiated of-course). With this extra class cleaning up the dependencies was quite simple, I've attached a dependency graph to the mail (depgraph.png). I also cleaned up the #includes so now only what actually needs inclusion is included. A nice side effect of this is that the impl. of CmdLine is now put back into CmdLine.h (where I guess you wanted it) which (recursivly) includes everything else needed. Just to make things clear for myself regarding the class dependencies I made a class TCLAP::Exception that inherits from std::exception and is a base of ArgException (Exception does nothing currently). If we don't want the Exception class it can be removed, however I think it could be a nice logic to have a base Exception class that every exception inherits from, but we can discuss that when we decide how to handle exceptions. 2004-09-26 08:07 macbishop * tests/runtests.sh: Now return 0 if all tests fail and 1 if any test fail 2004-09-26 07:58 macbishop * tests/runtests.sh: Runs all tests and sumarizes the result 2004-09-20 17:09 mes5k * include/tclap/CommandLine.h: added some comments 2004-09-20 17:08 mes5k * src/CmdLine.cpp: formatting only 2004-09-20 10:05 macbishop * include/tclap/CommandLine.h: Recommit because something is strange. The changes are that memory allocated in _construct is deallocated when the CmdLine obj is destroyed 2004-09-19 11:32 macbishop * src/CmdLine.cpp: Memory allocated in _constructor is now deleted when the object is destroyed 2004-09-18 09:54 mes5k * include/tclap/: Arg.h, ArgException.h, CmdLine.h, CommandLine.h, HelpVisitor.h, IgnoreRestVisitor.h, MultiArg.h, PrintSensibly.h, SwitchArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h, VersionVisitor.h, Visitor.h, XorHandler.h: changed ifndef labels 2004-09-18 07:53 macbishop * include/tclap/Arg.h: Had to make ~Arg() public because it won't be possible to delete Arg*s if it is not, and we want that (I think). 2004-09-15 21:24 mes5k * configure.in: version 1.0.0 2004-09-15 20:54 mes5k * include/tclap/Arg.h, include/tclap/ArgException.h, include/tclap/HelpVisitor.h, include/tclap/IgnoreRestVisitor.h, include/tclap/MultiArg.h, include/tclap/SwitchArg.h, include/tclap/UnlabeledMultiArg.h, include/tclap/ValueArg.h, include/tclap/VersionVisitor.h, include/tclap/Visitor.h, src/Arg.cpp, src/SwitchArg.cpp: cleaned up a bunch of things 2004-09-11 19:35 mes5k * tests/: Makefile.am, test47.out, test47.sh, test48.out, test48.sh, test49.out, test49.sh, test50.out, test50.sh, test51.out, test51.sh, test52.out, test52.sh, test53.out, test53.sh, test54.out, test54.sh: added tests for CmdLine arg 2004-09-11 19:33 mes5k * examples/: Makefile.am, test8.cpp: added new test for CmdLine arg 2004-09-11 19:32 mes5k * src/Arg.cpp, src/SwitchArg.cpp, include/tclap/Arg.h, include/tclap/MultiArg.h, include/tclap/SwitchArg.h, include/tclap/UnlabeledMultiArg.h, include/tclap/UnlabeledValueArg.h, include/tclap/ValueArg.h: got CmdLine arg working 2004-09-09 19:08 mes5k * configure: shouldn't be in cvs 2004-09-09 12:56 macbishop * src/: Arg.cpp, SwitchArg.cpp: Added support for automatic addition to a CmdLine parser 2004-09-09 12:55 macbishop * include/tclap/: Arg.h, MultiArg.h, SwitchArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h: Support for automatic addition to a CmdLine parser 2004-09-08 20:09 mes5k * src/CmdLine.cpp: fixed a warning in MSVC++ 2004-09-07 16:11 mes5k * include/tclap/Makefile.in, docs/Makefile.in, examples/Makefile.in, tests/Makefile.in: not needed 2004-09-07 16:08 mes5k * Makefile.in, src/Makefile.in, include/Makefile.in: not needed 2004-09-07 15:14 mes5k * src/CmdLine.cpp: now throws exception on matching names/flags/desc 2004-09-07 15:12 mes5k * examples/test4.cpp, examples/test7.cpp, tests/test38.out, tests/test39.out, tests/test43.out, tests/test46.out: fixed to handle new exception on matching names/flags/desc 2004-09-07 13:25 mes5k * docs/Doxyfile.in: updated Doxyfile for newer doxygen 2004-09-07 11:27 mes5k * examples/: test1.cpp, test2.cpp, test3.cpp, test4.cpp, test5.cpp, test6.cpp: changed namespace std handling 2004-09-07 11:25 mes5k * examples/test7.cpp: added more args to better test output printing 2004-09-07 11:24 mes5k * src/Arg.cpp, src/CmdLine.cpp, src/PrintSensibly.cpp, src/SwitchArg.cpp, src/XorHandler.cpp, include/tclap/Arg.h, include/tclap/ArgException.h, include/tclap/CommandLine.h, include/tclap/MultiArg.h, include/tclap/PrintSensibly.h, include/tclap/SwitchArg.h, include/tclap/UnlabeledMultiArg.h, include/tclap/UnlabeledValueArg.h, include/tclap/ValueArg.h, include/tclap/XorHandler.h: changed namespace std handling 2004-09-07 11:24 mes5k * tests/: test15.out, test16.out, test17.out, test22.out, test23.out, test24.out, test31.out, test32.out, test38.out, test39.out, test42.out, test44.out, test46.out: fixed test output for new formatting 2004-09-04 14:09 macbishop * include/tclap/: UnlabeledMultiArg.h, UnlabeledValueArg.h: Compilation was broken due to undef. symbols in compilers with 2 stage name-lookup (such as gcc >= 3.4). The fix for this is to tell the compiler what symbols to use withlines like: using MultiArg::_name; This is now done and everything compiles fine. Since I'm not sure about the support for things like using MultiArg::_name; on all compilers it is ifdef:ed away by default. To get 2 stage name-lookup to work you have to add -DTWO_STAGE_NAME_LOOKUP to your CXXFLAGS before running configure. 2004-08-18 12:34 mes5k * src/PrintSensibly.cpp: smartened printing even further 2004-08-10 20:35 mes5k * src/PrintSensibly.cpp: fixed int messiness 2004-08-10 20:32 mes5k * autotools.sh: made path explicit 2004-08-10 20:05 mes5k * include/tclap/: MultiArg.h, ValueArg.h: changed allowed separator 2004-08-10 19:53 mes5k * tests/: Makefile.am, test10.out, test11.out, test12.out, test15.out, test16.out, test17.out, test18.out, test22.out, test23.out, test24.out, test26.out, test27.out, test28.out, test29.out, test30.out, test31.out, test32.out, test35.out, test36.out, test38.out, test39.out, test4.out, test40.out, test40.sh, test41.out, test41.sh, test42.out, test42.sh, test43.out, test43.sh, test44.out, test44.sh, test45.out, test45.sh, test46.out, test46.sh, test7.out, test7.sh: changed error output and added usage stuff 2004-08-10 19:52 mes5k * NEWS, README: updated 2004-08-10 19:47 mes5k * configure.in: changed to 0.9.9 2004-08-10 19:46 mes5k * examples/test7.cpp: tweaked for usage 2004-08-10 19:45 mes5k * include/tclap/: CmdLine.h, CommandLine.h, Makefile.am, PrintSensibly.h, XorHandler.h: added usage stuff 2004-08-10 19:43 mes5k * src/: CmdLine.cpp, Makefile.am, PrintSensibly.cpp, XorHandler.cpp: tweaked usage 2004-07-05 19:02 mes5k * docs/manual.html: updated for allowed 2004-07-03 20:01 mes5k * tests/: test34.out, test34.sh, test35.out, test35.sh, test36.out, test36.sh, test37.out, test37.sh, test38.out, test38.sh, test39.out, test39.sh, Makefile.am: allow tests 2004-07-03 19:56 mes5k * include/tclap/ValueArg.h: doh 2004-07-03 19:34 mes5k * NEWS: allow 2004-07-03 19:31 mes5k * include/tclap/Arg.h: made isReq virtual 2004-07-03 19:30 mes5k * include/tclap/: MultiArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h: added allow 2004-07-03 19:29 mes5k * examples/: Makefile.am, test6.cpp, test7.cpp: added tests for allowed 2004-07-03 19:28 mes5k * docs/: index.html, manual.html: minor typos 2004-04-26 08:18 mes5k * Makefile.am, autotools.sh, examples/Makefile.am, src/Makefile.am: fixed for autotools for mandrake 2004-02-13 20:09 mes5k * configure.in: 0.9.8a 2004-02-13 15:23 mes5k * tests/: test22.out, test23.out, test24.out: output updates 2004-02-13 15:21 mes5k * include/tclap/: Arg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h: now the Arg adds itself to the CmdLine arglist 2004-02-13 15:20 mes5k * src/: Arg.cpp, CmdLine.cpp: reworked how we add args to list 2004-02-10 08:52 mes5k * NEWS: update 2004-02-09 21:04 mes5k * examples/test5.cpp: change 2004-02-09 21:03 mes5k * src/SwitchArg.cpp: allowing blank flags 2004-02-09 20:54 mes5k * configure.in: 0.9.8 2004-02-09 20:52 mes5k * tests/: Makefile.am, test20.out, test21.out, test22.out, test23.out, test24.out, test25.out, test33.out, test33.sh: updates 2004-02-09 20:39 mes5k * docs/manual.html: blank args 2004-02-09 20:16 mes5k * tests/: test15.out, test16.out, test17.out, test20.out, test20.sh, test21.out, test21.sh, test22.out, test23.out, test24.out, test25.out, test25.sh, test31.out, test32.out: updates 2004-02-09 20:05 mes5k * examples/: test5.cpp, test3.cpp: minor fixes and new args 2004-02-09 19:56 mes5k * include/tclap/Arg.h: added new var 2004-02-09 19:54 mes5k * src/: Arg.cpp, CmdLine.cpp, SwitchArg.cpp: allowing blank flags 2004-02-07 15:37 mes5k * src/XorHandler.cpp: fix for the output 2004-02-06 17:41 mes5k * NEWS: added info 2004-02-06 17:24 mes5k * tests/: test12.out, test15.out, test16.out, test17.out: fixed test3 stuff 2004-02-06 17:20 mes5k * tests/: test26.out, test26.sh, test27.out, test27.sh, test28.out, test28.sh, test29.out, test29.sh, test30.out, test30.sh, test31.out, test31.sh, test32.out, test32.sh, Makefile.am: added tests for reading extra incorrect values from arg 2004-02-06 17:18 mes5k * examples/test3.cpp: add multi float 2004-02-06 17:18 mes5k * include/tclap/: MultiArg.h, ValueArg.h: fixed error reading incorrect extra values in an arg 2004-02-04 18:56 mes5k * include/tclap/XorHandler.h: added include 2004-02-03 20:21 mes5k * include/tclap/XorHandler.h: added doxyen 2004-02-03 20:00 mes5k * docs/manual.html: xor stuff 2004-02-03 19:56 mes5k * examples/test5.cpp: prettified 2004-02-03 19:27 mes5k * examples/: Makefile.am, test5.cpp: xor stuff 2004-02-03 19:24 mes5k * configure.in: 0.9.7 2004-02-03 19:22 mes5k * src/: Arg.cpp, CmdLine.cpp, Makefile.am, XorHandler.cpp: added xor 2004-02-03 19:20 mes5k * include/tclap/: Arg.h, CmdLine.h, CommandLine.h, UnlabeledValueArg.h, XorHandler.h, Makefile.am: xor stuff 2004-02-03 19:14 mes5k * tests/: test1.sh, test10.sh, test11.sh, test12.sh, test13.sh, test14.sh, test15.sh, test16.sh, test17.sh, test18.sh, test19.sh, test2.sh, test20.sh, test21.sh, test22.sh, test23.sh, test24.sh, test25.sh, test3.sh, test4.sh, test5.sh, test6.sh, test7.sh, test8.sh, test9.sh, Makefile.am, test20.out, test21.out, test22.out, test23.out, test24.out, test25.out: added new tests and comments 2004-01-29 20:36 mes5k * include/tclap/: CmdLine.h, CommandLine.h, MultiArg.h, ValueArg.h: fix for strings with spaces 2004-01-10 09:39 mes5k * docs/index.html: spelling 2004-01-07 22:18 mes5k * docs/: index.html, manual.html: updates 2004-01-07 21:51 mes5k * NEWS: update 2004-01-07 21:30 mes5k * include/tclap/CmdLine.h, src/CmdLine.cpp: added backward compatibility 2004-01-07 21:11 mes5k * src/Arg.cpp: fixed warning 2004-01-07 21:04 mes5k * examples/: Makefile.am, test4.cpp: added new test 2004-01-07 21:00 mes5k * tests/Makefile.am: added two new tests 2004-01-07 20:59 mes5k * include/tclap/: Arg.h, ArgException.h, CmdLine.h, HelpVisitor.h, IgnoreRestVisitor.h, MultiArg.h, SwitchArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h, VersionVisitor.h, Visitor.h: fixed combined switch stuff and added doxygen comments 2004-01-07 20:58 mes5k * src/: Arg.cpp, CmdLine.cpp, SwitchArg.cpp: fixed some combined switch stuff 2004-01-07 20:50 mes5k * tests/: test18.out, test18.sh, test19.out, test19.sh: new tests 2003-12-21 18:32 mes5k * autotools.sh: init 2003-12-21 18:31 mes5k * include/tclap/UnlabeledMultiArg.h: delim stuff 2003-12-21 18:14 mes5k * examples/test1.cpp: new fangled 2003-12-21 18:11 mes5k * configure.in: 0.9.6 2003-12-21 18:10 mes5k * tests/: test13.sh, test14.sh: updated 2003-12-21 18:09 mes5k * tests/: test10.out, test11.out, test12.out, test13.out, test14.out, test15.out, test16.out, test4.out: updates 2003-12-21 18:07 mes5k * tests/Makefile.am: added test 2003-12-21 18:06 mes5k * tests/: test17.out, test17.sh: first checkin 2003-12-21 18:01 mes5k * src/Arg.cpp: removed message 2003-12-21 17:59 mes5k * examples/Makefile.am: added warnings 2003-12-21 17:58 mes5k * examples/: test2.cpp, test3.cpp: fixed warnings 2003-12-21 17:53 mes5k * Makefile.am: added warnings 2003-12-21 17:52 mes5k * src/Arg.cpp, src/CmdLine.cpp, src/SwitchArg.cpp, examples/test3.cpp: added delimiter 2003-12-21 17:50 mes5k * src/Makefile.am: added warnings 2003-12-21 17:48 mes5k * include/tclap/: Arg.h, ArgException.h, CmdLine.h, MultiArg.h, UnlabeledValueArg.h, ValueArg.h: delimiter changes 2003-04-03 10:26 mes5k * include/tclap/Makefile.am: added new visitor 2003-04-03 10:20 mes5k * include/tclap/Makefile.am: updates 2003-04-03 10:13 mes5k * config/: mkinstalldirs, install-sh, missing, depcomp: init checkin 2003-04-03 10:11 mes5k * NEWS: update 2003-04-03 10:06 mes5k * examples/Makefile.am, examples/test1.cpp, examples/test2.cpp, examples/test3.cpp, INSTALL, Makefile.in: updates 2003-04-03 10:01 mes5k * Makefile.am, configure.in: added tests 2003-04-03 10:00 mes5k * docs/: index.html, manual.html: updated docs 2003-04-03 09:59 mes5k * include/tclap/: Arg.h, CmdLine.h, IgnoreRestVisitor.h, MultiArg.h, SwitchArg.h, UnlabeledMultiArg.h, UnlabeledValueArg.h, ValueArg.h: big update 2003-04-03 09:57 mes5k * src/: CmdLine.cpp, SwitchArg.cpp, Arg.cpp: new update 2003-04-03 09:56 mes5k * tests/: test10.sh, test11.sh, test12.sh, test1.sh, test13.sh, test14.sh, test15.sh, test16.sh, test2.sh, test3.sh, test4.sh, test5.sh, test6.sh, test7.sh, test8.sh, test9.sh, test10.out, test11.out, test12.out, test13.out, test14.out, test15.out, test16.out, test1.out, test2.out, test3.out, test4.out, test5.out, test6.out, test7.out, Makefile.am, test8.out, test9.out, Makefile.in, genOut.pl: initial checkin 2003-03-18 18:39 mes5k * NEWS, configure.in, AUTHORS, COPYING, ChangeLog, Makefile.am, Makefile.in, README, aclocal.m4, configure, config/ac_cxx_have_sstream.m4, config/ac_cxx_have_strstream.m4, config/ac_cxx_namespaces.m4, config/bb_enable_doxygen.m4, config/config.h.in, config/stamp-h.in, config/stamp-h1, examples/Makefile.am, examples/Makefile.in, examples/test1.cpp, examples/test2.cpp, include/Makefile.am, include/Makefile.in, include/tclap/Arg.h, include/tclap/ArgException.h, include/tclap/CmdLine.h, include/tclap/HelpVisitor.h, include/tclap/MultiArg.h, docs/Doxyfile.in, docs/Makefile.am, docs/Makefile.in, docs/index.html, docs/manual.html, include/tclap/Makefile.am, include/tclap/Makefile.in, include/tclap/SwitchArg.h, include/tclap/ValueArg.h, include/tclap/VersionVisitor.h, include/tclap/Visitor.h, src/Arg.cpp, src/CmdLine.cpp, src/Makefile.am, src/Makefile.in, src/SwitchArg.cpp: Initial revision 2003-03-18 18:39 mes5k * NEWS, configure.in, AUTHORS, COPYING, ChangeLog, Makefile.am, Makefile.in, README, aclocal.m4, configure, config/ac_cxx_have_sstream.m4, config/ac_cxx_have_strstream.m4, config/ac_cxx_namespaces.m4, config/bb_enable_doxygen.m4, config/config.h.in, config/stamp-h.in, config/stamp-h1, examples/Makefile.am, examples/Makefile.in, examples/test1.cpp, examples/test2.cpp, include/Makefile.am, include/Makefile.in, include/tclap/Arg.h, include/tclap/ArgException.h, include/tclap/CmdLine.h, include/tclap/HelpVisitor.h, include/tclap/MultiArg.h, docs/Doxyfile.in, docs/Makefile.am, docs/Makefile.in, docs/index.html, docs/manual.html, include/tclap/Makefile.am, include/tclap/Makefile.in, include/tclap/SwitchArg.h, include/tclap/ValueArg.h, include/tclap/VersionVisitor.h, include/tclap/Visitor.h, src/Arg.cpp, src/CmdLine.cpp, src/Makefile.am, src/Makefile.in, src/SwitchArg.cpp: initial release ================================================ FILE: libs/tclap/INSTALL ================================================ Basic Installation ================== These are generic installation instructions. The `configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a `Makefile' in each directory of the package. It may also create one or more `.h' files containing system-dependent definitions. Finally, it creates a shell script `config.status' that you can run in the future to recreate the current configuration, a file `config.cache' that saves the results of its tests to speed up reconfiguring, and a file `config.log' containing compiler output (useful mainly for debugging `configure'). If you need to do unusual things to compile the package, please try to figure out how `configure' could check whether to do them, and mail diffs or instructions to the address given in the `README' so they can be considered for the next release. If at some point `config.cache' contains results you don't want to keep, you may remove or edit it. The file `configure.in' is used to create `configure' by a program called `autoconf'. You only need `configure.in' if you want to change it or regenerate `configure' using a newer version of `autoconf'. The simplest way to compile this package is: 1. `cd' to the directory containing the package's source code and type `./configure' to configure the package for your system. If you're using `csh' on an old version of System V, you might need to type `sh ./configure' instead to prevent `csh' from trying to execute `configure' itself. Running `configure' takes awhile. While running, it prints some messages telling which features it is checking for. 2. Type `make' to compile the package. 3. Optionally, type `make check' to run any self-tests that come with the package. 4. Type `make install' to install the programs and any data files and documentation. 5. You can remove the program binaries and object files from the source code directory by typing `make clean'. To also remove the files that `configure' created (so you can compile the package for a different kind of computer), type `make distclean'. There is also a `make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure' script does not know about. You can give `configure' initial values for variables by setting them in the environment. Using a Bourne-compatible shell, you can do that on the command line like this: CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure Or on systems that have the `env' program, you can do it like this: env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you must use a version of `make' that supports the `VPATH' variable, such as GNU `make'. `cd' to the directory where you want the object files and executables to go and run the `configure' script. `configure' automatically checks for the source code in the directory that `configure' is in and in `..'. If you have to use a `make' that does not supports the `VPATH' variable, you have to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use `make distclean' before reconfiguring for another architecture. Installation Names ================== By default, `make install' will install the package's files in `/usr/local/bin', `/usr/local/man', etc. You can specify an installation prefix other than `/usr/local' by giving `configure' the option `--prefix=PATH'. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you give `configure' the option `--exec-prefix=PATH', the package will use PATH as the prefix for installing programs and libraries. Documentation and other data files will still use the regular prefix. In addition, if you use an unusual directory layout you can give options like `--bindir=PATH' to specify different values for particular kinds of files. Run `configure --help' for a list of the directories you can set and what kinds of files go in them. If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving `configure' the option `--program-prefix=PREFIX' or `--program-suffix=SUFFIX'. Optional Features ================= Some packages pay attention to `--enable-FEATURE' options to `configure', where FEATURE indicates an optional part of the package. They may also pay attention to `--with-PACKAGE' options, where PACKAGE is something like `gnu-as' or `x' (for the X Window System). The `README' should mention any `--enable-' and `--with-' options that the package recognizes. For packages that use the X Window System, `configure' can usually find the X include and library files automatically, but if it doesn't, you can use the `configure' options `--x-includes=DIR' and `--x-libraries=DIR' to specify their locations. Specifying the System Type ========================== There may be some features `configure' can not figure out automatically, but needs to determine by the type of host the package will run on. Usually `configure' can figure that out, but if it prints a message saying it can not guess the host type, give it the `--host=TYPE' option. TYPE can either be a short name for the system type, such as `sun4', or a canonical name with three fields: CPU-COMPANY-SYSTEM See the file `config.sub' for the possible values of each field. If `config.sub' isn't included in this package, then this package doesn't need to know the host type. If you are building compiler tools for cross-compiling, you can also use the `--target=TYPE' option to select the type of system they will produce code for and the `--build=TYPE' option to select the type of system on which you are compiling the package. Sharing Defaults ================ If you want to set default values for `configure' scripts to share, you can create a site shell script called `config.site' that gives default values for variables like `CC', `cache_file', and `prefix'. `configure' looks for `PREFIX/share/config.site' if it exists, then `PREFIX/etc/config.site' if it exists. Or, you can set the `CONFIG_SITE' environment variable to the location of the site script. A warning: not all `configure' scripts look for a site script. Operation Controls ================== `configure' recognizes the following options to control how it operates. `--cache-file=FILE' Use and save the results of the tests in FILE instead of `./config.cache'. Set FILE to `/dev/null' to disable caching, for debugging `configure'. `--help' Print a summary of the options to `configure', and exit. `--quiet' `--silent' `-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to `/dev/null' (any error messages will still be shown). `--srcdir=DIR' Look for the package's source code in directory DIR. Usually `configure' can determine that directory automatically. `--version' Print the version of Autoconf used to generate the `configure' script, and exit. `configure' also accepts some other, not widely useful, options. ================================================ FILE: libs/tclap/NEWS ================================================ 4/3/03 - Checked in a good sized update that move support of the library closer to that of the POSIX/GNU standards. Switches can now be combined into single arguments, -- is supported and MultiArgs now allow for multiple labeled args. I've also changed things a bit by subclassing MultiArg and ValueArg to get unlabeled versions of these classes. I think this is a bit cleaner design, despite two new classes. 1/7/04 - ... and with great trepidation, I release 0.9.6. Loads of changes. The big change is that you can now define the delimiter used to separate argument flags and argument values. So if you prefer arguments of the style "-s=asdf" instead of "-s asdf", you can do so. I've also fixed a number of warnings generated and fixed a few pathologic bugs related to combined switches. That said, I suspect that there may be a few significant bugs in this release that I haven't uncovered yet. Please let me know ASAP if you find any. 2/6/04 - Another big release: 0.9.7. First is a bugfix submitted by Matthias Stiller that specializes the _extractValue method in a couple of places that allows strings with spaces to be correctly read by tclap. A second bug found by John Ling has been fixed so that exceptions are thrown if more than one value is parsed from a single arg or if the second value parsed is invalid. A big new feature has been added that allows args to be xor'd. This means that two (or more) args can be specified such that one and only one of the args is required. If a second arg is found an exception is thrown. See the manual for details. As always, let me know if you run into any problems. 2/10/04 - A minor release: 0.9.8. A couple of bug fixes for 0.9.7 are included and a feature has been added that allows Args to be specified without short options, meaning the user is forced to use only long options. This is useful for programs with more options than map sensibly to single chars. 7/3/04 - Added a new constructor and handling to the various value args that allows the user to provide a list of values that the input arg values should be restricted to. 8/9/04 - Created a function to print the output nicely, meaning line wraps are handled somewhat sensibly now. Also changed error handling slightly. Instead of printing the entire usage, I just print a short usage. If someone really hates this, its easy to change back. Let me know if this causes problems. I think this equals release 0.9.9! 10/19/04 - A number of changes that should substantially improve the library. The most important being that we've moved the implementation of the library entirely into the header files. This means there is no longer a library to complile against, you simply have to #include . New constructors have been added to the various Arg classes that allow them to be constructed with a CmdLine reference so that you no longer need to call the add method if you prefer it that way. The output generated by the library has been confined to a few methods in the CmdLine class. This means to generate different output you can extend CmdLine and override the offending methods. A number of style changes have been made in the code base to conform better to C++ best practices. A thoughtful user has contributed project files for the building the examples Microsoft Visual Studio. See the README file in the msc directory for more details And so we have release 1.0! 10/30/04 - A few bugfixes. Now checking for include.h before including it. This will help Windows users who don't have it. Also changed test1 so that it doesn't use toupper, which apparently causes problem for non-ASCII character sets. 10/31/04 - A few more tweaks, none of which should be noticeable to people who are already using the lib without trouble. Maybe I shouldn't release things early in the morning! Also note that manual.html is now generated from manual.xml. If you have your own docbook xsl style that you prefer, then have at it. 12/3/04 - Some minor bug fixes including the removal of the two stage name lookup ifdefs which means that the software should work out of the box for gcc 3.4+. Isolated output in a separate class that should make customization of output easier. I also included a rudimentary output class that generated a (bad) Docbook command summary when used. 1/4/05 - Several bug fixes, but no new features. Fixed a bug when mandatory long args and unlabeled args were used together and weren't working properly. Now they can be used together. Fixed another bug in spacePrint where long program names caused an infinite loop. Finally, fixed a small memory leak. 1/6/05 - Fixed a bug where setting the output object for a CmdLine didn't register for version or usage generation. Doh! Created a Constraint interface that should facilitate the creation of different constraints on Args. This has involved changing the constructor interface, so if you've been using allowed lists, you'll need to make a small modification to your existing code. See examples/test6.cpp for details. 9/26/09 - Whoa, long break. Primarily a bug-fix release, but we did switch to using traits, which necessitates the minor version bump. Take a look at test11.cpp and test12.cpp for examples on using ArgTraits for extending tclap for different types. 4/16/11 - Another long break! Several minor bug and memory leak fixes. ================================================ FILE: libs/tclap/README ================================================ TCLAP - Templatized Command Line Argument Parser This is a simple C++ library that facilitates parsing command line arguments in a type independent manner. It doesn't conform exactly to either the GNU or POSIX standards, although it is close. See docs/manual.html for descriptions of how things work or look at the simple examples in the examples dir. To find out what the latest changes are read the NEWS file in this directory. Any and all feedback is welcome to: Mike Smoot ================================================ FILE: libs/tclap/include/tclap/Arg.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: Arg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_ARGUMENT_H #define TCLAP_ARGUMENT_H #ifdef HAVE_CONFIG_H #include #else #define HAVE_SSTREAM #endif #include #include #include #include #include #include #if defined(HAVE_SSTREAM) #include typedef std::istringstream istringstream; #elif defined(HAVE_STRSTREAM) #include typedef std::istrstream istringstream; #else #error "Need a stringstream (sstream or strstream) to compile!" #endif #include #include #include #include #include namespace TCLAP { /** * A virtual base class that defines the essential data for all arguments. * This class, or one of its existing children, must be subclassed to do * anything. */ class Arg { private: /** * Prevent accidental copying. */ Arg(const Arg& rhs); /** * Prevent accidental copying. */ Arg& operator=(const Arg& rhs); /** * Indicates whether the rest of the arguments should be ignored. */ static bool& ignoreRestRef() { static bool ign = false; return ign; } /** * The delimiter that separates an argument flag/name from the * value. */ static char& delimiterRef() { static char delim = ' '; return delim; } protected: /** * The single char flag used to identify the argument. * This value (preceded by a dash {-}), can be used to identify * an argument on the command line. The _flag can be blank, * in fact this is how unlabeled args work. Unlabeled args must * override appropriate functions to get correct handling. Note * that the _flag does NOT include the dash as part of the flag. */ std::string _flag; /** * A single work namd indentifying the argument. * This value (preceded by two dashed {--}) can also be used * to identify an argument on the command line. Note that the * _name does NOT include the two dashes as part of the _name. The * _name cannot be blank. */ std::string _name; /** * Description of the argument. */ std::string _description; /** * Indicating whether the argument is required. */ bool _required; /** * Label to be used in usage description. Normally set to * "required", but can be changed when necessary. */ std::string _requireLabel; /** * Indicates whether a value is required for the argument. * Note that the value may be required but the argument/value * combination may not be, as specified by _required. */ bool _valueRequired; /** * Indicates whether the argument has been set. * Indicates that a value on the command line has matched the * name/flag of this argument and the values have been set accordingly. */ bool _alreadySet; /** * A pointer to a vistitor object. * The visitor allows special handling to occur as soon as the * argument is matched. This defaults to NULL and should not * be used unless absolutely necessary. */ Visitor* _visitor; /** * Whether this argument can be ignored, if desired. */ bool _ignoreable; /** * Indicates that the arg was set as part of an XOR and not on the * command line. */ bool _xorSet; bool _acceptsMultipleValues; /** * Performs the special handling described by the Vistitor. */ void _checkWithVisitor() const; /** * Primary constructor. YOU (yes you) should NEVER construct an Arg * directly, this is a base class that is extended by various children * that are meant to be used. Use SwitchArg, ValueArg, MultiArg, * UnlabeledValueArg, or UnlabeledMultiArg instead. * * \param flag - The flag identifying the argument. * \param name - The name identifying the argument. * \param desc - The description of the argument, used in the usage. * \param req - Whether the argument is required. * \param valreq - Whether the a value is required for the argument. * \param v - The visitor checked by the argument. Defaults to NULL. */ Arg( const std::string& flag, const std::string& name, const std::string& desc, bool req, bool valreq, Visitor* v = NULL ); public: /** * Destructor. */ virtual ~Arg(); /** * Adds this to the specified list of Args. * \param argList - The list to add this to. */ virtual void addToList( std::list& argList ) const; /** * Begin ignoring arguments since the "--" argument was specified. */ static void beginIgnoring() { ignoreRestRef() = true; } /** * Whether to ignore the rest. */ static bool ignoreRest() { return ignoreRestRef(); } /** * The delimiter that separates an argument flag/name from the * value. */ static char delimiter() { return delimiterRef(); } /** * The char used as a place holder when SwitchArgs are combined. * Currently set to the bell char (ASCII 7). */ static char blankChar() { return (char)7; } /** * The char that indicates the beginning of a flag. Defaults to '-', but * clients can define TCLAP_FLAGSTARTCHAR to override. */ #ifndef TCLAP_FLAGSTARTCHAR #define TCLAP_FLAGSTARTCHAR '-' #endif static char flagStartChar() { return TCLAP_FLAGSTARTCHAR; } /** * The sting that indicates the beginning of a flag. Defaults to "-", but * clients can define TCLAP_FLAGSTARTSTRING to override. Should be the same * as TCLAP_FLAGSTARTCHAR. */ #ifndef TCLAP_FLAGSTARTSTRING #define TCLAP_FLAGSTARTSTRING "-" #endif static const std::string flagStartString() { return TCLAP_FLAGSTARTSTRING; } /** * The sting that indicates the beginning of a name. Defaults to "--", but * clients can define TCLAP_NAMESTARTSTRING to override. */ #ifndef TCLAP_NAMESTARTSTRING #define TCLAP_NAMESTARTSTRING "--" #endif static const std::string nameStartString() { return TCLAP_NAMESTARTSTRING; } /** * The name used to identify the ignore rest argument. */ static const std::string ignoreNameString() { return "ignore_rest"; } /** * Sets the delimiter for all arguments. * \param c - The character that delimits flags/names from values. */ static void setDelimiter( char c ) { delimiterRef() = c; } /** * Pure virtual method meant to handle the parsing and value assignment * of the string on the command line. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. What is * passed in from main. */ virtual bool processArg(int *i, std::vector& args) = 0; /** * Operator ==. * Equality operator. Must be virtual to handle unlabeled args. * \param a - The Arg to be compared to this. */ virtual bool operator==(const Arg& a) const; /** * Returns the argument flag. */ const std::string& getFlag() const; /** * Returns the argument name. */ const std::string& getName() const; /** * Returns the argument description. */ std::string getDescription() const; /** * Indicates whether the argument is required. */ virtual bool isRequired() const; /** * Sets _required to true. This is used by the XorHandler. * You really have no reason to ever use it. */ void forceRequired(); /** * Sets the _alreadySet value to true. This is used by the XorHandler. * You really have no reason to ever use it. */ void xorSet(); /** * Indicates whether a value must be specified for argument. */ bool isValueRequired() const; /** * Indicates whether the argument has already been set. Only true * if the arg has been matched on the command line. */ bool isSet() const; /** * Indicates whether the argument can be ignored, if desired. */ bool isIgnoreable() const; /** * A method that tests whether a string matches this argument. * This is generally called by the processArg() method. This * method could be re-implemented by a child to change how * arguments are specified on the command line. * \param s - The string to be compared to the flag/name to determine * whether the arg matches. */ virtual bool argMatches( const std::string& s ) const; /** * Returns a simple string representation of the argument. * Primarily for debugging. */ virtual std::string toString() const; /** * Returns a short ID for the usage. * \param valueId - The value used in the id. */ virtual std::string shortID( const std::string& valueId = "val" ) const; /** * Returns a long ID for the usage. * \param valueId - The value used in the id. */ virtual std::string longID( const std::string& valueId = "val" ) const; /** * Trims a value off of the flag. * \param flag - The string from which the flag and value will be * trimmed. Contains the flag once the value has been trimmed. * \param value - Where the value trimmed from the string will * be stored. */ virtual void trimFlag( std::string& flag, std::string& value ) const; /** * Checks whether a given string has blank chars, indicating that * it is a combined SwitchArg. If so, return true, otherwise return * false. * \param s - string to be checked. */ bool _hasBlanks( const std::string& s ) const; /** * Sets the requireLabel. Used by XorHandler. You shouldn't ever * use this. * \param s - Set the requireLabel to this value. */ void setRequireLabel( const std::string& s ); /** * Used for MultiArgs and XorHandler to determine whether args * can still be set. */ virtual bool allowMore(); /** * Use by output classes to determine whether an Arg accepts * multiple values. */ virtual bool acceptsMultipleValues(); /** * Clears the Arg object and allows it to be reused by new * command lines. */ virtual void reset(); }; /** * Typedef of an Arg list iterator. */ typedef std::list::iterator ArgListIterator; /** * Typedef of an Arg vector iterator. */ typedef std::vector::iterator ArgVectorIterator; /** * Typedef of a Visitor list iterator. */ typedef std::list::iterator VisitorListIterator; /* * Extract a value of type T from it's string representation contained * in strVal. The ValueLike parameter used to select the correct * specialization of ExtractValue depending on the value traits of T. * ValueLike traits use operator>> to assign the value from strVal. */ template void ExtractValue(T &destVal, const std::string& strVal, ValueLike vl) { static_cast(vl); // Avoid warning about unused vl std::istringstream is(strVal); int valuesRead = 0; while ( is.good() ) { if ( is.peek() != EOF ) #ifdef TCLAP_SETBASE_ZERO is >> std::setbase(0) >> destVal; #else is >> destVal; #endif else break; valuesRead++; } if ( is.fail() ) throw( ArgParseException("Couldn't read argument value " "from string '" + strVal + "'")); if ( valuesRead > 1 ) throw( ArgParseException("More than one valid value parsed from " "string '" + strVal + "'")); } /* * Extract a value of type T from it's string representation contained * in strVal. The ValueLike parameter used to select the correct * specialization of ExtractValue depending on the value traits of T. * StringLike uses assignment (operator=) to assign from strVal. */ template void ExtractValue(T &destVal, const std::string& strVal, StringLike sl) { static_cast(sl); // Avoid warning about unused sl SetString(destVal, strVal); } ////////////////////////////////////////////////////////////////////// //BEGIN Arg.cpp ////////////////////////////////////////////////////////////////////// inline Arg::Arg(const std::string& flag, const std::string& name, const std::string& desc, bool req, bool valreq, Visitor* v) : _flag(flag), _name(name), _description(desc), _required(req), _requireLabel("required"), _valueRequired(valreq), _alreadySet(false), _visitor( v ), _ignoreable(true), _xorSet(false), _acceptsMultipleValues(false) { if ( _flag.length() > 1 ) throw(SpecificationException( "Argument flag can only be one character long", toString() ) ); if ( _name != ignoreNameString() && ( _flag == Arg::flagStartString() || _flag == Arg::nameStartString() || _flag == " " ) ) throw(SpecificationException("Argument flag cannot be either '" + Arg::flagStartString() + "' or '" + Arg::nameStartString() + "' or a space.", toString() ) ); if ( ( _name.substr( 0, Arg::flagStartString().length() ) == Arg::flagStartString() ) || ( _name.substr( 0, Arg::nameStartString().length() ) == Arg::nameStartString() ) || ( _name.find( " ", 0 ) != std::string::npos ) ) throw(SpecificationException("Argument name begin with either '" + Arg::flagStartString() + "' or '" + Arg::nameStartString() + "' or space.", toString() ) ); } inline Arg::~Arg() { } inline std::string Arg::shortID( const std::string& valueId ) const { std::string id = ""; if ( _flag != "" ) id = Arg::flagStartString() + _flag; else id = Arg::nameStartString() + _name; if ( _valueRequired ) id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">"; if ( !_required ) id = "[" + id + "]"; return id; } inline std::string Arg::longID( const std::string& valueId ) const { std::string id = ""; if ( _flag != "" ) { id += Arg::flagStartString() + _flag; if ( _valueRequired ) id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">"; id += ", "; } id += Arg::nameStartString() + _name; if ( _valueRequired ) id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">"; return id; } inline bool Arg::operator==(const Arg& a) const { if ( ( _flag != "" && _flag == a._flag ) || _name == a._name) return true; else return false; } inline std::string Arg::getDescription() const { std::string desc = ""; if ( _required ) desc = "(" + _requireLabel + ") "; // if ( _valueRequired ) // desc += "(value required) "; desc += _description; return desc; } inline const std::string& Arg::getFlag() const { return _flag; } inline const std::string& Arg::getName() const { return _name; } inline bool Arg::isRequired() const { return _required; } inline bool Arg::isValueRequired() const { return _valueRequired; } inline bool Arg::isSet() const { if ( _alreadySet && !_xorSet ) return true; else return false; } inline bool Arg::isIgnoreable() const { return _ignoreable; } inline void Arg::setRequireLabel( const std::string& s) { _requireLabel = s; } inline bool Arg::argMatches( const std::string& argFlag ) const { if ( ( argFlag == Arg::flagStartString() + _flag && _flag != "" ) || argFlag == Arg::nameStartString() + _name ) return true; else return false; } inline std::string Arg::toString() const { std::string s = ""; if ( _flag != "" ) s += Arg::flagStartString() + _flag + " "; s += "(" + Arg::nameStartString() + _name + ")"; return s; } inline void Arg::_checkWithVisitor() const { if ( _visitor != NULL ) _visitor->visit(); } /** * Implementation of trimFlag. */ inline void Arg::trimFlag(std::string& flag, std::string& value) const { int stop = 0; for ( int i = 0; static_cast(i) < flag.length(); i++ ) if ( flag[i] == Arg::delimiter() ) { stop = i; break; } if ( stop > 1 ) { value = flag.substr(stop+1); flag = flag.substr(0,stop); } } /** * Implementation of _hasBlanks. */ inline bool Arg::_hasBlanks( const std::string& s ) const { for ( int i = 1; static_cast(i) < s.length(); i++ ) if ( s[i] == Arg::blankChar() ) return true; return false; } inline void Arg::forceRequired() { _required = true; } inline void Arg::xorSet() { _alreadySet = true; _xorSet = true; } /** * Overridden by Args that need to added to the end of the list. */ inline void Arg::addToList( std::list& argList ) const { argList.push_front( const_cast(this) ); } inline bool Arg::allowMore() { return false; } inline bool Arg::acceptsMultipleValues() { return _acceptsMultipleValues; } inline void Arg::reset() { _xorSet = false; _alreadySet = false; } ////////////////////////////////////////////////////////////////////// //END Arg.cpp ////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/ArgException.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: ArgException.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_ARG_EXCEPTION_H #define TCLAP_ARG_EXCEPTION_H #include #include namespace TCLAP { /** * A simple class that defines and argument exception. Should be caught * whenever a CmdLine is created and parsed. */ class ArgException : public std::exception { public: /** * Constructor. * \param text - The text of the exception. * \param id - The text identifying the argument source. * \param td - Text describing the type of ArgException it is. * of the exception. */ ArgException( const std::string& text = "undefined exception", const std::string& id = "undefined", const std::string& td = "Generic ArgException") : std::exception(), _errorText(text), _argId( id ), _typeDescription(td) { } /** * Destructor. */ virtual ~ArgException() throw() { } /** * Returns the error text. */ std::string error() const { return ( _errorText ); } /** * Returns the argument id. */ std::string argId() const { if ( _argId == "undefined" ) return " "; else return ( "Argument: " + _argId ); } /** * Returns the arg id and error text. */ const char* what() const throw() { static std::string ex; ex = _argId + " -- " + _errorText; return ex.c_str(); } /** * Returns the type of the exception. Used to explain and distinguish * between different child exceptions. */ std::string typeDescription() const { return _typeDescription; } private: /** * The text of the exception message. */ std::string _errorText; /** * The argument related to this exception. */ std::string _argId; /** * Describes the type of the exception. Used to distinguish * between different child exceptions. */ std::string _typeDescription; }; /** * Thrown from within the child Arg classes when it fails to properly * parse the argument it has been passed. */ class ArgParseException : public ArgException { public: /** * Constructor. * \param text - The text of the exception. * \param id - The text identifying the argument source * of the exception. */ ArgParseException( const std::string& text = "undefined exception", const std::string& id = "undefined" ) : ArgException( text, id, std::string( "Exception found while parsing " ) + std::string( "the value the Arg has been passed." )) { } }; /** * Thrown from CmdLine when the arguments on the command line are not * properly specified, e.g. too many arguments, required argument missing, etc. */ class CmdLineParseException : public ArgException { public: /** * Constructor. * \param text - The text of the exception. * \param id - The text identifying the argument source * of the exception. */ CmdLineParseException( const std::string& text = "undefined exception", const std::string& id = "undefined" ) : ArgException( text, id, std::string( "Exception found when the values ") + std::string( "on the command line do not meet ") + std::string( "the requirements of the defined ") + std::string( "Args." )) { } }; /** * Thrown from Arg and CmdLine when an Arg is improperly specified, e.g. * same flag as another Arg, same name, etc. */ class SpecificationException : public ArgException { public: /** * Constructor. * \param text - The text of the exception. * \param id - The text identifying the argument source * of the exception. */ SpecificationException( const std::string& text = "undefined exception", const std::string& id = "undefined" ) : ArgException( text, id, std::string("Exception found when an Arg object ")+ std::string("is improperly defined by the ") + std::string("developer." )) { } }; class ExitException { public: ExitException(int estat) : _estat(estat) {} int getExitStatus() const { return _estat; } private: int _estat; }; } // namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/ArgTraits.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: ArgTraits.h * * Copyright (c) 2007, Daniel Aarno, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ // This is an internal tclap file, you should probably not have to // include this directly #ifndef TCLAP_ARGTRAITS_H #define TCLAP_ARGTRAITS_H namespace TCLAP { // We use two empty structs to get compile type specialization // function to work /** * A value like argument value type is a value that can be set using * operator>>. This is the default value type. */ struct ValueLike { typedef ValueLike ValueCategory; virtual ~ValueLike() {} }; /** * A string like argument value type is a value that can be set using * operator=(string). Usefull if the value type contains spaces which * will be broken up into individual tokens by operator>>. */ struct StringLike { virtual ~StringLike() {} }; /** * A class can inherit from this object to make it have string like * traits. This is a compile time thing and does not add any overhead * to the inherenting class. */ struct StringLikeTrait { typedef StringLike ValueCategory; virtual ~StringLikeTrait() {} }; /** * A class can inherit from this object to make it have value like * traits. This is a compile time thing and does not add any overhead * to the inherenting class. */ struct ValueLikeTrait { typedef ValueLike ValueCategory; virtual ~ValueLikeTrait() {} }; /** * Arg traits are used to get compile type specialization when parsing * argument values. Using an ArgTraits you can specify the way that * values gets assigned to any particular type during parsing. The two * supported types are StringLike and ValueLike. */ template struct ArgTraits { typedef typename T::ValueCategory ValueCategory; virtual ~ArgTraits() {} //typedef ValueLike ValueCategory; }; #endif } // namespace ================================================ FILE: libs/tclap/include/tclap/CmdLine.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: CmdLine.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_CMDLINE_H #define TCLAP_CMDLINE_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Needed for exit(), which isn't defined in some envs. namespace TCLAP { template void DelPtr(T ptr) { delete ptr; } template void ClearContainer(C &c) { typedef typename C::value_type value_type; std::for_each(c.begin(), c.end(), DelPtr); c.clear(); } /** * The base class that manages the command line definition and passes * along the parsing to the appropriate Arg classes. */ class CmdLine : public CmdLineInterface { protected: /** * The list of arguments that will be tested against the * command line. */ std::list _argList; /** * The name of the program. Set to argv[0]. */ std::string _progName; /** * A message used to describe the program. Used in the usage output. */ std::string _message; /** * The version to be displayed with the --version switch. */ std::string _version; /** * The number of arguments that are required to be present on * the command line. This is set dynamically, based on the * Args added to the CmdLine object. */ int _numRequired; /** * The character that is used to separate the argument flag/name * from the value. Defaults to ' ' (space). */ char _delimiter; /** * The handler that manages xoring lists of args. */ XorHandler _xorHandler; /** * A list of Args to be explicitly deleted when the destructor * is called. At the moment, this only includes the three default * Args. */ std::list _argDeleteOnExitList; /** * A list of Visitors to be explicitly deleted when the destructor * is called. At the moment, these are the Vistors created for the * default Args. */ std::list _visitorDeleteOnExitList; /** * Object that handles all output for the CmdLine. */ CmdLineOutput* _output; /** * Should CmdLine handle parsing exceptions internally? */ bool _handleExceptions; /** * Throws an exception listing the missing args. */ void missingArgsException(); /** * Checks whether a name/flag string matches entirely matches * the Arg::blankChar. Used when multiple switches are combined * into a single argument. * \param s - The message to be used in the usage. */ bool _emptyCombined(const std::string& s); /** * Perform a delete ptr; operation on ptr when this object is deleted. */ void deleteOnExit(Arg* ptr); /** * Perform a delete ptr; operation on ptr when this object is deleted. */ void deleteOnExit(Visitor* ptr); private: /** * Prevent accidental copying. */ CmdLine(const CmdLine& rhs); CmdLine& operator=(const CmdLine& rhs); /** * Encapsulates the code common to the constructors * (which is all of it). */ void _constructor(); /** * Is set to true when a user sets the output object. We use this so * that we don't delete objects that are created outside of this lib. */ bool _userSetOutput; /** * Whether or not to automatically create help and version switches. */ bool _helpAndVersion; public: /** * Command line constructor. Defines how the arguments will be * parsed. * \param message - The message to be used in the usage * output. * \param delimiter - The character that is used to separate * the argument flag/name from the value. Defaults to ' ' (space). * \param version - The version number to be used in the * --version switch. * \param helpAndVersion - Whether or not to create the Help and * Version switches. Defaults to true. */ CmdLine(const std::string& message, const char delimiter = ' ', const std::string& version = "none", bool helpAndVersion = true); /** * Deletes any resources allocated by a CmdLine object. */ virtual ~CmdLine(); /** * Adds an argument to the list of arguments to be parsed. * \param a - Argument to be added. */ void add( Arg& a ); /** * An alternative add. Functionally identical. * \param a - Argument to be added. */ void add( Arg* a ); /** * Add two Args that will be xor'd. If this method is used, add does * not need to be called. * \param a - Argument to be added and xor'd. * \param b - Argument to be added and xor'd. */ void xorAdd( Arg& a, Arg& b ); /** * Add a list of Args that will be xor'd. If this method is used, * add does not need to be called. * \param xors - List of Args to be added and xor'd. */ void xorAdd( std::vector& xors ); /** * Parses the command line. * \param argc - Number of arguments. * \param argv - Array of arguments. */ void parse(int argc, const char * const * argv); /** * Parses the command line. * \param args - A vector of strings representing the args. * args[0] is still the program name. */ void parse(std::vector& args); /** * */ CmdLineOutput* getOutput(); /** * */ void setOutput(CmdLineOutput* co); /** * */ std::string& getVersion(); /** * */ std::string& getProgramName(); /** * */ std::list& getArgList(); /** * */ XorHandler& getXorHandler(); /** * */ char getDelimiter(); /** * */ std::string& getMessage(); /** * */ bool hasHelpAndVersion(); /** * Disables or enables CmdLine's internal parsing exception handling. * * @param state Should CmdLine handle parsing exceptions internally? */ void setExceptionHandling(const bool state); /** * Returns the current state of the internal exception handling. * * @retval true Parsing exceptions are handled internally. * @retval false Parsing exceptions are propagated to the caller. */ bool getExceptionHandling() const; /** * Allows the CmdLine object to be reused. */ void reset(); }; /////////////////////////////////////////////////////////////////////////////// //Begin CmdLine.cpp /////////////////////////////////////////////////////////////////////////////// inline CmdLine::CmdLine(const std::string& m, char delim, const std::string& v, bool help ) : _argList(std::list()), _progName("not_set_yet"), _message(m), _version(v), _numRequired(0), _delimiter(delim), _xorHandler(XorHandler()), _argDeleteOnExitList(std::list()), _visitorDeleteOnExitList(std::list()), _output(0), _handleExceptions(true), _userSetOutput(false), _helpAndVersion(help) { _constructor(); } inline CmdLine::~CmdLine() { ClearContainer(_argDeleteOnExitList); ClearContainer(_visitorDeleteOnExitList); if ( !_userSetOutput ) { delete _output; _output = 0; } } inline void CmdLine::_constructor() { _output = new StdOutput; Arg::setDelimiter( _delimiter ); Visitor* v; if ( _helpAndVersion ) { v = new HelpVisitor( this, &_output ); SwitchArg* help = new SwitchArg("h","help", "Displays usage information and exits.", false, v); add( help ); deleteOnExit(help); deleteOnExit(v); v = new VersionVisitor( this, &_output ); SwitchArg* vers = new SwitchArg("","version", "Displays version information and exits.", false, v); add( vers ); deleteOnExit(vers); deleteOnExit(v); } v = new IgnoreRestVisitor(); SwitchArg* ignore = new SwitchArg(Arg::flagStartString(), Arg::ignoreNameString(), "Ignores the rest of the labeled arguments following this flag.", false, v); add( ignore ); deleteOnExit(ignore); deleteOnExit(v); } inline void CmdLine::xorAdd( std::vector& ors ) { _xorHandler.add( ors ); for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++) { (*it)->forceRequired(); (*it)->setRequireLabel( "OR required" ); add( *it ); } } inline void CmdLine::xorAdd( Arg& a, Arg& b ) { std::vector ors; ors.push_back( &a ); ors.push_back( &b ); xorAdd( ors ); } inline void CmdLine::add( Arg& a ) { add( &a ); } inline void CmdLine::add( Arg* a ) { for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ ) if ( *a == *(*it) ) throw( SpecificationException( "Argument with same flag/name already exists!", a->longID() ) ); a->addToList( _argList ); if ( a->isRequired() ) _numRequired++; } inline void CmdLine::parse(int argc, const char * const * argv) { // this step is necessary so that we have easy access to // mutable strings. std::vector args; for (int i = 0; i < argc; i++) args.push_back(argv[i]); parse(args); } inline void CmdLine::parse(std::vector& args) { bool shouldExit = false; int estat = 0; try { _progName = args.front(); args.erase(args.begin()); int requiredCount = 0; for (int i = 0; static_cast(i) < args.size(); i++) { bool matched = false; for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++) { if ( (*it)->processArg( &i, args ) ) { requiredCount += _xorHandler.check( *it ); matched = true; break; } } // checks to see if the argument is an empty combined // switch and if so, then we've actually matched it if ( !matched && _emptyCombined( args[i] ) ) matched = true; if ( !matched && !Arg::ignoreRest() ) throw(CmdLineParseException("Couldn't find match " "for argument", args[i])); } if ( requiredCount < _numRequired ) missingArgsException(); if ( requiredCount > _numRequired ) throw(CmdLineParseException("Too many arguments!")); } catch ( ArgException& e ) { // If we're not handling the exceptions, rethrow. if ( !_handleExceptions) { throw; } try { _output->failure(*this,e); } catch ( ExitException &ee ) { estat = ee.getExitStatus(); shouldExit = true; } } catch (ExitException &ee) { // If we're not handling the exceptions, rethrow. if ( !_handleExceptions) { throw; } estat = ee.getExitStatus(); shouldExit = true; } if (shouldExit) exit(estat); } inline bool CmdLine::_emptyCombined(const std::string& s) { if ( s.length() > 0 && s[0] != Arg::flagStartChar() ) return false; for ( int i = 1; static_cast(i) < s.length(); i++ ) if ( s[i] != Arg::blankChar() ) return false; return true; } inline void CmdLine::missingArgsException() { int count = 0; std::string missingArgList; for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++) { if ( (*it)->isRequired() && !(*it)->isSet() ) { missingArgList += (*it)->getName(); missingArgList += ", "; count++; } } missingArgList = missingArgList.substr(0,missingArgList.length()-2); std::string msg; if ( count > 1 ) msg = "Required arguments missing: "; else msg = "Required argument missing: "; msg += missingArgList; throw(CmdLineParseException(msg)); } inline void CmdLine::deleteOnExit(Arg* ptr) { _argDeleteOnExitList.push_back(ptr); } inline void CmdLine::deleteOnExit(Visitor* ptr) { _visitorDeleteOnExitList.push_back(ptr); } inline CmdLineOutput* CmdLine::getOutput() { return _output; } inline void CmdLine::setOutput(CmdLineOutput* co) { if ( !_userSetOutput ) delete _output; _userSetOutput = true; _output = co; } inline std::string& CmdLine::getVersion() { return _version; } inline std::string& CmdLine::getProgramName() { return _progName; } inline std::list& CmdLine::getArgList() { return _argList; } inline XorHandler& CmdLine::getXorHandler() { return _xorHandler; } inline char CmdLine::getDelimiter() { return _delimiter; } inline std::string& CmdLine::getMessage() { return _message; } inline bool CmdLine::hasHelpAndVersion() { return _helpAndVersion; } inline void CmdLine::setExceptionHandling(const bool state) { _handleExceptions = state; } inline bool CmdLine::getExceptionHandling() const { return _handleExceptions; } inline void CmdLine::reset() { for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ ) (*it)->reset(); _progName.clear(); } /////////////////////////////////////////////////////////////////////////////// //End CmdLine.cpp /////////////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/CmdLineInterface.h ================================================ /****************************************************************************** * * file: CmdLineInterface.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_COMMANDLINE_INTERFACE_H #define TCLAP_COMMANDLINE_INTERFACE_H #include #include #include #include #include namespace TCLAP { class Arg; class CmdLineOutput; class XorHandler; /** * The base class that manages the command line definition and passes * along the parsing to the appropriate Arg classes. */ class CmdLineInterface { public: /** * Destructor */ virtual ~CmdLineInterface() {} /** * Adds an argument to the list of arguments to be parsed. * \param a - Argument to be added. */ virtual void add( Arg& a )=0; /** * An alternative add. Functionally identical. * \param a - Argument to be added. */ virtual void add( Arg* a )=0; /** * Add two Args that will be xor'd. * If this method is used, add does * not need to be called. * \param a - Argument to be added and xor'd. * \param b - Argument to be added and xor'd. */ virtual void xorAdd( Arg& a, Arg& b )=0; /** * Add a list of Args that will be xor'd. If this method is used, * add does not need to be called. * \param xors - List of Args to be added and xor'd. */ virtual void xorAdd( std::vector& xors )=0; /** * Parses the command line. * \param argc - Number of arguments. * \param argv - Array of arguments. */ virtual void parse(int argc, const char * const * argv)=0; /** * Parses the command line. * \param args - A vector of strings representing the args. * args[0] is still the program name. */ void parse(std::vector& args); /** * Returns the CmdLineOutput object. */ virtual CmdLineOutput* getOutput()=0; /** * \param co - CmdLineOutput object that we want to use instead. */ virtual void setOutput(CmdLineOutput* co)=0; /** * Returns the version string. */ virtual std::string& getVersion()=0; /** * Returns the program name string. */ virtual std::string& getProgramName()=0; /** * Returns the argList. */ virtual std::list& getArgList()=0; /** * Returns the XorHandler. */ virtual XorHandler& getXorHandler()=0; /** * Returns the delimiter string. */ virtual char getDelimiter()=0; /** * Returns the message string. */ virtual std::string& getMessage()=0; /** * Indicates whether or not the help and version switches were created * automatically. */ virtual bool hasHelpAndVersion()=0; /** * Resets the instance as if it had just been constructed so that the * instance can be reused. */ virtual void reset()=0; }; } //namespace #endif ================================================ FILE: libs/tclap/include/tclap/CmdLineOutput.h ================================================ /****************************************************************************** * * file: CmdLineOutput.h * * Copyright (c) 2004, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_CMDLINEOUTPUT_H #define TCLAP_CMDLINEOUTPUT_H #include #include #include #include #include #include namespace TCLAP { class CmdLineInterface; class ArgException; /** * The interface that any output object must implement. */ class CmdLineOutput { public: /** * Virtual destructor. */ virtual ~CmdLineOutput() {} /** * Generates some sort of output for the USAGE. * \param c - The CmdLine object the output is generated for. */ virtual void usage(CmdLineInterface& c)=0; /** * Generates some sort of output for the version. * \param c - The CmdLine object the output is generated for. */ virtual void version(CmdLineInterface& c)=0; /** * Generates some sort of output for a failure. * \param c - The CmdLine object the output is generated for. * \param e - The ArgException that caused the failure. */ virtual void failure( CmdLineInterface& c, ArgException& e )=0; }; } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/Constraint.h ================================================ /****************************************************************************** * * file: Constraint.h * * Copyright (c) 2005, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_CONSTRAINT_H #define TCLAP_CONSTRAINT_H #include #include #include #include #include #include namespace TCLAP { /** * The interface that defines the interaction between the Arg and Constraint. */ template class Constraint { public: /** * Returns a description of the Constraint. */ virtual std::string description() const =0; /** * Returns the short ID for the Constraint. */ virtual std::string shortID() const =0; /** * The method used to verify that the value parsed from the command * line meets the constraint. * \param value - The value that will be checked. */ virtual bool check(const T& value) const =0; /** * Destructor. * Silences warnings about Constraint being a base class with virtual * functions but without a virtual destructor. */ virtual ~Constraint() { ; } }; } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/DocBookOutput.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: DocBookOutput.h * * Copyright (c) 2004, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_DOCBOOKOUTPUT_H #define TCLAP_DOCBOOKOUTPUT_H #include #include #include #include #include #include #include #include #include namespace TCLAP { /** * A class that generates DocBook output for usage() method for the * given CmdLine and its Args. */ class DocBookOutput : public CmdLineOutput { public: /** * Prints the usage to stdout. Can be overridden to * produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void usage(CmdLineInterface& c); /** * Prints the version to stdout. Can be overridden * to produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void version(CmdLineInterface& c); /** * Prints (to stderr) an error message, short usage * Can be overridden to produce alternative behavior. * \param c - The CmdLine object the output is generated for. * \param e - The ArgException that caused the failure. */ virtual void failure(CmdLineInterface& c, ArgException& e ); protected: /** * Substitutes the char r for string x in string s. * \param s - The string to operate on. * \param r - The char to replace. * \param x - What to replace r with. */ void substituteSpecialChars( std::string& s, char r, std::string& x ); void removeChar( std::string& s, char r); void basename( std::string& s ); void printShortArg(Arg* it); void printLongArg(Arg* it); char theDelimiter; }; inline void DocBookOutput::version(CmdLineInterface& _cmd) { std::cout << _cmd.getVersion() << std::endl; } inline void DocBookOutput::usage(CmdLineInterface& _cmd ) { std::list argList = _cmd.getArgList(); std::string progName = _cmd.getProgramName(); std::string xversion = _cmd.getVersion(); theDelimiter = _cmd.getDelimiter(); XorHandler xorHandler = _cmd.getXorHandler(); std::vector< std::vector > xorList = xorHandler.getXorList(); basename(progName); std::cout << "" << std::endl; std::cout << "" << std::endl << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << progName << "" << std::endl; std::cout << "1" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << progName << "" << std::endl; std::cout << "" << _cmd.getMessage() << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << progName << "" << std::endl; // xor for ( int i = 0; (unsigned int)i < xorList.size(); i++ ) { std::cout << "" << std::endl; for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end(); it++ ) printShortArg((*it)); std::cout << "" << std::endl; } // rest of args for (ArgListIterator it = argList.begin(); it != argList.end(); it++) if ( !xorHandler.contains( (*it) ) ) printShortArg((*it)); std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "Description" << std::endl; std::cout << "" << std::endl; std::cout << _cmd.getMessage() << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "Options" << std::endl; std::cout << "" << std::endl; for (ArgListIterator it = argList.begin(); it != argList.end(); it++) printLongArg((*it)); std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "Version" << std::endl; std::cout << "" << std::endl; std::cout << xversion << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; } inline void DocBookOutput::failure( CmdLineInterface& _cmd, ArgException& e ) { static_cast(_cmd); // unused std::cout << e.what() << std::endl; throw ExitException(1); } inline void DocBookOutput::substituteSpecialChars( std::string& s, char r, std::string& x ) { size_t p; while ( (p = s.find_first_of(r)) != std::string::npos ) { s.erase(p,1); s.insert(p,x); } } inline void DocBookOutput::removeChar( std::string& s, char r) { size_t p; while ( (p = s.find_first_of(r)) != std::string::npos ) { s.erase(p,1); } } inline void DocBookOutput::basename( std::string& s ) { size_t p = s.find_last_of('/'); if ( p != std::string::npos ) { s.erase(0, p + 1); } } inline void DocBookOutput::printShortArg(Arg* a) { std::string lt = "<"; std::string gt = ">"; std::string id = a->shortID(); substituteSpecialChars(id,'<',lt); substituteSpecialChars(id,'>',gt); removeChar(id,'['); removeChar(id,']'); std::string choice = "opt"; if ( a->isRequired() ) choice = "plain"; std::cout << "acceptsMultipleValues() ) std::cout << " rep='repeat'"; std::cout << '>'; if ( !a->getFlag().empty() ) std::cout << a->flagStartChar() << a->getFlag(); else std::cout << a->nameStartString() << a->getName(); if ( a->isValueRequired() ) { std::string arg = a->shortID(); removeChar(arg,'['); removeChar(arg,']'); removeChar(arg,'<'); removeChar(arg,'>'); arg.erase(0, arg.find_last_of(theDelimiter) + 1); std::cout << theDelimiter; std::cout << "" << arg << ""; } std::cout << "" << std::endl; } inline void DocBookOutput::printLongArg(Arg* a) { std::string lt = "<"; std::string gt = ">"; std::string desc = a->getDescription(); substituteSpecialChars(desc,'<',lt); substituteSpecialChars(desc,'>',gt); std::cout << "" << std::endl; if ( !a->getFlag().empty() ) { std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; } std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << desc << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; std::cout << "" << std::endl; } } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/HelpVisitor.h ================================================ /****************************************************************************** * * file: HelpVisitor.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_HELP_VISITOR_H #define TCLAP_HELP_VISITOR_H #include #include #include namespace TCLAP { /** * A Visitor object that calls the usage method of the given CmdLineOutput * object for the specified CmdLine object. */ class HelpVisitor: public Visitor { private: /** * Prevent accidental copying. */ HelpVisitor(const HelpVisitor& rhs); HelpVisitor& operator=(const HelpVisitor& rhs); protected: /** * The CmdLine the output will be generated for. */ CmdLineInterface* _cmd; /** * The output object. */ CmdLineOutput** _out; public: /** * Constructor. * \param cmd - The CmdLine the output will be generated for. * \param out - The type of output. */ HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out) : Visitor(), _cmd( cmd ), _out( out ) { } /** * Calls the usage method of the CmdLineOutput for the * specified CmdLine. */ void visit() { (*_out)->usage(*_cmd); throw ExitException(0); } }; } #endif ================================================ FILE: libs/tclap/include/tclap/IgnoreRestVisitor.h ================================================ /****************************************************************************** * * file: IgnoreRestVisitor.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_IGNORE_REST_VISITOR_H #define TCLAP_IGNORE_REST_VISITOR_H #include #include namespace TCLAP { /** * A Vistor that tells the CmdLine to begin ignoring arguments after * this one is parsed. */ class IgnoreRestVisitor: public Visitor { public: /** * Constructor. */ IgnoreRestVisitor() : Visitor() {} /** * Sets Arg::_ignoreRest. */ void visit() { Arg::beginIgnoring(); } }; } #endif ================================================ FILE: libs/tclap/include/tclap/MultiArg.h ================================================ /****************************************************************************** * * file: MultiArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_MULTIPLE_ARGUMENT_H #define TCLAP_MULTIPLE_ARGUMENT_H #include #include #include #include namespace TCLAP { /** * An argument that allows multiple values of type T to be specified. Very * similar to a ValueArg, except a vector of values will be returned * instead of just one. */ template class MultiArg : public Arg { public: typedef std::vector container_type; typedef typename container_type::iterator iterator; typedef typename container_type::const_iterator const_iterator; protected: /** * The list of values parsed from the CmdLine. */ std::vector _values; /** * The description of type T to be used in the usage. */ std::string _typeDesc; /** * A list of constraint on this Arg. */ Constraint* _constraint; /** * Extracts the value from the string. * Attempts to parse string as type T, if this fails an exception * is thrown. * \param val - The string to be read. */ void _extractValue( const std::string& val ); /** * Used by XorHandler to decide whether to keep parsing for this arg. */ bool _allowMore; public: /** * Constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, Visitor* v = NULL); /** * Constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, CmdLineInterface& parser, Visitor* v = NULL ); /** * Constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, Constraint* constraint, Visitor* v = NULL ); /** * Constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, Constraint* constraint, CmdLineInterface& parser, Visitor* v = NULL ); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. It knows the difference * between labeled and unlabeled. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed from main(). */ virtual bool processArg(int* i, std::vector& args); /** * Returns a vector of type T containing the values parsed from * the command line. */ const std::vector& getValue(); /** * Returns an iterator over the values parsed from the command * line. */ const_iterator begin() const { return _values.begin(); } /** * Returns the end of the values parsed from the command * line. */ const_iterator end() const { return _values.end(); } /** * Returns the a short id string. Used in the usage. * \param val - value to be used. */ virtual std::string shortID(const std::string& val="val") const; /** * Returns the a long id string. Used in the usage. * \param val - value to be used. */ virtual std::string longID(const std::string& val="val") const; /** * Once we've matched the first value, then the arg is no longer * required. */ virtual bool isRequired() const; virtual bool allowMore(); virtual void reset(); private: /** * Prevent accidental copying */ MultiArg(const MultiArg& rhs); MultiArg& operator=(const MultiArg& rhs); }; template MultiArg::MultiArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, Visitor* v) : Arg( flag, name, desc, req, true, v ), _values(std::vector()), _typeDesc( typeDesc ), _constraint( NULL ), _allowMore(false) { _acceptsMultipleValues = true; } template MultiArg::MultiArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, CmdLineInterface& parser, Visitor* v) : Arg( flag, name, desc, req, true, v ), _values(std::vector()), _typeDesc( typeDesc ), _constraint( NULL ), _allowMore(false) { parser.add( this ); _acceptsMultipleValues = true; } /** * */ template MultiArg::MultiArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, Constraint* constraint, Visitor* v) : Arg( flag, name, desc, req, true, v ), _values(std::vector()), _typeDesc( constraint->shortID() ), _constraint( constraint ), _allowMore(false) { _acceptsMultipleValues = true; } template MultiArg::MultiArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, Constraint* constraint, CmdLineInterface& parser, Visitor* v) : Arg( flag, name, desc, req, true, v ), _values(std::vector()), _typeDesc( constraint->shortID() ), _constraint( constraint ), _allowMore(false) { parser.add( this ); _acceptsMultipleValues = true; } template const std::vector& MultiArg::getValue() { return _values; } template bool MultiArg::processArg(int *i, std::vector& args) { if ( _ignoreable && Arg::ignoreRest() ) return false; if ( _hasBlanks( args[*i] ) ) return false; std::string flag = args[*i]; std::string value = ""; trimFlag( flag, value ); if ( argMatches( flag ) ) { if ( Arg::delimiter() != ' ' && value == "" ) throw( ArgParseException( "Couldn't find delimiter for this argument!", toString() ) ); // always take the first one, regardless of start string if ( value == "" ) { (*i)++; if ( static_cast(*i) < args.size() ) _extractValue( args[*i] ); else throw( ArgParseException("Missing a value for this argument!", toString() ) ); } else _extractValue( value ); /* // continuing taking the args until we hit one with a start string while ( (unsigned int)(*i)+1 < args.size() && args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) _extractValue( args[++(*i)] ); */ _alreadySet = true; _checkWithVisitor(); return true; } else return false; } /** * */ template std::string MultiArg::shortID(const std::string& val) const { static_cast(val); // Ignore input, don't warn return Arg::shortID(_typeDesc) + " ... "; } /** * */ template std::string MultiArg::longID(const std::string& val) const { static_cast(val); // Ignore input, don't warn return Arg::longID(_typeDesc) + " (accepted multiple times)"; } /** * Once we've matched the first value, then the arg is no longer * required. */ template bool MultiArg::isRequired() const { if ( _required ) { if ( _values.size() > 1 ) return false; else return true; } else return false; } template void MultiArg::_extractValue( const std::string& val ) { try { T tmp; ExtractValue(tmp, val, typename ArgTraits::ValueCategory()); _values.push_back(tmp); } catch( ArgParseException &e) { throw ArgParseException(e.error(), toString()); } if ( _constraint != NULL ) if ( ! _constraint->check( _values.back() ) ) throw( CmdLineParseException( "Value '" + val + "' does not meet constraint: " + _constraint->description(), toString() ) ); } template bool MultiArg::allowMore() { bool am = _allowMore; _allowMore = true; return am; } template void MultiArg::reset() { Arg::reset(); _values.clear(); } } // namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/MultiSwitchArg.h ================================================ /****************************************************************************** * * file: MultiSwitchArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * Copyright (c) 2005, Michael E. Smoot, Daniel Aarno, Erik Zeek. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_MULTI_SWITCH_ARG_H #define TCLAP_MULTI_SWITCH_ARG_H #include #include #include namespace TCLAP { /** * A multiple switch argument. If the switch is set on the command line, then * the getValue method will return the number of times the switch appears. */ class MultiSwitchArg : public SwitchArg { protected: /** * The value of the switch. */ int _value; /** * Used to support the reset() method so that ValueArg can be * reset to their constructed value. */ int _default; public: /** * MultiSwitchArg constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param init - Optional. The initial/default value of this Arg. * Defaults to 0. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiSwitchArg(const std::string& flag, const std::string& name, const std::string& desc, int init = 0, Visitor* v = NULL); /** * MultiSwitchArg constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param parser - A CmdLine parser object to add this Arg to * \param init - Optional. The initial/default value of this Arg. * Defaults to 0. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiSwitchArg(const std::string& flag, const std::string& name, const std::string& desc, CmdLineInterface& parser, int init = 0, Visitor* v = NULL); /** * Handles the processing of the argument. * This re-implements the SwitchArg version of this method to set the * _value of the argument appropriately. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed * in from main(). */ virtual bool processArg(int* i, std::vector& args); /** * Returns int, the number of times the switch has been set. */ int getValue(); /** * Returns the shortID for this Arg. */ std::string shortID(const std::string& val) const; /** * Returns the longID for this Arg. */ std::string longID(const std::string& val) const; void reset(); }; ////////////////////////////////////////////////////////////////////// //BEGIN MultiSwitchArg.cpp ////////////////////////////////////////////////////////////////////// inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, const std::string& name, const std::string& desc, int init, Visitor* v ) : SwitchArg(flag, name, desc, false, v), _value( init ), _default( init ) { } inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, const std::string& name, const std::string& desc, CmdLineInterface& parser, int init, Visitor* v ) : SwitchArg(flag, name, desc, false, v), _value( init ), _default( init ) { parser.add( this ); } inline int MultiSwitchArg::getValue() { return _value; } inline bool MultiSwitchArg::processArg(int *i, std::vector& args) { if ( _ignoreable && Arg::ignoreRest() ) return false; if ( argMatches( args[*i] )) { // so the isSet() method will work _alreadySet = true; // Matched argument: increment value. ++_value; _checkWithVisitor(); return true; } else if ( combinedSwitchesMatch( args[*i] ) ) { // so the isSet() method will work _alreadySet = true; // Matched argument: increment value. ++_value; // Check for more in argument and increment value. while ( combinedSwitchesMatch( args[*i] ) ) ++_value; _checkWithVisitor(); return false; } else return false; } inline std::string MultiSwitchArg::shortID(const std::string& val) const { return Arg::shortID(val) + " ... "; } inline std::string MultiSwitchArg::longID(const std::string& val) const { return Arg::longID(val) + " (accepted multiple times)"; } inline void MultiSwitchArg::reset() { MultiSwitchArg::_value = MultiSwitchArg::_default; } ////////////////////////////////////////////////////////////////////// //END MultiSwitchArg.cpp ////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/OptionalUnlabeledTracker.h ================================================ /****************************************************************************** * * file: OptionalUnlabeledTracker.h * * Copyright (c) 2005, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_OPTIONAL_UNLABELED_TRACKER_H #define TCLAP_OPTIONAL_UNLABELED_TRACKER_H #include namespace TCLAP { class OptionalUnlabeledTracker { public: static void check( bool req, const std::string& argName ); static void gotOptional() { alreadyOptionalRef() = true; } static bool& alreadyOptional() { return alreadyOptionalRef(); } private: static bool& alreadyOptionalRef() { static bool ct = false; return ct; } }; inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName ) { if ( OptionalUnlabeledTracker::alreadyOptional() ) throw( SpecificationException( "You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg", argName ) ); if ( !req ) OptionalUnlabeledTracker::gotOptional(); } } // namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/StandardTraits.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: StandardTraits.h * * Copyright (c) 2007, Daniel Aarno, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ // This is an internal tclap file, you should probably not have to // include this directly #ifndef TCLAP_STANDARD_TRAITS_H #define TCLAP_STANDARD_TRAITS_H #ifdef HAVE_CONFIG_H #include // To check for long long #endif // If Microsoft has already typedef'd wchar_t as an unsigned // short, then compiles will break because it's as if we're // creating ArgTraits twice for unsigned short. Thus... #ifdef _MSC_VER #ifndef _NATIVE_WCHAR_T_DEFINED #define TCLAP_DONT_DECLARE_WCHAR_T_ARGTRAITS #endif #endif namespace TCLAP { // ====================================================================== // Integer types // ====================================================================== /** * longs have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; /** * ints have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; /** * shorts have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; /** * chars have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; #ifdef HAVE_LONG_LONG /** * long longs have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; #endif // ====================================================================== // Unsigned integer types // ====================================================================== /** * unsigned longs have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; /** * unsigned ints have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; /** * unsigned shorts have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; /** * unsigned chars have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; // Microsoft implements size_t awkwardly. #if defined(_MSC_VER) && defined(_M_X64) /** * size_ts have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; #endif #ifdef HAVE_LONG_LONG /** * unsigned long longs have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; #endif // ====================================================================== // Float types // ====================================================================== /** * floats have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; /** * doubles have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; // ====================================================================== // Other types // ====================================================================== /** * bools have value-like semantics. */ template<> struct ArgTraits { typedef ValueLike ValueCategory; }; /** * wchar_ts have value-like semantics. */ #ifndef TCLAP_DONT_DECLARE_WCHAR_T_ARGTRAITS template<> struct ArgTraits { typedef ValueLike ValueCategory; }; #endif /** * Strings have string like argument traits. */ template<> struct ArgTraits { typedef StringLike ValueCategory; }; template void SetString(T &dst, const std::string &src) { dst = src; } } // namespace #endif ================================================ FILE: libs/tclap/include/tclap/StdOutput.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: StdOutput.h * * Copyright (c) 2004, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_STDCMDLINEOUTPUT_H #define TCLAP_STDCMDLINEOUTPUT_H #include #include #include #include #include #include #include #include #include namespace TCLAP { /** * A class that isolates any output from the CmdLine object so that it * may be easily modified. */ class StdOutput : public CmdLineOutput { public: /** * Prints the usage to stdout. Can be overridden to * produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void usage(CmdLineInterface& c); /** * Prints the version to stdout. Can be overridden * to produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void version(CmdLineInterface& c); /** * Prints (to stderr) an error message, short usage * Can be overridden to produce alternative behavior. * \param c - The CmdLine object the output is generated for. * \param e - The ArgException that caused the failure. */ virtual void failure(CmdLineInterface& c, ArgException& e ); protected: /** * Writes a brief usage message with short args. * \param c - The CmdLine object the output is generated for. * \param os - The stream to write the message to. */ void _shortUsage( CmdLineInterface& c, std::ostream& os ) const; /** * Writes a longer usage message with long and short args, * provides descriptions and prints message. * \param c - The CmdLine object the output is generated for. * \param os - The stream to write the message to. */ void _longUsage( CmdLineInterface& c, std::ostream& os ) const; /** * This function inserts line breaks and indents long strings * according the params input. It will only break lines at spaces, * commas and pipes. * \param os - The stream to be printed to. * \param s - The string to be printed. * \param maxWidth - The maxWidth allowed for the output line. * \param indentSpaces - The number of spaces to indent the first line. * \param secondLineOffset - The number of spaces to indent the second * and all subsequent lines in addition to indentSpaces. */ void spacePrint( std::ostream& os, const std::string& s, int maxWidth, int indentSpaces, int secondLineOffset ) const; }; inline void StdOutput::version(CmdLineInterface& _cmd) { std::string progName = _cmd.getProgramName(); std::string xversion = _cmd.getVersion(); std::cout << std::endl << progName << " version: " << xversion << std::endl << std::endl; } inline void StdOutput::usage(CmdLineInterface& _cmd ) { std::cout << std::endl << "USAGE: " << std::endl << std::endl; _shortUsage( _cmd, std::cout ); std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl; _longUsage( _cmd, std::cout ); std::cout << std::endl; } inline void StdOutput::failure( CmdLineInterface& _cmd, ArgException& e ) { std::string progName = _cmd.getProgramName(); std::cerr << "PARSE ERROR: " << e.argId() << std::endl << " " << e.error() << std::endl << std::endl; if ( _cmd.hasHelpAndVersion() ) { std::cerr << "Brief USAGE: " << std::endl; _shortUsage( _cmd, std::cerr ); std::cerr << std::endl << "For complete USAGE and HELP type: " << std::endl << " " << progName << " --help" << std::endl << std::endl; } else usage(_cmd); throw ExitException(1); } inline void StdOutput::_shortUsage( CmdLineInterface& _cmd, std::ostream& os ) const { std::list argList = _cmd.getArgList(); std::string progName = _cmd.getProgramName(); XorHandler xorHandler = _cmd.getXorHandler(); std::vector< std::vector > xorList = xorHandler.getXorList(); std::string s = progName + " "; // first the xor for ( int i = 0; static_cast(i) < xorList.size(); i++ ) { s += " {"; for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end(); it++ ) s += (*it)->shortID() + "|"; s[s.length()-1] = '}'; } // then the rest for (ArgListIterator it = argList.begin(); it != argList.end(); it++) if ( !xorHandler.contains( (*it) ) ) s += " " + (*it)->shortID(); // if the program name is too long, then adjust the second line offset int secondLineOffset = static_cast(progName.length()) + 2; if ( secondLineOffset > 75/2 ) secondLineOffset = static_cast(75/2); spacePrint( os, s, 75, 3, secondLineOffset ); } inline void StdOutput::_longUsage( CmdLineInterface& _cmd, std::ostream& os ) const { std::list argList = _cmd.getArgList(); std::string message = _cmd.getMessage(); XorHandler xorHandler = _cmd.getXorHandler(); std::vector< std::vector > xorList = xorHandler.getXorList(); // first the xor for ( int i = 0; static_cast(i) < xorList.size(); i++ ) { for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end(); it++ ) { spacePrint( os, (*it)->longID(), 75, 3, 3 ); spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); if ( it+1 != xorList[i].end() ) spacePrint(os, "-- OR --", 75, 9, 0); } os << std::endl << std::endl; } // then the rest for (ArgListIterator it = argList.begin(); it != argList.end(); it++) if ( !xorHandler.contains( (*it) ) ) { spacePrint( os, (*it)->longID(), 75, 3, 3 ); spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); os << std::endl; } os << std::endl; spacePrint( os, message, 75, 3, 0 ); } inline void StdOutput::spacePrint( std::ostream& os, const std::string& s, int maxWidth, int indentSpaces, int secondLineOffset ) const { int len = static_cast(s.length()); if ( (len + indentSpaces > maxWidth) && maxWidth > 0 ) { int allowedLen = maxWidth - indentSpaces; int start = 0; while ( start < len ) { // find the substring length // int stringLen = std::min( len - start, allowedLen ); // doing it this way to support a VisualC++ 2005 bug using namespace std; int stringLen = min( len - start, allowedLen ); // trim the length so it doesn't end in middle of a word if ( stringLen == allowedLen ) while ( stringLen >= 0 && s[stringLen+start] != ' ' && s[stringLen+start] != ',' && s[stringLen+start] != '|' ) stringLen--; // ok, the word is longer than the line, so just split // wherever the line ends if ( stringLen <= 0 ) stringLen = allowedLen; // check for newlines for ( int i = 0; i < stringLen; i++ ) if ( s[start+i] == '\n' ) stringLen = i+1; // print the indent for ( int i = 0; i < indentSpaces; i++ ) os << " "; if ( start == 0 ) { // handle second line offsets indentSpaces += secondLineOffset; // adjust allowed len allowedLen -= secondLineOffset; } os << s.substr(start,stringLen) << std::endl; // so we don't start a line with a space while ( s[stringLen+start] == ' ' && start < len ) start++; start += stringLen; } } else { for ( int i = 0; i < indentSpaces; i++ ) os << " "; os << s << std::endl; } } } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/SwitchArg.h ================================================ /****************************************************************************** * * file: SwitchArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_SWITCH_ARG_H #define TCLAP_SWITCH_ARG_H #include #include #include namespace TCLAP { /** * A simple switch argument. If the switch is set on the command line, then * the getValue method will return the opposite of the default value for the * switch. */ class SwitchArg : public Arg { protected: /** * The value of the switch. */ bool _value; /** * Used to support the reset() method so that ValueArg can be * reset to their constructed value. */ bool _default; public: /** * SwitchArg constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param def - The default value for this Switch. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ SwitchArg(const std::string& flag, const std::string& name, const std::string& desc, bool def = false, Visitor* v = NULL); /** * SwitchArg constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param parser - A CmdLine parser object to add this Arg to * \param def - The default value for this Switch. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ SwitchArg(const std::string& flag, const std::string& name, const std::string& desc, CmdLineInterface& parser, bool def = false, Visitor* v = NULL); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed * in from main(). */ virtual bool processArg(int* i, std::vector& args); /** * Checks a string to see if any of the chars in the string * match the flag for this Switch. */ bool combinedSwitchesMatch(std::string& combined); /** * Returns bool, whether or not the switch has been set. */ bool getValue(); virtual void reset(); private: /** * Checks to see if we've found the last match in * a combined string. */ bool lastCombined(std::string& combined); /** * Does the common processing of processArg. */ void commonProcessing(); }; ////////////////////////////////////////////////////////////////////// //BEGIN SwitchArg.cpp ////////////////////////////////////////////////////////////////////// inline SwitchArg::SwitchArg(const std::string& flag, const std::string& name, const std::string& desc, bool default_val, Visitor* v ) : Arg(flag, name, desc, false, false, v), _value( default_val ), _default( default_val ) { } inline SwitchArg::SwitchArg(const std::string& flag, const std::string& name, const std::string& desc, CmdLineInterface& parser, bool default_val, Visitor* v ) : Arg(flag, name, desc, false, false, v), _value( default_val ), _default(default_val) { parser.add( this ); } inline bool SwitchArg::getValue() { return _value; } inline bool SwitchArg::lastCombined(std::string& combinedSwitches ) { for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) if ( combinedSwitches[i] != Arg::blankChar() ) return false; return true; } inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches ) { // make sure this is actually a combined switch if ( combinedSwitches.length() > 0 && combinedSwitches[0] != Arg::flagStartString()[0] ) return false; // make sure it isn't a long name if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) == Arg::nameStartString() ) return false; // make sure the delimiter isn't in the string if ( combinedSwitches.find_first_of( Arg::delimiter() ) != std::string::npos ) return false; // ok, we're not specifying a ValueArg, so we know that we have // a combined switch list. for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) if ( _flag.length() > 0 && combinedSwitches[i] == _flag[0] && _flag[0] != Arg::flagStartString()[0] ) { // update the combined switches so this one is no longer present // this is necessary so that no unlabeled args are matched // later in the processing. //combinedSwitches.erase(i,1); combinedSwitches[i] = Arg::blankChar(); return true; } // none of the switches passed in the list match. return false; } inline void SwitchArg::commonProcessing() { if ( _xorSet ) throw(CmdLineParseException( "Mutually exclusive argument already set!", toString())); if ( _alreadySet ) throw(CmdLineParseException("Argument already set!", toString())); _alreadySet = true; if ( _value == true ) _value = false; else _value = true; _checkWithVisitor(); } inline bool SwitchArg::processArg(int *i, std::vector& args) { if ( _ignoreable && Arg::ignoreRest() ) return false; // if the whole string matches the flag or name string if ( argMatches( args[*i] ) ) { commonProcessing(); return true; } // if a substring matches the flag as part of a combination else if ( combinedSwitchesMatch( args[*i] ) ) { // check again to ensure we don't misinterpret // this as a MultiSwitchArg if ( combinedSwitchesMatch( args[*i] ) ) throw(CmdLineParseException("Argument already set!", toString())); commonProcessing(); // We only want to return true if we've found the last combined // match in the string, otherwise we return true so that other // switches in the combination will have a chance to match. return lastCombined( args[*i] ); } else return false; } inline void SwitchArg::reset() { Arg::reset(); _value = _default; } ////////////////////////////////////////////////////////////////////// //End SwitchArg.cpp ////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/UnlabeledMultiArg.h ================================================ /****************************************************************************** * * file: UnlabeledMultiArg.h * * Copyright (c) 2003, Michael E. Smoot. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H #define TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H #include #include #include #include namespace TCLAP { /** * Just like a MultiArg, except that the arguments are unlabeled. Basically, * this Arg will slurp up everything that hasn't been matched to another * Arg. */ template class UnlabeledMultiArg : public MultiArg { // If compiler has two stage name lookup (as gcc >= 3.4 does) // this is requried to prevent undef. symbols using MultiArg::_ignoreable; using MultiArg::_hasBlanks; using MultiArg::_extractValue; using MultiArg::_typeDesc; using MultiArg::_name; using MultiArg::_description; using MultiArg::_alreadySet; using MultiArg::toString; public: /** * Constructor. * \param name - The name of the Arg. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param ignoreable - Whether or not this argument can be ignored * using the "--" flag. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ UnlabeledMultiArg( const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, bool ignoreable = false, Visitor* v = NULL ); /** * Constructor. * \param name - The name of the Arg. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Whether or not this argument can be ignored * using the "--" flag. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ UnlabeledMultiArg( const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL ); /** * Constructor. * \param name - The name of the Arg. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param ignoreable - Whether or not this argument can be ignored * using the "--" flag. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ UnlabeledMultiArg( const std::string& name, const std::string& desc, bool req, Constraint* constraint, bool ignoreable = false, Visitor* v = NULL ); /** * Constructor. * \param name - The name of the Arg. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Whether or not this argument can be ignored * using the "--" flag. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ UnlabeledMultiArg( const std::string& name, const std::string& desc, bool req, Constraint* constraint, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL ); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. It knows the difference * between labeled and unlabeled. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed from main(). */ virtual bool processArg(int* i, std::vector& args); /** * Returns the a short id string. Used in the usage. * \param val - value to be used. */ virtual std::string shortID(const std::string& val="val") const; /** * Returns the a long id string. Used in the usage. * \param val - value to be used. */ virtual std::string longID(const std::string& val="val") const; /** * Opertor ==. * \param a - The Arg to be compared to this. */ virtual bool operator==(const Arg& a) const; /** * Pushes this to back of list rather than front. * \param argList - The list this should be added to. */ virtual void addToList( std::list& argList ) const; }; template UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, bool ignoreable, Visitor* v) : MultiArg("", name, desc, req, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(true, toString()); } template UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable, Visitor* v) : MultiArg("", name, desc, req, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(true, toString()); parser.add( this ); } template UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, const std::string& desc, bool req, Constraint* constraint, bool ignoreable, Visitor* v) : MultiArg("", name, desc, req, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(true, toString()); } template UnlabeledMultiArg::UnlabeledMultiArg(const std::string& name, const std::string& desc, bool req, Constraint* constraint, CmdLineInterface& parser, bool ignoreable, Visitor* v) : MultiArg("", name, desc, req, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(true, toString()); parser.add( this ); } template bool UnlabeledMultiArg::processArg(int *i, std::vector& args) { if ( _hasBlanks( args[*i] ) ) return false; // never ignore an unlabeled multi arg // always take the first value, regardless of the start string _extractValue( args[(*i)] ); /* // continue taking args until we hit the end or a start string while ( (unsigned int)(*i)+1 < args.size() && args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) _extractValue( args[++(*i)] ); */ _alreadySet = true; return true; } template std::string UnlabeledMultiArg::shortID(const std::string& val) const { static_cast(val); // Ignore input, don't warn return std::string("<") + _typeDesc + "> ..."; } template std::string UnlabeledMultiArg::longID(const std::string& val) const { static_cast(val); // Ignore input, don't warn return std::string("<") + _typeDesc + "> (accepted multiple times)"; } template bool UnlabeledMultiArg::operator==(const Arg& a) const { if ( _name == a.getName() || _description == a.getDescription() ) return true; else return false; } template void UnlabeledMultiArg::addToList( std::list& argList ) const { argList.push_back( const_cast(static_cast(this)) ); } } #endif ================================================ FILE: libs/tclap/include/tclap/UnlabeledValueArg.h ================================================ /****************************************************************************** * * file: UnlabeledValueArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_UNLABELED_VALUE_ARGUMENT_H #define TCLAP_UNLABELED_VALUE_ARGUMENT_H #include #include #include #include namespace TCLAP { /** * The basic unlabeled argument that parses a value. * This is a template class, which means the type T defines the type * that a given object will attempt to parse when an UnlabeledValueArg * is reached in the list of args that the CmdLine iterates over. */ template class UnlabeledValueArg : public ValueArg { // If compiler has two stage name lookup (as gcc >= 3.4 does) // this is requried to prevent undef. symbols using ValueArg::_ignoreable; using ValueArg::_hasBlanks; using ValueArg::_extractValue; using ValueArg::_typeDesc; using ValueArg::_name; using ValueArg::_description; using ValueArg::_alreadySet; using ValueArg::toString; public: /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, bool ignoreable = false, Visitor* v = NULL); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL ); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, Constraint* constraint, bool ignoreable = false, Visitor* v = NULL ); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, Constraint* constraint, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. Handling specific to * unlabled arguments. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. */ virtual bool processArg(int* i, std::vector& args); /** * Overrides shortID for specific behavior. */ virtual std::string shortID(const std::string& val="val") const; /** * Overrides longID for specific behavior. */ virtual std::string longID(const std::string& val="val") const; /** * Overrides operator== for specific behavior. */ virtual bool operator==(const Arg& a ) const; /** * Instead of pushing to the front of list, push to the back. * \param argList - The list to add this to. */ virtual void addToList( std::list& argList ) const; }; /** * Constructor implemenation. */ template UnlabeledValueArg::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, bool ignoreable, Visitor* v) : ValueArg("", name, desc, req, val, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); } template UnlabeledValueArg::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable, Visitor* v) : ValueArg("", name, desc, req, val, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); parser.add( this ); } /** * Constructor implemenation. */ template UnlabeledValueArg::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, Constraint* constraint, bool ignoreable, Visitor* v) : ValueArg("", name, desc, req, val, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); } template UnlabeledValueArg::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, Constraint* constraint, CmdLineInterface& parser, bool ignoreable, Visitor* v) : ValueArg("", name, desc, req, val, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); parser.add( this ); } /** * Implementation of processArg(). */ template bool UnlabeledValueArg::processArg(int *i, std::vector& args) { if ( _alreadySet ) return false; if ( _hasBlanks( args[*i] ) ) return false; // never ignore an unlabeled arg _extractValue( args[*i] ); _alreadySet = true; return true; } /** * Overriding shortID for specific output. */ template std::string UnlabeledValueArg::shortID(const std::string& val) const { static_cast(val); // Ignore input, don't warn return std::string("<") + _typeDesc + ">"; } /** * Overriding longID for specific output. */ template std::string UnlabeledValueArg::longID(const std::string& val) const { static_cast(val); // Ignore input, don't warn // Ideally we would like to be able to use RTTI to return the name // of the type required for this argument. However, g++ at least, // doesn't appear to return terribly useful "names" of the types. return std::string("<") + _typeDesc + ">"; } /** * Overriding operator== for specific behavior. */ template bool UnlabeledValueArg::operator==(const Arg& a ) const { if ( _name == a.getName() || _description == a.getDescription() ) return true; else return false; } template void UnlabeledValueArg::addToList( std::list& argList ) const { argList.push_back( const_cast(static_cast(this)) ); } } #endif ================================================ FILE: libs/tclap/include/tclap/ValueArg.h ================================================ /****************************************************************************** * * file: ValueArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_VALUE_ARGUMENT_H #define TCLAP_VALUE_ARGUMENT_H #include #include #include #include namespace TCLAP { /** * The basic labeled argument that parses a value. * This is a template class, which means the type T defines the type * that a given object will attempt to parse when the flag/name is matched * on the command line. While there is nothing stopping you from creating * an unflagged ValueArg, it is unwise and would cause significant problems. * Instead use an UnlabeledValueArg. */ template class ValueArg : public Arg { protected: /** * The value parsed from the command line. * Can be of any type, as long as the >> operator for the type * is defined. */ T _value; /** * Used to support the reset() method so that ValueArg can be * reset to their constructed value. */ T _default; /** * A human readable description of the type to be parsed. * This is a hack, plain and simple. Ideally we would use RTTI to * return the name of type T, but until there is some sort of * consistent support for human readable names, we are left to our * own devices. */ std::string _typeDesc; /** * A Constraint this Arg must conform to. */ Constraint* _constraint; /** * Extracts the value from the string. * Attempts to parse string as type T, if this fails an exception * is thrown. * \param val - value to be parsed. */ void _extractValue( const std::string& val ); public: /** * Labeled ValueArg constructor. * You could conceivably call this constructor with a blank flag, * but that would make you a bad person. It would also cause * an exception to be thrown. If you want an unlabeled argument, * use the other constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ ValueArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, Visitor* v = NULL); /** * Labeled ValueArg constructor. * You could conceivably call this constructor with a blank flag, * but that would make you a bad person. It would also cause * an exception to be thrown. If you want an unlabeled argument, * use the other constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ ValueArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, CmdLineInterface& parser, Visitor* v = NULL ); /** * Labeled ValueArg constructor. * You could conceivably call this constructor with a blank flag, * but that would make you a bad person. It would also cause * an exception to be thrown. If you want an unlabeled argument, * use the other constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ ValueArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, T value, Constraint* constraint, CmdLineInterface& parser, Visitor* v = NULL ); /** * Labeled ValueArg constructor. * You could conceivably call this constructor with a blank flag, * but that would make you a bad person. It would also cause * an exception to be thrown. If you want an unlabeled argument, * use the other constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ ValueArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, T value, Constraint* constraint, Visitor* v = NULL ); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. It knows the difference * between labeled and unlabeled. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed * in from main(). */ virtual bool processArg(int* i, std::vector& args); /** * Returns the value of the argument. */ T& getValue() ; /** * Specialization of shortID. * \param val - value to be used. */ virtual std::string shortID(const std::string& val = "val") const; /** * Specialization of longID. * \param val - value to be used. */ virtual std::string longID(const std::string& val = "val") const; virtual void reset() ; private: /** * Prevent accidental copying */ ValueArg(const ValueArg& rhs); ValueArg& operator=(const ValueArg& rhs); }; /** * Constructor implementation. */ template ValueArg::ValueArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, Visitor* v) : Arg(flag, name, desc, req, true, v), _value( val ), _default( val ), _typeDesc( typeDesc ), _constraint( NULL ) { } template ValueArg::ValueArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, CmdLineInterface& parser, Visitor* v) : Arg(flag, name, desc, req, true, v), _value( val ), _default( val ), _typeDesc( typeDesc ), _constraint( NULL ) { parser.add( this ); } template ValueArg::ValueArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, T val, Constraint* constraint, Visitor* v) : Arg(flag, name, desc, req, true, v), _value( val ), _default( val ), _typeDesc( constraint->shortID() ), _constraint( constraint ) { } template ValueArg::ValueArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, T val, Constraint* constraint, CmdLineInterface& parser, Visitor* v) : Arg(flag, name, desc, req, true, v), _value( val ), _default( val ), _typeDesc( constraint->shortID() ), _constraint( constraint ) { parser.add( this ); } /** * Implementation of getValue(). */ template T& ValueArg::getValue() { return _value; } /** * Implementation of processArg(). */ template bool ValueArg::processArg(int *i, std::vector& args) { if ( _ignoreable && Arg::ignoreRest() ) return false; if ( _hasBlanks( args[*i] ) ) return false; std::string flag = args[*i]; std::string value = ""; trimFlag( flag, value ); if ( argMatches( flag ) ) { if ( _alreadySet ) { if ( _xorSet ) throw( CmdLineParseException( "Mutually exclusive argument already set!", toString()) ); else throw( CmdLineParseException("Argument already set!", toString()) ); } if ( Arg::delimiter() != ' ' && value == "" ) throw( ArgParseException( "Couldn't find delimiter for this argument!", toString() ) ); if ( value == "" ) { (*i)++; if ( static_cast(*i) < args.size() ) _extractValue( args[*i] ); else throw( ArgParseException("Missing a value for this argument!", toString() ) ); } else _extractValue( value ); _alreadySet = true; _checkWithVisitor(); return true; } else return false; } /** * Implementation of shortID. */ template std::string ValueArg::shortID(const std::string& val) const { static_cast(val); // Ignore input, don't warn return Arg::shortID( _typeDesc ); } /** * Implementation of longID. */ template std::string ValueArg::longID(const std::string& val) const { static_cast(val); // Ignore input, don't warn return Arg::longID( _typeDesc ); } template void ValueArg::_extractValue( const std::string& val ) { try { ExtractValue(_value, val, typename ArgTraits::ValueCategory()); } catch( ArgParseException &e) { throw ArgParseException(e.error(), toString()); } if ( _constraint != NULL ) if ( ! _constraint->check( _value ) ) throw( CmdLineParseException( "Value '" + val + + "' does not meet constraint: " + _constraint->description(), toString() ) ); } template void ValueArg::reset() { Arg::reset(); _value = _default; } } // namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/ValuesConstraint.h ================================================ /****************************************************************************** * * file: ValuesConstraint.h * * Copyright (c) 2005, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_VALUESCONSTRAINT_H #define TCLAP_VALUESCONSTRAINT_H #include #include #include #ifdef HAVE_CONFIG_H #include #else #define HAVE_SSTREAM #endif #if defined(HAVE_SSTREAM) #include #elif defined(HAVE_STRSTREAM) #include #else #error "Need a stringstream (sstream or strstream) to compile!" #endif namespace TCLAP { /** * A Constraint that constrains the Arg to only those values specified * in the constraint. */ template class ValuesConstraint : public Constraint { public: /** * Constructor. * \param allowed - vector of allowed values. */ ValuesConstraint(std::vector& allowed); /** * Virtual destructor. */ virtual ~ValuesConstraint() {} /** * Returns a description of the Constraint. */ virtual std::string description() const; /** * Returns the short ID for the Constraint. */ virtual std::string shortID() const; /** * The method used to verify that the value parsed from the command * line meets the constraint. * \param value - The value that will be checked. */ virtual bool check(const T& value) const; protected: /** * The list of valid values. */ std::vector _allowed; /** * The string used to describe the allowed values of this constraint. */ std::string _typeDesc; }; template ValuesConstraint::ValuesConstraint(std::vector& allowed) : _allowed(allowed), _typeDesc("") { for ( unsigned int i = 0; i < _allowed.size(); i++ ) { #if defined(HAVE_SSTREAM) std::ostringstream os; #elif defined(HAVE_STRSTREAM) std::ostrstream os; #else #error "Need a stringstream (sstream or strstream) to compile!" #endif os << _allowed[i]; std::string temp( os.str() ); if ( i > 0 ) _typeDesc += "|"; _typeDesc += temp; } } template bool ValuesConstraint::check( const T& val ) const { if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() ) return false; else return true; } template std::string ValuesConstraint::shortID() const { return _typeDesc; } template std::string ValuesConstraint::description() const { return _typeDesc; } } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/VersionVisitor.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: VersionVisitor.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_VERSION_VISITOR_H #define TCLAP_VERSION_VISITOR_H #include #include #include namespace TCLAP { /** * A Vistor that will call the version method of the given CmdLineOutput * for the specified CmdLine object and then exit. */ class VersionVisitor: public Visitor { private: /** * Prevent accidental copying */ VersionVisitor(const VersionVisitor& rhs); VersionVisitor& operator=(const VersionVisitor& rhs); protected: /** * The CmdLine of interest. */ CmdLineInterface* _cmd; /** * The output object. */ CmdLineOutput** _out; public: /** * Constructor. * \param cmd - The CmdLine the output is generated for. * \param out - The type of output. */ VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out ) : Visitor(), _cmd( cmd ), _out( out ) { } /** * Calls the version method of the output object using the * specified CmdLine. */ void visit() { (*_out)->version(*_cmd); throw ExitException(0); } }; } #endif ================================================ FILE: libs/tclap/include/tclap/Visitor.h ================================================ /****************************************************************************** * * file: Visitor.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_VISITOR_H #define TCLAP_VISITOR_H namespace TCLAP { /** * A base class that defines the interface for visitors. */ class Visitor { public: /** * Constructor. Does nothing. */ Visitor() { } /** * Destructor. Does nothing. */ virtual ~Visitor() { } /** * Does nothing. Should be overridden by child. */ virtual void visit() { } }; } #endif ================================================ FILE: libs/tclap/include/tclap/XorHandler.h ================================================ /****************************************************************************** * * file: XorHandler.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_XORHANDLER_H #define TCLAP_XORHANDLER_H #include #include #include #include #include namespace TCLAP { /** * This class handles lists of Arg's that are to be XOR'd on the command * line. This is used by CmdLine and you shouldn't ever use it. */ class XorHandler { protected: /** * The list of of lists of Arg's to be or'd together. */ std::vector< std::vector > _orList; public: /** * Constructor. Does nothing. */ XorHandler( ) : _orList(std::vector< std::vector >()) {} /** * Add a list of Arg*'s that will be orred together. * \param ors - list of Arg* that will be xor'd. */ void add( std::vector& ors ); /** * Checks whether the specified Arg is in one of the xor lists and * if it does match one, returns the size of the xor list that the * Arg matched. If the Arg matches, then it also sets the rest of * the Arg's in the list. You shouldn't use this. * \param a - The Arg to be checked. */ int check( const Arg* a ); /** * Returns the XOR specific short usage. */ std::string shortUsage(); /** * Prints the XOR specific long usage. * \param os - Stream to print to. */ void printLongUsage(std::ostream& os); /** * Simply checks whether the Arg is contained in one of the arg * lists. * \param a - The Arg to be checked. */ bool contains( const Arg* a ); std::vector< std::vector >& getXorList(); }; ////////////////////////////////////////////////////////////////////// //BEGIN XOR.cpp ////////////////////////////////////////////////////////////////////// inline void XorHandler::add( std::vector& ors ) { _orList.push_back( ors ); } inline int XorHandler::check( const Arg* a ) { // iterate over each XOR list for ( int i = 0; static_cast(i) < _orList.size(); i++ ) { // if the XOR list contains the arg.. ArgVectorIterator ait = std::find( _orList[i].begin(), _orList[i].end(), a ); if ( ait != _orList[i].end() ) { // first check to see if a mutually exclusive switch // has not already been set for ( ArgVectorIterator it = _orList[i].begin(); it != _orList[i].end(); it++ ) if ( a != (*it) && (*it)->isSet() ) throw(CmdLineParseException( "Mutually exclusive argument already set!", (*it)->toString())); // go through and set each arg that is not a for ( ArgVectorIterator it = _orList[i].begin(); it != _orList[i].end(); it++ ) if ( a != (*it) ) (*it)->xorSet(); // return the number of required args that have now been set if ( (*ait)->allowMore() ) return 0; else return static_cast(_orList[i].size()); } } if ( a->isRequired() ) return 1; else return 0; } inline bool XorHandler::contains( const Arg* a ) { for ( int i = 0; static_cast(i) < _orList.size(); i++ ) for ( ArgVectorIterator it = _orList[i].begin(); it != _orList[i].end(); it++ ) if ( a == (*it) ) return true; return false; } inline std::vector< std::vector >& XorHandler::getXorList() { return _orList; } ////////////////////////////////////////////////////////////////////// //END XOR.cpp ////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif ================================================ FILE: libs/tclap/include/tclap/ZshCompletionOutput.h ================================================ // -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: ZshCompletionOutput.h * * Copyright (c) 2006, Oliver Kiddle * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_ZSHCOMPLETIONOUTPUT_H #define TCLAP_ZSHCOMPLETIONOUTPUT_H #include #include #include #include #include #include #include #include #include namespace TCLAP { /** * A class that generates a Zsh completion function as output from the usage() * method for the given CmdLine and its Args. */ class ZshCompletionOutput : public CmdLineOutput { public: ZshCompletionOutput(); /** * Prints the usage to stdout. Can be overridden to * produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void usage(CmdLineInterface& c); /** * Prints the version to stdout. Can be overridden * to produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void version(CmdLineInterface& c); /** * Prints (to stderr) an error message, short usage * Can be overridden to produce alternative behavior. * \param c - The CmdLine object the output is generated for. * \param e - The ArgException that caused the failure. */ virtual void failure(CmdLineInterface& c, ArgException& e ); protected: void basename( std::string& s ); void quoteSpecialChars( std::string& s ); std::string getMutexList( CmdLineInterface& _cmd, Arg* a ); void printOption( Arg* it, std::string mutex ); void printArg( Arg* it ); std::map common; char theDelimiter; }; ZshCompletionOutput::ZshCompletionOutput() : common(std::map()), theDelimiter('=') { common["host"] = "_hosts"; common["hostname"] = "_hosts"; common["file"] = "_files"; common["filename"] = "_files"; common["user"] = "_users"; common["username"] = "_users"; common["directory"] = "_directories"; common["path"] = "_directories"; common["url"] = "_urls"; } inline void ZshCompletionOutput::version(CmdLineInterface& _cmd) { std::cout << _cmd.getVersion() << std::endl; } inline void ZshCompletionOutput::usage(CmdLineInterface& _cmd ) { std::list argList = _cmd.getArgList(); std::string progName = _cmd.getProgramName(); std::string xversion = _cmd.getVersion(); theDelimiter = _cmd.getDelimiter(); basename(progName); std::cout << "#compdef " << progName << std::endl << std::endl << "# " << progName << " version " << _cmd.getVersion() << std::endl << std::endl << "_arguments -s -S"; for (ArgListIterator it = argList.begin(); it != argList.end(); it++) { if ( (*it)->shortID().at(0) == '<' ) printArg((*it)); else if ( (*it)->getFlag() != "-" ) printOption((*it), getMutexList(_cmd, *it)); } std::cout << std::endl; } inline void ZshCompletionOutput::failure( CmdLineInterface& _cmd, ArgException& e ) { static_cast(_cmd); // unused std::cout << e.what() << std::endl; } inline void ZshCompletionOutput::quoteSpecialChars( std::string& s ) { size_t idx = s.find_last_of(':'); while ( idx != std::string::npos ) { s.insert(idx, 1, '\\'); idx = s.find_last_of(':', idx); } idx = s.find_last_of('\''); while ( idx != std::string::npos ) { s.insert(idx, "'\\'"); if (idx == 0) idx = std::string::npos; else idx = s.find_last_of('\'', --idx); } } inline void ZshCompletionOutput::basename( std::string& s ) { size_t p = s.find_last_of('/'); if ( p != std::string::npos ) { s.erase(0, p + 1); } } inline void ZshCompletionOutput::printArg(Arg* a) { static int count = 1; std::cout << " \\" << std::endl << " '"; if ( a->acceptsMultipleValues() ) std::cout << '*'; else std::cout << count++; std::cout << ':'; if ( !a->isRequired() ) std::cout << ':'; std::cout << a->getName() << ':'; std::map::iterator compArg = common.find(a->getName()); if ( compArg != common.end() ) { std::cout << compArg->second; } else { std::cout << "_guard \"^-*\" " << a->getName(); } std::cout << '\''; } inline void ZshCompletionOutput::printOption(Arg* a, std::string mutex) { std::string flag = a->flagStartChar() + a->getFlag(); std::string name = a->nameStartString() + a->getName(); std::string desc = a->getDescription(); // remove full stop and capitalisation from description as // this is the convention for zsh function if (!desc.compare(0, 12, "(required) ")) { desc.erase(0, 12); } if (!desc.compare(0, 15, "(OR required) ")) { desc.erase(0, 15); } size_t len = desc.length(); if (len && desc.at(--len) == '.') { desc.erase(len); } if (len) { desc.replace(0, 1, 1, tolower(desc.at(0))); } std::cout << " \\" << std::endl << " '" << mutex; if ( a->getFlag().empty() ) { std::cout << name; } else { std::cout << "'{" << flag << ',' << name << "}'"; } if ( theDelimiter == '=' && a->isValueRequired() ) std::cout << "=-"; quoteSpecialChars(desc); std::cout << '[' << desc << ']'; if ( a->isValueRequired() ) { std::string arg = a->shortID(); arg.erase(0, arg.find_last_of(theDelimiter) + 1); if ( arg.at(arg.length()-1) == ']' ) arg.erase(arg.length()-1); if ( arg.at(arg.length()-1) == ']' ) { arg.erase(arg.length()-1); } if ( arg.at(0) == '<' ) { arg.erase(arg.length()-1); arg.erase(0, 1); } size_t p = arg.find('|'); if ( p != std::string::npos ) { do { arg.replace(p, 1, 1, ' '); } while ( (p = arg.find_first_of('|', p)) != std::string::npos ); quoteSpecialChars(arg); std::cout << ": :(" << arg << ')'; } else { std::cout << ':' << arg; std::map::iterator compArg = common.find(arg); if ( compArg != common.end() ) { std::cout << ':' << compArg->second; } } } std::cout << '\''; } inline std::string ZshCompletionOutput::getMutexList( CmdLineInterface& _cmd, Arg* a) { XorHandler xorHandler = _cmd.getXorHandler(); std::vector< std::vector > xorList = xorHandler.getXorList(); if (a->getName() == "help" || a->getName() == "version") { return "(-)"; } std::ostringstream list; if ( a->acceptsMultipleValues() ) { list << '*'; } for ( int i = 0; static_cast(i) < xorList.size(); i++ ) { for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end(); it++) if ( a == (*it) ) { list << '('; for ( ArgVectorIterator iu = xorList[i].begin(); iu != xorList[i].end(); iu++ ) { bool notCur = (*iu) != a; bool hasFlag = !(*iu)->getFlag().empty(); if ( iu != xorList[i].begin() && (notCur || hasFlag) ) list << ' '; if (hasFlag) list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' '; if ( notCur || hasFlag ) list << (*iu)->nameStartString() << (*iu)->getName(); } list << ')'; return list.str(); } } // wasn't found in xor list if (!a->getFlag().empty()) { list << "(" << a->flagStartChar() << a->getFlag() << ' ' << a->nameStartString() << a->getName() << ')'; } return list.str(); } } //namespace TCLAP #endif ================================================ FILE: luaGenerator.bat ================================================ REM call luaGenerator.bat %model% %volumic% %nozzle% %layer% %filament% %ironing% @echo off @echo set_setting_value('printer', 'curvi')> settings.lua @echo set_setting_value('filament_diameter_mm_0', %5)>> settings.lua @echo set_setting_value('nozzle_diameter_mm_0', %3)>> settings.lua @echo set_setting_value('z_layer_height_mm', %4)>> settings.lua @echo set_setting_value('gcode_volumic', %2)>> settings.lua @echo emit(load('%1/after.stl'))>> settings.lua @echo set_service('FilamentSlicer')>> settings.lua @echo run_service('%1.gcode')>> settings.lua ================================================ FILE: luaGenerator.sh ================================================ #luaGenerator.sh %model% %volumic% %nozzle% %layer% %filament% %ironing% echo "set_setting_value('printer', 'curvi')"> settings.lua echo "set_setting_value('filament_diameter_mm_0', $5)">> settings.lua echo "set_setting_value('nozzle_diameter_mm_0', $3)">> settings.lua echo "set_setting_value('z_layer_height_mm', $4)">> settings.lua echo "set_setting_value('gcode_volumic', $2)">> settings.lua echo "emit(load('$1/after.stl'))">> settings.lua echo "set_service('FilamentSlicer')">> settings.lua echo "run_service('$1.gcode')">> settings.lua ================================================ FILE: pack_release.bat ================================================ @echo off set zip_name=curvislice set bin_folder="bin" set icesl_folder="tools/icesl" set tetwild_folder="tools/tetwild-windows" set profile_folder="resources/curvi" set models_folder="models" set curvi_script="curvislice.bat" set lua_script="luaGenerator.bat" set grb_script="optimize_grb.bat" set osqp_script="optimize_osqp.bat" set tetmesh_script="toTetmesh.bat" set _7zip="C:\Program Files\7-Zip\7z.exe" echo Zipping ... %_7zip% a -tzip "%zip_name%.zip" %bin_folder% %icesl_folder% %tetwild_folder% %profile_folder% %models_folder% %curvi_script% %lua_script% %grb_script% %osqp_script% %tetmesh_script% echo Done ! echo Release Zip is %zip_name%.zip ================================================ FILE: resources/curvi/features.lua ================================================ version = 2 bed_size_x_mm = 220 bed_size_y_mm = 220 bed_size_z_mm = 240 nozzle_diameter_mm_0 = 0.4 extruder_count = 1 z_offset = 0.0 priming_mm_per_sec = 40 z_layer_height_mm_min = 0.01 z_layer_height_mm_max = 10.0 print_speed_mm_per_sec_min = 5 print_speed_mm_per_sec_max = 80 bed_temp_degree_c = 50 bed_temp_degree_c_min = 0 bed_temp_degree_c_max = 120 perimeter_print_speed_mm_per_sec_min = 5 perimeter_print_speed_mm_per_sec_max = 80 first_layer_print_speed_mm_per_sec = 10 first_layer_print_speed_mm_per_sec_min = 1 first_layer_print_speed_mm_per_sec_max = 80 for i=0,63,1 do _G['filament_diameter_mm_'..i] = 1.75 _G['filament_priming_mm_'..i] = 4.0 _G['extruder_temp_degree_c_' ..i] = 210 _G['extruder_temp_degree_c_'..i..'_min'] = 150 _G['extruder_temp_degree_c_'..i..'_max'] = 270 _G['extruder_mix_count_'..i] = 1 end add_checkbox_setting('gcode_volumic','volumic') ================================================ FILE: resources/curvi/printer.lua ================================================ version = 2 function comment(text) output('; ' .. text) end extruder_e = 0 extruder_e_restart = 0 function prep_extruder(extruder) end function header() output('o X ' .. gcode_to_model_x .. ' Y ' .. gcode_to_model_y .. ' Z ' .. gcode_to_model_z) output('t ' .. z_layer_height_mm) end function footer() end function layer_start(zheight) output(';()') if layer_id == 0 then output('G0 F600 Z' .. ff(zheight)) else output('G0 F100 Z' .. ff(zheight)) end -- output('G1 Z' .. f(zheight)) end function layer_stop() comment('') end function retract(extruder,e) -- speed = priming_mm_per_sec * 60; -- letter = 'E' -- output('G1 F' .. speed .. ' ' .. letter .. f(e - len - extruder_e_restart)) output('R') return e end function prime(extruder,e) -- speed = priming_mm_per_sec * 60; -- letter = 'E' -- output('G1 F' .. speed .. ' ' .. letter .. f(e + len - extruder_e_restart)) output('P') return e end current_extruder = 0 current_frate = 0 function select_extruder(extruder) end function swap_extruder(from,to,x,y,z) end function move_xyz(x,y,z) output('G1 X' .. f(x) .. ' Y' .. f(y) .. ' Z' .. f(z+z_offset)) end function move_xyze(x,y,z,e) to_mm_cube = 1.0 if gcode_ultimaker2 then r = filament_diameter_mm[extruders[0]] / 2 to_mm_cube = 3.14159 * r * r end if traveling == 1 then traveling = 0 -- start path if path_is_perimeter then output(';perimeter') elseif path_is_shell then output(';shell') elseif path_is_infill then output(';infill') elseif path_is_raft then output(';raft') elseif path_is_brim then output(';brim') elseif path_is_shield then output(';shield') elseif path_is_support then output(';support') elseif path_is_tower then output(';tower') elseif path_is_ironing then output(';ironing') end end extruder_e = e letter = 'E' instr = 'G' if path_is_ironing then instr = 'I' end if z == current_z then output(instr .. '1 F' .. f(current_frate) .. ' X' .. f(x) .. ' Y' .. f(y) .. ' ' .. letter .. ff((e-extruder_e_restart)*to_mm_cube)) else output(instr .. '1 F' .. f(current_frate) .. ' X' .. f(x) .. ' Y' .. f(y) .. ' Z' .. ff(z) .. ' ' .. letter .. ff((e-extruder_e_restart)*to_mm_cube)) current_z = z end end function move_e(e) to_mm_cube = 1.0 if gcode_ultimaker2 then r = filament_diameter_mm[extruders[0]] / 2 to_mm_cube = 3.14159 * r * r end extruder_e = e letter = 'E' output('G1 ' .. letter .. f((e - extruder_e_restart)*to_mm_cube)) end function set_feedrate(feedrate) current_frate = feedrate end function extruder_start() end function extruder_stop() end function progress(percent) end function set_extruder_temperature(extruder,temperature) end function set_fan_speed(speed) end ================================================ FILE: src/MeshFormat_msh.cpp ================================================ /* This work and all associated files are under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 A copy of the license full text is included in the distribution, please refer to it for details. (c) Jimmy Etienne and Sylvain Lefebvre */ //--------------------------------------------------------------------------- #include "LibSL.precompiled.h" //--------------------------------------------------------------------------- #include "MeshFormat_msh.h" using namespace LibSL::Mesh; #include using namespace LibSL::Errors; #include using namespace LibSL::Memory::Array; #include using namespace LibSL::Memory::Pointer; #include using namespace LibSL::Math; #include using namespace LibSL::CppHelpers; #include #include #include //--------------------------------------------------------------------------- #define NAMESPACE LibSL::Mesh //--------------------------------------------------------------------------- /// Declaring a global will automatically register the plugin namespace { NAMESPACE::MeshFormat_msh s_Msh; /// FIXME: this mechanism does not work with VC++ } /// see also MeshFormatManager constructor //--------------------------------------------------------------------------- NAMESPACE::MeshFormat_msh::MeshFormat_msh() { try { // register plugin MESH_FORMAT_MANAGER.registerPlugin(this); } catch (LibSL::Errors::Fatal& e) { std::cerr << e.message() << std::endl; } } //--------------------------------------------------------------------------- using namespace std; //--------------------------------------------------------------------------- void parseWhiteSpace(ifstream& stream) { char next = stream.peek(); while (next == '\n' || next == ' ' || next == '\t' || next == '\r') { stream.get(); next = stream.peek(); } } void parseMeshFormat(ifstream& stream, MeshFormat_msh::msh_format_info& format) { stream >> format.version_number; parseWhiteSpace(stream); stream >> format.binary; parseWhiteSpace(stream); stream >> format.data_size; parseWhiteSpace(stream); if (format.binary) { // binary int check = 1; stream.read(reinterpret_cast(&check), sizeof(int)); sl_assert(check == 1); // make sure the file is compatible (little or big endian) } } void parsePhysicalNames(ifstream& stream, MeshFormat_msh::msh_format_info& format) { } void parseNodes(ifstream& stream, MeshFormat_msh::msh_format_info& format) { uint nb_nodes; stream >> nb_nodes; parseWhiteSpace(stream); int num_i; double xyz[3]; if (format.binary) { ForIndex(i, nb_nodes) { stream.read(reinterpret_cast(&num_i), sizeof(int)); stream.read(reinterpret_cast(&xyz), sizeof(xyz)); format.nodes.emplace_back(v3f(xyz[0], xyz[1], xyz[2])); } } else { ForIndex (i, nb_nodes) { char trash; stream >> num_i; stream >> xyz[0] >> trash >> xyz[1] >> trash >> xyz[2]; parseWhiteSpace(stream); } } } void parseElements(ifstream& stream, MeshFormat_msh::msh_format_info& format) { uint nb_elements; stream >> nb_elements; parseWhiteSpace(stream); int header[3]; uint nb_elems = 0; while (nb_elems < nb_elements) { if (format.binary) { stream.read(reinterpret_cast(&header), sizeof(header)); } else { stream >> header[0]; parseWhiteSpace(stream); } int elem_size = 0; switch (header[0]) { case 1: // 2-node line break; case 2: // 3-node triangle elem_size = 3; break; case 3: // 4-node quadrangle elem_size = 4; break; case 4: // 4-node tetrahedron elem_size = 4; break; case 5: // 8-node hexahedron break; case 6: break; } for (int elem = 0; elem < header[1]; elem++) { for (int tag = 0; tag < header[2]; tag++) { int data; stream.read(reinterpret_cast(&data), sizeof(data)); } int num_i; stream.read(reinterpret_cast(&num_i), sizeof(num_i)); int data[4]; stream.read(reinterpret_cast(&data), sizeof(data)); vector elems; ForIndex (i, elem_size) { elems.emplace_back(data[i]); } format.elements.emplace_back(elems); } nb_elems += header[1]; } } void parseElementData(ifstream& stream, MeshFormat_msh::msh_format_info& format) { MeshFormat_msh::msh_entity_data element; { uint nb_string_tags; stream >> nb_string_tags; std::string tag; ForIndex(i, nb_string_tags) { string str; do { stream >> str; tag += (tag.empty() ? "" : " ") + str; } while (str.at(str.size() - 1) != '\"'); ; element.string_tags.emplace_back(tag); parseWhiteSpace(stream); } } { uint nb_real_tags; stream >> nb_real_tags; float tag; ForIndex(i, nb_real_tags) { stream >> tag; element.real_tags.emplace_back(tag); parseWhiteSpace(stream); } } { uint nb_int_tags; stream >> nb_int_tags; int tag; ForIndex(i, nb_int_tags) { stream >> tag; element.integer_tags.emplace_back(tag); parseWhiteSpace(stream); } } size_t nb_values = element.integer_tags[1]; size_t nb_elems = element.integer_tags[2]; size_t num_bytes = (nb_values * format.data_size + 4) * nb_elems; char* data = new char[num_bytes]; stream.read(data, num_bytes); ForIndex(i, nb_elems) { size_t base_idx = i * (4 + nb_values * format.data_size); int elem = (*reinterpret_cast(&data[base_idx])) - 1; base_idx += 4; vector values(nb_values); ForIndex(j, nb_values) { values[j] = (*reinterpret_cast(&data[base_idx + j * format.data_size])); } element.values.emplace(elem, values); } format.element_data.emplace_back(element); } void parseNodeData(ifstream& stream, MeshFormat_msh::msh_format_info& format) { MeshFormat_msh::msh_entity_data node_data; { uint nb_string_tags; stream >> nb_string_tags; std::string tag; ForIndex(i, nb_string_tags) { string str; do { stream >> str; tag += (tag.empty() ? "" : " ") + str; } while (str.at(str.size() - 1) != '\"'); ; node_data.string_tags.emplace_back(tag); parseWhiteSpace(stream); } } { uint nb_real_tags; stream >> nb_real_tags; float tag; ForIndex(i, nb_real_tags) { stream >> tag; node_data.real_tags.emplace_back(tag); parseWhiteSpace(stream); } } { uint nb_int_tags; stream >> nb_int_tags; int tag; ForIndex(i, nb_int_tags) { stream >> tag; node_data.integer_tags.emplace_back(tag); parseWhiteSpace(stream); } } size_t nb_values = node_data.integer_tags[1]; size_t nb_nodes = node_data.integer_tags[2]; size_t num_bytes = (nb_values * format.data_size + 4) * nb_nodes; char* data = new char[num_bytes]; stream.read(data, num_bytes); ForIndex (i, nb_nodes) { int node = *reinterpret_cast(&data[i*(4 + nb_values * format.data_size)]); node -= 1; size_t base_idx = i * (4 + nb_values * format.data_size) + 4; vector values(nb_values); ForIndex (j, nb_values) { values[j] = (*reinterpret_cast(&data[base_idx + j * format.data_size])); } node_data.values.emplace(node, values); } format.node_data.emplace_back(node_data); } //--------------------------------------------------------------------------- void NAMESPACE::MeshFormat_msh::parse(const char *fname) { LIBSL_BEGIN; // open file FILE *f = NULL; fopen_s(&f, fname, "rb"); if (f == NULL) { throw Fatal("[MeshFormat_msh::load] - file '%s' not found", fname); } ifstream stream(fname, ios::binary); std::string blockname, blockend; while (!stream.eof()) { stream >> blockname; if (blockname == "$MeshFormat") { parseMeshFormat(stream, m_format); stream >> blockend; sl_assert(blockend == "$EndMeshFormat"); } else if (blockname == "$PhysicalNames") { parsePhysicalNames(stream, m_format); stream >> blockend; sl_assert(blockend == "$EndPhysicalNames"); } else if (blockname == "$Nodes") { parseNodes(stream, m_format); stream >> blockend; sl_assert(blockend == "$EndNodes"); } else if (blockname == "$Elements") { parseElements(stream, m_format); stream >> blockend; sl_assert(blockend == "$EndElements"); } else if (blockname == "$ElementData") { parseElementData(stream, m_format); stream >> blockend; sl_assert(blockend == "$EndElementData"); } else if (blockname == "$NodeData") { parseNodeData(stream, m_format); stream >> blockend; sl_assert(blockend == "$EndNodeData"); } else { cerr << "Unknown block : " << blockname << endl; // TODO: READ UNTIL END OF BLOCK stream >> blockend; sl_assert(blockend == "$End" + blockname.substr(1, blockname.size() - 1)); } parseWhiteSpace(stream); } fclose(f); LIBSL_END; } NAMESPACE::TriangleMesh* NAMESPACE::MeshFormat_msh::load(const char *fname) const { MeshFormat_msh msh; msh.parse(fname); msh_format_info format = msh.m_format; set tris; map srfTris; // faces uint fi = 0; ForArray(format.elements, n_tet) { // TODO: manage non tet ForIndex(off, 4) { uint A = format.elements.at(n_tet)[(off + 0) % 4] - 1; uint B = format.elements.at(n_tet)[(off + 1) % 4] - 1; uint C = format.elements.at(n_tet)[(off + 2) % 4] - 1; if (A > B) std::swap(A, B); if (B > C) std::swap(B, C); if (A > B) std::swap(A, B); // extract the surface v3u t(A, B, C); auto it_ = tris.find(t); if (it_ == tris.end()) { tris.insert(t); fi++; } auto it = srfTris.find(t); if (it == srfTris.end()) { srfTris.insert_or_assign(t, fi); } else { srfTris.erase(it); } } } TriangleMesh_generic *mesh = new TriangleMesh_generic(format.nodes.size(), tris.size(), 1 , AutoPtr(MVF::make())); //vertices ForArray (format.nodes, n_ver) { v3f pos = format.nodes.at(n_ver); mesh->vertexAt(n_ver).pos = pos; } // tris fi = 0; for (auto it : tris) { mesh->triangleAt(fi) = it; fi++; } //surface tris uint si = 0; TriangleMesh::t_SurfaceNfo srf; srf.triangleIds.allocate(srfTris.size()); for(auto it : srfTris) { srf.triangleIds[si] = it.second; si++; } mesh->surfaceAt(0) = srf; // done return mesh; } //--------------------------------------------------------------------------- void NAMESPACE::MeshFormat_msh::save(const char *fname,const NAMESPACE::TriangleMesh *mesh) const { } //--------------------------------------------------------------------------- ================================================ FILE: src/MeshFormat_msh.h ================================================ /* This work and all associated files are under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 A copy of the license full text is included in the distribution, please refer to it for details. (c) Jimmy Etienne and Sylvain Lefebvre */ #pragma once #include #include #include namespace LibSL { namespace Mesh { class MeshFormat_msh : public TriangleMeshFormat_plugin { public: typedef struct { LibSL::Math::v3f pos; LibSL::Math::v3f nrm; } t_VertexData; typedef MVF2(mvf_position_3f, mvf_normal_3f) t_VertexFormat; typedef struct { std::vector string_tags; // [name of the post-processing view, name of the interpolation scheme, ???] std::vector real_tags; // [time value, ???] std::vector integer_tags; // [time step index, number of field components (1, 3 or 9), number of entities, partition index, ???] std::map> values; // entity number : [value1, value2, ...] } msh_entity_data; typedef struct { std::vector string_tags; // [name of the post-processing view, name of the interpolation scheme, ???] std::vector real_tags; // [time value, ???] std::vector integer_tags; // [time step index, number of field components (1, 3 or 9), number of elements, partition index, ???] std::map>> values; // element number : } msh_element_node_data; typedef struct { float version_number; bool binary; // 0 = ASCII, 1 = binary uint data_size = 0; uint number_of_nodes_per_element; uint element_type; std::vector nodes; std::vector> elements; std::vector node_data; std::vector element_data; std::vector element_node_data; } msh_format_info; public: MeshFormat_msh(); void parse(const char *); void save(const char *,const TriangleMesh *) const; TriangleMesh *load(const char *) const; const char *signature() const {return "msh";} public: mutable std::vector m_meshes; mutable std::vector> m_surfaces; msh_format_info m_format; }; } //namespace LibSL::Mesh } //namespace LibSL // ------------------------------------------------------ ================================================ FILE: src/TetMesh.cpp ================================================ /* This work and all associated files are under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 A copy of the license full text is included in the distribution, please refer to it for details. (c) Jimmy Etienne and Sylvain Lefebvre */ #include "TetMesh.h" //--------------------------------------------------------------------------- #include "LibSL.precompiled.h" //--------------------------------------------------------------------------- using namespace LibSL::Mesh; #include using namespace LibSL::Errors; #include using namespace LibSL::Memory::Array; #include using namespace LibSL::Memory::Pointer; #include using namespace LibSL::Math; #include using namespace LibSL::CppHelpers; #include #include #include #include #include "Model.h" TetMesh::TetMesh() { } TetMesh::TetMesh(TetMesh* mesh) { for (auto vertex : mesh->m_vertices) { m_vertices.emplace_back(vertex); } for (auto tet : mesh->m_tetrahedrons) { m_tetrahedrons.emplace_back(tet); } for (auto tri : mesh->m_triangles) { m_triangles.emplace_back(tri); } for (auto srfs : mesh->m_surfaces) { m_surfaces.emplace_back(srfs); } } TetMesh::~TetMesh() { } size_t TetMesh::numVertices() { return m_vertices.size(); } v3f& TetMesh::vertexAt(uint n) { return m_vertices.at(n); } size_t TetMesh::numTetrahedrons() { return m_tetrahedrons.size(); } bool TetMesh::isInside(uint t) { return !m_tetrahedrons.at(t).second; } v4u& TetMesh::tetrahedronAt(uint t) { return m_tetrahedrons.at(t).first; } size_t TetMesh::numTriangles() { return m_triangles.size(); } v3u& TetMesh::triangleAt(uint t) { return m_triangles.at(t); } size_t TetMesh::numSurfaces() { return m_surfaces.size(); } v3u& TetMesh::surfaceTriangleAt(uint s) { return m_triangles.at(m_surfaces.at(s)); } using namespace std; //--------------------------------------------------------------------------- TetMesh* TetMesh::load(const char *fname) { TetMesh* mesh = new TetMesh(); mesh->m_mesh = AutoPtr(new MeshFormat_msh); mesh->m_mesh->parse(fname); MeshFormat_msh::msh_format_info format = mesh->m_mesh->m_format; MeshFormat_msh::msh_entity_data element_inout; // Check if the domain is tetrahedralized or just the object bool domain = false; for (auto data : format.element_data) { if (data.string_tags[0] == "\"in/out\"") { element_inout = data; domain = true; } } map> tris; vector srfTris; size_t nb_elements = format.elements.size(); srfTris.resize(nb_elements * 4); // assuming that the file only contains tets // faces uint fi = 0; ForArray(format.elements, n_tet) { // TODO: manage non tet bool in = domain && element_inout.values[n_tet][0] == 1.f; mesh->m_tetrahedrons.push_back(make_pair( v4u(format.elements.at(n_tet)[0] - 1, format.elements.at(n_tet)[1] - 1, format.elements.at(n_tet)[2] - 1, format.elements.at(n_tet)[3] - 1), in)); ForIndex(off, 4) { uint A = format.elements.at(n_tet)[(off + 0) % 4] - 1; uint B = format.elements.at(n_tet)[(off + 1) % 4] - 1; uint C = format.elements.at(n_tet)[(off + 2) % 4] - 1; uint _A = A, _B = B, _C = C; if (A > B) std::swap(A, B); if (B > C) std::swap(B, C); if (A > B) std::swap(A, B); // extract the surface v3u t(A, B, C); v3u r(_A, _B, _C); auto it = tris.find(t); if (it == tris.end()) { tris[t].first = r; if (in) { tris[t].second = 2; } else { tris[t].second = 1; } fi++; } else { if (in) { tris[t].first = r; tris[t].second += 2; } else { tris[t].second += 1; } } } } //vertices ForArray(mesh->m_mesh->m_format.nodes, n_ver) { v3f pos = mesh->m_mesh->m_format.nodes.at(n_ver); mesh->m_vertices.push_back(pos); } // tris & srf tris uint i = 0; for (auto it : tris) { mesh->m_triangles.push_back(it.second.first); if (it.second.second % 2) mesh->m_surfaces.push_back(i); i++; } mesh->reorientSurface(); // done return (mesh); } void TetMesh::save(const char *fname, TetMesh *mesh) { FILE *f = NULL; fopen_s(&f, fname, "wb"); if (f == NULL) { throw Fatal("[MeshFormat_msh::save] - cannot open file '%s' for writing", fname); } // header char header[80]; memset(header, 0x00, 80); sprintf(header, "LibSL_STL_1.0"); fwrite(header, sizeof(char), 80, f); // num triangles size_t nTris = mesh->numSurfaces(); fwrite(&nTris, sizeof(uint), 1, f); // vertices ForIndex(t, nTris) { v3u tri = mesh->surfaceTriangleAt(t); v3f nrm = cross(mesh->vertexAt(tri[1]) - mesh->vertexAt(tri[0]), mesh->vertexAt(tri[2]) - mesh->vertexAt(tri[0])); nrm = normalize_safe(nrm); v3f pt[3]; ForIndex(v, 3) { pt[v] = mesh->vertexAt(tri[v]); } fwrite(&nrm, sizeof(float), 3, f); fwrite(&pt, sizeof(float), 3 * 3, f); ushort attr = 0; fwrite(&attr, sizeof(ushort), 1, f); } fclose(f); } /* INPUT: A - array of pointers to rows of a square matrix having dimension N * Tol - small tolerance number to detect failure when the matrix is near degenerate * OUTPUT: Matrix A is changed, it contains both matrices L-E and U as A=(L-E)+U such that P*A=L*U. * The permutation matrix is not stored as a matrix, but in an integer vector P of size N+1 * containing column indexes where the permutation matrix has "1". The last element P[N]=S+N, * where S is the number of row exchanges needed for determinant computation, det(P)=(-1)^S */ int LUPDecompose(double **A, int N, double Tol, int *P) { int i, j, k, imax; double maxA, absA; for (i = 0; i <= N; i++) P[i] = i; //Unit permutation matrix, P[N] initialized with N for (i = 0; i < N; i++) { maxA = 0.0; imax = i; for (k = i; k < N; k++) if ((absA = fabs(A[k][i])) > maxA) { maxA = absA; imax = k; } if (maxA < Tol) return 0; //failure, matrix is degenerate if (imax != i) { //pivoting P swap(P[i], P[imax]); //pivoting rows of A swap(A[i], A[imax]); //counting pivots starting from N (for determinant) P[N]++; } for (j = i + 1; j < N; j++) { A[j][i] /= A[i][i]; for (k = i + 1; k < N; k++) A[j][k] -= A[j][i] * A[i][k]; } } return 1; //decomposition done } /* INPUT: A,P filled in LUPDecompose; b - rhs vector; N - dimension * OUTPUT: x - solution vector of A*x=b */ void LUPSolve(double **A, int *P, double *b, int N, double *x) { for (int i = 0; i < N; i++) { x[i] = b[P[i]]; for (int k = 0; k < i; k++) x[i] -= A[i][k] * x[k]; } for (int i = N - 1; i >= 0; i--) { for (int k = i + 1; k < N; k++) x[i] -= A[i][k] * x[k]; x[i] = x[i] / A[i][i]; } } /* INPUT: A,P filled in LUPDecompose; N - dimension * OUTPUT: IA is the inverse of the initial matrix */ void LUPInvert(double **A, int *P, int N, double **IA) { for (int j = 0; j < N; j++) { for (int i = 0; i < N; i++) { if (P[i] == j) IA[i][j] = 1.0; else IA[i][j] = 0.0; for (int k = 0; k < i; k++) IA[i][j] -= A[i][k] * IA[k][j]; } for (int i = N - 1; i >= 0; i--) { for (int k = i + 1; k < N; k++) IA[i][j] -= A[i][k] * IA[k][j]; IA[i][j] = IA[i][j] / A[i][i]; } } } /* INPUT: A,P filled in LUPDecompose; N - dimension. * OUTPUT: Function returns the determinant of the initial matrix */ double LUPDeterminant(double **A, int *P, int N) { double det = A[0][0]; for (int i = 1; i < N; i++) det *= A[i][i]; if ((P[N] - N) % 2 == 0) return det; else return -det; } M3x3 TetMesh::getGradientMatrix(uint t) { M3x3 m(0.); v3f A = vertexAt(tetrahedronAt(t)[0]); v3f B = vertexAt(tetrahedronAt(t)[1]); v3f C = vertexAt(tetrahedronAt(t)[2]); v3f D = vertexAt(tetrahedronAt(t)[3]); A -= D; B -= D; C -= D; AutoPtr> model(new SLRModel()); model->printDebug(false); SLRVar M[9]; ForIndex(i, 9) { M[i] = model->addVar(-1000.0f, 1000.0f, m[i]); } model->addConstr(M[0] * A[0] + M[1] * B[0] + M[2] * C[0] == 1.); model->addConstr(M[0] * A[1] + M[1] * B[1] + M[2] * C[1] == 0.); model->addConstr(M[0] * A[2] + M[1] * B[2] + M[2] * C[2] == 0.); model->addConstr(M[3] * A[0] + M[4] * B[0] + M[5] * C[0] == 0.); model->addConstr(M[3] * A[1] + M[4] * B[1] + M[5] * C[1] == 1.); model->addConstr(M[3] * A[2] + M[4] * B[2] + M[5] * C[2] == 0.); model->addConstr(M[6] * A[0] + M[7] * B[0] + M[8] * C[0] == 0.); model->addConstr(M[6] * A[1] + M[7] * B[1] + M[8] * C[1] == 0.); model->addConstr(M[6] * A[2] + M[7] * B[2] + M[8] * C[2] == 1.); model->optimize(); ForIndex(i, 9) { m[i] = M[i].get(); } return m; } vector& TetMesh::tet_neighbours(uint t) { if (m_tet_neighborhood.empty()) { for(int i = 0; i < m_tetrahedrons.size()-1; i++) { v4u origin = tetrahedronAt(i); for (int j = i + 1; j < m_tetrahedrons.size(); j++) { v4u curr = tetrahedronAt(j); int common = 0; ForIndex(a, 4) { ForIndex(b, 4) { if (curr[a] == origin[b]) { common++; } } } if (common == 3) { m_tet_neighborhood[i].push_back(j); m_tet_neighborhood[j].push_back(i); } } } } return m_tet_neighborhood[t]; } vector& TetMesh::tri_neighbours(uint t) { if (m_tri_neighborhood.empty()) { for (int i = 0; i < numSurfaces() - 1; i++) { v3u origin = surfaceTriangleAt(i); for (int j = i + 1; j < numSurfaces(); j++) { v3u curr = surfaceTriangleAt(j); int common = 0; ForIndex(a, 3) { ForIndex(b, 3) { if (curr[a] == origin[b]) { common++; } } } if (common == 2) { m_tri_neighborhood[i].push_back(j); m_tri_neighborhood[j].push_back(i); } } } } return m_tri_neighborhood[t]; } vector TetMesh::ver_neighbours(uint t) { if (m_ver_to_tris.empty()) { ForIndex (s, m_surfaces.size()) { ForIndex(v, 3) { m_ver_to_tris[v].push_back(s); } } } vector vec; for (uint s : m_ver_to_tris[t]) { ForIndex(v, 3) { if (m_triangles.at(s)[v] != t) { vec.push_back(m_triangles.at(s)[v]); } } } sort(vec.begin(), vec.end()); vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; } uint TetMesh::getTetrahedronSurface(uint t) { v3u tri = m_triangles.at(t); for (int i = 0; i < m_tetrahedrons.size(); i++) { if (!m_tetrahedrons.at(i).second) continue; v4u tet = m_tetrahedrons.at(i).first; int common = 0; ForIndex(a, 4) { ForIndex(b, 3) { if (tet[a] == tri[b]) { common++; } } } if (common == 3) { return i; } } return 0; } AABox TetMesh::getBBox() { AABox bbox; for (v3f vertex : m_vertices) { bbox.addPoint(vertex); } return bbox; } void TetMesh::reorientSurface() { if (numSurfaces() == 0) return; Array visited(numSurfaces()); visited.fill(false); // build edge info map > edge_to_tris; ForIndex(t, numSurfaces()) { v3u tri = surfaceTriangleAt(t); ForIndex(i, 3) { v2i e = v2i(min(tri[i], tri[(i + 1) % 3]), max(tri[i], tri[(i + 1) % 3])); edge_to_tris[e].push_back(t); } } while (true) { // find a lowest triangle not visited int next = -1; float minz = 1e20; ForIndex(t, numSurfaces()) { if (!visited[t]) { ForIndex(i, 3) { float z = vertexAt(surfaceTriangleAt(t)[i])[2]; if (z < minz) { minz = z; next = t; } } } } if (next == -1) { break; // done! } // orient 'next' v3u tn = surfaceTriangleAt(next); v3f nrm = cross(vertexAt(tn[1]) - vertexAt(tn[0]), vertexAt(tn[2]) - vertexAt(tn[0])); if (nrm[2] > 0) { swap(tn[0], tn[2]); surfaceTriangleAt(next) = tn; } // orient by local growth std::queue q; q.push(next); visited[next] = true; while (!q.empty()) { // pop current int curid = q.front(); v3u cur = surfaceTriangleAt(curid); q.pop(); // get neighbors ForIndex(i, 3) { v2i e = v2i(min(cur[i], cur[(i + 1) % 3]), max(cur[i], cur[(i + 1) % 3])); const vector& neighs = edge_to_tris[e]; if (neighs.size() == 2) { // only trust two-manifold edges ForIndex(n, neighs.size()) { if (!visited[neighs[n]]) { visited[neighs[n]] = true; // check orientation v3u tri_n = surfaceTriangleAt(neighs[n]); bool fliped = false; v2i e_cur = v2i(cur[i], cur[(i + 1) % 3]); ForIndex(j, 3) { v2i e_j = v2i(tri_n[j], tri_n[(j + 1) % 3]); if (e_j == e_cur) { fliped = true; break; } } if (fliped) { // flip swap(tri_n[0], tri_n[2]); surfaceTriangleAt(neighs[n]) = tri_n; } q.push(neighs[n]); } } } } } } // search for face at bottom to check if we have to flip all float bottomz = std::numeric_limits::max(); ForIndex(t, numSurfaces()) { ForIndex(i, 3) { v3f pt = vertexAt(surfaceTriangleAt(t)[i]); bottomz = min(bottomz, pt[2]); } } bool flip = false; ForIndex(t, numSurfaces()) { bool bottom = true; v3f pts[3]; ForIndex(i, 3) { v3f pt = vertexAt(surfaceTriangleAt(t)[i]); if (abs(pt[2] - bottomz) > 1e-3f) { bottom = false; } pts[i] = pt; } if (bottom) { // compute normal to check it faces down v3f nrm = cross(pts[1] - pts[0], pts[2] - pts[0]); if (length(nrm) > 1e-6f) { // can trust normal if (nrm[2] > 0) { // flip all flip = true; } // done break; } } } if (flip) { ForIndex(t, numSurfaces()) { v3u tri = surfaceTriangleAt(t); std::swap(tri[0], tri[1]); surfaceTriangleAt(t) = tri; } } } ================================================ FILE: src/TetMesh.h ================================================ /* This work and all associated files are under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 A copy of the license full text is included in the distribution, please refer to it for details. (c) Jimmy Etienne and Sylvain Lefebvre */ #pragma once #include #include #include #include #include #include "MeshFormat_msh.h" using namespace LibSL::Math; using namespace std; typedef Tuple M3x3; class TetMesh { private : AutoPtr m_mesh; vector> m_tetrahedrons; vector m_vertices; vector m_triangles; vector m_surfaces; map> m_tet_neighborhood; map> m_tri_neighborhood; map> m_ver_to_tris; public: TetMesh(); TetMesh(TetMesh*); ~TetMesh(); static TetMesh* load(const char *fname); static void save(const char *fname, TetMesh *mesh); size_t numVertices(); v3f& vertexAt(uint n); size_t numTetrahedrons(); bool isInside(uint t); v4u& tetrahedronAt(uint t); vector& tet_neighbours(uint t); vector& tri_neighbours(uint t); vector ver_neighbours(uint t); uint getTetrahedronSurface(uint t); size_t numTriangles(); v3u& triangleAt(uint t); size_t numSurfaces(); v3u& surfaceTriangleAt(uint s); M3x3 getGradientMatrix(uint t); AABox getBBox(); void reorientSurface(); }; ================================================ FILE: src/config.h.in ================================================ #pragma once #define SRC_PATH "@CMAKE_SOURCE_DIR@" ================================================ FILE: src/gcode.cpp ================================================ /* This work and all associated files are under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 A copy of the license full text is included in the distribution, please refer to it for details. (c) Jimmy Etienne and Sylvain Lefebvre */ #include "gcode.h" // -------------------------------------------------------------- typedef LibSL::BasicParser::BufferStream t_stream; typedef LibSL::BasicParser::Parser t_parser; typedef AutoPtr t_stream_ptr; typedef AutoPtr t_parser_ptr; // -------------------------------------------------------------- t_stream_ptr g_Stream; t_parser_ptr g_Parser; v4f g_Pos(0.0f); v4f g_Offset(0.0f); float g_Speed = 20.0f; int g_Line = 0; const char *g_GCode = NULL; bool g_GCodeError = false; bool g_DoPrime = false; bool g_DoRetract = false; bool g_Ironing = false; float g_LayerThickness = -1.0f; v3f g_GCodeOffset(0.0f); // -------------------------------------------------------------- void gcode_start(const char *gcode) { g_GCode = gcode; g_Stream = t_stream_ptr(new t_stream(g_GCode,(uint)strlen(g_GCode)+1)); g_Parser = t_parser_ptr(new t_parser(*g_Stream,false)); g_Pos = 0.0f; g_Offset = 0.0f; g_Speed = 20.0f; g_Line = 0; g_GCodeError = false; g_DoPrime = false; g_DoRetract = false; g_LayerThickness = -1.0f; int c; while (!g_Parser->eof()) { g_Line++; c = g_Parser->readChar(); c = tolower(c); if (c == 'o') { while (!g_Parser->eof()) { c = g_Parser->readChar(); if (c == '\n') break; if (c == ';') { g_Parser->reachChar('\n'); break; } c = tolower(c); float f = g_Parser->readFloat(); if (c >= 'x' && c <= 'z') { g_GCodeOffset[c - 'x'] = f; } } // break; } if (c == 't') { g_LayerThickness = g_Parser->readFloat(); // done with header! g_Parser->reachChar('\n'); break; } } } // -------------------------------------------------------------- void gcode_reset() { sl_assert(g_GCode != NULL); g_Stream = t_stream_ptr(new t_stream(g_GCode, (uint)strlen(g_GCode) + 1)); g_Parser = t_parser_ptr(new t_parser(*g_Stream, false)); g_Pos = 0.0f; g_Offset = 0.0f; g_Speed = 20.0f; g_Line = 0; g_GCodeError = false; g_DoPrime = false; g_DoRetract = false; g_LayerThickness = -1.0f; } // -------------------------------------------------------------- v3f gcode_offset() { return g_GCodeOffset; } // -------------------------------------------------------------- bool gcode_advance() { if (g_GCodeError) return false; int c; g_DoPrime = false; g_DoRetract = false; while (!g_Parser->eof()) { g_Line ++; c = g_Parser->readChar(); c = tolower(c); if (c == 'p') { // prime g_Parser->reachChar('\n'); g_DoPrime = true; break; } else if (c == 'r') { // retract g_Parser->reachChar('\n'); g_DoRetract = true; break; } else if (c == 'g' || c == 'i') { // 'i' for ironing int n = g_Parser->readInt(); if (n == 0 || n == 1) { // G0 G1 g_Ironing = (c == 'i'); while (!g_Parser->eof()) { c = g_Parser->readChar(); if (c == '\n') break; if (c == ';') { g_Parser->reachChar('\n'); break; } c = tolower(c); float f = g_Parser->readFloat(); if (c >= 'x' && c <= 'z') { g_Pos[c - 'x'] = f + g_Offset[c - 'x']; } else if (c == 'e') { g_Pos[3] = f + g_Offset[3]; } else if (c == 'f') { g_Speed = f / 60.0f; } else if (c >= 'a' && c <= 'f') { // TODO mixing ratios } else { g_GCodeError = true; return false; } } break; // done advancing } else if (n == 92) { // G92 while (!g_Parser->eof()) { c = g_Parser->readChar(); if (c == '\n') break; c = tolower(c); float f = g_Parser->readFloat(); if (c >= 'x' && c <= 'z') { g_Offset[c - 'x'] = g_Pos[c - 'x'] - f; } else if (c == 'e') { g_Offset[3] = g_Pos[3] - f; } } } else if (n == 10) { // G10 g_Parser->reachChar('\n'); } else if (n == 11) { // G11 g_Parser->reachChar('\n'); } else { // other => ignore g_Parser->reachChar('\n'); } } else if (c == 'm') { int n = g_Parser->readInt(); g_Parser->reachChar('\n'); } else if (c == '\n') { // do nothing } else if (c == '<') { g_Parser->reachChar('\n'); } else if (c == ';' || c == 'o') { g_Parser->reachChar('\n'); } else if (c == '\r') { g_Parser->reachChar('\n'); } else if (c == '\0' || c == -1) { return false; } else { g_GCodeError = true; return false; } } return !g_Parser->eof(); } // -------------------------------------------------------------- v4f gcode_next_pos() { return g_Pos; } // -------------------------------------------------------------- float gcode_speed() { return g_Speed; } // -------------------------------------------------------------- int gcode_line() { return g_Line; } // -------------------------------------------------------------- bool gcode_error() { return g_GCodeError; } // -------------------------------------------------------------- bool gcode_do_prime() { return g_DoPrime; } // -------------------------------------------------------------- bool gcode_do_retract() { return g_DoRetract; } // -------------------------------------------------------------- float gcode_layer_thickness() { return g_LayerThickness; } // -------------------------------------------------------------- bool gcode_is_ironing() { return g_Ironing; } // -------------------------------------------------------------- ================================================ FILE: src/gcode.h ================================================ // SL 2018-07-03 #pragma once #include #include #include // start interpreting the gcode void gcode_start(const char *gcode); v3f gcode_offset(); // advances to the next position // return false if none exists (end of gcode) bool gcode_advance(); // returns the next position to reach (x,y,z,e) v4f gcode_next_pos(); // returns the speed in mm/sec float gcode_speed(); // return current line in gcode stream int gcode_line(); // restart from scratch void gcode_reset(); // returns true in a reading error occured bool gcode_error(); // returns true if has to prime bool gcode_do_prime(); // returns true if has to retract bool gcode_do_retract(); // returns true if ironing is active bool gcode_is_ironing(); // returns the layer thickness float gcode_layer_thickness(); ================================================ FILE: src/helpers.h ================================================ /* This work and all associated files are under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 A copy of the license full text is included in the distribution, please refer to it for details. (c) Jimmy Etienne and Sylvain Lefebvre */ #include // -------------------------------------------------------------- // -------------- FUNCTIONS / HELPERS ---------------------- // -------------------------------------------------------------- // ScTP computes the scalar triple product #define ScTP(a, b, c) dot(a, cross(b,c)) // -------------------------------------------------------------- float tetrahedron_signed_volume(const Tuple& tet) { v3f vab = tet[1] - tet[0]; v3f vac = tet[2] - tet[0]; v3f vad = tet[3] - tet[0]; return 1.0F / 6.0F * ScTP(vab, vac, vad); } // -------------------------------------------------------------- float tetrahedron_signed_volume(TetMesh& mesh, const v4u& tet) { return tetrahedron_signed_volume(Tuple(mesh.vertexAt(tet[0]), mesh.vertexAt(tet[1]), mesh.vertexAt(tet[2]), mesh.vertexAt(tet[3]))); } // -------------------------------------------------------------- float tetrahedron_volume(const Tuple& tet) { return abs(tetrahedron_signed_volume(tet)); } // -------------------------------------------------------------- float tetrahedron_volume(TetMesh& mesh, const v4u& tet) { return tetrahedron_volume(Tuple(mesh.vertexAt(tet[0]), mesh.vertexAt(tet[1]), mesh.vertexAt(tet[2]), mesh.vertexAt(tet[3]))); } // -------------------------------------------------------------- v4f tetrahedron_barycenter_coefs(const Tuple& tet, v3f pt) { v3f vap = pt - tet[0]; v3f vbp = pt - tet[1]; v3f vab = tet[1] - tet[0]; v3f vac = tet[2] - tet[0]; v3f vad = tet[3] - tet[0]; v3f vbc = tet[2] - tet[1]; v3f vbd = tet[3] - tet[1]; float va = 1.0F / 6.0F * ScTP(vbp, vbd, vbc); float vb = 1.0F / 6.0F * ScTP(vap, vac, vad); float vc = 1.0F / 6.0F * ScTP(vap, vad, vab); float vd = 1.0F / 6.0F * ScTP(vap, vab, vac); return v4f(va, vb, vc, vd) / tetrahedron_volume(tet); } // -------------------------------------------------------------- float triangle_area(const Tuple& tri) { v3d vab = tri[1] - tri[0]; v3d vac = tri[2] - tri[0]; float v = 1.0F / 2.0F * length(cross(vab, vac)); return abs(v); } // -------------------------------------------------------------- float triangle_area(TetMesh& mesh, const v3u& tri) { return triangle_area(Tuple(v3d(mesh.vertexAt(tri[0])), v3d(mesh.vertexAt(tri[1])), v3d(mesh.vertexAt(tri[2])))); } // -------------------------------------------------------------- float triangle_area_xy(const Tuple& tri) { v3d vab = tri[1] - tri[0]; v3d vac = tri[2] - tri[0]; vab[2] = 0.0F; vac[2] = 0.0F; float v = 1.0F / 2.0F * length(cross(vab, vac)); return abs(v); } // -------------------------------------------------------------- double triangle_area_xy(TetMesh& mesh, const v3u& tri) { return triangle_area_xy(Tuple(v3d(mesh.vertexAt(tri[0])), v3d(mesh.vertexAt(tri[1])), v3d(mesh.vertexAt(tri[2])))); } // -------------------------------------------------------------- float component_area(TetMesh& mesh, const vector& surfaces) { float area = 0.0F; for (int surface : surfaces) { area += triangle_area(mesh, mesh.surfaceTriangleAt(surface)); } return area; } // -------------------------------------------------------------- template Tuple, 3> tetrahedron_gradient(TetMesh& mesh, map& h, const Array& mats, uint t) { v4u tet = mesh.tetrahedronAt(t); T_var ha = h[tet[0]]; T_var hb = h[tet[1]]; T_var hc = h[tet[2]]; T_var hd = h[tet[3]]; SLRExpr dhdx = (ha - hd) * mats[t][0] + (hb - hd) * mats[t][1] + (hc - hd) * mats[t][2]; SLRExpr dhdy = (ha - hd) * mats[t][3] + (hb - hd) * mats[t][4] + (hc - hd) * mats[t][5]; SLRExpr dhdz = (ha - hd) * mats[t][6] + (hb - hd) * mats[t][7] + (hc - hd) * mats[t][8]; return Tuple, 3>(dhdx, dhdy, dhdz); } // -------------------------------------------------------------- template < class T_Graph > class TestFlattened { private: const set& flats; public: TestFlattened(const set& flats_) : flats(flats_) {} bool operator()(const T_Graph& graph, LibSL::DataStructures::t_NodeId node) const { return (flats.find(node) != flats.end()); } }; // --------------------------------------------------------------- void connected_components(TetMesh& mesh, const set& surfaces_to_flatten, vector >& _comps) { typedef LibSL::DataStructures::Graph t_Graph; t_Graph g; ForIndex(v, mesh.numSurfaces()) { g.addNode(v); } ForIndex(v, mesh.numSurfaces()) { vector neighs = mesh.tri_neighbours(v); for (auto n : neighs) { g.addEdge(v, n, Loki::NullType()); } } LibSL::DataStructures::GraphAlgorithms::ConnectedComponents, TestFlattened> comps; Array visited; vector connected; _comps.clear(); while (comps.enumerateConnectedComponents(g, visited, connected, LibSL::DataStructures::GraphAlgorithms::DefaultEdgeTester(), TestFlattened(surfaces_to_flatten))) { _comps.push_back(vector()); for (auto n : connected) { _comps.back().push_back(n); } } } // --------------------------------------------------------------- double triangle_non_flatness(v3u tri, SLRModel *model) { double va = model->getVarByName(sprint("z_%03d", tri[0])).get(); double vb = model->getVarByName(sprint("z_%03d", tri[1])).get(); double vc = model->getVarByName(sprint("z_%03d", tri[2])).get(); double non_flatness = max((va - vb)*(va - vb), max((va - vc)*(va - vc), (vb - vc)*(vb - vc))); return non_flatness; } // -------------------------------------------------------------- double component_non_flatness(TetMesh& mesh, const std::vector& tris, SLRModel *model, double max_admissible) { double non_flatness = 0.0, max_non_flatness = 0.0; double comp_area = 0.0; for (auto t : tris) { v3u tri = mesh.surfaceTriangleAt(t); double ta = triangle_area_xy(mesh, tri); double nftri = triangle_non_flatness(tri, model); max_non_flatness = max(max_non_flatness, nftri); non_flatness += nftri * ta; comp_area += ta; } if (max_non_flatness > max_admissible) { return max_non_flatness; } else { return non_flatness / comp_area; } } ================================================ FILE: src/main.cpp ================================================ /* This work and all associated files are under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 A copy of the license full text is included in the distribution, please refer to it for details. (c) Jimmy Etienne and Sylvain Lefebvre */ // -------------------------------------------------------------- // ------------------ INCLUDES ---------------------------- // -------------------------------------------------------------- #include #include #include #include #include #include #include #include #include #include #include "Model.h" #include "gcode.h" #include "TetMesh.h" #include "MeshFormat_msh.h" #include "thicknesses.h" #include "helpers.h" // -------------------------------------------------------------- // ------------------ GUROBI ---------------------------- // -------------------------------------------------------------- #define PRESOLVE -1 // -1 = auto, 0 = off, 1 = conservative, 2 = agressive // -------------------------------------------------------------- // ------------------ PARAMETERS ---------------------------- // -------------------------------------------------------------- #define WEIGHT_OBJ_SLOPE 0.1 #define WEIGHT_OBJ_SMOOTHNESS 0.02 #define WEIGHT_OBJ_FLATTENING 30.0 #define CSTRT_COLLISION_SLOPE 1 #define CSTRT_THICKNESS 1 #define CSTRT_FOLDOVER 1 #define CSTRT_ANCHOR_POINT 0 #define CSTRT_ANCHOR_LAYER 1 & !CSTRT_ANCHOR_POINT #define OBJ_SURFACE_SLOPE 1 #define OBJ_SMOOTHNESS_L1 0 #define OBJ_SMOOTHNESS_L2 0 #define IGNORE_EMPTINESS 0 #define THRESHOLD_AREA_mm2 10.0 #define THRESHOLD_MIN_VOLUME_mm3 0.01 // -------------------------------------------------------------- using namespace std; // -------------------------------------------------------------- // ------------ COMMANDLINE PARAMETERS ---------------------- // -------------------------------------------------------------- string folder; string filename; double max_theta; // theta max : maximum angle printable double obj_angle; // phi : objectif angle if not flat or vertical ---- 0: vertical float normal_threshold = 0.95f; int target_num_layers = -1; float layer_thickness = default_layer_thickness; float compute_time = 0.0f; // time for a compute iteration (0 = no limit) int nb_threads = 4; bool fabricable_emptiness = false; bool skip_alignment = false; // -------------------------------------------------------------- void display_conf() { cout << endl << Console::yellow << "Normal threshold: " << normal_threshold << endl << endl; if (fabricable_emptiness) { cout << endl << Console::yellow << "<>" << endl << endl; } #if CSTRT_FOLDOVER cout << Console::green << "CSTRT_FOLDOVER " << endl; #else cout << Console::red << "NO CSTRT_FOLDOVER" << endl; #endif #if CSTRT_THICKNESS cout << Console::green << "CSTRT_THICKNESS " << min_thickness << " < " << layer_thickness << " < " << max_thickness << endl; #else cout << Console::red << "NO CSTRT_THICKNESS" << endl; #endif #if CSTRT_COLLISION_SLOPE cout << Console::green << "CSTRT_COLLISION_SLOPE " << -max_theta << " < ? < " << max_theta << endl; #else cout << Console::red << "NO CSTRT_COLLISION_SLOPE" << endl; #endif #if CSTRT_ANCHOR_POINT cout << Console::yellow << "CSTRT_ANCHOR_POINT ( /!\\ to much freedom)" << endl; #else #if CSTRT_ANCHOR_LAYER cout << Console::green << "CSTRT_ANCHOR_LAYER" << endl; #else cout << Console::red << "NO CSTRT_ANCHOR" << endl; #endif #endif #if OBJ_SMOOTHNESS_L1 cout << Console::cyan << "OBJ_SMOOTHNESS_L1" << endl; #endif #if OBJ_SMOOTHNESS_L2 cout << Console::cyan << "OBJ_SMOOTHNESS_L2" << endl; #endif #if OBJ_SURFACE_SLOPE cout << Console::cyan << "OBJ_SURFACE_SLOPE angle = " << obj_angle << endl; #endif cout << Console::cyan << "TARGET_NUM_LAYERS " << target_num_layers << endl; cout << Console::gray << endl; } /****************************************************************/ /********************* OBJECTIVES ***********************/ /****************************************************************/ //////////////////////////////////////////////////////////////////// // // // SMOOTHNESS // // // //////////////////////////////////////////////////////////////////// template void obj_smoothness_l2(TetMesh& mesh, map& h, const Array& mats, T_obj& obj) { double volume = 0.0; ForIndex(t, mesh.numTetrahedrons()) { volume += tetrahedron_volume(mesh, mesh.tetrahedronAt(t)); } ForIndex(t, mesh.numTetrahedrons()) { #if IGNORE_EMPTINESS if (!mesh.isInside(t)) { continue; } #endif v4u tet = mesh.tetrahedronAt(t); auto gradient = tetrahedron_gradient(mesh, h, mats, t); auto dhdx = gradient[0]; auto dhdy = gradient[1]; auto dhdz = gradient[2]; for (uint i_tet : mesh.tet_neighbours(t)) { if (i_tet == t) continue; v4u tet_n = mesh.tetrahedronAt(i_tet); auto gradient_n = tetrahedron_gradient(mesh, h, mats, i_tet); auto dhdx2 = gradient_n[0]; auto dhdy2 = gradient_n[1]; auto dhdz2 = gradient_n[2]; double vtets = tetrahedron_volume(mesh, tet) + tetrahedron_volume(mesh, tet_n); // weight double w = WEIGHT_OBJ_SMOOTHNESS * max(vtets, THRESHOLD_MIN_VOLUME_mm3) / volume; obj += w * (dhdz - dhdz2) * (dhdz - dhdz2); obj += w * (dhdx - dhdx2) * (dhdx - dhdx2); obj += w * (dhdy - dhdy2) * (dhdy - dhdy2); } } } //////////////////////////////////////////////////////////////////// // // // SLOPE // // // //////////////////////////////////////////////////////////////////// template void obj_slope(TetMesh& mesh, double tot_surface,map& h, T_obj& obj, set& to_flatten) { // determine normals (only z-component) Array normals; normals.allocate(mesh.numSurfaces()); ForIndex(t, mesh.numSurfaces()) { v3u tri = mesh.surfaceTriangleAt(t); v3f p[3] = { mesh.vertexAt(tri[0]), mesh.vertexAt(tri[1]), mesh.vertexAt(tri[2]) }; normals[t] = v3d(normalize_safe(cross(p[2] - p[0], p[1] - p[0]))); } ForIndex(s, mesh.numSurfaces()) { // Get the surface normal v3d n = normals[s]; // Ignore surfaces tagged as "to flatten". if (to_flatten.find(s) != to_flatten.end()) continue; // Ignore vertical ones if (abs(n[2]) < 1e-3) continue; v3u tri = mesh.surfaceTriangleAt(s); v3d p[3] = { v3d(mesh.vertexAt(tri[0])), v3d(mesh.vertexAt(tri[1])), v3d(mesh.vertexAt(tri[2])) }; v3d t = cross(n, v3d(0, 0, 1)); t = normalize_safe(t); v3d q = normalize_safe(cross(v3d(0, 0, 1), t)); v3d u = normalize_safe(cross(n, t)); // triangle project as a line along u double alpha = obj_angle * M_PI / 180.; v3d ut = cos(alpha) * v3d(0, 0, 1) * sign(u[2]) + sin(alpha) * q; double Ax = p[0][0]; double Ay = p[0][1]; T_var Az = h[tri[0]]; double Bx = p[1][0]; double By = p[1][1]; T_var Bz = h[tri[1]]; double Cx = p[2][0]; double Cy = p[2][1]; T_var Cz = h[tri[2]]; auto exprab = -Bz + Az + ((Bx - Ax)*u[0] + (By - Ay)*u[1] + (Bz - Az)*u[2]) * ut[2]; auto exprac = -Cz + Az + ((Cx - Ax)*u[0] + (Cy - Ay)*u[1] + (Cz - Az)*u[2]) * ut[2]; auto exprbc = -Cz + Bz + ((Cx - Bx)*u[0] + (Cy - By)*u[1] + (Cz - Bz)*u[2]) * ut[2]; // weight double w = WEIGHT_OBJ_SLOPE * triangle_area(mesh, tri) / tot_surface; obj += w * exprab * exprab; obj += w * exprac * exprac; obj += w * exprbc * exprbc; } } //////////////////////////////////////////////////////////////////// // // // SOFT FLATTENING // // // //////////////////////////////////////////////////////////////////// template void obj_soft_flattening(TetMesh& mesh, double tot_surface, map& h, T_obj& obj, set& surfaces_to_flatten) { for (auto s : surfaces_to_flatten) { v3u tri = mesh.surfaceTriangleAt(s); uint a = tri[0], b = tri[1], c = tri[2]; T_var ha = h[a]; T_var hb = h[b]; T_var hc = h[c]; // weight double w = WEIGHT_OBJ_FLATTENING * triangle_area(mesh, tri) / tot_surface; obj += w * (ha - hb)*(ha - hb); obj += w * (ha - hc)*(ha - hc); obj += w * (hb - hc)*(hb - hc); } } // -------------------------------------------------------------- bool gurobi_opt( TetMesh& mesh, const Array>& mats, Array& n_pts ) { double thres_flatteness_mm = max_thickness / 10.0; double max_admissible_non_flatteness_mm = max_thickness / 2.0; display_conf(); Elapsed time{}; time.elapsed(); // compute total surface area double tot_surface = 0.; ForIndex(s, mesh.numSurfaces()) { tot_surface += triangle_area(mesh, mesh.surfaceTriangleAt(s)); } // determine normals (only z-component) Array normals; normals.allocate(mesh.numSurfaces()); float bottomz = std::numeric_limits::max(); // i_bottom_shape is the lowest variable at the bottom of the shape // this is needed for slice alignment int i_bottom_shape = -1; ForIndex(t, mesh.numSurfaces()) { v3u tri = mesh.surfaceTriangleAt(t); v3f p[3] = { mesh.vertexAt(tri[0]), mesh.vertexAt(tri[1]), mesh.vertexAt(tri[2]) }; normals[t] = v3d(normalize_safe(cross(p[2] - p[0], p[1] - p[0]))); ForIndex(i, 3) { if (p[i][2] < bottomz) { bottomz = p[i][2]; i_bottom_shape = tri[i]; } } } // find out lowest domain position and max possible height on solution int min_ = 0; float maxz = -std::numeric_limits::max(); float minz = std::numeric_limits::max(); ForIndex(v, mesh.numVertices()) { if (mesh.vertexAt(v)[2] < mesh.vertexAt(min_)[2]) { min_ = v; } maxz = max(maxz, mesh.vertexAt(v)[2]); minz = min(minz, mesh.vertexAt(v)[2]); } float maxh = minz + ((maxz - minz) * layer_thickness / min_thickness); // =================== // ==== OPTIMIZER ==== // =================== cout << "Creating the model ... "; AutoPtr> model(new SLRModel()); model->setTimeLimit(compute_time); model->setNbThread(nb_threads); model->setPresolve(PRESOLVE); model->printDebug(true); // Create variables map> h; ForIndex(i, mesh.numVertices()) { h[i] = model->addVar(0.0, maxh, 0.0, sprint("z_%03d", i)); } /****************************************************************/ /******************** CONSTRAINTS ***********************/ /****************************************************************/ if (target_num_layers > -1) { set surface_vertices; ForIndex(t, mesh.numSurfaces()) { v3u tri = mesh.surfaceTriangleAt(t); ForIndex(i, 3) { surface_vertices.insert(tri[i]); } } for (auto v : surface_vertices) { if (v != i_bottom_shape) { model->addConstr(h[v] <= h[i_bottom_shape] + layer_thickness* target_num_layers); } } } SLRExpr obj = 0.0F; ForIndex(t, mesh.numTetrahedrons()) { v4u tet = mesh.tetrahedronAt(t); if (tetrahedron_volume(mesh,tet) < THRESHOLD_MIN_VOLUME_mm3) { continue; } auto gradient = tetrahedron_gradient(mesh, h, mats, t); auto dhdx = gradient[0]; auto dhdy = gradient[1]; auto dhdz = gradient[2]; //////////////////////////////////////////////////////////////////// // // // IGNORE EMPTINESS // // // //////////////////////////////////////////////////////////////////// #if IGNORE_EMPTINESS if (!mesh.isInside(t)) { continue; } #endif //////////////////////////////////////////////////////////////////// // // // NO FOLDOVER // // // //////////////////////////////////////////////////////////////////// #if CSTRT_FOLDOVER if (!mesh.isInside(t) && !fabricable_emptiness) { model->addConstr(dhdz >= 0.0); continue; } #endif //////////////////////////////////////////////////////////////////// // // // THICKNESS // // // //////////////////////////////////////////////////////////////////// #if CSTRT_THICKNESS sl_assert(min_thickness > 0); float ratio = max_thickness / min_thickness; model->addConstr(dhdz >= 1.0); model->addConstr(dhdz <= ratio); #endif //////////////////////////////////////////////////////////////////// // // // COLLISION SLOPE // // // //////////////////////////////////////////////////////////////////// #if CSTRT_COLLISION_SLOPE double theta = tan(max_theta * M_PI / 180.0); model->addConstr(-dhdz <= dhdx / theta); model->addConstr( dhdz >= dhdx / theta); model->addConstr(-dhdz <= dhdy / theta); model->addConstr( dhdz >= dhdy / theta); #endif } //////////////////////////////////////////////////////////////////// // // // ANCHOR // // // //////////////////////////////////////////////////////////////////// #if CSTRT_ANCHOR_POINT model->addConstr(h[min_] == 0); #elif CSTRT_ANCHOR_LAYER // first find out lowest point we would constraint ForIndex(i_pts, mesh.numVertices()) { if (fabs(mesh.vertexAt(i_pts)[2] - mesh.vertexAt(min_)[2]) < max_thickness / 2.0) { model->addConstr(h[i_pts] == (mesh.vertexAt(i_pts)[2] - mesh.vertexAt(min_)[2])); } } #endif // CSTRT_ANCHOR_POINT || CSTRT_ANCHOR_LAYER //////////////////////////////////////////////////////////////////// // // // FLATTEN // // // //////////////////////////////////////////////////////////////////// set surfaces_to_flatten; set relaxed_surfaces; ForIndex(s, mesh.numSurfaces()) { v3u tri = mesh.surfaceTriangleAt(s); if (abs(normals[s][2]) >= normal_threshold) { uint a = tri[0], b = tri[1], c = tri[2]; v3f pa = mesh.vertexAt(a); v3f pb = mesh.vertexAt(b); v3f pc = mesh.vertexAt(c); bool bottom = (fabs(pa[2] - bottomz) < 0.05) && (fabs(pb[2] - bottomz) < 0.05) && (fabs(pc[2] - bottomz) < 0.05); if (bottom) { model->addConstr(h[a] - h[b] == 0.0); model->addConstr(h[b] - h[c] == 0.0); } // Ignore flattening for overhanging triangles, unless they are flat already else if (normals[s][2] < 0 || normals[s][2] > 0.97) { surfaces_to_flatten.insert(s); } } } /****************************************************************/ /********************** MAIN LOOP ***********************/ /****************************************************************/ AutoPtr> scratch; model->update(); int cnt = 0; bool first_pass = true; bool last_pass = false; while (!surfaces_to_flatten.empty()) { AutoPtr> previous = scratch; scratch = AutoPtr>(new SLRModel(*model)); if (!previous.isNull()) { ForIndex(v, mesh.numVertices()) { double start = previous->getVarByName(sprint("z_%03d", v)).get(); scratch->getVarByName(sprint("z_%03d", v)).set(start); } } SLRExpr obj = 0.0f; { // compute total flattened area before filtering double tot_flat_area = 0.0; for (auto s : surfaces_to_flatten) { v3u tri = mesh.surfaceTriangleAt(s); tot_flat_area += triangle_area(mesh, tri); } // filter tiny components set filtered_set; vector> flattened; connected_components(mesh, surfaces_to_flatten, flattened); for (const auto& f : flattened) { double area = 0.0; for (const auto& t : f) { v3u tri = mesh.surfaceTriangleAt(t); area += triangle_area(mesh, tri); } if (area > THRESHOLD_AREA_mm2 && f.size() > 1 && (area / tot_flat_area > 0.05)) { for (const auto& t : f) { filtered_set.insert(t); } } } // Remove tiny or isolated areas, and displays the count int before = surfaces_to_flatten.size(); surfaces_to_flatten = filtered_set; int after = surfaces_to_flatten.size(); std::cerr << "removed " << before - after << " tiny or isolated flattened areas." << std::endl; } double tot_flatten_area = 0.0; for (auto s : surfaces_to_flatten) { v3u tri = mesh.surfaceTriangleAt(s); tot_flatten_area += triangle_area(mesh, tri); } // ==================== // ==== flattening ==== // ==================== obj_soft_flattening(mesh, tot_flatten_area, h, obj, surfaces_to_flatten); // Add alignement objective on each connected component double area_check = 0.0; bool all_aligned = true; if (!previous.isNull()) { cerr << Console::white << "alignment objectives" << Console::gray << endl; // get components vector > flattened; connected_components(mesh, surfaces_to_flatten, flattened); // sort by area vector > comp_by_area; ForIndex(i,flattened.size()) { double comp_area = 0.0; for (const auto& t : flattened[i]) { v3u tri = mesh.surfaceTriangleAt(t); comp_area += triangle_area(mesh, tri); } comp_by_area.push_back(make_pair(comp_area, i)); } std::sort(comp_by_area.begin(), comp_by_area.end()); // alignmenent double shape_bottom = previous->getVarByName(sprint("z_%03d", i_bottom_shape)).get(); cerr << "shape_bottom = " << shape_bottom << endl; // -> foreach component, by decreasing area // for (const auto& f : flattened) { ForRangeReverse(i,(int)comp_by_area.size()-1,0) { const auto& f = flattened[comp_by_area[i].second]; set uniquepts; double comp_area = 0.0; double comp_area_xy = 0.0; bool comp_flat = true; double comp_non_flatness = 0.0; for (const auto& t : f) { v3u tri = mesh.surfaceTriangleAt(t); comp_area += triangle_area(mesh, tri); comp_area_xy += triangle_area_xy(mesh, tri); ForIndex(i, 3) { uniquepts.insert(tri[i]); } // test if flat double non_flatness = triangle_non_flatness(tri, previous.raw()); comp_non_flatness = max(comp_non_flatness, non_flatness); if (non_flatness >= thres_flatteness_mm * thres_flatteness_mm) { comp_flat = false; } } double nfcomp = component_non_flatness(mesh,f,previous.raw(), max_admissible_non_flatteness_mm); comp_flat = (nfcomp < thres_flatteness_mm * thres_flatteness_mm); comp_non_flatness = nfcomp; area_check += comp_area; // compute snapping pos double avg = 0.0; for (const auto& t : f) { v3u tri = mesh.surfaceTriangleAt(t); double za = previous->getVarByName(sprint("z_%03d", tri[0])).get(); double zb = previous->getVarByName(sprint("z_%03d", tri[1])).get(); double zc = previous->getVarByName(sprint("z_%03d", tri[2])).get(); avg += triangle_area_xy(mesh, tri) * (za + zb + zc) / 3.0; } avg /= comp_area_xy; avg = avg - shape_bottom; double slice = round(avg / layer_thickness) * layer_thickness; // align? only if all flat bool align = comp_flat; // info if (align) cerr << Console::green; else cerr << Console::white; if (comp_flat) cerr << "[flat ] " << Console::gray; else cerr << Console::yellow << "[non flat] " << Console::gray; // cerr << "nonflat: " << comp_non_flatness; cerr << " alignement error: " << fabs(avg - slice) << " " << slice <<"-" << avg << " (A = " << comp_area << " w = " << (comp_area / tot_flatten_area) << ")" << endl; // do not align => skip if (!align) { all_aligned = false; break; // do not align smaller ones either } if (skip_alignment) { cerr << "==> skipping alignment (as per command line argument)\n"; break; } SLRExpr lavg = 0.0; for (const auto& t : f) { v3u tri = mesh.surfaceTriangleAt(t); SLRVar za = scratch->getVarByName(sprint("z_%03d", tri[0])); SLRVar zb = scratch->getVarByName(sprint("z_%03d", tri[1])); SLRVar zc = scratch->getVarByName(sprint("z_%03d", tri[2])); lavg += triangle_area_xy(mesh, tri) * (za + zb + zc) / 3.0; } lavg /= comp_area_xy; SLRExpr lexpr = lavg - scratch->getVarByName(sprint("z_%03d", i_bottom_shape)) - slice; // weight obj += 1.0 * (comp_area / tot_flatten_area) * lexpr*lexpr; } } scratch->update(); cerr << "area check: expected = " << tot_flatten_area << " found = " << area_check << endl; // ==================== // ==== smoothness ==== // ==================== #if OBJ_SMOOTHNESS_L2 obj_smoothness_l2(mesh, h, mats, obj); #endif // OBJ_SMOOTHNESS_L2 // =============== // ==== slope ==== // =============== #if OBJ_SURFACE_SLOPE // normal obj_slope(mesh, tot_surface, h, obj, surfaces_to_flatten); #endif // OBJ_SURFACE_SLOPE std::cout << "objective" << std::endl; scratch->setObjective(obj); std::cout << "optimize" << std::endl; scratch->optimize(); //std::cout << "Error : " << scratch->getObjectiveError(obj) << std::endl; // ============================================== { MeshFormat_stl stl; // ensures the STL format is registered TriangleMesh_Ptr tmp(new TriangleMesh_generic(mesh.numVertices(), mesh.numSurfaces())); ForIndex(s, mesh.numSurfaces()) { tmp->triangleAt(s) = mesh.surfaceTriangleAt(s); if (surfaces_to_flatten.find(s) != surfaces_to_flatten.end()) { v3u tri = tmp->triangleAt(s); std::swap(tri[0], tri[1]); tmp->triangleAt(s) = tri; } } ForIndex(v, mesh.numVertices()) { tmp->posAt(v) = mesh.vertexAt(v); tmp->posAt(v)[2] = scratch->getVarByName(sprint("z_%03d", v)).get() + mesh.vertexAt(min_)[2]; } saveTriangleMesh((folder + sprint("/tmp_after_%02d.stl", cnt++)).c_str(), tmp.raw()); } // ============================================== if (last_pass) break; // ============================================== // evaluate bool early_stop = true; std::vector > scores; std::map score_by_tri; { vector > flattened; connected_components(mesh, surfaces_to_flatten, flattened); for (const auto& f : flattened) { #if 1 { double nfcomp = component_non_flatness(mesh, f, scratch.raw(), max_admissible_non_flatteness_mm); if (nfcomp < thres_flatteness_mm * thres_flatteness_mm) continue; } #endif for (const auto& t : f) { v3u tri = mesh.surfaceTriangleAt(t); double non_flatness = triangle_non_flatness(tri, scratch.raw()); // flat in input? if (normals[t][2] > 0.97 || normals[t][2] < -0.97) { continue; // non_flatness = 0.0; // never relaxed } scores.push_back(make_pair(non_flatness, t)); score_by_tri[t] = non_flatness; } } std::sort(scores.begin(), scores.end()); } if (!scores.empty()) { cerr << Console::cyan; cerr << "best = " << scores.front().first << endl; cerr << "worse = " << scores.back().first << endl; cerr << "thres = " << thres_flatteness_mm * thres_flatteness_mm << endl; } cerr << "num flattening 'constraints' " << surfaces_to_flatten.size() << endl; // relax some bool none_removed = false; bool none_removed_at_all = true; /*while (!none_removed)*/ { /* TEST, comment to go back to normal */ none_removed = true; vector > flattened; set prev_relaxed = relaxed_surfaces; connected_components(mesh, surfaces_to_flatten, flattened); for (const auto& f : flattened) { // for each component #if 1 { double nfcomp = component_non_flatness(mesh, f, scratch.raw(), max_admissible_non_flatteness_mm); if (nfcomp < thres_flatteness_mm * thres_flatteness_mm) continue; } #endif double worst = 0.0; int worst_t = -1; bool none_removed_comp = true; for (const auto& t : f) { // for each triangle // flat in input? if (normals[t][2] > 0.97 || normals[t][2] < -0.97) { continue; // skip } // track worst if (score_by_tri[t] > worst) { worst = score_by_tri[t]; worst_t = t; } // on border? bool onborder = false; vector neighs = mesh.tri_neighbours(t); ForIndex(n, neighs.size()) { // check if neighbor has been relaxed if (prev_relaxed.find(neighs[n]) != prev_relaxed.end()) { // there is at least one relaxed neighbor nearby onborder = true; break; } } if (onborder && score_by_tri[t] >= thres_flatteness_mm * thres_flatteness_mm) { // kill none_removed = false; none_removed_comp = false; surfaces_to_flatten.erase(t); relaxed_surfaces.insert(t); } } if (none_removed_comp && worst_t > -1) { if (score_by_tri[worst_t] >= thres_flatteness_mm * thres_flatteness_mm) { // kill none_removed = false; surfaces_to_flatten.erase(worst_t); relaxed_surfaces.insert(worst_t); } } } if (!none_removed) { none_removed_at_all = false; } } if (!scores.empty()) { // safety: kill at least the worst (unless it is below theshold) if (none_removed_at_all && scores.back().first > thres_flatteness_mm*thres_flatteness_mm) { cerr << Console::yellow << "WARNING: relaxation safety triggered" << Console::gray << endl; //sl_assert(false); // SL: no longer supposed to happen none_removed_at_all = false; surfaces_to_flatten.erase(scores.back().second); relaxed_surfaces.insert(scores.back().second); } if (!first_pass) { if (scores.back().first < thres_flatteness_mm*thres_flatteness_mm && none_removed_at_all) { // termination on success! cerr << Console::gray; last_pass = true && all_aligned; } } } else { last_pass = true; } first_pass = false; cerr << "num flattening 'constraints' after relaxation " << surfaces_to_flatten.size() << endl; cerr << Console::gray; } model = scratch; /////////////////////////////////////////////// /////////////////////////////////////////////// //////////// ALIGNMENT CHECK /////////////// /////////////////////////////////////////////// /////////////////////////////////////////////// vector > flattened; connected_components(mesh, surfaces_to_flatten, flattened); double shape_bottom = model->getVarByName(sprint("z_%03d", i_bottom_shape)).get(); for (const auto& f : flattened) { set uniquepts; double area = 0.0; for (const auto& t : f) { v3u tri = mesh.surfaceTriangleAt(t); ForIndex(i, 3) { uniquepts.insert(tri[i]); } area += triangle_area(mesh, tri); } double avg = 0.0; for (auto v : uniquepts) { double vh = model->getVarByName(sprint("z_%03d", v)).get(); avg += vh; } avg /= (double)uniquepts.size(); double slice = shape_bottom + round((avg - shape_bottom) / layer_thickness)*layer_thickness; cerr << "alignement error: " << fabs(avg - slice) << "(area: " << area << ")" << endl; } //cerr << "=============== POSTPROCESS =============== " << endl; // //AutoPtr> post = postprocess(mesh,env,model,maxh,i_bottom_shape,surfaces_to_flatten); AutoPtr> post = model; // ============================================== // get the result ForArray(h, i) { SLRVar vh = post->getVarByName(sprint("z_%03d", i)); n_pts[i] = float(vh.get() + mesh.vertexAt(min_)[2]); } // ============================================== map z; for (uint i = 0; i < n_pts.size(); i++) { z[i] = n_pts[i]; } double lmin = std::numeric_limits::max(); double lmax = -std::numeric_limits::max(); ForIndex(i_srf, mesh.numSurfaces()) { ForIndex(i_ver, 3) { double z = n_pts[mesh.surfaceTriangleAt(i_srf)[i_ver]]; lmin = std::min(lmin, z); lmax = std::max(lmax, z); } } cerr << "Vertical extent: " << lmax - lmin << endl; // ============================================== int plot_nb_cstr = surfaces_to_flatten.size(); int nb_slices = floor((lmax - lmin) / layer_thickness); double plot_slope_obj = 0.0; obj_slope(mesh, tot_surface, z, plot_slope_obj, surfaces_to_flatten); double plot_slope_obj_incl_flat = 0.0; auto tmpVar = set(); obj_slope(mesh, tot_surface, z, plot_slope_obj_incl_flat, tmpVar); std::ofstream out; out.open(folder + "/objective_" + filename + ".csv", std::ios::app); out << normal_threshold << "," << obj_angle << "," << nb_slices << "," << time.elapsed() << "," << plot_slope_obj << "," << plot_slope_obj_incl_flat << endl; // ============================================== return model->hasSolution(); } // -------------------------------------------------------------- #include int main(int argc, char **argv) { string filepath = ""; max_theta = 30.0; obj_angle = 0.0; compute_time = 6*600; // Default is 60 min // command line TCLAP::CmdLine cmd("", ' ', "1.0"); TCLAP::UnlabeledValueArg pathArg("f", "filepath", true, "filepath", "file path" ); TCLAP::ValueArg tauArg("t", "tau" , "layer thickness (mm)" , false, 0.0f, "float"); TCLAP::ValueArg thetaArg("" , "theta" , "Maximum printing angle (degrees)", false, 30.0f, "float"); TCLAP::ValueArg thresholdArg("n", "normal-threshold", "Normal threshold" , false, 0.0f, "float"); TCLAP::ValueArg layerThArg("l", "layer-thickness" , "Layer thickness (mm)" , false, default_layer_thickness, "float"); TCLAP::ValueArg phiArg("" , "phi" , "deprecated" , false, 0.0, "float"); TCLAP::ValueArg ratioArg("r", "ratio" , "ratio" , false, 6.0, "float"); TCLAP::ValueArg numLayerArg("" , "numlayers" , "Target number of layers" , false, -1, "int"); TCLAP::ValueArg threadArg("T", "threads" , "number of threads used for optimisation, default: 4" , false, 4, "int"); TCLAP::ValueArg timeArg("c", "compute-time", "max compute time (s) for each iteration, default: 600s", false, 600, "int"); TCLAP::SwitchArg fabemptyArg("" , "fabempty" , "fabricable emptyness" , true); TCLAP::SwitchArg skipAlign ("" , "skipalign" , "skip top slice alignment" , false); // file and folder cmd.add(pathArg); // angles and thresholds cmd.add(tauArg); cmd.add(thetaArg); cmd.add(phiArg); // thicknesses and ratio cmd.add(layerThArg); cmd.add(numLayerArg); cmd.add(ratioArg); cmd.add(thresholdArg); cmd.add(fabemptyArg); cmd.add(skipAlign); // computation cmd.add(timeArg); cmd.add(threadArg); // Parsing cmd.parse(argc, argv); filepath = pathArg.getValue(); if ( thetaArg.isSet()) max_theta = thetaArg.getValue(); layer_thickness = layerThArg.getValue(); target_num_layers = numLayerArg.getValue(); max_thickness = layer_thickness; min_thickness = max_thickness / ratioArg.getValue(); normal_threshold = thresholdArg.isSet() ? thresholdArg.getValue() : cos(max_theta * M_PI / 180); fabricable_emptiness = fabemptyArg.getValue(); skip_alignment = skipAlign.getValue(); if ( timeArg.isSet()) compute_time = (float)timeArg.getValue(); if (threadArg.isSet()) nb_threads = threadArg.getValue(); ///////////////////////////// folder = removeExtensionFromFileName(filepath); filename = removeExtensionFromFileName(extractFileName(filepath)); try { TetMesh* mesh(TetMesh::load((folder + ".msh").c_str())); cerr << Console::white << "Mesh has " << mesh->numTetrahedrons() << " tets." << Console::gray << std::endl; if (numLayerArg.isSet()) { float bottomz = std::numeric_limits::max(); int i_bottom_shape = -1; ForIndex(t, mesh->numSurfaces()) { v3u tri = mesh->surfaceTriangleAt(t); v3f p[3] = { mesh->vertexAt(tri[0]), mesh->vertexAt(tri[1]), mesh->vertexAt(tri[2]) }; ForIndex(i, 3) { if (p[i][2] < bottomz) { bottomz = p[i][2]; } } } bool toMuch = bottomz > (layer_thickness * max_thickness / min_thickness) * target_num_layers; bool toFew = layer_thickness * target_num_layers < bottomz; if (toMuch || toFew) { cerr << Console::red << "Targeted number of layers unreachable, "; if (toMuch) cerr << "to much, " << mesh->getBBox().extent()[2] << " > " << (layer_thickness * max_thickness / min_thickness) * target_num_layers; if (toFew) cerr << "to few, " << mesh->getBBox().extent()[2] << " < " << layer_thickness * target_num_layers; cerr << Console::gray << std::endl; return 0; } } { // load triangle mesh createDirectory(folder.c_str()); mesh->save((folder + "/before.stl").c_str(), mesh); Array> mats; { // prepare tetrahedrons cout << "Compute all matrices... "; cerr << mesh->numTetrahedrons() << endl; mats.allocate(mesh->numTetrahedrons()); ForIndex(t, mesh->numTetrahedrons()) { mats[t] = mesh->getGradientMatrix(t); } saveArray(mats, (folder + "/tetmats").c_str()); cout << "done !" << endl; } // optimize Array displ(mesh->numVertices()); try { displ.fill(0.0f); gurobi_opt(*mesh, mats, displ); } catch (const SLRException& e) { cerr << Console::red << "Optimizer error " << e.getErrorCode() << ": " << e.getMessage() << Console::gray << endl; return -1; } cout << Console::green << "Solution found !" << endl; TetMesh tmp(mesh); ForArray(displ, i) { tmp.vertexAt(i)[2] = displ[i]; } tmp.save((folder + "/after.stl").c_str(), &tmp); saveArray(displ, (folder + "/displacements").c_str()); /////////////////////////////////////// if (thresholdArg.isSet() || layerThArg.isSet()) { std::ostringstream angle; angle.precision(0); angle << std::fixed << obj_angle; std::ostringstream cstr_angle; cstr_angle.precision(0); cstr_angle << std::fixed << max_theta; std::ostringstream normal; normal.precision(3); normal << std::fixed << normal_threshold; std::ostringstream lthick; lthick.precision(2); lthick << std::fixed << layer_thickness; std::string postfix = angle.str() + "_" + cstr_angle.str() + "_" + normal.str() + "_" + lthick.str(); saveArray(displ, (folder + "/displacements_" + postfix).c_str()); tmp.save((folder + "/after_" + postfix + ".stl").c_str(), &tmp); } } } catch (const SLRException& e) { cerr << Console::red << "Optimizer error " << e.getErrorCode() << ": " << e.getMessage() << Console::gray << endl; } catch (Fatal& e) { cerr << "[ERROR] " << e.message() << endl; } cerr << Console::gray; } // -------------------------------------------------------------- ================================================ FILE: src/thicknesses.h ================================================ // ------------------ VARIABLES ---------------------------- float min_thickness = 0.1f; // tau min : minimum thickness (constraint) float max_thickness = 0.6f; // tau max : maximum thickness (constraint) const float default_layer_thickness = 0.6f; // tau // 0.2 [0.05-0.3] // 0.7 [0.3-0.9] // also edit: mesh.bat , settings_curvi.xml // -------------------------------------------------------------- ================================================ FILE: src/uncurve.cpp ================================================ /* This work and all associated files are under the GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 A copy of the license full text is included in the distribution, please refer to it for details. (c) Jimmy Etienne and Sylvain Lefebvre */ #include #include #include #include #include #include #include #include #include #include #include #include "Model.h" #include "gcode.h" #include "TetMesh.h" #include "MeshFormat_msh.h" #include "thicknesses.h" // -------------------------------------------------------------- using namespace std; const float retract_e_length_mm = 6.0f; const float min_speed_mm_sec = 10.0f; const float max_speed_mm_sec = 30.0f; const double e_dampening = 0.025; const float c_delta_centering = 75.0f; bool um2 = false; bool a8 = false; bool deltaP = false; bool do_reflow = true; bool do_sim = false; // -------------------------------------------------------------- // Commandline parameters string filename; float layer_thickness = default_layer_thickness; // -------------------------------------------------------------- #define ScTP(a, b, c) dot(a, cross(b,c)) // -------------------------------------------------------------- float tetrahedron_volume(const Tuple& tet) { v3f vab = tet[1] - tet[0]; v3f vac = tet[2] - tet[0]; v3f vad = tet[3] - tet[0]; // ScTP computes the scalar triple product float v = 1.f / 6.f * ScTP(vab, vac, vad); return abs(v); } // -------------------------------------------------------------- float tetrahedron_volume(TetMesh& mesh, const v4u& tet) { return tetrahedron_volume(Tuple(mesh.vertexAt(tet[0]), mesh.vertexAt(tet[1]), mesh.vertexAt(tet[2]), mesh.vertexAt(tet[3]))); } // -------------------------------------------------------------- v4f tetrahedron_barycenter_coefs(const Tuple& tet, v3f pt) { v3f vap = pt - tet[0]; v3f vbp = pt - tet[1]; v3f vab = tet[1] - tet[0]; v3f vac = tet[2] - tet[0]; v3f vad = tet[3] - tet[0]; v3f vbc = tet[2] - tet[1]; v3f vbd = tet[3] - tet[1]; // ScTP computes the scalar triple product float va = 1.f / 6.f * ScTP(vbp, vbd, vbc); float vb = 1.f / 6.f * ScTP(vap, vac, vad); float vc = 1.f / 6.f * ScTP(vap, vad, vab); float vd = 1.f / 6.f * ScTP(vap, vab, vac); float v = 1.f / 6.f * ScTP(vab, vac, vad); float v_ = abs(v); v4f coeffs = v4f(va / v_, vb / v_, vc / v_, vd / v_); return coeffs; } // -------------------------------------------------------------- float triangle_area(const Tuple& tri) { v3f vab = tri[1] - tri[0]; v3f vac = tri[2] - tri[0]; float v = 1.f / 2.f * length(cross(vab, vac)); return abs(v); } // -------------------------------------------------------------- float triangle_area(TetMesh& mesh, const v3u& tri) { return triangle_area(Tuple(mesh.vertexAt(tri[0]), mesh.vertexAt(tri[1]), mesh.vertexAt(tri[2]))); } // -------------------------------------------------------------- bool sameSide(const v3f& v1, const v3f& v2, const v3f& v3, const v3f& v4, const v3f& pt) { v3f normal = cross(v2 - v1, v3 - v1); float dotV4 = dot(normal, v4 - v1); float dotPt = dot(normal, pt - v1); return (sign(dotV4) * sign(dotPt)) >= -1e-6f; } // -------------------------------------------------------------- inline bool isInTetrahedron(const Tuple& tet, const v3f& pt) { float vol = tetrahedron_volume(tet); if (vol < 0.01f) { // see curvislice thres_min_tet_volume_mm3 return false; } float eps = 1e-9f; v4f coefs = tetrahedron_barycenter_coefs(tet, pt); for (int i = 0; i < 4; ++i) { if (coefs[i] < -eps || coefs[i] > 1.f + eps) { return false; } } return true; /* return sameSide(tet[0], tet[1], tet[2], tet[3], pt) && sameSide(tet[1], tet[2], tet[3], tet[0], pt) && sameSide(tet[2], tet[3], tet[0], tet[1], pt) && sameSide(tet[3], tet[0], tet[1], tet[2], pt); */ } // -------------------------------------------------------------- template T_Type tetrahedral_interpolation(const Tuple& tet, v4f& coefs) { T_Type vab = tet[1] - tet[0]; T_Type vac = tet[2] - tet[0]; T_Type vad = tet[3] - tet[0]; T_Type interp = coefs[0] * tet[0] + coefs[1] * tet[1] + coefs[2] * tet[2] + coefs[3] * tet[3]; return interp; } // -------------------------------------------------------------- bool init = false; Array3D> tet_location; v3f split; // bad name, but just for here AABox meshbox; AABox getBBox(Tuple tet) { AABox bbox; ForIndex(i, 4) { bbox.addPoint(tet[i]); } return bbox; } int find_containing_tet(TetMesh* mesh, v3f& pt, bool use_in_and_out) { int res = 100; if (!init) { init = true; meshbox = mesh->getBBox(); tet_location.allocate(res, res, res); tet_location.fill(vector()); split = meshbox.maxCorner() - meshbox.minCorner(); split[0] /= res; split[1] /= res; split[2] /= res; ForIndex(itet, mesh->numTetrahedrons()) { Tuple tet; ForIndex(i, 4) { tet[i] = mesh->vertexAt(mesh->tetrahedronAt(itet)[i]); } AABox tetbox = getBBox(tet); v3i start = v3i(floor((tetbox.minCorner() - meshbox.minCorner()) / split)); v3i end = v3i(ceil((tetbox.maxCorner() - meshbox.minCorner()) / split)); for (int x = start[0]; x <= end[0]; ++x) { for (int y = start[1]; y <= end[1]; ++y) { for (int z = start[2]; z <= end[2]; ++z) { tet_location.at(x, y, z).emplace_back(itet); } } } } } v3i pos = v3i(round((pt - meshbox.minCorner()) / split)); ForIndex(i, 3) pos[i] = min(max(pos[i], 0), res - 1); const vector& tets = tet_location.at(pos[0], pos[1], pos[2]); // traverses the entire list, return the first solid, or the first encountered empty int itet_empty_containing = -1; for (int itet : tets) { Tuple tet; ForIndex(i, 4) { tet[i] = mesh->vertexAt(mesh->tetrahedronAt(itet)[i]); } if (isInTetrahedron(tet, pt)) { if (mesh->isInside(itet)) { return itet; } else { itet_empty_containing = itet; } } } return itet_empty_containing; } // -------------------------------------------------------------- enum e_step_type { e_Prime, e_Retract, e_Print, e_Travel, e_Ironing }; typedef struct { e_step_type type; v3f xyz; float e; float f; } t_step; #define SAMPLING 0.8f // -------------------------------------------------------------- void reflow(std::vector& _steps) { const double max_e_delta = 1.0; // optimize flow std::vector> vars; vars.resize(2*_steps.size()); // configure gurobi env AutoPtr> model(new SLRModel()); model->setTimeLimit(600); //model->setNbThread(8); model->setPresolve(-1); model->printDebug(true); double e_start = _steps.front().e; // vars ForIndex(i,_steps.size()) { if (_steps[i].type == e_Print) { vars[i] = model->addVar(0.0, (_steps.back().e - e_start) * 2.0f, 0.0, sprint("e_%03d", i)); vars[i+_steps.size()] = model->addVar(0.0, (_steps.back().e - e_start) * 2.0f, 0.0, sprint("a_%03d", i)); } } // constraints #if 1 SLRVar e_i_m_1; SLRVar a_i_m_1; bool first = true; v3f prev_pos; ForIndex(i, _steps.size()) { if (_steps[i].type == e_Print) { auto e_i = vars[i]; auto a_i = vars[i + _steps.size()]; if (!first) { // limit gradient on E model->addConstr(e_i <= e_i_m_1 + 1.0f * SAMPLING ); model->addConstr( e_i_m_1 - 1.0f * SAMPLING <= e_i); // compute a_i float w = min(1.0f, length(_steps[i].xyz - prev_pos) / SAMPLING); model->addConstr(a_i == a_i_m_1 + w * e_dampening * (e_i - a_i_m_1)); } else { model->addConstr(vars[i] == 0.0); // e_0 model->addConstr(vars[i+_steps.size()] == 0.0); // a_0 first = false; } prev_pos = _steps[i].xyz; e_i_m_1 = e_i; a_i_m_1 = a_i; } } #endif // objective for reflow double w_min = 0.0001; SLRExpr obj = 0.0f; unordered_map weights; Console::progressTextInit((int)_steps.size()); ForIndex(i, _steps.size()) { Console::progressTextUpdate(i); if (_steps[i].type == e_Print) { auto a_i = vars[i + _steps.size()]; double E_i = (_steps[i].e - e_start); obj += (a_i - E_i) * (a_i - E_i); } } Console::progressTextEnd(); LIBSL_TRACE; model->setObjective(obj); LIBSL_TRACE; model->optimize(); // set result float e = 0.0f; ForIndex(i, _steps.size()) { if (_steps[i].type == e_Print) { float v = (float)vars[i].get(); e = v; // _steps[i].e; } _steps[i].e = e; } } // -------------------------------------------------------------- void inv_curv(TetMesh* mesh, string filepath) { // inverse displacement Array h; loadArray(h, (filepath + "/displacements").c_str()); TetMesh* mesh_crv = new TetMesh(mesh); ForArray(h, i) { mesh_crv->vertexAt(i)[2] = h[i]; } Array> mats; loadArray(mats, (filepath + "/tetmats").c_str()); std::string gcode = loadFileIntoString((filepath + ".gcode").c_str()); gcode_start(gcode.c_str()); if (fabs(gcode_layer_thickness() - layer_thickness) > 1e-3f) { cerr << Console::red; cerr << "GCode thickness : " << gcode_layer_thickness() << endl; cerr << "Layer thickness : " << layer_thickness << endl; cerr << "=====================================================\n"; cerr << "=====================================================\n"; cerr << " GCode layer thickness does not match compiled parameter\n"; cerr << "=====================================================\n"; cerr << "=====================================================\n"; cerr << Console::gray; layer_thickness = gcode_layer_thickness(); exit(-1); } v4f offset(gcode_offset(), 0.0f); // this brings the gcode 'z=0' to object 'h=0' float zmin_object = std::numeric_limits::max(); float hmin_object = std::numeric_limits::max(); ForIndex(t, mesh->numTetrahedrons()) { if (mesh->isInside(t)) { ForIndex(i, 4) { zmin_object = min(zmin_object, mesh->vertexAt(mesh->tetrahedronAt(t)[i])[2]); hmin_object = min(hmin_object, h[mesh->tetrahedronAt(t)[i]]); } } } v2f centering = v2f(0.0f); if (deltaP) { centering = - 75.0f; } //////////////////////////// v4f pos, prev_pos; gcode_advance(); prev_pos = gcode_next_pos() + offset; std::vector< t_step > steps; float min_thick = std::numeric_limits::max(); float max_thick = -std::numeric_limits::max(); float z_clamp = -std::numeric_limits::max(); float z_last = -std::numeric_limits::max(); bool traveling = false; float total_e = 0.0f; // gather steps while (gcode_advance()) { if (gcode_do_prime()) { steps.push_back(t_step()); steps.back().e = total_e; steps.back().f = 0.0f; steps.back().xyz = v3f(0.0f,0.0f,z_last); steps.back().type = e_Prime; traveling = false; continue; } else if (gcode_do_retract()) { steps.push_back(t_step()); steps.back().e = total_e; steps.back().f = 0.0f; steps.back().xyz = v3f(0.0f, 0.0f, z_last); steps.back().type = e_Retract; traveling = true; continue; } // read gcode pos = gcode_next_pos() + offset; float f = gcode_speed(); // get distance v3f delta = v3f(pos - prev_pos); float dist = length(delta); int nb_steps = max(2, int(dist / SAMPLING)); ForIndex(step, nb_steps) { float a = step / float(nb_steps); float next_a = (step + 1) / float(nb_steps); // field sampling point ; note the half layer thickness shift to sample on the slicing plane v4f A = (a * pos + (1.f - a) * prev_pos) - v4f(0, 0, layer_thickness / 2.0f, 0.0f); v4f B = (next_a * pos + (1.f - next_a) * prev_pos) - v4f(0, 0, layer_thickness / 2.0f, 0.0f); v4u itet; Tuple tet, tet_crv; v4f coefs; bool A_inside = false; int i; v3f vectorA(A); if ((i = find_containing_tet(mesh_crv, vectorA, true)) != -1) { itet = mesh->tetrahedronAt(i); for (int i = 0; i < 4; i++) { tet[i] = mesh->vertexAt(itet[i]); tet_crv[i] = mesh_crv->vertexAt(itet[i]); } coefs = tetrahedron_barycenter_coefs(tet_crv, v3f(A)); A[2] = tetrahedral_interpolation(tet, coefs)[2]; A_inside = (mesh->isInside(i)); } else { // if no tet found, do nothing continue; } float ha = h[itet[0]]; float hb = h[itet[1]]; float hc = h[itet[2]]; float hd = h[itet[3]]; float grad_z_a = (ha - hd) * (float)mats[i][6] + (hb - hd) * (float)mats[i][7] + (hc - hd) * (float)mats[i][8]; if (A_inside) { min_thick = min(min_thick, layer_thickness / grad_z_a); max_thick = max(max_thick, layer_thickness / grad_z_a); } A[2] += layer_thickness * 0.5f / grad_z_a; v3f vectorB(B); if ((i = find_containing_tet(mesh_crv, vectorB, true)) != -1) { itet = mesh->tetrahedronAt(i); for (int i = 0; i < 4; i++) { tet[i] = mesh->vertexAt(itet[i]); tet_crv[i] = mesh_crv->vertexAt(itet[i]); } coefs = tetrahedron_barycenter_coefs(tet_crv, v3f(B)); B[2] = tetrahedral_interpolation(tet, coefs)[2]; } else { // if no tet found, do nothing // sl_assert(false); continue; } ha = h[itet[0]]; hb = h[itet[1]]; hc = h[itet[2]]; hd = h[itet[3]]; float grad_z_b = (ha - hd) * (float)mats[i][6] + (hb - hd) * (float)mats[i][7] + (hc - hd) * (float)mats[i][8]; B[2] += layer_thickness * 0.5f / grad_z_b; float delta_E = B[3] - A[3]; float delta_pos = length(v2f(B) - v2f(A)); float grad = 0.5f * grad_z_a + 0.5f * grad_z_b; // float grad = max( grad_z_a , grad_z_b ); float new_e = delta_E / grad; total_e += new_e; float ratio = delta_E / new_e; if (!um2) { f = gcode_speed() * grad; f = min(max_speed_mm_sec, max(min_speed_mm_sec, f)) * 60.f; } else { f = min_speed_mm_sec * 60.0f; } B[0] -= offset[0]; B[1] -= offset[1]; // adjust based on offset input/deformed object B[2] += -zmin_object; float z = B[2]; z_last = z; if (traveling) { sl_assert(!gcode_is_ironing()); z = max(B[2], z_clamp); } steps.push_back(t_step()); steps.back().e = total_e; steps.back().f = f; steps.back().xyz = v3f(B[0],B[1], max(0.0f, z)); steps.back().type = traveling ? e_Travel : (gcode_is_ironing() ? e_Ironing : e_Print); } // next prev_pos = pos; } cerr << "num steps: " << steps.size() << endl; //////////////////////////////////////////////////////// if (do_reflow) { #if 1 reflow(steps); #else std::vector< t_step > new_steps; // split into paths and solve each double e_prev = 0.0; int i = 0; while (i < steps.size()) { std::vector< t_step > sub_steps; while (steps[i].type != e_Retract && i < steps.size()) { sub_steps.push_back(steps[i]); i++; } sub_steps.push_back(steps[i]); i++; reflow(sub_steps); for (auto& step : sub_steps) { step.e += e_prev; } e_prev = sub_steps.back().e; new_steps.insert(new_steps.end(), sub_steps.begin(), sub_steps.end()); } steps = new_steps; #endif } //////////////////////////////////////////////////////// std::ofstream out_gcode((filepath + ".gcode").c_str(), ios::out | ios::trunc); if (!out_gcode) { std::cerr << "Erreur � l'ouverture !" << endl; return; } float actual_e = 0.0f; prev_pos = v4f(steps.front().xyz); ForIndex(s,steps.size()) { const auto& step = steps[s]; if (step.type == e_Prime) { if (um2) { out_gcode << "G1 Z" << std::setprecision(5) << step.xyz[2] << " ; prime (z correction)" << std::endl; out_gcode << "G11" << std::endl; } else { out_gcode << "G1 E" << std::setprecision(7) << step.e << " ; prime" << std::endl; } continue; } else if (step.type == e_Retract) { if (um2) { out_gcode << "G10" << std::endl; } else { out_gcode << "G1 E" << std::setprecision(7) << step.e - retract_e_length_mm << " ; retract" << std::endl; } continue; } else { if (step.type == e_Print) { float w = min(1.0f, length(step.xyz - v3f(prev_pos)) / SAMPLING); prev_pos = v4f(step.xyz); actual_e = actual_e + (step.e - actual_e) * (float)e_dampening * w; out_gcode << "G1 X" << step.xyz[0] + centering[0] << " Y" << step.xyz[1] + centering[1] << " Z" << max(0.0f, step.xyz[2]); if (do_sim) { out_gcode << " E" << std::setprecision(7) << actual_e; } else { out_gcode << " E" << std::setprecision(7) << step.e; } out_gcode << " F" << std::setprecision(5) << step.f << endl; } else { // lift up if ironing float z_lift = 0.0; if (step.type == e_Ironing) { const float nozzle_padding = 1.0f; if (s > 0 && s + 1 < steps.size()) { // if enough points around v3f m1 = steps[s - 1].xyz; v3f p1 = steps[s + 1].xyz; v3f delta = p1 - m1; if (sqLength(delta) > 1e-6f) { float z_delta = delta[2]; float agl = asin(z_delta / length(delta)); z_lift = abs(tan(agl) * nozzle_padding); } } } out_gcode << "G0 X" << step.xyz[0] + centering[0] << " Y" << step.xyz[1] + centering[1] << " Z" << max(0.0f, step.xyz[2] + z_lift) << " F" << std::setprecision(5) << step.f << endl; } } } out_gcode.close(); cerr << "min/max thickness encountered: " << min_thick << "/" << max_thick << endl; } // -------------------------------------------------------------- void inv_deform(TetMesh* mesh, string path) { // inverse displacement Array h; loadArray(h, (path + "/displacements").c_str()); TetMesh* mesh_crv = new TetMesh(mesh); ForArray(h, i) { mesh_crv->vertexAt(i)[2] = h[i]; } AABox bbox = mesh_crv->getBBox(); TriangleMesh *stl = loadTriangleMesh((path + ".stl").c_str()); ForIndex(v, stl->numVertices()) { MeshFormat_stl::t_VertexData *d = (MeshFormat_stl::t_VertexData*)stl->vertexDataAt(v); v4u itet; Tuple tet, tet_crv; v4f coefs; int i; if ((i = find_containing_tet(mesh_crv, d->pos, true)) != -1) { itet = mesh->tetrahedronAt(i); for (int i = 0; i < 4; i++) { tet[i] = mesh->vertexAt(itet[i]); tet_crv[i] = mesh_crv->vertexAt(itet[i]); } coefs = tetrahedron_barycenter_coefs(tet_crv, d->pos); d->pos[2] = tetrahedral_interpolation(tet, coefs)[2];; } else { if (!bbox.contain(d->pos)) { cerr << 'o'; } } } MeshFormat_stl meshformat; meshformat.save((path + "/uncurved.stl").c_str(), stl); } // -------------------------------------------------------------- int main(int argc, char **argv) { string path = ""; // command line TCLAP::CmdLine cmd("", ' ', "1.0"); TCLAP::UnlabeledValueArg dirArg("d", "path", true, ".", "path"); TCLAP::ValueArg layerThArg("l", "layer-thickness", "Layer thickness (mm)", false, default_layer_thickness, "float"); TCLAP::SwitchArg invArg("g", "gcode", "generate curved gcode", true); TCLAP::SwitchArg stlArg("s", "stl", "generate stl from msh with deformations", true); TCLAP::SwitchArg um2Arg("", "um2", "generate GCode for UM2", false); TCLAP::SwitchArg a8Arg("", "a8", "generate GCode for A8", false); TCLAP::SwitchArg deltaArg("", "delta", "generate GCode for the delta printer", false); TCLAP::SwitchArg rflwArg("", "reflow", "apply reflow", false); TCLAP::SwitchArg simArg("", "sim", "'simulate' nozzle pressure", false); cmd.add(invArg); cmd.add(stlArg); cmd.add(um2Arg); cmd.add(a8Arg); cmd.add(deltaArg); cmd.add(rflwArg); cmd.add(simArg); cmd.add(layerThArg); cmd.add(dirArg); cmd.parse(argc, argv); path = dirArg .getValue(); max_thickness = layerThArg.getValue(); um2 = um2Arg .getValue(); a8 = a8Arg .getValue(); deltaP = deltaArg.getValue(); do_reflow = rflwArg .getValue(); do_sim = simArg .getValue(); ///////////////////////////// layer_thickness = max_thickness; min_thickness = max_thickness / 6.0f; path = removeExtensionFromFileName(path); try { TetMesh* mesh(TetMesh::load((path + ".msh").c_str())); if (invArg.getValue() == false) { inv_curv(mesh, path); } else if (stlArg.getValue() == false) { inv_deform(mesh, path); } else { std::cerr << "nothing to do ..." << std::endl; } } catch (SLRException& e) { cerr << "[ERROR] " << e.getMessage() << endl; } catch (Fatal& e) { cerr << "[ERROR] " << e.message() << endl; } } // -------------------------------------------------------------- ================================================ FILE: toTetmesh.bat ================================================ @echo off set a=%1 set a=%a:/=\% if not exist %a%.msh ( .\tools\tetwild-windows\TetWild.exe --save-mid-result 2 %a%.stl -e 0.025 --targeted-num-v 1000 --is-laplacian move "%a%__mid2.000000.msh" "%a%.msh" ) ================================================ FILE: toTetmesh.sh ================================================ if [ -e "$1.msh" ] then echo "msh already generated" else ./tools/tetwild/TetWild --save-mid-result 2 $1.stl -e 0.025 --targeted-num-v 1000 --is-laplacian mv "$1__mid2.000000.msh" "$1.msh" fi ================================================ FILE: tools/icesl/icesl-printers/fff/curvi/features.lua ================================================ version = 2 bed_size_x_mm = 220 bed_size_y_mm = 220 bed_size_z_mm = 240 nozzle_diameter_mm_0 = 0.4 extruder_count = 1 z_offset = 0.0 priming_mm_per_sec = 40 z_layer_height_mm = 0.3 z_layer_height_mm_min = 0.01 z_layer_height_mm_max = 10.0 print_speed_mm_per_sec_min = 5 print_speed_mm_per_sec_max = 80 bed_temp_degree_c = 50 bed_temp_degree_c_min = 0 bed_temp_degree_c_max = 120 perimeter_print_speed_mm_per_sec_min = 5 perimeter_print_speed_mm_per_sec_max = 80 first_layer_print_speed_mm_per_sec = 10 first_layer_print_speed_mm_per_sec_min = 1 first_layer_print_speed_mm_per_sec_max = 80 for i=0,63,1 do _G['filament_diameter_mm_'..i] = 1.75 _G['filament_priming_mm_'..i] = 4.0 _G['extruder_temp_degree_c_' ..i] = 210 _G['extruder_temp_degree_c_'..i..'_min'] = 150 _G['extruder_temp_degree_c_'..i..'_max'] = 270 _G['extruder_mix_count_'..i] = 1 end add_checkbox_setting('gcode_ultimaker2','ultimaker2') add_checkbox_setting('gcode_delta','delta') ================================================ FILE: tools/icesl/icesl-printers/fff/curvi/printer.lua ================================================ version = 2 function comment(text) output('; ' .. text) end extruder_e = 0 extruder_e_restart = 0 function prep_extruder(extruder) end function header() output('o X ' .. gcode_to_model_x .. ' Y ' .. gcode_to_model_y .. ' Z ' .. gcode_to_model_z) output('t ' .. z_layer_height_mm) end function footer() end function layer_start(zheight) output(';()') if layer_id == 0 then output('G0 F600 Z' .. ff(zheight)) else output('G0 F100 Z' .. ff(zheight)) end -- output('G1 Z' .. f(zheight)) end function layer_stop() comment('') end function retract(extruder,e) -- speed = priming_mm_per_sec * 60; -- letter = 'E' -- output('G1 F' .. speed .. ' ' .. letter .. f(e - len - extruder_e_restart)) output('R') return e end function prime(extruder,e) -- speed = priming_mm_per_sec * 60; -- letter = 'E' -- output('G1 F' .. speed .. ' ' .. letter .. f(e + len - extruder_e_restart)) output('P') return e end current_extruder = 0 current_frate = 0 function select_extruder(extruder) end function swap_extruder(from,to,x,y,z) end function move_xyz(x,y,z) output('G1 X' .. f(x) .. ' Y' .. f(y) .. ' Z' .. f(z+z_offset)) end function move_xyze(x,y,z,e) to_mm_cube = 1.0 if gcode_ultimaker2 then r = filament_diameter_mm[extruders[0]] / 2 to_mm_cube = 3.14159 * r * r end if traveling == 1 then traveling = 0 -- start path if path_is_perimeter then output(';perimeter') elseif path_is_shell then output(';shell') elseif path_is_infill then output(';infill') elseif path_is_raft then output(';raft') elseif path_is_brim then output(';brim') elseif path_is_shield then output(';shield') elseif path_is_support then output(';support') elseif path_is_tower then output(';tower') elseif path_is_ironing then output(';ironing') end end extruder_e = e letter = 'E' instr = 'G' if path_is_ironing then instr = 'I' end if z == current_z then output(instr .. '1 F' .. f(current_frate) .. ' X' .. f(x) .. ' Y' .. f(y) .. ' ' .. letter .. ff((e-extruder_e_restart)*to_mm_cube)) else output(instr .. '1 F' .. f(current_frate) .. ' X' .. f(x) .. ' Y' .. f(y) .. ' Z' .. ff(z) .. ' ' .. letter .. ff((e-extruder_e_restart)*to_mm_cube)) current_z = z end end function move_e(e) to_mm_cube = 1.0 if gcode_ultimaker2 then r = filament_diameter_mm[extruders[0]] / 2 to_mm_cube = 3.14159 * r * r end extruder_e = e letter = 'E' output('G1 ' .. letter .. f((e - extruder_e_restart)*to_mm_cube)) end function set_feedrate(feedrate) current_frate = feedrate end function extruder_start() end function extruder_stop() end function progress(percent) end function set_extruder_temperature(extruder,temperature) end function set_fan_speed(speed) end ================================================ FILE: tools/icesl/settings_curvi.xml ================================================ ================================================ FILE: tools/icesl/settings_curvi_a8.xml ================================================ ================================================ FILE: tools/icesl/settings_curvi_delta.xml ================================================ ================================================ FILE: tools/icesl/settings_curvi_fig.xml ================================================ ================================================ FILE: tools/icesl/settings_curvi_um2.xml ================================================ ================================================ FILE: tools/icesl/settings_curvi_um2_no_iron.xml ================================================ ================================================ FILE: tools/tetviz/.gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto ================================================ FILE: tools/tetviz/.gitignore ================================================ # Prerequisites *.d # Compiled Object files *.slo *.lo *.o *.obj # Precompiled Headers *.gch *.pch # Compiled Dynamic libraries *.so *.dylib *.dll # Fortran module files *.mod *.smod # Compiled Static libraries *.lai *.la *.a *.lib # Executables *.exe *.out *.app !TetViz.exe ================================================ FILE: tools/tetviz/.gitmodules ================================================ [submodule "LibSL"] path = libs/LibSL url = https://github.com/JuDePom/LibSL ================================================ FILE: tools/tetviz/CMakeLists.txt ================================================ CMAKE_MINIMUM_REQUIRED(VERSION 2.6) if (WIN32) ADD_DEFINITIONS(-DWIN32) endif (WIN32) ADD_SUBDIRECTORY(libs) ADD_SUBDIRECTORY(src) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP") ================================================ FILE: tools/tetviz/libs/CMakeLists.txt ================================================ CMAKE_MINIMUM_REQUIRED(VERSION 2.6) ADD_SUBDIRECTORY(LibSL) ================================================ FILE: tools/tetviz/src/CMakeLists.txt ================================================ CMAKE_MINIMUM_REQUIRED(VERSION 2.6) ADD_EXECUTABLE( TetViz TetViz.h TetViz.cpp shade.fp shade.vp shade.h slicerror.fp slicerror.vp slicerror.h gcode.h gcode.cpp TetMesh.h TetMesh.cpp ) TARGET_LINK_LIBRARIES(TetViz LibSL LibSL_gl4 ) AUTO_BIND_SHADERS( shade slicerror ) INSTALL(TARGETS TetViz RUNTIME DESTINATION ${CMAKE_SOURCE_DIR} ) ================================================ FILE: tools/tetviz/src/TetMesh.cpp ================================================ #include "TetMesh.h" //--------------------------------------------------------------------------- #include "LibSL.precompiled.h" //--------------------------------------------------------------------------- using namespace LibSL::Mesh; #include using namespace LibSL::Errors; #include using namespace LibSL::Memory::Array; #include using namespace LibSL::Memory::Pointer; #include using namespace LibSL::Math; #include using namespace LibSL::CppHelpers; #include #include #include #include TetMesh::TetMesh() { } TetMesh::TetMesh(TetMesh* mesh) { for (auto vertex : mesh->m_vertices) { m_vertices.emplace_back(vertex); } for (auto tet : mesh->m_tetrahedrons) { m_tetrahedrons.emplace_back(tet); } for (auto tri : mesh->m_triangles) { m_triangles.emplace_back(tri); } for (auto srfs : mesh->m_surfaces) { m_surfaces.emplace_back(srfs); } } TetMesh::~TetMesh() { } size_t TetMesh::numVertices() { return m_vertices.size(); } v3f& TetMesh::vertexAt(uint n) { return m_vertices.at(n); } size_t TetMesh::numTetrahedrons() { return m_tetrahedrons.size(); } bool TetMesh::isInside(uint t) { return !m_tetrahedrons.at(t).second; } v4u& TetMesh::tetrahedronAt(uint t) { return m_tetrahedrons.at(t).first; } size_t TetMesh::numTriangles() { return m_triangles.size(); } v3u& TetMesh::triangleAt(uint t) { return m_triangles.at(t); } size_t TetMesh::numSurfaces() { return m_surfaces.size(); } v3u& TetMesh::surfaceTriangleAt(uint s) { return m_triangles.at(m_surfaces.at(s)); } using namespace std; //--------------------------------------------------------------------------- TetMesh* TetMesh::load(const char *fname) { TetMesh* mesh = new TetMesh(); mesh->m_mesh = AutoPtr(new MeshFormat_msh); mesh->m_mesh->parse(fname); MeshFormat_msh::msh_format_info format = mesh->m_mesh->m_format; MeshFormat_msh::msh_entity_data element_inout; // Check if the domain is tetrahedralized or just the object bool domain = false; for (auto data : format.element_data) { if (data.string_tags[0] == "\"in/out\"") { element_inout = data; domain = true; } } map> tris; vector srfTris; int nb_elements = format.elements.size(); srfTris.resize(nb_elements * 4); // assuming that the file only contains tets // faces uint fi = 0; ForArray(format.elements, n_tet) { // TODO: manage non tet bool in = domain && element_inout.values[n_tet][0] == 1.f; mesh->m_tetrahedrons.push_back(make_pair( v4u(format.elements.at(n_tet)[0] - 1, format.elements.at(n_tet)[1] - 1, format.elements.at(n_tet)[2] - 1, format.elements.at(n_tet)[3] - 1), in)); ForIndex(off, 4) { uint A = format.elements.at(n_tet)[(off + 0) % 4] - 1; uint B = format.elements.at(n_tet)[(off + 1) % 4] - 1; uint C = format.elements.at(n_tet)[(off + 2) % 4] - 1; uint _A = A, _B = B, _C = C; if (A > B) std::swap(A, B); if (B > C) std::swap(B, C); if (A > B) std::swap(A, B); // extract the surface v3u t(A, B, C); v3u r(_A, _B, _C); auto it = tris.find(t); if (it == tris.end()) { tris[t].first = r; if (in) { tris[t].second = 2; } else { tris[t].second = 1; } fi++; } else { if (in) { tris[t].first = r; tris[t].second += 2; } else { tris[t].second += 1; } } } } //vertices ForArray(mesh->m_mesh->m_format.nodes, n_ver) { v3f pos = mesh->m_mesh->m_format.nodes.at(n_ver); mesh->m_vertices.push_back(pos); } // tris & srf tris uint i = 0; for (auto it : tris) { mesh->m_triangles.push_back(it.second.first); if (it.second.second % 2) mesh->m_surfaces.push_back(i); i++; } mesh->reorientSurface(); // done return (mesh); } void TetMesh::save(const char *fname, TetMesh *mesh) { FILE *f = NULL; fopen_s(&f, fname, "wb"); if (f == NULL) { throw Fatal("[MeshFormat_msh::save] - cannot open file '%s' for writing", fname); } // header char header[80]; memset(header, 0x00, 80); sprintf(header, "LibSL_STL_1.0"); fwrite(header, sizeof(char), 80, f); // num triangles size_t nTris = mesh->numSurfaces(); fwrite(&nTris, sizeof(uint), 1, f); // vertices ForIndex(t, nTris) { v3u tri = mesh->surfaceTriangleAt(t); v3f nrm = cross(mesh->vertexAt(tri[1]) - mesh->vertexAt(tri[0]), mesh->vertexAt(tri[2]) - mesh->vertexAt(tri[0])); nrm = normalize_safe(nrm); v3f pt[3]; ForIndex(v, 3) { pt[v] = mesh->vertexAt(tri[v]); } fwrite(&nrm, sizeof(float), 3, f); fwrite(&pt, sizeof(float), 3 * 3, f); ushort attr = 0; fwrite(&attr, sizeof(ushort), 1, f); } fclose(f); } /* INPUT: A - array of pointers to rows of a square matrix having dimension N * Tol - small tolerance number to detect failure when the matrix is near degenerate * OUTPUT: Matrix A is changed, it contains both matrices L-E and U as A=(L-E)+U such that P*A=L*U. * The permutation matrix is not stored as a matrix, but in an integer vector P of size N+1 * containing column indexes where the permutation matrix has "1". The last element P[N]=S+N, * where S is the number of row exchanges needed for determinant computation, det(P)=(-1)^S */ int LUPDecompose(double **A, int N, double Tol, int *P) { int i, j, k, imax; double maxA, absA; for (i = 0; i <= N; i++) P[i] = i; //Unit permutation matrix, P[N] initialized with N for (i = 0; i < N; i++) { maxA = 0.0; imax = i; for (k = i; k < N; k++) if ((absA = fabs(A[k][i])) > maxA) { maxA = absA; imax = k; } if (maxA < Tol) return 0; //failure, matrix is degenerate if (imax != i) { //pivoting P swap(P[i], P[imax]); //pivoting rows of A swap(A[i], A[imax]); //counting pivots starting from N (for determinant) P[N]++; } for (j = i + 1; j < N; j++) { A[j][i] /= A[i][i]; for (k = i + 1; k < N; k++) A[j][k] -= A[j][i] * A[i][k]; } } return 1; //decomposition done } /* INPUT: A,P filled in LUPDecompose; b - rhs vector; N - dimension * OUTPUT: x - solution vector of A*x=b */ void LUPSolve(double **A, int *P, double *b, int N, double *x) { for (int i = 0; i < N; i++) { x[i] = b[P[i]]; for (int k = 0; k < i; k++) x[i] -= A[i][k] * x[k]; } for (int i = N - 1; i >= 0; i--) { for (int k = i + 1; k < N; k++) x[i] -= A[i][k] * x[k]; x[i] = x[i] / A[i][i]; } } /* INPUT: A,P filled in LUPDecompose; N - dimension * OUTPUT: IA is the inverse of the initial matrix */ void LUPInvert(double **A, int *P, int N, double **IA) { for (int j = 0; j < N; j++) { for (int i = 0; i < N; i++) { if (P[i] == j) IA[i][j] = 1.0; else IA[i][j] = 0.0; for (int k = 0; k < i; k++) IA[i][j] -= A[i][k] * IA[k][j]; } for (int i = N - 1; i >= 0; i--) { for (int k = i + 1; k < N; k++) IA[i][j] -= A[i][k] * IA[k][j]; IA[i][j] = IA[i][j] / A[i][i]; } } } /* INPUT: A,P filled in LUPDecompose; N - dimension. * OUTPUT: Function returns the determinant of the initial matrix */ double LUPDeterminant(double **A, int *P, int N) { double det = A[0][0]; for (int i = 1; i < N; i++) det *= A[i][i]; if ((P[N] - N) % 2 == 0) return det; else return -det; } #include "gurobi_c++.h" M3x3 TetMesh::getGradientMatrix(uint t) { M3x3 m(0.); v3f A = vertexAt(tetrahedronAt(t)[0]); v3f B = vertexAt(tetrahedronAt(t)[1]); v3f C = vertexAt(tetrahedronAt(t)[2]); v3f D = vertexAt(tetrahedronAt(t)[3]); A -= D; B -= D; C -= D; static GRBEnv env = GRBEnv(); GRBModel model = GRBModel(env); model.set(GRB_IntParam_OutputFlag, false); GRBVar M[9]; ForIndex(i, 9) { M[i] = model.addVar(-1000.0f, 1000.0f, m[i], GRB_CONTINUOUS); } model.addConstr(M[0] * A[0] + M[1] * B[0] + M[2] * C[0] == 1.); model.addConstr(M[0] * A[1] + M[1] * B[1] + M[2] * C[1] == 0.); model.addConstr(M[0] * A[2] + M[1] * B[2] + M[2] * C[2] == 0.); model.addConstr(M[3] * A[0] + M[4] * B[0] + M[5] * C[0] == 0.); model.addConstr(M[3] * A[1] + M[4] * B[1] + M[5] * C[1] == 1.); model.addConstr(M[3] * A[2] + M[4] * B[2] + M[5] * C[2] == 0.); model.addConstr(M[6] * A[0] + M[7] * B[0] + M[8] * C[0] == 0.); model.addConstr(M[6] * A[1] + M[7] * B[1] + M[8] * C[1] == 0.); model.addConstr(M[6] * A[2] + M[7] * B[2] + M[8] * C[2] == 1.); model.optimize(); ForIndex(i, 9) { m[i] = M[i].get(GRB_DoubleAttr_X); } // without optim /* double** M_2 = new double*[9]; for (int i = 0; i < 3; ++i) { M_2[i] = new double[9]; } double b[9] = { 1.0 , 0.0 , 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; double res[9] = { 0, 0, 0 , 0, 0, 0, 0, 0, 0}; for (int k = 0; k < 3; k++) { for (int i = 0; i < 3; i++) M_2[i][0] = A[i]; for (int i = 0; i < 3; i++) M_2[i][1] = B[i]; for (int i = 0; i < 3; i++) M_2[i][2] = C[i]; int permut[4] = { 0, 0, 0, 0 }; LUPDecompose(M_2, 3, 1E-18, permut); LUPSolve(M_2, permut, &b[k * 3], 3, &res[k * 3]); } for (int i = 0; i < 3; ++i) { delete[] M_2[i]; } delete[] M_2; for(int i = 0; i < 9; i++) m[i] = res[i]; */ return m; } vector& TetMesh::tet_neighbours(uint t) { if (m_tet_neighborhood.empty()) { for(int i = 0; i < m_tetrahedrons.size()-1; i++) { v4u origin = tetrahedronAt(i); for (int j = i + 1; j < m_tetrahedrons.size(); j++) { v4u curr = tetrahedronAt(j); int common = 0; ForIndex(a, 4) { ForIndex(b, 4) { if (curr[a] == origin[b]) { common++; } } } if (common == 3) { m_tet_neighborhood[i].push_back(j); m_tet_neighborhood[j].push_back(i); } } } } return m_tet_neighborhood[t]; } vector& TetMesh::tri_neighbours(uint t) { if (m_tri_neighborhood.empty()) { for (int i = 0; i < numSurfaces() - 1; i++) { v3u origin = surfaceTriangleAt(i); for (int j = i + 1; j < numSurfaces(); j++) { v3u curr = surfaceTriangleAt(j); int common = 0; ForIndex(a, 3) { ForIndex(b, 3) { if (curr[a] == origin[b]) { common++; } } } if (common == 2) { m_tri_neighborhood[i].push_back(j); m_tri_neighborhood[j].push_back(i); } } } } return m_tri_neighborhood[t]; } vector TetMesh::ver_neighbours(uint t) { if (m_ver_to_tris.empty()) { ForIndex (s, m_surfaces.size()) { ForIndex(v, 3) { m_ver_to_tris[v].push_back(s); } } } vector vec; for (uint s : m_ver_to_tris[t]) { ForIndex(v, 3) { if (m_triangles.at(s)[v] != t) { vec.push_back(m_triangles.at(s)[v]); } } } sort(vec.begin(), vec.end()); vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec; } uint TetMesh::getTetrahedronSurface(uint t) { v3u tri = m_triangles.at(t); for (int i = 0; i < m_tetrahedrons.size(); i++) { if (!m_tetrahedrons.at(i).second) continue; v4u tet = m_tetrahedrons.at(i).first; int common = 0; ForIndex(a, 4) { ForIndex(b, 3) { if (tet[a] == tri[b]) { common++; } } } if (common == 3) { return i; } } return 0; } AABox TetMesh::getBBox() { AABox bbox; for (v3f vertex : m_vertices) { bbox.addPoint(vertex); } return bbox; } void TetMesh::reorientSurface() { if (numSurfaces() == 0) return; Array visited(numSurfaces()); visited.fill(false); // build edge info map > edge_to_tris; ForIndex(t, numSurfaces()) { v3u tri = surfaceTriangleAt(t); ForIndex(i, 3) { v2i e = v2i(min(tri[i], tri[(i + 1) % 3]), max(tri[i], tri[(i + 1) % 3])); edge_to_tris[e].push_back(t); } } while (true) { // find a lowest triangle not visited int next = -1; float minz = FLT_MAX; ForIndex(t, numSurfaces()) { if (!visited[t]) { ForIndex(i, 3) { float z = vertexAt(surfaceTriangleAt(t)[i])[2]; if (z < minz) { minz = z; next = t; } } } } if (next == -1) { break; // done! } // orient 'next' v3u tn = surfaceTriangleAt(next); v3f nrm = cross(vertexAt(tn[1]) - vertexAt(tn[0]), vertexAt(tn[2]) - vertexAt(tn[0])); if (nrm[2] > 0) { swap(tn[0], tn[2]); surfaceTriangleAt(next) = tn; } // orient by local growth std::queue q; q.push(next); visited[next] = true; while (!q.empty()) { // pop current int curid = q.front(); v3u cur = surfaceTriangleAt(curid); q.pop(); // get neighbors ForIndex(i, 3) { v2i e = v2i(min(cur[i], cur[(i + 1) % 3]), max(cur[i], cur[(i + 1) % 3])); const vector& neighs = edge_to_tris[e]; if (neighs.size() == 2) { // only trust two-manifold edges ForIndex(n, neighs.size()) { if (!visited[neighs[n]]) { visited[neighs[n]] = true; // check orientation v3u tri_n = surfaceTriangleAt(neighs[n]); bool fliped = false; v2i e_cur = v2i(cur[i], cur[(i + 1) % 3]); ForIndex(j, 3) { v2i e_j = v2i(tri_n[j], tri_n[(j + 1) % 3]); if (e_j == e_cur) { fliped = true; break; } } if (fliped) { // flip swap(tri_n[0], tri_n[2]); surfaceTriangleAt(neighs[n]) = tri_n; } q.push(neighs[n]); } } } } } } // search for face at bottom to check if we have to flip all float bottomz = std::numeric_limits::max(); ForIndex(t, numSurfaces()) { ForIndex(i, 3) { v3f pt = vertexAt(surfaceTriangleAt(t)[i]); bottomz = min(bottomz, pt[2]); } } bool flip = false; ForIndex(t, numSurfaces()) { bool bottom = true; v3f pts[3]; ForIndex(i, 3) { v3f pt = vertexAt(surfaceTriangleAt(t)[i]); if (abs(pt[2] - bottomz) > 1e-3f) { bottom = false; } pts[i] = pt; } if (bottom) { // compute normal to check it faces down v3f nrm = cross(pts[1] - pts[0], pts[2] - pts[0]); if (length(nrm) > 1e-6f) { // can trust normal if (nrm[2] > 0) { // flip all flip = true; } // done break; } } } if (flip) { ForIndex(t, numSurfaces()) { v3u tri = surfaceTriangleAt(t); std::swap(tri[0], tri[1]); surfaceTriangleAt(t) = tri; } } } ================================================ FILE: tools/tetviz/src/TetMesh.h ================================================ #pragma once #include #include #include #include #include using namespace LibSL::Math; using namespace std; typedef Tuple M3x3; class TetMesh { private : AutoPtr m_mesh; vector> m_tetrahedrons; vector m_vertices; vector m_triangles; vector m_surfaces; map> m_tet_neighborhood; map> m_tri_neighborhood; map> m_ver_to_tris; public: TetMesh(); TetMesh(TetMesh*); ~TetMesh(); static TetMesh* load(const char *fname); static void save(const char *fname, TetMesh *mesh); size_t numVertices(); v3f& vertexAt(uint n); size_t numTetrahedrons(); bool isInside(uint t); v4u& tetrahedronAt(uint t); vector& tet_neighbours(uint t); vector& tri_neighbours(uint t); vector ver_neighbours(uint t); uint getTetrahedronSurface(uint t); size_t numTriangles(); v3u& triangleAt(uint t); size_t numSurfaces(); v3u& surfaceTriangleAt(uint s); M3x3 getGradientMatrix(uint t); AABox getBBox(); void reorientSurface(); }; ================================================ FILE: tools/tetviz/src/TetViz.cpp ================================================ #include "TetViz.h" #include "shade.h" #include "slicerror.h" #include #include #include #include #include #include #include #include using namespace LibSL::Mesh; using namespace LibSL; // -------------------------------------------------------------- using namespace std; // -------------------------------------------------------------- // -------------------------------------------------------------- // -------------------------------------------------------------- double thickness = 0.6; ///////// SL:WARNING!!!! hard coded thickness (also elsewehre) // -------------------------------------------------------------- // -------------------------------------------------------------- // -------------------------------------------------------------- LIBSL_WIN32_FIX GLUX_LOAD(GL_VERSION_2_0) // -------------------------------------------------------------- #include TCLAP::UnlabeledValueArg dirArg("a", "dir", true, "models\\", "directory name"); TCLAP::UnlabeledValueArg fileArg("b", "file", true, "filename", "file name"); TCLAP::ValueArg fieldArg("f", "field", "", false, "", "field path"); TCLAP::ValueArg errorArg("e", "error", "compute error", false, 0, "int"); TCLAP::ValueArg thickArg("l", "", "base layer thickess", false, 0.6, "float"); TCLAP::SwitchArg screenshotArg("s", "screenshot", "generate screenshot", false); TCLAP::SwitchArg deformedArg("d", "deformed", "", false); TCLAP::SwitchArg reversededArg("r", "reversed", "", false); TCLAP::ValueArg yPlaneArg("y", "slice", "", false, 0.5, "float"); TCLAP::ValueArg posArg("p", "position", "screenshot position (F1, F2, ...), default: 1", false, "001", "int"); // -------------------------------------------------------------- #define SCREEN_W 1024 #define SCREEN_H 1024 AutoBindShader::shade g_Sh; GLuint g_ShAttribH; GLuint g_ShAttribW; GLuint g_ShAttribGradHdZ; AutoBindShader::slicerror g_ShError; GLuint g_ShErrorAttribH; GLuint g_ShErrorAttribGradHdZ; #include "TetMesh.h" MeshFormat_stl g_stlformat; AutoPtr g_Mesh; //TriangleMesh_Ptr g_MeshStl; //MeshRenderer* g_Renderer; float slice = 0.5f; Array h; int displaymode = 1; bool g_DrawTetsOrMesh = true; bool g_DrawDeformed = false; bool g_Screenshot = false; Array> g_grad_mats; int g_i_bottom_shape = -1; float g_bottomz = std::numeric_limits::max(); float g_topz = - std::numeric_limits::max(); float g_extent_h = 0.0f; bool g_ComputeError = false; enum e_ErrorType {e_Curved = 0, e_Adaptive = 1, e_Uniform = 2}; e_ErrorType g_ErrorToCompute = e_Curved; // -------------------------------------------------------------- bool g_doScreenshot = false; bool g_Reversed = false; // -------------------------------------------------------------- map tris_to_tets; void buildTrisToTet() { if (tris_to_tets.empty()) { ForIndex(t, g_Mesh->numTetrahedrons()) { if (!g_Mesh->isInside(t)) continue; ForIndex(off, 4) { v3u tri; ForIndex(i, 3) { tri[i] = g_Mesh->tetrahedronAt(t)[(off + i) % 4]; } // sort tri if (tri[0] > tri[1]) std::swap(tri[0], tri[1]); if (tri[1] > tri[2]) std::swap(tri[1], tri[2]); if (tri[0] > tri[1]) std::swap(tri[0], tri[1]); tris_to_tets[tri] = t; } } } } // -------------------------------------------------------------- void mainKeyboard(unsigned char key) { static float speed = 1.0f; static char last = ' '; if (key == 'q') { TrackballUI::exit(); } else if (key == ' ') { displaymode = (displaymode + 1) % 4; } else if (key == 'm') { g_DrawTetsOrMesh = !g_DrawTetsOrMesh; } else if (key == 'd') { g_DrawDeformed = !g_DrawDeformed; } else if (key == 'r') { g_Reversed = !g_Reversed; } else if (key == 's') { g_Screenshot = true; } else if (key == '*') { g_ComputeError = !g_ComputeError; } else if (key == '/') { g_ErrorToCompute = (e_ErrorType)(((int)g_ErrorToCompute + 1) % 3); } if (key == '+') { slice = min(slice + 0.01, 1.00); } if (key == '-') { slice = max(slice - 0.01, 0.00); } } // -------------------------------------------------------------- void mainAnimate(double time, float elapsed) { } // -------------------------------------------------------------- void mainOnReshape(uint x, uint y) { } // -------------------------------------------------------------- void drawTriangle(v4f *pts, int a, int b, int c) { glVertexAttrib1f(g_ShAttribH, pts[a][3]); glVertex3fv(&pts[a][0]); glVertexAttrib1f(g_ShAttribH, pts[b][3]); glVertex3fv(&pts[b][0]); glVertexAttrib1f(g_ShAttribH, pts[c][3]); glVertex3fv(&pts[c][0]); } // -------------------------------------------------------------- void render_tets() { if (g_Reversed) { g_Sh.u_ClipDir.set(-1); } else { g_Sh.u_ClipDir.set(1); } float plane_y = slice * g_Mesh->getBBox().extent()[1] + g_Mesh->getBBox().minCorner()[1]; glEnable(GL_CLIP_DISTANCE0); glDisable(GL_CULL_FACE); g_Sh.u_ClipY.set(plane_y + (g_Reversed ? 0.01f : -0.01f)); glBegin(GL_TRIANGLES); ForIndex(t, g_Mesh->numTetrahedrons()) { ForIndex(off, 4) { ForIndex(i, 3) { int v = g_Mesh->tetrahedronAt(t)[(off + i) % 4]; v3f pos = g_Mesh->vertexAt(v); glVertexAttrib1f(g_ShAttribH, h[v]); glVertexAttrib1f(g_ShAttribW, g_Mesh->isInside(t) ? 0.0f : 1.0f); glVertex3f(pos[0], pos[1], pos[2]); } } } glEnd(); glDisable(GL_CULL_FACE); g_Sh.u_ClipY.set(plane_y + (g_Reversed ? -0.01f : 0.01f)); g_Sh.u_Deform.set(g_DrawDeformed ? 1 : 0); glBegin(GL_TRIANGLES); ForIndex(t, g_Mesh->numTetrahedrons()) { AAB<3> tetbx; ForIndex(off, 4) { v3f pos = g_Mesh->vertexAt(g_Mesh->tetrahedronAt(t)[off]); tetbx.addPoint(pos); } // if outside and hits plane if (!g_Mesh->isInside(t)) { if (tetbx.minCorner()[1] <= plane_y && plane_y <= tetbx.maxCorner()[1]) { // intersect! int ni = 0; v4f intersects[16]; ForIndex(o0, 4) { ForRange(o1, o0 + 1, 3) { v3f v0 = g_Mesh->vertexAt(g_Mesh->tetrahedronAt(t)[o0]); v3f v1 = g_Mesh->vertexAt(g_Mesh->tetrahedronAt(t)[o1]); v4f p0 = v4f(v0, h[g_Mesh->tetrahedronAt(t)[o0]]); v4f p1 = v4f(v1, h[g_Mesh->tetrahedronAt(t)[o1]]); if (p0[1] > p1[1]) { std::swap(p0, p1); } if (p0[1] < plane_y && plane_y <= p1[1]) { // intersection exists intersects[ni++] = (p0 + (p1 - p0) * ((plane_y - p0[1]) / (p1[1] - p0[1]))); sl_assert(ni < 16); } } } glVertexAttrib1f(g_ShAttribW, 1.0f); if (ni == 3) { // draw! drawTriangle(intersects, 0, 1, 2); } else if (ni == 4) { // draw! drawTriangle(intersects, 0, 1, 2); drawTriangle(intersects, 0, 1, 3); drawTriangle(intersects, 0, 2, 3); } } } } glEnd(); LIBSL_GL_CHECK_ERROR; } // -------------------------------------------------------------- void render_mesh() { buildTrisToTet(); // draw mesh glBegin(GL_TRIANGLES); glVertexAttrib1f(g_ShAttribW, 0.0f); ForIndex(i_srf, g_Mesh->numSurfaces()) { ForIndex(i, 3) { v3u tri = g_Mesh->surfaceTriangleAt(i_srf); v3u key = tri; if (key[0] > key[1]) std::swap(key[0], key[1]); if (key[1] > key[2]) std::swap(key[1], key[2]); if (key[0] > key[1]) std::swap(key[0], key[1]); int t = tris_to_tets[key]; v4u tet = g_Mesh->tetrahedronAt(t); double ha = h[tet[0]]; double hb = h[tet[1]]; double hc = h[tet[2]]; double hd = h[tet[3]]; double tri_grad_h_dz = (ha - hd) * (float)g_grad_mats[t][6] + (hb - hd) * (float)g_grad_mats[t][7] + (hc - hd) * (float)g_grad_mats[t][8]; v3f pos = g_Mesh->vertexAt(tri[i]); if (g_ErrorToCompute == e_Curved) { glVertexAttrib1f(g_ShAttribH, h[g_Mesh->surfaceTriangleAt(i_srf)[i]]); glVertexAttrib1f(g_ShAttribGradHdZ, 1.0f / (float)tri_grad_h_dz); } else { glVertexAttrib1f(g_ShAttribGradHdZ, 1.0f); glVertexAttrib1f(g_ShAttribH, pos[2]); } if (g_DrawDeformed) { glVertex3f(pos[0], pos[1], pos[2]); } else { glVertex3f(pos[0], pos[1], h[g_Mesh->surfaceTriangleAt(i_srf)[i]]); } } } glEnd(); } // -------------------------------------------------------------- void makeAdaptiveSequence(int num_layers, Array& sequence, GLTexBuffer& tex_sequence) { // static int num_layers = 0; // num_layers = (num_layers+1)%155; if (g_ErrorToCompute == e_Adaptive) { string filename = dirArg.getValue() + fileArg.getValue() + sprint("/%.1f/sequence_%04d.array_v3d",thickness,num_layers); if (!LibSL::System::File::exists(filename.c_str())) { cerr << "cannot find sequence " << filename << endl; exit(-1); } loadArray(sequence, filename.c_str()); } if (!sequence.empty()) { tex_sequence.init(2 * sequence.size() * sizeof(float), GL_R32F); Array rawseq(sequence.size()); ForIndex(i, sequence.size()) { rawseq[i][0] = (float)sequence[i][0]; rawseq[i][1] = (float)sequence[i][1]; } tex_sequence.writeTo(rawseq); } } // -------------------------------------------------------------- // This below is highly innefficient, but that is not the goal is it? double render_error() { // #define DEBUG_ERROR GLProtectViewport vp; RenderTarget2DRGBA rt(2048,2048); int num_layers = ceil(g_extent_h / thickness); Array sequence; GLTexBuffer tex_sequence; if (g_ErrorToCompute == e_Adaptive) { makeAdaptiveSequence(num_layers, sequence, tex_sequence); } #ifndef DEBUG_ERROR rt.bind(); glViewport(0, 0, rt.w(), rt.h()); #endif glClearColor(0, 0, 0, 0); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); GLTexBuffer errors; errors.init(rt.w()*rt.h()*sizeof(uint), GL_R32UI); Array rawdata(rt.w()*rt.h()); rawdata.fill(0); errors.writeTo(rawdata); glMemoryBarrier(GL_ALL_BARRIER_BITS); AAB<3> bx = g_Mesh->getBBox(); g_ShError.begin(); // SL: NOTE: view is distorted but this is taken into account below when computing the final error // float max_ex = max(bx.extent()[0], bx.extent()[1]); float l = bx.minCorner()[0];//bx.center()[0] - max_ex / 2.0f; float r = bx.maxCorner()[0];//bx.center()[0] + max_ex / 2.0f; float t = bx.minCorner()[1];//bx.center()[1] - max_ex / 2.0f; float b = bx.maxCorner()[1];//bx.center()[1] + max_ex / 2.0f; g_ShError.u_matrix.set( orthoMatrixGL( l,r,t,b,-bx.minCorner()[2], -bx.maxCorner()[2] ) ); //g_ShError.u_matrix.set(perspectiveMatrixGL(float(M_PI / 8.0), 1.0f, 1.0f, 1000.0f) * TrackballUI::matrix()); if (g_ErrorToCompute == e_Curved) { g_ShError.u_v_h_min.set(h[g_i_bottom_shape]); } else { g_ShError.u_v_h_min.set(g_bottomz); } float thu = (g_topz - g_bottomz) / (float)num_layers; if (g_ErrorToCompute == e_Uniform) { // compute thickness giving the correct number of layers g_ShError.u_thickness.set( thu ); } else { g_ShError.u_thickness.set( (float)thickness); } g_ShError.u_base_thickness.set((float)thickness); glBindImageTexture(0, errors.glTexId(), 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI); g_ShError.u_Errors.set(0); if (!sequence.empty()) { glBindImageTexture(1, tex_sequence.glTexId(), 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32F); g_ShError.u_Sequence.set(1); g_ShError.u_SequenceLength.set((int)sequence.size()); } else { g_ShError.u_SequenceLength.set(0); } // draw mesh buildTrisToTet(); glBegin(GL_TRIANGLES); ForIndex(i_srf, g_Mesh->numSurfaces()) { v3u tri = g_Mesh->surfaceTriangleAt(i_srf); v3u key = tri; if (key[0] > key[1]) std::swap(key[0], key[1]); if (key[1] > key[2]) std::swap(key[1], key[2]); if (key[0] > key[1]) std::swap(key[0], key[1]); int t = tris_to_tets[key]; v4u tet = g_Mesh->tetrahedronAt(t); double ha = h[tet[0]]; double hb = h[tet[1]]; double hc = h[tet[2]]; double hd = h[tet[3]]; double tri_grad_h_dz = (ha - hd) * (float)g_grad_mats[t][6] + (hb - hd) * (float)g_grad_mats[t][7] + (hc - hd) * (float)g_grad_mats[t][8]; ForIndex(i, 3) { v3f pos = g_Mesh->vertexAt(tri[i]); if (g_ErrorToCompute == e_Curved) { glVertexAttrib1f(g_ShErrorAttribGradHdZ, 1.0f / (float)tri_grad_h_dz); glVertexAttrib1f(g_ShErrorAttribH, h[g_Mesh->surfaceTriangleAt(i_srf)[i]]); } else { glVertexAttrib1f(g_ShErrorAttribGradHdZ, 1.0f); glVertexAttrib1f(g_ShErrorAttribH, pos[2]); } glVertex3f(pos[0], pos[1], pos[2]); } } glEnd(); g_ShError.end(); #ifndef DEBUG_ERROR rt.unbind(); #endif glMemoryBarrier(GL_ALL_BARRIER_BITS); glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); #ifndef DEBUG_ERROR errors.readBack(rawdata); errors.terminate(); const double fxp = 4096.0; double sum_of_all = 0.0; ForArray(rawdata, i) { sum_of_all += thickness * 0.5 * ((double)rawdata[i]) / fxp; } double volume_error = sum_of_all * (bx.extent()[0] * bx.extent()[1]) / (rt.w() * rt.h()); if (g_ErrorToCompute == e_Uniform) cerr << "uniform "; if (g_ErrorToCompute == e_Curved) cerr << "curved "; if (g_ErrorToCompute == e_Adaptive) cerr << "adaptive "; cerr << " error : " << volume_error << " mm^3"; if (g_ErrorToCompute == e_Uniform) cerr << " ( num layers : " << ceil((g_topz - g_bottomz) / thu) << ", thickness : " << thu << ") "; if (g_ErrorToCompute == e_Adaptive) cerr << " ( num layers : " << num_layers << " )"; cerr << endl; // store error in file if (errorArg.isSet()) { std::string freport = dirArg.getValue() + "..\\" + fileArg.getValue() + ".txt"; ofstream f(freport, ios::app); if (g_ErrorToCompute == e_Curved) { // external script is expected to call on curve first, so this make a header f << endl; f << fieldArg.getValue() << endl; } if (g_ErrorToCompute == e_Uniform) f << "uniform "; if (g_ErrorToCompute == e_Curved) f << "curved "; if (g_ErrorToCompute == e_Adaptive) f << "adaptive "; f << " error : " << volume_error << " mm^3"; if (g_ErrorToCompute == e_Uniform) f << " ( num layers : " << ceil((g_topz - g_bottomz) / thu) << ", thickness : " << thu << ") "; if (g_ErrorToCompute == e_Adaptive) f << " ( num layers : " << num_layers << " )"; f << " [" << thickness << "] "; f << endl; f.close(); exit(0); } return volume_error; #else return 0.0f; #endif } // -------------------------------------------------------------- void render_bbox() { glDisable(GL_CLIP_DISTANCE0); /// draw bbox v3f min = g_Mesh->getBBox().minCorner(); v3f max = g_Mesh->getBBox().maxCorner(); glLineWidth(2.5); glColor3f(1.0, 1.0, 1.0); glBegin(GL_LINES); glVertex3f(min[0], min[1], min[2]); glVertex3f(max[0], min[1], min[2]); glVertex3f(max[0], min[1], min[2]); glVertex3f(max[0], max[1], min[2]); glVertex3f(max[0], max[1], min[2]); glVertex3f(min[0], max[1], min[2]); glVertex3f(min[0], max[1], min[2]); glVertex3f(min[0], min[1], min[2]); glVertex3f(min[0], min[1], max[2]); glVertex3f(max[0], min[1], max[2]); glVertex3f(max[0], min[1], max[2]); glVertex3f(max[0], max[1], max[2]); glVertex3f(max[0], max[1], max[2]); glVertex3f(min[0], max[1], max[2]); glVertex3f(min[0], max[1], max[2]); glVertex3f(min[0], min[1], max[2]); glVertex3f(min[0], min[1], min[2]); glVertex3f(min[0], min[1], max[2]); glVertex3f(max[0], min[1], min[2]); glVertex3f(max[0], min[1], max[2]); glVertex3f(max[0], max[1], min[2]); glVertex3f(max[0], max[1], max[2]); glVertex3f(min[0], max[1], min[2]); glVertex3f(min[0], max[1], max[2]); glEnd(); } // -------------------------------------------------------------- void take_screenshot() { ImageRGBA_Ptr img = ImageRGBA_Ptr(new ImageRGBA(SCREEN_W, SCREEN_H)); glReadPixels(0, 0, SCREEN_W, SCREEN_H, GL_RGBA, GL_UNSIGNED_BYTE, img->pixels().raw()); ImageRGB_Ptr rgb = ImageRGB_Ptr(img->cast()); rgb->flipH(); static int cnt = 0; string file; while (cnt < 4096) { file = sprint("shot%04d.png", cnt++); if (!LibSL::System::File::exists(file.c_str())) { break; } } saveImage(file.c_str(), rgb); cerr << "Screenshot saved as: " << file << endl; if (g_doScreenshot) { exit(0); } } // -------------------------------------------------------------- void mainRender() { /// render on screen LIBSL_GL_CHECK_ERROR; GPUHelpers::clearScreen(LIBSL_COLOR_BUFFER | LIBSL_DEPTH_BUFFER, 1, 1, 1); if (g_ComputeError) { render_error(); return; } LIBSL_GL_CHECK_ERROR; m4x4f mat = perspectiveMatrixGL(float(M_PI / 8.0), 1.0f, 1.0f, 1000.0f) * TrackballUI::matrix() * translationMatrix(-g_Mesh->getBBox().center()) ; v4f eye_at = mat.inverse() * v4f(0, 0, 1, 0); float dist = length(eye_at - mat.inverse() * v4f(0, 0, -1, 0)); LIBSL_GL_CHECK_ERROR; g_Sh.begin(); g_Sh.u_model.set(TrackballUI::matrix()); g_Sh.u_matrix.set(mat); float plane_y = slice * g_Mesh->getBBox().extent()[1] + g_Mesh->getBBox().minCorner()[1]; g_Sh.u_drawing_mesh.set(g_DrawTetsOrMesh ? 0 : 1); LIBSL_GL_CHECK_ERROR; /// draw tets glDisable(GL_CLIP_DISTANCE0); if (g_DrawTetsOrMesh) { render_tets(); LIBSL_GL_CHECK_ERROR; } else { if (g_ErrorToCompute == e_Curved) { g_Sh.u_v_h_min.set(h[g_i_bottom_shape]); } else { g_Sh.u_v_h_min.set(g_bottomz); } int num_layers = ceil(g_extent_h / thickness); if (g_ErrorToCompute == e_Uniform) { // compute thickness giving the correct number of layers float thu = (g_topz - g_bottomz) / (float)num_layers; g_Sh.u_thickness.set(thu); } else { g_Sh.u_thickness.set((float)thickness); } g_Sh.u_base_thickness.set((float)thickness); Array sequence; GLTexBuffer tex_sequence; if (g_ErrorToCompute == e_Adaptive) { makeAdaptiveSequence(num_layers, sequence, tex_sequence); } if (!sequence.empty()) { glBindImageTexture(1, tex_sequence.glTexId(), 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32F); g_Sh.u_Sequence.set(1); g_Sh.u_SequenceLength.set((int)sequence.size()); } else { g_Sh.u_SequenceLength.set(0); } render_mesh(); LIBSL_GL_CHECK_ERROR; } if (g_DrawTetsOrMesh && !g_DrawDeformed) { render_bbox(); LIBSL_GL_CHECK_ERROR; } g_Sh.end(); if (g_Screenshot) { take_screenshot(); g_Screenshot = false; } LIBSL_GL_CHECK_ERROR; } /* -------------------------------------------------------- */ int main(int argc, char **argv) { std::string additionnal = ""; TCLAP::CmdLine cmd("", ' ', "1.0"); cmd.add(dirArg); cmd.add(fileArg); cmd.add(fieldArg); cmd.add(errorArg); cmd.add(thickArg); cmd.add(screenshotArg); cmd.add(deformedArg); cmd.add(reversededArg); cmd.add(yPlaneArg); cmd.add(posArg); cmd.parse(argc, argv); g_Screenshot = g_doScreenshot = screenshotArg.isSet(); g_DrawDeformed = deformedArg.isSet(); g_Reversed = reversededArg.isSet(); slice = yPlaneArg.isSet() ? yPlaneArg.getValue() : 0.5; thickness = thickArg.isSet() ? thickArg.getValue() : 0.6; try { /// init TrackballUI UI (glut clone for both GL and D3D, with a trackball) cerr << "Init TrackballUI "; TrackballUI::onRender = mainRender; TrackballUI::onKeyPressed = mainKeyboard; TrackballUI::onAnimate = mainAnimate; TrackballUI::onReshape = mainOnReshape; TrackballUI::init(SCREEN_W, SCREEN_H); if (posArg.isSet()) { TrackballUI::trackballLoad( posArg.getValue().c_str() ); } cerr << "[OK]" << endl; /// help printf("[q] - quit\n"); glEnable(GL_DEPTH_TEST); g_ShError.init(); g_ShErrorAttribH = glGetAttribLocationARB(g_ShError.shader().handle(), "a_h"); g_ShErrorAttribGradHdZ = glGetAttribLocationARB(g_ShError.shader().handle(), "a_grad_h_z"); g_Sh.init(); g_ShAttribH = glGetAttribLocationARB(g_Sh.shader().handle(), "a_h"); g_ShAttribW = glGetAttribLocationARB(g_Sh.shader().handle(), "a_widding"); g_ShAttribGradHdZ = glGetAttribLocationARB(g_ShError.shader().handle(), "a_grad_h_z"); LIBSL_GL_CHECK_ERROR; // open mesh cerr << "Loading mesh "; string filename = dirArg.getValue() + fileArg.getValue() + ".msh"; cerr << filename << " "; g_Mesh = AutoPtr(new TetMesh()); g_Mesh = AutoPtr(g_Mesh->load(filename.c_str())); cerr << "[OK]" << endl; cerr << sprint(" mesh contains %d vertices, %d triangles, %d tets\n", g_Mesh->numVertices(), g_Mesh->numTriangles(), g_Mesh->numTetrahedrons()); cerr << "bbox center: " << g_Mesh->getBBox().center() << endl; cerr << "bbox min corner: " << g_Mesh->getBBox().minCorner() << endl; cerr << "bbox max corner: " << g_Mesh->getBBox().maxCorner() << endl; cerr << "Creating renderer " << endl; string displacement = fieldArg.isSet() ? fieldArg.getValue() : dirArg.getValue() + fileArg.getValue() + "/displacements" ; loadArray(h, displacement.c_str() ); string tetmats = dirArg.getValue() + fileArg.getValue() + "/tetmats"; loadArray(g_grad_mats, tetmats.c_str()); // i_bottom_shape is the variable at the bottom of the shape // this is needed for slice alignment float hmin_shape = std::numeric_limits::max(); float hmax_shape = -std::numeric_limits::max(); ForIndex(t, g_Mesh->numSurfaces()) { v3u tri = g_Mesh->surfaceTriangleAt(t); ForIndex(i, 3) { v3f p = g_Mesh->vertexAt(tri[i]); if (p[2] < g_bottomz) { g_bottomz = p[2]; g_i_bottom_shape = tri[i]; } g_topz = max(p[2], g_topz); hmin_shape = min(hmin_shape, h[tri[i]]); hmax_shape = max(hmax_shape, h[tri[i]]); } } g_extent_h = (hmax_shape - hmin_shape); cerr << "model z extent in deformed space: " << g_extent_h << endl; g_Sh.begin(); g_Sh.u_v_h_min.set(h[g_i_bottom_shape]); g_Sh.end(); cerr << "[OK]" << endl; // setup view float h_avg = 0.0f; ForIndex(i, h.size()) { h_avg += h[i]; } h_avg /= (float)h.size(); // init trackball viewpoint TrackballUI::trackball().setCenter( //v3f(v2f(g_Mesh->getBBox().center()), h_avg) v3f(g_Mesh->getBBox().center()) ); if (errorArg.isSet()) { g_ComputeError = true; g_ErrorToCompute = (e_ErrorType)errorArg.getValue(); } /// main loop TrackballUI::loop(); /// clean exit g_Sh.terminate(); g_ShError.terminate(); // shutdown UI TrackballUI::shutdown(); } catch (Fatal& e) { cerr << e.message() << endl; return (-1); } return (0); } /* -------------------------------------------------------- */ ================================================ FILE: tools/tetviz/src/TetViz.h ================================================ #pragma once #include #include #include "imgui\imgui.h" #define IMGUI_DEFINE_MATH_OPERATORS true #include "imgui\imgui_internal.h" class TetViz{ private: TetViz & operator= (const TetViz&) {}; TetViz(const TetViz&) {}; static TetViz *s_instance; TetViz(); ~TetViz() {} public: static void TetViz::launch(); static TetViz *Instance() { if (!s_instance) s_instance = new TetViz; return s_instance; } protected: const float ZN = 1.0f; const float ZF = 2000.0f; public: /** * Called at each frame */ static void mainRender(); /** * Called on resize * @param width the new width * @param height the new height */ static void mainOnResize(uint _width, uint _height); /** * Called when a key is pressed * @param k the typed character */ static void mainKeyPressed(uchar _k); static void mainScanCodePressed(uint _sc); static void mainScanCodeUnpressed(uint _sc); static void mainMouseMoved(uint _x, uint _y); static void mainMousePressed(uint _x, uint _y, uint _button, uint _flags); bool draw(); private: ImVec2 m_size; Trackball m_Trackball; }; ================================================ FILE: tools/tetviz/src/gcode.cpp ================================================ #include "gcode.h" // -------------------------------------------------------------- typedef LibSL::BasicParser::BufferStream t_stream; typedef LibSL::BasicParser::Parser t_parser; typedef AutoPtr t_stream_ptr; typedef AutoPtr t_parser_ptr; // -------------------------------------------------------------- t_stream_ptr g_Stream; t_parser_ptr g_Parser; v4f g_Pos(0.0f); v4f g_Offset(0.0f); float g_Speed = 20.0f; int g_Line = 0; const char *g_GCode = NULL; bool g_GCodeError = false; v3f g_GCodeOffset(0.0f); // -------------------------------------------------------------- void gcode_start(const char *gcode) { g_GCode = gcode; g_Stream = t_stream_ptr(new t_stream(g_GCode,(uint)strlen(g_GCode)+1)); g_Parser = t_parser_ptr(new t_parser(*g_Stream,false)); g_Pos = 0.0f; g_Offset = 0.0f; g_Speed = 20.0f; g_Line = 0; g_GCodeError = false; int c; while (!g_Parser->eof()) { g_Line++; c = g_Parser->readChar(); c = tolower(c); if (c == 'o') { while (!g_Parser->eof()) { c = g_Parser->readChar(); if (c == '\n') break; if (c == ';') { g_Parser->reachChar('\n'); break; } c = tolower(c); float f = g_Parser->readFloat(); if (c >= 'x' && c <= 'z') { g_GCodeOffset[c - 'x'] = f; } } break; } } } // -------------------------------------------------------------- void gcode_reset() { sl_assert(g_GCode != NULL); g_Stream = t_stream_ptr(new t_stream(g_GCode, (uint)strlen(g_GCode) + 1)); g_Parser = t_parser_ptr(new t_parser(*g_Stream, false)); g_Pos = 0.0f; g_Offset = 0.0f; g_Speed = 20.0f; g_Line = 0; g_GCodeError = false; } // -------------------------------------------------------------- v3f gcode_offset() { return g_GCodeOffset; } // -------------------------------------------------------------- bool gcode_advance() { if (g_GCodeError) return false; int c; while (!g_Parser->eof()) { g_Line ++; c = g_Parser->readChar(); c = tolower(c); if (c == 'g') { int n = g_Parser->readInt(); if (n == 0 || n == 1) { // G0 G1 while (!g_Parser->eof()) { c = g_Parser->readChar(); if (c == '\n') break; if (c == ';') { g_Parser->reachChar('\n'); break; } c = tolower(c); float f = g_Parser->readFloat(); if (c >= 'x' && c <= 'z') { g_Pos[c - 'x'] = f + g_Offset[c - 'x']; } else if (c == 'e') { g_Pos[3] = f + g_Offset[3]; } else if (c == 'f') { g_Speed = f / 60.0f; } else if (c >= 'a' && c <= 'f') { // TODO mixing ratios } else { g_GCodeError = true; return false; } } break; // done advancing } else if (n == 92) { // G92 while (!g_Parser->eof()) { c = g_Parser->readChar(); if (c == '\n') break; c = tolower(c); float f = g_Parser->readFloat(); if (c >= 'x' && c <= 'z') { g_Offset[c - 'x'] = g_Pos[c - 'x'] - f; } else if (c == 'e') { g_Offset[3] = g_Pos[3] - f; } } } else if (n == 10) { // G10 g_Parser->reachChar('\n'); } else if (n == 11) { // G11 g_Parser->reachChar('\n'); } else { // other => ignore g_Parser->reachChar('\n'); } } else if (c == 'm') { int n = g_Parser->readInt(); g_Parser->reachChar('\n'); } else if (c == '\n') { // do nothing } else if (c == '<') { g_Parser->reachChar('\n'); } else if (c == ';' || c == 'o') { g_Parser->reachChar('\n'); } else if (c == '\r') { g_Parser->reachChar('\n'); } else if (c == '\0' || c == -1) { return false; } else { g_GCodeError = true; return false; } } return !g_Parser->eof(); } // -------------------------------------------------------------- v4f gcode_next_pos() { return g_Pos; } // -------------------------------------------------------------- float gcode_speed() { return g_Speed; } // -------------------------------------------------------------- int gcode_line() { return g_Line; } // -------------------------------------------------------------- bool gcode_error() { return g_GCodeError; } // -------------------------------------------------------------- ================================================ FILE: tools/tetviz/src/gcode.h ================================================ // SL 2018-07-03 #pragma once #include #include // start interpreting the gcode void gcode_start(const char *gcode); v3f gcode_offset(); // advances to the next position // return false if none exists (end of gcode) bool gcode_advance(); // returns the next position to reach (x,y,z,e) v4f gcode_next_pos(); // returns the speed in mm/sec float gcode_speed(); // return current line in gcode stream int gcode_line(); // restart from scratch void gcode_reset(); // returns true in a reading error occured bool gcode_error(); ================================================ FILE: tools/tetviz/src/shade.fp ================================================ #version 430 core #extension GL_ARB_shader_image_load_store : enable #extension GL_ARB_gpu_shader5 : enable in float v_h; in float v_grad_h_z; in float v_z; in vec3 v_pos; in float v_widding; uniform int u_drawing_mesh; uniform float u_v_h_min; uniform float u_base_thickness; uniform float u_thickness; uniform int u_SequenceLength; layout(r32f) coherent uniform imageBuffer u_Sequence; vec2 findSlice(float z) { int l = 0; int r = u_SequenceLength; for (int i = 0; i < 64; i++) { // read sequence int m = min((l + r) / 2, u_SequenceLength - 1); vec2 slice_nfo; slice_nfo.x = imageLoad(u_Sequence, m * 2 + 0).x; slice_nfo.y = imageLoad(u_Sequence, m * 2 + 1).x; if (z >= slice_nfo.x && z < slice_nfo.x + slice_nfo.y) { return slice_nfo; } if (z < slice_nfo.x) { r = m; } else { l = m; } } int last = u_SequenceLength - 1; return vec2(imageLoad(u_Sequence, last * 2 + 0).x, imageLoad(u_Sequence, last * 2 + 1).x); } void main() { float t = fract(v_h / 5); vec3 dpdx = dFdx(v_pos); vec3 dpdy = dFdy(v_pos); vec3 nrm = normalize( cross(dpdx,dpdy)); if (u_drawing_mesh == 1) { if (u_SequenceLength > 0) { vec2 slice = findSlice(v_h); gl_FragColor = (slice.y / u_base_thickness) * vec4(1.0 - abs(0.5 - ((v_h - slice.x) / slice.y)) * 2.0); } else { gl_FragColor = v_grad_h_z * (u_thickness / u_base_thickness) * vec4(1.0 - abs(0.5 - fract((v_h - u_v_h_min) / u_thickness)) * 2.0); } } else { if (v_widding > 0.5) { if (t < 0.5) { gl_FragColor = vec4(0.8, 0.4, 0.6, 0)*(0.5+0.5*nrm.z); } else { gl_FragColor = vec4(0, 1, 1, 0)*(0.5 + 0.5*nrm.z); } } else { if (t < 0.5) { gl_FragColor = vec4(0.4, 0.8, 0.6, 0)*nrm.z; } else { gl_FragColor = vec4(0.2, 1, 0.6, 0)*nrm.z; } } } } ================================================ FILE: tools/tetviz/src/shade.vp ================================================ uniform mat4 u_matrix; uniform mat4 u_model; attribute float a_h; attribute float a_grad_h_z; attribute float a_widding; varying float v_h; varying float v_grad_h_z; varying float v_z; varying vec3 v_pos; varying float v_widding; uniform float u_ClipY; uniform int u_ClipDir; uniform int u_Deform; void main() { v_h = a_h; v_grad_h_z = a_grad_h_z; v_z = gl_Vertex.z; v_widding = a_widding; vec4 pos; if (u_Deform == 1) { pos = vec4(gl_Vertex.xy,v_h,1.0); } else { pos = vec4(gl_Vertex.xyz,1.0); } v_pos = (u_model * pos).xyz; gl_Position = u_matrix * pos; if (a_widding == 0) { gl_ClipDistance[0] = 1.0; } else { gl_ClipDistance[0] = u_ClipDir * (-pos.y + u_ClipY); } } ================================================ FILE: tools/tetviz/src/slicerror.fp ================================================ #version 430 core #extension GL_ARB_shader_image_load_store : enable #extension GL_ARB_gpu_shader5 : enable uniform uint u_ScreenW; uniform float u_v_h_min; uniform int u_SequenceLength; layout(r32ui) coherent uniform uimageBuffer u_Errors; layout(r32f) coherent uniform imageBuffer u_Sequence; in float v_h; in float v_grad_h_z; uniform float u_base_thickness; uniform float u_thickness; vec2 findSlice(float z) { int l = 0; int r = u_SequenceLength; for (int i = 0 ; i < 64 ; i++) { // read sequence int m = min((l+r)/2,u_SequenceLength-1); vec2 slice_nfo; slice_nfo.x = imageLoad(u_Sequence,m*2+0).x; slice_nfo.y = imageLoad(u_Sequence,m*2+1).x; if (z >= slice_nfo.x && z < slice_nfo.x + slice_nfo.y) { return slice_nfo; } if (z < slice_nfo.x) { r = m; } else { l = m; } } int last = u_SequenceLength-1; return vec2(imageLoad(u_Sequence,last*2+0).x,imageLoad(u_Sequence,last*2+1).x); } void main() { float normalized_distance = 0.0; if (u_SequenceLength > 0) { vec2 slice = findSlice( v_h ); normalized_distance = (slice.y / u_base_thickness) * (1.0 - abs(0.5 - ( (v_h-slice.x) / slice.y) ) * 2.0); } else { normalized_distance = v_grad_h_z * (u_thickness / u_base_thickness) * (1.0 - abs(0.5 - fract( (v_h-u_v_h_min) / u_thickness) ) * 2.0); } uint ptr = uint(gl_FragCoord.x) + uint(gl_FragCoord.y) * u_ScreenW; uint fxp_distance = uint(normalized_distance * 4096.0); imageAtomicAdd( u_Errors, int(ptr), fxp_distance ); gl_FragColor = vec4( normalized_distance ); } ================================================ FILE: tools/tetviz/src/slicerror.vp ================================================ #version 430 core in vec4 mvf_vertex; // LibSL takes care of vertex attributes 'mvf_*' (normal,color0,texcoord0,etc.) in float a_h; in float a_grad_h_z; out float v_h; out float v_grad_h_z; uniform mat4 u_matrix; void main() { v_h = a_h; v_grad_h_z = a_grad_h_z; gl_Position = u_matrix * mvf_vertex; }