├── LICENSE
├── README.md
├── RTRenderer.js
└── Tutorial (Simple).md
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | #Unity Raytraced Renderer
2 | ===
3 | ##Usage
4 | Just by simple attaching this script to any camera, the raytraced renderer will perform it's magic,
5 | It is however noteworthy that this was made in Unity 4 and backwards comppatability is not guaranteed.
6 | This works in both indie and pro, with all features, no ristrictions.
7 | All Textures that are to be rendered must have `Read/Write Enabled` Enabled
8 |
9 | ##Settings
10 | I will briefly explain each setting of the script
11 |
12 | `Real Time` Simple enough, if you want the renderer to do more than 1 render, check this
13 |
14 | `AutoGenerateColliders` Unless you've read the code and know what this dies, keep this one on
15 |
16 | `Smooth Edges` This will make round edges seem rounf and not jagged. It does however decrease performance quite a bit.
17 |
18 | `Single material Only` If your meshes have more than 1 material, and you want them to render, tick this, otherwise it's just a performance boost ;)
19 |
20 | `Use Lighting` Without this everything will be rendered as if it was completely lit on all sides.
21 |
22 | `Resolution` The multiplyer of the resolution to render at. If you have a `100x100` display and it is at `0.1`, it will render at `10x10`. At `2.0` it will render at `200x200`.
23 |
24 | `Max Stack` The maximum number of recursive steps to take. Good numbers: 5-20
25 |
26 | ##Rights
27 | Note that this is a community project. Any commits are welcome! Any feedback is welcome.
28 | I do not care about credit. Tell your friends you made this for all I care :P
29 | Also note that this was started by me: Benproductions1
30 |
31 | ##Contact
32 | If anyone has any questions/comments/remarks feel free to do so on the unity forums page for this project here:
33 | http://forum.unity3d.com/showthread.php?175212
34 |
--------------------------------------------------------------------------------
/RTRenderer.js:
--------------------------------------------------------------------------------
1 | /*
2 | This Script was originally created by (me) Benproductions1
3 | Be advised that it is in no way shape or form not permitted to edit this!
4 | This is designed to be a community project, it will always stay that way!
5 | The Github repository can be found here:
6 | https://github.com/Benproductions1/Unity-Raytracer
7 |
8 | I hope you learn something from this project and/or contribute to it :)
9 |
10 | HOW TO USE!!
11 | If your just here to see my work,
12 | I suggest making a new scene, throwing in some objects
13 | Adding this script to the camera and see what happens
14 |
15 | TIP: if your computer is slow, it will have allot of hang time
16 |
17 | TIP: This raytracing uses the CPU, not the GPU
18 |
19 | TIP: Do not try real time raytracing with a resolution of 1
20 | */
21 |
22 | /*
23 | ---||SETUP||---
24 | */
25 |
26 | import System.IO;
27 |
28 | //Raytracer Settings
29 | var RealTime:boolean = true;
30 | var AutoGenerateColliders:boolean = true;
31 | var SmoothEdges:boolean = true;
32 | var SingleMaterialOnly:boolean = false;
33 | var UseLighting:boolean = true;
34 | var resolution:float = 1;
35 | var MaxStack:int = 2;
36 |
37 | //The render texture
38 | @System.NonSerialized
39 | var screen:Texture2D;
40 |
41 | //The shader used for reflections
42 | private var reflectiveShader:Shader;
43 |
44 | //iteration variables
45 | private var x:int;
46 | private var y:int;
47 |
48 | private var light:Light;
49 | private var tris:int[];
50 | private var tri:int[];
51 |
52 | private var index:int;
53 | private var index2:int;
54 | private var index3:int;
55 |
56 | //temporary variables
57 | private var ray:Ray;
58 | private var direction:Vector3;
59 | private var normal:Vector3;
60 |
61 | private var tmpFloat:float;
62 | private var tmpFloat2:float;
63 |
64 | private var tmpTex:Texture2D;
65 | private var tmpMat:Material;
66 |
67 | private var tmpMeshFilter:MeshFilter;
68 | private var tmpGameObject:GameObject;
69 |
70 | //List variables for optimisation
71 | private var lights:Light[];
72 |
73 | //Collision Mask
74 | private var collisionMask:LayerMask = 1 << 31;
75 |
76 |
77 | /*
78 | ---||INITIALISATION||---
79 | */
80 |
81 | function Start() {
82 | //If the render texture already exists, destroy it!
83 | if (screen) {
84 | Destroy(screen);
85 | }
86 |
87 | //Create a new texture to render to
88 | screen = new Texture2D(Screen.width*resolution, Screen.height*resolution);
89 |
90 | //Find the reflective shader to use (Specular)
91 | reflectiveShader = Shader.Find("Specular");
92 |
93 | if (AutoGenerateColliders) {
94 | //Generate Raytrace Colliders (mesh) for all renderers
95 | for (tmpMeshFilter in FindSceneObjectsOfType(typeof MeshFilter) as MeshFilter[]) {
96 | GenerateColliders(tmpMeshFilter);
97 | }
98 | }
99 |
100 | if (!RealTime) {
101 | //Start Single Ray Trace
102 | RayTrace();
103 | }
104 | }
105 |
106 |
107 | /*
108 | ---||RUNTIME LOOP||---
109 | */
110 |
111 | function Update() {
112 | if (RealTime) {
113 | //Try real time ray tracing
114 | RayTrace();
115 | }
116 | }
117 |
118 | function OnGUI() {
119 | //Draw the rendered image along with an FPS count
120 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), screen);
121 | GUILayout.Label("fps: " + Mathf.Round(1/Time.smoothDeltaTime));
122 | }
123 |
124 | //One full raytrace
125 | function RayTrace():void {
126 | //Find all lights and remember them (optimisation)
127 | lights = FindSceneObjectsOfType(typeof Light) as Light[];
128 |
129 | //Iterate through each pixel
130 | for (x = 0; x < screen.width; x += 1) {
131 | for (y = 0; y < screen.height; y += 1) {
132 | //Trace each pixel and set the return value as the colour
133 | screen.SetPixel(x, y, TracePixel(Vector2(x, y)));
134 | }
135 | }
136 | //Apply changes to the render texture
137 | screen.Apply();
138 | }
139 |
140 | //Raytrace for one pixel
141 | function TracePixel(pos:Vector2):Color {
142 | //Calculate world position of the pixel and start a single Trace
143 | ray = camera.ScreenPointToRay(Vector3(pos.x/resolution, pos.y/resolution, 0));
144 | return TraceRay(ray.origin, ray.direction, 0);
145 | }
146 |
147 | //A Single Trace
148 | function TraceRay(origin:Vector3, direction:Vector3, stack:int):Color {
149 | //Set nessesary temporary local variables
150 | var tmpColor:Color;
151 | var hit:RaycastHit;
152 |
153 | //Check Stack Flow and perform Raycast
154 | if (stack < MaxStack && Physics.Raycast(origin, direction, hit, camera.farClipPlane, collisionMask)) {
155 |
156 | //Perform calculations only if we hit a collider with a parent (error handling)
157 | if (hit.collider && hit.collider.transform.parent) {
158 | //if we have multiple materials and we are checking for multiple materials
159 | if (hit.collider.transform.parent.GetComponent(MeshFilter).mesh.subMeshCount > 1 && !SingleMaterialOnly) {
160 | //find material from triangle index
161 | tmpMat = hit.collider.transform.parent.renderer.materials[GetMatFromTrisInMesh(hit.collider.transform.parent.GetComponent(MeshFilter).mesh, hit.triangleIndex)];
162 | }
163 | else {
164 | //set material to primary material
165 | tmpMat = hit.collider.transform.parent.renderer.material;
166 | }
167 |
168 | //if the material has a texture
169 | if (tmpMat.mainTexture) {
170 | //set the colour to that of the texture coord of the raycast hit
171 | tmpColor = (tmpMat.mainTexture as Texture2D).GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
172 | }
173 | else {
174 | //set the colour to the colour of the material
175 | tmpColor = tmpMat.color;
176 | }
177 |
178 | //Transparent pixel, trace again and add on to colour
179 | if (tmpColor.a < 1) {
180 | tmpColor *= tmpColor.a;
181 | tmpColor += (1-tmpColor.a)*TraceRay(hit.point-hit.normal*0.01, direction, stack+1);
182 | }
183 |
184 | //Surface is reflective, trace reflection and add on to colour
185 | if (tmpMat.shader == reflectiveShader) {
186 | tmpFloat = tmpColor.a*tmpMat.GetFloat("_Shininess");
187 | tmpColor += tmpFloat*TraceRay(hit.point+hit.normal*0.0001, Vector3.Reflect(direction, hit.normal), stack+1);
188 | }
189 |
190 | //Calculate lighting
191 | if (UseLighting) {
192 | //With smooth edges
193 | if (SmoothEdges) {
194 | tmpColor *= TraceLight(hit.point+hit.normal*0.0001, InterpolateNormal(hit.point, hit.normal, hit.collider.transform.parent.GetComponent(MeshFilter).mesh, hit.triangleIndex, hit.transform));
195 | }
196 | //Without smooth edges
197 | else {
198 | tmpColor *= TraceLight(hit.point+hit.normal*0.0001, hit.normal);
199 | }
200 | }
201 |
202 | tmpColor.a = 1;
203 | return tmpColor;
204 | }
205 | else {
206 | //Return Error colour on wierd error
207 | return Color.red;
208 | }
209 | }
210 | else {
211 | //Render Skybox if present, else just blue
212 | if (RenderSettings.skybox) {
213 | //Perform A Skybox Trace
214 | tmpColor = SkyboxTrace(direction, RenderSettings.skybox);
215 |
216 | //Replace alpha with White colour
217 | //for some reason nessesary
218 | tmpColor += Color.white*(1-tmpColor.a)/10;
219 | tmpColor.a = 1;
220 |
221 | return tmpColor;
222 | }
223 | else {
224 | return Color.blue;
225 | }
226 | }
227 | }
228 |
229 | //Convert a direction to a pixel of a cubemap (used only for skyboxes)
230 | function SkyboxTrace(direction:Vector3, skybox:Material):Color {
231 | //Funky stuff I still don't quite get
232 | //If you can explain this, please add comments
233 |
234 | if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y)) {
235 | if (Mathf.Abs(direction.x) > Mathf.Abs(direction.z)) {
236 | if (direction.x < 0) {
237 | return (skybox.GetTexture("_LeftTex") as Texture2D).GetPixelBilinear((-direction.z/-direction.x+1)/2, (direction.y/-direction.x+1)/2);
238 | }
239 | else{
240 | return (skybox.GetTexture("_RightTex") as Texture2D).GetPixelBilinear((direction.z/direction.x+1)/2, (direction.y/direction.x+1)/2);
241 | }
242 | }
243 | else{
244 | if (direction.z < 0) {
245 | return (skybox.GetTexture("_BackTex") as Texture2D).GetPixelBilinear((direction.x/-direction.z+1)/2, (direction.y/-direction.z+1)/2);
246 | }
247 | else{
248 | return (skybox.GetTexture("_FrontTex") as Texture2D).GetPixelBilinear((-direction.x/direction.z+1)/2, (direction.y/direction.z+1)/2);
249 | }
250 | }
251 | }
252 | else if (Mathf.Abs(direction.y) > Mathf.Abs(direction.z)){
253 | if (direction.y < 0) {
254 | return (skybox.GetTexture("_DownTex") as Texture2D).GetPixelBilinear((-direction.x/-direction.y+1)/2, (direction.z/-direction.y+1)/2);
255 | }
256 | else{
257 | return (skybox.GetTexture("_UpTex") as Texture2D).GetPixelBilinear((-direction.x/direction.y+1)/2, (-direction.z/direction.y+1)/2);
258 | }
259 | }
260 | else{
261 | if (direction.z < 0) {
262 | return (skybox.GetTexture("_BackTex") as Texture2D).GetPixelBilinear((direction.x/-direction.z+1)/2, (direction.y/-direction.z+1)/2);
263 | }
264 | else{
265 | return (skybox.GetTexture("_FrontTex") as Texture2D).GetPixelBilinear((-direction.x/direction.z+1)/2, (direction.y/direction.z+1)/2);
266 | }
267 | }
268 | }
269 |
270 | //Returns the material index of a mesh a triangle is using
271 | //Acctually it returns the index of the submesh the triangle is in
272 | function GetMatFromTrisInMesh(mesh:Mesh, trisIndex:int):int {
273 | //get the triangel from the triangle index
274 | tri = [mesh.triangles[trisIndex*3], mesh.triangles[trisIndex*3+1], mesh.triangles[trisIndex*3+2]];
275 |
276 | //Iterate through all submeshes, each submesh has a different material of the same index as the submesh
277 | for (index = 0; index < mesh.subMeshCount; index++) {
278 | //Get submesh trianges
279 | tris = mesh.GetTriangles(index);
280 | //Iterate through all triangles
281 | for (index2 = 0; index2 < tris.length; index2 += 3) {
282 | //Find the same triangle and return the index of the submesh it is in
283 | if (tris[index2] == tri[0] && tris[index2+1] == tri[1] && tris[index2+2] == tri[2]) {
284 | return index;
285 | }
286 | }
287 | }
288 | }
289 |
290 | //Interpolates between the 3 normals of a triangle given the point
291 | function InterpolateNormal(point:Vector3, normal:Vector3, mesh:Mesh, trisIndex:int, trans:Transform):Vector3 {
292 | //find the indexes of each verticie of the triange
293 | index = mesh.triangles[trisIndex*3];
294 | index2 = mesh.triangles[trisIndex*3+1];
295 | index3 = mesh.triangles[trisIndex*3+2];
296 |
297 | //temporary variable used for re-arrenement
298 | var tmpIndex:int;
299 |
300 | //Find the distance between each verticie and the point
301 | var d1:float = Vector3.Distance(mesh.vertices[index], point);
302 | var d2:float = Vector3.Distance(mesh.vertices[index2], point);
303 | var d3:float = Vector3.Distance(mesh.vertices[index3], point);
304 |
305 | //compare and rearrange the verticie index so that index is the one furthest away from the point
306 | if (d2 > d1 && d2 > d3) {
307 | tmpIndex = index;
308 | index = index2;
309 | index2 = tmpIndex;
310 | }
311 | else if (d3 > d1 && d3 > d2) {
312 | tmpIndex = index;
313 | index = index3;
314 | index3 = tmpIndex;
315 | tmpIndex = index2;
316 | index2 = index3;
317 | index3 = tmpIndex;
318 | }
319 |
320 | //Find the point along the line between the 2 other verticies that the ray from the furthest verticies through the point intersects
321 | //Using Plane raycasting
322 | //Generate Plane
323 | var plane:Plane = Plane(trans.TransformPoint(mesh.vertices[index2]), trans.TransformPoint(mesh.vertices[index3])+normal, trans.TransformPoint(mesh.vertices[index3])-normal);
324 | //Renerate Ray
325 | ray = Ray(trans.TransformPoint(mesh.vertices[index]), (point - trans.TransformPoint(mesh.vertices[index])).normalized);
326 |
327 | //Intersect Ray and Plane
328 | if (!plane.Raycast(ray, tmpFloat)) {
329 | //Something went terribly wrong... damn it
330 | Debug.Log("This Shouldn't EVER happen");
331 | return normal;
332 | }
333 |
334 | //Do the interpolation :D
335 | //If you really wanna see how this works, just google it
336 | //It's too complicated to explain here
337 | var point2:Vector3 = ray.origin+ray.direction*tmpFloat;
338 | var normal2:Vector3 = Vector3.Lerp(trans.TransformDirection(mesh.normals[index2]), trans.TransformDirection(mesh.normals[index3]), Vector3.Distance(trans.TransformPoint(mesh.vertices[index2]), point2)/Vector3.Distance(trans.TransformPoint(mesh.vertices[index2]), trans.TransformPoint(mesh.vertices[index3])));
339 | var normal3:Vector3 = Vector3.Lerp(normal2, trans.TransformDirection(mesh.normals[index]), Vector3.Distance(point2, point)/Vector3.Distance(point2, trans.TransformPoint(mesh.vertices[index])));
340 | //return interpolated normal
341 | return normal3;
342 | }
343 |
344 | //Calculate the lighting of a point
345 | function TraceLight(pos:Vector3, normal:Vector3):Color {
346 | //set nessesary temporary provate variables
347 | //set default light to ambient lighting
348 | var tmpColor:Color = RenderSettings.ambientLight;
349 |
350 | //Iterate through all lights in the scene
351 | //lights is computer once per render (optimisation)
352 | for (light in lights) {
353 | //Only calculate lighting if the light is on
354 | if (light.enabled) {
355 | //trace the light and add it to the light colour
356 | tmpColor += LightTrace(light, pos, normal);
357 | }
358 | }
359 |
360 | //return light colour at that point
361 | return tmpColor;
362 | }
363 |
364 | //Trace lighting for one light at one spot
365 | function LightTrace(light:Light, pos:Vector3, normal:Vector3):Color {
366 | var hit:RaycastHit;
367 |
368 | //If light is directional (easy)
369 | //Just trace in the opposite direction
370 | if (light.type == LightType.Directional) {
371 | direction = light.transform.TransformDirection(Vector3.back);
372 | return transparancyTrace(Color(light.intensity, light.intensity, light.intensity)*(1-Quaternion.Angle(Quaternion.identity, Quaternion.FromToRotation(normal, direction))/90), pos, direction, Mathf.Infinity);
373 | }
374 |
375 | //If light is point light (medium)
376 | //Just trace towards it, if within range
377 | //also apply linear falloff according to distance and range
378 | if (light.type == LightType.Point) {
379 | if (Vector3.Distance(pos, light.transform.position) <= light.range) {
380 | direction = (light.transform.position - pos).normalized;
381 | tmpFloat = (light.range-Vector3.Distance(pos, light.transform.position))/light.range*light.intensity;
382 | return transparancyTrace(Color(tmpFloat, tmpFloat, tmpFloat)*(1-Quaternion.Angle(Quaternion.identity, Quaternion.FromToRotation(normal, direction))/90), pos, direction, Vector3.Distance(light.transform.position, pos));
383 | }
384 | }
385 |
386 | //If light is spot light (Hard)
387 | //Do the same as a point light, but also get the angle from direction towards the light to the opposite direction of the light
388 | //If this angle is more than the spot angle, no light
389 | //else apply linear fall off according to this angle and spot angle
390 | if (light.type == LightType.Spot) {
391 | if (Vector3.Distance(pos, light.transform.position) <= light.range) {
392 | direction = (light.transform.position - pos).normalized;
393 | if (Vector3.Angle(direction, -light.transform.forward) < light.spotAngle) {
394 | tmpFloat = (light.range-Vector3.Distance(pos, light.transform.position))/light.range*light.intensity;
395 | tmpFloat *= 1 - Vector3.Angle(direction, -light.transform.forward)/light.spotAngle;
396 | return transparancyTrace(Color(tmpFloat, tmpFloat, tmpFloat)*(1-Quaternion.Angle(Quaternion.identity, Quaternion.FromToRotation(normal, direction))/90), pos, direction, Vector3.Distance(light.transform.position, pos));
397 | }
398 | }
399 | }
400 |
401 | //If the light is of any other type, do not calculate any lighting
402 | return Color.black;
403 | }
404 |
405 | //This traces for transparent shadows
406 | //Instead of tracing once to see if an object was hit, it does a RaycastAll
407 | //And Iterates through all objects, gets the pixel colour of that raycast hit
408 | //Then multiples it by the inverse of the alpha of that pixel
409 | function transparancyTrace(col:Color, pos:Vector3, dir:Vector3, dist:float) {
410 | var tmpColor = col;
411 | var hits:RaycastHit[];
412 | var hit:RaycastHit;
413 |
414 | //Raycast throug everything, returning a list of hits, instead of just the closest
415 | hits = Physics.RaycastAll(pos, dir, dist, collisionMask);
416 | //Iterate through each hit
417 | for (hit in hits) {
418 | //Same as in TraceRay, it gets the pixel colour of that hit point
419 | //So no point in commenting on this
420 | if (hit.collider.transform.parent.GetComponent(MeshFilter).mesh.subMeshCount > 1 && !SingleMaterialOnly) {
421 | tmpMat = hit.collider.transform.parent.renderer.materials[GetMatFromTrisInMesh(hit.collider.transform.parent.GetComponent(MeshFilter).mesh, hit.triangleIndex)];
422 | }
423 | else {
424 | tmpMat = hit.collider.transform.parent.renderer.material;
425 | }
426 |
427 | //Apply colour transformation according to pixels alpha value
428 | if (tmpMat.mainTexture) {
429 | tmpTex = (tmpMat.mainTexture as Texture2D);
430 | tmpColor *= 1-tmpTex.GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y).a;
431 | }
432 | else {
433 | tmpColor *= 1-tmpMat.color.a;
434 | }
435 | }
436 | //return resulting colour
437 | return tmpColor;
438 | }
439 |
440 | //Some stupid unnessesary and unused stuff to save the rendered texture to file
441 | //really not worth explaining
442 | function SaveTextureToFile(texture:Texture2D, fileName):void {
443 | var bytes = texture.EncodeToPNG();
444 | var file = new File.Open(Application.dataPath + "/" + fileName,FileMode.Create);
445 | BinaryWriter(file).Write(bytes);
446 | file.Close();
447 | }
448 |
449 | //Generates colliders used for raytracing for one GamObject
450 | //I wish I could add this to Instantiate!!
451 | function GenerateColliders(go:GameObject):GameObject {
452 | //Generate colliders only if there is a mesh filter
453 | if (go.GetComponent(MeshFilter)) {
454 | GenerateColliders(go.GetComponent(MeshFilter));
455 | }
456 | //return same gameObject
457 | return go;
458 | }
459 |
460 | //Generate Colliders for a MeshFilter
461 | function GenerateColliders(mf:MeshFilter):GameObject {
462 | //Create Object
463 | tmpGameObject = GameObject("MeshRender");
464 | //Set Defaults and copy settings
465 | tmpGameObject.transform.parent = mf.transform;
466 | tmpGameObject.AddComponent(MeshFilter).mesh = mf.mesh;
467 | tmpGameObject.AddComponent(MeshCollider).sharedMesh = mf.mesh;
468 | //Make collider a trigger
469 | tmpGameObject.collider.isTrigger = true;
470 | //reset positioning
471 | tmpGameObject.transform.localPosition = Vector3.zero;
472 | tmpGameObject.transform.localScale = Vector3.one;
473 | tmpGameObject.transform.rotation = mf.transform.rotation;
474 | //set layer
475 | tmpGameObject.layer = 31;
476 | //return MeshFilter
477 | return tmpGameObject;
478 | }
479 |
--------------------------------------------------------------------------------
/Tutorial (Simple).md:
--------------------------------------------------------------------------------
1 | Building a RayTracer in Unity
2 | =============================
3 | ##Intro
4 | Hello, and again, welcome to the "Building a RayTracer in Unity" tutorial.
5 | Here are a couple things you should probably know:
6 |
7 | - Everything will be statically typed... even function
8 | - I will post the full script after every chapter
9 | - This is made in Unity 4 indie. I have no guarantees it will work anywhere else
10 | - If at any time during this tutorial you get lost on something, please take the time to look it up, before you ask me
11 | - If you do not feel comfortable doing some basic programing, please learn before you come here :)
12 |
13 | Note that throughout this tutorial I am assuming that you are already aware of the basics behind raytracing.I also assume you have basic knowledge in programming in Unityscript.
14 | Note that I will not teach you scripting, nor will I answer any questions related to basic scripting problems, as there are enough tutorials out there that already do that. I am solely focusing on Raytracing in Unity.
15 |
16 | ##Part 1: Black and White
17 | The very first thing we should get working, is just getting unity to render something on the screen. For the time being, we are not going to worry what we are rendering, but more on how we are going to render it.
18 |
19 | Lets begin with the start of the script: Defining the variables.
20 | The Only variable we need as of yet is the texture we want to render too
21 | This textur emust be of type `Texture2D` as this is the only texture type which allows reading and writing.
22 | ```javascript
23 | private var renderTexture:Texture2D;
24 | ```
25 |
26 | Now we must also create a new texture and assign it to our new variable
27 | We should do this in the `Awake` function, as this is the earliest point where we have access to the screen height
28 | ```javascript
29 | //Create render texture with screen size
30 | function Awake():void {
31 | renderTexture = new Texture2D(Screen.height, Screen.width);
32 | }
33 | ```
34 |
35 | Now that we have the foundations, lets write the function that will do 1 full render
36 | We should split this "render" into 2 parts, as we will need the other part later
37 | Lets start with a function that loops through all the pixels
38 |
39 | ```javascript
40 | //The function that renders the entire scene to a texture
41 | function RayTrace():void {
42 | for (var x:int = 0; x < renderTexture.width; x += 1) {
43 | for (var y:int = 0; y < renderTexture.height; y += 1) {
44 |
45 | //Now that we have an x/y value for each pixel, we need to make that into a 3d ray
46 | //according to the camera we are attached to
47 | var ray:Ray = camera.ScreenPointToRay(Vector3(x, y, 0));
48 |
49 | //Now lets call a function with this ray and apply it's return value to the pixel we are on
50 | //We will define this function afterwards
51 | renderTexture.SetPixel(x, y, TraceRay(ray));
52 | }
53 | }
54 |
55 | //We also need to apply the changes we have made to the texture
56 | //This is a part that can cause much pain and frustraction if forgotten
57 | //So don't forget ;)
58 | renderTexture.Apply();
59 | }
60 | ```
61 |
62 | Next thing we have to do is get the rendering that's done for each pixel down.
63 | To do this I will be using the inbuilt `Raycast` function.
64 | I assume you already know how to use this function.
65 | For now all we want to do is find out if at the current pixel there is or isn't an object.
66 | In the first case, we will return white else black. It's that simple.
67 |
68 | ```javascript
69 | //Trace a Ray for a singple point
70 | function TraceRay(ray:Ray):Color {
71 |
72 | if (Physics.Raycast(ray)) {
73 | return Color.white;
74 | }
75 |
76 | return Color.black;
77 | }
78 | ```
79 |
80 | Before we can test what we have written though, we need to actually display the texture on the screen.
81 | I preffer always doing this with `GUI` elements, specifically `DrawTexture` as it fits perfectly
82 | We also have to call our `RayTrace` function. Lets put it in `Start` for now
83 |
84 | ```javascript
85 | function Start():void {
86 | RayTrace();
87 | }
88 |
89 | //Draw the render
90 | function OnGUI():void {
91 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), renderTexture);
92 | }
93 | ```
94 |
95 | Now we have a "working" raytracer. If we open up a new scene, place a couple of objects with colliders attached, attach our script to the camera and run it, we will see exactly what we had hoped for, Black and White:
96 |
97 | 
98 |
99 | Thats it for part 1, here is the code so far:
100 | ```javascript
101 | private var renderTexture:Texture2D;
102 |
103 | //Create render texture with screen size
104 | function Awake() {
105 | renderTexture = new Texture2D(Screen.width, Screen.height);
106 | }
107 |
108 | //Do one raytrace when we start playing
109 | function Start() {
110 | RayTrace();
111 | }
112 |
113 | //Draw the render
114 | function OnGUI() {
115 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), renderTexture);
116 | }
117 |
118 | //The function that renders the entire scene to a texture
119 | function RayTrace():void {
120 | for (var x:int = 0; x < renderTexture.width; x += 1) {
121 | for (var y:int = 0; y < renderTexture.height; y += 1) {
122 |
123 | //Now that we have an x/y value for each pixel, we need to make that into a 3d ray
124 | //according to the camera we are attached to
125 | var ray:Ray = camera.ScreenPointToRay(Vector3(x, y, 0));
126 |
127 | //Now lets call a function with this ray and apply it's return value to the pixel we are on
128 | //We will define this function afterwards
129 | renderTexture.SetPixel(x, y, TraceRay(ray));
130 | }
131 | }
132 |
133 | renderTexture.Apply();
134 | }
135 |
136 | //Trace a Ray for a singple point
137 | function TraceRay(ray:Ray):Color {
138 |
139 | if (Physics.Raycast(ray)) {
140 | return Color.white;
141 | }
142 |
143 | return Color.black;
144 | }
145 | ```
146 |
147 | ##Part 1.5: Additional Features
148 | As you might have noticed, it takes Unity some time to even render a simple scene with the code so far. It is certainly not a good idea to try and do this in real time, unless we change the resolution.
149 | I thought it might be a good Idea to add in some special features with this raytracer, more specifically the ability to render "real-time" and also the ability to "set" the resolution.
150 | Honestly features you should be able to add yourself, but I'll do it anyway.
151 | This will be a quite short part, but I will go over quickly adding these small features:
152 |
153 |
154 | First we need to add 2 more variables, ones accessible to the user:
155 |
156 | ```javascript
157 | //weather or not to render in real time
158 | var RealTime:boolean = false;
159 |
160 | //How much of our screen resolution we render at
161 | var RenderResolution:float = 1;
162 | ```
163 |
164 | Lets first make the nessesary changes for adding real time:
165 |
166 | ```javascript
167 | //In Start we only render if we are not real time
168 | function Start() {
169 | if (!RealTime) {
170 | RayTrace();
171 | }
172 | }
173 |
174 | //In the new Update, we only render if we are real time
175 | function Update() {
176 | if (RealTime) {
177 | RayTrace();
178 | }
179 | }
180 | ```
181 |
182 | Now lets change the `renderTexture` depending on the resolution we set,
183 | As well as cast the ray inversly relative to the resolution
184 |
185 | ```javascript
186 | //Create render texture with screen size with resolution
187 | function Awake() {
188 | renderTexture = new Texture2D(Screen.width*RenderResolution, Screen.height*RenderResolution);
189 | }
190 |
191 | //Now in our nested for loops
192 | var ray:Ray = camera.ScreenPointToRay(Vector3(x/RenderResolution, y/RenderResolution, 0));
193 | ```
194 |
195 | Now that we've added these simple features, lets move on to part 2
196 | And as always, heres all the code:
197 |
198 | ```javascript
199 | //weather or not to render in real time
200 | var RealTime:boolean = false;
201 |
202 | //How much of our screen resolution we render at
203 | var RenderResolution:float = 1;
204 |
205 | private var renderTexture:Texture2D;
206 |
207 | //Create render texture with screen size with resolution
208 | function Awake() {
209 | renderTexture = new Texture2D(Screen.width*RenderResolution, Screen.height*RenderResolution);
210 | }
211 |
212 | //Do one raytrace when we start playing
213 | function Start() {
214 | if (!RealTime) {
215 | RayTrace();
216 | }
217 | }
218 |
219 | //Real Time Rendering
220 | function Update() {
221 | if (RealTime) {
222 | RayTrace();
223 | }
224 | }
225 |
226 | //Draw the render
227 | function OnGUI() {
228 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), renderTexture);
229 | }
230 |
231 | //The function that renders the entire scene to a texture
232 | function RayTrace():void {
233 | for (var x:int = 0; x < renderTexture.width; x += 1) {
234 | for (var y:int = 0; y < renderTexture.height; y += 1) {
235 |
236 | //Now that we have an x/y value for each pixel, we need to make that into a 3d ray
237 | //according to the camera we are attached to
238 | var ray:Ray = camera.ScreenPointToRay(Vector3(x/RenderResolution, y/RenderResolution, 0));
239 |
240 | //Now lets call a function with this ray and apply it's return value to the pixel we are on
241 | //We will define this function afterwards
242 | renderTexture.SetPixel(x, y, TraceRay(ray));
243 | }
244 | }
245 |
246 | renderTexture.Apply();
247 | }
248 |
249 | //Trace a Ray for a singple point
250 | function TraceRay(ray:Ray):Color {
251 |
252 | if (Physics.Raycast(ray)) {
253 | return Color.white;
254 | }
255 |
256 | return Color.black;
257 | }
258 | ```
259 |
260 | ##Part 2: Colors and Textures
261 | How about we now move away from just rendering black and white and let's use the color of the material of whatever we hit.
262 | The Main thing we are going to work on from now on, is going to be our `TraceRay` function, so assume from now on all code is written in there unless specifically stated otherwise:
263 |
264 | ```javascript
265 | //We fist have to create the hit variable
266 | var hit:RaycastHit;
267 |
268 | //Now we parse it in as another argument
269 | if (Physics.Raycast(ray, hit)) {
270 | //now we can get all kinds of information out of the "hit"
271 | //like hit.distance, hit.point, all of which will be usefull later on
272 | }
273 |
274 | return Color.black;
275 | ```
276 |
277 | Next we should get the material we hit, then get it's color and return it:
278 |
279 | ```javascript
280 | var hit:RaycastHit;
281 | if (Physics.Raycast(ray, hit)) {
282 |
283 | //Create a temporary reference variable (useful later on)
284 | var mat:Material;
285 |
286 | //Get the material attached to the renderer of the collider we hit
287 | //if we used hit.transform instead, we would encounter bugs with rigidbodys
288 | //so we use collider
289 | mat = hit.collider.renderer.material;
290 |
291 | //return the main color of that material
292 | return mat.color;
293 |
294 | }
295 | return Color.black;
296 | ```
297 |
298 | Congratulations, if we now make different materials for the objects and assign them different colours, our raytraced renderer will properly shade them.
299 | But just shading is quite boring. How about we add texturing while we're at it?
300 | One of the awesome things about Unity Raycasting, is that the raycast hit also returns a UV coordinate.
301 | This makes it very simple for us to also add texturing:
302 |
303 | ```javascript
304 | var hit:RaycastHit;
305 |
306 | if (Physics.Raycast(ray, hit)) {
307 | var mat:Material;
308 | mat = hit.collider.renderer.material;
309 |
310 | //if the material has a texture
311 | if (mat.mainTexture) {
312 | //return the color of the pixel at the pixel coordinate of the hit
313 | return (mat.mainTexture as Texture2D).GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
314 | }
315 | else {
316 | //return the material color
317 | return mat.color;
318 | }
319 | }
320 | return Color.black;
321 | ```
322 |
323 | One note to make, is that this will only work if the texture of that material is read-write accessible.
324 | This can be set in the import options of that texture.
325 | Another note, is that to get the texture coordinates, you have to have a `MeshCollider` on the object.
326 | When looking at this, and thinking about the things we want to add later, it seems like it will be quite a pain (and a lot of `if` statements) for all possible values of the return color.
327 | Instead of doing what we are doing right now, lets make our lives easier and have 1 color we change throught that function?
328 |
329 | ```javascript
330 | //The color this function will return
331 | var returnColor:Color = Color.black;
332 |
333 | var hit:RaycastHit;
334 |
335 | if (Physics.Raycast(ray, hit)) {
336 | var mat:Material;
337 | mat = hit.collider.renderer.material;
338 |
339 | //Instead of returning or settings the color, we simply add the color
340 | if (mat.mainTexture) {
341 | returnColor += (mat.mainTexture as Texture2D).GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
342 | }
343 | else {
344 | returnColor += mat.color;
345 | }
346 | }
347 |
348 | //At the end, we simple return the color
349 | return returnColor
350 | ```
351 |
352 | Yay! We now have textured and shaded objects.
353 | Lets see what it looks like so far?
354 |
355 | 
356 |
357 | Before we begin to add lighting, as promised, I will paste the full code again
358 |
359 | ```javascript
360 | //weather or not to render in real time
361 | var RealTime:boolean = false;
362 |
363 | //How much of our screen resolution we render at
364 | var RenderResolution:float = 1;
365 |
366 | private var renderTexture:Texture2D;
367 |
368 | //Create render texture with screen size with resolution
369 | function Awake() {
370 | renderTexture = new Texture2D(Screen.width*RenderResolution, Screen.height*RenderResolution);
371 | }
372 |
373 | //Do one raytrace when we start playing
374 | function Start() {
375 | if (!RealTime) {
376 | RayTrace();
377 | }
378 | }
379 |
380 | //Real Time Rendering
381 | function Update() {
382 | if (RealTime) {
383 | RayTrace();
384 | }
385 | }
386 |
387 | //Draw the render
388 | function OnGUI() {
389 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), renderTexture);
390 | }
391 |
392 | //The function that renders the entire scene to a texture
393 | function RayTrace():void {
394 | for (var x:int = 0; x < renderTexture.width; x += 1) {
395 | for (var y:int = 0; y < renderTexture.height; y += 1) {
396 |
397 | //Now that we have an x/y value for each pixel, we need to make that into a 3d ray
398 | //according to the camera we are attached to
399 | var ray:Ray = camera.ScreenPointToRay(Vector3(x/RenderResolution, y/RenderResolution, 0));
400 |
401 | //Now lets call a function with this ray and apply it's return value to the pixel we are on
402 | //We will define this function afterwards
403 | renderTexture.SetPixel(x, y, TraceRay(ray));
404 | }
405 | }
406 |
407 | renderTexture.Apply();
408 | }
409 |
410 | //Trace a Ray for a singple point
411 | function TraceRay(ray:Ray):Color {
412 | //The color we change throught the function
413 | var returnColor:Color = Color.black;
414 |
415 | var hit:RaycastHit;
416 |
417 | if (Physics.Raycast(ray, hit)) {
418 |
419 | //The material of the object we hit
420 | var mat:Material;
421 |
422 | //Set the used material
423 | mat = hit.collider.renderer.material;
424 |
425 | //if the material has a texture
426 | if (mat.mainTexture) {
427 | //return the color of the pixel at the pixel coordinate of the hit
428 | returnColor += (mat.mainTexture as Texture2D).GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
429 | }
430 | else {
431 | //return the material color
432 | returnColor += mat.color;
433 | }
434 | }
435 |
436 | //The color of this pixel
437 | return returnColor;
438 | }
439 | ```
440 |
441 | ##Part 3: Finally some Light
442 |
443 | A very important part in any Raytraced renderer is always the way it handles light.
444 | In this part I will go over the basics of implementing directional lighting in our renderer.
445 |
446 | To do this, we need a function that asseses the light color, given a certain point.
447 | The first major information we need for this, are all the lights in the scene.
448 | For optimisation purposes, we will only do a full search for all lights before we render:
449 |
450 | ```javascript
451 | //We create a new variable to hold all lights
452 | private var lights:Light[];
453 |
454 | //In our RayTrace Function
455 | //We find all lights
456 | function RayTrace():void {
457 | lights = FindSceneObjectsOfType(typeof(Light)) as Light[];
458 | }
459 | ```
460 |
461 | Now that we have access to all the lights, we begin writing the function to assess the lighting at a certain point.
462 | Just for nicer looking code, we should break this up into 2 functions.
463 |
464 | ```javascript
465 | //Trace a single point for all lights
466 | function TraceLight(pos:Vector3):Color {
467 | //We set the starting light to that of the render settings ambient light
468 | //This makes it easier to predict how it will look when we render it
469 | var returnColor:Color = RenderSettings.ambientLight;
470 |
471 | //We loop through all the lights and perform a light addition with each
472 | for (var light:Light in lights) {
473 | if (light.enabled) {
474 | //Add the light that this light source casts to the color of this point
475 | returnColor += LightTrace(light, pos);
476 | }
477 | }
478 |
479 | //return the color of this point according to lighting
480 | return returnColor;
481 | }
482 |
483 | //Trace a single point for a single light
484 | function LightTrace(light:Light, pos:Vector3):Color {
485 | //Only trace if it's a directional light
486 | if (light.type == LightType.Directional) {
487 |
488 | /*
489 | This needs some explaining:
490 | All we do here, is cast a ray indefinately in the opposite direction
491 | Of the way the directional light is facing. If this ray hits an object, it means
492 | that no light is recieved from this light source at this point,
493 | so we return black.
494 | If this ray doesn not hit, it means this point is recieving light from this light source
495 | so we return the color of the light, multiplied by it's intensity
496 | */
497 | if (Physics.Raycast(pos, -light.transform.forward)) {
498 | return Color.black;
499 | }
500 | return light.color*light.intensity;
501 | }
502 | }
503 | ```
504 |
505 | Before we can test this, we also need to add the `TraceLight` function into our `TraceRay` calculation, so that we take into account lighting for every point we hit.
506 | This is a relatively easy part, all we have to do is multiply the `returnColor` by the "light" at that point:
507 |
508 | ```javascript
509 | //After we apply the material color
510 | //We apply lighting
511 | returnColor *= TraceLight(hit.point);
512 | ```
513 |
514 | And thats it! We now have shadows.
515 |
516 | 
517 |
518 | As you probably have noticed while playing around with the directional lighting we now have,
519 | That there is one major problem with this: White error spots...
520 |
521 | The problem is that we are tracing the light from the exact point on the surface.
522 | Due to inaccuracies of raycasting (due to floating point precision) there is no guarantee that the ray will intersect with the surface if it originates from it.
523 | The only way to counter this problem, is to trace our light from a point very slightly off the surface, using the normal:
524 |
525 | ```javascript
526 | //Instead of just tracing from the point
527 | //we add a small value of the hit normal to it
528 | returnColor *= TraceLight(hit.point + hit.normal*0.0001);
529 | ```
530 |
531 | This tiny little change will make all the difference.
532 |
533 | 
534 |
535 | And here is all the code so far:
536 |
537 | ```javascript
538 | //weather or not to render in real time
539 | var RealTime:boolean = false;
540 |
541 | //How much of our screen resolution we render at
542 | var RenderResolution:float = 1;
543 |
544 | private var renderTexture:Texture2D;
545 | private var lights:Light[];
546 |
547 | //Create render texture with screen size with resolution
548 | function Awake() {
549 | renderTexture = new Texture2D(Screen.width*RenderResolution, Screen.height*RenderResolution);
550 | }
551 |
552 | //Do one raytrace when we start playing
553 | function Start() {
554 | if (!RealTime) {
555 | RayTrace();
556 | }
557 | }
558 |
559 | //Real Time Rendering
560 | function Update() {
561 | if (RealTime) {
562 | RayTrace();
563 | }
564 | }
565 |
566 | //Draw the render
567 | function OnGUI() {
568 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), renderTexture);
569 | }
570 |
571 | //The function that renders the entire scene to a texture
572 | function RayTrace():void {
573 | //Gather all lights
574 | lights = FindSceneObjectsOfType(typeof(Light)) as Light[];
575 |
576 | for (var x:int = 0; x < renderTexture.width; x += 1) {
577 | for (var y:int = 0; y < renderTexture.height; y += 1) {
578 |
579 | //Now that we have an x/y value for each pixel, we need to make that into a 3d ray
580 | //according to the camera we are attached to
581 | var ray:Ray = camera.ScreenPointToRay(Vector3(x/RenderResolution, y/RenderResolution, 0));
582 |
583 | //Now lets call a function with this ray and apply it's return value to the pixel we are on
584 | //We will define this function afterwards
585 | renderTexture.SetPixel(x, y, TraceRay(ray));
586 | }
587 | }
588 |
589 | renderTexture.Apply();
590 | }
591 |
592 | //Trace a Ray for a singple point
593 | function TraceRay(ray:Ray):Color {
594 | //The color we change throught the function
595 | var returnColor:Color = Color.black;
596 |
597 | var hit:RaycastHit;
598 |
599 | if (Physics.Raycast(ray, hit)) {
600 |
601 | //The material of the object we hit
602 | var mat:Material;
603 |
604 | //Set the used material
605 | mat = hit.collider.renderer.material;
606 |
607 | //if the material has a texture
608 | if (mat.mainTexture) {
609 | //return the color of the pixel at the pixel coordinate of the hit
610 | returnColor += (mat.mainTexture as Texture2D).GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
611 | }
612 | else {
613 | //return the material color
614 | returnColor += mat.color;
615 | }
616 |
617 | returnColor *= TraceLight(hit.point + hit.normal*0.0001);
618 | }
619 |
620 | //The color of this pixel
621 | return returnColor;
622 | }
623 |
624 | //Trace a single point for all lights
625 | function TraceLight(pos:Vector3):Color {
626 | //Set starting light to that of the render settings
627 | var returnColor:Color = RenderSettings.ambientLight;
628 |
629 | //We loop through all the lights and perform a light addition with each
630 | for (var light:Light in lights) {
631 | if (light.enabled) {
632 | //Add the light that this light source casts to the color of this point
633 | returnColor += LightTrace(light, pos);
634 | }
635 | }
636 | return returnColor;
637 | }
638 |
639 | //Trace a single point for a single light
640 | function LightTrace(light:Light, pos:Vector3):Color {
641 | //Trace the directional light
642 | if (light.type == LightType.Directional) {
643 | if (Physics.Raycast(pos, -light.transform.forward)) {
644 | return Color.black;
645 | }
646 | return light.color*light.intensity;
647 | }
648 | }
649 | ```
650 |
651 | ##Part 4: Automatic Collision Setup
652 |
653 | So far we have always relied on whoever set up the scene to have put mesh colliders on everything.
654 | We have also been relying on there not being any functionality besides our renderer.
655 | The problem is in some cases, we just want to throw some things in the scene, run it and have it work.
656 |
657 | This part has nothing to do with raytracing, but it will make your life easier later on.
658 | Feel free to just skip to the end and copy the code.
659 |
660 | What we need to do is add our own colliders to all the objects in the scene.
661 | Put these colliders on a different layer (so they don't effect anything).
662 | And then only raycast this layer.
663 |
664 | Lets start by writing the function that does this automatically:
665 |
666 | ```javascript
667 | function GenerateColliders():void {
668 |
669 | //Loop through all mesh filters
670 | for (var mf:MeshFilter in FindSceneObjectsOfType(typeof MeshFilter) as MeshFilter[]) {
671 |
672 | //Only if they have a MeshRenderer attached
673 | //They might not... who knows?
674 | if (mf.GetComponent(MeshRenderer)) {
675 | //Create a new object we will use for rendering
676 | var tmpGO:GameObject = GameObject("RTRMeshRenderer");
677 |
678 | //Add the Collider with the same mesh as the MeshFilter
679 | tmpGO.AddComponent(MeshCollider).sharedMesh = mf.mesh;
680 |
681 | //Make it a child of the MeshFilter
682 | tmpGO.transform.parent = mf.transform;
683 |
684 | //Make this new object the same dimentions as the meshFilter
685 | tmpGO.transform.localPosition = Vector3.zero;
686 | tmpGO.transform.localScale = Vector3.one;
687 | tmpGO.transform.localRotation = Quaternion.identity;
688 |
689 | //Make it a trigger (to avoid Physx)
690 | tmpGO.collider.isTrigger = true;
691 |
692 | //Set it's layer
693 | tmpGO.layer = 31;
694 | }
695 | }
696 | }
697 | ```
698 |
699 | We then have to make the changes so that we only raycast that layer, and we also generate the coliders when we `Start`.
700 |
701 | ```javascript
702 | //Collision Mask
703 | private var collisionMask:LayerMask = 1 << 31;
704 |
705 | function Start() {
706 | //Generate Colliders for all objects
707 | GenerateColliders();
708 |
709 | if (!RealTime) {
710 | RayTrace();
711 | }
712 | }
713 |
714 | //In the TraceRay Function
715 | if (Physics.Raycast(ray, hit, collisionMask)) {
716 | //Also we need to access the parent of the object to be able to get rendering information
717 | mat = hit.collider.transform.parent.renderer.material;
718 |
719 | //In the LightTrace function
720 | if (Physics.Raycast(pos, -light.transform.forward, collisionMask)) {
721 | ```
722 |
723 | And there we have it! Automatic collider setup. Now we can even run physics with no problems!
724 |
725 | As always, here is the complete code:
726 |
727 | ```javascript
728 | //weather or not to render in real time
729 | var RealTime:boolean = false;
730 |
731 | //How much of our screen resolution we render at
732 | var RenderResolution:float = 1;
733 |
734 | private var renderTexture:Texture2D;
735 | private var lights:Light[];
736 |
737 | //Collision Mask
738 | private var collisionMask:LayerMask = 1 << 31;
739 |
740 | //Create render texture with screen size with resolution
741 | function Awake() {
742 | renderTexture = new Texture2D(Screen.width*RenderResolution, Screen.height*RenderResolution);
743 | }
744 |
745 | //Do one raytrace when we start playing
746 | function Start() {
747 | GenerateColliders();
748 |
749 | if (!RealTime) {
750 | RayTrace();
751 | }
752 | }
753 |
754 | //Real Time Rendering
755 | function Update() {
756 | if (RealTime) {
757 | RayTrace();
758 | }
759 | }
760 |
761 | //Draw the render
762 | function OnGUI() {
763 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), renderTexture);
764 | }
765 |
766 | //The function that renders the entire scene to a texture
767 | function RayTrace():void {
768 | //Gather all lights
769 | lights = FindSceneObjectsOfType(typeof(Light)) as Light[];
770 |
771 | for (var x:int = 0; x < renderTexture.width; x += 1) {
772 | for (var y:int = 0; y < renderTexture.height; y += 1) {
773 |
774 | //Now that we have an x/y value for each pixel, we need to make that into a 3d ray
775 | //according to the camera we are attached to
776 | var ray:Ray = camera.ScreenPointToRay(Vector3(x/RenderResolution, y/RenderResolution, 0));
777 |
778 | //Now lets call a function with this ray and apply it's return value to the pixel we are on
779 | //We will define this function afterwards
780 | renderTexture.SetPixel(x, y, TraceRay(ray));
781 | }
782 | }
783 |
784 | renderTexture.Apply();
785 | }
786 |
787 | //Trace a Ray for a singple point
788 | function TraceRay(ray:Ray):Color {
789 | //The color we change throught the function
790 | var returnColor:Color = Color.black;
791 |
792 | var hit:RaycastHit;
793 |
794 | if (Physics.Raycast(ray, hit, Mathf.Infinity, collisionMask)) {
795 |
796 | //The material of the object we hit
797 | var mat:Material;
798 |
799 | //Set the used material
800 | mat = hit.collider.transform.parent.renderer.material;
801 |
802 | //if the material has a texture
803 | if (mat.mainTexture) {
804 | //return the color of the pixel at the pixel coordinate of the hit
805 | returnColor += (mat.mainTexture as Texture2D).GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
806 | }
807 | else {
808 | //return the material color
809 | returnColor += mat.color;
810 | }
811 |
812 | returnColor *= TraceLight(hit.point + hit.normal*0.0001);
813 | }
814 |
815 | //The color of this pixel
816 | return returnColor;
817 | }
818 |
819 | //Trace a single point for all lights
820 | function TraceLight(pos:Vector3):Color {
821 | //Set starting light to that of the render settings
822 | var returnColor:Color = RenderSettings.ambientLight;
823 |
824 | //We loop through all the lights and perform a light addition with each
825 | for (var light:Light in lights) {
826 | if (light.enabled) {
827 | //Add the light that this light source casts to the color of this point
828 | returnColor += LightTrace(light, pos);
829 | }
830 | }
831 | return returnColor;
832 | }
833 |
834 | //Trace a single point for a single light
835 | function LightTrace(light:Light, pos:Vector3):Color {
836 | //Trace the directional light
837 | if (light.type == LightType.Directional) {
838 | if (Physics.Raycast(pos, -light.transform.forward, Mathf.Infinity, collisionMask)) {
839 | return Color.black;
840 | }
841 | return light.color*light.intensity;
842 | }
843 | }
844 |
845 | //Generate colliders for all objects
846 | function GenerateColliders():void {
847 | //Loop through all mesh filters
848 | for (var mf:MeshFilter in FindSceneObjectsOfType(typeof MeshFilter) as MeshFilter[]) {
849 | if (mf.GetComponent(MeshRenderer)) {
850 | //Create a new object we will use for rendering
851 | //And make it the same as the MeshFilter
852 | var tmpGO:GameObject = GameObject("RTRMeshRenderer");
853 | tmpGO.AddComponent(MeshCollider).sharedMesh = mf.mesh;
854 | tmpGO.transform.parent = mf.transform;
855 | tmpGO.transform.localPosition = Vector3.zero;
856 | tmpGO.transform.localScale = Vector3.one;
857 | tmpGO.transform.localRotation = Quaternion.identity;
858 |
859 | tmpGO.collider.isTrigger = true;
860 | tmpGO.layer = 31;
861 | }
862 | }
863 | }
864 | ```
865 |
866 | ##Pasrt 5: Shading with normals
867 |
868 | As you might have noticed, when we render something like a sphere,
869 | we have some obvious differences between how Unity renders it, and how we render it.
870 | The main difference is, that Unity determines the light at a point depending on the Normal of that surface.
871 |
872 | The way we can determine a multiplyer of our light color at that point, is by looking at a "dot product"
873 |
874 | A "Dot Product" is a mathamatical function, that allows us to determin the relationship between 2 directional vectors.
875 | Lets say we have 2 vectors that are equal. The dot product would equal 1. If they are perpendicular, it's 0. And if they are opposite, the dot product is -1.
876 | As you have probably noticed, this is exactly what we need, but it is also an optimisation, as we do not need to calculate lighting, if the dot product is negative.
877 | The way a dot product is calculated in Unity, is by using the inbuilt `Vector3` function: `Dot`.
878 |
879 | The first thing we need to do is parse both our lighting functions, the normal of the raycast hit:
880 |
881 | ```javascript
882 | //In TraceRay
883 | returnColor *= TraceLight(hit.point + hit.normal*0.0001, hit.normal);
884 |
885 | function TraceLight(pos:Vector3, normal:Vector3):Color {
886 | //When we call the other function:
887 | returnColor += LightTrace(light, pos, normal);
888 |
889 | function LightTrace(light:Light, pos:Vector3, normal:Vector3):Color {
890 | ```
891 |
892 | In our `LightTrace` function, we can then calculate the dot and act accordingly:
893 |
894 | ```javascript
895 | //Trace the directional light
896 | if (light.type == LightType.Directional) {
897 | //calculate the dot product
898 | var dot:float = Vector3.Dot(-light.transform.forward, normal);
899 |
900 | //only perform lighting calculations, if the dot is more than 0
901 | if (dot > 0) {
902 | if (Physics.Raycast(pos, -light.transform.forward, Mathf.Infinity, collisionMask)) {
903 | return Color.black;
904 | }
905 |
906 | //return the color multiplied by the dot
907 | return light.color*light.intensity*dot;
908 | }
909 | //the face is facing away from the light, so no light is on it
910 | return Color.black;
911 | }
912 | ```
913 |
914 | After running this you might think: Hey... it's an improvement... but now everything looks kind of blocky.
915 | AKA there is no smoothness in along the edges of the triangles that make a sphere.
916 |
917 | What you are reffering to is called Normal Interpolation. It's a very complex, computationally expensive calculation, that interpolates between the normals in a triangle to produce smooth looking surfaces.
918 | Most likely I will not be going over that in this tutorial, because of it's complexity. If you want an implementation of it, fell free to look at the github repository of my own Raytracer I built before making this tutorial.
919 |
920 | Now we have proper (fast) normal shading, isn't it awesome!?
921 |
922 | 
923 |
924 | And now the code.... again...
925 |
926 | ```javascript
927 | //weather or not to render in real time
928 | var RealTime:boolean = false;
929 |
930 | //How much of our screen resolution we render at
931 | var RenderResolution:float = 1;
932 |
933 | private var renderTexture:Texture2D;
934 | private var lights:Light[];
935 |
936 | //Collision Mask
937 | private var collisionMask:LayerMask = 1 << 31;
938 |
939 | //Create render texture with screen size with resolution
940 | function Awake() {
941 | renderTexture = new Texture2D(Screen.width*RenderResolution, Screen.height*RenderResolution);
942 | }
943 |
944 | //Do one raytrace when we start playing
945 | function Start() {
946 | GenerateColliders();
947 |
948 | if (!RealTime) {
949 | RayTrace();
950 | }
951 | }
952 |
953 | //Real Time Rendering
954 | function Update() {
955 | if (RealTime) {
956 | RayTrace();
957 | }
958 | }
959 |
960 | //Draw the render
961 | function OnGUI() {
962 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), renderTexture);
963 | }
964 |
965 | //The function that renders the entire scene to a texture
966 | function RayTrace():void {
967 | //Gather all lights
968 | lights = FindSceneObjectsOfType(typeof(Light)) as Light[];
969 |
970 | for (var x:int = 0; x < renderTexture.width; x += 1) {
971 | for (var y:int = 0; y < renderTexture.height; y += 1) {
972 |
973 | //Now that we have an x/y value for each pixel, we need to make that into a 3d ray
974 | //according to the camera we are attached to
975 | var ray:Ray = camera.ScreenPointToRay(Vector3(x/RenderResolution, y/RenderResolution, 0));
976 |
977 | //Now lets call a function with this ray and apply it's return value to the pixel we are on
978 | //We will define this function afterwards
979 | renderTexture.SetPixel(x, y, TraceRay(ray));
980 | }
981 | }
982 |
983 | renderTexture.Apply();
984 | }
985 |
986 | //Trace a Ray for a singple point
987 | function TraceRay(ray:Ray):Color {
988 | //The color we change throught the function
989 | var returnColor:Color = Color.black;
990 |
991 | var hit:RaycastHit;
992 |
993 | if (Physics.Raycast(ray, hit, Mathf.Infinity, collisionMask)) {
994 |
995 | //The material of the object we hit
996 | var mat:Material;
997 |
998 | //Set the used material
999 | mat = hit.collider.transform.parent.renderer.material;
1000 |
1001 | //if the material has a texture
1002 | if (mat.mainTexture) {
1003 | //return the color of the pixel at the pixel coordinate of the hit
1004 | returnColor += (mat.mainTexture as Texture2D).GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
1005 | }
1006 | else {
1007 | //return the material color
1008 | returnColor += mat.color;
1009 | }
1010 |
1011 | returnColor *= TraceLight(hit.point + hit.normal*0.0001, hit.normal);
1012 | }
1013 |
1014 | //The color of this pixel
1015 | return returnColor;
1016 | }
1017 |
1018 | //Trace a single point for all lights
1019 | function TraceLight(pos:Vector3, normal:Vector3):Color {
1020 | //Set starting light to that of the render settings
1021 | var returnColor:Color = RenderSettings.ambientLight;
1022 |
1023 | //We loop through all the lights and perform a light addition with each
1024 | for (var light:Light in lights) {
1025 | if (light.enabled) {
1026 | //Add the light that this light source casts to the color of this point
1027 | returnColor += LightTrace(light, pos, normal);
1028 | }
1029 | }
1030 | return returnColor;
1031 | }
1032 |
1033 | //Trace a single point for a single light
1034 | function LightTrace(light:Light, pos:Vector3, normal:Vector3):Color {
1035 | //Trace the directional light
1036 | if (light.type == LightType.Directional) {
1037 | //calculate the dot product
1038 | var dot:float = Vector3.Dot(-light.transform.forward, normal);
1039 |
1040 | //only perform lighting calculations, if the dot is more than 0
1041 | if (dot > 0) {
1042 | if (Physics.Raycast(pos, -light.transform.forward, Mathf.Infinity, collisionMask)) {
1043 | return Color.black;
1044 | }
1045 |
1046 | return light.color*light.intensity*dot;
1047 | }
1048 | return Color.black;
1049 | }
1050 | }
1051 |
1052 | //Generate colliders for all objects
1053 | function GenerateColliders():void {
1054 | //Loop through all mesh filters
1055 | for (var mf:MeshFilter in FindSceneObjectsOfType(typeof MeshFilter) as MeshFilter[]) {
1056 | if (mf.GetComponent(MeshRenderer)) {
1057 | //Create a new object we will use for rendering
1058 | //And make it the same as the MeshFilter
1059 | var tmpGO:GameObject = GameObject("RTRMeshRenderer");
1060 | tmpGO.AddComponent(MeshCollider).sharedMesh = mf.mesh;
1061 | tmpGO.transform.parent = mf.transform;
1062 | tmpGO.transform.localPosition = Vector3.zero;
1063 | tmpGO.transform.localScale = Vector3.one;
1064 | tmpGO.transform.localRotation = Quaternion.identity;
1065 |
1066 | tmpGO.collider.isTrigger = true;
1067 | tmpGO.layer = 31;
1068 | }
1069 | }
1070 | }
1071 | ```
1072 |
1073 | ##Part 6: More Lighting
1074 |
1075 | So now we have a raytracer that can do many things, but there are some key aspects that we have missed.
1076 | More specifically the different types of lights Unity offers.
1077 |
1078 | In this part, I will be going over how to add Point and Spot light support into the Raytracer.
1079 | Note that in this part all code will be in the `LigthTrace` function.
1080 |
1081 | Lets start with Point as it's easier.
1082 | ###Point Lights
1083 | First we have to consider all the aspects of a point light:
1084 |
1085 | - Range
1086 | - Intensity
1087 | - Color
1088 |
1089 | Intensity and Color we have already implemented sucessfully in our Directional lighting, but Range adds a whole new consept.
1090 | No longer will we have either a light at full brightness or in the shadow, but interpolation between fully bright and in the shadows.
1091 | We also have to consider that our Raycast can not be infinite, because the light source has an origin, unlike a directional light.
1092 |
1093 | Lets start by calculating the distance from our point to the light.
1094 | Because both point and spot are so similar, I will make some optimisations for each.
1095 |
1096 | ```javascript
1097 | function LightTrace(light:Light, pos:Vector3, normal:Vector3):Color {
1098 | if (light.type == LightType.Directional) {
1099 | }
1100 | else {
1101 | //calculate the distance between our point and the light
1102 | var distance:float = Vector3.Distance(pos, light.transform.position);
1103 |
1104 | //No matter if the light is point or spot, it still has a range and we account for that
1105 | if (distance < light.range) {
1106 |
1107 | //Now we have to check for which type of light it is
1108 | if (light.type == LightType.Point) {
1109 | }
1110 | }
1111 |
1112 | //we are outside of the lights range, so no need for light
1113 | return Color.black;
1114 | }
1115 | }
1116 | ```
1117 |
1118 | While we are at it, lets also account for the new normal shading, which is again the same for both light types.
1119 | As an optimisation I will create 2 new variables as we will need both later.
1120 |
1121 | ```javascript
1122 | function LightTrace(light:Light, pos:Vector3, normal:Vector3):Color {
1123 | //Because we have already defined dot in here, we should define it at the top of our funstion and only use it inside
1124 | //If you do not do this, you will recieve errors
1125 | var dot:float;
1126 |
1127 | if (light.type == LightType.Directional) {
1128 | //We also need to change this line, to remove errors it would generate
1129 | dot = Vector3.Dot(-light.transform.forward, normal);
1130 | }
1131 | else {
1132 | //Lets calculate the direction from our point, to the light.
1133 | //we will need this for both the normal shading and also shadow checking
1134 | var direction:Vector3 = (light.transform.position - pos).normalized;
1135 |
1136 | //Now we calculate the dot product of the direction and the normal.
1137 | dot = Vector3.Dot(normal, direction);
1138 |
1139 | var distance:float = Vector3.Distance(pos, light.transform.position);
1140 |
1141 | //We also check if our dot is larger than 0 here
1142 | if (distance < light.range && dot > 0) {
1143 | if (light.type == LightType.Point) {
1144 | }
1145 | }
1146 | return Color.black;
1147 | }
1148 | }
1149 | ```
1150 |
1151 | Now we move on to the logic behind what color to return:
1152 | It's acctually quite simple.
1153 | If a raycast from our point, in the direction we calculated, with the maximum distance we calculated hit's anything, we return black as usual.
1154 | Else we return the color of the light multiplied by it's intensity and by the dot (as per usual), but then we also multiply it by the percentage of distance we are from the light source origin.
1155 |
1156 | If you don't understand it, I don't blame you... Heres the formula for our new multiplier: `1 - light.range/distance`.
1157 |
1158 | So all we have to do is:
1159 |
1160 | ```javascript
1161 | function LightTrace(light:Light, pos:Vector3, normal:Vector3):Color {
1162 | if (light.type == LightType.Directional) {
1163 | }
1164 | else {
1165 | var direction:Vector3 = (light.transform.position - pos).normalized;
1166 | dot = Vector3.Dot(normal, direction);
1167 | var distance:float = Vector3.Distance(pos, light.transform.position);
1168 | if (distance < light.range && dot > 0) {
1169 | if (light.type == LightType.Point) {
1170 | //Raycast as we described
1171 | if (Physics.Raycast(pos, direction, distance, collisionMask)) {
1172 | return Color.black;
1173 | }
1174 |
1175 | //Amd then our new formula
1176 | return light.color*light.intensity*dot*(1 - light.range/distance);
1177 |
1178 | }
1179 | }
1180 | return Color.black;
1181 | }
1182 | }
1183 | ```
1184 |
1185 | And there we have it... we now have working point lights!
1186 |
1187 | ###Spot Lights
1188 |
1189 | Lets do this in the same fassion that we did with point lights.
1190 | Fist lets consider all aspects of a spot light:
1191 |
1192 | - Spot Angle
1193 | - Range
1194 | - Intensity
1195 | - Color
1196 |
1197 | Like before we have 1 new thing to work on. Although it might not be exactly the same way Unity does it, but let's consider a spot light to be a point light, where there is a limited angle of exposure. This means, that the dot product of the direction to the light source and the backward direction of the light must be smaller than the Spot angle transformed in some way.
1198 | If we consider that dot product would range from 1 to 0 with 180 degrees of the lights forward direction.
1199 | Therefore, the point is within the spot light, if the `dot > 1 - light.spotAngle/180`.
1200 |
1201 | But just finding weather or not the point is within the spot is not enough. We also have to interpolate between the edge of the spot angle and the dot. So as well as considering distance when we calculate the color, we have a new multiplier: `(dot/(1 - light.spotAngle/180))`
1202 |
1203 | Lets implement this. As we already have most of the information present, this should be easy:
1204 |
1205 | ```javascript
1206 | function LightTrace(light:Light, pos:Vector3, normal:Vector3):Color {
1207 | if (light.type == LightType.Directional) {
1208 | }
1209 | else {
1210 | if (distance < light.range && dot > 0) {
1211 | if (light.type == LightType.Point) {
1212 | }
1213 | //Lets check weather we are in the spot or not
1214 | else if (light.type == LightType.Spot) {
1215 | //Get the dot product between the backwards direction of the light and our direction to it
1216 | var dot2:float = Vector3.Dot(-light.transform.forward, normal);
1217 |
1218 | //Only do spot lighting if we are within the spot light
1219 | if (dot2 < (1 - light.spotAngle/180)) {
1220 | if (Physics.Raycast(pos, direction, distance, collisionMask)) {
1221 | return Color.black;
1222 | }
1223 |
1224 | //We multiply by the multiplier we defined above
1225 | return light.color*light.intensity*dot*(1 - light.range/distance)*((dot2/(1 - light.spotAngle/180)));
1226 | }
1227 | }
1228 | }
1229 | return Color.black;
1230 | }
1231 | }
1232 | ```
1233 |
1234 | And there we go! We now have working spot lights. They don't work in quite the same way as the ones in Unity, but at least they are spot lights.
1235 |
1236 | Lets look at both of them in action:
1237 |
1238 | 
1239 |
1240 | On that note, here is also the current code:
1241 |
1242 | ```javascript
1243 | //weather or not to render in real time
1244 | var RealTime:boolean = false;
1245 |
1246 | //How much of our screen resolution we render at
1247 | var RenderResolution:float = 1;
1248 |
1249 | private var renderTexture:Texture2D;
1250 | private var lights:Light[];
1251 |
1252 | //Collision Mask
1253 | private var collisionMask:LayerMask = 1 << 31;
1254 |
1255 | //Create render texture with screen size with resolution
1256 | function Awake() {
1257 | renderTexture = new Texture2D(Screen.width*RenderResolution, Screen.height*RenderResolution);
1258 | }
1259 |
1260 | //Do one raytrace when we start playing
1261 | function Start() {
1262 | GenerateColliders();
1263 |
1264 | if (!RealTime) {
1265 | RayTrace();
1266 | RTRenderer.SaveTextureToFile(renderTexture, "lolies.png");
1267 | }
1268 | }
1269 |
1270 | //Real Time Rendering
1271 | function Update() {
1272 | if (RealTime) {
1273 | RayTrace();
1274 | }
1275 | }
1276 |
1277 | //Draw the render
1278 | function OnGUI() {
1279 | GUI.DrawTexture(Rect(0, 0, Screen.width, Screen.height), renderTexture);
1280 | }
1281 |
1282 | //The function that renders the entire scene to a texture
1283 | function RayTrace():void {
1284 | //Gather all lights
1285 | lights = FindSceneObjectsOfType(typeof(Light)) as Light[];
1286 |
1287 | for (var x:int = 0; x < renderTexture.width; x += 1) {
1288 | for (var y:int = 0; y < renderTexture.height; y += 1) {
1289 |
1290 | //Now that we have an x/y value for each pixel, we need to make that into a 3d ray
1291 | //according to the camera we are attached to
1292 | var ray:Ray = camera.ScreenPointToRay(Vector3(x/RenderResolution, y/RenderResolution, 0));
1293 |
1294 | //Now lets call a function with this ray and apply it's return value to the pixel we are on
1295 | //We will define this function afterwards
1296 | renderTexture.SetPixel(x, y, TraceRay(ray));
1297 | }
1298 | }
1299 |
1300 | renderTexture.Apply();
1301 | }
1302 |
1303 | //Trace a Ray for a singple point
1304 | function TraceRay(ray:Ray):Color {
1305 | //The color we change throught the function
1306 | var returnColor:Color = Color.black;
1307 |
1308 | var hit:RaycastHit;
1309 |
1310 | if (Physics.Raycast(ray, hit, Mathf.Infinity, collisionMask)) {
1311 |
1312 | //The material of the object we hit
1313 | var mat:Material;
1314 |
1315 | //Set the used material
1316 | mat = hit.collider.transform.parent.renderer.material;
1317 |
1318 | //if the material has a texture
1319 | if (mat.mainTexture) {
1320 | //return the color of the pixel at the pixel coordinate of the hit
1321 | returnColor += (mat.mainTexture as Texture2D).GetPixelBilinear(hit.textureCoord.x, hit.textureCoord.y);
1322 | }
1323 | else {
1324 | //return the material color
1325 | returnColor += mat.color;
1326 | }
1327 |
1328 | returnColor *= TraceLight(hit.point + hit.normal*0.0001, hit.normal);
1329 | }
1330 |
1331 | //The color of this pixel
1332 | return returnColor;
1333 | }
1334 |
1335 | //Trace a single point for all lights
1336 | function TraceLight(pos:Vector3, normal:Vector3):Color {
1337 | //Set starting light to that of the render settings
1338 | var returnColor:Color = RenderSettings.ambientLight;
1339 |
1340 | //We loop through all the lights and perform a light addition with each
1341 | for (var light:Light in lights) {
1342 | if (light.enabled) {
1343 | //Add the light that this light source casts to the color of this point
1344 | returnColor += LightTrace(light, pos, normal);
1345 | }
1346 | }
1347 | return returnColor;
1348 | }
1349 |
1350 | //Trace a single point for a single light
1351 | function LightTrace(light:Light, pos:Vector3, normal:Vector3):Color {
1352 | var dot:float;
1353 |
1354 | //Trace the directional light
1355 | if (light.type == LightType.Directional) {
1356 | //calculate the dot product
1357 | dot = Vector3.Dot(-light.transform.forward, normal);
1358 |
1359 | //only perform lighting calculations, if the dot is more than 0
1360 | if (dot > 0) {
1361 | if (Physics.Raycast(pos, -light.transform.forward, Mathf.Infinity, collisionMask)) {
1362 | return Color.black;
1363 | }
1364 |
1365 | return light.color*light.intensity*dot;
1366 | }
1367 | return Color.black;
1368 | }
1369 | else {
1370 | var direction:Vector3 = (light.transform.position - pos).normalized;
1371 | dot = Vector3.Dot(normal, direction);
1372 | var distance:float = Vector3.Distance(pos, light.transform.position);
1373 | if (distance < light.range && dot > 0) {
1374 | if (light.type == LightType.Point) {
1375 | //Raycast as we described
1376 | if (Physics.Raycast(pos, direction, distance, collisionMask)) {
1377 | return Color.black;
1378 | }
1379 | return light.color*light.intensity*dot*(1 - distance/light.range);
1380 | }
1381 | //Lets check weather we are in the spot or not
1382 | else if (light.type == LightType.Spot) {
1383 | var dot2:float = Vector3.Dot(-light.transform.forward, direction);
1384 | if (dot2 > (1 - light.spotAngle/180)) {
1385 | if (Physics.Raycast(pos, direction, distance, collisionMask)) {
1386 | return Color.black;
1387 | }
1388 |
1389 | //We multiply by the multiplier we defined above
1390 | return light.color*light.intensity*dot*(1 - distance/light.range)*((dot2/(1 - light.spotAngle/180)));
1391 | }
1392 | }
1393 | }
1394 | return Color.black;
1395 | }
1396 | }
1397 |
1398 | //Generate colliders for all objects
1399 | function GenerateColliders():void {
1400 | //Loop through all mesh filters
1401 | for (var mf:MeshFilter in FindSceneObjectsOfType(typeof MeshFilter) as MeshFilter[]) {
1402 | if (mf.GetComponent(MeshRenderer)) {
1403 | //Create a new object we will use for rendering
1404 | //And make it the same as the MeshFilter
1405 | var tmpGO:GameObject = GameObject("RTRMeshRenderer");
1406 | tmpGO.AddComponent(MeshCollider).sharedMesh = mf.mesh;
1407 | tmpGO.transform.parent = mf.transform;
1408 | tmpGO.transform.localPosition = Vector3.zero;
1409 | tmpGO.transform.localScale = Vector3.one;
1410 | tmpGO.transform.localRotation = Quaternion.identity;
1411 |
1412 | tmpGO.collider.isTrigger = true;
1413 | tmpGO.layer = 31;
1414 | }
1415 | }
1416 | }
1417 | ```
1418 |
1419 | ##Conclusion
1420 |
1421 | After quite a long time, I have finally finished this tutorial. I hope it was at least of some use to you.
1422 | Although I myself have written a way more advanced Raytraced Renderer than the one I wrote for this tutorial, It was definately fun. If you have any questions, feel free to hit me up on the Unity Forums.
1423 |
1424 | My name is Benproductions1
1425 | Have a nice day
1426 |
1427 | Unity Forums:
1428 | http://forum.unity3d.com/members/45364-Benproductions1
1429 | http://forum.unity3d.com/threads/178992-RayTracing-Tutorial-Full-(Simple)
1430 |
1431 | My RayTracer:
1432 | https://github.com/Benproductions1/Unity-Raytracer
1433 |
--------------------------------------------------------------------------------