diff --git a/.directory b/.directory new file mode 100644 index 0000000..cbfbfa2 --- /dev/null +++ b/.directory @@ -0,0 +1,3 @@ +[Dolphin] +Timestamp=2013,10,11,0,43,45 +Version=3 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ee01a57 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +PROJ1_NIX/565raytracer +*.o +cscope.out +*.swp +tags diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/PERFORMANCE_COMPARISON.txt b/PERFORMANCE_COMPARISON.txt new file mode 100644 index 0000000..b8d220e --- /dev/null +++ b/PERFORMANCE_COMPARISON.txt @@ -0,0 +1,15 @@ +For my performance comparison experiment, I tweaked the tile size. Here are my results: + +Tile Size 1: 0.6 fps +Tile Size 2: 0.6 fps +Tile Size 3: 8.55 fps +Tile Size 8: 19.96 fps +Tile Size 16: 19.96 fps + +See the graph on performance_experiment.png. + +It makes sense that performance rises as we increase the tile size and assign more threads +to each block. However, as the tile size gets larger, we see the performance plateau, probably +because the GPU isn't capable of running that many threads at the same time (we run out +of registers). A tile size of 32 or above doesn't work at all! + diff --git a/PROJ1_MAC/makefile b/PROJ1_MAC/makefile index 85aa34c..fbf32b3 100755 --- a/PROJ1_MAC/makefile +++ b/PROJ1_MAC/makefile @@ -23,4 +23,4 @@ clean: rm bin/565raytracer rm *.o -.PHONY : bin/565raytracer \ No newline at end of file +.PHONY : bin/565raytracer diff --git a/PROJ1_NIX/makefile b/PROJ1_NIX/makefile index 543b0e7..ef4bf71 100755 --- a/PROJ1_NIX/makefile +++ b/PROJ1_NIX/makefile @@ -1,15 +1,18 @@ #All cuda paths are for v5.0+ -NVCC = nvcc -m64 -CC = gcc -m64 +NVCC = nvcc -m64 -arch sm_21 +CC = gcc -m64 CPPC = g++ -m64 CUDA_FLAGS = -I/usr/local/cuda/samples/common/inc -I/usr/local/cuda/include -LFLAGS = -lglut -lGL -lGLEW +LFLAGS = -lglut -lGL -lGLEW all: 565raytracer +#raytraceHelpers.o: ../src/raytraceHelpers.cu + #$(NVCC) $(CUDA_FLAGS) -c ../src/raytraceHelpers.cu + raytraceKernel.o: ../src/raytraceKernel.cu $(NVCC) $(CUDA_FLAGS) -c ../src/raytraceKernel.cu @@ -34,7 +37,7 @@ stb_image_write.o: ../src/stb_image/stb_image_write.c main.o: ../src/main.cpp $(CPPC) $(CUDA_FLAGS) ../src/main.cpp -c -565raytracer: main.o raytraceKernel.o glslUtility.o utilities.o image.o scene.o stb_image_write.o stb_image.o +565raytracer: main.o raytraceKernel.o glslUtility.o utilities.o image.o scene.o stb_image_write.o stb_image.o $(NVCC) $(LFLAGS) main.o raytraceKernel.o glslUtility.o utilities.o image.o scene.o stb_image_write.o stb_image.o -o 565raytracer clean: diff --git a/PROJ1_NIX/sampleScene.txt b/PROJ1_NIX/sampleScene.txt new file mode 100755 index 0000000..dd835fb --- /dev/null +++ b/PROJ1_NIX/sampleScene.txt @@ -0,0 +1,221 @@ +MATERIAL 0 //white diffuse +RGB 0.9 0.9 0.9 +SPECEX 1 +SPECRGB 1 1 1 +REFL 0 +REFR 0 +REFRIOR 0 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 0 + +MATERIAL 1 //red diffuse +RGB .63 .06 .04 +SPECEX 1 +SPECRGB 1 1 1 +REFL 0 +REFR 0 +REFRIOR 0 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 0 + +MATERIAL 2 //green diffuse +RGB .15 .48 .09 +SPECEX 1 +SPECRGB 1 1 1 +REFL 0 +REFR 0 +REFRIOR 0 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 0 + +MATERIAL 3 //red glossy +RGB .63 .06 .04 +SPECEX 100 +SPECRGB 1 1 1 +REFL 0 +REFR 0 +REFRIOR 2 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 0 + +MATERIAL 4 //white glossy +RGB 0.9 0.9 0.9 +SPECEX 100 +SPECRGB 1 1 1 +REFL 0 +REFR 0 +REFRIOR 2 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 0 + +MATERIAL 5 //moving +RGB 0.15 0.09 0.48 +SPECEX 1 +SPECRGB 1 1 1 +REFL 0 +REFR 1 +REFRIOR 2.2 +SCATTER 0 +ABSCOEFF 2 2 2 +RSCTCOEFF 13 +EMITTANCE 0 + +MATERIAL 6 //green glossy +RGB .15 .48 .09 +SPECEX 100 +SPECRGB 1 1 1 +REFL 0 +REFR 0 +REFRIOR 2.6 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 0 + +MATERIAL 7 //light +RGB 1 1 1 +SPECEX 1 +SPECRGB 0 0 0 +REFL 0 +REFR 0 +REFRIOR 0 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 1 + +MATERIAL 8 //light +RGB 1 1 1 +SPECEX 1 +SPECRGB 0 0 0 +REFL 0 +REFR 0 +REFRIOR 0 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 2 + +MATERIAL 9 //mirror +RGB .43 .43 .47 +SPECEX 100 +SPECRGB 1 1 1 +REFL 1 +REFR 0 +REFRIOR 2 +SCATTER 0 +ABSCOEFF 0 0 0 +RSCTCOEFF 0 +EMITTANCE 0 + +MATERIAL 10 //moving +RGB 0.15 0.09 0.48 +SPECEX 1 +SPECRGB 1 1 1 +REFL 0 +REFR 1 +REFRIOR 2.2 +SCATTER 0 +ABSCOEFF 2 2 2 +RSCTCOEFF 13 +EMITTANCE 0 + +CAMERA +RES 800 800 +FOVY 45 +ITERATIONS 5000 +FILE test.bmp +frame 0 +EYE 0 4.5 4.9 +VIEW 0 0 -1 +UP 0 1 0 + +OBJECT 0 +cube +material 0 +frame 0 +TRANS 0 0 0 +ROTAT 0 0 90 +SCALE .01 10 10 + +OBJECT 1 +cube +material 0 +frame 0 +TRANS 0 5 -5 +ROTAT 0 90 0 +SCALE .01 10 10 + +OBJECT 2 +cube +material 0 +frame 0 +TRANS 0 10 0 +ROTAT 0 0 90 +SCALE .01 10 10 + +OBJECT 3 +cube +material 1 +frame 0 +TRANS -5 5 0 +ROTAT 0 0 0 +SCALE .01 10 10 + +OBJECT 4 +cube +material 2 +frame 0 +TRANS 5 5 0 +ROTAT 0 0 0 +SCALE .01 10 10 + +OBJECT 5 +sphere +material 9 +frame 0 +TRANS 0 2 0 +ROTAT 0 180 0 +SCALE 3 3 3 + +OBJECT 6 +sphere +material 0 +frame 0 +TRANS 2 5 2 +ROTAT 0 180 0 +SCALE 2.5 2.5 2.5 + +OBJECT 7 +sphere +material 0 +frame 0 +TRANS 0 5 -2 +ROTAT 0 180 0 +SCALE 3 3 3 + +OBJECT 8 +cube +material 8 +frame 0 +TRANS 0 10 0 +ROTAT 0 0 90 +SCALE .3 10 10 + +OBJECT 9 +cube +material 0 +frame 0 +TRANS 0 5 5 +ROTAT 0 -90 0 +SCALE .01 10 10 diff --git a/scenes/sampleScene.txt b/PROJ1_NIX/sphereScene.txt old mode 100755 new mode 100644 similarity index 77% rename from scenes/sampleScene.txt rename to PROJ1_NIX/sphereScene.txt index 877706f..0b05039 --- a/scenes/sampleScene.txt +++ b/PROJ1_NIX/sphereScene.txt @@ -1,3 +1,5 @@ +scene + MATERIAL 0 //white diffuse RGB 1 1 1 SPECEX 0 @@ -117,46 +119,6 @@ VIEW 0 0 -1 UP 0 1 0 OBJECT 0 -cube -material 0 -frame 0 -TRANS 0 0 0 -ROTAT 0 0 90 -SCALE .01 10 10 - -OBJECT 1 -cube -material 0 -frame 0 -TRANS 0 5 -5 -ROTAT 0 90 0 -SCALE .01 10 10 - -OBJECT 2 -cube -material 0 -frame 0 -TRANS 0 10 0 -ROTAT 0 0 90 -SCALE .01 10 10 - -OBJECT 3 -cube -material 1 -frame 0 -TRANS -5 5 0 -ROTAT 0 0 0 -SCALE .01 10 10 - -OBJECT 4 -cube -material 2 -frame 0 -TRANS 5 5 0 -ROTAT 0 0 0 -SCALE .01 10 10 - -OBJECT 5 sphere material 4 frame 0 @@ -164,7 +126,7 @@ TRANS 0 2 0 ROTAT 0 180 0 SCALE 3 3 3 -OBJECT 6 +OBJECT 1 sphere material 3 frame 0 @@ -172,19 +134,10 @@ TRANS 2 5 2 ROTAT 0 180 0 SCALE 2.5 2.5 2.5 -OBJECT 7 +OBJECT 2 sphere material 6 frame 0 TRANS -2 5 -2 ROTAT 0 180 0 SCALE 3 3 3 - - -OBJECT 8 -cube -material 8 -frame 0 -TRANS 0 10 0 -ROTAT 0 0 90 -SCALE .3 3 3 \ No newline at end of file diff --git a/PROJ1_NIX/test.0.bmp b/PROJ1_NIX/test.0.bmp new file mode 100644 index 0000000..b11e638 Binary files /dev/null and b/PROJ1_NIX/test.0.bmp differ diff --git a/PROJ1_NIX/test_output b/PROJ1_NIX/test_output new file mode 100644 index 0000000..1128f6d --- /dev/null +++ b/PROJ1_NIX/test_output @@ -0,0 +1,76 @@ +Reading scene from sampleScene.txt ... + +Loading Material 0... + +Loading Material 1... + +Loading Material 2... + +Loading Material 3... + +Loading Material 4... + +Loading Material 5... + +Loading Material 6... + +Loading Material 7... + +Loading Material 8... + +Loading Material 9... + +Loading Camera ... +Loaded 1 frames for camera! + +Loading Object 0... +Creating new cube... +Connecting Object 0 to Material 0... +Loaded 1 frames for Object 0! + +Loading Object 1... +Creating new cube... +Connecting Object 1 to Material 0... +Loaded 1 frames for Object 1! + +Loading Object 2... +Creating new cube... +Connecting Object 2 to Material 0... +Loaded 1 frames for Object 2! + +Loading Object 3... +Creating new cube... +Connecting Object 3 to Material 1... +Loaded 1 frames for Object 3! + +Loading Object 4... +Creating new cube... +Connecting Object 4 to Material 2... +Loaded 1 frames for Object 4! + +Loading Object 5... +Creating new sphere... +Connecting Object 5 to Material 4... +Loaded 1 frames for Object 5! + +Loading Object 6... +Creating new sphere... +Connecting Object 6 to Material 0... +Loaded 1 frames for Object 6! + +Loading Object 7... +Creating new sphere... +Connecting Object 7 to Material 0... +Loaded 1 frames for Object 7! + +Loading Object 8... +Creating new cube... +Connecting Object 8 to Material 8... +Loaded 1 frames for Object 8! + +Loading Object 9... +Creating new cube... +Connecting Object 9 to Material 0... +Loaded 1 frames for Object 9! + +Ray Buffer A points to something! diff --git a/README.md b/README.md index 6bef2b9..0262d6c 100644 --- a/README.md +++ b/README.md @@ -1,333 +1,46 @@ -------------------------------------------------------------------------------- -CIS565: Project 1: CUDA Raytracer -------------------------------------------------------------------------------- -Fall 2013 -------------------------------------------------------------------------------- -Due Thursday, 09/19/2013 -------------------------------------------------------------------------------- +CUDA Pathtracer (AKA NaTracer) +================= +![alt tag](https://raw.github.com/nmarshak1337/CUDA-NaTracer/master/renders/blur_1000.png) -------------------------------------------------------------------------------- -NOTE: -------------------------------------------------------------------------------- -This project requires an NVIDIA graphics card with CUDA capability! Any card -after the Geforce 8xxx series will work. If you do not have an NVIDIA graphics -card in the machine you are working on, feel free to use any machine in the SIG -Lab or in Moore100 labs. All machines in the SIG Lab and Moore100 are equipped -with CUDA capable NVIDIA graphics cards. If this too proves to be a problem, -please contact Patrick or Liam as soon as possible. +[See a video here, demonstrating interactivity.](http://youtu.be/jGMDtnSyyjo) +*************** +Features antialiasing with jittering. By jittering our samples in each pixel, we get antialiasing by taking one sample per pixel in the pathtracer. Below is the result with jittering one sample per pixel: -------------------------------------------------------------------------------- -INTRODUCTION: -------------------------------------------------------------------------------- -In this project, you will implement a CUDA based raytracer capable of -generating raytraced rendered images extremely quickly. For those of you who -have taken CIS460/560, building a raytracer should not be anything new to you -from a conceptual point of you. For those of you that have not taken -CIS460/560, raytracing is a technique for generating images by tracing rays of -light through pixels in an image plane out into a scene and following the way -the rays of light bounce and interact with objects in the scene. More -information can be found here: -http://en.wikipedia.org/wiki/Ray_tracing_(graphics). +![alt tag](https://raw.github.com/nmarshak1337/CUDA-NaTracer/master/renders/WITH_jittering_reflect_no_jaggies.png) -The ultimate purpose of this project is to serve as the foundation for your -next project: a full CUDA based global illumination pathtracer. Raytracing can -be thought of as a way to generate an isolated version of the direct light -contribution in a global illumination scenario. +Below is without jittering: -Since in this class we are concerned with working in generating actual images -and less so with mundane tasks like file I/O, this project includes basecode -for loading a scene description file format, described below, and various other -things that generally make up the render "harness" that takes care of -everything up to the rendering itself. The core renderer is left for you to -implement. Finally, note that while this basecode is meant to serve as a -strong starting point for a CUDA raytracer, you are not required to use this -basecode if you wish, and you may also change any part of the basecode -specification as you please, so long as the final rendered result is correct. +![alt tag](https://raw.github.com/nmarshak1337/CUDA-NaTracer/master/renders/without_jittering_210_iterations.png) +DIY Scan, Reduction, Stream Compaction +================= +I implemented the "Stream Compaction" algorithm (similar to the one in [Thrust](http://thrust.github.io/doc/group__stream__compaction.html)), implemented from scratch using my own Parallel Scan and Reduction algorithms. -------------------------------------------------------------------------------- -CONTENTS: -------------------------------------------------------------------------------- -The Project1 root directory contains the following subdirectories: - -* src/ contains the source code for the project. Both the Windows Visual Studio - solution and the OSX and Linux makefiles reference this folder for all - source; the base source code compiles on Linux, OSX and Windows without - modification. -* scenes/ contains an example scene description file. -* renders/ contains an example render of the given example scene file. -* PROJ1_WIN/ contains a Windows Visual Studio 2010 project and all dependencies - needed for building and running on Windows 7. -* PROJ1_OSX/ contains a OSX makefile, run script, and all dependencies needed - for building and running on Mac OSX 10.8. -* PROJ1_NIX/ contains a Linux makefile for building and running on Ubuntu - 12.04 LTS. Note that you will need to set the following environment - variables: - - - PATH=$PATH:/usr/local/cuda-5.5/bin - - LD_LIBRARY_PATH=/usr/local/cuda-5.5/lib64:/lib +Stream compaction allows us (in parallel) to take an array, select eligible members, and put them into a smaller array. This is useful when pathtracing, since we start with a large array of rays that gets smaller and smaller. See the following picture from the profiler, and notice how the time spent on the call to raytraceRays gets smaller and smaller: - you may set these any way that you like. I added them to my .bashrc - +![alt tag](https://raw.github.com/nmarshak1337/CUDA-NaTracer/master/renders/raytrace_compaction.png) -The Windows and OSX versions of the project build and run exactly the same way -as in Project0. +This is only possible if stream compaction is used to cull rays that have become "useless" in the path tracing procedure. -------------------------------------------------------------------------------- -REQUIREMENTS: -------------------------------------------------------------------------------- -In this project, you are given code for: +Notes on Linux Development +================= +Debugging on Linux with a single GPU is extremely challenging since this project uses CUDA-GL interop requires X to run while CUDA is being debugged. I spent an entire day trying to get the debugger to work, before coming to the conclusion that the best way to debug is probably to port to Windows and use Parallel Nsight (which supports single-GPU debugging on Windows). While I was not successful in getting the debugger to work, I did [post some notes on my blog](http://lightspeedbanana.blogspot.com/2013/10/debugging-cuda-gl-interop-on-linux-with.html), that should be of use when I debug CUDA applications on Linux in the future. -* Loading, reading, and storing the TAKUAscene scene description format -* Example functions that can run on both the CPU and GPU for generating random - numbers, spherical intersection testing, and surface point sampling on cubes -* A class for handling image operations and saving images -* Working code for CUDA-GL interop +Notes on Performance +================= +My own stream compaction procedure can be made substantially faster by using the Reduce function and Scan function from Thrust (see [Reductions](http://docs.thrust.googlecode.com/hg/group__reductions.html) and [Prefix Sums](http://docs.thrust.googlecode.com/hg/group__prefixsums.html)), respectively. -You will need to implement the following features: +Using Thrust, the time between the first call to RaytraceRay and the second call is 0.005 seconds, according to the NVIDIA Visual Profiler, whereas the time taken with my own reduce and scan functions is 0.29 seconds. Clearly +there is work to be done on my end. One reason why my own stream compaction is so much slower is because I am +using a naive exclusive scan, as opposed to a more optimized version. See http://http.developer.nvidia.com/GPUGems3/gpugems3_ch39.html for information on how to optimize an exclusive scan. -* Raycasting from a camera into a scene through a pixel grid -* Phong lighting for one point light source -* Diffuse lambertian surfaces -* Raytraced shadows -* Cube intersection testing -* Sphere surface point sampling - -You are also required to implement at least 2 of the following features: - -* Specular reflection -* Soft shadows and area lights -* Texture mapping -* Bump mapping -* Depth of field -* Supersampled antialiasing -* Refraction, i.e. glass -* OBJ Mesh loading and renderin -* Interactive camera - -------------------------------------------------------------------------------- -BASE CODE TOUR: -------------------------------------------------------------------------------- -You will be working in three files: raytraceKernel.cu, intersections.h, and -interactions.h. Within these files, areas that you need to complete are marked -with a TODO comment. Areas that are useful to and serve as hints for optional -features are marked with TODO (Optional). Functions that are useful for -reference are marked with the comment LOOK. - -* raytraceKernel.cu contains the core raytracing CUDA kernel. You will need to - complete: - * cudaRaytraceCore() handles kernel launches and memory management; this - function already contains example code for launching kernels, - transferring geometry and cameras from the host to the device, and transferring - image buffers from the host to the device and back. You will have to complete - this function to support passing materials and lights to CUDA. - * raycastFromCameraKernel() is a function that you need to implement. This - function once correctly implemented should handle camera raycasting. - * raytraceRay() is the core raytracing CUDA kernel; all of your raytracing - logic should be implemented in this CUDA kernel. raytraceRay() should - take in a camera, image buffer, geometry, materials, and lights, and should - trace a ray through the scene and write the resultant color to a pixel in the - image buffer. - -* intersections.h contains functions for geometry intersection testing and - point generation. You will need to complete: - * boxIntersectionTest(), which takes in a box and a ray and performs an - intersection test. This function should work in the same way as - sphereIntersectionTest(). - * getRandomPointOnSphere(), which takes in a sphere and returns a random - point on the surface of the sphere with an even probability distribution. - This function should work in the same way as getRandomPointOnCube(). You can - (although do not necessarily have to) use this to generate points on a sphere - to use a point lights, or can use this for area lighting. - -* interactions.h contains functions for ray-object interactions that define how - rays behave upon hitting materials and objects. You will need to complete: - * getRandomDirectionInSphere(), which generates a random direction in a - sphere with a uniform probability. This function works in a fashion - similar to that of calculateRandomDirectionInHemisphere(), which generates a - random cosine-weighted direction in a hemisphere. - * calculateBSDF(), which takes in an incoming ray, normal, material, and - other information, and returns an outgoing ray. You can either implement - this function for ray-surface interactions, or you can replace it with your own - function(s). - -You will also want to familiarize yourself with: - -* sceneStructs.h, which contains definitions for how geometry, materials, - lights, cameras, and animation frames are stored in the renderer. -* utilities.h, which serves as a kitchen-sink of useful functions - -------------------------------------------------------------------------------- -NOTES ON GLM: -------------------------------------------------------------------------------- -This project uses GLM, the GL Math library, for linear algebra. You need to -know two important points on how GLM is used in this project: - -* In this project, indices in GLM vectors (such as vec3, vec4), are accessed - via swizzling. So, instead of v[0], v.x is used, and instead of v[1], v.y is - used, and so on and so forth. -* GLM Matrix operations work fine on NVIDIA Fermi cards and later, but - pre-Fermi cards do not play nice with GLM matrices. As such, in this project, - GLM matrices are replaced with a custom matrix struct, called a cudaMat4, found - in cudaMat4.h. A custom function for multiplying glm::vec4s and cudaMat4s is - provided as multiplyMV() in intersections.h. - -------------------------------------------------------------------------------- -TAKUAscene FORMAT: -------------------------------------------------------------------------------- -This project uses a custom scene description format, called TAKUAscene. -TAKUAscene files are flat text files that describe all geometry, materials, -lights, cameras, render settings, and animation frames inside of the scene. -Items in the format are delimited by new lines, and comments can be added at -the end of each line preceded with a double-slash. - -Materials are defined in the following fashion: - -* MATERIAL (material ID) //material header -* RGB (float r) (float g) (float b) //diffuse color -* SPECX (float specx) //specular exponent -* SPECRGB (float r) (float g) (float b) //specular color -* REFL (bool refl) //reflectivity flag, 0 for - no, 1 for yes -* REFR (bool refr) //refractivity flag, 0 for - no, 1 for yes -* REFRIOR (float ior) //index of refraction - for Fresnel effects -* SCATTER (float scatter) //scatter flag, 0 for - no, 1 for yes -* ABSCOEFF (float r) (float b) (float g) //absorption - coefficient for scattering -* RSCTCOEFF (float rsctcoeff) //reduced scattering - coefficient -* EMITTANCE (float emittance) //the emittance of the - material. Anything >0 makes the material a light source. - -Cameras are defined in the following fashion: - -* CAMERA //camera header -* RES (float x) (float y) //resolution -* FOVY (float fovy) //vertical field of - view half-angle. the horizonal angle is calculated from this and the - reslution -* ITERATIONS (float interations) //how many - iterations to refine the image, only relevant for supersampled antialiasing, - depth of field, area lights, and other distributed raytracing applications -* FILE (string filename) //file to output - render to upon completion -* frame (frame number) //start of a frame -* EYE (float x) (float y) (float z) //camera's position in - worldspace -* VIEW (float x) (float y) (float z) //camera's view - direction -* UP (float x) (float y) (float z) //camera's up vector - -Objects are defined in the following fashion: -* OBJECT (object ID) //object header -* (cube OR sphere OR mesh) //type of object, can - be either "cube", "sphere", or "mesh". Note that cubes and spheres are unit - sized and centered at the origin. -* material (material ID) //material to - assign this object -* frame (frame number) //start of a frame -* TRANS (float transx) (float transy) (float transz) //translation -* ROTAT (float rotationx) (float rotationy) (float rotationz) //rotation -* SCALE (float scalex) (float scaley) (float scalez) //scale - -An example TAKUAscene file setting up two frames inside of a Cornell Box can be -found in the scenes/ directory. - -For meshes, note that the base code will only read in .obj files. For more -information on the .obj specification see http://en.wikipedia.org/wiki/Wavefront_.obj_file. - -An example of a mesh object is as follows: - -OBJECT 0 -mesh tetra.obj -material 0 -frame 0 -TRANS 0 5 -5 -ROTAT 0 90 0 -SCALE .01 10 10 - -Check the Google group for some sample .obj files of varying complexity. - -------------------------------------------------------------------------------- -README -------------------------------------------------------------------------------- -All students must replace or augment the contents of this Readme.md in a clear -manner with the following: - -* A brief description of the project and the specific features you implemented. -* At least one screenshot of your project running. -* A 30 second or longer video of your project running. To create the video you - can use http://www.microsoft.com/expression/products/Encoder4_Overview.aspx -* A performance evaluation (described in detail below). - -------------------------------------------------------------------------------- -PERFORMANCE EVALUATION -------------------------------------------------------------------------------- -The performance evaluation is where you will investigate how to make your CUDA -programs more efficient using the skills you've learned in class. You must have -perform at least one experiment on your code to investigate the positive or -negative effects on performance. - -One such experiment would be to investigate the performance increase involved -with adding a spatial data-structure to your scene data. - -Another idea could be looking at the change in timing between various block -sizes. - -A good metric to track would be number of rays per second, or frames per -second, or number of objects displayable at 60fps. - -We encourage you to get creative with your tweaks. Consider places in your code -that could be considered bottlenecks and try to improve them. - -Each student should provide no more than a one page summary of their -optimizations along with tables and or graphs to visually explain and -performance differences. - -------------------------------------------------------------------------------- -THIRD PARTY CODE POLICY -------------------------------------------------------------------------------- -* Use of any third-party code must be approved by asking on our Google Group. - If it is approved, all students are welcome to use it. Generally, we approve - use of third-party code that is not a core part of the project. For example, - for the ray tracer, we would approve using a third-party library for loading - models, but would not approve copying and pasting a CUDA function for doing - refraction. -* Third-party code must be credited in README.md. -* Using third-party code without its approval, including using another - student's code, is an academic integrity violation, and will result in you - receiving an F for the semester. - -------------------------------------------------------------------------------- -SELF-GRADING -------------------------------------------------------------------------------- -* On the submission date, email your grade, on a scale of 0 to 100, to Liam, - liamboone+cis565@gmail.com, with a one paragraph explanation. Be concise and - realistic. Recall that we reserve 30 points as a sanity check to adjust your - grade. Your actual grade will be (0.7 * your grade) + (0.3 * our grade). We - hope to only use this in extreme cases when your grade does not realistically - reflect your work - it is either too high or too low. In most cases, we plan - to give you the exact grade you suggest. -* Projects are not weighted evenly, e.g., Project 0 doesn't count as much as - the path tracer. We will determine the weighting at the end of the semester - based on the size of each project. - -------------------------------------------------------------------------------- -SUBMISSION -------------------------------------------------------------------------------- -As with the previous project, you should fork this project and work inside of -your fork. Upon completion, commit your finished project back to your fork, and -make a pull request to the master repository. You should include a README.md -file in the root directory detailing the following - -* A brief description of the project and specific features you implemented -* At least one screenshot of your project running, and at least one screenshot - of the final rendered output of your raytracer -* A link to a video of your raytracer running. -* Instructions for building and running your project if they differ from the - base code -* A performance writeup as detailed above. -* A list of all third-party code used. -* This Readme file, augmented or replaced as described above in the README section. +Credits +================= +* This is based on some very minimal skeleton code, which provides some basic structure. All of the raytracing was done by me. Plus I changed it to parallelize along rays rather than along tiles of the screen, in order to make stream compaction work. The skeleton code (avialable on +https://github.com/CIS565-Fall-2013/Project1-RayTracer) belongs to its original +authors. +* Used FPS counter from http://www.lighthouse3d.com/tutorials/glut-tutorial/frames-per-second/ +* Rest of the code is my own. Some of it is from my CPU raytracer, and some of the camera control +code is from one of my old projects. +* Aditions to the skeleton code that are part of NaTracer are Copyright +(C) Nathan Marshak 2013 and licensed under the GPLv3 (included in this project +as LICENSE.txt). diff --git a/renders/1000_newrandom.png b/renders/1000_newrandom.png new file mode 100644 index 0000000..745b3ca Binary files /dev/null and b/renders/1000_newrandom.png differ diff --git a/renders/1092_newrandom.png b/renders/1092_newrandom.png new file mode 100644 index 0000000..7569687 Binary files /dev/null and b/renders/1092_newrandom.png differ diff --git a/renders/WITH_jittering_reflect_no_jaggies.png b/renders/WITH_jittering_reflect_no_jaggies.png new file mode 100644 index 0000000..8d4834a Binary files /dev/null and b/renders/WITH_jittering_reflect_no_jaggies.png differ diff --git a/renders/better_random_330.png b/renders/better_random_330.png new file mode 100644 index 0000000..dbf338b Binary files /dev/null and b/renders/better_random_330.png differ diff --git a/renders/better_random_331.png b/renders/better_random_331.png new file mode 100644 index 0000000..e06950e Binary files /dev/null and b/renders/better_random_331.png differ diff --git a/renders/blur_1000.png b/renders/blur_1000.png new file mode 100644 index 0000000..26840b7 Binary files /dev/null and b/renders/blur_1000.png differ diff --git a/renders/newrandom_101.png b/renders/newrandom_101.png new file mode 100644 index 0000000..cc8ae17 Binary files /dev/null and b/renders/newrandom_101.png differ diff --git a/renders/no_pathtracing.png b/renders/no_pathtracing.png new file mode 100644 index 0000000..856a8e6 Binary files /dev/null and b/renders/no_pathtracing.png differ diff --git a/renders/raytrace_compaction.png b/renders/raytrace_compaction.png new file mode 100644 index 0000000..04d1a82 Binary files /dev/null and b/renders/raytrace_compaction.png differ diff --git a/renders/without_jittering_210_iterations.png b/renders/without_jittering_210_iterations.png new file mode 100644 index 0000000..d9e8b14 Binary files /dev/null and b/renders/without_jittering_210_iterations.png differ diff --git a/src/interactions.h b/src/interactions.h index 8c3f5f6..4b04cd9 100755 --- a/src/interactions.h +++ b/src/interactions.h @@ -7,7 +7,6 @@ #define INTERACTIONS_H #include "intersections.h" - struct Fresnel { float reflectionCoefficient; float transmissionCoefficient; @@ -43,10 +42,9 @@ __host__ __device__ glm::vec3 calculateTransmissionDirection(glm::vec3 normal, g return glm::vec3(0,0,0); } -//TODO (OPTIONAL): IMPLEMENT THIS FUNCTION __host__ __device__ glm::vec3 calculateReflectionDirection(glm::vec3 normal, glm::vec3 incident) { - //nothing fancy here - return glm::vec3(0,0,0); + const float cosI = -glm::dot( normal, incident ); + return glm::normalize(incident + 2 * cosI * normal); } //TODO (OPTIONAL): IMPLEMENT THIS FUNCTION @@ -86,13 +84,28 @@ __host__ __device__ glm::vec3 calculateRandomDirectionInHemisphere(glm::vec3 nor } -//TODO: IMPLEMENT THIS FUNCTION -//Now that you know how cosine weighted direction generation works, try implementing non-cosine (uniform) weighted random direction generation. -//This should be much easier than if you had to implement calculateRandomDirectionInHemisphere. +//We remap two uniform distributions epsilon1 and epsilon2 in order to uniformly +//sample the sphere. This is based on Ch. 13 of Physically-Based Rendering by +//Humphreys and Pharr (and ported from my CPU raytracer). __host__ __device__ glm::vec3 getRandomDirectionInSphere(float xi1, float xi2) { - return glm::vec3(0,0,0); + float epsilon1 = xi1; + float epsilon2 = xi2; + glm::vec3 toReturn; + float sqrtTerm = (float)sqrt( 1 - epsilon1*epsilon1 ); + toReturn.x = (float)cos( 2 * M_PI * epsilon2 ) * sqrtTerm; + toReturn.y = (float)sin( 2 * M_PI * epsilon2 ) * sqrtTerm; + toReturn.z = epsilon1; + return toReturn; } +//__host__ __device__ glm::vec3 sampleCube(float xi1, float xi2, float xi3) { + //float halfX1 = 0.5 * xi1; + //float halfX2 = 0.5 * xi2; + //float halfX3 = 0.5 * xi3; + //return glm::vec3(halfX1, halfX2, halfX3); +//} + + //TODO (PARTIALLY OPTIONAL): IMPLEMENT THIS FUNCTION //returns 0 if diffuse scatter, 1 if reflected, 2 if transmitted. __host__ __device__ int calculateBSDF(ray& r, glm::vec3 intersect, glm::vec3 normal, glm::vec3 emittedColor, diff --git a/src/intersections.h b/src/intersections.h index daefe95..9c23aa2 100755 --- a/src/intersections.h +++ b/src/intersections.h @@ -6,11 +6,13 @@ #ifndef INTERSECTIONS_H #define INTERSECTIONS_H +#define INTER_EPSILON 0.001f #include "sceneStructs.h" #include "cudaMat4.h" #include "glm/glm.hpp" #include "utilities.h" #include +#include //Some forward declarations __host__ __device__ glm::vec3 getPointOnRay(ray r, float t); @@ -70,9 +72,103 @@ __host__ __device__ glm::vec3 getSignOfRay(ray r){ //TODO: IMPLEMENT THIS FUNCTION //Cube intersection test, return -1 if no intersection, otherwise, distance to intersection +//Assumes that the cube's "radius" is 0.5 __host__ __device__ float boxIntersectionTest(staticGeom box, ray r, glm::vec3& intersectionPoint, glm::vec3& normal){ - return -1; + glm::vec3 P0 = multiplyMV(box.inverseTransform, glm::vec4(r.origin,1.0f)); + glm::vec3 d = glm::normalize(multiplyMV(box.inverseTransform, glm::vec4(r.direction,0.0f))); + ray rt; + rt.origin = P0; + rt.direction = d; + float Tnear = -std::numeric_limits::infinity(); + float Tfar = std::numeric_limits::infinity(); + + for(int i = 0; i < 3; i++){ + float currD = d[i]; //current dir component, e.g. Xd + float currO = P0[i]; //current origin component, e.g Xo + if( (currD > INTER_EPSILON && currD < INTER_EPSILON) + && (currO < -0.5 || currO > 0.5) ){ + return -1; + } + else{ + float t1 = (-0.5 - currO) / currD; + float t2 = (0.5 - currO) / currD; + if(t1 > t2){ + float temp = t1; + t1 = t2; + t2 = temp; + } + if(t1 > Tnear) + Tnear = t1; + if(t2 < Tfar) + Tfar = t2; + if(Tnear > Tfar) + return -1; + if(Tfar < 0) + return -1; + } + } + + glm::vec4 localInterPt = glm::vec4(getPointOnRay(rt, Tnear), 1.0); + glm::vec4 localNormal; + + if(localInterPt.x > 0.5 - INTER_EPSILON && localInterPt.x < 0.5 + INTER_EPSILON) + localNormal = glm::vec4(1, 0, 0, 0); + else if(localInterPt.x > -0.5 - INTER_EPSILON && localInterPt.x < -0.5 + INTER_EPSILON) + localNormal = glm::vec4(-1, 0, 0, 0); + else if(localInterPt.y > 0.5 - INTER_EPSILON && localInterPt.y < 0.5 + INTER_EPSILON) + localNormal = glm::vec4(0, 1, 0, 0); + else if(localInterPt.y > -0.5 - INTER_EPSILON && localInterPt.y < -0.5 + INTER_EPSILON) + localNormal = glm::vec4(0, -1, 0, 0); + else if(localInterPt.z > 0.5 - INTER_EPSILON && localInterPt.z < 0.5 + INTER_EPSILON) + localNormal = glm::vec4(0, 0, 1, 0); + else //if(localInterPt.z > -0.5 - INTER_EPSILON && localInterPt.z < -0.5 + INTER_EPSILON) + localNormal = glm::vec4(0, 0, -1, 0); + + glm::vec3 realintersectionpoint = multiplyMV(box.transform, localInterPt); + glm::vec3 realorigin = multiplyMV(box.transform, glm::vec4(0,0,0,1)); + + intersectionPoint = realintersectionpoint; + normal = multiplyMV(box.transform, localNormal); + normal = glm::normalize(normal); + + return glm::length(r.origin - realintersectionpoint); +} + +//Metaball intersection test! +__host__ __device__ float metaballIntersectionTest(staticGeom* metaballs, int numMetaballs, ray r, glm::vec3& intersectionPoint, glm::vec3& normal){ + + glm::vec3 currInterPt; + glm::vec3 currNormal; + float currT; + float minT = INFINITY; + glm::vec3 minInterPt; + glm::vec3 minNormal; + //for(int i = 0; i < numMetaballs; i++){ + //currT = sphereIntersectionTest(metaballs[i], r, currInterPt, currNormal); + //if(currT > 0 && currT < minT){ + //minT = currT; + //minInterPt = currInterPt; + //minNormal = currNormal; + //} + //} + + //reparamaterize ray by Z + ray reRay; + reRay.origin = r.origin; + reRay.direction = r.direction / r.direction.z; + glm::vec3 R = reRay.direction; + float rDotR = glm::dot(R, R); + for(int i = 0; i < numMetaballs; i++){ + glm::vec3 Pi = metaballs[i].translation - r.origin; + float Zmi = glm::dot(Pi, R)/rDotR; + glm::vec3 miVec = Pi - Zmi*R; + float mi = glm::dot(miVec, miVec); + } + + intersectionPoint = minInterPt; + normal = minNormal; + return minT; } //LOOK: Here's an intersection test example from a sphere. Now you just need to figure out cube and, optionally, triangle. @@ -111,6 +207,9 @@ __host__ __device__ float sphereIntersectionTest(staticGeom sphere, ray r, glm:: intersectionPoint = realIntersectionPoint; normal = glm::normalize(realIntersectionPoint - realOrigin); + + //testing by NATHAN: + //intersectionPoint = glm::vec3(0, 10, 0); return glm::length(r.origin - realIntersectionPoint); } diff --git a/src/main.cpp b/src/main.cpp index 9b1fdf7..a7091e3 100755 --- a/src/main.cpp +++ b/src/main.cpp @@ -6,13 +6,81 @@ // Yining Karl Li's TAKUA Render, a massively parallel pathtracing renderer: http://www.yiningkarlli.com #include "main.h" +//#include +#include //------------------------------- //-------------MAIN-------------- //------------------------------- +long int frame = 0; +long int elapsedTime = 0; +long int timebase = 0; + +glm::vec3 position; +glm::vec3 currView; +glm::vec3 currUp; +glm::vec3 startView; +glm::vec3 startUp; + +//P0 and P1 are for Arcball camera +glm::vec3 startP0; +glm::vec3 endP1; +glm::quat qstart; //starting rotation for camera + +bool arcballRotOn = false; +bool firstRun = true; +bool interactiveCamera = true; //false for multi-frame animation rendering + +void resetTracer(){ //reset the pathtracer once the camera moves + naIter = 0; + for(int i=0; iresolution.x*renderCam->resolution.y; i++){ + renderCam->image[i] = glm::vec3(0,0,0); + } +} + +glm::fquat computeArcballRot(glm::vec3 point0, glm::vec3 point1) +{ + glm::fquat rotQuat = glm::fquat(); + glm::vec3 crossProduct = glm::cross(startP0, endP1); + rotQuat.x = crossProduct.x; + rotQuat.y = crossProduct.y; + rotQuat.z = crossProduct.z; + rotQuat.w = glm::dot(startP0, endP1); + return rotQuat; +} + +glm::vec3 computeSphereCoords(int screenX, int screenY, int screenWidth, int screenHeight) +{ + glm::vec2 center = glm::vec2(screenWidth/2, screenHeight/2); + float radius = min(screenWidth/2, screenHeight/2); + glm::vec3 pt = glm::vec3(0.0f); //point that we are returning + + pt.x = (screenX - center.x)/radius; + pt.y = (screenY - center.y)/radius; + float r = pt.x*pt.x + pt.y*pt.y; + if(r > 1.0){ + float s = 1.0/sqrt(r); + pt.x = s*pt.x; + pt.y = s*pt.y; + pt.z = 0.0; + } + else + pt.z = sqrt(1.0 - r); + + return pt; +} + int main(int argc, char** argv){ + rayBuffers[0] = NULL; + rayBuffers[1] = NULL; + + qstart.x = 0; + qstart.y = 0; + qstart.z = 0; + qstart.w = 1; + #ifdef __APPLE__ // Needed in OSX to force use of OpenGL3.2 glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); @@ -58,6 +126,7 @@ int main(int argc, char** argv){ targetFrame = 0; } + printf("Initializing CUDA/random numbers. This may take a minute.\n"); // Launch CUDA/GL #ifdef __APPLE__ @@ -68,6 +137,25 @@ int main(int argc, char** argv){ initCuda(); + int numRays = renderCam->resolution.x * renderCam->resolution.y; + cudaMalloc((void**)&rand_states, numRays*sizeof(curandState)); + initRandomWrapper(rand_states, numRays); + + printf("Num metaballs: %d\n", renderScene->numMetaballs); + + //initRayBuffers(renderCam->resolution, rayBufferA, rayBufferB); + rayBuffers[0] = initRayBuffer(renderCam->resolution); + rayBuffers[1] = initRayBuffer(renderCam->resolution); + isFinishedBuf = initIntBuffer(renderCam->resolution); + scanIndices = initIntBuffer(renderCam->resolution); + //isFinishedBuf.reserve(renderCam->resolution.x*renderCam->resolution.y); + + if(rayBuffers[0]){ + cout << "Ray Buffer A points to something!" << endl; + } else{ + cout << "Ray Buffer A points to NOTHING!!!!" << endl; + } + initVAO(); initTextures(); @@ -90,18 +178,36 @@ int main(int argc, char** argv){ #else glutDisplayFunc(display); glutKeyboardFunc(keyboard); + glutMouseFunc(mousePress); + glutMotionFunc(mouseMove); glutMainLoop(); #endif + return 0; } //------------------------------- //---------RUNTIME STUFF--------- //------------------------------- +//struct not_finished +//{ + //__host__ __device__ + //bool operator()(ray r) + //{ + //return !r.finished; + //} +//}; void runCuda(){ + //testScan(); + //int result[8]; + //cudaMemcpy(result, scanDevice, 8*sizeof(int), cudaMemcpyDeviceToHost); + + //for(int i = 0; i < 8; i++){ + //printf("Scan test: %d\n", result[i]); + //} // Map OpenGL buffer object for writing from CUDA on a single GPU // No data is moved (Win & Linux). When mapped to CUDA, OpenGL should not use this buffer @@ -113,17 +219,37 @@ void runCuda(){ //pack geom and material arrays geom* geoms = new geom[renderScene->objects.size()]; material* materials = new material[renderScene->materials.size()]; - + for(int i=0; iobjects.size(); i++){ geoms[i] = renderScene->objects[i]; } for(int i=0; imaterials.size(); i++){ materials[i] = renderScene->materials[i]; } - - - // execute the kernel - cudaRaytraceCore(dptr, renderCam, targetFrame, iterations, materials, renderScene->materials.size(), geoms, renderScene->objects.size() ); + + if(firstRun){ + position = renderCam->positions[0]; + currView = renderCam->views[0]; + startView = currView; + currUp = renderCam->ups[0]; + startUp = currUp; + firstRun = false; + } + + if(arcballRotOn){ + currView = computeArcballRot(startP0, endP1) * qstart * startView; + currUp = computeArcballRot(startP0, endP1) * qstart * startUp; + } + + //populate the ray buffer + if(rayBuffers[0]){ + ray* activeBuffer = rayBuffers[0]; + ray* inactiveBuffer = rayBuffers[1]; + //calcScreenRaysCore(naIter, renderCam, targetFrame, activeBuffer, position, currView, currUp, interactiveCamera, elapsedTime); + int numRays = (renderCam->resolution).x*(renderCam->resolution).y; + cudaRaytraceCore(dptr, renderCam, targetFrame, naIter, materials, renderScene->materials.size(), geoms, renderScene->objects.size(), position, currView, currUp, interactiveCamera, activeBuffer, inactiveBuffer, isFinishedBuf, scanIndices, numRays, elapsedTime, SUPERSAMPLE_NUM, rand_states, useGI, renderScene->numMetaballs); + naIter++; + } // unmap buffer object cudaGLUnmapBufferObject(pbo); @@ -180,7 +306,7 @@ void runCuda(){ void display(){ runCuda(); - string title = "CIS565 Render | " + utilityCore::convertIntToString(iterations) + " Iterations"; + string title = "CUDA-NaTracer | " + utilityCore::convertIntToString(iterations) + " Iterations"; glfwSetWindowTitle(title.c_str()); glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo); @@ -201,7 +327,8 @@ void runCuda(){ void display(){ runCuda(); - string title = "565Raytracer | " + utilityCore::convertIntToString(iterations) + " Iterations"; + //string title = "CUDA-Natracer | " + utilityCore::convertIntToString(iterations) + " Iterations"; + string title = "CUDA-Natracer | " + utilityCore::convertIntToString(naIter) + " Iterations"; glutSetWindowTitle(title.c_str()); glBindBuffer( GL_PIXEL_UNPACK_BUFFER, pbo); @@ -216,19 +343,72 @@ void runCuda(){ glutPostRedisplay(); glutSwapBuffers(); + + //from http://www.lighthouse3d.com/tutorials/glut-tutorial/frames-per-second/ + frame++; + elapsedTime = glutGet(GLUT_ELAPSED_TIME); + if (elapsedTime - timebase > 1000) { + //printf("FPS:%4.2f\n", + //frame*1000.0/(elapsedTime-timebase)); + timebase = elapsedTime; + frame = 0; + } } void keyboard(unsigned char key, int x, int y) { - std::cout << key << std::endl; + //std::cout << key << std::endl; switch (key) { case(27): exit(1); - break; - } + break; + case(119): //W + position += 0.1f*currUp; + resetTracer(); + break; + case(115): //S + position -= 0.1f*currUp; + resetTracer(); + break; + case(97): //A + position += 0.1f*glm::cross(currView,currUp); + resetTracer(); + break; + case(100)://D + position -= 0.1f*glm::cross(currView,currUp); + resetTracer(); + break; + case(103): + useGI = !useGI; + resetTracer(); + break; + } } + void mousePress(int button, int state, int x, int y) + { + resetTracer(); + if(button == 3){ + position += 0.1f*currView; + } else if (button == 4){ + position -= 0.1f*currView; + } + if(state == GLUT_DOWN){ //pressed + startP0 = computeSphereCoords(x, y, width, height); + endP1 = startP0; + arcballRotOn = true; + } else{ //released + qstart = computeArcballRot(startP0, endP1)*qstart; + arcballRotOn = false; + } + } + + void mouseMove(int x, int y) + { + endP1 = computeSphereCoords(x, y, width, height); + } + #endif @@ -369,8 +549,25 @@ GLuint initShader(const char *vertexShaderPath, const char *fragmentShaderPath){ //------------------------------- void cleanupCuda(){ + //if(rayBufferA && rayBufferB) deleteRayBuffers(rayBufferA, rayBufferB); + if(rayBuffers[0]){ + deleteRayBuffer(rayBuffers[0]); + } + if(rayBuffers[1]){ + deleteRayBuffer(rayBuffers[1]); + } + if(isFinishedBuf){ + cudaFree(isFinishedBuf); + } + if(scanIndices){ + cudaFree(scanIndices); + } if(pbo) deletePBO(&pbo); if(displayImage) deleteTexture(&displayImage); + + if(rand_states){ + cudaFree(rand_states); + } } void deletePBO(GLuint* pbo){ diff --git a/src/main.h b/src/main.h index 0bab7cb..9df9a82 100755 --- a/src/main.h +++ b/src/main.h @@ -25,10 +25,12 @@ #include "glslUtility.h" #include "sceneStructs.h" #include "glm/glm.hpp" +#include "glm/gtc/quaternion.hpp" #include "image.h" #include "raytraceKernel.h" #include "utilities.h" #include "scene.h" +#include #if CUDA_VERSION >= 5000 #include @@ -42,17 +44,36 @@ using namespace std; +#include +#include +#include +#include +#define SUPERSAMPLE_NUM 1 + //------------------------------- //----------PATHTRACER----------- //------------------------------- +bool useGI = true; scene* renderScene; camera* renderCam; int targetFrame; int iterations; +int naIter = 0; bool finishedRender; bool singleFrameMode; +//Two ray buffers for "double buffering" when parallelizing along rays. +//ray* rayBufferA = NULL; +//ray* rayBufferB = NULL; +ray* rayBuffers[2]; +int* isFinishedBuf = NULL; +int* scanIndices = NULL; + +curandState* rand_states = NULL; + +//thrust::device_vector isFinishedBuf; +//bool AisActive = true; //True if the tracer is currently using A... //------------------------------- //------------GL STUFF----------- //------------------------------- @@ -86,6 +107,8 @@ void runCuda(); #else void display(); void keyboard(unsigned char key, int x, int y); + void mousePress(int button, int state, int x, int y); + void mouseMove(int x, int y); #endif //------------------------------- @@ -100,6 +123,7 @@ void runCuda(); void initPBO(GLuint* pbo); void initCuda(); +void initRayCache(); void initTextures(); void initVAO(); GLuint initShader(const char *vertexShaderPath, const char *fragmentShaderPath); diff --git a/src/raytraceHelpers.h b/src/raytraceHelpers.h new file mode 100644 index 0000000..567ca5d --- /dev/null +++ b/src/raytraceHelpers.h @@ -0,0 +1,112 @@ +#ifndef RAYTRACE_HELPERS_H +#define RAYTRACE_HELPERS_H + +#include +#include "sceneStructs.h" +#include "intersections.h" +#include "interactions.h" + +#define MAX_DIFFUSE_BOUNCE 30 + +//This file contains helper methods for the most essential steps of raytracing. + +//Some forward declarations +__host__ __device__ bool hitSomething(ray testRay, staticGeom* geoms, int numberOfGeoms, float& hitPt, glm::vec3& intersectionPt, glm::vec3& normal, int& hitGeomIdx, staticGeom* metaballs, int numMetaballs); +__host__ __device__ float calcDiffuseCoeff(glm::vec3 lightPos, glm::vec3 hitPt, glm::vec3 normal); +__host__ __device__ float calcSpecularCoeff(glm::vec3 lightPos, glm::vec3 hitPt, glm::vec3 normal); +__host__ __device__ bool isInShadow(glm::vec3 hitPt, staticGeom& light, int lightIdx, staticGeom* geoms, int numberOfGeoms, staticGeom* metaballs, int numMetaballs); + +__host__ __device__ bool hitSomething(ray testRay, staticGeom* geoms, int numberOfGeoms, float& hitPt, glm::vec3& intersectionPt, glm::vec3& normal, int& hitGeomIdx, staticGeom* metaballs, int numMetaballs){ + bool hit = false; + float minT = INFINITY; + glm::vec3 minInterPt; + glm::vec3 minNormal; + int minIdx = 0; + glm::vec3 currInterPt; + glm::vec3 currNormal; + float currT; + + for(int i = 0; i < numberOfGeoms; ++i){ + if(geoms[i].type == SPHERE){ + currT = sphereIntersectionTest(geoms[i], testRay, currInterPt, currNormal); + } else if(geoms[i].type == CUBE){ + currT = boxIntersectionTest(geoms[i], testRay, currInterPt, currNormal); + } + + if(currT > 0 && currT < minT){ + minT = currT; + minInterPt = currInterPt; + minNormal = currNormal; + minIdx = i; + hit = true; + } + + currT = metaballIntersectionTest(metaballs, numMetaballs, testRay, currInterPt, currNormal); + + if(currT > 0 && currT < minT){ + minT = currT; + minInterPt = currInterPt; + minNormal = currNormal; + minIdx = i; + hit = true; + } + } + + hitPt = minT; + intersectionPt = minInterPt; + normal = minNormal; + hitGeomIdx = minIdx; + return hit; +} + +//returns a random point on the unit sphere. +__host__ __device__ glm::vec3 sampleSphere(glm::vec2 resolution, float time, int x, int y){ + + int index = x + (y * resolution.x); + thrust::default_random_engine rng(hash(index*time)); + thrust::uniform_real_distribution distro1(-1,1); + thrust::uniform_real_distribution distro2(0,1); + + float epsilon1 = (float)distro1(rng); + float epsilon2 = (float)distro2(rng); + + return getRandomDirectionInSphere(epsilon1, epsilon2); +} + +__host__ __device__ float calcDiffuseCoeff(glm::vec3 lightPos, glm::vec3 hitPt, glm::vec3 normal){ + glm::vec3 lightVector = glm::normalize(lightPos - hitPt); + float dotProd = glm::dot(glm::normalize(normal), lightVector); + return glm::clamp(dotProd, 0.0f, 1.0f); +} + +__host__ __device__ float calcSpecularCoeff(glm::vec3 lightPos, glm::vec3 hitPt, glm::vec3 normal, + glm::vec3 eyePos, float specPow){ + normal = glm::normalize(normal); + glm::vec3 lightVector = glm::normalize(lightPos - hitPt); + glm::vec3 incident = -lightVector; + glm::vec3 reflected = calculateReflectionDirection(normal, incident); + float specularTerm = glm::clamp(glm::dot(reflected, glm::normalize(eyePos - hitPt)), 0.0f, 1.0f); + return (float)pow(specularTerm, specPow); +} + +//If if the hitpoint is in the shadow of the light we pass this function, return true. +//If the hitpoint can "see" the light, return false. +__host__ __device__ bool isInShadow(glm::vec3 hitPt, staticGeom& light, int lightIdx, staticGeom* geoms, int numberOfGeoms, staticGeom* metaballs, int numMetaballs){ + ray feelerRay; + feelerRay.direction = light.translation - hitPt; + //Add a little bit to the hitPt to avoid floating-point error + feelerRay.origin = hitPt + 0.01f*feelerRay.direction; + + float hitParam = -1; + glm::vec3 intersectionPt; + glm::vec3 normal; + int hitGeomIdx = -1; + + if( hitSomething(feelerRay, geoms, numberOfGeoms, hitParam, intersectionPt, normal, hitGeomIdx, metaballs, numMetaballs) ){ + if(lightIdx == hitGeomIdx) //feeler hit the light we passed to it + return false; + } + + return true; +} +#endif diff --git a/src/raytraceKernel.cu b/src/raytraceKernel.cu old mode 100755 new mode 100644 index b4f4ec5..8a72cef --- a/src/raytraceKernel.cu +++ b/src/raytraceKernel.cu @@ -8,13 +8,26 @@ #include #include #include +#include #include "sceneStructs.h" #include "glm/glm.hpp" #include "utilities.h" #include "raytraceKernel.h" #include "intersections.h" #include "interactions.h" -#include +#include "raytraceHelpers.h" +#include +#include +#include +#include +#include "glm/gtc/matrix_transform.hpp" +#define DIFFUSE_K 0.7f +#define SPECULAR_K 0.3f +#define AMBIENT_K 0.1f + +#define MAX_DEPTH 5 + +#define RAY_TILE_SIZE 64 #if CUDA_VERSION >= 5000 #include @@ -30,6 +43,19 @@ void checkCUDAError(const char *msg) { } } +__global__ void init_random(curandState* states){ + int index = (blockIdx.x * blockDim.x) + threadIdx.x; + curand_init(hash(1+index), index, 0, &states[index]); +} + +void initRandomWrapper(curandState* states, int numRays) +{ + int rayTileSize = RAY_TILE_SIZE; //try making this 16 + dim3 threadsPerRayBlock(rayTileSize, 1, 1); + dim3 numRayBlocks((int)ceil(float(numRays)/float(rayTileSize)),1, 1); + init_random<<>>(states); +} + //LOOK: This function demonstrates how to use thrust for random number generation on the GPU! //Function that generates static. __host__ __device__ glm::vec3 generateRandomNumberFromThread(glm::vec2 resolution, float time, int x, int y){ @@ -41,12 +67,63 @@ __host__ __device__ glm::vec3 generateRandomNumberFromThread(glm::vec2 resolutio return glm::vec3((float) u01(rng), (float) u01(rng), (float) u01(rng)); } -//TODO: IMPLEMENT THIS FUNCTION //Function that does the initial raycast from the camera -__host__ __device__ ray raycastFromCameraKernel(glm::vec2 resolution, float time, int x, int y, glm::vec3 eye, glm::vec3 view, glm::vec3 up, glm::vec2 fov){ +__device__ ray raycastFromCameraKernel(glm::vec2 resolution, float time, int x, int y, glm::vec3 eye, glm::vec3 view, glm::vec3 up, glm::vec2 fov, long elapsedTime, int supersampleIdx, curandState* randStates){ ray r; - r.origin = glm::vec3(0,0,0); - r.direction = glm::vec3(0,0,-1); + + float ndcXbase = x/(float)resolution.x; + float ndcYbase = y/(float)resolution.y; + + float ndcXPlus = (x+1)/(float)resolution.x; + float ndcYPlus = (y+1)/(float)resolution.y; + + float dx = ndcXPlus - ndcXbase; + float dy = ndcYPlus - ndcYbase; + + int index = x + (y * resolution.x); + + /*thrust::default_random_engine rng(hash((supersampleIdx+1)*index*(time+1) + elapsedTime/1000.0f));*/ + /*[>thrust::taus88 rng(hash((supersampleIdx+1)*index*(time+1) + elapsedTime/1000.0f));<]*/ + /*thrust::uniform_real_distribution u01(0,1);*/ + + float rand1 = curand_uniform(&randStates[index]); + float rand2 = curand_uniform(&randStates[index]); + + /*float rand1 = (float)( u01(rng) );*/ + /*float rand2 = (float)( u01(rng) );*/ + + float ndcX = ndcXbase + dx * ( rand1 ); + float ndcY = ndcYbase + dy * ( rand2 ); + + /*if(index == 42){*/ + /*printf("ndcX: %f, ndcY: %f\n", ndcX, ndcY);*/ + /*}*/ + //from the lecture notes, to go from screen coordinates to world coordinates + float fovyRad = fov.y * (PI/180); //fovy in radians + + //C is the vector from the camera to the center of view. + glm::vec3 C = view; + glm::vec3 A = glm::cross( C, up ); + glm::vec3 B = glm::cross( A,C ); + glm::vec3 M = eye + C; + + float Hscale = static_cast(glm::length(C) * + (tan(fovyRad)*(resolution.x/(float)resolution.y))/glm::length(A)); + glm::vec3 H = Hscale*A; + float Vscale = static_cast(glm::length(C) * + tan(fovyRad)/glm::length(B)); + glm::vec3 V = Vscale*B; + + glm::vec3 Point = M + (2*ndcX - 1)*H + (2*ndcY - 1)*V; + glm::vec3 newDir = glm::normalize(Point - eye); + + r.origin = Point; + r.direction = newDir; + r.finished = false; + r.startX = x; + r.startY = y; + r.specularBounces = 0; + r.diffuseBounces = 0; return r; } @@ -61,7 +138,7 @@ __global__ void clearImage(glm::vec2 resolution, glm::vec3* image){ } //Kernel that writes the image to the OpenGL PBO directly. -__global__ void sendImageToPBO(uchar4* PBOpos, glm::vec2 resolution, glm::vec3* image){ +__global__ void sendImageToPBO(uchar4* PBOpos, glm::vec2 resolution, glm::vec3* image, int iterations){ int x = (blockIdx.x * blockDim.x) + threadIdx.x; int y = (blockIdx.y * blockDim.y) + threadIdx.y; @@ -74,6 +151,8 @@ __global__ void sendImageToPBO(uchar4* PBOpos, glm::vec2 resolution, glm::vec3* color.y = image[index].y*255.0; color.z = image[index].z*255.0; + color = color * ( 1.0f / (iterations + 1)); + if(color.x>255){ color.x = 255; } @@ -94,78 +173,482 @@ __global__ void sendImageToPBO(uchar4* PBOpos, glm::vec2 resolution, glm::vec3* } } -//TODO: IMPLEMENT THIS FUNCTION -//Core raytracer kernel -__global__ void raytraceRay(glm::vec2 resolution, float time, cameraData cam, int rayDepth, glm::vec3* colors, - staticGeom* geoms, int numberOfGeoms){ +__global__ void nathansImageToPBO(uchar4* PBOpos, glm::vec2 resolution, glm::vec3* image, ray* rayBuf, int numRays, int iterations){ + + int x = (blockIdx.x * blockDim.x) + threadIdx.x; + int index = x; + ray currRay = rayBuf[index]; + int pixIndex = currRay.startX + ((resolution.y - currRay.startY) * resolution.x);//index of the pixel the ray corresponds to + /*[>if( rayIdx < numRays ){<]*/ + /*int PBOindex = currRay.startX + (currRay.startY * resolution.x);*/ + if( pixIndex < resolution.x*resolution.y && pixIndex > 0 ){ + + glm::vec3 color; + + color.x = image[pixIndex].x*255.0; + color.y = image[pixIndex].y*255.0; + color.z = image[pixIndex].z*255.0; + + color = color * ( 1.0f / (iterations + 1)); + if(color.x>255){ + color.x = 255; + } + + if(color.y>255){ + color.y = 255; + } + + if(color.z>255){ + color.z = 255; + } + + /*// Each thread writes one pixel location in the texture (textel)*/ + PBOpos[pixIndex].w = 0; + PBOpos[pixIndex].x = color.x; + PBOpos[pixIndex].y = color.y; + PBOpos[pixIndex].z = color.z; + } +} + +//Raycast from the camera and store the rays in the array of rays. (Try that for +//a tounge-twister!) +__global__ void calcScreenRaysKernel(float time, cameraData cam, ray* rayBuf, long elapsedTime, int supersampleIdx, curandState* randStates ){ int x = (blockIdx.x * blockDim.x) + threadIdx.x; int y = (blockIdx.y * blockDim.y) + threadIdx.y; - int index = x + (y * resolution.x); + int index = x + ((cam.resolution.y - y) * cam.resolution.x); + rayBuf[index] = raycastFromCameraKernel(cam.resolution, time, x, y, cam.position, cam.view, cam.up, cam.fov, elapsedTime, supersampleIdx, randStates); +} + +void calcScreenRaysCore(float time, camera* renderCam, int frame, ray* rayBuf, glm::vec3 currPosition, glm::vec3 currView, glm::vec3 currUp, bool interactiveCamera, long elapsedTime, int supersampleIdx, curandState* randStates){ + //package camera + cameraData cam; + cam.resolution = renderCam->resolution; + if(interactiveCamera){ + cam.position = currPosition; + cam.view = currView; + cam.up = currUp; + } else { + cam.position = renderCam->positions[frame]; + cam.view = renderCam->views[frame]; + cam.up = renderCam->ups[frame]; + } + cam.fov = renderCam->fov; + + int tileSize = 8; + dim3 threadsPerBlock(tileSize, tileSize); + dim3 fullBlocksPerGrid((int)ceil(float(cam.resolution.x)/float(tileSize)), (int)ceil(float(cam.resolution.y)/float(tileSize))); + calcScreenRaysKernel<<>>(time, cam, rayBuf, elapsedTime, supersampleIdx, randStates); +} + +//Core raytracer kernel +__global__ void raytraceRay(glm::vec2 resolution, float time, cameraData cam, int rayDepth, glm::vec3* colors, glm::vec3* accumMap, staticGeom* geoms, int numberOfGeoms, emitter* emitters, int numEmitters, material* materials, ray* rayBuffer, long elapsedTime, int supersampleNum, int supersampleIdx, curandState* randStates, bool useGI, staticGeom* metaballs, int numMetaballs){ + + int x = (blockIdx.x * blockDim.x) + threadIdx.x; + int index = x; + + float superSampleRecip = 1.0f / supersampleNum; + + ray currRay = rayBuffer[index]; + int pixIndex = currRay.startX + ((resolution.y - currRay.startY) * resolution.x);//index of the pixel the ray corresponds to + + if( !currRay.finished ){ + if(currRay.specularBounces == 0 && currRay.diffuseBounces == 0){ + accumMap[pixIndex] = glm::vec3(1, 1, 1); + } + float hitPt = -1; + glm::vec3 intersectionPt; + glm::vec3 normal; + int hitGeomIdx = -1; + if( hitSomething(currRay, geoms, numberOfGeoms, hitPt, intersectionPt, normal, hitGeomIdx, metaballs, numMetaballs) ){ + material mat = materials[geoms[hitGeomIdx].materialid]; + if(useGI){ + if(mat.emittance > 0){ //hit a light + colors[pixIndex] += accumMap[pixIndex] * mat.color * mat.emittance * superSampleRecip; + rayBuffer[index].finished = true; + } else { //hit a diffuse surface + + float rand1 = curand_uniform(&randStates[index]); + float rand2 = curand_uniform(&randStates[index]); + + glm::vec3 randomDir = calculateRandomDirectionInHemisphere(normal, rand1, rand2); + rayBuffer[index].direction = glm::normalize(randomDir); + rayBuffer[index].origin = intersectionPt + 0.05f*rayBuffer[index].direction; + rayBuffer[index].diffuseBounces = rayBuffer[index].diffuseBounces + 1; + + glm::vec3 diffuseColor = mat.color; + accumMap[pixIndex] = accumMap[pixIndex] * diffuseColor; //* dotProd; + rayBuffer[index].finished = false; + + if( rayBuffer[index].diffuseBounces > MAX_DIFFUSE_BOUNCE || rayBuffer[index].specularBounces > MAX_BOUNCE){ + rayBuffer[index].finished = true; + } + if ( mat.hasReflective > 0 ){ + rayBuffer[index].direction = calculateReflectionDirection(normal, currRay.direction); + rayBuffer[index].origin = intersectionPt + 0.05f*rayBuffer[index].direction; + rayBuffer[index].specularBounces = rayBuffer[index].specularBounces + 1; + } + } + } else{ //use plain old ray tracing + glm::vec3 translation = geoms[hitGeomIdx].translation; + glm::vec3 rotation = geoms[hitGeomIdx].rotation; + glm::vec3 scale = geoms[hitGeomIdx].scale; + if(materials[geoms[hitGeomIdx].materialid].emittance > 0){ //hit a light + colors[pixIndex] += accumMap[pixIndex] * materials[geoms[hitGeomIdx].materialid].color; + rayBuffer[index].finished = true; + return; + } + material mat = materials[geoms[hitGeomIdx].materialid]; + glm::vec3 diffuseColor = mat.color; + glm::vec3 pixColor; //color of the pixel corresponding to the ray + + for(int i = 0; i < numEmitters; i++){ + emitter currEmitter = emitters[i]; + staticGeom light = geoms[currEmitter.geomIdx]; + + material lightMat = materials[light.materialid]; + glm::vec3 finalColor(0, 0, 0); + if(lightMat.emittance > 0 && !isInShadow(intersectionPt, light, currEmitter.geomIdx, geoms, numberOfGeoms,metaballs, numMetaballs) ){ + float diffuseCoeff = calcDiffuseCoeff(light.translation, intersectionPt, normal); + float specularCoeff = calcSpecularCoeff(light.translation, intersectionPt, normal, + cam.position, mat.specularExponent); + finalColor = DIFFUSE_K * diffuseCoeff * diffuseColor + AMBIENT_K * diffuseColor + + SPECULAR_K * specularCoeff * mat.specularColor; + } + pixColor += finalColor; + } + + if(mat.hasReflective > 0 && rayBuffer[index].specularBounces <= MAX_BOUNCE){ //alternative to recursion + rayBuffer[index].direction = calculateReflectionDirection(normal, currRay.direction); + rayBuffer[index].origin = intersectionPt; + rayBuffer[index].finished = false; + rayBuffer[index].specularBounces = rayBuffer[index].specularBounces + 1; + } else { + colors[pixIndex] += accumMap[pixIndex] * pixColor; + /*colors[pixIndex] += accumMap[pixIndex];*/ + rayBuffer[index].finished = true; + } + } + } else{ //hit nothing! + colors[pixIndex] += glm::vec3(0, 0, 0); + rayBuffer[index].finished = true; + } + } +} - if((x<=resolution.x && y<=resolution.y)){ - colors[index] = generateRandomNumberFromThread(resolution, time, x, y); - } +__global__ void calcIsFinished(int* isFinished, ray* rayBuf, int numRays, int* scanIndices){ + int index = (blockIdx.x * blockDim.x) + threadIdx.x; + if( index < numRays ){ + if( !rayBuf[index].finished ){ + isFinished[index] = 1; + scanIndices[index] = 1; + } else { + isFinished[index] = 0; + scanIndices[index] = 0; + } + } +} + +/*__global__ void scanInitKernel(int* scanIndices, int numRays, int n, int k, int* isFinished){*/ + /*int index = (blockIdx.x * blockDim.x) + threadIdx.x;*/ + /*int index = threadIdx.x;*/ + /*if(index < numRays && index >= k){*/ + /*scanIndices[index] = isFinished[index - k] + isFinished[index];*/ + /*} */ +/*}*/ + +//d is the exponent used in the slides explaining exclusive scna +__global__ void exclusiveScanKernel(int* aboveArray, int* currArray, int numRays, int powerD){ + int index = (blockIdx.x * blockDim.x) + threadIdx.x; + if(index < numRays && index >= powerD){ + currArray[index] = aboveArray[index - powerD] + aboveArray[index]; + } else { + currArray[index] = aboveArray[index]; + } +} + + +void scanWrapper(int* isFinished, int* scanIndices, int numRays){ + /*thrust::device_ptr isFin_ptr(isFinished);*/ + /*thrust::device_ptr scanIdx_ptr(scanIndices);*/ + /*thrust::exclusive_scan(isFin_ptr, isFin_ptr + numRays, scanIdx_ptr);*/ + + //because we are not scanning in place + cudaMemcpy( scanIndices, isFinished, numRays*sizeof(int), cudaMemcpyDeviceToDevice); + + int rayTileSize = RAY_TILE_SIZE; //try making this 16 + dim3 threadsPerRayBlock(rayTileSize, 1, 1); + dim3 numRayBlocks((int)ceil(float(numRays)/float(rayTileSize)),1, 1); + + int* aboveArray = NULL; + cudaMalloc((void**)&aboveArray, numRays*sizeof(int)); + cudaMemcpy( aboveArray, isFinished, numRays*sizeof(int), cudaMemcpyDeviceToDevice); + + int* currArray = NULL; + cudaMalloc((void**)&currArray, numRays*sizeof(int)); + cudaMemcpy( currArray, isFinished, numRays*sizeof(int), cudaMemcpyDeviceToDevice); + + int n = numRays; + for(int d = 1; n > 0; d++){ + int powerD = pow(2, (d-1)); + exclusiveScanKernel<<>>(aboveArray, currArray, numRays, powerD); + int* tmp = currArray; + currArray = aboveArray; + aboveArray = tmp; + n = n/2; + } + + cudaMemcpy( scanIndices, aboveArray, numRays*sizeof(int), cudaMemcpyDeviceToDevice ); + int zero = 0; + cudaMemcpy( scanIndices, &zero, sizeof(int), cudaMemcpyHostToDevice ); + + cudaFree(currArray); + cudaFree(aboveArray); +} + +//given an array and its length, reduce! +//spacing is how far we step to add the next number +__global__ void reduceKernel(int* array, int arrayLength, int numthreads, int spacing){ + int index = (blockIdx.x * blockDim.x) + threadIdx.x; + index = index * 2 * spacing; //spacing starts out as 1, increases by powers of 2 + if(index + spacing < arrayLength){ + array[index] = array[index] + array[index + spacing]; + } +} + +int reduceWrapper(int* isFinished, int numRays){ + /*thrust::device_ptr isFin_ptr(isFinished);*/ + /*return thrust::reduce(isFin_ptr, isFin_ptr + numRays); */ + int rayTileSize = RAY_TILE_SIZE; //try making this 16 + dim3 threadsPerRayBlock(rayTileSize, 1, 1); + + int* tmpBuffer = NULL; //because we are not reducing in place + cudaMalloc((void**)&tmpBuffer, numRays*sizeof(int)); + cudaMemcpy( tmpBuffer, isFinished, numRays*sizeof(int), cudaMemcpyDeviceToDevice); + + int n = numRays; + int k = 1; + while( n > 0 ){ + dim3 numRayBlocks((int)ceil(float(n)/float(rayTileSize)),1, 1); + reduceKernel<<>>(tmpBuffer, numRays, n, k); + k = k*2; + n = n/2; + } + + //copy the first value of the array into toReturn + int toReturn; + cudaMemcpy( &toReturn, tmpBuffer, sizeof(int), cudaMemcpyDeviceToHost); + cudaFree(tmpBuffer); + return toReturn; +} + +void calcIsFinishedCore(int* isFinished, ray* rayBuf, int numRays, int* scanIndices){ + int rayTileSize = RAY_TILE_SIZE; //try making this 16 + dim3 threadsPerRayBlock(rayTileSize, 1, 1); + dim3 numRayBlocks((int)ceil(float(numRays)/float(rayTileSize)),1, 1); + calcIsFinished<<>>(isFinished, rayBuf, numRays, scanIndices); +} + +__global__ void finalScatterKernel(ray* compactedBuffer, ray* startingBuffer, int* isFinished, int* scanIndices, int numRays){ + int index = (blockIdx.x * blockDim.x) + threadIdx.x; + if(index < numRays){ + if(isFinished[index]){ //<< might have to change it to !isFinished + int compactedIdx = scanIndices[index]; + compactedBuffer[compactedIdx] = startingBuffer[index]; + } + } +} + +void finalScatterCore(ray* compactedBuffer, ray* startingBuffer, int* isFinished, int* scanIndices, int numRays){ + int rayTileSize = RAY_TILE_SIZE; //try making this 16 + dim3 threadsPerRayBlock(rayTileSize, 1, 1); + dim3 numRayBlocks((int)ceil(float(numRays)/float(rayTileSize)),1, 1); + finalScatterKernel<<>>(compactedBuffer, startingBuffer, isFinished, scanIndices, numRays); } -//TODO: FINISH THIS FUNCTION // Wrapper for the __global__ call that sets up the kernel calls and does a ton of memory management -void cudaRaytraceCore(uchar4* PBOpos, camera* renderCam, int frame, int iterations, material* materials, int numberOfMaterials, geom* geoms, int numberOfGeoms){ +void cudaRaytraceCore(uchar4* PBOpos, camera* renderCam, int frame, int iterations, material* materials, int numberOfMaterials, geom* geoms, int numberOfGeoms, glm::vec3 currPosition, glm::vec3 currView, glm::vec3 currUp, bool interactiveCamera, ray* activeBuffer, ray* inactiveBuffer, int* isFinishedBuf, int* scanIndices, int numRays, long elapsedTime, int supersampleNum, curandState* rand_states, bool useGI, int numMetaballs){ int traceDepth = 1; //determines how many bounces the raytracer traces - // set up crucial magic - int tileSize = 8; - dim3 threadsPerBlock(tileSize, tileSize); - dim3 fullBlocksPerGrid((int)ceil(float(renderCam->resolution.x)/float(tileSize)), (int)ceil(float(renderCam->resolution.y)/float(tileSize))); - //send image to GPU - glm::vec3* cudaimage = NULL; + glm::vec3* cudaimage; cudaMalloc((void**)&cudaimage, (int)renderCam->resolution.x*(int)renderCam->resolution.y*sizeof(glm::vec3)); cudaMemcpy( cudaimage, renderCam->image, (int)renderCam->resolution.x*(int)renderCam->resolution.y*sizeof(glm::vec3), cudaMemcpyHostToDevice); + //send map of accumulated colors to GPU + glm::vec3* accumMap; + cudaMalloc((void**)&accumMap, (int)renderCam->resolution.x*(int)renderCam->resolution.y*sizeof(glm::vec3)); + cudaMemcpy( accumMap, renderCam->image, (int)renderCam->resolution.x*(int)renderCam->resolution.y*sizeof(glm::vec3), cudaMemcpyHostToDevice); + //package geometry and materials and sent to GPU - staticGeom* geomList = new staticGeom[numberOfGeoms]; - for(int i=0; i emitters; + for(int i=0; i 0){ + emitter newEmitter; + newEmitter.geomIdx = i; + emitters.push_back(newEmitter); + } + } + + emitter* cudaEmitters = NULL; + cudaMalloc((void**)&cudaEmitters, emitters.size()*sizeof(staticGeom)); + cudaMemcpy( cudaEmitters, &emitters[0], emitters.size()*sizeof(staticGeom), cudaMemcpyHostToDevice); + //package camera cameraData cam; cam.resolution = renderCam->resolution; - cam.position = renderCam->positions[frame]; - cam.view = renderCam->views[frame]; - cam.up = renderCam->ups[frame]; + if(interactiveCamera){ + cam.position = currPosition; + cam.view = currView; + cam.up = currUp; + } else { + cam.position = renderCam->positions[frame]; + cam.view = renderCam->views[frame]; + cam.up = renderCam->ups[frame]; + } cam.fov = renderCam->fov; - //kernel launches - raytraceRay<<>>(renderCam->resolution, (float)iterations, cam, traceDepth, cudaimage, cudageoms, numberOfGeoms); - sendImageToPBO<<>>(PBOpos, renderCam->resolution, cudaimage); + for(int i = 0; i < supersampleNum; i++){ + calcScreenRaysCore(iterations, renderCam, frame, activeBuffer, currPosition, currView, currUp, interactiveCamera, elapsedTime, i, rand_states); + int currNumRays = numRays; + + ray* currActive = activeBuffer; + ray* currInactive = inactiveBuffer; + int rayTileSize = RAY_TILE_SIZE; //try making this 16 + dim3 threadsPerRayBlock(rayTileSize, 1, 1); + dim3 numRayBlocks((int)ceil(float(currNumRays)/float(rayTileSize)),1, 1); + while( currNumRays > 0) { + dim3 subNumRayBlocks((int)ceil(float(currNumRays)/float(rayTileSize)),1, 1); + raytraceRay<<>>(renderCam->resolution, (float)iterations, cam, traceDepth, cudaimage, accumMap, cudageoms, numNonMetaGeoms, cudaEmitters, emitters.size(), cudaMats, currActive, elapsedTime, supersampleNum, i, rand_states, useGI, cudametas, numMetaballs); + calcIsFinishedCore(isFinishedBuf, currActive, currNumRays, scanIndices); + int unfinishedCount = reduceWrapper(isFinishedBuf, currNumRays); + scanWrapper(isFinishedBuf, scanIndices, currNumRays); + finalScatterCore(currInactive, currActive, isFinishedBuf, scanIndices, currNumRays); + currNumRays = unfinishedCount; + ray* tmp = currInactive; + currInactive = currActive; + currActive = tmp; + } + } + + //write currInactive because the "active" one just got swapped to inactive in the last iteration + /*nathansImageToPBO<<>>(PBOpos, renderCam->resolution, cudaimage, currInactive, numRays, iterations);*/ + + int tileSize = 8; + dim3 threadsPerBlock(tileSize, tileSize); + dim3 fullBlocksPerGrid((int)ceil(float(renderCam->resolution.x)/float(tileSize)), (int)ceil(float(renderCam->resolution.y)/float(tileSize))); + sendImageToPBO<<>>(PBOpos, renderCam->resolution, cudaimage, iterations); //retrieve image from GPU cudaMemcpy( renderCam->image, cudaimage, (int)renderCam->resolution.x*(int)renderCam->resolution.y*sizeof(glm::vec3), cudaMemcpyDeviceToHost); //free up stuff, or else we'll leak memory like a madman cudaFree( cudaimage ); + cudaFree( accumMap ); cudaFree( cudageoms ); + cudaFree( cudametas ); + cudaFree( cudaEmitters ); + cudaFree( cudaMats ); delete geomList; + delete metaballList; // make certain the kernel has completed cudaThreadSynchronize(); checkCUDAError("Kernel failed!"); } + +void testScan() +{ + int scanTest[8] = { 0, 1, 1, 0, 1, 0, 1, 0 }; + int* scanDevice = NULL; + int* scanDevice2 = NULL; + + cudaMalloc((void**)scanDevice, 8*sizeof(int)); + cudaMemcpy(scanDevice, scanTest, 8*sizeof(int), cudaMemcpyHostToDevice); + + cudaMalloc((void**)scanDevice2, 8*sizeof(int)); + cudaMemcpy(scanDevice2, scanTest, 8*sizeof(int), cudaMemcpyHostToDevice); + + //scanWrapper(scanDevice2, scanDevice, 7); + //scanWrapper(reduceKernel, scanDevice, 7); + + int result = reduceWrapper(scanDevice, 8); + printf("Result: %d\n", result); + + cudaFree(scanDevice); + cudaFree(scanDevice2); +} + +ray* initRayBuffer(glm::vec2 resolution){ + int size = resolution.x*resolution.y; + ray* rays = NULL; + cudaMalloc((void**)&rays, size*sizeof(ray)); + return rays; +} + +int* initIntBuffer(glm::vec2 resolution){ + int size = resolution.x*resolution.y; + int* ints = NULL; + cudaMalloc((void**)&ints, size*sizeof(int)); + cudaMemset(ints, 0, size*sizeof(int)); + return ints; +} + +void deleteRayBuffer(ray* rayBuf1){ + cudaFree(rayBuf1); +} diff --git a/src/raytraceKernel.h b/src/raytraceKernel.h index 5fcf5a3..f08f15d 100755 --- a/src/raytraceKernel.h +++ b/src/raytraceKernel.h @@ -5,14 +5,16 @@ // Peter Kutz and Yining Karl Li's GPU Pathtracer: http://gpupathtracer.blogspot.com/ // Yining Karl Li's TAKUA Render, a massively parallel pathtracing renderer: http://www.yiningkarlli.com -#ifndef RAYTRACEKERNEL_H +#ifndef PATHTRACEKERNEL_H #define PATHTRACEKERNEL_H #include #include #include #include +#include #include "sceneStructs.h" +#define MAX_BOUNCE 5 #if CUDA_VERSION >= 5000 #include @@ -20,6 +22,26 @@ #include #endif -void cudaRaytraceCore(uchar4* pos, camera* renderCam, int frame, int iterations, material* materials, int numberOfMaterials, geom* geoms, int numberOfGeoms); +void cudaRaytraceCore(uchar4* pos, camera* renderCam, int frame, int iterations, material* materials, int numberOfMaterials, geom* geoms, int numberOfGeoms, glm::vec3 position, glm::vec3 currView, glm::vec3 currUp, bool interactiveCamera, ray* rayBufferA, ray* inactiveBuffer, int* isFinishedBuf, int* scanIndices, int numRays, long elapsedTime, int supersampleNum, curandState* states, bool useGI, int numMetaballs); +void calcScreenRaysCore(float time, camera* renderCam, int frame, ray* rayBuf, glm::vec3 position, glm::vec3 currView, glm::vec3 currUp, bool interactiveCamera, long elapsedTime); + +__global__ void calcIsFinished(int* isFinished, ray* rayBuf, int numRays); + +void calcIsFinishedCore(int* isFinished, ray* rayBuf, int numRays); +int reduceWrapper(int* isFinished, int numRays); +void scanWrapper(int* isFinished, int* scanIndices, int numRays); +void finalScatterCore(ray* compactedBuffer, ray* startingBuffer, int* isFinished, int* scanIndices, int numRays); +__global__ void finalScatterKernel(ray* compactedBuffer, ray* startingBuffer, int* isFinished, int* scanIndices, int numRays); + +//Initialize buffer for parallelization along rays (with stream compaction). +//We have two buffers for "double buffering". +//void initRayBuffers(glm::vec2 resolution, ray** rayBuf1, ray** rayBuf2); +void deleteRayBuffer(ray* rayBuf1); +ray* initRayBuffer(glm::vec2 resolution); +int* initIntBuffer(glm::vec2 resolution); + +void initRandomWrapper(curandState* states, int numRays); + +void testScan(); #endif diff --git a/src/scene.cpp b/src/scene.cpp index 415d627..2f912ee 100755 --- a/src/scene.cpp +++ b/src/scene.cpp @@ -9,6 +9,7 @@ #include scene::scene(string filename){ + numMetaballs = 0; cout << "Reading scene from " << filename << " ..." << endl; cout << " " << endl; char* fname = (char*)filename.c_str(); @@ -53,6 +54,9 @@ int scene::loadObject(string objectid){ }else if(strcmp(line.c_str(), "cube")==0){ cout << "Creating new cube..." << endl; newObject.type = CUBE; + }else if(strcmp(line.c_str(), "metaball")==0){ + newObject.type = METABALL; + numMetaballs++; }else{ string objline = line; string name; diff --git a/src/scene.h b/src/scene.h index 9bfa71f..f4d554c 100755 --- a/src/scene.h +++ b/src/scene.h @@ -29,6 +29,7 @@ class scene{ vector objects; vector materials; camera renderCam; + int numMetaballs; }; #endif diff --git a/src/sceneStructs.h b/src/sceneStructs.h index b10f1cf..4afea9b 100755 --- a/src/sceneStructs.h +++ b/src/sceneStructs.h @@ -11,11 +11,17 @@ #include #include -enum GEOMTYPE{ SPHERE, CUBE, MESH }; +enum GEOMTYPE{ SPHERE, CUBE, MESH, METABALL }; struct ray { glm::vec3 origin; glm::vec3 direction; + bool finished; //true if no more bounces needed, false if more bounces needed. + //startX and startY are the starting position of the ray in screenspace. + short startX; + short startY; + char specularBounces; //number of perfect specular bounces + char diffuseBounces; //number of diffuse bounces }; struct geom { @@ -39,6 +45,12 @@ struct staticGeom { cudaMat4 inverseTransform; }; +//an emitter is a wrapper for geometry that emits light +//it just holds an index to let us look up that piece of geometry +struct emitter { + int geomIdx; +}; + struct cameraData { glm::vec2 resolution; glm::vec3 position; diff --git a/src/utilities.cpp b/src/utilities.cpp index 3fd4b73..af26d1c 100755 --- a/src/utilities.cpp +++ b/src/utilities.cpp @@ -76,6 +76,15 @@ glm::mat4 utilityCore::buildTransformationMatrix(glm::vec3 translation, glm::vec return translationMat*rotationMat*scaleMat; } +glm::mat4 utilityCore::buildInverseMatrix(glm::vec3 translation, glm::vec3 rotation, glm::vec3 scale){ + glm::mat4 translationMat = glm::translate(glm::mat4(), -translation); + glm::mat4 rotationMat = glm::rotate(glm::mat4(), rotation.x, glm::vec3(1,0,0)); + rotationMat = rotationMat*glm::rotate(glm::mat4(), rotation.y, glm::vec3(0,1,0)); + rotationMat = rotationMat*glm::rotate(glm::mat4(), rotation.z, glm::vec3(0,0,1)); + glm::mat4 scaleMat = glm::scale(glm::mat4(), 1.0f/scale); + return scaleMat*glm::transpose(rotationMat)*translationMat; +} + cudaMat4 utilityCore::glmMat4ToCudaMat4(glm::mat4 a){ cudaMat4 m; a = glm::transpose(a); m.x = a[0]; diff --git a/src/utilities.h b/src/utilities.h index e23ba1f..7c79f60 100755 --- a/src/utilities.h +++ b/src/utilities.h @@ -20,7 +20,7 @@ #define PI 3.1415926535897932384626422832795028841971 #define TWO_PI 6.2831853071795864769252867665590057683943 #define SQRT_OF_ONE_THIRD 0.5773502691896257645091487805019574556476 -#define E 2.7182818284590452353602874713526624977572 +#define NATURAL_E 2.7182818284590452353602874713526624977572 #define EPSILON .000000001 #define ZERO_ABSORPTION_EPSILON 0.00001 #define RAY_BIAS_AMOUNT 0.0002 @@ -34,6 +34,7 @@ namespace utilityCore { extern cudaMat4 glmMat4ToCudaMat4(glm::mat4 a); extern glm::mat4 cudaMat4ToGlmMat4(cudaMat4 a); extern glm::mat4 buildTransformationMatrix(glm::vec3 translation, glm::vec3 rotation, glm::vec3 scale); + extern glm::mat4 buildInverseMatrix(glm::vec3 translation, glm::vec3 rotation, glm::vec3 scale); extern void printCudaMat4(cudaMat4 m); extern std::string convertIntToString(int number); extern std::istream& safeGetline(std::istream& is, std::string& t); //Thanks to http://stackoverflow.com/a/6089413