*.o
*.d
*.swp
+*.a
cyberay
+data/
+datasrc/
-src = $(wildcard src/*.c)
+src = $(wildcard src/*.c) $(wildcard libs/miniglut/*.c)
obj = $(src:.c=.o)
dep = $(src:.c=.d)
bin = cyberay
opt = -O3 -ffast-math -fno-strict-aliasing
dbg = -g
warn = -pedantic -Wall
-inc = -Ilibs
+def = -DMINIGLUT_USE_LIBC
+inc = -Ilibs -Ilibs/treestore -Ilibs/miniglut
+libdir = -Llibs/treestore
-CFLAGS = $(warn) $(opt) $(dbg) -pthread -MMD $(inc)
-LDFLAGS = $(libgl) -lm -pthread -limago
+CFLAGS = $(warn) $(opt) $(dbg) $(def) $(inc) -pthread -MMD
+LDFLAGS = $(libgl) $(libs) -lm -pthread -limago -ltreestore
-libgl = -lGL -lGLU -lglut
+libgl = -lGL -lGLU -lX11 -lXext
-$(bin): $(obj)
+$(bin): $(obj) libs
$(CC) -o $@ $(obj) $(LDFLAGS)
-include $(dep)
.PHONY: cleandep
cleandep:
rm -f $(dep)
+
+.PHONY: libs
+libs:
+ $(MAKE) -C libs
+
+.PHONY: clean-libs
+clean-libs:
+ $(MAKE) -C libs clean
--- /dev/null
+.PHONY: all
+all: treestore
+
+.PHONY: clean
+clean: clean-treestore
+
+.PHONY: treestore
+treestore:
+ $(MAKE) -C treestore
+
+.PHONY: clean-treestore
+clean-treestore:
+ $(MAKE) -C treestore clean
--- /dev/null
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
--- /dev/null
+MiniGLUT
+========
+
+![logo](http://nuclear.mutantstargoat.com/sw/miniglut/img/miniglut_logo_sm_alpha.png)
+
+MiniGLUT is a subset of GLUT (or more precisely a subset of FreeGLUT)
+implemented in a single C source file, without any non-essential dependencies,
+not even the C library.
+
+You can use MiniGLUT by simply dropping two files: `miniglut.h` and `miniglut.c`
+into your project source tree, or by building MiniGLUT as a static library and
+linking with it.
+
+MiniGLUT does not intend to replace a full GLUT library, like FreeGLUT, for
+hacking small to medium OpenGL programs. The purpose of MiniGLUT is to
+potentially replace a full GLUT library when it's time for release, in order to
+minimize runtime dependencies of the resulting binary.
+
+A second reason to use MiniGLUT is to ease porting of UNIX OpenGL programs to
+Windows, especially when using the microsoft compiler, where setting up and
+linking with a proper 3rd-party library is an ordeal in itself. Even more so if
+you decide to statically link, at which point you need to deal with the whole
+"MSVC runtime" chaos. Even if you decide to link MiniGLUT as a static library,
+instead of dropping it in your code, it still won't present any MSVC runtime
+compatibility issues, since it doesn't call any C library functions whatsoever.
+
+Download
+--------
+Latest release (v0.3):
+ - https://github.com/jtsiomb/miniglut/releases/download/v0.3/miniglut-0.3.tar.gz
+ - https://github.com/jtsiomb/miniglut/releases/download/v0.3/miniglut-0.3.zip
+
+Both archives are identical, choose whichever is more convenient.
+
+Source repository (git):
+ - https://github.com/jtsiomb/miniglut
+
+Build
+-----
+Under X11 MiniGLUT depends only on Xlib and OpenGL. Therefore to build a program
+using MiniGLUT you'll need to link with `-lX11 -lGL`.
+
+Under Windows MiniGLUT depends only on OpenGL, GDI and winmm. Therefore to build
+a program using MiniGLUT you'll need to link with `-lopengl32 -lgdi32 -lwinmm`.
+When building with MSVC, linking with the correct libraries is taken care by
+pragmas in the header file. If you wish to avoid the winmm dependency, define
+`MINIGLUT_NO_WINMM`.
+
+To avoid calling C library functions, MiniGLUT uses inline assembly code for
+system calls and trigonometric operations. This makes the default build
+incompatible with non-x86 systems, and with MSVC x64 builds. If you don't mind
+linking with the C library, you can define `MINIGLUT_USE_LIBC` to lift these
+limitations.
+
+License
+-------
+Copyright (C) 2020 John Tsiombikas <nuclear@member.fsf.org>
+
+MiniGLUT is free software. Feel free to use, modify and/or redistribute it,
+under the terms of the GNU General Public License v3, or at your option any
+newer version published by the Free Software Foundation. See COPYING for
+details.
+
+The intention is not to dictate a specific free software license (GPL) but to
+shut the door to proprietary programs. If you want to use MiniGLUT in a free
+software project with an incompatible license, contact me and we will figure out
+a way to enable that.
+
+To learn more about GPL-incompatible free software licenses where this might
+be an issue, see:
+https://www.gnu.org/licenses/license-list.en.html#GPLIncompatibleLicenses
+
+Known Issues
+------------
+MiniGLUT being a subset of GLUT, is missing a number of features. Some of them
+on purpose to keep it minimal, and some of them because I didn't happen to use
+them in a program I wanted to link with MiniGLUT yet.
+
+Missing GLUT features:
+ - The only supported systems are: UNIX with X11 (GLX), and Windows (WGL).
+ - Multiple windows.
+ - Subwindows.
+ - Overlays.
+ - Game mode (video mode switching).
+ - Menus.
+ - Font rendering.
+ - Some of the primitives.
+ - Buttons and Dials callbacks.
+ - Tablet callbacks.
+ - Spaceball callbacks are only implemented on UNIX/X11.
+ - Timer callback.
+
+Missing FreeGLUT features:
+ - Mobile callbacks.
+ - Context version and profile selection and other context flags.
+ - Window close actions.
+ - Multi-touch/multi-pointer callbacks.
+ - User-pointer callbacks.
+ - Joystick callbacks.
+ - More missing primitives.
+
+If wish to let me know how much you need one of the missing features, or even
+better if you are volunteering to implement it yourself, send me an email at:
+nuclear@member.fsf.org
+
+Only plain-text emails, hard-wrapped at 72 columns will be accepted.
--- /dev/null
+/*
+MiniGLUT - minimal GLUT subset without dependencies
+Copyright (C) 2020 John Tsiombikas <nuclear@member.fsf.org>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+#if defined(__unix__)
+
+#include <X11/Xlib.h>
+#include <X11/keysym.h>
+#include <X11/cursorfont.h>
+#include <GL/glx.h>
+#define BUILD_X11
+
+#ifndef GLX_SAMPLE_BUFFERS_ARB
+#define GLX_SAMPLE_BUFFERS_ARB 100000
+#define GLX_SAMPLES_ARB 100001
+#endif
+#ifndef GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB
+#define GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20b2
+#endif
+
+static Display *dpy;
+static Window win, root;
+static int scr;
+static GLXContext ctx;
+static Atom xa_wm_proto, xa_wm_del_win;
+static Atom xa_net_wm_state, xa_net_wm_state_fullscr;
+static Atom xa_motif_wm_hints;
+static Atom xa_motion_event, xa_button_press_event, xa_button_release_event, xa_command_event;
+static unsigned int evmask;
+static Cursor blank_cursor;
+
+static int have_netwm_fullscr(void);
+
+#elif defined(_WIN32)
+
+#include <windows.h>
+#define BUILD_WIN32
+
+static HRESULT CALLBACK handle_message(HWND win, unsigned int msg, WPARAM wparam, LPARAM lparam);
+
+static HINSTANCE hinst;
+static HWND win;
+static HDC dc;
+static HGLRC ctx;
+
+#else
+#error unsupported platform
+#endif
+#include <GL/gl.h>
+#include "miniglut.h"
+
+struct ctx_info {
+ int rsize, gsize, bsize, asize;
+ int zsize, ssize;
+ int dblbuf;
+ int samples;
+ int stereo;
+ int srgb;
+};
+
+static void cleanup(void);
+static void create_window(const char *title);
+static void get_window_pos(int *x, int *y);
+static void get_window_size(int *w, int *h);
+static void get_screen_size(int *scrw, int *scrh);
+
+static long get_msec(void);
+static void panic(const char *msg);
+static void sys_exit(int status);
+static int sys_write(int fd, const void *buf, int count);
+
+
+static int init_x = -1, init_y, init_width = 256, init_height = 256;
+static unsigned int init_mode;
+
+static struct ctx_info ctx_info;
+static int cur_cursor = GLUT_CURSOR_INHERIT;
+
+static glut_cb cb_display;
+static glut_cb cb_idle;
+static glut_cb_reshape cb_reshape;
+static glut_cb_state cb_vis, cb_entry;
+static glut_cb_keyb cb_keydown, cb_keyup;
+static glut_cb_special cb_skeydown, cb_skeyup;
+static glut_cb_mouse cb_mouse;
+static glut_cb_motion cb_motion, cb_passive;
+static glut_cb_sbmotion cb_sball_motion, cb_sball_rotate;
+static glut_cb_sbbutton cb_sball_button;
+
+static int fullscreen;
+static int prev_win_x, prev_win_y, prev_win_width, prev_win_height;
+
+static int win_width, win_height;
+static int mapped;
+static int quit;
+static int upd_pending;
+static int modstate;
+
+void glutInit(int *argc, char **argv)
+{
+#ifdef BUILD_X11
+ Pixmap blankpix = 0;
+ XColor xcol;
+
+ if(!(dpy = XOpenDisplay(0))) {
+ panic("Failed to connect to the X server\n");
+ }
+ scr = DefaultScreen(dpy);
+ root = RootWindow(dpy, scr);
+ xa_wm_proto = XInternAtom(dpy, "WM_PROTOCOLS", False);
+ xa_wm_del_win = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
+ xa_motif_wm_hints = XInternAtom(dpy, "_MOTIF_WM_HINTS", False);
+ xa_net_wm_state_fullscr = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False);
+ if(have_netwm_fullscr()) {
+ xa_net_wm_state = XInternAtom(dpy, "_NET_WM_STATE", False);
+ }
+
+ xa_motion_event = XInternAtom(dpy, "MotionEvent", True);
+ xa_button_press_event = XInternAtom(dpy, "ButtonPressEvent", True);
+ xa_button_release_event = XInternAtom(dpy, "ButtonReleaseEvent", True);
+ xa_command_event = XInternAtom(dpy, "CommandEvent", True);
+
+ evmask = ExposureMask | StructureNotifyMask;
+
+ if((blankpix = XCreateBitmapFromData(dpy, root, (char*)&blankpix, 1, 1))) {
+ blank_cursor = XCreatePixmapCursor(dpy, blankpix, blankpix, &xcol, &xcol, 0, 0);
+ XFreePixmap(dpy, blankpix);
+ }
+
+#endif
+#ifdef BUILD_WIN32
+ WNDCLASSEX wc = {0};
+
+ hinst = GetModuleHandle(0);
+
+ wc.cbSize = sizeof wc;
+ wc.hbrBackground = GetStockObject(BLACK_BRUSH);
+ wc.hCursor = LoadCursor(0, IDC_ARROW);
+ wc.hIcon = wc.hIconSm = LoadIcon(0, IDI_APPLICATION);
+ wc.hInstance = hinst;
+ wc.lpfnWndProc = handle_message;
+ wc.lpszClassName = "MiniGLUT";
+ wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
+ if(!RegisterClassEx(&wc)) {
+ panic("Failed to register \"MiniGLUT\" window class\n");
+ }
+
+ if(init_x == -1) {
+ get_screen_size(&init_x, &init_y);
+ init_x >>= 3;
+ init_y >>= 3;
+ }
+#endif
+}
+
+void glutInitWindowPosition(int x, int y)
+{
+ init_x = x;
+ init_y = y;
+}
+
+void glutInitWindowSize(int xsz, int ysz)
+{
+ init_width = xsz;
+ init_height = ysz;
+}
+
+void glutInitDisplayMode(unsigned int mode)
+{
+ init_mode = mode;
+}
+
+void glutCreateWindow(const char *title)
+{
+ create_window(title);
+}
+
+void glutExit(void)
+{
+ quit = 1;
+}
+
+void glutMainLoop(void)
+{
+ while(!quit) {
+ glutMainLoopEvent();
+ }
+}
+
+void glutPostRedisplay(void)
+{
+ upd_pending = 1;
+}
+
+#define UPD_EVMASK(x) \
+ do { \
+ if(func) { \
+ evmask |= x; \
+ } else { \
+ evmask &= ~(x); \
+ } \
+ if(win) XSelectInput(dpy, win, evmask); \
+ } while(0)
+
+
+void glutIdleFunc(glut_cb func)
+{
+ cb_idle = func;
+}
+
+void glutDisplayFunc(glut_cb func)
+{
+ cb_display = func;
+}
+
+void glutReshapeFunc(glut_cb_reshape func)
+{
+ cb_reshape = func;
+}
+
+void glutVisibilityFunc(glut_cb_state func)
+{
+ cb_vis = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(VisibilityChangeMask);
+#endif
+}
+
+void glutEntryFunc(glut_cb_state func)
+{
+ cb_entry = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(EnterWindowMask | LeaveWindowMask);
+#endif
+}
+
+void glutKeyboardFunc(glut_cb_keyb func)
+{
+ cb_keydown = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(KeyPressMask);
+#endif
+}
+
+void glutKeyboardUpFunc(glut_cb_keyb func)
+{
+ cb_keyup = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(KeyReleaseMask);
+#endif
+}
+
+void glutSpecialFunc(glut_cb_special func)
+{
+ cb_skeydown = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(KeyPressMask);
+#endif
+}
+
+void glutSpecialUpFunc(glut_cb_special func)
+{
+ cb_skeyup = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(KeyReleaseMask);
+#endif
+}
+
+void glutMouseFunc(glut_cb_mouse func)
+{
+ cb_mouse = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(ButtonPressMask | ButtonReleaseMask);
+#endif
+}
+
+void glutMotionFunc(glut_cb_motion func)
+{
+ cb_motion = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(ButtonMotionMask);
+#endif
+}
+
+void glutPassiveMotionFunc(glut_cb_motion func)
+{
+ cb_passive = func;
+#ifdef BUILD_X11
+ UPD_EVMASK(PointerMotionMask);
+#endif
+}
+
+void glutSpaceballMotionFunc(glut_cb_sbmotion func)
+{
+ cb_sball_motion = func;
+}
+
+void glutSpaceballRotateFunc(glut_cb_sbmotion func)
+{
+ cb_sball_rotate = func;
+}
+
+void glutSpaceballButtonFunc(glut_cb_sbbutton func)
+{
+ cb_sball_button = func;
+}
+
+int glutGet(unsigned int s)
+{
+ int x, y;
+ switch(s) {
+ case GLUT_WINDOW_X:
+ get_window_pos(&x, &y);
+ return x;
+ case GLUT_WINDOW_Y:
+ get_window_pos(&x, &y);
+ return y;
+ case GLUT_WINDOW_WIDTH:
+ get_window_size(&x, &y);
+ return x;
+ case GLUT_WINDOW_HEIGHT:
+ get_window_size(&x, &y);
+ return y;
+ case GLUT_WINDOW_BUFFER_SIZE:
+ return ctx_info.rsize + ctx_info.gsize + ctx_info.bsize + ctx_info.asize;
+ case GLUT_WINDOW_STENCIL_SIZE:
+ return ctx_info.ssize;
+ case GLUT_WINDOW_DEPTH_SIZE:
+ return ctx_info.zsize;
+ case GLUT_WINDOW_RED_SIZE:
+ return ctx_info.rsize;
+ case GLUT_WINDOW_GREEN_SIZE:
+ return ctx_info.gsize;
+ case GLUT_WINDOW_BLUE_SIZE:
+ return ctx_info.bsize;
+ case GLUT_WINDOW_ALPHA_SIZE:
+ return ctx_info.asize;
+ case GLUT_WINDOW_DOUBLEBUFFER:
+ return ctx_info.dblbuf;
+ case GLUT_WINDOW_RGBA:
+ return 1;
+ case GLUT_WINDOW_NUM_SAMPLES:
+ return ctx_info.samples;
+ case GLUT_WINDOW_STEREO:
+ return ctx_info.stereo;
+ case GLUT_WINDOW_SRGB:
+ return ctx_info.srgb;
+ case GLUT_WINDOW_CURSOR:
+ return cur_cursor;
+ case GLUT_SCREEN_WIDTH:
+ get_screen_size(&x, &y);
+ return x;
+ case GLUT_SCREEN_HEIGHT:
+ get_screen_size(&x, &y);
+ return y;
+ case GLUT_INIT_DISPLAY_MODE:
+ return init_mode;
+ case GLUT_INIT_WINDOW_X:
+ return init_x;
+ case GLUT_INIT_WINDOW_Y:
+ return init_y;
+ case GLUT_INIT_WINDOW_WIDTH:
+ return init_width;
+ case GLUT_INIT_WINDOW_HEIGHT:
+ return init_height;
+ case GLUT_ELAPSED_TIME:
+ return get_msec();
+ default:
+ break;
+ }
+ return 0;
+}
+
+int glutGetModifiers(void)
+{
+ return modstate;
+}
+
+static int is_space(int c)
+{
+ return c == ' ' || c == '\t' || c == '\v' || c == '\n' || c == '\r';
+}
+
+static const char *skip_space(const char *s)
+{
+ while(*s && is_space(*s)) s++;
+ return s;
+}
+
+int glutExtensionSupported(char *ext)
+{
+ const char *str, *eptr;
+
+ if(!(str = (const char*)glGetString(GL_EXTENSIONS))) {
+ return 0;
+ }
+
+ while(*str) {
+ str = skip_space(str);
+ eptr = skip_space(ext);
+ while(*str && !is_space(*str) && *eptr && *str == *eptr) {
+ str++;
+ eptr++;
+ }
+ if((!*str || is_space(*str)) && !*eptr) {
+ return 1;
+ }
+ while(*str && !is_space(*str)) str++;
+ }
+
+ return 0;
+}
+
+
+/* --------------- UNIX/X11 implementation ----------------- */
+#ifdef BUILD_X11
+enum {
+ SPNAV_EVENT_ANY, /* used by spnav_remove_events() */
+ SPNAV_EVENT_MOTION,
+ SPNAV_EVENT_BUTTON /* includes both press and release */
+};
+
+struct spnav_event_motion {
+ int type;
+ int x, y, z;
+ int rx, ry, rz;
+ unsigned int period;
+ int *data;
+};
+
+struct spnav_event_button {
+ int type;
+ int press;
+ int bnum;
+};
+
+union spnav_event {
+ int type;
+ struct spnav_event_motion motion;
+ struct spnav_event_button button;
+};
+
+
+static void handle_event(XEvent *ev);
+
+static int spnav_window(Window win);
+static int spnav_event(const XEvent *xev, union spnav_event *event);
+static int spnav_remove_events(int type);
+
+
+void glutMainLoopEvent(void)
+{
+ XEvent ev;
+
+ if(!cb_display) {
+ panic("display callback not set");
+ }
+
+ if(!upd_pending && !cb_idle) {
+ XNextEvent(dpy, &ev);
+ handle_event(&ev);
+ if(quit) goto end;
+ }
+ while(XPending(dpy)) {
+ XNextEvent(dpy, &ev);
+ handle_event(&ev);
+ if(quit) goto end;
+ }
+
+ if(cb_idle) {
+ cb_idle();
+ }
+
+ if(upd_pending && mapped) {
+ upd_pending = 0;
+ cb_display();
+ }
+
+end:
+ if(quit) {
+ cleanup();
+ }
+}
+
+static void cleanup(void)
+{
+ if(win) {
+ spnav_window(root);
+ glXMakeCurrent(dpy, 0, 0);
+ XDestroyWindow(dpy, win);
+ }
+}
+
+static KeySym translate_keysym(KeySym sym)
+{
+ switch(sym) {
+ case XK_Escape:
+ return 27;
+ case XK_BackSpace:
+ return '\b';
+ case XK_Linefeed:
+ return '\r';
+ case XK_Return:
+ return '\n';
+ case XK_Delete:
+ return 127;
+ case XK_Tab:
+ return '\t';
+ default:
+ break;
+ }
+ return sym;
+}
+
+static void handle_event(XEvent *ev)
+{
+ KeySym sym;
+ union spnav_event sev;
+
+ switch(ev->type) {
+ case MapNotify:
+ mapped = 1;
+ break;
+ case UnmapNotify:
+ mapped = 0;
+ break;
+ case ConfigureNotify:
+ if(cb_reshape && (ev->xconfigure.width != win_width || ev->xconfigure.height != win_height)) {
+ win_width = ev->xconfigure.width;
+ win_height = ev->xconfigure.height;
+ cb_reshape(ev->xconfigure.width, ev->xconfigure.height);
+ }
+ break;
+
+ case ClientMessage:
+ if(ev->xclient.message_type == xa_wm_proto) {
+ if(ev->xclient.data.l[0] == xa_wm_del_win) {
+ quit = 1;
+ }
+ }
+ if(spnav_event(ev, &sev)) {
+ switch(sev.type) {
+ case SPNAV_EVENT_MOTION:
+ if(cb_sball_motion) {
+ cb_sball_motion(sev.motion.x, sev.motion.y, sev.motion.z);
+ }
+ if(cb_sball_rotate) {
+ cb_sball_rotate(sev.motion.rx, sev.motion.ry, sev.motion.rz);
+ }
+ spnav_remove_events(SPNAV_EVENT_MOTION);
+ break;
+
+ case SPNAV_EVENT_BUTTON:
+ if(cb_sball_button) {
+ cb_sball_button(sev.button.bnum + 1, sev.button.press ? GLUT_DOWN : GLUT_UP);
+ }
+ break;
+
+ default:
+ break;
+ }
+ }
+ break;
+
+ case Expose:
+ upd_pending = 1;
+ break;
+
+ case KeyPress:
+ case KeyRelease:
+ modstate = ev->xkey.state & (ShiftMask | ControlMask | Mod1Mask);
+ if(!(sym = XLookupKeysym(&ev->xkey, 0))) {
+ break;
+ }
+ sym = translate_keysym(sym);
+ if(sym < 256) {
+ if(ev->type == KeyPress) {
+ if(cb_keydown) cb_keydown((unsigned char)sym, ev->xkey.x, ev->xkey.y);
+ } else {
+ if(cb_keyup) cb_keyup((unsigned char)sym, ev->xkey.x, ev->xkey.y);
+ }
+ } else {
+ if(ev->type == KeyPress) {
+ if(cb_skeydown) cb_skeydown(sym, ev->xkey.x, ev->xkey.y);
+ } else {
+ if(cb_skeyup) cb_skeyup(sym, ev->xkey.x, ev->xkey.y);
+ }
+ }
+ break;
+
+ case ButtonPress:
+ case ButtonRelease:
+ modstate = ev->xbutton.state & (ShiftMask | ControlMask | Mod1Mask);
+ if(cb_mouse) {
+ int bn = ev->xbutton.button - Button1;
+ cb_mouse(bn, ev->type == ButtonPress ? GLUT_DOWN : GLUT_UP,
+ ev->xbutton.x, ev->xbutton.y);
+ }
+ break;
+
+ case MotionNotify:
+ if(ev->xmotion.state & (Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask)) {
+ if(cb_motion) cb_motion(ev->xmotion.x, ev->xmotion.y);
+ } else {
+ if(cb_passive) cb_passive(ev->xmotion.x, ev->xmotion.y);
+ }
+ break;
+
+ case VisibilityNotify:
+ if(cb_vis) {
+ cb_vis(ev->xvisibility.state == VisibilityFullyObscured ? GLUT_NOT_VISIBLE : GLUT_VISIBLE);
+ }
+ break;
+ case EnterNotify:
+ if(cb_entry) cb_entry(GLUT_ENTERED);
+ break;
+ case LeaveNotify:
+ if(cb_entry) cb_entry(GLUT_LEFT);
+ break;
+ }
+}
+
+void glutSwapBuffers(void)
+{
+ glXSwapBuffers(dpy, win);
+}
+
+/* BUG:
+ * set_fullscreen_mwm removes the decorations with MotifWM hints, and then it
+ * needs to resize the window to make it fullscreen. The way it does this is by
+ * querying the size of the root window (see get_screen_size), which in the
+ * case of multi-monitor setups will be the combined size of all monitors.
+ * This is problematic; the way to solve it is to use the XRandR extension, or
+ * the Xinerama extension, to figure out the dimensions of the correct video
+ * output, which would add potentially two extension support libraries to our
+ * dependencies list.
+ * Moreover, any X installation modern enough to support XR&R will almost
+ * certainly be running a window manager supporting the EHWM
+ * _NET_WM_STATE_FULLSCREEN method (set_fullscreen_ewmh), which does not rely
+ * on manual resizing, and is used in preference if available, making this
+ * whole endeavor pointless.
+ * So I'll just leave it with set_fullscreen_mwm covering the entire
+ * multi-monitor area for now.
+ */
+
+struct mwm_hints {
+ unsigned long flags;
+ unsigned long functions;
+ unsigned long decorations;
+ long input_mode;
+ unsigned long status;
+};
+
+#define MWM_HINTS_DECORATIONS 2
+#define MWM_DECOR_ALL 1
+
+static void set_fullscreen_mwm(int fs)
+{
+ struct mwm_hints hints;
+ int scr_width, scr_height;
+
+ if(fs) {
+ get_window_pos(&prev_win_x, &prev_win_y);
+ get_window_size(&prev_win_width, &prev_win_height);
+ get_screen_size(&scr_width, &scr_height);
+
+ hints.decorations = 0;
+ hints.flags = MWM_HINTS_DECORATIONS;
+ XChangeProperty(dpy, win, xa_motif_wm_hints, xa_motif_wm_hints, 32,
+ PropModeReplace, (unsigned char*)&hints, 5);
+
+ XMoveResizeWindow(dpy, win, 0, 0, scr_width, scr_height);
+ } else {
+ XDeleteProperty(dpy, win, xa_motif_wm_hints);
+ XMoveResizeWindow(dpy, win, prev_win_x, prev_win_y, prev_win_width, prev_win_height);
+ }
+}
+
+static int have_netwm_fullscr(void)
+{
+ int fmt;
+ long offs = 0;
+ unsigned long i, count, rem;
+ Atom prop[8], type;
+ Atom xa_net_supported = XInternAtom(dpy, "_NET_SUPPORTED", False);
+
+ do {
+ XGetWindowProperty(dpy, root, xa_net_supported, offs, 8, False, AnyPropertyType,
+ &type, &fmt, &count, &rem, (unsigned char**)prop);
+
+ for(i=0; i<count; i++) {
+ if(prop[i] == xa_net_wm_state_fullscr) {
+ return 1;
+ }
+ }
+ offs += count;
+ } while(rem > 0);
+
+ return 0;
+}
+
+static void set_fullscreen_ewmh(int fs)
+{
+ XClientMessageEvent msg = {0};
+
+ msg.type = ClientMessage;
+ msg.window = win;
+ msg.message_type = xa_net_wm_state; /* _NET_WM_STATE */
+ msg.format = 32;
+ msg.data.l[0] = fs ? 1 : 0;
+ msg.data.l[1] = xa_net_wm_state_fullscr; /* _NET_WM_STATE_FULLSCREEN */
+ msg.data.l[2] = 0;
+ msg.data.l[3] = 1; /* source regular application */
+ XSendEvent(dpy, root, False, SubstructureNotifyMask | SubstructureRedirectMask, (XEvent*)&msg);
+}
+
+static void set_fullscreen(int fs)
+{
+ if(fullscreen == fs) return;
+
+ if(xa_net_wm_state && xa_net_wm_state_fullscr) {
+ set_fullscreen_ewmh(fs);
+ fullscreen = fs;
+ } else if(xa_motif_wm_hints) {
+ set_fullscreen_mwm(fs);
+ fullscreen = fs;
+ }
+}
+
+void glutPositionWindow(int x, int y)
+{
+ set_fullscreen(0);
+ XMoveWindow(dpy, win, x, y);
+}
+
+void glutReshapeWindow(int xsz, int ysz)
+{
+ set_fullscreen(0);
+ XResizeWindow(dpy, win, xsz, ysz);
+}
+
+void glutFullScreen(void)
+{
+ set_fullscreen(1);
+}
+
+void glutSetWindowTitle(const char *title)
+{
+ XTextProperty tprop;
+ if(!XStringListToTextProperty((char**)&title, 1, &tprop)) {
+ return;
+ }
+ XSetWMName(dpy, win, &tprop);
+ XFree(tprop.value);
+}
+
+void glutSetIconTitle(const char *title)
+{
+ XTextProperty tprop;
+ if(!XStringListToTextProperty((char**)&title, 1, &tprop)) {
+ return;
+ }
+ XSetWMIconName(dpy, win, &tprop);
+ XFree(tprop.value);
+}
+
+void glutSetCursor(int cidx)
+{
+ Cursor cur = None;
+
+ switch(cidx) {
+ case GLUT_CURSOR_LEFT_ARROW:
+ cur = XCreateFontCursor(dpy, XC_left_ptr);
+ break;
+ case GLUT_CURSOR_INHERIT:
+ break;
+ case GLUT_CURSOR_NONE:
+ cur = blank_cursor;
+ break;
+ default:
+ return;
+ }
+
+ XDefineCursor(dpy, win, cur);
+ cur_cursor = cidx;
+}
+
+static XVisualInfo *choose_visual(unsigned int mode)
+{
+ XVisualInfo *vi;
+ int attr[32];
+ int *aptr = attr;
+ int *samples = 0;
+
+ if(mode & GLUT_DOUBLE) {
+ *aptr++ = GLX_DOUBLEBUFFER;
+ }
+
+ if(mode & GLUT_INDEX) {
+ *aptr++ = GLX_BUFFER_SIZE;
+ *aptr++ = 1;
+ } else {
+ *aptr++ = GLX_RGBA;
+ *aptr++ = GLX_RED_SIZE; *aptr++ = 4;
+ *aptr++ = GLX_GREEN_SIZE; *aptr++ = 4;
+ *aptr++ = GLX_BLUE_SIZE; *aptr++ = 4;
+ }
+ if(mode & GLUT_ALPHA) {
+ *aptr++ = GLX_ALPHA_SIZE;
+ *aptr++ = 4;
+ }
+ if(mode & GLUT_DEPTH) {
+ *aptr++ = GLX_DEPTH_SIZE;
+ *aptr++ = 16;
+ }
+ if(mode & GLUT_STENCIL) {
+ *aptr++ = GLX_STENCIL_SIZE;
+ *aptr++ = 1;
+ }
+ if(mode & GLUT_ACCUM) {
+ *aptr++ = GLX_ACCUM_RED_SIZE; *aptr++ = 1;
+ *aptr++ = GLX_ACCUM_GREEN_SIZE; *aptr++ = 1;
+ *aptr++ = GLX_ACCUM_BLUE_SIZE; *aptr++ = 1;
+ }
+ if(mode & GLUT_STEREO) {
+ *aptr++ = GLX_STEREO;
+ }
+ if(mode & GLUT_SRGB) {
+ *aptr++ = GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB;
+ }
+ if(mode & GLUT_MULTISAMPLE) {
+ *aptr++ = GLX_SAMPLE_BUFFERS_ARB;
+ *aptr++ = 1;
+ *aptr++ = GLX_SAMPLES_ARB;
+ samples = aptr;
+ *aptr++ = 32;
+ }
+ *aptr++ = None;
+
+ if(!samples) {
+ return glXChooseVisual(dpy, scr, attr);
+ }
+ while(!(vi = glXChooseVisual(dpy, scr, attr)) && *samples) {
+ *samples >>= 1;
+ if(!*samples) {
+ aptr[-3] = None;
+ }
+ }
+ return vi;
+}
+
+static void create_window(const char *title)
+{
+ XSetWindowAttributes xattr = {0};
+ XVisualInfo *vi;
+ unsigned int xattr_mask;
+ unsigned int mode = init_mode;
+
+ if(!(vi = choose_visual(mode))) {
+ mode &= ~GLUT_SRGB;
+ if(!(vi = choose_visual(mode))) {
+ panic("Failed to find compatible visual\n");
+ }
+ }
+
+ if(!(ctx = glXCreateContext(dpy, vi, 0, True))) {
+ XFree(vi);
+ panic("Failed to create OpenGL context\n");
+ }
+
+ glXGetConfig(dpy, vi, GLX_RED_SIZE, &ctx_info.rsize);
+ glXGetConfig(dpy, vi, GLX_GREEN_SIZE, &ctx_info.gsize);
+ glXGetConfig(dpy, vi, GLX_BLUE_SIZE, &ctx_info.bsize);
+ glXGetConfig(dpy, vi, GLX_ALPHA_SIZE, &ctx_info.asize);
+ glXGetConfig(dpy, vi, GLX_DEPTH_SIZE, &ctx_info.zsize);
+ glXGetConfig(dpy, vi, GLX_STENCIL_SIZE, &ctx_info.ssize);
+ glXGetConfig(dpy, vi, GLX_DOUBLEBUFFER, &ctx_info.dblbuf);
+ glXGetConfig(dpy, vi, GLX_STEREO, &ctx_info.stereo);
+ glXGetConfig(dpy, vi, GLX_SAMPLES_ARB, &ctx_info.samples);
+ glXGetConfig(dpy, vi, GLX_FRAMEBUFFER_SRGB_CAPABLE_ARB, &ctx_info.srgb);
+
+ xattr.background_pixel = BlackPixel(dpy, scr);
+ xattr.colormap = XCreateColormap(dpy, root, vi->visual, AllocNone);
+ xattr_mask = CWBackPixel | CWColormap | CWBackPixmap | CWBorderPixel;
+ if(!(win = XCreateWindow(dpy, root, init_x, init_y, init_width, init_height, 0,
+ vi->depth, InputOutput, vi->visual, xattr_mask, &xattr))) {
+ XFree(vi);
+ glXDestroyContext(dpy, ctx);
+ panic("Failed to create window\n");
+ }
+ XFree(vi);
+
+ XSelectInput(dpy, win, evmask);
+
+ spnav_window(win);
+
+ glutSetWindowTitle(title);
+ glutSetIconTitle(title);
+ XSetWMProtocols(dpy, win, &xa_wm_del_win, 1);
+ XMapWindow(dpy, win);
+
+ glXMakeCurrent(dpy, win, ctx);
+}
+
+static void get_window_pos(int *x, int *y)
+{
+ Window child;
+ XTranslateCoordinates(dpy, win, root, 0, 0, x, y, &child);
+}
+
+static void get_window_size(int *w, int *h)
+{
+ XWindowAttributes wattr;
+ XGetWindowAttributes(dpy, win, &wattr);
+ *w = wattr.width;
+ *h = wattr.height;
+}
+
+static void get_screen_size(int *scrw, int *scrh)
+{
+ XWindowAttributes wattr;
+ XGetWindowAttributes(dpy, root, &wattr);
+ *scrw = wattr.width;
+ *scrh = wattr.height;
+}
+
+
+/* spaceball */
+enum {
+ CMD_APP_WINDOW = 27695,
+ CMD_APP_SENS
+};
+
+static Window get_daemon_window(Display *dpy);
+static int catch_badwin(Display *dpy, XErrorEvent *err);
+
+#define SPNAV_INITIALIZED (xa_motion_event)
+
+static int spnav_window(Window win)
+{
+ int (*prev_xerr_handler)(Display*, XErrorEvent*);
+ XEvent xev;
+ Window daemon_win;
+
+ if(!SPNAV_INITIALIZED) {
+ return -1;
+ }
+
+ if(!(daemon_win = get_daemon_window(dpy))) {
+ return -1;
+ }
+
+ prev_xerr_handler = XSetErrorHandler(catch_badwin);
+
+ xev.type = ClientMessage;
+ xev.xclient.send_event = False;
+ xev.xclient.display = dpy;
+ xev.xclient.window = win;
+ xev.xclient.message_type = xa_command_event;
+ xev.xclient.format = 16;
+ xev.xclient.data.s[0] = ((unsigned int)win & 0xffff0000) >> 16;
+ xev.xclient.data.s[1] = (unsigned int)win & 0xffff;
+ xev.xclient.data.s[2] = CMD_APP_WINDOW;
+
+ XSendEvent(dpy, daemon_win, False, 0, &xev);
+ XSync(dpy, False);
+
+ XSetErrorHandler(prev_xerr_handler);
+ return 0;
+}
+
+static Bool match_events(Display *dpy, XEvent *xev, char *arg)
+{
+ int evtype = *(int*)arg;
+
+ if(xev->type != ClientMessage) {
+ return False;
+ }
+
+ if(xev->xclient.message_type == xa_motion_event) {
+ return !evtype || evtype == SPNAV_EVENT_MOTION ? True : False;
+ }
+ if(xev->xclient.message_type == xa_button_press_event ||
+ xev->xclient.message_type == xa_button_release_event) {
+ return !evtype || evtype == SPNAV_EVENT_BUTTON ? True : False;
+ }
+ return False;
+}
+
+static int spnav_remove_events(int type)
+{
+ int rm_count = 0;
+ XEvent xev;
+ while(XCheckIfEvent(dpy, &xev, match_events, (char*)&type)) {
+ rm_count++;
+ }
+ return rm_count;
+}
+
+static int spnav_event(const XEvent *xev, union spnav_event *event)
+{
+ int i;
+ int xmsg_type;
+
+ xmsg_type = xev->xclient.message_type;
+
+ if(xmsg_type != xa_motion_event && xmsg_type != xa_button_press_event &&
+ xmsg_type != xa_button_release_event) {
+ return 0;
+ }
+
+ if(xmsg_type == xa_motion_event) {
+ event->type = SPNAV_EVENT_MOTION;
+ event->motion.data = &event->motion.x;
+
+ for(i=0; i<6; i++) {
+ event->motion.data[i] = xev->xclient.data.s[i + 2];
+ }
+ event->motion.period = xev->xclient.data.s[8];
+ } else {
+ event->type = SPNAV_EVENT_BUTTON;
+ event->button.press = xmsg_type == xa_button_press_event ? 1 : 0;
+ event->button.bnum = xev->xclient.data.s[2];
+ }
+ return event->type;
+}
+
+static int mglut_strcmp(const char *s1, const char *s2)
+{
+ while(*s1 && *s1 == *s2) {
+ s1++;
+ s2++;
+ }
+ return *s1 - *s2;
+}
+
+static Window get_daemon_window(Display *dpy)
+{
+ Window win;
+ XTextProperty wname;
+ Atom type;
+ int fmt;
+ unsigned long nitems, bytes_after;
+ unsigned char *prop;
+
+ XGetWindowProperty(dpy, root, xa_command_event, 0, 1, False, AnyPropertyType,
+ &type, &fmt, &nitems, &bytes_after, &prop);
+ if(!prop) {
+ return 0;
+ }
+
+ win = *(Window*)prop;
+ XFree(prop);
+
+ if(!XGetWMName(dpy, win, &wname) || mglut_strcmp("Magellan Window", (char*)wname.value) != 0) {
+ return 0;
+ }
+
+ return win;
+}
+
+static int catch_badwin(Display *dpy, XErrorEvent *err)
+{
+ return 0;
+}
+
+
+
+#endif /* BUILD_X11 */
+
+
+/* --------------- windows implementation ----------------- */
+#ifdef BUILD_WIN32
+static int reshape_pending;
+
+static void update_modkeys(void);
+static int translate_vkey(int vkey);
+static void handle_mbutton(int bn, int st, WPARAM wparam, LPARAM lparam);
+
+#ifdef MINIGLUT_WINMAIN
+int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hprev, char *cmdline, int showcmd)
+{
+ int argc = 1;
+ char *argv[] = { "miniglut.exe", 0 };
+ return main(argc, argv);
+}
+#endif
+
+void glutMainLoopEvent(void)
+{
+ MSG msg;
+
+ if(!cb_display) {
+ panic("display callback not set");
+ }
+
+ if(reshape_pending && cb_reshape) {
+ reshape_pending = 0;
+ get_window_size(&win_width, &win_height);
+ cb_reshape(win_width, win_height);
+ }
+
+ if(!upd_pending && !cb_idle) {
+ GetMessage(&msg, 0, 0, 0);
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ if(quit) return;
+ }
+ while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ if(quit) return;
+ }
+
+ if(cb_idle) {
+ cb_idle();
+ }
+
+ if(upd_pending && mapped) {
+ upd_pending = 0;
+ cb_display();
+ }
+}
+
+static void cleanup(void)
+{
+ if(win) {
+ wglMakeCurrent(dc, 0);
+ wglDeleteContext(ctx);
+ UnregisterClass("MiniGLUT", hinst);
+ }
+}
+
+void glutSwapBuffers(void)
+{
+ SwapBuffers(dc);
+}
+
+void glutPositionWindow(int x, int y)
+{
+ RECT rect;
+ unsigned int flags = SWP_SHOWWINDOW;
+
+ if(fullscreen) {
+ rect.left = prev_win_x;
+ rect.top = prev_win_y;
+ rect.right = rect.left + prev_win_width;
+ rect.bottom = rect.top + prev_win_height;
+ SetWindowLong(win, GWL_STYLE, WS_OVERLAPPEDWINDOW);
+ fullscreen = 0;
+ flags |= SWP_FRAMECHANGED;
+ } else {
+ GetWindowRect(win, &rect);
+ }
+ SetWindowPos(win, HWND_NOTOPMOST, x, y, rect.right - rect.left, rect.bottom - rect.top, flags);
+}
+
+void glutReshapeWindow(int xsz, int ysz)
+{
+ RECT rect;
+ unsigned int flags = SWP_SHOWWINDOW;
+
+ if(fullscreen) {
+ rect.left = prev_win_x;
+ rect.top = prev_win_y;
+ SetWindowLong(win, GWL_STYLE, WS_OVERLAPPEDWINDOW);
+ fullscreen = 0;
+ flags |= SWP_FRAMECHANGED;
+ } else {
+ GetWindowRect(win, &rect);
+ }
+ SetWindowPos(win, HWND_NOTOPMOST, rect.left, rect.top, xsz, ysz, flags);
+}
+
+void glutFullScreen(void)
+{
+ RECT rect;
+ int scr_width, scr_height;
+
+ if(fullscreen) return;
+
+ GetWindowRect(win, &rect);
+ prev_win_x = rect.left;
+ prev_win_y = rect.top;
+ prev_win_width = rect.right - rect.left;
+ prev_win_height = rect.bottom - rect.top;
+
+ get_screen_size(&scr_width, &scr_height);
+
+ SetWindowLong(win, GWL_STYLE, 0);
+ SetWindowPos(win, HWND_TOPMOST, 0, 0, scr_width, scr_height, SWP_SHOWWINDOW);
+
+ fullscreen = 1;
+}
+
+void glutSetWindowTitle(const char *title)
+{
+ SetWindowText(win, title);
+}
+
+void glutSetIconTitle(const char *title)
+{
+}
+
+void glutSetCursor(int cidx)
+{
+ switch(cidx) {
+ case GLUT_CURSOR_NONE:
+ ShowCursor(0);
+ break;
+ case GLUT_CURSOR_INHERIT:
+ case GLUT_CURSOR_LEFT_ARROW:
+ default:
+ SetCursor(LoadCursor(0, IDC_ARROW));
+ ShowCursor(1);
+ }
+}
+
+#define WGL_DRAW_TO_WINDOW 0x2001
+#define WGL_SUPPORT_OPENGL 0x2010
+#define WGL_DOUBLE_BUFFER 0x2011
+#define WGL_STEREO 0x2012
+#define WGL_PIXEL_TYPE 0x2013
+#define WGL_COLOR_BITS 0x2014
+#define WGL_RED_BITS 0x2015
+#define WGL_GREEN_BITS 0x2017
+#define WGL_BLUE_BITS 0x2019
+#define WGL_ALPHA_BITS 0x201b
+#define WGL_ACCUM_BITS 0x201d
+#define WGL_DEPTH_BITS 0x2022
+#define WGL_STENCIL_BITS 0x2023
+
+#define WGL_TYPE_RGBA 0x202b
+#define WGL_TYPE_COLORINDEX 0x202c
+
+#define WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB 0x20a9
+#define WGL_SAMPLE_BUFFERS_ARB 0x2041
+#define WGL_SAMPLES_ARB 0x2042
+
+static PROC wglChoosePixelFormat;
+static PROC wglGetPixelFormatAttribiv;
+
+#define ATTR(a, v) \
+ do { *aptr++ = (a); *aptr++ = (v); } while(0)
+
+static unsigned int choose_pixfmt(unsigned int mode)
+{
+ unsigned int num_pixfmt, pixfmt = 0;
+ int attr[32] = { WGL_DRAW_TO_WINDOW, 1, WGL_SUPPORT_OPENGL, 1 };
+
+ int *aptr = attr;
+ int *samples = 0;
+
+ if(mode & GLUT_DOUBLE) {
+ ATTR(WGL_DOUBLE_BUFFER, 1);
+ }
+
+ ATTR(WGL_PIXEL_TYPE, mode & GLUT_INDEX ? WGL_TYPE_COLORINDEX : WGL_TYPE_RGBA);
+ ATTR(WGL_COLOR_BITS, 8);
+ if(mode & GLUT_ALPHA) {
+ ATTR(WGL_ALPHA_BITS, 4);
+ }
+ if(mode & GLUT_DEPTH) {
+ ATTR(WGL_DEPTH_BITS, 16);
+ }
+ if(mode & GLUT_STENCIL) {
+ ATTR(WGL_STENCIL_BITS, 1);
+ }
+ if(mode & GLUT_ACCUM) {
+ ATTR(WGL_ACCUM_BITS, 1);
+ }
+ if(mode & GLUT_STEREO) {
+ ATTR(WGL_STEREO, 1);
+ }
+ if(mode & GLUT_SRGB) {
+ ATTR(WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, 1);
+ }
+ if(mode & GLUT_MULTISAMPLE) {
+ ATTR(WGL_SAMPLE_BUFFERS_ARB, 1);
+ *aptr++ = WGL_SAMPLES_ARB;
+ samples = aptr;
+ *aptr++ = 32;
+ }
+ *aptr++ = 0;
+
+ while((!wglChoosePixelFormat(dc, attr, 0, 1, &pixfmt, &num_pixfmt) || !num_pixfmt) && samples && *samples) {
+ *samples >>= 1;
+ if(!*samples) {
+ aptr[-3] = 0;
+ }
+ }
+ return pixfmt;
+}
+
+static PIXELFORMATDESCRIPTOR tmppfd = {
+ sizeof tmppfd, 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
+ PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 8, 0,
+ PFD_MAIN_PLANE, 0, 0, 0, 0
+};
+#define TMPCLASS "TempMiniGLUT"
+
+#define GETATTR(attr, vptr) \
+ do { \
+ int gattr = attr; \
+ wglGetPixelFormatAttribiv(dc, pixfmt, 0, 1, &gattr, vptr); \
+ } while(0)
+
+static int create_window_wglext(const char *title, int width, int height)
+{
+ WNDCLASSEX wc = {0};
+ HWND tmpwin = 0;
+ HDC tmpdc = 0;
+ HGLRC tmpctx = 0;
+ int pixfmt;
+
+ /* create a temporary window and GL context, just to query and retrieve
+ * the wglChoosePixelFormatEXT function
+ */
+ wc.cbSize = sizeof wc;
+ wc.hbrBackground = GetStockObject(BLACK_BRUSH);
+ wc.hCursor = LoadCursor(0, IDC_ARROW);
+ wc.hIcon = wc.hIconSm = LoadIcon(0, IDI_APPLICATION);
+ wc.hInstance = hinst;
+ wc.lpfnWndProc = DefWindowProc;
+ wc.lpszClassName = TMPCLASS;
+ wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
+ if(!RegisterClassEx(&wc)) {
+ return 0;
+ }
+ if(!(tmpwin = CreateWindow(TMPCLASS, "temp", WS_OVERLAPPEDWINDOW, 0, 0,
+ width, height, 0, 0, hinst, 0))) {
+ goto fail;
+ }
+ tmpdc = GetDC(tmpwin);
+
+ if(!(pixfmt = ChoosePixelFormat(tmpdc, &tmppfd)) ||
+ !SetPixelFormat(tmpdc, pixfmt, &tmppfd) ||
+ !(tmpctx = wglCreateContext(tmpdc))) {
+ goto fail;
+ }
+ wglMakeCurrent(tmpdc, tmpctx);
+
+ if(!(wglChoosePixelFormat = wglGetProcAddress("wglChoosePixelFormatARB"))) {
+ if(!(wglChoosePixelFormat = wglGetProcAddress("wglChoosePixelFormatEXT"))) {
+ goto fail;
+ }
+ if(!(wglGetPixelFormatAttribiv = wglGetProcAddress("wglGetPixelFormatAttribivEXT"))) {
+ goto fail;
+ }
+ } else {
+ if(!(wglGetPixelFormatAttribiv = wglGetProcAddress("wglGetPixelFormatAttribivARB"))) {
+ goto fail;
+ }
+ }
+ wglMakeCurrent(0, 0);
+ wglDeleteContext(tmpctx);
+ DestroyWindow(tmpwin);
+ UnregisterClass(TMPCLASS, hinst);
+
+ /* create the real window and context */
+ if(!(win = CreateWindow("MiniGLUT", title, WS_OVERLAPPEDWINDOW, init_x,
+ init_y, width, height, 0, 0, hinst, 0))) {
+ panic("Failed to create window\n");
+ }
+ dc = GetDC(win);
+
+ if(!(pixfmt = choose_pixfmt(init_mode))) {
+ panic("Failed to find suitable pixel format\n");
+ }
+ if(!SetPixelFormat(dc, pixfmt, &tmppfd)) {
+ panic("Failed to set the selected pixel format\n");
+ }
+ if(!(ctx = wglCreateContext(dc))) {
+ panic("Failed to create the OpenGL context\n");
+ }
+ wglMakeCurrent(dc, ctx);
+
+ GETATTR(WGL_RED_BITS, &ctx_info.rsize);
+ GETATTR(WGL_GREEN_BITS, &ctx_info.gsize);
+ GETATTR(WGL_BLUE_BITS, &ctx_info.bsize);
+ GETATTR(WGL_ALPHA_BITS, &ctx_info.asize);
+ GETATTR(WGL_DEPTH_BITS, &ctx_info.zsize);
+ GETATTR(WGL_STENCIL_BITS, &ctx_info.ssize);
+ GETATTR(WGL_DOUBLE_BUFFER, &ctx_info.dblbuf);
+ GETATTR(WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, &ctx_info.srgb);
+ GETATTR(WGL_SAMPLES_ARB, &ctx_info.samples);
+ return 0;
+
+fail:
+ if(tmpctx) {
+ wglMakeCurrent(0, 0);
+ wglDeleteContext(tmpctx);
+ }
+ if(tmpwin) {
+ DestroyWindow(tmpwin);
+ }
+ UnregisterClass(TMPCLASS, hinst);
+ return -1;
+}
+
+
+static void create_window(const char *title)
+{
+ int pixfmt;
+ PIXELFORMATDESCRIPTOR pfd = {0};
+ RECT rect;
+ int width, height;
+
+ rect.left = init_x;
+ rect.top = init_y;
+ rect.right = init_x + init_width;
+ rect.bottom = init_y + init_height;
+ AdjustWindowRect(&rect, WS_OVERLAPPEDWINDOW, 0);
+ width = rect.right - rect.left;
+ height = rect.bottom - rect.top;
+
+ if(create_window_wglext(title, width, height) == -1) {
+
+ if(!(win = CreateWindow("MiniGLUT", title, WS_OVERLAPPEDWINDOW,
+ rect.left, rect.top, width, height, 0, 0, hinst, 0))) {
+ panic("Failed to create window\n");
+ }
+ dc = GetDC(win);
+
+ pfd.nSize = sizeof pfd;
+ pfd.nVersion = 1;
+ pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
+ if(init_mode & GLUT_STEREO) {
+ pfd.dwFlags |= PFD_STEREO;
+ }
+ pfd.iPixelType = init_mode & GLUT_INDEX ? PFD_TYPE_COLORINDEX : PFD_TYPE_RGBA;
+ pfd.cColorBits = 24;
+ if(init_mode & GLUT_ALPHA) {
+ pfd.cAlphaBits = 8;
+ }
+ if(init_mode & GLUT_ACCUM) {
+ pfd.cAccumBits = 24;
+ }
+ if(init_mode & GLUT_DEPTH) {
+ pfd.cDepthBits = 24;
+ }
+ if(init_mode & GLUT_STENCIL) {
+ pfd.cStencilBits = 8;
+ }
+ pfd.iLayerType = PFD_MAIN_PLANE;
+
+ if(!(pixfmt = ChoosePixelFormat(dc, &pfd))) {
+ panic("Failed to find suitable pixel format\n");
+ }
+ if(!SetPixelFormat(dc, pixfmt, &pfd)) {
+ panic("Failed to set the selected pixel format\n");
+ }
+ if(!(ctx = wglCreateContext(dc))) {
+ panic("Failed to create the OpenGL context\n");
+ }
+ wglMakeCurrent(dc, ctx);
+
+ DescribePixelFormat(dc, pixfmt, sizeof pfd, &pfd);
+ ctx_info.rsize = pfd.cRedBits;
+ ctx_info.gsize = pfd.cGreenBits;
+ ctx_info.bsize = pfd.cBlueBits;
+ ctx_info.asize = pfd.cAlphaBits;
+ ctx_info.zsize = pfd.cDepthBits;
+ ctx_info.ssize = pfd.cStencilBits;
+ ctx_info.dblbuf = pfd.dwFlags & PFD_DOUBLEBUFFER ? 1 : 0;
+ ctx_info.samples = 0;
+ ctx_info.srgb = 0;
+ }
+
+ ShowWindow(win, 1);
+ SetForegroundWindow(win);
+ SetFocus(win);
+ upd_pending = 1;
+ reshape_pending = 1;
+}
+
+static HRESULT CALLBACK handle_message(HWND win, unsigned int msg, WPARAM wparam, LPARAM lparam)
+{
+ static int mouse_x, mouse_y;
+ int x, y, key;
+
+ switch(msg) {
+ case WM_CLOSE:
+ if(win) DestroyWindow(win);
+ break;
+
+ case WM_DESTROY:
+ cleanup();
+ quit = 1;
+ PostQuitMessage(0);
+ break;
+
+ case WM_PAINT:
+ upd_pending = 1;
+ ValidateRect(win, 0);
+ break;
+
+ case WM_SIZE:
+ x = lparam & 0xffff;
+ y = lparam >> 16;
+ if(x != win_width && y != win_height) {
+ win_width = x;
+ win_height = y;
+ if(cb_reshape) {
+ reshape_pending = 0;
+ cb_reshape(win_width, win_height);
+ }
+ }
+ break;
+
+ case WM_SHOWWINDOW:
+ mapped = wparam;
+ if(cb_vis) cb_vis(mapped ? GLUT_VISIBLE : GLUT_NOT_VISIBLE);
+ break;
+
+ case WM_KEYDOWN:
+ case WM_SYSKEYDOWN:
+ update_modkeys();
+ key = translate_vkey(wparam);
+ if(key < 256) {
+ if(cb_keydown) {
+ cb_keydown((unsigned char)key, mouse_x, mouse_y);
+ }
+ } else {
+ if(cb_skeydown) {
+ cb_skeydown(key, mouse_x, mouse_y);
+ }
+ }
+ break;
+
+ case WM_KEYUP:
+ case WM_SYSKEYUP:
+ update_modkeys();
+ key = translate_vkey(wparam);
+ if(key < 256) {
+ if(cb_keyup) {
+ cb_keyup((unsigned char)key, mouse_x, mouse_y);
+ }
+ } else {
+ if(cb_skeyup) {
+ cb_skeyup(key, mouse_x, mouse_y);
+ }
+ }
+ break;
+
+ case WM_LBUTTONDOWN:
+ handle_mbutton(0, 1, wparam, lparam);
+ break;
+ case WM_MBUTTONDOWN:
+ handle_mbutton(1, 1, wparam, lparam);
+ break;
+ case WM_RBUTTONDOWN:
+ handle_mbutton(2, 1, wparam, lparam);
+ break;
+ case WM_LBUTTONUP:
+ handle_mbutton(0, 0, wparam, lparam);
+ break;
+ case WM_MBUTTONUP:
+ handle_mbutton(1, 0, wparam, lparam);
+ break;
+ case WM_RBUTTONUP:
+ handle_mbutton(2, 0, wparam, lparam);
+ break;
+
+ case WM_MOUSEMOVE:
+ if(wparam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) {
+ if(cb_motion) cb_motion(lparam & 0xffff, lparam >> 16);
+ } else {
+ if(cb_passive) cb_passive(lparam & 0xffff, lparam >> 16);
+ }
+ break;
+
+ case WM_SYSCOMMAND:
+ wparam &= 0xfff0;
+ if(wparam == SC_KEYMENU || wparam == SC_SCREENSAVE || wparam == SC_MONITORPOWER) {
+ return 0;
+ }
+ default:
+ return DefWindowProc(win, msg, wparam, lparam);
+ }
+
+ return 0;
+}
+
+static void update_modkeys(void)
+{
+ if(GetKeyState(VK_SHIFT) & 0x8000) {
+ modstate |= GLUT_ACTIVE_SHIFT;
+ } else {
+ modstate &= ~GLUT_ACTIVE_SHIFT;
+ }
+ if(GetKeyState(VK_CONTROL) & 0x8000) {
+ modstate |= GLUT_ACTIVE_CTRL;
+ } else {
+ modstate &= ~GLUT_ACTIVE_CTRL;
+ }
+ if(GetKeyState(VK_MENU) & 0x8000) {
+ modstate |= GLUT_ACTIVE_ALT;
+ } else {
+ modstate &= ~GLUT_ACTIVE_ALT;
+ }
+}
+
+static int translate_vkey(int vkey)
+{
+ switch(vkey) {
+ case VK_PRIOR: return GLUT_KEY_PAGE_UP;
+ case VK_NEXT: return GLUT_KEY_PAGE_DOWN;
+ case VK_END: return GLUT_KEY_END;
+ case VK_HOME: return GLUT_KEY_HOME;
+ case VK_LEFT: return GLUT_KEY_LEFT;
+ case VK_UP: return GLUT_KEY_UP;
+ case VK_RIGHT: return GLUT_KEY_RIGHT;
+ case VK_DOWN: return GLUT_KEY_DOWN;
+ default:
+ break;
+ }
+
+ if(vkey >= 'A' && vkey <= 'Z') {
+ vkey += 32;
+ } else if(vkey >= VK_F1 && vkey <= VK_F12) {
+ vkey -= VK_F1 + GLUT_KEY_F1;
+ }
+
+ return vkey;
+}
+
+static void handle_mbutton(int bn, int st, WPARAM wparam, LPARAM lparam)
+{
+ int x, y;
+
+ update_modkeys();
+
+ if(cb_mouse) {
+ x = lparam & 0xffff;
+ y = lparam >> 16;
+ cb_mouse(bn, st ? GLUT_DOWN : GLUT_UP, x, y);
+ }
+}
+
+static void get_window_pos(int *x, int *y)
+{
+ RECT rect;
+ GetWindowRect(win, &rect);
+ *x = rect.left;
+ *y = rect.top;
+}
+
+static void get_window_size(int *w, int *h)
+{
+ RECT rect;
+ GetClientRect(win, &rect);
+ *w = rect.right - rect.left;
+ *h = rect.bottom - rect.top;
+}
+
+static void get_screen_size(int *scrw, int *scrh)
+{
+ *scrw = GetSystemMetrics(SM_CXSCREEN);
+ *scrh = GetSystemMetrics(SM_CYSCREEN);
+}
+#endif /* BUILD_WIN32 */
+
+#if defined(__unix__) || defined(__APPLE__)
+#include <sys/time.h>
+
+#ifdef MINIGLUT_USE_LIBC
+#define sys_gettimeofday(tv, tz) gettimeofday(tv, tz)
+#else
+static int sys_gettimeofday(struct timeval *tv, struct timezone *tz);
+#endif
+
+static long get_msec(void)
+{
+ static struct timeval tv0;
+ struct timeval tv;
+
+ sys_gettimeofday(&tv, 0);
+ if(tv0.tv_sec == 0 && tv0.tv_usec == 0) {
+ tv0 = tv;
+ return 0;
+ }
+ return (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000;
+}
+#endif /* UNIX */
+#ifdef _WIN32
+static long get_msec(void)
+{
+ static long t0;
+ long tm;
+
+#ifdef MINIGLUT_NO_WINMM
+ tm = GetTickCount();
+#else
+ tm = timeGetTime();
+#endif
+ if(!t0) {
+ t0 = tm;
+ return 0;
+ }
+ return tm - t0;
+}
+#endif
+
+static void panic(const char *msg)
+{
+ const char *end = msg;
+ while(*end) end++;
+ sys_write(2, msg, end - msg);
+ sys_exit(1);
+}
+
+
+#ifdef MINIGLUT_USE_LIBC
+#include <stdlib.h>
+#ifdef __unix__
+#include <unistd.h>
+#endif
+
+static void sys_exit(int status)
+{
+ exit(status);
+}
+
+static int sys_write(int fd, const void *buf, int count)
+{
+ return write(fd, buf, count);
+}
+
+#else /* !MINIGLUT_USE_LIBC */
+
+#ifdef __linux__
+#ifdef __x86_64__
+static void sys_exit(int status)
+{
+ asm volatile(
+ "syscall\n\t"
+ :: "a"(60), "D"(status));
+}
+static int sys_write(int fd, const void *buf, int count)
+{
+ long res;
+ asm volatile(
+ "syscall\n\t"
+ : "=a"(res)
+ : "a"(1), "D"(fd), "S"(buf), "d"(count));
+ return res;
+}
+static int sys_gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+ int res;
+ asm volatile(
+ "syscall\n\t"
+ : "=a"(res)
+ : "a"(96), "D"(tv), "S"(tz));
+ return res;
+}
+#endif /* __x86_64__ */
+#ifdef __i386__
+static void sys_exit(int status)
+{
+ asm volatile(
+ "int $0x80\n\t"
+ :: "a"(1), "b"(status));
+}
+static int sys_write(int fd, const void *buf, int count)
+{
+ int res;
+ asm volatile(
+ "int $0x80\n\t"
+ : "=a"(res)
+ : "a"(4), "b"(fd), "c"(buf), "d"(count));
+ return res;
+}
+static int sys_gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+ int res;
+ asm volatile(
+ "int $0x80\n\t"
+ : "=a"(res)
+ : "a"(78), "b"(tv), "c"(tz));
+ return res;
+}
+#endif /* __i386__ */
+#endif /* __linux__ */
+
+#ifdef _WIN32
+static void sys_exit(int status)
+{
+ ExitProcess(status);
+}
+static int sys_write(int fd, const void *buf, int count)
+{
+ unsigned long wrsz = 0;
+
+ HANDLE out = GetStdHandle(fd == 1 ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE);
+ if(!WriteFile(out, buf, count, &wrsz, 0)) {
+ return -1;
+ }
+ return wrsz;
+}
+#endif /* _WIN32 */
+#endif /* !MINIGLUT_USE_LIBC */
+
+
+/* ----------------- primitives ------------------ */
+#ifdef MINIGLUT_USE_LIBC
+#include <stdlib.h>
+#include <math.h>
+
+void mglut_sincos(float angle, float *sptr, float *cptr)
+{
+ *sptr = sin(angle);
+ *cptr = cos(angle);
+}
+
+float mglut_atan(float x)
+{
+ return atan(x);
+}
+
+#else /* !MINIGLUT_USE_LIBC */
+
+#ifdef __GNUC__
+void mglut_sincos(float angle, float *sptr, float *cptr)
+{
+ asm volatile(
+ "flds %2\n\t"
+ "fsincos\n\t"
+ "fstps %1\n\t"
+ "fstps %0\n\t"
+ : "=m"(*sptr), "=m"(*cptr)
+ : "m"(angle)
+ );
+}
+
+float mglut_atan(float x)
+{
+ float res;
+ asm volatile(
+ "flds %1\n\t"
+ "fld1\n\t"
+ "fpatan\n\t"
+ "fstps %0\n\t"
+ : "=m"(res)
+ : "m"(x)
+ );
+ return res;
+}
+#endif
+
+#ifdef _MSC_VER
+void mglut_sincos(float angle, float *sptr, float *cptr)
+{
+ float s, c;
+ __asm {
+ fld angle
+ fsincos
+ fstp c
+ fstp s
+ }
+ *sptr = s;
+ *cptr = c;
+}
+
+float mglut_atan(float x)
+{
+ float res;
+ __asm {
+ fld x
+ fld1
+ fpatan
+ fstp res
+ }
+ return res;
+}
+#endif
+
+#ifdef __WATCOMC__
+#pragma aux mglut_sincos = \
+ "fsincos" \
+ "fstp dword ptr [edx]" \
+ "fstp dword ptr [eax]" \
+ parm[8087][eax][edx] \
+ modify[8087];
+
+#pragma aux mglut_atan = \
+ "fld1" \
+ "fpatan" \
+ parm[8087] \
+ value[8087] \
+ modify [8087];
+#endif /* __WATCOMC__ */
+
+#endif /* !MINIGLUT_USE_LIBC */
+
+#define PI 3.1415926536f
+
+void glutSolidSphere(float rad, int slices, int stacks)
+{
+ int i, j, k, gray;
+ float x, y, z, s, t, u, v, phi, theta, sintheta, costheta, sinphi, cosphi;
+ float du = 1.0f / (float)slices;
+ float dv = 1.0f / (float)stacks;
+
+ glBegin(GL_QUADS);
+ for(i=0; i<stacks; i++) {
+ v = i * dv;
+ for(j=0; j<slices; j++) {
+ u = j * du;
+ for(k=0; k<4; k++) {
+ gray = k ^ (k >> 1);
+ s = gray & 1 ? u + du : u;
+ t = gray & 2 ? v + dv : v;
+ theta = s * PI * 2.0f;
+ phi = t * PI;
+ mglut_sincos(theta, &sintheta, &costheta);
+ mglut_sincos(phi, &sinphi, &cosphi);
+ x = sintheta * sinphi;
+ y = costheta * sinphi;
+ z = cosphi;
+
+ glColor3f(s, t, 1);
+ glTexCoord2f(s, t);
+ glNormal3f(x, y, z);
+ glVertex3f(x * rad, y * rad, z * rad);
+ }
+ }
+ }
+ glEnd();
+}
+
+void glutWireSphere(float rad, int slices, int stacks)
+{
+ glPushAttrib(GL_POLYGON_BIT);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glutSolidSphere(rad, slices, stacks);
+ glPopAttrib();
+}
+
+void glutSolidCube(float sz)
+{
+ int i, j, idx, gray, flip, rotx;
+ float vpos[3], norm[3];
+ float rad = sz * 0.5f;
+
+ glBegin(GL_QUADS);
+ for(i=0; i<6; i++) {
+ flip = i & 1;
+ rotx = i >> 2;
+ idx = (~i & 2) - rotx;
+ norm[0] = norm[1] = norm[2] = 0.0f;
+ norm[idx] = flip ^ ((i >> 1) & 1) ? -1 : 1;
+ glNormal3fv(norm);
+ vpos[idx] = norm[idx] * rad;
+ for(j=0; j<4; j++) {
+ gray = j ^ (j >> 1);
+ vpos[i & 2] = (gray ^ flip) & 1 ? rad : -rad;
+ vpos[rotx + 1] = (gray ^ (rotx << 1)) & 2 ? rad : -rad;
+ glTexCoord2f(gray & 1, gray >> 1);
+ glVertex3fv(vpos);
+ }
+ }
+ glEnd();
+}
+
+void glutWireCube(float sz)
+{
+ glPushAttrib(GL_POLYGON_BIT);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glutSolidCube(sz);
+ glPopAttrib();
+}
+
+static void draw_cylinder(float rbot, float rtop, float height, int slices, int stacks)
+{
+ int i, j, k, gray;
+ float x, y, z, s, t, u, v, theta, phi, sintheta, costheta, sinphi, cosphi, rad;
+ float du = 1.0f / (float)slices;
+ float dv = 1.0f / (float)stacks;
+
+ rad = rbot - rtop;
+ phi = mglut_atan((rad < 0 ? -rad : rad) / height);
+ mglut_sincos(phi, &sinphi, &cosphi);
+
+ glBegin(GL_QUADS);
+ for(i=0; i<stacks; i++) {
+ v = i * dv;
+ for(j=0; j<slices; j++) {
+ u = j * du;
+ for(k=0; k<4; k++) {
+ gray = k ^ (k >> 1);
+ s = gray & 2 ? u + du : u;
+ t = gray & 1 ? v + dv : v;
+ rad = rbot + (rtop - rbot) * t;
+ theta = s * PI * 2.0f;
+ mglut_sincos(theta, &sintheta, &costheta);
+
+ x = sintheta * cosphi;
+ y = costheta * cosphi;
+ z = sinphi;
+
+ glColor3f(s, t, 1);
+ glTexCoord2f(s, t);
+ glNormal3f(x, y, z);
+ glVertex3f(sintheta * rad, costheta * rad, t * height);
+ }
+ }
+ }
+ glEnd();
+}
+
+void glutSolidCone(float base, float height, int slices, int stacks)
+{
+ draw_cylinder(base, 0, height, slices, stacks);
+}
+
+void glutWireCone(float base, float height, int slices, int stacks)
+{
+ glPushAttrib(GL_POLYGON_BIT);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glutSolidCone(base, height, slices, stacks);
+ glPopAttrib();
+}
+
+void glutSolidCylinder(float rad, float height, int slices, int stacks)
+{
+ draw_cylinder(rad, rad, height, slices, stacks);
+}
+
+void glutWireCylinder(float rad, float height, int slices, int stacks)
+{
+ glPushAttrib(GL_POLYGON_BIT);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glutSolidCylinder(rad, height, slices, stacks);
+ glPopAttrib();
+}
+
+void glutSolidTorus(float inner_rad, float outer_rad, int sides, int rings)
+{
+ int i, j, k, gray;
+ float x, y, z, s, t, u, v, phi, theta, sintheta, costheta, sinphi, cosphi;
+ float du = 1.0f / (float)rings;
+ float dv = 1.0f / (float)sides;
+
+ glBegin(GL_QUADS);
+ for(i=0; i<rings; i++) {
+ u = i * du;
+ for(j=0; j<sides; j++) {
+ v = j * dv;
+ for(k=0; k<4; k++) {
+ gray = k ^ (k >> 1);
+ s = gray & 1 ? u + du : u;
+ t = gray & 2 ? v + dv : v;
+ theta = s * PI * 2.0f;
+ phi = t * PI * 2.0f;
+ mglut_sincos(theta, &sintheta, &costheta);
+ mglut_sincos(phi, &sinphi, &cosphi);
+ x = sintheta * sinphi;
+ y = costheta * sinphi;
+ z = cosphi;
+
+ glColor3f(s, t, 1);
+ glTexCoord2f(s, t);
+ glNormal3f(x, y, z);
+
+ x = x * inner_rad + sintheta * outer_rad;
+ y = y * inner_rad + costheta * outer_rad;
+ z *= inner_rad;
+ glVertex3f(x, y, z);
+ }
+ }
+ }
+ glEnd();
+}
+
+void glutWireTorus(float inner_rad, float outer_rad, int sides, int rings)
+{
+ glPushAttrib(GL_POLYGON_BIT);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glutSolidTorus(inner_rad, outer_rad, sides, rings);
+ glPopAttrib();
+}
+
+#define NUM_TEAPOT_INDICES (sizeof teapot_index / sizeof *teapot_index)
+#define NUM_TEAPOT_VERTS (sizeof teapot_verts / sizeof *teapot_verts)
+
+#define NUM_TEAPOT_PATCHES (NUM_TEAPOT_INDICES / 16)
+
+#define PATCH_SUBDIV 7
+
+static float teapot_part_flip[] = {
+ 1, 1, 1, 1, /* rim flip */
+ 1, 1, 1, 1, /* body1 flip */
+ 1, 1, 1, 1, /* body2 flip */
+ 1, 1, 1, 1, /* lid patch 1 flip */
+ 1, 1, 1, 1, /* lid patch 2 flip */
+ 1, -1, /* handle 1 flip */
+ 1, -1, /* handle 2 flip */
+ 1, -1, /* spout 1 flip */
+ 1, -1, /* spout 2 flip */
+ 1, 1, 1, 1 /* bottom flip */
+};
+
+static float teapot_part_rot[] = {
+ 0, 90, 180, 270, /* rim rotations */
+ 0, 90, 180, 270, /* body patch 1 rotations */
+ 0, 90, 180, 270, /* body patch 2 rotations */
+ 0, 90, 180, 270, /* lid patch 1 rotations */
+ 0, 90, 180, 270, /* lid patch 2 rotations */
+ 0, 0, /* handle 1 rotations */
+ 0, 0, /* handle 2 rotations */
+ 0, 0, /* spout 1 rotations */
+ 0, 0, /* spout 2 rotations */
+ 0, 90, 180, 270 /* bottom rotations */
+};
+
+
+static int teapot_index[] = {
+ /* rim */
+ 102, 103, 104, 105, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 102, 103, 104, 105, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 102, 103, 104, 105, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ 102, 103, 104, 105, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+ /* body1 */
+ 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
+ 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
+ 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
+ 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
+ /* body 2 */
+ 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+ 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+ 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+ 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+ /* lid 1 */
+ 96, 96, 96, 96, 97, 98, 99, 100, 101, 101, 101, 101, 0, 1, 2, 3,
+ 96, 96, 96, 96, 97, 98, 99, 100, 101, 101, 101, 101, 0, 1, 2, 3,
+ 96, 96, 96, 96, 97, 98, 99, 100, 101, 101, 101, 101, 0, 1, 2, 3,
+ 96, 96, 96, 96, 97, 98, 99, 100, 101, 101, 101, 101, 0, 1, 2, 3,
+ /* lid 2 */
+ 0, 1, 2, 3, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
+ 0, 1, 2, 3, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
+ 0, 1, 2, 3, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
+ 0, 1, 2, 3, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
+ /* handle 1 */
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
+ /* handle 2 */
+ 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 28, 65, 66, 67,
+ 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 28, 65, 66, 67,
+ /* spout 1 */
+ 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
+ 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
+ /* spout 2 */
+ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+ 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+ /* bottom */
+ 118, 118, 118, 118, 124, 122, 119, 121, 123, 126, 125, 120, 40, 39, 38, 37,
+ 118, 118, 118, 118, 124, 122, 119, 121, 123, 126, 125, 120, 40, 39, 38, 37,
+ 118, 118, 118, 118, 124, 122, 119, 121, 123, 126, 125, 120, 40, 39, 38, 37,
+ 118, 118, 118, 118, 124, 122, 119, 121, 123, 126, 125, 120, 40, 39, 38, 37
+};
+
+
+static float teapot_verts[][3] = {
+ { 0.2000, 0.0000, 2.70000 }, { 0.2000, -0.1120, 2.70000 },
+ { 0.1120, -0.2000, 2.70000 }, { 0.0000, -0.2000, 2.70000 },
+ { 1.3375, 0.0000, 2.53125 }, { 1.3375, -0.7490, 2.53125 },
+ { 0.7490, -1.3375, 2.53125 }, { 0.0000, -1.3375, 2.53125 },
+ { 1.4375, 0.0000, 2.53125 }, { 1.4375, -0.8050, 2.53125 },
+ { 0.8050, -1.4375, 2.53125 }, { 0.0000, -1.4375, 2.53125 },
+ { 1.5000, 0.0000, 2.40000 }, { 1.5000, -0.8400, 2.40000 },
+ { 0.8400, -1.5000, 2.40000 }, { 0.0000, -1.5000, 2.40000 },
+ { 1.7500, 0.0000, 1.87500 }, { 1.7500, -0.9800, 1.87500 },
+ { 0.9800, -1.7500, 1.87500 }, { 0.0000, -1.7500, 1.87500 },
+ { 2.0000, 0.0000, 1.35000 }, { 2.0000, -1.1200, 1.35000 },
+ { 1.1200, -2.0000, 1.35000 }, { 0.0000, -2.0000, 1.35000 },
+ { 2.0000, 0.0000, 0.90000 }, { 2.0000, -1.1200, 0.90000 },
+ { 1.1200, -2.0000, 0.90000 }, { 0.0000, -2.0000, 0.90000 },
+ { -2.0000, 0.0000, 0.90000 }, { 2.0000, 0.0000, 0.45000 },
+ { 2.0000, -1.1200, 0.45000 }, { 1.1200, -2.0000, 0.45000 },
+ { 0.0000, -2.0000, 0.45000 }, { 1.5000, 0.0000, 0.22500 },
+ { 1.5000, -0.8400, 0.22500 }, { 0.8400, -1.5000, 0.22500 },
+ { 0.0000, -1.5000, 0.22500 }, { 1.5000, 0.0000, 0.15000 },
+ { 1.5000, -0.8400, 0.15000 }, { 0.8400, -1.5000, 0.15000 },
+ { 0.0000, -1.5000, 0.15000 }, { -1.6000, 0.0000, 2.02500 },
+ { -1.6000, -0.3000, 2.02500 }, { -1.5000, -0.3000, 2.25000 },
+ { -1.5000, 0.0000, 2.25000 }, { -2.3000, 0.0000, 2.02500 },
+ { -2.3000, -0.3000, 2.02500 }, { -2.5000, -0.3000, 2.25000 },
+ { -2.5000, 0.0000, 2.25000 }, { -2.7000, 0.0000, 2.02500 },
+ { -2.7000, -0.3000, 2.02500 }, { -3.0000, -0.3000, 2.25000 },
+ { -3.0000, 0.0000, 2.25000 }, { -2.7000, 0.0000, 1.80000 },
+ { -2.7000, -0.3000, 1.80000 }, { -3.0000, -0.3000, 1.80000 },
+ { -3.0000, 0.0000, 1.80000 }, { -2.7000, 0.0000, 1.57500 },
+ { -2.7000, -0.3000, 1.57500 }, { -3.0000, -0.3000, 1.35000 },
+ { -3.0000, 0.0000, 1.35000 }, { -2.5000, 0.0000, 1.12500 },
+ { -2.5000, -0.3000, 1.12500 }, { -2.6500, -0.3000, 0.93750 },
+ { -2.6500, 0.0000, 0.93750 }, { -2.0000, -0.3000, 0.90000 },
+ { -1.9000, -0.3000, 0.60000 }, { -1.9000, 0.0000, 0.60000 },
+ { 1.7000, 0.0000, 1.42500 }, { 1.7000, -0.6600, 1.42500 },
+ { 1.7000, -0.6600, 0.60000 }, { 1.7000, 0.0000, 0.60000 },
+ { 2.6000, 0.0000, 1.42500 }, { 2.6000, -0.6600, 1.42500 },
+ { 3.1000, -0.6600, 0.82500 }, { 3.1000, 0.0000, 0.82500 },
+ { 2.3000, 0.0000, 2.10000 }, { 2.3000, -0.2500, 2.10000 },
+ { 2.4000, -0.2500, 2.02500 }, { 2.4000, 0.0000, 2.02500 },
+ { 2.7000, 0.0000, 2.40000 }, { 2.7000, -0.2500, 2.40000 },
+ { 3.3000, -0.2500, 2.40000 }, { 3.3000, 0.0000, 2.40000 },
+ { 2.8000, 0.0000, 2.47500 }, { 2.8000, -0.2500, 2.47500 },
+ { 3.5250, -0.2500, 2.49375 }, { 3.5250, 0.0000, 2.49375 },
+ { 2.9000, 0.0000, 2.47500 }, { 2.9000, -0.1500, 2.47500 },
+ { 3.4500, -0.1500, 2.51250 }, { 3.4500, 0.0000, 2.51250 },
+ { 2.8000, 0.0000, 2.40000 }, { 2.8000, -0.1500, 2.40000 },
+ { 3.2000, -0.1500, 2.40000 }, { 3.2000, 0.0000, 2.40000 },
+ { 0.0000, 0.0000, 3.15000 }, { 0.8000, 0.0000, 3.15000 },
+ { 0.8000, -0.4500, 3.15000 }, { 0.4500, -0.8000, 3.15000 },
+ { 0.0000, -0.8000, 3.15000 }, { 0.0000, 0.0000, 2.85000 },
+ { 1.4000, 0.0000, 2.40000 }, { 1.4000, -0.7840, 2.40000 },
+ { 0.7840, -1.4000, 2.40000 }, { 0.0000, -1.4000, 2.40000 },
+ { 0.4000, 0.0000, 2.55000 }, { 0.4000, -0.2240, 2.55000 },
+ { 0.2240, -0.4000, 2.55000 }, { 0.0000, -0.4000, 2.55000 },
+ { 1.3000, 0.0000, 2.55000 }, { 1.3000, -0.7280, 2.55000 },
+ { 0.7280, -1.3000, 2.55000 }, { 0.0000, -1.3000, 2.55000 },
+ { 1.3000, 0.0000, 2.40000 }, { 1.3000, -0.7280, 2.40000 },
+ { 0.7280, -1.3000, 2.40000 }, { 0.0000, -1.3000, 2.40000 },
+ { 0.0000, 0.0000, 0.00000 }, { 1.4250, -0.7980, 0.00000 },
+ { 1.5000, 0.0000, 0.07500 }, { 1.4250, 0.0000, 0.00000 },
+ { 0.7980, -1.4250, 0.00000 }, { 0.0000, -1.5000, 0.07500 },
+ { 0.0000, -1.4250, 0.00000 }, { 1.5000, -0.8400, 0.07500 },
+ { 0.8400, -1.5000, 0.07500 }
+};
+
+static void draw_patch(int *index, int flip, float scale);
+static float bernstein(int i, float x);
+
+void glutSolidTeapot(float size)
+{
+ int i;
+
+ size /= 2.0;
+
+ for(i=0; i<NUM_TEAPOT_PATCHES; i++) {
+ float flip = teapot_part_flip[i];
+ float rot = teapot_part_rot[i];
+
+ glMatrixMode(GL_MODELVIEW);
+ glPushMatrix();
+ glTranslatef(0, -3.15 * size * 0.5, 0);
+ glRotatef(rot, 0, 1, 0);
+ glScalef(1, 1, flip);
+ glRotatef(-90, 1, 0, 0);
+
+ draw_patch(teapot_index + i * 16, flip < 0.0 ? 1 : 0, size);
+
+ glPopMatrix();
+ }
+}
+
+void glutWireTeapot(float size)
+{
+ glPushAttrib(GL_POLYGON_BIT);
+ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
+ glutSolidTeapot(size);
+ glPopAttrib();
+}
+
+
+static void bezier_patch(float *res, float *cp, float u, float v)
+{
+ int i, j;
+
+ res[0] = res[1] = res[2] = 0.0f;
+
+ for(j=0; j<4; j++) {
+ for(i=0; i<4; i++) {
+ float bu = bernstein(i, u);
+ float bv = bernstein(j, v);
+
+ res[0] += cp[0] * bu * bv;
+ res[1] += cp[1] * bu * bv;
+ res[2] += cp[2] * bu * bv;
+
+ cp += 3;
+ }
+ }
+}
+
+static float rsqrt(float x)
+{
+ float xhalf = x * 0.5f;
+ int i = *(int*)&x;
+ i = 0x5f3759df - (i >> 1);
+ x = *(float*)&i;
+ x = x * (1.5f - xhalf * x * x);
+ return x;
+}
+
+
+#define CROSS(res, a, b) \
+ do { \
+ (res)[0] = (a)[1] * (b)[2] - (a)[2] * (b)[1]; \
+ (res)[1] = (a)[2] * (b)[0] - (a)[0] * (b)[2]; \
+ (res)[2] = (a)[0] * (b)[1] - (a)[1] * (b)[0]; \
+ } while(0)
+
+#define NORMALIZE(v) \
+ do { \
+ float s = rsqrt((v)[0] * (v)[0] + (v)[1] * (v)[1] + (v)[2] * (v)[2]); \
+ (v)[0] *= s; \
+ (v)[1] *= s; \
+ (v)[2] *= s; \
+ } while(0)
+
+#define DT 0.001
+
+static void bezier_patch_norm(float *res, float *cp, float u, float v)
+{
+ float tang[3], bitan[3], tmp[3];
+
+ bezier_patch(tang, cp, u + DT, v);
+ bezier_patch(tmp, cp, u - DT, v);
+ tang[0] -= tmp[0];
+ tang[1] -= tmp[1];
+ tang[2] -= tmp[2];
+
+ bezier_patch(bitan, cp, u, v + DT);
+ bezier_patch(tmp, cp, u, v - DT);
+ bitan[0] -= tmp[0];
+ bitan[1] -= tmp[1];
+ bitan[2] -= tmp[2];
+
+ CROSS(res, tang, bitan);
+ NORMALIZE(res);
+}
+
+
+
+static float bernstein(int i, float x)
+{
+ float invx = 1.0f - x;
+
+ switch(i) {
+ case 0:
+ return invx * invx * invx;
+ case 1:
+ return 3.0f * x * invx * invx;
+ case 2:
+ return 3.0f * x * x * invx;
+ case 3:
+ return x * x * x;
+ default:
+ break;
+ }
+ return 0.0f;
+}
+
+static void draw_patch(int *index, int flip, float scale)
+{
+ static const float uoffs[2][4] = {{0, 0, 1, 1}, {1, 1, 0, 0}};
+ static const float voffs[4] = {0, 1, 1, 0};
+
+ int i, j, k;
+ float cp[16 * 3];
+ float pt[3], n[3];
+ float u, v;
+ float du = 1.0 / PATCH_SUBDIV;
+ float dv = 1.0 / PATCH_SUBDIV;
+
+ /* collect control points */
+ for(i=0; i<16; i++) {
+ cp[i * 3] = teapot_verts[index[i]][0];
+ cp[i * 3 + 1] = teapot_verts[index[i]][1];
+ cp[i * 3 + 2] = teapot_verts[index[i]][2];
+ }
+
+ glBegin(GL_QUADS);
+ glColor3f(1, 1, 1);
+
+ u = 0;
+ for(i=0; i<PATCH_SUBDIV; i++) {
+ v = 0;
+ for(j=0; j<PATCH_SUBDIV; j++) {
+
+ for(k=0; k<4; k++) {
+ bezier_patch(pt, cp, u + uoffs[flip][k] * du, v + voffs[k] * dv);
+
+ /* top/bottom normal hack */
+ if(pt[2] > 3.14) {
+ n[0] = n[1] = 0.0f;
+ n[2] = 1.0f;
+ } else if(pt[2] < 0.00001) {
+ n[0] = n[1] = 0.0f;
+ n[2] = -1.0f;
+ } else {
+ bezier_patch_norm(n, cp, u + uoffs[flip][k] * du, v + voffs[k] * dv);
+ }
+
+ glTexCoord2f(u, v);
+ glNormal3fv(n);
+ glVertex3f(pt[0] * scale, pt[1] * scale, pt[2] * scale);
+ }
+
+ v += dv;
+ }
+ u += du;
+ }
+
+ glEnd();
+}
--- /dev/null
+/*
+MiniGLUT - minimal GLUT subset without dependencies
+Copyright (C) 2020 John Tsiombikas <nuclear@member.fsf.org>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <https://www.gnu.org/licenses/>.
+ */
+#ifndef MINIGLUT_H_
+#define MINIGLUT_H_
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN 1
+#include <windows.h>
+
+#ifdef _MSC_VER
+#pragma comment (lib, "opengl32")
+#ifndef MINIGLUT_NO_WINMM
+#pragma comment (lib, "winmm")
+#endif
+#endif /* MSVC */
+
+#endif
+#include <GL/gl.h>
+
+/* mode flags for glutInitDisplayMode */
+#define GLUT_RGB 0
+#define GLUT_RGBA 0
+#define GLUT_INDEX 0x001
+#define GLUT_SINGLE 0
+#define GLUT_DOUBLE 0x002
+#define GLUT_ACCUM 0x004
+#define GLUT_ALPHA 0x008
+#define GLUT_DEPTH 0x010
+#define GLUT_STENCIL 0x020
+#define GLUT_STEREO 0x040
+#define GLUT_MULTISAMPLE 0x100
+#define GLUT_SRGB 0x200
+
+enum { GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, GLUT_RIGHT_BUTTON };
+enum { GLUT_UP, GLUT_DOWN };
+enum { GLUT_NOT_VISIBLE, GLUT_VISIBLE };
+enum { GLUT_LEFT, GLUT_ENTERED };
+
+/* cursors */
+enum {
+ GLUT_CURSOR_INHERIT,
+ GLUT_CURSOR_LEFT_ARROW,
+ GLUT_CURSOR_NONE
+};
+
+/* glutGet */
+enum {
+ GLUT_WINDOW_X,
+ GLUT_WINDOW_Y,
+ GLUT_WINDOW_WIDTH,
+ GLUT_WINDOW_HEIGHT,
+ GLUT_WINDOW_BUFFER_SIZE,
+ GLUT_WINDOW_STENCIL_SIZE,
+ GLUT_WINDOW_DEPTH_SIZE,
+ GLUT_WINDOW_RED_SIZE,
+ GLUT_WINDOW_GREEN_SIZE,
+ GLUT_WINDOW_BLUE_SIZE,
+ GLUT_WINDOW_ALPHA_SIZE,
+ GLUT_WINDOW_DOUBLEBUFFER,
+ GLUT_WINDOW_RGBA,
+ GLUT_WINDOW_NUM_SAMPLES,
+ GLUT_WINDOW_STEREO,
+ GLUT_WINDOW_SRGB,
+ GLUT_WINDOW_CURSOR,
+ GLUT_SCREEN_WIDTH,
+ GLUT_SCREEN_HEIGHT,
+ GLUT_INIT_DISPLAY_MODE,
+ GLUT_INIT_WINDOW_X,
+ GLUT_INIT_WINDOW_Y,
+ GLUT_INIT_WINDOW_WIDTH,
+ GLUT_INIT_WINDOW_HEIGHT,
+ GLUT_ELAPSED_TIME
+};
+
+enum {
+ GLUT_KEY_HOME = 0xff50,
+ GLUT_KEY_LEFT = 0xff51,
+ GLUT_KEY_UP,
+ GLUT_KEY_RIGHT,
+ GLUT_KEY_DOWN,
+ GLUT_KEY_PAGE_UP,
+ GLUT_KEY_PAGE_DOWN,
+ GLUT_KEY_END = 0xff57,
+ GLUT_KEY_INSERT = 0xff63,
+ GLUT_KEY_F1 = 0xffbe,
+ GLUT_KEY_F2,
+ GLUT_KEY_F3,
+ GLUT_KEY_F4,
+ GLUT_KEY_F5,
+ GLUT_KEY_F6,
+ GLUT_KEY_F7,
+ GLUT_KEY_F8,
+ GLUT_KEY_F9,
+ GLUT_KEY_F10,
+ GLUT_KEY_F11,
+ GLUT_KEY_F12
+};
+
+/* returned by glutGetModifiers */
+#define GLUT_ACTIVE_SHIFT 1
+#define GLUT_ACTIVE_CTRL 4
+#define GLUT_ACTIVE_ALT 8
+
+typedef void (*glut_cb)(void);
+typedef void (*glut_cb_reshape)(int x, int y);
+typedef void (*glut_cb_state)(int state);
+typedef void (*glut_cb_keyb)(unsigned char key, int x, int y);
+typedef void (*glut_cb_special)(int key, int x, int y);
+typedef void (*glut_cb_mouse)(int bn, int state, int x, int y);
+typedef void (*glut_cb_motion)(int x, int y);
+typedef void (*glut_cb_sbmotion)(int x, int y, int z);
+typedef void (*glut_cb_sbbutton)(int bn, int state);
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void glutInit(int *argc, char **argv);
+void glutInitWindowPosition(int x, int y);
+void glutInitWindowSize(int xsz, int ysz);
+void glutInitDisplayMode(unsigned int mode);
+void glutCreateWindow(const char *title);
+
+void glutExit(void);
+void glutMainLoop(void);
+void glutMainLoopEvent(void);
+
+void glutPostRedisplay(void);
+void glutSwapBuffers(void);
+void glutPositionWindow(int x, int y);
+void glutReshapeWindow(int xsz, int ysz);
+void glutFullScreen(void);
+void glutSetWindowTitle(const char *title);
+void glutSetIconTitle(const char *title);
+void glutSetCursor(int cursor);
+
+void glutIdleFunc(glut_cb func);
+void glutDisplayFunc(glut_cb func);
+void glutReshapeFunc(glut_cb_reshape func);
+void glutVisibilityFunc(glut_cb_state func);
+void glutEntryFunc(glut_cb_state func);
+void glutKeyboardFunc(glut_cb_keyb func);
+void glutKeyboardUpFunc(glut_cb_keyb func);
+void glutSpecialFunc(glut_cb_special func);
+void glutSpecialUpFunc(glut_cb_special func);
+void glutMouseFunc(glut_cb_mouse func);
+void glutMotionFunc(glut_cb_motion func);
+void glutPassiveMotionFunc(glut_cb_motion func);
+void glutSpaceballMotionFunc(glut_cb_sbmotion func);
+void glutSpaceballRotateFunc(glut_cb_sbmotion func);
+void glutSpaceballButtonFunc(glut_cb_sbbutton func);
+
+int glutGet(unsigned int s);
+int glutGetModifiers(void);
+int glutExtensionSupported(char *ext);
+
+void glutSolidSphere(float rad, int slices, int stacks);
+void glutWireSphere(float rad, int slices, int stacks);
+void glutSolidCube(float sz);
+void glutWireCube(float sz);
+void glutSolidCone(float base, float height, int slices, int stacks);
+void glutWireCone(float base, float height, int slices, int stacks);
+void glutSolidCylinder(float rad, float height, int slices, int stacks);
+void glutSolidTorus(float inner_rad, float outer_rad, int sides, int rings);
+void glutWireTorus(float inner_rad, float outer_rad, int sides, int rings);
+void glutSolidTeapot(float size);
+void glutWireTeapot(float size);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif /* MINIGLUT_H_ */
--- /dev/null
+Copyright (C) 2016 John Tsiombikas <nuclear@member.fsf.org>
+
+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.
--- /dev/null
+obj = treestore.o text.o dynarr.o
+lib = libtreestore.a
+
+CFLAGS = -O3
+
+$(lib): $(obj)
+ $(AR) rcs $@ $(obj)
+
+.PHONY: clean
+clean:
+ rm -f $(obj) $(lib)
--- /dev/null
+libtreestore
+============
+
+Libtreestore is a simple C library for reading/writing hierarchical data in a
+json-like text format, or a chunk-based binary format.
+
+A better way to describe the text format is like XML without the CDATA, and with
+curly braces instead of tags:
+
+```
+rootnode {
+ some_attribute = "some_string_value"
+ some_numeric_attrib = 10
+ vector_attrib = [255, 128, 0]
+ array_attrib = ["tom", "dick", "harry"]
+
+ # you can have multiple nodes with the same name
+ childnode {
+ childattr = "whatever"
+ }
+ childnode {
+ another_childattr = "xyzzy"
+ }
+}
+```
+
+License
+-------
+Copyright (C) 2016-2019 John Tsiombikas <nuclear@member.fsf.org>
+
+Libtreestore is free software. Feel free to use, modify, and/or redistribute
+it, under the terms of the MIT/X11 license. See LICENSE for detauls.
+
+Issues
+------
+At the moment only the text format has been implemented.
+
+More info soon...
--- /dev/null
+/* dynarr - dynamic resizable C array data structure
+ * author: John Tsiombikas <nuclear@member.fsf.org>
+ * license: public domain
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "dynarr.h"
+
+/* The array descriptor keeps auxilliary information needed to manipulate
+ * the dynamic array. It's allocated adjacent to the array buffer.
+ */
+struct arrdesc {
+ int nelem, szelem;
+ int max_elem;
+ int bufsz; /* not including the descriptor */
+};
+
+#define DESC(x) ((struct arrdesc*)((char*)(x) - sizeof(struct arrdesc)))
+
+void *ts_dynarr_alloc(int elem, int szelem)
+{
+ struct arrdesc *desc;
+
+ if(!(desc = malloc(elem * szelem + sizeof *desc))) {
+ return 0;
+ }
+ desc->nelem = desc->max_elem = elem;
+ desc->szelem = szelem;
+ desc->bufsz = elem * szelem;
+ return (char*)desc + sizeof *desc;
+}
+
+void ts_dynarr_free(void *da)
+{
+ if(da) {
+ free(DESC(da));
+ }
+}
+
+void *ts_dynarr_resize(void *da, int elem)
+{
+ int newsz;
+ void *tmp;
+ struct arrdesc *desc;
+
+ if(!da) return 0;
+ desc = DESC(da);
+
+ newsz = desc->szelem * elem;
+
+ if(!(tmp = realloc(desc, newsz + sizeof *desc))) {
+ return 0;
+ }
+ desc = tmp;
+
+ desc->nelem = desc->max_elem = elem;
+ desc->bufsz = newsz;
+ return (char*)desc + sizeof *desc;
+}
+
+int ts_dynarr_empty(void *da)
+{
+ return DESC(da)->nelem ? 0 : 1;
+}
+
+int ts_dynarr_size(void *da)
+{
+ return DESC(da)->nelem;
+}
+
+
+void *ts_dynarr_clear(void *da)
+{
+ return ts_dynarr_resize(da, 0);
+}
+
+/* stack semantics */
+void *ts_dynarr_push(void *da, void *item)
+{
+ struct arrdesc *desc;
+ int nelem;
+
+ desc = DESC(da);
+ nelem = desc->nelem;
+
+ if(nelem >= desc->max_elem) {
+ /* need to resize */
+ struct arrdesc *tmp;
+ int newsz = desc->max_elem ? desc->max_elem * 2 : 1;
+
+ if(!(tmp = ts_dynarr_resize(da, newsz))) {
+ fprintf(stderr, "failed to resize\n");
+ return da;
+ }
+ da = tmp;
+ desc = DESC(da);
+ desc->nelem = nelem;
+ }
+
+ if(item) {
+ memcpy((char*)da + desc->nelem++ * desc->szelem, item, desc->szelem);
+ }
+ return da;
+}
+
+void *ts_dynarr_pop(void *da)
+{
+ struct arrdesc *desc;
+ int nelem;
+
+ desc = DESC(da);
+ nelem = desc->nelem;
+
+ if(!nelem) return da;
+
+ if(nelem <= desc->max_elem / 3) {
+ /* reclaim space */
+ struct arrdesc *tmp;
+ int newsz = desc->max_elem / 2;
+
+ if(!(tmp = ts_dynarr_resize(da, newsz))) {
+ fprintf(stderr, "failed to resize\n");
+ return da;
+ }
+ da = tmp;
+ desc = DESC(da);
+ desc->nelem = nelem;
+ }
+ desc->nelem--;
+
+ return da;
+}
--- /dev/null
+/* dynarr - dynamic resizable C array data structure
+ * author: John Tsiombikas <nuclear@member.fsf.org>
+ * license: public domain
+ */
+#ifndef DYNARR_H_
+#define DYNARR_H_
+
+/* usage example:
+ * -------------
+ * int *arr = ts_dynarr_alloc(0, sizeof *arr);
+ *
+ * int x = 10;
+ * arr = ts_dynarr_push(arr, &x);
+ * x = 5;
+ * arr = ts_dynarr_push(arr, &x);
+ * x = 42;
+ * arr = ts_dynarr_push(arr, &x);
+ *
+ * for(i=0; i<ts_dynarr_size(arr); i++) {
+ * printf("%d\n", arr[i]);
+ * }
+ * ts_dynarr_free(arr);
+ */
+
+void *ts_dynarr_alloc(int elem, int szelem);
+void ts_dynarr_free(void *da);
+void *ts_dynarr_resize(void *da, int elem);
+
+int ts_dynarr_empty(void *da);
+int ts_dynarr_size(void *da);
+
+void *ts_dynarr_clear(void *da);
+
+/* stack semantics */
+void *ts_dynarr_push(void *da, void *item);
+void *ts_dynarr_pop(void *da);
+
+
+/* helper macros */
+#define DYNARR_RESIZE(da, n) \
+ do { (da) = ts_dynarr_resize((da), (n)); } while(0)
+#define DYNARR_CLEAR(da) \
+ do { (da) = ts_dynarr_clear(da); } while(0)
+#define DYNARR_PUSH(da, item) \
+ do { (da) = ts_dynarr_push((da), (item)); } while(0)
+#define DYNARR_POP(da) \
+ do { (da) = ts_dynarr_pop(da); } while(0)
+
+/* utility macros to push characters to a string. assumes and maintains
+ * the invariant that the last element is always a zero
+ */
+#define DYNARR_STRPUSH(da, c) \
+ do { \
+ char cnull = 0, ch = (char)(c); \
+ (da) = ts_dynarr_pop(da); \
+ (da) = ts_dynarr_push((da), &ch); \
+ (da) = ts_dynarr_push((da), &cnull); \
+ } while(0)
+
+#define DYNARR_STRPOP(da) \
+ do { \
+ char cnull = 0; \
+ (da) = ts_dynarr_pop(da); \
+ (da) = ts_dynarr_pop(da); \
+ (da) = ts_dynarr_push((da), &cnull); \
+ } while(0)
+
+
+#endif /* DYNARR_H_ */
--- /dev/null
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <assert.h>
+#include "treestore.h"
+#include "dynarr.h"
+
+struct parser {
+ struct ts_io *io;
+ int nline;
+ char *token;
+ int nextc;
+};
+
+enum { TOK_SYM, TOK_ID, TOK_NUM, TOK_STR };
+
+static struct ts_node *read_node(struct parser *pstate);
+static int read_array(struct parser *pstate, struct ts_value *tsv, char endsym);
+static int next_token(struct parser *pstate);
+
+static int print_attr(struct ts_attr *attr, struct ts_io *io, int level);
+static char *value_to_str(struct ts_value *value);
+static int tree_level(struct ts_node *n);
+static const char *indent(int x);
+static const char *toktypestr(int type);
+
+#define EXPECT(type) \
+ do { \
+ if(next_token(pst) != (type)) { \
+ fprintf(stderr, "expected %s token\n", toktypestr(type)); \
+ goto err; \
+ } \
+ } while(0)
+
+#define EXPECT_SYM(c) \
+ do { \
+ if(next_token(pst) != TOK_SYM || pst->token[0] != (c)) { \
+ fprintf(stderr, "expected symbol: %c\n", c); \
+ goto err; \
+ } \
+ } while(0)
+
+
+struct ts_node *ts_text_load(struct ts_io *io)
+{
+ char *root_name;
+ struct parser pstate, *pst = &pstate;
+ struct ts_node *node = 0;
+
+ pstate.io = io;
+ pstate.nline = 0;
+ pstate.nextc = -1;
+ if(!(pstate.token = ts_dynarr_alloc(0, 1))) {
+ perror("failed to allocate token string");
+ return 0;
+ }
+
+ EXPECT(TOK_ID);
+ if(!(root_name = strdup(pst->token))) {
+ perror("failed to allocate root node name");
+ ts_dynarr_free(pst->token);
+ return 0;
+ }
+ EXPECT_SYM('{');
+ if(!(node = read_node(pst))) {
+ ts_dynarr_free(pst->token);
+ return 0;
+ }
+ node->name = root_name;
+
+err:
+ ts_dynarr_free(pst->token);
+ return node;
+}
+
+static int read_value(struct parser *pst, int toktype, struct ts_value *val)
+{
+ switch(toktype) {
+ case TOK_NUM:
+ ts_set_valuef(val, atof(pst->token));
+ break;
+
+ case TOK_SYM:
+ if(pst->token[0] == '[' || pst->token[0] == '{') {
+ char endsym = pst->token[0] + 2; /* end symbol is dist 2 from either '[' or '{' */
+ if(read_array(pst, val, endsym) == -1) {
+ return -1;
+ }
+ } else {
+ fprintf(stderr, "read_node: unexpected rhs symbol: %c\n", pst->token[0]);
+ }
+ break;
+
+ case TOK_ID:
+ case TOK_STR:
+ default:
+ ts_set_value_str(val, pst->token);
+ }
+
+ return 0;
+}
+
+static struct ts_node *read_node(struct parser *pst)
+{
+ int type;
+ struct ts_node *node;
+
+ if(!(node = ts_alloc_node())) {
+ perror("failed to allocate treestore node");
+ return 0;
+ }
+
+ while((type = next_token(pst)) == TOK_ID) {
+ char *id;
+
+ if(!(id = strdup(pst->token))) {
+ goto err;
+ }
+
+ EXPECT(TOK_SYM);
+
+ if(pst->token[0] == '=') {
+ /* attribute */
+ struct ts_attr *attr;
+ int type;
+
+ if(!(attr = ts_alloc_attr())) {
+ goto err;
+ }
+
+ if((type = next_token(pst)) == -1) {
+ ts_free_attr(attr);
+ fprintf(stderr, "read_node: unexpected EOF\n");
+ goto err;
+ }
+
+ if(read_value(pst, type, &attr->val) == -1) {
+ ts_free_attr(attr);
+ fprintf(stderr, "failed to read value\n");
+ goto err;
+ }
+ attr->name = id;
+ ts_add_attr(node, attr);
+
+ } else if(pst->token[0] == '{') {
+ /* child */
+ struct ts_node *child;
+
+ if(!(child = read_node(pst))) {
+ ts_free_node(node);
+ return 0;
+ }
+
+ child->name = id;
+ ts_add_child(node, child);
+
+ } else {
+ fprintf(stderr, "unexpected token: %s\n", pst->token);
+ goto err;
+ }
+ }
+
+ if(type != TOK_SYM || pst->token[0] != '}') {
+ fprintf(stderr, "expected closing brace\n");
+ goto err;
+ }
+ return node;
+
+err:
+ fprintf(stderr, "treestore read_node failed\n");
+ ts_free_node(node);
+ return 0;
+}
+
+static int read_array(struct parser *pst, struct ts_value *tsv, char endsym)
+{
+ int type;
+ struct ts_value values[32];
+ int i, nval = 0;
+ int res;
+
+ while((type = next_token(pst)) != -1) {
+ ts_init_value(values + nval);
+ if(read_value(pst, type, values + nval) == -1) {
+ return -1;
+ }
+ if(nval < 31) {
+ ++nval;
+ } else {
+ ts_destroy_value(values + nval);
+ }
+
+ type = next_token(pst);
+ if(!(type == TOK_SYM && (pst->token[0] == ',' || pst->token[0] == endsym))) {
+ fprintf(stderr, "read_array: expected comma or end symbol ('%c')\n", endsym);
+ return -1;
+ }
+ if(pst->token[0] == endsym) {
+ break; /* we're done */
+ }
+ }
+
+ if(!nval) {
+ return -1;
+ }
+
+ res = ts_set_value_arr(tsv, nval, values);
+
+ for(i=0; i<nval; i++) {
+ ts_destroy_value(values + i);
+ }
+ return res;
+}
+
+static int nextchar(struct parser *pst)
+{
+ char c;
+
+ if(pst->nextc >= 0) {
+ c = pst->nextc;
+ pst->nextc = -1;
+ } else {
+ if(pst->io->read(&c, 1, pst->io->data) < 1) {
+ return -1;
+ }
+ }
+ return c;
+}
+
+static void ungetchar(char c, struct parser *pst)
+{
+ assert(pst->nextc == -1);
+ pst->nextc = c;
+}
+
+static int next_token(struct parser *pst)
+{
+ int c;
+
+ DYNARR_CLEAR(pst->token);
+
+ /* skip whitespace */
+ while((c = nextchar(pst)) != -1) {
+ if(c == '#') { /* skip to end of line */
+ while((c = nextchar(pst)) != -1 && c != '\n');
+ if(c == -1) return -1;
+ }
+ if(!isspace(c)) break;
+ if(c == '\n') ++pst->nline;
+ }
+ if(c == -1) return -1;
+
+ DYNARR_STRPUSH(pst->token, c);
+
+ if(isdigit(c) || c == '-' || c == '+') {
+ /* token is a number */
+ int found_dot = 0;
+ while((c = nextchar(pst)) != -1 &&
+ (isdigit(c) || (c == '.' && !found_dot))) {
+ DYNARR_STRPUSH(pst->token, c);
+ if(c == '.') found_dot = 1;
+ }
+ if(c != -1) ungetchar(c, pst);
+ return TOK_NUM;
+ }
+ if(isalpha(c)) {
+ /* token is an identifier */
+ while((c = nextchar(pst)) != -1 && (isalnum(c) || c == '_')) {
+ DYNARR_STRPUSH(pst->token, c);
+ }
+ if(c != -1) ungetchar(c, pst);
+ return TOK_ID;
+ }
+ if(c == '"') {
+ /* token is a string constant, remove the opening quote */
+ DYNARR_STRPOP(pst->token);
+ while((c = nextchar(pst)) != -1 && c != '"') {
+ DYNARR_STRPUSH(pst->token, c);
+ if(c == '\n') ++pst->nline;
+ }
+ if(c != '"') {
+ return -1;
+ }
+ return TOK_STR;
+ }
+ return TOK_SYM;
+}
+
+int ts_text_save(struct ts_node *tree, struct ts_io *io)
+{
+ char *buf;
+ struct ts_node *c;
+ struct ts_attr *attr;
+ int lvl = tree_level(tree);
+ int sz, inline_attr, res = -1;
+
+ if(!(buf = malloc(lvl + strlen(tree->name) + 4))) {
+ perror("ts_text_save failed to allocate buffer");
+ goto end;
+ }
+
+ if(tree->child_list || (tree->attr_list && tree->attr_list->next)) {
+ inline_attr = 0;
+ } else {
+ inline_attr = 1;
+ }
+
+ sz = sprintf(buf, "%s%s {", indent(lvl), tree->name);
+ if(!inline_attr) {
+ strcat(buf, "\n");
+ sz++;
+ }
+ if(io->write(buf, sz, io->data) < sz) {
+ goto end;
+ }
+
+ attr = tree->attr_list;
+ while(attr) {
+ if(print_attr(attr, io, inline_attr ? -1 : lvl) == -1) {
+ goto end;
+ }
+ attr = attr->next;
+ }
+
+ c = tree->child_list;
+ while(c) {
+ if(ts_text_save(c, io) == -1) {
+ goto end;
+ }
+ c = c->next;
+ }
+
+ if(inline_attr) {
+ sz = sprintf(buf, "}\n");
+ } else {
+ sz = sprintf(buf, "%s}\n", indent(lvl));
+ }
+ if(io->write(buf, sz, io->data) < sz) {
+ goto end;
+ }
+ res = 0;
+end:
+ free(buf);
+ return res;
+}
+
+static int print_attr(struct ts_attr *attr, struct ts_io *io, int level)
+{
+ char *buf, *val;
+ int sz;
+
+ if(!(val = value_to_str(&attr->val))) {
+ return -1;
+ }
+
+ sz = (level >= 0 ? level : 0) + strlen(attr->name) + ts_dynarr_size(val) + 5;
+ if(!(buf = malloc(sz))) {
+ perror("print_attr: failed to allocate name buffer");
+ ts_dynarr_free(val);
+ }
+
+ if(level >= 0) {
+ sz = sprintf(buf, "%s%s = %s\n", indent(level + 1), attr->name, val);
+ } else {
+ sz = sprintf(buf, " %s = %s ", attr->name, val);
+ }
+ if(io->write(buf, sz, io->data) < sz) {
+ ts_dynarr_free(val);
+ free(buf);
+ return -1;
+ }
+ ts_dynarr_free(val);
+ free(buf);
+ return 0;
+}
+
+static char *append_dynstr(char *dest, char *s)
+{
+ while(*s) {
+ DYNARR_STRPUSH(dest, *s++);
+ }
+ return dest;
+}
+
+static char *value_to_str(struct ts_value *value)
+{
+ int i;
+ char buf[128];
+ char *str, *valstr;
+
+ if(!(str = ts_dynarr_alloc(0, 1))) {
+ return 0;
+ }
+
+ switch(value->type) {
+ case TS_NUMBER:
+ sprintf(buf, "%g", value->fnum);
+ str = append_dynstr(str, buf);
+ break;
+
+ case TS_VECTOR:
+ DYNARR_STRPUSH(str, '[');
+ for(i=0; i<value->vec_size; i++) {
+ if(i == 0) {
+ sprintf(buf, "%g", value->vec[i]);
+ } else {
+ sprintf(buf, ", %g", value->vec[i]);
+ }
+ str = append_dynstr(str, buf);
+ }
+ DYNARR_STRPUSH(str, ']');
+ break;
+
+ case TS_ARRAY:
+ DYNARR_STRPUSH(str, '[');
+ for(i=0; i<value->array_size; i++) {
+ if(i > 0) {
+ str = append_dynstr(str, ", ");
+ }
+ if(!(valstr = value_to_str(value->array + i))) {
+ ts_dynarr_free(str);
+ return 0;
+ }
+ str = append_dynstr(str, valstr);
+ ts_dynarr_free(valstr);
+ }
+ DYNARR_STRPUSH(str, ']');
+ break;
+
+ default:
+ sprintf(buf, "\"%s\"", value->str);
+ str = append_dynstr(str, buf);
+ }
+
+ return str;
+}
+
+static int tree_level(struct ts_node *n)
+{
+ if(!n->parent) return 0;
+ return tree_level(n->parent) + 1;
+}
+
+static const char *indent(int x)
+{
+ static const char buf[] = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
+ const char *end = buf + sizeof buf - 1;
+ return x > sizeof buf - 1 ? buf : end - x;
+}
+
+static const char *toktypestr(int type)
+{
+ switch(type) {
+ case TOK_ID:
+ return "identifier";
+ case TOK_NUM:
+ return "number";
+ case TOK_STR:
+ return "string";
+ case TOK_SYM:
+ return "symbol";
+ }
+ return "unknown";
+}
--- /dev/null
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+#include "treestore.h"
+
+#ifdef WIN32
+#include <malloc.h>
+#else
+#include <alloca.h>
+#endif
+
+struct ts_node *ts_text_load(struct ts_io *io);
+int ts_text_save(struct ts_node *tree, struct ts_io *io);
+
+static long io_read(void *buf, size_t bytes, void *uptr);
+static long io_write(const void *buf, size_t bytes, void *uptr);
+
+
+/* ---- ts_value implementation ---- */
+
+int ts_init_value(struct ts_value *tsv)
+{
+ memset(tsv, 0, sizeof *tsv);
+ return 0;
+}
+
+void ts_destroy_value(struct ts_value *tsv)
+{
+ int i;
+
+ free(tsv->str);
+ free(tsv->vec);
+
+ for(i=0; i<tsv->array_size; i++) {
+ ts_destroy_value(tsv->array + i);
+ }
+ free(tsv->array);
+}
+
+
+struct ts_value *ts_alloc_value(void)
+{
+ struct ts_value *v = malloc(sizeof *v);
+ if(!v || ts_init_value(v) == -1) {
+ free(v);
+ return 0;
+ }
+ return v;
+}
+
+void ts_free_value(struct ts_value *tsv)
+{
+ ts_destroy_value(tsv);
+ free(tsv);
+}
+
+
+int ts_copy_value(struct ts_value *dest, struct ts_value *src)
+{
+ int i;
+
+ if(dest == src) return 0;
+
+ *dest = *src;
+
+ dest->str = 0;
+ dest->vec = 0;
+ dest->array = 0;
+
+ if(src->str) {
+ if(!(dest->str = malloc(strlen(src->str) + 1))) {
+ goto fail;
+ }
+ strcpy(dest->str, src->str);
+ }
+ if(src->vec && src->vec_size > 0) {
+ if(!(dest->vec = malloc(src->vec_size * sizeof *src->vec))) {
+ goto fail;
+ }
+ memcpy(dest->vec, src->vec, src->vec_size * sizeof *src->vec);
+ }
+ if(src->array && src->array_size > 0) {
+ if(!(dest->array = calloc(src->array_size, sizeof *src->array))) {
+ goto fail;
+ }
+ for(i=0; i<src->array_size; i++) {
+ if(ts_copy_value(dest->array + i, src->array + i) == -1) {
+ goto fail;
+ }
+ }
+ }
+ return 0;
+
+fail:
+ free(dest->str);
+ free(dest->vec);
+ if(dest->array) {
+ for(i=0; i<dest->array_size; i++) {
+ ts_destroy_value(dest->array + i);
+ }
+ free(dest->array);
+ }
+ return -1;
+}
+
+#define MAKE_NUMSTR_FUNC(type, fmt) \
+ static char *make_##type##str(type x) \
+ { \
+ static char scrap[128]; \
+ char *str; \
+ int sz = snprintf(scrap, sizeof scrap, fmt, x); \
+ if(!(str = malloc(sz + 1))) return 0; \
+ sprintf(str, fmt, x); \
+ return str; \
+ }
+
+MAKE_NUMSTR_FUNC(int, "%d")
+MAKE_NUMSTR_FUNC(float, "%g")
+
+
+struct val_list_node {
+ struct ts_value val;
+ struct val_list_node *next;
+};
+
+int ts_set_value_str(struct ts_value *tsv, const char *str)
+{
+ if(tsv->str) {
+ ts_destroy_value(tsv);
+ if(ts_init_value(tsv) == -1) {
+ return -1;
+ }
+ }
+
+ tsv->type = TS_STRING;
+ if(!(tsv->str = malloc(strlen(str) + 1))) {
+ return -1;
+ }
+ strcpy(tsv->str, str);
+
+#if 0
+ /* try to parse the string and see if it fits any of the value types */
+ if(*str == '[' || *str == '{') {
+ /* try to parse as a vector */
+ struct val_list_node *list = 0, *tail = 0, *node;
+ int nelem = 0;
+ char endsym = *str++ + 2; /* ']' is '[' + 2 and '}' is '{' + 2 */
+
+ while(*str && *str != endsym) {
+ float val = strtod(str, &endp);
+ if(endp == str || !(node = malloc(sizeof *node))) {
+ break;
+ }
+ ts_init_value(&node->val);
+ ts_set_valuef(&node->val, val);
+ node->next = 0;
+
+ if(list) {
+ tail->next = node;
+ tail = node;
+ } else {
+ list = tail = node;
+ }
+ ++nelem;
+ str = endp;
+ }
+
+ if(nelem && (tsv->array = malloc(nelem * sizeof *tsv->array)) &&
+ (tsv->vec = malloc(nelem * sizeof *tsv->vec))) {
+ int idx = 0;
+ while(list) {
+ node = list;
+ list = list->next;
+
+ tsv->array[idx] = node->val;
+ tsv->vec[idx] = node->val.fnum;
+ ++idx;
+ free(node);
+ }
+ tsv->type = TS_VECTOR;
+ }
+
+ } else if((tsv->fnum = strtod(str, &endp)), endp != str) {
+ /* it's a number I guess... */
+ tsv->type = TS_NUMBER;
+ }
+#endif
+
+ return 0;
+}
+
+int ts_set_valuei_arr(struct ts_value *tsv, int count, const int *arr)
+{
+ int i;
+
+ if(count < 1) return -1;
+ if(count == 1) {
+ if(!(tsv->str = make_intstr(*arr))) {
+ return -1;
+ }
+
+ tsv->type = TS_NUMBER;
+ tsv->fnum = (float)*arr;
+ tsv->inum = *arr;
+ return 0;
+ }
+
+ /* otherwise it's an array, we need to create the ts_value array, and
+ * the simplified vector
+ */
+ if(!(tsv->vec = malloc(count * sizeof *tsv->vec))) {
+ return -1;
+ }
+ tsv->vec_size = count;
+
+ for(i=0; i<count; i++) {
+ tsv->vec[i] = arr[i];
+ }
+
+ if(!(tsv->array = malloc(count * sizeof *tsv->array))) {
+ free(tsv->vec);
+ }
+ tsv->array_size = count;
+
+ for(i=0; i<count; i++) {
+ ts_init_value(tsv->array + i);
+ ts_set_valuef(tsv->array + i, arr[i]);
+ }
+
+ tsv->type = TS_VECTOR;
+ return 0;
+}
+
+int ts_set_valueiv(struct ts_value *tsv, int count, ...)
+{
+ int res;
+ va_list ap;
+ va_start(ap, count);
+ res = ts_set_valueiv_va(tsv, count, ap);
+ va_end(ap);
+ return res;
+}
+
+int ts_set_valueiv_va(struct ts_value *tsv, int count, va_list ap)
+{
+ int i, *vec;
+
+ if(count < 1) return -1;
+ if(count == 1) {
+ int num = va_arg(ap, int);
+ ts_set_valuei(tsv, num);
+ return 0;
+ }
+
+ vec = alloca(count * sizeof *vec);
+ for(i=0; i<count; i++) {
+ vec[i] = va_arg(ap, int);
+ }
+ return ts_set_valuei_arr(tsv, count, vec);
+}
+
+int ts_set_valuei(struct ts_value *tsv, int inum)
+{
+ return ts_set_valuei_arr(tsv, 1, &inum);
+}
+
+int ts_set_valuef_arr(struct ts_value *tsv, int count, const float *arr)
+{
+ int i;
+
+ if(count < 1) return -1;
+ if(count == 1) {
+ if(!(tsv->str = make_floatstr(*arr))) {
+ return -1;
+ }
+
+ tsv->type = TS_NUMBER;
+ tsv->fnum = *arr;
+ tsv->inum = (int)*arr;
+ return 0;
+ }
+
+ /* otherwise it's an array, we need to create the ts_value array, and
+ * the simplified vector
+ */
+ if(!(tsv->vec = malloc(count * sizeof *tsv->vec))) {
+ return -1;
+ }
+ tsv->vec_size = count;
+
+ for(i=0; i<count; i++) {
+ tsv->vec[i] = arr[i];
+ }
+
+ if(!(tsv->array = malloc(count * sizeof *tsv->array))) {
+ free(tsv->vec);
+ }
+ tsv->array_size = count;
+
+ for(i=0; i<count; i++) {
+ ts_init_value(tsv->array + i);
+ ts_set_valuef(tsv->array + i, arr[i]);
+ }
+
+ tsv->type = TS_VECTOR;
+ return 0;
+}
+
+int ts_set_valuefv(struct ts_value *tsv, int count, ...)
+{
+ int res;
+ va_list ap;
+ va_start(ap, count);
+ res = ts_set_valuefv_va(tsv, count, ap);
+ va_end(ap);
+ return res;
+}
+
+int ts_set_valuefv_va(struct ts_value *tsv, int count, va_list ap)
+{
+ int i;
+ float *vec;
+
+ if(count < 1) return -1;
+ if(count == 1) {
+ float num = va_arg(ap, double);
+ ts_set_valuef(tsv, num);
+ return 0;
+ }
+
+ vec = alloca(count * sizeof *vec);
+ for(i=0; i<count; i++) {
+ vec[i] = va_arg(ap, double);
+ }
+ return ts_set_valuef_arr(tsv, count, vec);
+}
+
+int ts_set_valuef(struct ts_value *tsv, float fnum)
+{
+ return ts_set_valuef_arr(tsv, 1, &fnum);
+}
+
+int ts_set_value_arr(struct ts_value *tsv, int count, const struct ts_value *arr)
+{
+ int i, allnum = 1;
+
+ if(count <= 1) return -1;
+
+ if(!(tsv->array = malloc(count * sizeof *tsv->array))) {
+ return -1;
+ }
+ tsv->array_size = count;
+
+ for(i=0; i<count; i++) {
+ if(arr[i].type != TS_NUMBER) {
+ allnum = 0;
+ }
+ if(ts_copy_value(tsv->array + i, (struct ts_value*)arr + i) == -1) {
+ while(--i >= 0) {
+ ts_destroy_value(tsv->array + i);
+ }
+ free(tsv->array);
+ tsv->array = 0;
+ return -1;
+ }
+ }
+
+ if(allnum) {
+ if(!(tsv->vec = malloc(count * sizeof *tsv->vec))) {
+ ts_destroy_value(tsv);
+ return -1;
+ }
+ tsv->type = TS_VECTOR;
+ tsv->vec_size = count;
+
+ for(i=0; i<count; i++) {
+ tsv->vec[i] = tsv->array[i].fnum;
+ }
+ } else {
+ tsv->type = TS_ARRAY;
+ }
+ return 0;
+}
+
+int ts_set_valuev(struct ts_value *tsv, int count, ...)
+{
+ int res;
+ va_list ap;
+ va_start(ap, count);
+ res = ts_set_valuev_va(tsv, count, ap);
+ va_end(ap);
+ return res;
+}
+
+int ts_set_valuev_va(struct ts_value *tsv, int count, va_list ap)
+{
+ int i;
+
+ if(count <= 1) return -1;
+
+ if(!(tsv->array = malloc(count * sizeof *tsv->array))) {
+ return -1;
+ }
+ tsv->array_size = count;
+
+ for(i=0; i<count; i++) {
+ struct ts_value *src = va_arg(ap, struct ts_value*);
+ if(ts_copy_value(tsv->array + i, src) == -1) {
+ while(--i >= 0) {
+ ts_destroy_value(tsv->array + i);
+ }
+ free(tsv->array);
+ tsv->array = 0;
+ return -1;
+ }
+ }
+ return 0;
+}
+
+
+/* ---- ts_attr implementation ---- */
+
+int ts_init_attr(struct ts_attr *attr)
+{
+ memset(attr, 0, sizeof *attr);
+ return ts_init_value(&attr->val);
+}
+
+void ts_destroy_attr(struct ts_attr *attr)
+{
+ free(attr->name);
+ ts_destroy_value(&attr->val);
+}
+
+struct ts_attr *ts_alloc_attr(void)
+{
+ struct ts_attr *attr = malloc(sizeof *attr);
+ if(!attr || ts_init_attr(attr) == -1) {
+ free(attr);
+ return 0;
+ }
+ return attr;
+}
+
+void ts_free_attr(struct ts_attr *attr)
+{
+ ts_destroy_attr(attr);
+ free(attr);
+}
+
+int ts_copy_attr(struct ts_attr *dest, struct ts_attr *src)
+{
+ if(dest == src) return 0;
+
+ if(ts_set_attr_name(dest, src->name) == -1) {
+ return -1;
+ }
+
+ if(ts_copy_value(&dest->val, &src->val) == -1) {
+ ts_destroy_attr(dest);
+ return -1;
+ }
+ return 0;
+}
+
+int ts_set_attr_name(struct ts_attr *attr, const char *name)
+{
+ char *n = malloc(strlen(name) + 1);
+ if(!n) return -1;
+ strcpy(n, name);
+
+ free(attr->name);
+ attr->name = n;
+ return 0;
+}
+
+
+/* ---- ts_node implementation ---- */
+
+int ts_init_node(struct ts_node *node)
+{
+ memset(node, 0, sizeof *node);
+ return 0;
+}
+
+void ts_destroy_node(struct ts_node *node)
+{
+ if(!node) return;
+
+ free(node->name);
+
+ while(node->attr_list) {
+ struct ts_attr *attr = node->attr_list;
+ node->attr_list = node->attr_list->next;
+ ts_free_attr(attr);
+ }
+}
+
+struct ts_node *ts_alloc_node(void)
+{
+ struct ts_node *node = malloc(sizeof *node);
+ if(!node || ts_init_node(node) == -1) {
+ free(node);
+ return 0;
+ }
+ return node;
+}
+
+void ts_free_node(struct ts_node *node)
+{
+ ts_destroy_node(node);
+ free(node);
+}
+
+void ts_free_tree(struct ts_node *tree)
+{
+ if(!tree) return;
+
+ while(tree->child_list) {
+ struct ts_node *child = tree->child_list;
+ tree->child_list = tree->child_list->next;
+ ts_free_tree(child);
+ }
+
+ ts_free_node(tree);
+}
+
+void ts_add_attr(struct ts_node *node, struct ts_attr *attr)
+{
+ attr->next = 0;
+ if(node->attr_list) {
+ node->attr_tail->next = attr;
+ node->attr_tail = attr;
+ } else {
+ node->attr_list = node->attr_tail = attr;
+ }
+ node->attr_count++;
+}
+
+struct ts_attr *ts_get_attr(struct ts_node *node, const char *name)
+{
+ struct ts_attr *attr = node->attr_list;
+ while(attr) {
+ if(strcmp(attr->name, name) == 0) {
+ return attr;
+ }
+ attr = attr->next;
+ }
+ return 0;
+}
+
+const char *ts_get_attr_str(struct ts_node *node, const char *aname, const char *def_val)
+{
+ struct ts_attr *attr = ts_get_attr(node, aname);
+ if(!attr || !attr->val.str) {
+ return def_val;
+ }
+ return attr->val.str;
+}
+
+float ts_get_attr_num(struct ts_node *node, const char *aname, float def_val)
+{
+ struct ts_attr *attr = ts_get_attr(node, aname);
+ if(!attr || attr->val.type != TS_NUMBER) {
+ return def_val;
+ }
+ return attr->val.fnum;
+}
+
+int ts_get_attr_int(struct ts_node *node, const char *aname, int def_val)
+{
+ struct ts_attr *attr = ts_get_attr(node, aname);
+ if(!attr || attr->val.type != TS_NUMBER) {
+ return def_val;
+ }
+ return attr->val.inum;
+}
+
+float *ts_get_attr_vec(struct ts_node *node, const char *aname, float *def_val)
+{
+ struct ts_attr *attr = ts_get_attr(node, aname);
+ if(!attr || !attr->val.vec) {
+ return def_val;
+ }
+ return attr->val.vec;
+}
+
+struct ts_value *ts_get_attr_array(struct ts_node *node, const char *aname, struct ts_value *def_val)
+{
+ struct ts_attr *attr = ts_get_attr(node, aname);
+ if(!attr || !attr->val.array) {
+ return def_val;
+ }
+ return attr->val.array;
+}
+
+void ts_add_child(struct ts_node *node, struct ts_node *child)
+{
+ if(child->parent) {
+ if(child->parent == node) return;
+ ts_remove_child(child->parent, child);
+ }
+ child->parent = node;
+ child->next = 0;
+
+ if(node->child_list) {
+ node->child_tail->next = child;
+ node->child_tail = child;
+ } else {
+ node->child_list = node->child_tail = child;
+ }
+ node->child_count++;
+}
+
+int ts_remove_child(struct ts_node *node, struct ts_node *child)
+{
+ struct ts_node dummy, *iter = &dummy;
+ dummy.next = node->child_list;
+
+ while(iter->next && iter->next != child) {
+ iter = iter->next;
+ }
+ if(!iter->next) {
+ return -1;
+ }
+
+ child->parent = 0;
+
+ iter->next = child->next;
+ if(!iter->next) {
+ node->child_tail = iter;
+ }
+ node->child_list = dummy.next;
+ node->child_count--;
+ assert(node->child_count >= 0);
+ return 0;
+}
+
+struct ts_node *ts_get_child(struct ts_node *node, const char *name)
+{
+ struct ts_node *res = node->child_list;
+ while(res) {
+ if(strcmp(res->name, name) == 0) {
+ return res;
+ }
+ res = res->next;
+ }
+ return 0;
+}
+
+struct ts_node *ts_load(const char *fname)
+{
+ FILE *fp;
+ struct ts_node *root;
+
+ if(!(fp = fopen(fname, "rb"))) {
+ fprintf(stderr, "ts_load: failed to open file: %s: %s\n", fname, strerror(errno));
+ return 0;
+ }
+
+ root = ts_load_file(fp);
+ fclose(fp);
+ return root;
+}
+
+struct ts_node *ts_load_file(FILE *fp)
+{
+ struct ts_io io = {0};
+ io.data = fp;
+ io.read = io_read;
+
+ return ts_load_io(&io);
+}
+
+struct ts_node *ts_load_io(struct ts_io *io)
+{
+ return ts_text_load(io);
+}
+
+int ts_save(struct ts_node *tree, const char *fname)
+{
+ FILE *fp;
+ int res;
+
+ if(!(fp = fopen(fname, "wb"))) {
+ fprintf(stderr, "ts_save: failed to open file: %s: %s\n", fname, strerror(errno));
+ return 0;
+ }
+ res = ts_save_file(tree, fp);
+ fclose(fp);
+ return res;
+}
+
+int ts_save_file(struct ts_node *tree, FILE *fp)
+{
+ struct ts_io io = {0};
+ io.data = fp;
+ io.write = io_write;
+
+ return ts_save_io(tree, &io);
+}
+
+int ts_save_io(struct ts_node *tree, struct ts_io *io)
+{
+ return ts_text_save(tree, io);
+}
+
+static const char *pathtok(const char *path, char *tok)
+{
+ int len;
+ const char *dot = strchr(path, '.');
+ if(!dot) {
+ strcpy(tok, path);
+ return 0;
+ }
+
+ len = dot - path;
+ memcpy(tok, path, len);
+ tok[len] = 0;
+ return dot + 1;
+}
+
+struct ts_attr *ts_lookup(struct ts_node *node, const char *path)
+{
+ char *name = alloca(strlen(path) + 1);
+
+ if(!node) return 0;
+
+ if(!(path = pathtok(path, name)) || strcmp(name, node->name) != 0) {
+ return 0;
+ }
+
+ while((path = pathtok(path, name)) && (node = ts_get_child(node, name)));
+
+ if(path || !node) return 0;
+ return ts_get_attr(node, name);
+}
+
+const char *ts_lookup_str(struct ts_node *root, const char *path, const char *def_val)
+{
+ struct ts_attr *attr = ts_lookup(root, path);
+ if(!attr || !attr->val.str) {
+ return def_val;
+ }
+ return attr->val.str;
+}
+
+float ts_lookup_num(struct ts_node *root, const char *path, float def_val)
+{
+ struct ts_attr *attr = ts_lookup(root, path);
+ if(!attr || attr->val.type != TS_NUMBER) {
+ return def_val;
+ }
+ return attr->val.fnum;
+}
+
+int ts_lookup_int(struct ts_node *root, const char *path, int def_val)
+{
+ struct ts_attr *attr = ts_lookup(root, path);
+ if(!attr || attr->val.type != TS_NUMBER) {
+ return def_val;
+ }
+ return attr->val.inum;
+}
+
+float *ts_lookup_vec(struct ts_node *root, const char *path, float *def_val)
+{
+ struct ts_attr *attr = ts_lookup(root, path);
+ if(!attr || !attr->val.vec) {
+ return def_val;
+ }
+ return attr->val.vec;
+}
+
+struct ts_value *ts_lookup_array(struct ts_node *node, const char *path, struct ts_value *def_val)
+{
+ struct ts_attr *attr = ts_lookup(node, path);
+ if(!attr || !attr->val.array) {
+ return def_val;
+ }
+ return attr->val.array;
+}
+
+static long io_read(void *buf, size_t bytes, void *uptr)
+{
+ size_t sz = fread(buf, 1, bytes, uptr);
+ if(sz < bytes && errno) return -1;
+ return sz;
+}
+
+static long io_write(const void *buf, size_t bytes, void *uptr)
+{
+ size_t sz = fwrite(buf, 1, bytes, uptr);
+ if(sz < bytes && errno) return -1;
+ return sz;
+}
--- /dev/null
+#ifndef TREESTORE_H_
+#define TREESTORE_H_
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#ifdef __cplusplus
+#define TS_DEFVAL(x) =(x)
+extern "C" {
+#else
+#define TS_DEFVAL(x)
+#endif
+
+/** set of user-supplied I/O functions, for ts_load_io/ts_save_io */
+struct ts_io {
+ void *data;
+
+ long (*read)(void *buf, size_t bytes, void *uptr);
+ long (*write)(const void *buf, size_t bytes, void *uptr);
+};
+
+enum ts_value_type { TS_STRING, TS_NUMBER, TS_VECTOR, TS_ARRAY };
+
+/** treestore node attribute value */
+struct ts_value {
+ enum ts_value_type type;
+
+ char *str; /**< string values will have this set */
+ int inum; /**< numeric values will have this set */
+ float fnum; /**< numeric values will have this set */
+
+ /** vector values (arrays containing ONLY numbers) will have this set */
+ float *vec; /**< elements of the vector */
+ int vec_size; /**< size of the vector (in elements), same as array_size */
+
+ /** array values (including vectors) will have this set */
+ struct ts_value *array; /**< elements of the array */
+ int array_size; /**< size of the array (in elements) */
+};
+
+int ts_init_value(struct ts_value *tsv);
+void ts_destroy_value(struct ts_value *tsv);
+
+struct ts_value *ts_alloc_value(void); /**< also calls ts_init_value */
+void ts_free_value(struct ts_value *tsv); /**< also calls ts_destroy_value */
+
+/** perform a deep-copy of a ts_value */
+int ts_copy_value(struct ts_value *dest, struct ts_value *src);
+
+/** set a ts_value as a string */
+int ts_set_value_str(struct ts_value *tsv, const char *str);
+
+/** set a ts_value from a list of integers */
+int ts_set_valuei_arr(struct ts_value *tsv, int count, const int *arr);
+int ts_set_valueiv(struct ts_value *tsv, int count, ...);
+int ts_set_valueiv_va(struct ts_value *tsv, int count, va_list ap);
+int ts_set_valuei(struct ts_value *tsv, int inum); /**< equiv: ts_set_valueiv(val, 1, inum) */
+
+/** set a ts_value from a list of floats */
+int ts_set_valuef_arr(struct ts_value *tsv, int count, const float *arr);
+int ts_set_valuefv(struct ts_value *tsv, int count, ...);
+int ts_set_valuefv_va(struct ts_value *tsv, int count, va_list ap);
+int ts_set_valuef(struct ts_value *tsv, float fnum); /**< equiv: ts_set_valuefv(val, 1, fnum) */
+
+/** set a ts_value from a list of ts_value pointers. they are deep-copied as per ts_copy_value */
+int ts_set_value_arr(struct ts_value *tsv, int count, const struct ts_value *arr);
+int ts_set_valuev(struct ts_value *tsv, int count, ...);
+int ts_set_valuev_va(struct ts_value *tsv, int count, va_list ap);
+
+
+/** treestore node attribute */
+struct ts_attr {
+ char *name;
+ struct ts_value val;
+
+ struct ts_attr *next;
+};
+
+int ts_init_attr(struct ts_attr *attr);
+void ts_destroy_attr(struct ts_attr *attr);
+
+struct ts_attr *ts_alloc_attr(void); /**< also calls ts_init_attr */
+void ts_free_attr(struct ts_attr *attr); /**< also calls ts_destroy_attr */
+
+/** perform a deep-copy of a ts_attr */
+int ts_copy_attr(struct ts_attr *dest, struct ts_attr *src);
+
+int ts_set_attr_name(struct ts_attr *attr, const char *name);
+
+
+
+/** treestore node */
+struct ts_node {
+ char *name;
+
+ int attr_count;
+ struct ts_attr *attr_list, *attr_tail;
+
+ int child_count;
+ struct ts_node *child_list, *child_tail;
+ struct ts_node *parent;
+
+ struct ts_node *next; /* next sibling */
+};
+
+int ts_init_node(struct ts_node *node);
+void ts_destroy_node(struct ts_node *node);
+
+struct ts_node *ts_alloc_node(void); /**< also calls ts_init_node */
+void ts_free_node(struct ts_node *n); /**< also calls ts_destroy_node */
+
+/** recursively destroy all the nodes of the tree */
+void ts_free_tree(struct ts_node *tree);
+
+void ts_add_attr(struct ts_node *node, struct ts_attr *attr);
+struct ts_attr *ts_get_attr(struct ts_node *node, const char *name);
+
+const char *ts_get_attr_str(struct ts_node *node, const char *aname,
+ const char *def_val TS_DEFVAL(0));
+float ts_get_attr_num(struct ts_node *node, const char *aname,
+ float def_val TS_DEFVAL(0.0f));
+int ts_get_attr_int(struct ts_node *node, const char *aname,
+ int def_val TS_DEFVAL(0.0f));
+float *ts_get_attr_vec(struct ts_node *node, const char *aname,
+ float *def_val TS_DEFVAL(0));
+struct ts_value *ts_get_attr_array(struct ts_node *node, const char *aname,
+ struct ts_value *def_val TS_DEFVAL(0));
+
+
+void ts_add_child(struct ts_node *node, struct ts_node *child);
+int ts_remove_child(struct ts_node *node, struct ts_node *child);
+struct ts_node *ts_get_child(struct ts_node *node, const char *name);
+
+/* load/save by opening the specified file */
+struct ts_node *ts_load(const char *fname);
+int ts_save(struct ts_node *tree, const char *fname);
+
+/* load/save using the supplied FILE pointer */
+struct ts_node *ts_load_file(FILE *fp);
+int ts_save_file(struct ts_node *tree, FILE *fp);
+
+/* load/save using custom I/O functions */
+struct ts_node *ts_load_io(struct ts_io *io);
+int ts_save_io(struct ts_node *tree, struct ts_io *io);
+
+
+struct ts_attr *ts_lookup(struct ts_node *root, const char *path);
+const char *ts_lookup_str(struct ts_node *root, const char *path,
+ const char *def_val TS_DEFVAL(0));
+float ts_lookup_num(struct ts_node *root, const char *path,
+ float def_val TS_DEFVAL(0.0f));
+int ts_lookup_int(struct ts_node *root, const char *path,
+ int def_val TS_DEFVAL(0));
+float *ts_lookup_vec(struct ts_node *root, const char *path,
+ float *def_val TS_DEFVAL(0));
+struct ts_value *ts_lookup_array(struct ts_node *root, const char *path,
+ struct ts_value *def_val TS_DEFVAL(0));
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* TREESTORE_H_ */
#include <float.h>
#include "geom.h"
+void free_bvh_tree(struct bvhnode *tree)
+{
+ struct bvhnode *node, *tmp;
+
+ free(tree->faces);
+
+ node = tree->sub;
+ while(node) {
+ tmp = node;
+ node = node->next;
+ free_bvh_tree(tmp);
+ }
+
+ free(tree);
+}
+
int ray_triangle(cgm_ray *ray, struct triangle *tri, float tmax, struct rayhit *hit)
{
float t, ndotdir;
#define SLABCHECK(dim) \
do { \
- min = box->p.dim - box->r.dim; \
- max = box->p.dim + box->r.dim; \
invdir = 1.0f / ray->dir.dim; \
- t0 = (min - ray->origin.dim) * invdir; \
- t1 = (max - ray->origin.dim) * invdir; \
+ t0 = (box->vmin.dim - ray->origin.dim) * invdir; \
+ t1 = (box->vmax.dim - ray->origin.dim) * invdir; \
if(invdir < 0.0f) { \
tmp = t0; \
t0 = t1; \
int ray_aabox_any(cgm_ray *ray, struct aabox *box, float tmax)
{
float invdir, t0, t1, tmp;
- float min, max, tmin = 0.0f;
+ float tmin = 0.0f;
SLABCHECK(x);
SLABCHECK(y);
if(!hit) {
for(i=0; i<bn->num_faces; i++) {
- if(ray_triangle(ray, bn->faces[i], tmax, 0)) {
+ if(ray_triangle(ray, bn->faces + i, tmax, 0)) {
return 1;
}
}
hit0.t = FLT_MAX;
for(i=0; i<bn->num_faces; i++) {
- if(ray_triangle(ray, bn->faces[i], tmax, hit) && hit->t < hit0.t) {
+ if(ray_triangle(ray, bn->faces + i, tmax, hit) && hit->t < hit0.t) {
hit0 = *hit;
res = 1;
}
};
struct aabox {
- cgm_vec3 p, r;
+ cgm_vec3 vmin, vmax;
};
struct bvhnode {
struct aabox aabb;
- struct triangle **faces;
- int num_faces, max_faces;
+ struct triangle *faces;
+ int num_faces;
+ struct bvhnode *next;
struct bvhnode *sub;
int num_sub;
};
struct material *mtl;
};
+void free_bvh_tree(struct bvhnode *tree);
+
int ray_triangle(cgm_ray *ray, struct triangle *tri, float tmax, struct rayhit *hit);
int ray_aabox_any(cgm_ray *ray, struct aabox *box, float tmax);
int ray_bvhnode(cgm_ray *ray, struct bvhnode *bn, float tmax, struct rayhit *hit);
#include <stdio.h>
+#include <stdlib.h>
+#include <float.h>
#include "level.h"
+#include "treestore.h"
+#include "mesh.h"
+static struct material *add_material(struct level *lvl, struct material *mtl);
+static int append_polygons(struct bvhnode *bnode, struct triangle *faces, int num_faces, struct material *mtl);
int load_level(struct level *lvl, const char *fname)
{
- return -1;
+ char *dirname, *ptr;
+ char path[256];
+ struct ts_node *root, *node;
+ struct scenefile scn;
+ struct mesh *mesh;
+ struct material *mtl;
+
+ memset(lvl, 0, sizeof *lvl);
+ if(!(lvl->st_root = calloc(1, sizeof *lvl->st_root)) ||
+ !(lvl->dyn_root = calloc(1, sizeof *lvl->dyn_root))) {
+ free(lvl->st_root);
+ fprintf(stderr, "load_level: failed to allocate bvh root nodes\n");
+ return -1;
+ }
+
+ cgm_vcons(&lvl->st_root->aabb.vmin, FLT_MAX, FLT_MAX, FLT_MAX);
+ cgm_vcons(&lvl->st_root->aabb.vmax, -FLT_MAX, -FLT_MAX, -FLT_MAX);
+ lvl->dyn_root->aabb = lvl->st_root->aabb;
+
+ dirname = alloca(strlen(fname) + 1);
+ strcpy(dirname, fname);
+ if((ptr = strrchr(dirname, '/'))) {
+ ptr[1] = 0;
+ } else {
+ *dirname = 0;
+ }
+
+ if(!(root = ts_load(fname))) {
+ fprintf(stderr, "load_level: failed to load: %s\n", fname);
+ return -1;
+ }
+ if(strcmp(root->name, "level") != 0) {
+ fprintf(stderr, "load_level: invalid level file %s, root is not \"level\"\n", fname);
+ ts_free_tree(root);
+ return -1;
+ }
+
+ node = root->child_list;
+ while(node) {
+ if(strcmp(node->name, "scene") == 0) {
+ if(!(fname = ts_get_attr_str(node, "file", 0))) {
+ fprintf(stderr, "load_level: ignoring \"scene\" without a \"file\" attribute\n");
+ goto cont;
+ }
+ snprintf(path, sizeof path, "%s%s", dirname, fname);
+ printf("loading scene file: %s\n", path);
+
+ if(load_scenefile(&scn, path) == -1) {
+ goto cont;
+ }
+ mesh = scn.meshlist;
+ while(mesh) {
+ mtl = add_material(lvl, &mesh->mtl);
+ append_polygons(lvl->st_root, mesh->faces, mesh->num_faces, mtl);
+ mesh = mesh->next;
+ }
+
+ destroy_scenefile(&scn);
+ }
+cont: node = node->next;
+ }
+
+ ts_free_tree(root);
+ return 0;
}
+void destroy_level(struct level *lvl)
+{
+ free_bvh_tree(lvl->st_root);
+ free_bvh_tree(lvl->dyn_root);
+ free(lvl->mtls);
+}
+
+
int ray_level(cgm_ray *ray, struct level *lvl, float tmax, struct rayhit *hit)
{
return 0;
}
+
+static void draw_level_rec(struct bvhnode *bn)
+{
+ int i, j;
+ struct triangle *tri;
+ struct material *curmtl;
+ float color[4] = {0, 0, 0, 1};
+
+ if(bn->faces) {
+ tri = bn->faces;
+ curmtl = tri->mtl;
+
+ glBegin(GL_TRIANGLES);
+ for(i=0; i<bn->num_faces; i++) {
+ if(tri->mtl != curmtl) {
+ glEnd();
+ color[0] = tri->mtl->color.x;
+ color[1] = tri->mtl->color.y;
+ color[2] = tri->mtl->color.z;
+ glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color);
+ curmtl = tri->mtl;
+ glBegin(GL_TRIANGLES);
+ }
+
+ for(j=0; j<3; j++) {
+ glNormal3fv(&tri->v[j].norm.x);
+ glTexCoord2fv(&tri->v[j].tex.x);
+ glVertex3fv(&tri->v[j].pos.x);
+ }
+ tri++;
+ }
+ glEnd();
+ }
+
+ bn = bn->sub;
+ while(bn) {
+ draw_level_rec(bn);
+ bn = bn->next;
+ }
+}
+
+void draw_level(struct level *lvl)
+{
+ draw_level_rec(lvl->st_root);
+ draw_level_rec(lvl->dyn_root);
+}
+
+static struct material *add_material(struct level *lvl, struct material *mtl)
+{
+ int i, newsz;
+ struct material *tmp;
+
+ for(i=0; i<lvl->num_mtls; i++) {
+ if(memcmp(lvl->mtls + i, mtl, sizeof *mtl) == 0) {
+ return lvl->mtls + i;
+ }
+ }
+
+ if(lvl->num_mtls >= lvl->max_mtls) {
+ newsz = lvl->max_mtls ? lvl->max_mtls * 2 : 16;
+ if(!(tmp = realloc(lvl->mtls, newsz * sizeof *lvl->mtls))) {
+ fprintf(stderr, "add_material: failed to resize materials array to %d\n", newsz);
+ return 0;
+ }
+ lvl->mtls = tmp;
+ lvl->max_mtls = newsz;
+ }
+ lvl->mtls[lvl->num_mtls] = *mtl;
+
+ return lvl->mtls + lvl->num_mtls++;
+}
+
+static int append_polygons(struct bvhnode *bnode, struct triangle *faces, int num_faces, struct material *mtl)
+{
+ int i, j, newsz;
+ struct triangle *tri;
+
+ newsz = bnode->num_faces + num_faces;
+ if(!(tri = realloc(bnode->faces, newsz * sizeof *bnode->faces))) {
+ fprintf(stderr, "append_polygons: failed to resize faces array to %d\n", newsz);
+ return -1;
+ }
+ bnode->faces = tri;
+ tri += bnode->num_faces;
+ bnode->num_faces = newsz;
+
+ for(i=0; i<num_faces; i++) {
+ *tri = *faces++;
+ tri->mtl = mtl;
+
+ for(j=0; j<3; j++) {
+ cgm_vec3 *p = &tri->v[j].pos;
+ if(p->x < bnode->aabb.vmin.x) bnode->aabb.vmin.x = p->x;
+ if(p->x > bnode->aabb.vmax.x) bnode->aabb.vmax.x = p->x;
+ if(p->y < bnode->aabb.vmin.y) bnode->aabb.vmin.y = p->y;
+ if(p->y > bnode->aabb.vmax.y) bnode->aabb.vmax.y = p->y;
+ if(p->z < bnode->aabb.vmin.z) bnode->aabb.vmin.z = p->z;
+ if(p->z > bnode->aabb.vmax.z) bnode->aabb.vmax.z = p->z;
+ }
+ tri++;
+ }
+ return 0;
+}
struct bvhnode *dyn_root;
struct material *mtls;
+ int num_mtls, max_mtls;
};
int load_level(struct level *lvl, const char *fname);
+void destroy_level(struct level *lvl);
int ray_level(cgm_ray *ray, struct level *lvl, float tmax, struct rayhit *hit);
+void draw_level(struct level *lvl);
+
#endif /* LEVEL_H_ */
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
-#include <GL/glut.h>
#include <cgmath/cgmath.h>
-#include "mesh.h"
+#include "miniglut.h"
+#include "level.h"
enum {
KEY_F1 = GLUT_KEY_F1 | 0x100,
{' ', 0}
};
-static struct scenefile scn;
+static struct level lvl;
int main(int argc, char **argv)
{
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
- if(load_scenefile(&scn, "data/testlvl.obj") == -1) {
+ if(load_level(&lvl, "data/test.lvl") == -1) {
return -1;
}
static void cleanup(void)
{
- destroy_scenefile(&scn);
+ destroy_level(&lvl);
}
#define WALK_SPEED 3.0f
static void display(void)
{
- struct mesh *mesh;
-
update();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(pxform);
- mesh = scn.meshlist;
- while(mesh) {
- float col[4];
- col[0] = mesh->mtl.color.x;
- col[1] = mesh->mtl.color.y;
- col[2] = mesh->mtl.color.z;
- col[3] = 1.0f;
- glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, col);
-
- draw_mesh(mesh);
- mesh = mesh->next;
- }
+ draw_level(&lvl);
glutSwapBuffers();
assert(glGetError() == GL_NO_ERROR);
static void reshape(int x, int y)
{
+ float proj[16];
+
+ cgm_mperspective(proj, cgm_deg_to_rad(50.0f), (float)x / (float)y, 0.5, 500.0);
+
glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- gluPerspective(50.0, (float)x / (float)y, 0.5, 500.0);
+ glLoadMatrixf(proj);
}
static void keyb(int key, int press)
scn->meshlist = mesh;
scn->num_meshes++;
- printf("added mesh with mtl: %s\n", curmtl.name);
-
if(!(mesh = calloc(1, sizeof *mesh))) {
fprintf(stderr, "failed to allocate mesh\n");
goto fail;