diff options
author | Laszlo Agocs <laszlo.agocs@theqtcompany.com> | 2015-04-17 10:53:25 +0200 |
---|---|---|
committer | Laszlo Agocs <laszlo.agocs@theqtcompany.com> | 2015-04-17 09:43:36 +0000 |
commit | 5051c63b3b818f5fb0ed9f92e74b916ea9d4e723 (patch) | |
tree | c44cd5f423d8e6a8217e7f7557ed9cd79c136bf6 | |
parent | 6d073d4e070790d4e9ef707a9deef975e9f70695 (diff) |
Long live QtQuickCL!
Change-Id: I16954f50c631441189dd450980da2c3266a68c71
Reviewed-by: Andy Nichols <andy.nichols@theqtcompany.com>
38 files changed, 3850 insertions, 0 deletions
diff --git a/.qmake.conf b/.qmake.conf new file mode 100644 index 0000000..ed2d45e --- /dev/null +++ b/.qmake.conf @@ -0,0 +1,5 @@ +load(qt_build_config) + +MODULE_VERSION = 5.5.0 + +CMAKE_MODULE_TESTS = - diff --git a/LICENSE.GPL b/LICENSE.GPL new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/LICENSE.GPL @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<http://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<http://www.gnu.org/philosophy/why-not-lgpl.html>. diff --git a/LICENSE.LGPLv3 b/LICENSE.LGPLv3 new file mode 100644 index 0000000..8fbb743 --- /dev/null +++ b/LICENSE.LGPLv3 @@ -0,0 +1,173 @@ + GNU LESSER GENERAL PUBLIC LICENSE + + The Qt Toolkit is Copyright (C) 2015 The Qt Company Ltd. + Contact: http://www.qt.io/licensing/ + + You may use, distribute and copy the Qt GUI Toolkit under the terms of + GNU Lesser General Public License version 3, which is displayed below. + +------------------------------------------------------------------------- + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/> +Everyone is permitted to copy and distribute verbatim copies of this +licensedocument, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + +0. Additional Definitions. + + As used herein, “this License” refers to version 3 of the GNU Lesser +General Public License, and the “GNU GPL” refers to version 3 of the +GNU General Public License. + + “The Library” refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An “Application” is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A “Combined Work” is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the “Linked +Version”. + + The “Minimal Corresponding Source” for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The “Corresponding Application Code” for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + +2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort + to ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + +3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this + license document. + +4. Combined Works. + + You may convey a Combined Work under terms of your choice that, taken +together, effectively do not restrict modification of the portions of +the Library contained in the Combined Work and reverse engineering for +debugging such modifications, if you also do each of the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this + license document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of + this License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with + the Library. A suitable mechanism is one that (a) uses at run + time a copy of the Library already present on the user's + computer system, and (b) will operate properly with a modified + version of the Library that is interface-compatible with the + Linked Version. + + e) Provide Installation Information, but only if you would + otherwise be required to provide such information under section 6 + of the GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the Application + with a modified version of the Linked Version. (If you use option + 4d0, the Installation Information must accompany the Minimal + Corresponding Source and Corresponding Application Code. If you + use option 4d1, you must provide the Installation Information in + the manner specified by section 6 of the GNU GPL for conveying + Corresponding Source.) + +5. Combined Libraries. + + You may place library facilities that are a work based on the Library +side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities, conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of + it is a work based on the Library, and explaining where to find + the accompanying uncombined form of the same work. + +6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +as you received it specifies that a certain numbered version of the +GNU Lesser General Public License “or any later version” applies to +it, you have the option of following the terms and conditions either +of that published version or of any later version published by the +Free Software Foundation. If the Library as you received it does not +specify a version number of the GNU Lesser General Public License, +you may choose any version of the GNU Lesser General Public License +ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the Library. + diff --git a/README.md b/README.md new file mode 100644 index 0000000..5cca20d --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +QtQuickCL - Write kernels, not boilerplate + +QtQuickCL is a research module for Qt 5 that enables easily creating Qt Quick +items that execute OpenCL kernels and use OpenGL resources as their input or +output. The functionality is minimal but powerful. + +For example, a Qt Quick item executing an OpenCL kernel on a texture provider, +meaning an Image element or even an entire sub-tree of the Qt Quick scene, and +rendering the resulting OpenGL texture gets reduced to the following: + + static const char *openclSrc = + "__kernel void Kernel(__read_only image2d_t imgIn, __write_only image2d_t imgOut) {\n" + ... + + class CLRunnable : public QQuickCLImageRunnable + { + public: + CLRunnable(QQuickCLItem *item) + : QQuickCLImageRunnable(item) + { + m_clProgram = item->buildProgram(openclSrc); + m_clKernel = clCreateKernel(m_clProgram, "Kernel", 0); + } + + ~CLRunnable() { + clReleaseKernel(m_clKernel); + clReleaseProgram(m_clProgram); + } + + void runKernel(cl_mem inImage, cl_mem outImage, const QSize &size) Q_DECL_OVERRIDE { + clSetKernelArg(m_clKernel, 0, sizeof(cl_mem), &inImage); + clSetKernelArg(m_clKernel, 1, sizeof(cl_mem), &outImage); + const size_t workSize[] = { size_t(size.width()), size_t(size.height()) }; + clEnqueueNDRangeKernel(commandQueue(), m_clKernel, 2, 0, workSize, 0, 0, 0, 0); + } + + private: + cl_program m_clProgram; + cl_kernel m_clKernel; + }; + + class CLItem : public QQuickCLItem + { + Q_OBJECT + Q_PROPERTY(QQuickItem *source READ source WRITE setSource) + + public: + CLItem() : m_source(0) { } + + QQuickCLRunnable *createCL() Q_DECL_OVERRIDE { return new CLRunnable(this); } + + QQuickItem *source() const { return m_source; } + void setSource(QQuickItem *source) { m_source = source; update(); } + + private: + QQuickItem *m_source; + }; + +All the CL-GL interop, including the selection of the correct CL platform and +device, is taken care of by the module. The QQuickCLItem - QQuickCLRunnable +split ensures easy and safe CL and GL resource management even when threaded +rendering is in use. + +Besides the minimal and lightweight framework, examples are provided for the +following common use cases: + + * GL texture -> GL texture (image processing, i.e. ShaderEffect but with CL) + + * GL texture -> arbitrary data that gets visualized through Qt Quick + (f.ex. histogram) + + * Non-GL data -> GL buffer with vertex data which is used in OpenGL rendering + without any additional readbacks or copies (e.g. particle simulation) + +The intention for these is not merely to test and demo the classes, but to serve +as a reference for integrating Qt Quick and OpenCL and to help getting started +with CL development. diff --git a/config.tests/opencl/main.cpp b/config.tests/opencl/main.cpp new file mode 100644 index 0000000..25bf33c --- /dev/null +++ b/config.tests/opencl/main.cpp @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifdef Q_OS_OSX +#include <OpenCL/opencl.h> +#else +#include <CL/opencl.h> +#endif + +int main(int argc, char** argv) +{ + cl_uint size; + clGetPlatformIDs(0, 0, &size); + clCreateImage2D(0, CL_MEM_READ_WRITE, 0, 640, 480, 0, 0, 0); + + cl_gl_object_type objectType = CL_GL_OBJECT_BUFFER; + clGetGLObjectInfo(0, &objectType, 0); + clEnqueueAcquireGLObjects(0, 0, 0, 0, 0, 0); + + return 0; +} diff --git a/config.tests/opencl/opencl.pro b/config.tests/opencl/opencl.pro new file mode 100644 index 0000000..3a6e9d4 --- /dev/null +++ b/config.tests/opencl/opencl.pro @@ -0,0 +1,12 @@ +SOURCES += main.cpp +CONFIG -= qt +CONFIG += console + +osx { + LIBS += -framework OpenCL + DEFINES += Q_OS_OSX +} + +unix: !osx: LIBS += -lOpenCL + +win32:!winrt:!wince*: LIBS += -lopengl32 -lOpenCL diff --git a/examples/examples.pro b/examples/examples.pro new file mode 100644 index 0000000..8ec7ac4 --- /dev/null +++ b/examples/examples.pro @@ -0,0 +1,2 @@ +TEMPLATE = subdirs +SUBDIRS += quickcl diff --git a/examples/quickcl/histogram/histogram.cl b/examples/quickcl/histogram/histogram.cl new file mode 100644 index 0000000..de97c2d --- /dev/null +++ b/examples/quickcl/histogram/histogram.cl @@ -0,0 +1,57 @@ +// Based on https://code.google.com/p/opencl-book-samples/source/browse/trunk/src/Chapter_14/histogram + +#pragma OPENCL EXTENSION cl_khr_local_int32_base_atomics : enable + +constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST; + +kernel void histogram(image2d_t img, int num_pixels_per_workitem, global uint *buf) +{ + int local_size = get_local_size(0) * get_local_size(1); + int item_offset = get_local_id(0) + get_local_id(1) * get_local_size(0); + local uint tmp[256]; + + int i = 0, j = 256; + do { + if (item_offset < j) + tmp[item_offset + i] = 0; + j -= local_size; + i += local_size; + } while (j > 0); + + barrier(CLK_LOCAL_MEM_FENCE); + + int x, image_width = get_image_width(img), image_height = get_image_height(img); + for (i = 0, x = get_global_id(0); i < num_pixels_per_workitem; ++i, x += get_global_size(0)) { + if (x < image_width && get_global_id(1) < image_height) { + float4 clr = read_imagef(img, sampler, (int2)(x, get_global_id(1))); + if (clr.w > 0.99f) { + float v = (clr.x + clr.y + clr.z) / 3.0f; + atom_inc(&tmp[convert_ushort_sat(min(v, 1.0f) * 255.0f)]); + } + } + } + + barrier(CLK_LOCAL_MEM_FENCE); + + int group_offset = (get_group_id(0) + get_group_id(1) * get_num_groups(0)) * 256; + i = 0; + j = 256; + do { + if (item_offset < j) + buf[group_offset + item_offset + i] = tmp[item_offset + i]; + j -= local_size; + i += local_size; + } while (j > 0); +} + +kernel void sum_histogram(global uint *buf, int num_groups, global uint *result) +{ + int idx = get_global_id(0) + get_group_id(0); + uint v = 0; + int group_offset = 0, n = num_groups; + while (--n >= 0) { + v += buf[group_offset + idx]; + group_offset += 256; + } + result[idx] = v; +} diff --git a/examples/quickcl/histogram/histogram.cpp b/examples/quickcl/histogram/histogram.cpp new file mode 100644 index 0000000..6ba0b65 --- /dev/null +++ b/examples/quickcl/histogram/histogram.cpp @@ -0,0 +1,318 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// Demonstrates the texture-to-data use case where the results of the +// computation are exposed to QML and visualized using Qt Quick items. + +#include <QGuiApplication> +#include <QQuickView> +#include <QQmlEngine> +#include <QQuickCLItem> +#include <QQuickCLImageRunnable> +#include <QAbstractListModel> + +static bool profile = false; + +class HistogramModel : public QAbstractListModel +{ + Q_OBJECT + +public: + Q_INVOKABLE uint get(int idx) const { return h[idx]; } + + void setHistogram(const QVector<uint> &histogram) { + emit beginResetModel(); + h = histogram; + emit endResetModel(); + } + + int rowCount(const QModelIndex &) const Q_DECL_OVERRIDE { + return h.count(); + } + + QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE { + if (index.isValid() && index.row() < h.count() && role == Qt::UserRole + 1) + return h[index.row()]; + return QVariant(); + } + + QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE { + QHash<int, QByteArray> roles; + roles[Qt::UserRole + 1] = "value"; + return roles; + } + +private: + QVector<uint> h; +}; + +class CLRunnable; + +class CLItem : public QQuickCLItem +{ + Q_OBJECT + Q_PROPERTY(QQuickItem *source READ source WRITE setSource NOTIFY sourceChanged) + Q_PROPERTY(QAbstractItemModel *result READ result NOTIFY resultChanged) + +public: + CLItem() : m_source(0), m_result(new HistogramModel) { } + ~CLItem() { delete m_result; } + + QQuickCLRunnable *createCL() Q_DECL_OVERRIDE; + void eventCompleted(cl_event event) Q_DECL_OVERRIDE; + + QQuickItem *source() const { return m_source; } + void setSource(QQuickItem *source) { + if (m_source != source) { + m_source = source; + emit sourceChanged(); + update(); + } + } + + QAbstractItemModel *result() const { return m_result; } + void updateResult(const QByteArray &histogram) { + const cl_uint *p = (const cl_uint *) histogram.constData(); + QVector<uint> v(256); + for (int i = 0; i < v.count(); ++i) + v[i] = p[i]; + m_result->setHistogram(v); + emit newResultsAvailable(); + } + +signals: + void sourceChanged(); + void resultChanged(); // not used as there is a single HistogramModel instance + void newResultsAvailable(); + +private: + QQuickItem *m_source; + HistogramModel *m_result; + CLRunnable *m_runnable; +}; + +class CLRunnable : public QQuickCLImageRunnable +{ +public: + CLRunnable(CLItem *item); + ~CLRunnable(); + void runKernel(cl_mem inImage, cl_mem outImage, const QSize &size) Q_DECL_OVERRIDE; + QByteArray rawResult() const { return m_result; } + void resetPending() { m_resultPending.testAndSetOrdered(1, 0); } + +private: + CLItem *m_item; + cl_program m_program; + cl_kernel m_kernel; + cl_kernel m_sumKernel; + cl_mem m_resultBuf; + cl_mem m_sharedBuf; + cl_event m_doneEvent; + QByteArray m_result; + QAtomicInt m_resultPending; +}; + +CLRunnable::CLRunnable(CLItem *item) + : QQuickCLImageRunnable(item, NoOutputImage | (profile ? Profile : Flag(0))), // note the NoOutputImage flag + m_item(item), + m_program(0), + m_kernel(0), + m_sumKernel(0), + m_resultBuf(0), + m_sharedBuf(0), + m_doneEvent(0) +{ + QByteArray platform = m_item->platformName(); + qDebug("Using platform %s", platform.constData()); + m_program = m_item->buildProgramFromFile(QStringLiteral(":/histogram.cl")); + if (!m_program) + return; + cl_int err; + m_kernel = clCreateKernel(m_program, "histogram", &err); + if (!m_kernel) { + qWarning("Failed to create histogram OpenCL kernel: %d", err); + return; + } + m_sumKernel = clCreateKernel(m_program, "sum_histogram", &err); + if (!m_sumKernel) { + qWarning("Failed to create sum histogram OpenCL kernel: %d", err); + return; + } + m_resultBuf = clCreateBuffer(m_item->context(), CL_MEM_WRITE_ONLY, 256 * sizeof(cl_uint), 0, &err); + if (!m_resultBuf) { + qWarning("Failed to create OpenCL buffer: %d", err); + return; + } + m_result.resize(256 * sizeof(cl_uint)); +} + +CLRunnable::~CLRunnable() +{ + if (m_sharedBuf) + clReleaseMemObject(m_sharedBuf); + if (m_resultBuf) + clReleaseMemObject(m_resultBuf); + if (m_kernel) + clReleaseKernel(m_kernel); + if (m_sumKernel) + clReleaseKernel(m_sumKernel); + if (m_program) + clReleaseProgram(m_program); +} + +class PendingGuard +{ +public: + PendingGuard(CLRunnable *r) : r(r) { } + ~PendingGuard() { if (r) r->resetPending(); } + void take() { r = 0; } +private: + CLRunnable *r; +}; + +#define DIV(a, b) ((a + b - 1) / b) + +void CLRunnable::runKernel(cl_mem inImage, cl_mem, const QSize &size) +{ + if (!m_program || !m_kernel || !m_sumKernel || !m_resultBuf) + return; + + if (!m_resultPending.testAndSetOrdered(0, 1)) + return; + PendingGuard pg(this); + + if (profile) + qDebug("CL time: %f ms", elapsed()); + + const size_t group_size_x = 16; + const size_t group_size_y = 8; + const cl_int num_pixels_per_item = 32; + const size_t num_items_per_row = DIV(size.width(), num_pixels_per_item); + const size_t num_groups_x = DIV(num_items_per_row, group_size_x); + const size_t num_groups_y = DIV(size.height(), group_size_y); + const cl_int num_groups = cl_int(num_groups_x * num_groups_y); + + const size_t localWorkSize[2] = { group_size_x, group_size_y }; + const size_t globalWorkSize[2] = { localWorkSize[0] * num_groups_x, localWorkSize[1] * num_groups_y }; + + cl_int err; + if (!m_sharedBuf) { + const size_t sharedBufSize = num_groups * 256 * sizeof(cl_uint); + m_sharedBuf = clCreateBuffer(m_item->context(), CL_MEM_READ_WRITE, sharedBufSize, 0, &err); + if (!m_sharedBuf) { + qWarning("Failed to create shared buffer: %d", err); + return; + } + } + + clSetKernelArg(m_kernel, 0, sizeof(cl_mem), &inImage); + clSetKernelArg(m_kernel, 1, sizeof(cl_int), &num_pixels_per_item); + clSetKernelArg(m_kernel, 2, sizeof(cl_mem), &m_sharedBuf); + err = clEnqueueNDRangeKernel(commandQueue(), m_kernel, 2, 0, globalWorkSize, localWorkSize, 0, 0, 0); + if (err != CL_SUCCESS) { + qWarning("Failed to enqueue kernel: %d", err); + return; + } + + clSetKernelArg(m_sumKernel, 0, sizeof(cl_mem), &m_sharedBuf); + clSetKernelArg(m_sumKernel, 1, sizeof(cl_int), &num_groups); + clSetKernelArg(m_sumKernel, 2, sizeof(cl_mem), &m_resultBuf); + const size_t sumLocalWorkSize = 256; + const size_t sumGlobalWorkSize = 256; + err = clEnqueueNDRangeKernel(commandQueue(), m_sumKernel, 1, 0, &sumGlobalWorkSize, &sumLocalWorkSize, 0, 0, 0); + if (err != CL_SUCCESS) { + qWarning("Failed to enqueue sum kernel: %d", err); + return; + } + + err = clEnqueueReadBuffer(commandQueue(), m_resultBuf, CL_FALSE, 0, m_result.size(), m_result.data(), 0, 0, &m_doneEvent); + if (err != CL_SUCCESS) { + qWarning("Failed to enqueue read buffer: %d", err); + return; + } + + pg.take(); + m_item->watchEvent(m_doneEvent); +} + +QQuickCLRunnable *CLItem::createCL() +{ + m_runnable = new CLRunnable(this); + return m_runnable; +} + +void CLItem::eventCompleted(cl_event event) +{ + // We are on the gui thread here. + updateResult(m_runnable->rawResult()); + + clReleaseEvent(event); + m_runnable->resetPending(); + + // Request an update, which will eventually also lead to issuing the next + // round of computation. + scheduleUpdate(); +} + +int main(int argc, char **argv) +{ +#ifdef Q_OS_WIN + QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); +#endif + QGuiApplication app(argc, argv); + + if (app.arguments().contains(QStringLiteral("--profile"))) + profile = true; + + QQuickView view; + QObject::connect(view.engine(), SIGNAL(quit()), &app, SLOT(quit())); + + qmlRegisterType<CLItem>("quickcl.qt.io", 1, 0, "CLItem"); + + view.setSource(QUrl("qrc:///qml/histogram.qml")); + view.setResizeMode(QQuickView::SizeRootObjectToView); + + view.resize(1200, 600); + view.show(); + + return app.exec(); +} + +#include "histogram.moc" diff --git a/examples/quickcl/histogram/histogram.pro b/examples/quickcl/histogram/histogram.pro new file mode 100644 index 0000000..f759f6a --- /dev/null +++ b/examples/quickcl/histogram/histogram.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +QT += qml quick quickcl + +SOURCES = histogram.cpp + +RESOURCES = histogram.qrc + +OTHER_FILES = $$PWD/qml/histogram.qml + +osx { + LIBS += -framework OpenCL +} else { + LIBS += -lOpenCL +} diff --git a/examples/quickcl/histogram/histogram.qrc b/examples/quickcl/histogram/histogram.qrc new file mode 100644 index 0000000..8061a8e --- /dev/null +++ b/examples/quickcl/histogram/histogram.qrc @@ -0,0 +1,8 @@ +<RCC> + <qresource prefix="/"> + <file>qml/histogram.qml</file> + <file>qml/image.png</file> + <file>qml/qt.png</file> + <file>histogram.cl</file> + </qresource> +</RCC> diff --git a/examples/quickcl/histogram/qml/histogram.qml b/examples/quickcl/histogram/qml/histogram.qml new file mode 100644 index 0000000..f0fade9 --- /dev/null +++ b/examples/quickcl/histogram/qml/histogram.qml @@ -0,0 +1,140 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.0 +import QtQuick.Controls 1.0 +import quickcl.qt.io 1.0 + +Item { + Rectangle { + id: orig + width: parent.width / 2 - 4 + height: parent.height + border.color: "magenta" + border.width: 4 + + Item { + id: src + anchors.fill: parent + layer.enabled: true + Image { + anchors.fill: parent + anchors.margins: 4 + source: "image.png" + } + Image { + source: "qt.png" + width: 100 + height: 100 + smooth: true + SequentialAnimation on scale { + loops: Animation.Infinite + NumberAnimation { from: 1; to: 8; duration: 2000; easing.type: Easing.OutBounce } + PauseAnimation { duration: 2000 } + NumberAnimation { from: 8; to: 1; duration: 2000; easing.type: Easing.OutBounce } + PauseAnimation { duration: 2000 } + } + NumberAnimation on rotation { from: 0; to: 360; duration: 2000; loops: Animation.Infinite } + anchors.centerIn: parent + } + } + } + + Rectangle { + width: parent.width / 2 - 4 + height: parent.height + anchors.left: orig.right + anchors.leftMargin: 4 + border.color: "magenta" + border.width: 4 + + CLItem { + id: clItem + source: src + anchors.fill: parent + anchors.margins: 4 + onNewResultsAvailable: { + var maxValue = rectRoot.height - topText.y - topText.height; + for (var i = 0; i < 256; ++i) + rep.itemAt(i).height = Math.max(1, Math.min(result.get(i) / scaleFactor.value, maxValue)) + } + Item { + anchors.fill: parent + Row { + anchors.fill: parent + id: rectRoot + Repeater { + id: rep + // It might be tempting to use clItem.result as the + // model. This would however result in a serious + // slowdown due to dropping and adding 256 new + // rectangles on every update. + model: 256 + Rectangle { + width: parent ? parent.width / rep.count : 0 + height: 0 + y: parent ? parent.height - height : 0 + color: "black" + } + } + } + } + } + Text { + id: topText + font.pointSize: 16 + text: "Histogram calculated on the GPU with OpenCL (scale: " + Math.round(scaleFactor.value) + ")" + color: "green" + x: 10 + y: 10 + } + Slider { + id: scaleFactor + x: 10 + anchors.top: topText.bottom + anchors.bottom: parent.bottom + anchors.margins: 10 + minimumValue: 1 + maximumValue: 1024 + value: 8 + orientation: Qt.Vertical + } + } +} diff --git a/examples/quickcl/histogram/qml/image.png b/examples/quickcl/histogram/qml/image.png Binary files differnew file mode 100644 index 0000000..8339210 --- /dev/null +++ b/examples/quickcl/histogram/qml/image.png diff --git a/examples/quickcl/histogram/qml/qt.png b/examples/quickcl/histogram/qml/qt.png Binary files differnew file mode 100644 index 0000000..7d3e97e --- /dev/null +++ b/examples/quickcl/histogram/qml/qt.png diff --git a/examples/quickcl/imageprocess/imageprocess.cpp b/examples/quickcl/imageprocess/imageprocess.cpp new file mode 100644 index 0000000..9738ea4 --- /dev/null +++ b/examples/quickcl/imageprocess/imageprocess.cpp @@ -0,0 +1,187 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// Demonstrates the texture-to-texture use case. This is basically an +// OpenCL-based equivalent to ShaderEffect items. + +#include <QGuiApplication> +#include <QQuickView> +#include <QQmlEngine> +#include <QQuickCLItem> +#include <QQuickCLImageRunnable> + +static bool profile = false; + +class CLItem : public QQuickCLItem +{ + Q_OBJECT + Q_PROPERTY(QQuickItem *source READ source WRITE setSource NOTIFY sourceChanged) + Q_PROPERTY(qreal factor READ factor WRITE setFactor NOTIFY factorChanged) + +public: + CLItem() : m_source(0), m_factor(1) { } + + QQuickCLRunnable *createCL() Q_DECL_OVERRIDE; + + QQuickItem *source() const { return m_source; } + void setSource(QQuickItem *source) { + if (m_source != source) { + m_source = source; + emit sourceChanged(); + update(); + } + } + + qreal factor() const { return m_factor; } + void setFactor(qreal v) { + if (m_factor != v) { + m_factor = v; + emit factorChanged(); + update(); + } + } + +signals: + void sourceChanged(); + void factorChanged(); + +private: + QQuickItem *m_source; + qreal m_factor; +}; + +class CLRunnable : public QQuickCLImageRunnable +{ +public: + CLRunnable(CLItem *item); + ~CLRunnable(); + void runKernel(cl_mem inImage, cl_mem outImage, const QSize &size) Q_DECL_OVERRIDE; + +private: + CLItem *m_item; + cl_program m_clProgram; + cl_kernel m_clKernel; +}; + +QQuickCLRunnable *CLItem::createCL() +{ + return new CLRunnable(this); +} + +static const char *openclSrc = + "__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST;\n" + "__kernel void Emboss(__read_only image2d_t imgIn, __write_only image2d_t imgOut, float factor) {\n" + " const int2 pos = { get_global_id(0), get_global_id(1) };\n" + " float4 diff = read_imagef(imgIn, sampler, pos + (int2)(1,1)) - read_imagef(imgIn, sampler, pos - (int2)(1,1));\n" + " float color = (diff.x + diff.y + diff.z) / factor + 0.5f;\n" + " write_imagef(imgOut, pos, (float4)(color, color, color, 1.0f));\n" + "}\n"; + +CLRunnable::CLRunnable(CLItem *item) + : QQuickCLImageRunnable(item, profile ? Profile : Flag(0)), + m_item(item), + m_clProgram(0), + m_clKernel(0) +{ + QByteArray platform = m_item->platformName(); + qDebug("Using platform %s", platform.constData()); + m_clProgram = m_item->buildProgram(openclSrc); + if (!m_clProgram) + return; + cl_int err; + m_clKernel = clCreateKernel(m_clProgram, "Emboss", &err); + if (!m_clKernel) { + qWarning("Failed to create emboss OpenCL kernel: %d", err); + return; + } +} + +CLRunnable::~CLRunnable() +{ + if (m_clKernel) + clReleaseKernel(m_clKernel); + if (m_clProgram) + clReleaseProgram(m_clProgram); +} + +void CLRunnable::runKernel(cl_mem inImage, cl_mem outImage, const QSize &size) +{ + if (!m_clProgram) + return; + + if (profile) + qDebug("CL time: %f", elapsed()); + + clSetKernelArg(m_clKernel, 0, sizeof(cl_mem), &inImage); + clSetKernelArg(m_clKernel, 1, sizeof(cl_mem), &outImage); + const cl_float factor = m_item->factor(); + clSetKernelArg(m_clKernel, 2, sizeof(cl_float), &factor); + + const size_t workSize[] = { size_t(size.width()), size_t(size.height()) }; + cl_int err = clEnqueueNDRangeKernel(commandQueue(), m_clKernel, 2, 0, workSize, 0, 0, 0, 0); + if (err != CL_SUCCESS) + qWarning("Failed to enqueue kernel: %d", err); +} + +int main(int argc, char **argv) +{ +#ifdef Q_OS_WIN + QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); +#endif + QGuiApplication app(argc, argv); + + if (app.arguments().contains(QStringLiteral("--profile"))) + profile = true; + + QQuickView view; + QObject::connect(view.engine(), SIGNAL(quit()), &app, SLOT(quit())); + + qmlRegisterType<CLItem>("quickcl.qt.io", 1, 0, "CLItem"); + + view.setSource(QUrl("qrc:///qml/imageprocess.qml")); + view.setResizeMode(QQuickView::SizeRootObjectToView); + + view.resize(1200, 600); + view.show(); + + return app.exec(); +} + +#include "imageprocess.moc" diff --git a/examples/quickcl/imageprocess/imageprocess.pro b/examples/quickcl/imageprocess/imageprocess.pro new file mode 100644 index 0000000..c7825a2 --- /dev/null +++ b/examples/quickcl/imageprocess/imageprocess.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +QT += qml quick quickcl + +SOURCES = imageprocess.cpp + +RESOURCES = imageprocess.qrc + +OTHER_FILES = $$PWD/qml/imageprocess.qml + +osx { + LIBS += -framework OpenCL +} else { + LIBS += -lOpenCL +} diff --git a/examples/quickcl/imageprocess/imageprocess.qrc b/examples/quickcl/imageprocess/imageprocess.qrc new file mode 100644 index 0000000..ecf25e7 --- /dev/null +++ b/examples/quickcl/imageprocess/imageprocess.qrc @@ -0,0 +1,6 @@ +<RCC> + <qresource prefix="/"> + <file>qml/imageprocess.qml</file> + <file>qml/image.png</file> + </qresource> +</RCC> diff --git a/examples/quickcl/imageprocess/qml/image.png b/examples/quickcl/imageprocess/qml/image.png Binary files differnew file mode 100644 index 0000000..f8ff553 --- /dev/null +++ b/examples/quickcl/imageprocess/qml/image.png diff --git a/examples/quickcl/imageprocess/qml/imageprocess.qml b/examples/quickcl/imageprocess/qml/imageprocess.qml new file mode 100644 index 0000000..99526ee --- /dev/null +++ b/examples/quickcl/imageprocess/qml/imageprocess.qml @@ -0,0 +1,129 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.0 +import QtQuick.Controls 1.0 +import quickcl.qt.io 1.0 + +Item { + Rectangle { + id: orig + width: parent.width / 2 - 4 + height: parent.height + border.color: "magenta" + border.width: 4 + + Item { + id: srcSubTree + anchors.fill: parent + layer.enabled: true + visible: !cbHide.checked + Image { + id: srcImage + anchors.fill: parent + anchors.margins: 4 + source: "image.png" + } + Rectangle { + width: 100 + height: 100 + color: "red" + NumberAnimation on rotation { from: 0; to: 360; duration: 2000; loops: Animation.Infinite; } + anchors.right: parent.right + anchors.bottom: parent.bottom + anchors.margins: 20 + } + Column { + spacing: 10 + anchors.centerIn: parent + CheckBox { + id: cbLayer + text: "Apply to entire sub-tree (FBO)" + checked: false + onCheckedChanged: clItem.source = checked ? srcSubTree : srcImage + } + CheckBox { + id: cbHide + text: "Hide source" + checked: false + enabled: cbLayer.checked + } + } + } + Button { + text: "Make visible" + visible: cbHide.checked + onClicked: cbHide.checked = false + anchors.centerIn: parent + } + } + + Rectangle { + width: parent.width / 2 - 4 + height: parent.height + anchors.left: orig.right + anchors.leftMargin: 4 + border.color: "magenta" + border.width: 4 + + CLItem { + id: clItem + anchors.fill: parent + anchors.margins: 4 + source: srcImage + factor: 1 + NumberAnimation on factor { + from: 1 + to: 20 + duration: 8000 + loops: Animation.Infinite + } + } + + Text { + x: 10 + y: 10 + text: "Emboss factor: " + Math.round(clItem.factor) + "\nSource is " + + (clItem.source === srcImage ? "image" : "layered sub-tree") + font.pointSize: 16 + color: "green" + } + } +} diff --git a/examples/quickcl/particles/particles.cl b/examples/quickcl/particles/particles.cl new file mode 100644 index 0000000..47a8013 --- /dev/null +++ b/examples/quickcl/particles/particles.cl @@ -0,0 +1,13 @@ +kernel void updateParticles(global float *buf, float t, float dt, global float *info) +{ + int idx = get_global_id(0) * 2; + if (t < 0.000001f) { + buf[idx] = -1.0f; + buf[idx + 1] = -1.0f; + } else { + float2 dir = (float2)(info[idx], info[idx + 1]); + float2 speed = (float2)(info[idx + 2], info[idx + 3]); + buf[idx] += dir.x * dt * speed.x; + buf[idx + 1] += dir.y * dt * speed.y; + } +} diff --git a/examples/quickcl/particles/particles.cpp b/examples/quickcl/particles/particles.cpp new file mode 100644 index 0000000..917baeb --- /dev/null +++ b/examples/quickcl/particles/particles.cpp @@ -0,0 +1,448 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// Demonstrates generating vertex data (GL buffer) from OpenCL. + +#include <QGuiApplication> +#include <QQuickView> +#include <QQmlEngine> +#include <QSGSimpleTextureNode> +#include <QOpenGLFramebufferObject> +#include <QOpenGLFunctions> +#include <QOpenGLShaderProgram> +#include <QQuickCLItem> +#include <QQuickCLRunnable> +#include <time.h> + +const int PARTICLE_COUNT = 1024; + +class CLItem; + +// CLNode visualizes the results of CLRunnable. This is done by rendering via a +// FBO since we will have the data (the output from the CL kernel) on the GPU +// already so QSGGeometryNode and friends are not suitable for us. +// +// If mixing with other Quick items is not needed, this can be simplified to +// render straight to the window in a slot connected directly to the +// beforeRendering() or afterRendering() signals of the QQuickWindow. +// +class CLNode : public QObject, public QSGSimpleTextureNode +{ + Q_OBJECT + +public: + CLNode(CLItem *item) : m_item(item), m_fbo(0), m_buf(0), m_clBuf(0), m_program(0) { } + + ~CLNode() { + delete m_program; + delete m_fbo; + if (m_clBuf) + clReleaseMemObject(m_clBuf); + QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions(); + if (m_buf) + f->glDeleteBuffers(1, &m_buf); + } + +public slots: + void render(); + +public: + CLItem *m_item; + QOpenGLFramebufferObject *m_fbo; + GLuint m_buf; + cl_mem m_clBuf; + QAtomicInt m_renderPending; + QOpenGLShaderProgram *m_program; + int m_tUniformLoc; +}; + +// The CLRunnable lives on the render thread, like the CLNode. +class CLRunnable : public QObject, public QQuickCLRunnable +{ + Q_OBJECT + +public: + CLRunnable(CLItem *item); + ~CLRunnable(); + QSGNode *update(QSGNode *node) Q_DECL_OVERRIDE; + CLNode *node() const { return m_node; } + void resetComputeInProgress() { m_computeInProgress.testAndSetOrdered(1, 0); } + +public slots: + void handleScreenChange(); + +private: + static void CL_CALLBACK computeDoneCallback(cl_event event, cl_int event_command_exec_status, void *user_data); + void computeDone(); + QSize itemSize() const; + void createBuffer(); + void createFbo(); + + CLItem *m_item; + CLNode *m_node; + bool m_recreateFbo; + cl_command_queue m_queue; + cl_program m_program; + cl_kernel m_kernel; + cl_event m_computeDoneEvent; + QSize m_itemSize; + bool m_needsExplicitSync; + QAtomicInt m_computeInProgress; + qreal m_lastT; + cl_mem m_clBufParticleInfo; +}; + +class CLItem : public QQuickCLItem +{ + Q_OBJECT + Q_PROPERTY(qreal t READ t WRITE setT NOTIFY tChanged) + +public: + CLItem() : m_t(0) { } + + QQuickCLRunnable *createCL() Q_DECL_OVERRIDE; + void eventCompleted(cl_event event) Q_DECL_OVERRIDE; + + qreal t() const { return m_t; } + void setT(qreal v) { + if (m_t != v) { + m_t = v; + emit tChanged(); + update(); + } + } + +signals: + void tChanged(); + +private: + qreal m_t; + CLRunnable *m_runnable; +}; + +static const char *vertexShaderSource = + "attribute vec2 vertex;\n" + "void main() {\n" + " gl_PointSize = 4.0;\n" + " gl_Position = vec4(vertex.xy, 0.0, 1.0);\n" + "}\n"; + +static const char *fragmentShaderSource = + "uniform highp float t;\n" + "void main() {\n" + " gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0 - t);\n" + "}\n"; + +void CLNode::render() +{ + if (!m_renderPending.testAndSetOrdered(1, 0)) + return; + + m_fbo->bind(); + QOpenGLContext *ctx = QOpenGLContext::currentContext(); + QOpenGLFunctions *f = ctx->functions(); + + if (!m_program) { + m_program = new QOpenGLShaderProgram; + m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource); + m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource); + m_program->link(); + m_tUniformLoc = m_program->uniformLocation("t"); + +#ifndef QT_OPENGL_ES_2 + if (!ctx->isOpenGLES()) { + f->glEnable(GL_POINT_SPRITE); + f->glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); + } +#endif + } + + f->glEnable(GL_BLEND); + f->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + f->glViewport(0, 0, m_fbo->width(), m_fbo->height()); + f->glClearColor(0, 0, 0.25f, 1); + f->glClear(GL_COLOR_BUFFER_BIT); + + m_program->bind(); + m_program->setUniformValue(m_tUniformLoc, GLfloat(m_item->t())); + + f->glBindBuffer(GL_ARRAY_BUFFER, m_buf); + f->glEnableVertexAttribArray(0); + f->glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); + + f->glDrawArrays(GL_POINTS, 0, PARTICLE_COUNT); +} + +CLRunnable::CLRunnable(CLItem *item) + : m_item(item), + m_node(0), + m_recreateFbo(false), + m_program(0), + m_kernel(0), + m_computeDoneEvent(0), + m_lastT(-1), + m_clBufParticleInfo(0) +{ + qDebug() << "Platform" << m_item->platformName() << "Device extensions" << m_item->deviceExtensions(); + cl_int err; + + m_queue = clCreateCommandQueue(m_item->context(), m_item->device(), 0, &err); + if (!m_queue) { + qWarning("Failed to create OpenCL command queue: %d", err); + return; + } + + m_program = m_item->buildProgramFromFile(QStringLiteral(":/particles.cl")); + if (!m_program) + return; + m_kernel = clCreateKernel(m_program, "updateParticles", &err); + if (!m_kernel) { + qWarning("Failed to create particles OpenCL kernel: %d", err); + return; + } + + m_needsExplicitSync = !m_item->deviceExtensions().contains(QByteArrayLiteral("cl_khr_gl_event")); + + // m_clBufParticleInfo is an ordinary OpenCL buffer. + size_t velBufSize = PARTICLE_COUNT * sizeof(cl_float) * 4; + m_clBufParticleInfo = clCreateBuffer(m_item->context(), CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, velBufSize, 0, &err); + if (!m_clBufParticleInfo) { + qWarning("Failed to create CL buffer: %d", err); + return; + } + cl_float *ptr = (cl_float *) clEnqueueMapBuffer(m_queue, m_clBufParticleInfo, CL_TRUE, CL_MAP_WRITE, 0, velBufSize, 0, 0, 0, &err); + if (!ptr) { + qWarning("Failed to map CL buffer: %d", err); + return; + } + cl_float *p = ptr; + for (int i = 0; i < PARTICLE_COUNT; ++i) { + // Direction + *p++ = ((qrand() % 1000) + 1) / 1000.0f; + *p++ = ((qrand() % 1000) + 1) / 1000.0f; + // Speed + *p++ = ((qrand() % 1000) + 1) / 100.0f; + *p++ = ((qrand() % 1000) + 1) / 100.0f; + } + clEnqueueUnmapMemObject(m_queue, m_clBufParticleInfo, ptr, 0, 0, 0); +} + +CLRunnable::~CLRunnable() +{ + if (m_clBufParticleInfo) + clReleaseMemObject(m_clBufParticleInfo); + if (m_kernel) + clReleaseKernel(m_kernel); + if (m_program) + clReleaseProgram(m_program); + if (m_queue) + clReleaseCommandQueue(m_queue); +} + +void CLRunnable::createBuffer() +{ + QOpenGLFunctions *f = QOpenGLContext::currentContext()->functions(); + + // m_buf is an OpenGL buffer that is read/written from OpenCL and then used + // as the input to the OpenGL vertex shader. + GLuint buf; + f->glGenBuffers(1, &buf); + f->glBindBuffer(GL_ARRAY_BUFFER, buf); + f->glBufferData(GL_ARRAY_BUFFER, PARTICLE_COUNT * sizeof(GLfloat) * 2, 0, GL_DYNAMIC_DRAW); + if (m_node->m_buf) + f->glDeleteBuffers(1, &m_node->m_buf); + m_node->m_buf = buf; + + if (m_node->m_clBuf) + clReleaseMemObject(m_node->m_clBuf); + cl_int err; + m_node->m_clBuf = clCreateFromGLBuffer(m_item->context(), CL_MEM_READ_WRITE, buf, &err); + if (!m_node->m_clBuf) + qWarning("Failed to create OpenCL object for OpenGL buffer: %d", err); +} + +QSize CLRunnable::itemSize() const +{ + QSize size(m_item->width(), m_item->height()); + size *= m_item->window()->effectiveDevicePixelRatio(); + return size; +} + +void CLRunnable::createFbo() +{ + QOpenGLFramebufferObject *fbo = new QOpenGLFramebufferObject(itemSize()); + m_node->setTexture(m_item->window()->createTextureFromId(fbo->texture(), fbo->size(), + QQuickWindow::TextureHasAlphaChannel)); + delete m_node->m_fbo; + m_node->m_fbo = fbo; + m_node->m_renderPending.testAndSetOrdered(0, 1); +} + +void CLRunnable::handleScreenChange() +{ + // We could have been moved from a high to low dpi screen or vice versa. + m_recreateFbo = true; + m_item->scheduleUpdate(); +} + +class StateGuard +{ +public: + StateGuard(CLRunnable *r) : r(r) { } + ~StateGuard() { if (r) r->resetComputeInProgress(); } + void release() { r = 0; } +private: + CLRunnable *r; +}; + +QSGNode *CLRunnable::update(QSGNode *node) +{ + if (!m_queue || !m_program || !m_kernel || !m_clBufParticleInfo) + return 0; + + if (!node) { + m_node = new CLNode(m_item); + m_node->setFiltering(QSGTexture::Linear); + QObject::connect(m_item->window(), SIGNAL(beforeRendering()), m_node, SLOT(render())); + QObject::connect(m_item->window(), SIGNAL(screenChanged(QScreen*)), this, SLOT(handleScreenChange())); + node = m_node; + createBuffer(); + } + if (m_itemSize != itemSize()) { + m_itemSize = itemSize(); + m_recreateFbo = true; + } + if (m_recreateFbo) { + m_recreateFbo = false; + createFbo(); + } + m_node->setRect(0, 0, m_item->width(), m_item->height()); + if (m_node->m_renderPending) + m_node->markDirty(QSGNode::DirtyMaterial); + + // Animation is based on the time property. No need to enqueue anything if + // the value has not yet changed. + if (m_lastT == m_item->t()) + return node; + + if (!m_computeInProgress.testAndSetOrdered(0, 1)) + return node; + + StateGuard sg(this); + + cl_float dt = m_item->t() - m_lastT; + m_lastT = m_item->t(); + + if (m_needsExplicitSync) + QOpenGLContext::currentContext()->functions()->glFinish(); + + cl_int err = clEnqueueAcquireGLObjects(m_queue, 1, &m_node->m_clBuf, 0, 0, 0); + if (err != CL_SUCCESS) { + qWarning("Failed to queue acquiring the GL buffer: %d", err); + return node; + } + + clSetKernelArg(m_kernel, 0, sizeof(cl_mem), &m_node->m_clBuf); + cl_float t = m_item->t(); + clSetKernelArg(m_kernel, 1, sizeof(cl_float), &t); + clSetKernelArg(m_kernel, 2, sizeof(cl_float), &dt); + clSetKernelArg(m_kernel, 3, sizeof(cl_mem), &m_clBufParticleInfo); + size_t globalWorkSize = PARTICLE_COUNT; + err = clEnqueueNDRangeKernel(m_queue, m_kernel, 1, 0, &globalWorkSize, 0, 0, 0, 0); + if (err != CL_SUCCESS) { + qWarning("Failed to enqueue kernel: %d", err); + return node; + } + + err = clEnqueueReleaseGLObjects(m_queue, 1, &m_node->m_clBuf, 0, 0, &m_computeDoneEvent); + if (err != CL_SUCCESS) { + qWarning("Failed to queue releasing the GL buffer: %d", err); + return node; + } + + sg.release(); + m_item->watchEvent(m_computeDoneEvent); + + if (m_needsExplicitSync) + clFinish(m_queue); + + return node; +} + +void CLItem::eventCompleted(cl_event event) +{ + clReleaseEvent(event); + m_runnable->resetComputeInProgress(); + // Tell the node that the FBO's contents is stale and needs updating. + m_runnable->node()->m_renderPending.testAndSetOrdered(0, 1); + scheduleUpdate(); +} + +QQuickCLRunnable *CLItem::createCL() +{ + m_runnable = new CLRunnable(this); + return m_runnable; +} + +int main(int argc, char **argv) +{ +#ifdef Q_OS_WIN + QCoreApplication::setAttribute(Qt::AA_UseDesktopOpenGL); +#endif + QGuiApplication app(argc, argv); + + qsrand(time(0)); + + QQuickView view; + QObject::connect(view.engine(), SIGNAL(quit()), &app, SLOT(quit())); + + qmlRegisterType<CLItem>("quickcl.qt.io", 1, 0, "CLItem"); + + view.setSource(QUrl("qrc:///qml/particles.qml")); + view.setResizeMode(QQuickView::SizeRootObjectToView); + + view.resize(1200, 600); + view.show(); + + return app.exec(); +} + +#include "particles.moc" diff --git a/examples/quickcl/particles/particles.pro b/examples/quickcl/particles/particles.pro new file mode 100644 index 0000000..74050e1 --- /dev/null +++ b/examples/quickcl/particles/particles.pro @@ -0,0 +1,15 @@ +TEMPLATE = app + +QT += qml quick quickcl + +SOURCES = particles.cpp + +RESOURCES = particles.qrc + +OTHER_FILES = $$PWD/qml/particles.qml + +osx { + LIBS += -framework OpenCL +} else { + LIBS += -lOpenCL +} diff --git a/examples/quickcl/particles/particles.qrc b/examples/quickcl/particles/particles.qrc new file mode 100644 index 0000000..630169c --- /dev/null +++ b/examples/quickcl/particles/particles.qrc @@ -0,0 +1,6 @@ +<RCC> + <qresource prefix="/"> + <file>qml/particles.qml</file> + <file>particles.cl</file> + </qresource> +</RCC> diff --git a/examples/quickcl/particles/qml/particles.qml b/examples/quickcl/particles/qml/particles.qml new file mode 100644 index 0000000..9e872e5 --- /dev/null +++ b/examples/quickcl/particles/qml/particles.qml @@ -0,0 +1,101 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.0 +import QtQuick.Controls 1.0 +import quickcl.qt.io 1.0 + +Rectangle { + gradient: Gradient { + GradientStop { position: 0; color: "steelblue" } + GradientStop { position: 1; color: "black" } + } + Text { + text: "Yes, it's a QQuickItem" + x: 10 + y: 10 + color: "yellow" + } + CLItem { + id: clItem + anchors.fill: parent + NumberAnimation on t { + from: 0.0 + to: 1.0 + duration: 10000 + id: particleAnim + running: false + } + transform: [ + Rotation { id: rotation; axis.x: 0; axis.z: 0; axis.y: 1; angle: 0; origin.x: width / 2; origin.y: height / 2; }, + Translate { id: txOut; x: -width / 2; y: -height / 2 }, + Scale { id: scale; }, + Translate { id: txIn; x: width / 2; y: height / 2 } + ] + // animation borrowed from textureinsgnode + SequentialAnimation { + PauseAnimation { duration: 2000 } + ParallelAnimation { + NumberAnimation { target: scale; property: "xScale"; to: 0.6; duration: 1000; easing.type: Easing.InOutBack } + NumberAnimation { target: scale; property: "yScale"; to: 0.6; duration: 1000; easing.type: Easing.InOutBack } + } + NumberAnimation { target: rotation; property: "angle"; to: 80; duration: 1000; easing.type: Easing.InOutCubic } + NumberAnimation { target: rotation; property: "angle"; to: -80; duration: 1000; easing.type: Easing.InOutCubic } + NumberAnimation { target: rotation; property: "angle"; to: 0; duration: 1000; easing.type: Easing.InOutCubic } + PauseAnimation { duration: 1000 } + ParallelAnimation { + NumberAnimation { target: scale; property: "xScale"; to: 1; duration: 1000; easing.type: Easing.InOutBack } + NumberAnimation { target: scale; property: "yScale"; to: 1; duration: 1000; easing.type: Easing.InOutBack } + } + running: true + onStarted: particleAnim.restart() + onStopped: { particleAnim.restart(); restart() } + } + } + Text { + text: "VBO generated from OpenCL" + color: "yellow" + x: 10 + y: 10 + font.pointSize: 16 + anchors.right: parent.right + anchors.margins: 10 + } +} diff --git a/examples/quickcl/quickcl.pro b/examples/quickcl/quickcl.pro new file mode 100644 index 0000000..f4f79c3 --- /dev/null +++ b/examples/quickcl/quickcl.pro @@ -0,0 +1,2 @@ +TEMPLATE = subdirs +SUBDIRS += imageprocess histogram particles diff --git a/qtquickcl.pro b/qtquickcl.pro new file mode 100644 index 0000000..dc54c16 --- /dev/null +++ b/qtquickcl.pro @@ -0,0 +1,10 @@ +load(configure) + +qtCompileTest(opencl) + +load(qt_parts) + +!config_opencl { + warning("OpenCL not found") + SUBDIRS = +} diff --git a/src/quickcl/doc/qtquickcl.qdocconf b/src/quickcl/doc/qtquickcl.qdocconf new file mode 100644 index 0000000..583111c --- /dev/null +++ b/src/quickcl/doc/qtquickcl.qdocconf @@ -0,0 +1,65 @@ +include($QT_INSTALL_DOCS/global/macros.qdocconf) +include($QT_INSTALL_DOCS/global/qt-cpp-defines.qdocconf) +include($QT_INSTALL_DOCS/global/compat.qdocconf) +include($QT_INSTALL_DOCS/global/fileextensions.qdocconf) +include($QT_INSTALL_DOCS/global/qt-html-templates-offline.qdocconf) + +project = QtQuickCL +description = Qt Quick CL Reference Documentation +url = http://doc.qt.io/QtQuickCL/ +version = 1.0 + +qhp.projects = QtQuickCL + +qhp.QtQuickCL.file = qtquickcl.qhp +qhp.QtQuickCL.namespace = com.qt.quickcl.1.0 +qhp.QtQuickCL.virtualFolder = qtquickcl +qhp.QtQuickCL.indexTitle = Qt Quick CL +qhp.QtQuickCL.indexRoot = +qhp.QtQuickCL.filterAttributes = qtquickcl 1.0 qtrefdoc +qhp.QtQuickCL.customFilters.Qt.name = QtQuickCL 1.0 +qhp.QtQuickCL.customFilters.Qt.filterAttributes = qtquickcl 1.0 + +qhp.QtQuickCL.subprojects = qmltypes classes examples +qhp.QtQuickCL.subprojects.qmltypes.title = QML Types +qhp.QtQuickCL.subprojects.qmltypes.indexTitle = Qt Quick CL QML Types +qhp.QtQuickCL.subprojects.qmltypes.selectors = fake:qmlclass +qhp.QtQuickCL.subprojects.qmltypes.sortPages = true +qhp.QtQuickCL.subprojects.classes.title = C++ Classes +qhp.QtQuickCL.subprojects.classes.indexTitle = Qt Quick CL C++ Classes +qhp.QtQuickCL.subprojects.classes.selectors = class fake:headerfile +qhp.QtQuickCL.subprojects.classes.sortPages = true +qhp.QtQuickCL.subprojects.examples.title = Examples +qhp.QtQuickCL.subprojects.examples.indexTitle = Qt Quick CL Examples +qhp.QtQuickCL.subprojects.examples.selectors = fake:example + +HTML.footer = \ + "<div class=\"footer\">\n" \ + " <p>\n" \ + " <acronym title=\"Copyright\">©</acronym> 2014 Digia. Qt and Qt logos are\n" \ + " trademarks of of Digia Corporation in Finland and/or other countries worldwide.\n" \ + " </p>\n" \ + " All other trademarks are property of their respective owners.\n" \ + " <br />\n" \ + " <p>\n" \ + " Licensees holding valid Qt Enterprise licenses may use this document in accordance\n" \ + " with the Qt Enterprise License Agreement provided with the Software or,\n" \ + " alternatively, in accordance with the terms contained in a written agreement\n" \ + " between you and Digia.\n" \ + " </p>\n" \ + "</div>\n" + +indexes += $QT_INSTALL_DOCS/qtqml/qtqml.index \ + $QT_INSTALL_DOCS/qtquick/qtquick.index \ + $QT_INSTALL_DOCS/qtdoc/qtdoc.index \ + $QT_INSTALL_DOCS/qtquickcontrols/qtquickcontrols.index + +headerdirs += ../ +sourcedirs += ../ +exampledirs += ../../../examples/ +imagedirs += images + +navigation.landingpage = "Qt Quick CL" +navigation.qmltypespage = "Qt Quick CL QML Types" +navigation.cppclassespage = "Qt Quick CL C++ Classes" +buildversion = "Qt Quick CL 1.0" diff --git a/src/quickcl/qquickclcontext.cpp b/src/quickcl/qquickclcontext.cpp new file mode 100644 index 0000000..4c07593 --- /dev/null +++ b/src/quickcl/qquickclcontext.cpp @@ -0,0 +1,199 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qquickclcontext_p.h" + +#include <QtGui/QOpenGLContext> +#include <QtGui/QOpenGLFunctions> +#include <QtCore/QLoggingCategory> +#include <qpa/qplatformnativeinterface.h> + +QT_BEGIN_NAMESPACE + +Q_LOGGING_CATEGORY(logCL, "qt.quickcl") + +QQuickCLContext::QQuickCLContext() + : m_platform(0), + m_device(0), + m_context(0) +{ +} + +QQuickCLContext::~QQuickCLContext() +{ + destroy(); +} + +bool QQuickCLContext::create() +{ + destroy(); + qCDebug(logCL, "Creating new OpenCL context"); + + QOpenGLContext *ctx = QOpenGLContext::currentContext(); + if (!ctx) { + qWarning("Attempted CL-GL interop without a current OpenGL context"); + return false; + } + QOpenGLFunctions *f = ctx->functions(); + + cl_uint n; + cl_int err = clGetPlatformIDs(0, 0, &n); + if (err != CL_SUCCESS) { + qWarning("Failed to get platform ID count (error %d)", err); + if (err == -1001) { + qWarning("Could not find OpenCL implementation. ICD missing?" +#ifdef Q_OS_LINUX + " Check /etc/OpenCL/vendors." +#endif + ); + } + return false; + } + if (n == 0) { + qWarning("No OpenCL platform found"); + return false; + } + QVector<cl_platform_id> platformIds; + platformIds.resize(n); + if (clGetPlatformIDs(n, platformIds.data(), 0) != CL_SUCCESS) { + qWarning("Failed to get platform IDs"); + return false; + } + m_platform = platformIds[0]; + const char *vendor = (const char *) f->glGetString(GL_VENDOR); + qCDebug(logCL, "GL_VENDOR: %s", vendor); + const bool isNV = vendor && strstr(vendor, "NVIDIA"); + const bool isIntel = vendor && strstr(vendor, "Intel"); + const bool isAMD = vendor && strstr(vendor, "ATI"); + qCDebug(logCL, "Found %u OpenCL platforms:", n); + for (cl_uint i = 0; i < n; ++i) { + QByteArray name; + name.resize(1024); + clGetPlatformInfo(platformIds[i], CL_PLATFORM_NAME, name.size(), name.data(), 0); + qCDebug(logCL, "Platform %p: %s", platformIds[i], name.constData()); + if (isNV && name.contains(QByteArrayLiteral("NVIDIA"))) + m_platform = platformIds[i]; + else if (isIntel && name.contains(QByteArrayLiteral("Intel"))) + m_platform = platformIds[i]; + else if (isAMD && name.contains(QByteArrayLiteral("AMD"))) + m_platform = platformIds[i]; + } + qCDebug(logCL, "Using platform %p", m_platform); + +#if defined (Q_OS_OSX) + cl_context_properties contextProps[] = { CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, + (cl_context_properties) CGLGetShareGroup(CGLGetCurrentContext()), + 0 }; +#elif defined(Q_OS_WIN) + if (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES) { + // We don't do D3D-CL interop. + qWarning("ANGLE is not supported"); + return false; + } + cl_context_properties contextProps[] = { CL_CONTEXT_PLATFORM, (cl_context_properties) m_platform, + CL_GL_CONTEXT_KHR, (cl_context_properties) wglGetCurrentContext(), + CL_WGL_HDC_KHR, (cl_context_properties) wglGetCurrentDC(), + 0 }; +#elif defined(Q_OS_LINUX) + cl_context_properties contextProps[] = { CL_CONTEXT_PLATFORM, (cl_context_properties) m_platform, + CL_GL_CONTEXT_KHR, 0, + 0, 0, + 0 }; + QPlatformNativeInterface *nativeIf = qGuiApp->platformNativeInterface(); + void *dpy = nativeIf->nativeResourceForIntegration(QByteArrayLiteral("egldisplay")); // EGLDisplay + if (dpy) { + void *nativeContext = nativeIf->nativeResourceForContext("eglcontext", ctx); + if (!nativeContext) + qWarning("Failed to get the underlying EGL context from the current QOpenGLContext"); + contextProps[3] = (cl_context_properties) nativeContext; + contextProps[4] = CL_EGL_DISPLAY_KHR; + contextProps[5] = (cl_context_properties) dpy; + } else { + dpy = nativeIf->nativeResourceForIntegration(QByteArrayLiteral("display")); // Display * + void *nativeContext = nativeIf->nativeResourceForContext("glxcontext", ctx); + if (!nativeContext) + qWarning("Failed to get the underlying GLX context from the current QOpenGLContext"); + contextProps[3] = (cl_context_properties) nativeContext; + contextProps[4] = CL_GLX_DISPLAY_KHR; + contextProps[5] = (cl_context_properties) dpy; + } +#endif + + m_context = clCreateContextFromType(contextProps, CL_DEVICE_TYPE_GPU, 0, 0, &err); + if (!m_context) { + qWarning("Failed to create OpenCL context: %d", err); + return false; + } + qCDebug(logCL, "Using context %p", m_context); + +#if defined(Q_OS_OSX) + err = clGetGLContextInfoAPPLE(m_context, CGLGetCurrentContext(), + CL_CGL_DEVICE_FOR_CURRENT_VIRTUAL_SCREEN_APPLE, + sizeof(cl_device_id), &m_device, 0); + if (err != CL_SUCCESS) { + qWarning("Failed to get OpenCL device for current screen: %d", err); + destroy(); + return false; + } +#else + clGetGLContextInfoKHR_fn getGLContextInfo = (clGetGLContextInfoKHR_fn) clGetExtensionFunctionAddress("clGetGLContextInfoKHR"); + if (!getGLContextInfo || getGLContextInfo(contextProps, CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR, + sizeof(cl_device_id), &m_device, 0) != CL_SUCCESS) { + err = clGetDeviceIDs(m_platform, CL_DEVICE_TYPE_GPU, 1, &m_device, 0); + if (err != CL_SUCCESS) { + qWarning("Failed to get OpenCL device: %d", err); + destroy(); + return false; + } + } +#endif + qCDebug(logCL, "Using device %p", m_device); + + return true; +} + +void QQuickCLContext::destroy() +{ + if (m_context) { + qCDebug(logCL, "Releasing OpenCL context %p", m_context); + clReleaseContext(m_context); + m_context = 0; + } + m_device = 0; + m_platform = 0; +} + +QT_END_NAMESPACE diff --git a/src/quickcl/qquickclcontext_p.h b/src/quickcl/qquickclcontext_p.h new file mode 100644 index 0000000..10bf70d --- /dev/null +++ b/src/quickcl/qquickclcontext_p.h @@ -0,0 +1,67 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QQUICKCLCONTEXT_P_H +#define QQUICKCLCONTEXT_P_H + +#include <QtQuickCL/qtquickclglobal.h> + +QT_BEGIN_NAMESPACE + +class QQuickCLContext +{ +public: + QQuickCLContext(); + ~QQuickCLContext(); + + bool create(); + void destroy(); + + bool isValid() const { return m_context != 0; } + + cl_platform_id platform() const { return m_platform; } + cl_device_id device() const { return m_device; } + cl_context context() const { return m_context; } + +private: + cl_platform_id m_platform; + cl_device_id m_device; + cl_context m_context; +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/quickcl/qquickclimagerunnable.cpp b/src/quickcl/qquickclimagerunnable.cpp new file mode 100644 index 0000000..01a7be1 --- /dev/null +++ b/src/quickcl/qquickclimagerunnable.cpp @@ -0,0 +1,340 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qquickclimagerunnable.h" +#include "qquickclitem.h" +#include <QSGSimpleTextureNode> +#include <QSGTextureProvider> +#include <QOpenGLTexture> +#include <QOpenGLFunctions> + +QT_BEGIN_NAMESPACE + +/*! + \class QQuickCLImageRunnable + \brief A QQuickCLItem backend specialized for operating on a single texture from the scenegraph. + + Specialized QQuickCLRunnable for applications wishing to perform + OpenCL operations on an OpenCL image object wrapping an OpenGL texture of + an Image element - or any other texture provider in the Qt Quick scene - + and show the result in the scene. + + The class provides an OpenCL command queue and a simple texture node for + the scenegraph. The item providing the texture is read from the associated + QQuickCLItem's \c source property by default. This can be overridden by + calling setSourcePropertyName(). + + By using this specialized class instead of the more generic base + QQuickCLRunnable, applications can focus on the kernels and there is no + need to manually manage OpenCL image objects, textures, and scenegraph nodes. + + For example, assuming a QQuickCLItem subclass named CLItem, running OpenCL + kernels on an image, producing a new output image rendered by CLItem in an + accelerated manner without any CPU side readbacks, becomes as simple as the + following: + + \badcode + Image { + id: srcImage + source: "image.png" + } + ... + CLItem { + source: srcImage + } + \endcode + + The source can be any texture provider. By enabling layering, the OpenCL + kernels can operate on the rendering of an entire sub-tree instead of just + a single Image item. In addition, this approach also allows hiding the + source sub-tree: + + \badcode + Item { + id: srcItem + layer.enabled: true + visible: false + ... + } + CLItem { + source: srcItem + } + \endcode + + Besides image processing scenarios it is also possible to use + QQuickCLImageRunnable for computations that produce arbitrary data from an + image (for example histogram calculation). Passing the flag NoImageOutput to + the constructor will avoid generating an OpenGL texture and corresponding + OpenCL image object for the output. Instead, it is up to the runKernel() + implementation to emit a signal on the associated QQuickCLItem and pass an + object exposing the results of the computation to QML. The visualization is + then done by child items since the QQuickCLItem itself does not render + anything in the Qt Quick scenegraph in this case, although it is still + present as an item having contents. + */ + +/*! + \fn void QQuickCLImageRunnable::runKernel(cl_mem inImage, cl_mem outImage, const QSize &size) + + Called when the OpenCL kernel(s) performing the image processing need to be + run. \a inImage and \a outImage are ready to be used as input and output + \c image2d_t parameters to a kernel. \a size specifies the size of the images. + + \note For QQuickCLImageRunnable instances created with the NoImageOutput + flag \a outImage is always \c 0. + + \note QQuickCLImageRunnable is aware of \c cl_khr_gl_event and will invoke + glFinish() and clFinish() as necessary in case the extension is not + supported. Both will be omitted when the extension is present. However, + clFinish() is still invoked regardless of the presence of the extension when + either the \c ForceCLFinish or \c Profile flags are set. + */ + +class QQuickCLImageRunnablePrivate +{ +public: + QQuickCLImageRunnablePrivate(QQuickCLItem *item, QQuickCLImageRunnable::Flags flags) + : item(item), + flags(flags), + queue(0), + inputTexture(0), + outputTexture(0), + elapsed(0) + { + image[0] = image[1] = 0; + profEv[0] = profEv[1] = 0; + sourcePropertyName = QByteArrayLiteral("source"); + } + + ~QQuickCLImageRunnablePrivate() { + if (image[0]) + clReleaseMemObject(image[0]); + if (image[1]) + clReleaseMemObject(image[1]); + if (queue) + clReleaseCommandQueue(queue); + delete outputTexture; + } + + QQuickCLItem *item; + QQuickCLImageRunnable::Flags flags; + cl_command_queue queue; + cl_mem image[2]; + QSize textureSize; + uint inputTexture; + QOpenGLTexture *outputTexture; + QByteArray sourcePropertyName; + cl_event profEv[2]; + double elapsed; + bool needsExplicitSync; +}; + +/*! + Constructs a new QQuickCLImageRunnable instance associated with \a item. + Special behavior, for example computations producing arbitrary non-image + output, can be enabled via \a flags. + */ +QQuickCLImageRunnable::QQuickCLImageRunnable(QQuickCLItem *item, Flags flags) + : d_ptr(new QQuickCLImageRunnablePrivate(item, flags)) +{ + Q_D(QQuickCLImageRunnable); + cl_int err; + cl_command_queue_properties queueProps = flags.testFlag(Profile) ? CL_QUEUE_PROFILING_ENABLE : 0; + d->queue = clCreateCommandQueue(item->context(), item->device(), queueProps, &err); + if (!d->queue) { + qWarning("Failed to create OpenCL command queue: %d", err); + return; + } + d->needsExplicitSync = !item->deviceExtensions().contains(QByteArrayLiteral("cl_khr_gl_event")); +} + +QQuickCLImageRunnable::~QQuickCLImageRunnable() +{ + delete d_ptr; +} + +/*! + \return the OpenCL command queue. + */ +cl_command_queue QQuickCLImageRunnable::commandQueue() const +{ + Q_D(const QQuickCLImageRunnable); + return d->queue; +} + +/*! + Sets the name of the property that is queried from the item that was passed + to the constructor. The default value is \c source. + */ +void QQuickCLImageRunnable::setSourcePropertyName(const QByteArray &name) +{ + Q_D(QQuickCLImageRunnable); + d->sourcePropertyName = name; +} + +QSGNode *QQuickCLImageRunnable::update(QSGNode *node) +{ + Q_D(QQuickCLImageRunnable); + QSGTextureProvider *textureProvider; + QSGTexture *texture; + QQuickItem *source = d->item->property(d->sourcePropertyName.constData()).value<QQuickItem *>(); + if (!source + || !source->isTextureProvider() + || !(textureProvider = source->textureProvider()) + || !(texture = textureProvider->texture())) { + delete node; + return 0; + } + + QSGDynamicTexture *dtex = qobject_cast<QSGDynamicTexture *>(texture); + if (dtex) + dtex->updateTexture(); + + if (!texture->textureId()) { // the texture provider may not be ready yet, try again later + d->item->scheduleUpdate(); + return node; + } + + if (d->inputTexture != uint(texture->textureId()) + || d->textureSize != texture->textureSize() + || (!d->flags.testFlag(NoOutputImage) && !d->outputTexture)) { + if (d->image[0]) + clReleaseMemObject(d->image[0]); + d->image[0] = 0; + if (d->image[1]) + clReleaseMemObject(d->image[1]); + d->image[1] = 0; + delete d->outputTexture; + d->outputTexture = 0; + delete node; + node = 0; + } + + cl_int err = 0; + if (!d->image[0]) + d->image[0] = clCreateFromGLTexture2D(d->item->context(), CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, + texture->textureId(), &err); + if (!d->image[0]) { + if (err == CL_INVALID_GL_OBJECT) // the texture provider may not be ready yet, try again later + d->item->scheduleUpdate(); + else + qWarning("Failed to create OpenCL image object from input OpenGL texture: %d", err); + return node; + } + + d->inputTexture = texture->textureId(); + d->textureSize = texture->textureSize(); + + const int imageCount = d->flags.testFlag(NoOutputImage) ? 1 : 2; + if (imageCount == 2) { + if (!d->outputTexture) + d->outputTexture = new QOpenGLTexture(QImage(d->textureSize, QImage::Format_RGB32)); + + if (!d->image[1]) + d->image[1] = clCreateFromGLTexture2D(d->item->context(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, + d->outputTexture->textureId(), &err); + if (!d->image[1]) { + qWarning("Failed to create OpenCL image object for output OpenGL texture: %d", err); + return node; + } + } + + if (d->needsExplicitSync) + QOpenGLContext::currentContext()->functions()->glFinish(); + + err = clEnqueueAcquireGLObjects(d->queue, imageCount, d->image, 0, 0, 0); + if (err != CL_SUCCESS) { + qWarning("Failed to queue acquiring the GL textures: %d", err); + return node; + } + + if (d->flags.testFlag(Profile)) + if (clEnqueueMarker(d->queue, &d->profEv[0]) != CL_SUCCESS) + qWarning("Failed to enqueue profiling marker (start)"); + + runKernel(d->image[0], d->image[1], d->textureSize); + + if (d->flags.testFlag(Profile)) + if (clEnqueueMarker(d->queue, &d->profEv[1]) != CL_SUCCESS) + qWarning("Failed to enqueue profiling marker (end)"); + + clEnqueueReleaseGLObjects(d->queue, imageCount, d->image, 0, 0, 0); + + if (d->flags.testFlag(ForceCLFinish) || d->needsExplicitSync || d->flags.testFlag(Profile)) + clFinish(d->queue); + + if (d->flags.testFlag(Profile)) { + cl_ulong start = 0, end = 0; + err = clGetEventProfilingInfo(d->profEv[0], CL_PROFILING_COMMAND_QUEUED, sizeof(cl_ulong), &start, 0); + if (err != CL_SUCCESS) + qWarning("Failed to get profiling info for start event: %d", err); + err = clGetEventProfilingInfo(d->profEv[1], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end, 0); + if (err != CL_SUCCESS) + qWarning("Failed to get profiling info for end event: %d", err); + d->elapsed = double(end - start) / 1000000.0; + clReleaseEvent(d->profEv[0]); + clReleaseEvent(d->profEv[1]); + } + + if (imageCount == 1) + return 0; + + QSGSimpleTextureNode *tnode = static_cast<QSGSimpleTextureNode *>(node); + if (!tnode) { + tnode = new QSGSimpleTextureNode; + tnode->setFiltering(QSGTexture::Linear); + tnode->setTexture(d->item->window()->createTextureFromId(d->outputTexture->textureId(), d->textureSize)); + } + tnode->setRect(d->item->boundingRect()); + tnode->markDirty(QSGNode::DirtyMaterial); + + return tnode; +} + +/*! + Returns the number of milliseconds spent on OpenCL operations during the + last finished invocation of runKernel(). + + \note OpenCL command queue profiling must be enabled by passing the \c Profile + flag to the constructor. + */ +double QQuickCLImageRunnable::elapsed() const +{ + Q_D(const QQuickCLImageRunnable); + return d->elapsed; +} + +QT_END_NAMESPACE diff --git a/src/quickcl/qquickclimagerunnable.h b/src/quickcl/qquickclimagerunnable.h new file mode 100644 index 0000000..8ca32b0 --- /dev/null +++ b/src/quickcl/qquickclimagerunnable.h @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QQUICKCLIMAGERUNNABLE_H +#define QQUICKCLIMAGERUNNABLE_H + +#include <QtQuickCL/qtquickclglobal.h> +#include <QtQuickCL/qquickclrunnable.h> + +QT_BEGIN_NAMESPACE + +class QQuickCLImageRunnablePrivate; +class QQuickCLItem; + +class Q_QUICKCL_EXPORT QQuickCLImageRunnable : public QQuickCLRunnable +{ + Q_DECLARE_PRIVATE(QQuickCLImageRunnable) + +public: + enum Flag { + NoOutputImage = 0x01, + Profile = 0x02, + ForceCLFinish = 0x04 + }; + Q_DECLARE_FLAGS(Flags, Flag) + + QQuickCLImageRunnable(QQuickCLItem *item, Flags flags = 0); + ~QQuickCLImageRunnable(); + + cl_command_queue commandQueue() const; + + void setSourcePropertyName(const QByteArray &name); + + double elapsed() const; + +protected: + virtual void runKernel(cl_mem inImage, cl_mem outImage, const QSize &size) = 0; + +private: + QSGNode *update(QSGNode *node) Q_DECL_OVERRIDE; + + QQuickCLImageRunnablePrivate *d_ptr; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(QQuickCLImageRunnable::Flags) + +QT_END_NAMESPACE + +#endif diff --git a/src/quickcl/qquickclitem.cpp b/src/quickcl/qquickclitem.cpp new file mode 100644 index 0000000..fa5933c --- /dev/null +++ b/src/quickcl/qquickclitem.cpp @@ -0,0 +1,385 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qquickclitem.h" +#include "qquickclcontext_p.h" +#include <QtCore/QAtomicInt> +#include <QtCore/QHash> +#include <QtCore/QFile> +#include <QtCore/QLoggingCategory> +#include <QtQuick/private/qquickitem_p.h> + +QT_BEGIN_NAMESPACE + +Q_DECLARE_LOGGING_CATEGORY(logCL) + +/*! + \class QQuickCLItem + + \brief QQuickCLItem is a QQuickItem that automatically gets an OpenCL + context with the proper platform and device chosen for CL-GL interop. + + Each instance of QQuickCLItem is backed by a corresponding QQuickCLRunnable. + + \note When animating properties that are used in OpenCL kernels, call the + \l{QQuickItem::update()}{update()} function (from the gui thread) to + trigger updates. + */ + +/*! + \class QQuickCLRunnable + + \brief QQuickCLRunnable instances live on the scenegraph's render thread + encapsulating OpenCL and related OpenGL resources. + + The constructor, destructor and update() are always invoked on the render + thread with the OpenGL context bound and the OpenCL context ready. This + allows easy usage of OpenCL and especially OpenGL resources without + worrying about lifetime and threading. They can simply be created in the + constructor and released in the destructor. + */ + +/*! + \fn QSGNode *QQuickCLRunnable::update(QSGNode *node) + + Called on the render thread every time the QQuickCLItem is updated. + Semantically equivalent to + \l{QQuickItem::updatePaintNode()}{updatePaintNode()}. + + It is up to the implementation to decide what to do here: it can launch + OpenCL operations, wait for them to finish, and return a scenegraph node, + for example a QSGSimpleTextureNode wrapping the resulting texture. + + Alternatively, it can also launch a longer running CL operation and return + \c null or a node providing some temporary content. Then, when the CL + operation is finished, \l{QQuickCLItem::scheduleUpdate()}{scheduleUpdate()} + is called from an OpenCL event callback to schedule an update for the Quick + item, which means eventually invoking this function again. This function + can then provide a new node with the results of the computation. + + \note When necessary, future updates for the QQuickCLItem can also be + scheduled from this function. However, this requires calling + QQuickCLItem::scheduleUpdate() instead of QQuickItem::update(). + */ + +/*! + \fn QQuickCLRunnable *QQuickCLItem::createCL() + + Factory function invoked on the render thread after initializing OpenCL. + */ + +class QQuickCLItemPrivate : public QQuickItemPrivate +{ + Q_DECLARE_PUBLIC(QQuickCLItem) + +public: + QQuickCLItemPrivate() : clctx(0), clnode(0) { } + + static void CL_CALLBACK eventCallback(cl_event event, cl_int status, void *user_data); + + QQuickCLContext *clctx; + QQuickCLRunnable *clnode; +}; + +QQuickCLItem::QQuickCLItem(QQuickItem *parent) + : QQuickItem(*new QQuickCLItemPrivate, parent) +{ + setFlag(ItemHasContents); +} + +/*! + \return the selected OpenCL platform. Matches the OpenGL context in use. + + \note The value is only available after the item is first rendered. It is + always safe to call this function from QQuickCLRunnable's constructor, + destructor and \l{QQuickCLRunnable::update()}{update()} function. + */ +cl_platform_id QQuickCLItem::platform() const +{ + Q_D(const QQuickCLItem); + return d->clctx ? d->clctx->platform() : 0; +} + +/*! + \return the selected OpenCL device. Matches the OpenGL context in use. + + \note The value is only available after the item is first rendered. It is + always safe to call this function from QQuickCLRunnable's constructor, + destructor and \l{QQuickCLRunnable::update()}{update()} function. + */ +cl_device_id QQuickCLItem::device() const +{ + Q_D(const QQuickCLItem); + return d->clctx ? d->clctx->device() : 0; +} + +/*! + \return the OpenCL context. + + \note The value is only available after the item is first rendered. It is + always safe to call this function from QQuickCLRunnable's constructor, + destructor and \l{QQuickCLRunnable::update()}{update()} function. + */ +cl_context QQuickCLItem::context() const +{ + Q_D(const QQuickCLItem); + return d->clctx ? d->clctx->context() : 0; +} + +QSGNode *QQuickCLItem::updatePaintNode(QSGNode *node, UpdatePaintNodeData *) +{ + Q_D(QQuickCLItem); + + if (width() <= 0 || height() <= 0) { + delete node; + return 0; + } + + // render thread, initialize CL if not yet done + if (!d->clctx) { + d->clctx = new QQuickCLContext; + if (!d->clctx->create()) { + qWarning("Failed to create OpenCL context"); + delete d->clctx; + d->clctx = 0; + } + } + + if (!d->clctx) + return 0; + + if (!d->clnode) + d->clnode = createCL(); + + return d->clnode ? d->clnode->update(node) : 0; +} + +class ReleaseRunnable : public QRunnable +{ +public: + ReleaseRunnable(QQuickCLContext *clctx, QQuickCLRunnable *clnode) : clctx(clctx), clnode(clnode) { } + void run() Q_DECL_OVERRIDE { + delete clnode; + delete clctx; + } +private: + QQuickCLContext *clctx; + QQuickCLRunnable *clnode; +}; + +void QQuickCLItem::releaseResources() +{ + // gui thread, just schedule. NB this and d may be dead by the time the runnable is run + Q_D(QQuickCLItem); + window()->scheduleRenderJob(new ReleaseRunnable(d->clctx, d->clnode), QQuickWindow::BeforeSynchronizingStage); + d->clnode = 0; + d->clctx = 0; +} + +void QQuickCLItem::invalidateSceneGraph() +{ + // render thread + Q_D(QQuickCLItem); + delete d->clnode; + d->clnode = 0; + delete d->clctx; + d->clctx = 0; +} + +static const int EV_UPDATE = QEvent::User + 128; +static const int EV_EVENT = QEvent::User + 129; + +class EventCompleteEvent : public QEvent +{ +public: + EventCompleteEvent(cl_event event) : QEvent(QEvent::Type(EV_EVENT)), event(event) { } + cl_event event; +}; + +bool QQuickCLItem::event(QEvent *e) +{ + if (e->type() == EV_UPDATE) { + update(); + return true; + } else if (e->type() == EV_EVENT) { + EventCompleteEvent *ev = static_cast<EventCompleteEvent *>(e); + eventCompleted(ev->event); + return true; + } + return QQuickItem::event(e); +} + +/*! + Schedules an update for the item. Unlike \l{QQuickItem::update()}{the base + class' update()}, this is safe to be called on any thread, hence it is safe + for use from CL event callbacks. + */ +void QQuickCLItem::scheduleUpdate() +{ + QCoreApplication::postEvent(this, new QEvent(QEvent::Type(EV_UPDATE))); +} + +/*! + \return the name of the current platform in use. + + \note This function can only be called from a QQuickCLRunnable's + constructor, destructor and \l{QQuickCLRunnable::update()}{update()} + function, or after the item has been rendered at least once. + */ +QByteArray QQuickCLItem::platformName() const +{ + QByteArray name(1024, '\0'); + clGetPlatformInfo(platform(), CL_PLATFORM_NAME, name.size(), name.data(), 0); + name.resize(int(strlen(name.constData()))); + return name; +} + +/*! + \return the list of device extensions. + + \note This function can only be called from a QQuickCLRunnable's + constructor, destructor and \l{QQuickCLRunnable::update()}{update()} + function, or after the item has been rendered at least once. + */ +QByteArray QQuickCLItem::deviceExtensions() const +{ + QByteArray ext(8192, '\0'); + clGetDeviceInfo(device(), CL_DEVICE_EXTENSIONS, ext.size(), ext.data(), 0); + ext.resize(int(strlen(ext.constData()))); + return ext; +} + +/*! + Creates and builds an OpenCL program from the source code in \a src. + + \return the cl_program or \c 0 when failed. Errors and build logs are + printed to the warning output. + + \note This function can only be called from a QQuickCLRunnable's + constructor, destructor and \l{QQuickCLRunnable::update()}{update()} + function, or after the item has been rendered at least once. + */ +cl_program QQuickCLItem::buildProgram(const QByteArray &src) +{ + cl_int err; + const char *str = src.constData(); + cl_program prog = clCreateProgramWithSource(context(), 1, &str, 0, &err); + if (!prog) { + qWarning("Failed to create OpenCL program: %d", err); + qWarning("Source was:\n%s", str); + return 0; + } + cl_device_id dev = device(); + err = clBuildProgram(prog, 1, &dev, 0, 0, 0); + if (err != CL_SUCCESS) { + qWarning("Failed to build OpenCL program: %d", err); + qWarning("Source was:\n%s", str); + QByteArray log; + log.resize(8192); + clGetProgramBuildInfo(prog, dev, CL_PROGRAM_BUILD_LOG, log.size(), log.data(), 0); + qWarning("Build log:\n%s", log.constData()); + return 0; + } + return prog; +} + +/*! + Creates and builds an OpenCL program from the source file \a filename. + + \sa buildProgram() + */ +cl_program QQuickCLItem::buildProgramFromFile(const QString &filename) +{ + QFile f(filename); + if (!f.open(QIODevice::ReadOnly | QIODevice::Text)) { + qWarning("Failed to open OpenCL program source file %s", qPrintable(filename)); + return 0; + } + return buildProgram(f.readAll()); +} + +struct EventCallbackParam +{ + EventCallbackParam(QQuickCLItem *item) : item(item) { } + QPointer<QQuickCLItem> item; +}; + +/*! + Registers an event callback for \a event. The virtual function + eventCompleted() will get invoked on the gui/main thread when the event + completes. + + This allows easy and safe asynchronous computations because the results can + directly be exposed to QML from eventCompleted() due to it running on the + gui/main thread. In addition it is guaranteed that eventCompleted() is + never called directly from the OpenCL callback function. Special cases like + destroying the QQuickCLItem before completing the event are also handled + gracefully. + + \note \a event is not released. + */ +void QQuickCLItem::watchEvent(cl_event event) +{ + EventCallbackParam *param = new EventCallbackParam(this); + cl_int err = clSetEventCallback(event, CL_COMPLETE, QQuickCLItemPrivate::eventCallback, param); + if (err != CL_SUCCESS) + qWarning("Failed to set event callback: %d", err); +} + +/*! + Called on the gui/main thread when the \a event watched via watchEvent() + completes. The default implementation does nothing. + */ +void QQuickCLItem::eventCompleted(cl_event event) +{ + Q_UNUSED(event); +} + +void CL_CALLBACK QQuickCLItemPrivate::eventCallback(cl_event event, cl_int status, void *user_data) +{ + if (status != CL_COMPLETE) + return; + EventCallbackParam *param = static_cast<EventCallbackParam *>(user_data); + if (!param->item.isNull()) + QCoreApplication::postEvent(param->item, new EventCompleteEvent(event)); + delete param; +} + +QQuickCLRunnable::~QQuickCLRunnable() +{ +} + +QT_END_NAMESPACE diff --git a/src/quickcl/qquickclitem.h b/src/quickcl/qquickclitem.h new file mode 100644 index 0000000..98ce7fc --- /dev/null +++ b/src/quickcl/qquickclitem.h @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QQUICKCLITEM_H +#define QQUICKCLITEM_H + +#include <QtQuickCL/qtquickclglobal.h> +#include <QtQuickCL/qquickclrunnable.h> +#include <QtQuick/qquickitem.h> + +QT_BEGIN_NAMESPACE + +class QQuickCLItemPrivate; + +class Q_QUICKCL_EXPORT QQuickCLItem : public QQuickItem +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QQuickCLItem) + +public: + QQuickCLItem(QQuickItem *parent = 0); + + cl_platform_id platform() const; + cl_device_id device() const; + cl_context context() const; + + void scheduleUpdate(); + + QByteArray platformName() const; + QByteArray deviceExtensions() const; + cl_program buildProgram(const QByteArray &src); + cl_program buildProgramFromFile(const QString &filename); + + void watchEvent(cl_event event); + virtual void eventCompleted(cl_event event); + +protected: + virtual QQuickCLRunnable *createCL() = 0; + +private slots: + void invalidateSceneGraph(); // called by QQuickWindow, must be a slot + +private: + QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *) Q_DECL_OVERRIDE; + void releaseResources() Q_DECL_OVERRIDE; + bool event(QEvent *) Q_DECL_OVERRIDE; +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/quickcl/qquickclrunnable.h b/src/quickcl/qquickclrunnable.h new file mode 100644 index 0000000..3086afd --- /dev/null +++ b/src/quickcl/qquickclrunnable.h @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QQUICKCLRUNNABLE_H +#define QQUICKCLRUNNABLE_H + +#include <QtQuickCL/qtquickclglobal.h> +#include <QtQuick/qsgnode.h> + +QT_BEGIN_NAMESPACE + +class Q_QUICKCL_EXPORT QQuickCLRunnable +{ +public: + virtual ~QQuickCLRunnable(); + virtual QSGNode *update(QSGNode *node) = 0; +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/quickcl/qtquickclglobal.h b/src/quickcl/qtquickclglobal.h new file mode 100644 index 0000000..1e459eb --- /dev/null +++ b/src/quickcl/qtquickclglobal.h @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the Qt Quick CL module +** +** $QT_BEGIN_LICENSE:LGPL3$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTQUICKCLGLOBAL_H +#define QTQUICKCLGLOBAL_H + +#include <QtCore/qglobal.h> + +#ifdef Q_OS_OSX +#include <OpenCL/opencl.h> +#include <OpenGL/OpenGL.h> +#else +#include <CL/opencl.h> +#endif + +QT_BEGIN_NAMESPACE + +#ifndef Q_QUICKCL_EXPORT +# ifndef QT_STATIC +# if defined(QT_BUILD_QUICKCL_LIB) +# define Q_QUICKCL_EXPORT Q_DECL_EXPORT +# else +# define Q_QUICKCL_EXPORT Q_DECL_IMPORT +# endif +# else +# define Q_QUICKCL_EXPORT +# endif +#endif + +QT_END_NAMESPACE + +#endif diff --git a/src/quickcl/quickcl.pro b/src/quickcl/quickcl.pro new file mode 100644 index 0000000..2a28924 --- /dev/null +++ b/src/quickcl/quickcl.pro @@ -0,0 +1,24 @@ +TARGET = QtQuickCL +QT = core core-private gui gui-private qml-private quick quick-private + +load(qt_module) + +DEFINES += QT_BUILD_QUICKCL_LIB + +HEADERS = \ + qtquickclglobal.h \ + qquickclcontext_p.h \ + qquickclitem.h \ + qquickclrunnable.h \ + qquickclimagerunnable.h + +SOURCES = \ + qquickclcontext.cpp \ + qquickclitem.cpp \ + qquickclimagerunnable.cpp + +QMAKE_DOCS = $$PWD/doc/qtquickcl.qdocconf + +osx: LIBS += -framework OpenCL +unix: !osx: LIBS += -lOpenCL +win32: !winrt: !wince*: LIBS += -lopengl32 -lOpenCL diff --git a/src/src.pro b/src/src.pro new file mode 100644 index 0000000..108b2c0 --- /dev/null +++ b/src/src.pro @@ -0,0 +1,3 @@ +TEMPLATE = subdirs +SUBDIRS += \ + quickcl diff --git a/sync.profile b/sync.profile new file mode 100644 index 0000000..92710c9 --- /dev/null +++ b/sync.profile @@ -0,0 +1,15 @@ +%modules = ( # path to module name map + "QtQuickCL" => "$basedir/src/quickcl", +); +%moduleheaders = ( # restrict the module headers to those found in relative path +); +# Module dependencies. +# Every module that is required to build this module should have one entry. +# Each of the module version specifiers can take one of the following values: +# - A specific Git revision. +# - any git symbolic ref resolvable from the module's repository (e.g. "refs/heads/master" to track master branch) +# +%dependencies = ( + "qtbase" => "refs/heads/master", + "qtdeclarative" => "refs/heads/master", +); |