aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLaszlo Agocs <laszlo.agocs@theqtcompany.com>2016-01-22 12:04:11 +0100
committerAndy Nichols <andy.nichols@theqtcompany.com>2016-01-22 11:19:49 +0000
commit9a95c33279cba9be6e34983c9a2bb1e6f300c2a3 (patch)
treeae849401a6c0d50df8bece7337e98b3675cbdfa7
parent41358da2d9806c4069263e01d8ecf7df3d7e1192 (diff)
Add QD3D12Window, a HLSL qmake rule and 8 examples
Change-Id: Ida7852af10e0236a5d80e95a0876fff6276b410c Reviewed-by: Andy Nichols <andy.nichols@theqtcompany.com>
-rw-r--r--.qmake.conf3
-rw-r--r--LICENSE.GPL674
-rw-r--r--LICENSE.LGPLv3173
-rw-r--r--README.md58
-rw-r--r--examples/examples.pro10
-rw-r--r--examples/hellocompressedtexture/hellocompressedtexture.pro23
-rw-r--r--examples/hellocompressedtexture/hellocompressedtexture.qrc5
-rw-r--r--examples/hellocompressedtexture/main.cpp67
-rw-r--r--examples/hellocompressedtexture/qt.ddsbin0 -> 174888 bytes
-rw-r--r--examples/hellocompressedtexture/shader.hlsl36
-rw-r--r--examples/hellocompressedtexture/window.cpp513
-rw-r--r--examples/hellocompressedtexture/window.h72
-rw-r--r--examples/hellodevicereset/hellodevicereset.pro17
-rw-r--r--examples/hellodevicereset/main.cpp69
-rw-r--r--examples/hellodevicereset/tdr.hlsl11
-rw-r--r--examples/hellodevicereset/window.cpp155
-rw-r--r--examples/hellodevicereset/window.h68
-rw-r--r--examples/hellogpumipmap/hellogpumipmap.pro29
-rw-r--r--examples/hellogpumipmap/hellogpumipmap.qrc5
-rw-r--r--examples/hellogpumipmap/main.cpp67
-rw-r--r--examples/hellogpumipmap/mipmapgen.hlsl60
-rw-r--r--examples/hellogpumipmap/qt.pngbin0 -> 11917 bytes
-rw-r--r--examples/hellogpumipmap/shader.hlsl36
-rw-r--r--examples/hellogpumipmap/window.cpp525
-rw-r--r--examples/hellogpumipmap/window.h78
-rw-r--r--examples/hellomultisample/hellomultisample.pro22
-rw-r--r--examples/hellomultisample/main.cpp73
-rw-r--r--examples/hellomultisample/shader.hlsl27
-rw-r--r--examples/hellomultisample/window.cpp274
-rw-r--r--examples/hellomultisample/window.h72
-rw-r--r--examples/hellooffscreen/hellooffscreen.pro32
-rw-r--r--examples/hellooffscreen/main.cpp74
-rw-r--r--examples/hellooffscreen/shader.hlsl52
-rw-r--r--examples/hellooffscreen/window.cpp541
-rw-r--r--examples/hellooffscreen/window.h95
-rw-r--r--examples/hellooffscreen_opengl/hellooffscreen_opengl.pro6
-rw-r--r--examples/hellooffscreen_opengl/hellooffscreen_opengl.qrc8
-rw-r--r--examples/hellooffscreen_opengl/main.cpp74
-rw-r--r--examples/hellooffscreen_opengl/shader_offscreen.frag6
-rw-r--r--examples/hellooffscreen_opengl/shader_offscreen.vert13
-rw-r--r--examples/hellooffscreen_opengl/shader_onscreen.frag8
-rw-r--r--examples/hellooffscreen_opengl/shader_onscreen.vert13
-rw-r--r--examples/hellooffscreen_opengl/window.cpp286
-rw-r--r--examples/hellooffscreen_opengl/window.h94
-rw-r--r--examples/hellotexture/hellotexture.pro23
-rw-r--r--examples/hellotexture/hellotexture.qrc5
-rw-r--r--examples/hellotexture/main.cpp71
-rw-r--r--examples/hellotexture/qt.pngbin0 -> 11917 bytes
-rw-r--r--examples/hellotexture/shader.hlsl36
-rw-r--r--examples/hellotexture/window.cpp406
-rw-r--r--examples/hellotexture/window.h72
-rw-r--r--examples/hellotriangle/hellotriangle.pro22
-rw-r--r--examples/hellotriangle/main.cpp65
-rw-r--r--examples/hellotriangle/shader.hlsl27
-rw-r--r--examples/hellotriangle/window.cpp263
-rw-r--r--examples/hellotriangle/window.h70
-rw-r--r--examples/hellowindow/hellowindow.pro5
-rw-r--r--examples/hellowindow/main.cpp51
-rw-r--r--examples/hellowindow/window.cpp95
-rw-r--r--examples/hellowindow/window.h58
-rw-r--r--features/hlsl.prf10
-rw-r--r--qd3d12window.pro1
-rw-r--r--src/d3d12window/d3d12window.pro14
-rw-r--r--src/d3d12window/qd3d12window.cpp677
-rw-r--r--src/d3d12window/qd3d12window.h127
-rw-r--r--src/d3d12window/qd3d12windowglobal.h52
-rw-r--r--src/src.pro2
-rw-r--r--sync.profile6
68 files changed, 6682 insertions, 0 deletions
diff --git a/.qmake.conf b/.qmake.conf
new file mode 100644
index 0000000..71766f0
--- /dev/null
+++ b/.qmake.conf
@@ -0,0 +1,3 @@
+load(qt_build_config)
+MODULE_VERSION = 5.6.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..4a97fa7
--- /dev/null
+++ b/README.md
@@ -0,0 +1,58 @@
+QtD3D12Window is a Qt 5.6 module providing a QD3D12Window class
+similar to QOpenGLWindow, a handy qmake rule for offline HLSL shader
+compilation via fxc, and a number of basic examples.
+
+In the .pro file, add:
+
+ QT += d3d12window
+
+Then use it like QOpenGLWindow:
+
+ class Window : public QD3D12Window
+ {
+ public:
+ void initializeD3D() { create command list etc. }
+ void resizeD3D(const QSize &size) { ... }
+ void paintD3D() { populate and execute command list }
+ void afterPresent() { wait as necessary }
+ };
+
+Use QWidget::createWindowContainer() to embed into widget-based UIs.
+
+To use the qmake rule to generate headers from shaders at build time,
+copy hlsl.prf to mkspecs/features folder of the Qt SDK.
+
+ VSPS = shader.hlsl
+
+ vshader.input = VSPS
+ vshader.header = shader_vs.h
+ vshader.entry = VS_MyShader
+ vshader.type = vs_5_0
+
+ pshader.input = VSPS
+ pshader.header = shader_ps.h
+ pshader.entry = PS_MyShader
+ pshader.type = ps_5_0
+
+ HLSL_SHADERS = vshader pshader
+ load(hlsl)
+
+Examples in order of increasing complexity:
+
+1. hellowindow - Bringing up a window and clearing the backbuffer
+
+2. hellodevicereset - Handle device removed errors and make the application able to survive a driver update, shader timeout, etc.
+
+3. hellotriangle - Basic rendering, shader and pipeline setup, constant buffers
+
+4. hellotexture - Texturing, mipmaps
+
+5. hellooffscreen - Rendering into offscreen render targets, then using them from the pixel shader
+
+ hellooffscreen_opengl - OpenGL version, for comparing performance, overhead, etc.
+
+6. hellomultisample - Rendering with MSAA
+
+7. hellocompressedtexture - Compressed textures loaded from DDS files
+
+8. hellogpumipmap - Mipmap generation via compute shaders
diff --git a/examples/examples.pro b/examples/examples.pro
new file mode 100644
index 0000000..9f8ae64
--- /dev/null
+++ b/examples/examples.pro
@@ -0,0 +1,10 @@
+TEMPLATE = subdirs
+SUBDIRS += hellowindow \
+ hellotriangle \
+ hellotexture \
+ hellooffscreen \
+ hellooffscreen_opengl \
+ hellomultisample \
+ hellogpumipmap \
+ hellocompressedtexture \
+ hellodevicereset
diff --git a/examples/hellocompressedtexture/hellocompressedtexture.pro b/examples/hellocompressedtexture/hellocompressedtexture.pro
new file mode 100644
index 0000000..6db7ae5
--- /dev/null
+++ b/examples/hellocompressedtexture/hellocompressedtexture.pro
@@ -0,0 +1,23 @@
+TEMPLATE = app
+QT += d3d12window widgets
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
+RESOURCES = hellocompressedtexture.qrc
+
+LIBS = -ld3d12
+
+VSPS = shader.hlsl
+
+vshader.input = VSPS
+vshader.header = shader_vs.h
+vshader.entry = VS_Texture
+vshader.type = vs_5_0
+
+pshader.input = VSPS
+pshader.header = shader_ps.h
+pshader.entry = PS_Texture
+pshader.type = ps_5_0
+
+HLSL_SHADERS = vshader pshader
+load(hlsl)
diff --git a/examples/hellocompressedtexture/hellocompressedtexture.qrc b/examples/hellocompressedtexture/hellocompressedtexture.qrc
new file mode 100644
index 0000000..2f44da8
--- /dev/null
+++ b/examples/hellocompressedtexture/hellocompressedtexture.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>qt.dds</file>
+</qresource>
+</RCC>
diff --git a/examples/hellocompressedtexture/main.cpp b/examples/hellocompressedtexture/main.cpp
new file mode 100644
index 0000000..c00dd81
--- /dev/null
+++ b/examples/hellocompressedtexture/main.cpp
@@ -0,0 +1,67 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QWidget>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QLabel>
+#include <QScrollArea>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Window *d3dw = new Window;
+ QWidget w;
+ QVBoxLayout *vl = new QVBoxLayout;
+ vl->addWidget(new QPushButton("Widgets + a native child window with D3D12, this time in a scroll area"));
+ vl->addWidget(new QLabel("Unlike hellotexture, the image is now loaded from a DDS file (BC1) instead of a PNG"));
+ QWidget *ww = QWidget::createWindowContainer(d3dw);
+ ww->setMinimumSize(100, 100);
+ vl->addWidget(ww);
+ vl->setStretchFactor(ww, 1.0f);
+ w.resize(300, 300);
+ w.setLayout(vl);
+ w.show();
+
+ return app.exec();
+}
diff --git a/examples/hellocompressedtexture/qt.dds b/examples/hellocompressedtexture/qt.dds
new file mode 100644
index 0000000..1581cfb
--- /dev/null
+++ b/examples/hellocompressedtexture/qt.dds
Binary files differ
diff --git a/examples/hellocompressedtexture/shader.hlsl b/examples/hellocompressedtexture/shader.hlsl
new file mode 100644
index 0000000..be69b39
--- /dev/null
+++ b/examples/hellocompressedtexture/shader.hlsl
@@ -0,0 +1,36 @@
+cbuffer ConstantBuffer : register(b0)
+{
+ float4x4 modelview;
+ float4x4 projection;
+};
+
+struct VSInput
+{
+ float4 position : POSITION;
+ float2 coord : TEXCOORD0;
+};
+
+struct PSInput
+{
+ float4 position : SV_POSITION;
+ float2 coord : TEXCOORD0;
+};
+
+Texture2D tex : register(t0);
+SamplerState samp : register(s0);
+
+PSInput VS_Texture(VSInput input)
+{
+ PSInput result;
+
+ float4x4 mvp = mul(projection, modelview);
+ result.position = mul(mvp, input.position);
+ result.coord = input.coord;
+
+ return result;
+}
+
+float4 PS_Texture(PSInput input) : SV_TARGET
+{
+ return tex.Sample(samp, input.coord);
+}
diff --git a/examples/hellocompressedtexture/window.cpp b/examples/hellocompressedtexture/window.cpp
new file mode 100644
index 0000000..74c7e6a
--- /dev/null
+++ b/examples/hellocompressedtexture/window.cpp
@@ -0,0 +1,513 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+#include "shader_vs.h"
+#include "shader_ps.h"
+#include <QFile>
+
+Window::Window()
+ : f(Q_NULLPTR),
+ cbPtr(Q_NULLPTR),
+ rotationAngle(0)
+{
+}
+
+Window::~Window()
+{
+ if (cbPtr)
+ constantBuffer->Unmap(0, Q_NULLPTR);
+
+ delete f;
+}
+
+static const quint32 DDS_MAGIC = 0x20534444; // 'DDS '
+static const quint32 DDS_FOURCC = 4;
+
+#define FOURCC(c0, c1, c2, c3) ((c0) | ((c1) << 8) | ((c2) << 16) | ((c3 << 24)))
+
+struct DDS_PIXELFORMAT {
+ quint32 size;
+ quint32 flags;
+ quint32 fourCC;
+ quint32 rgbBitCount;
+ quint32 rBitMask;
+ quint32 gBitMask;
+ quint32 bBitMask;
+ quint32 aBitMask;
+};
+
+struct DDS_HEADER {
+ quint32 size;
+ quint32 flags;
+ quint32 height;
+ quint32 width;
+ quint32 pitch;
+ quint32 depth;
+ quint32 mipMapCount;
+ quint32 reserved1[11];
+ DDS_PIXELFORMAT pixelFormat;
+ quint32 caps;
+ quint32 caps2;
+ quint32 caps3;
+ quint32 caps4;
+ quint32 reserved2;
+};
+
+static quint32 unalignedDxt1Size(const QSize &size, quint32 *bpl = Q_NULLPTR, quint32 *vertBlocks = Q_NULLPTR)
+{
+ static const quint32 blockSize = 8; // 8 bytes for BC1
+ const quint32 bytesPerLine = qMax<quint32>(1, (size.width() + 3) / 4) * blockSize;
+ const quint32 ySize = qMax<quint32>(1, (size.height() + 3) / 4);
+ if (bpl)
+ *bpl = bytesPerLine;
+ if (vertBlocks)
+ *vertBlocks = ySize;
+ return bytesPerLine * ySize;
+}
+
+// We only support DXT1 (BC1) for the demo's purposes.
+static QByteArrayList loadDXT1(const QString &filename, DXGI_FORMAT *format, QSize *size, int *mipLevelCount)
+{
+ QFile f(filename);
+ if (!f.open(QIODevice::ReadOnly)) {
+ qWarning("Failed to open %s", qPrintable(filename));
+ return QByteArrayList();
+ }
+
+ quint32 magic = 0;
+ f.read(reinterpret_cast<char *>(&magic), sizeof(magic));
+ if (magic != DDS_MAGIC) {
+ qWarning("%s is not a DDS file", qPrintable(filename));
+ return QByteArrayList();
+ }
+ DDS_HEADER header;
+ f.read(reinterpret_cast<char *>(&header), sizeof(header));
+ if (header.size != sizeof(DDS_HEADER)) {
+ qWarning("Invalid DDS header size");
+ return QByteArrayList();
+ }
+ if (header.pixelFormat.size != sizeof(DDS_PIXELFORMAT)) {
+ qWarning("Invalid DDS pixel format size");
+ return QByteArrayList();
+ }
+ if (!(header.pixelFormat.flags & DDS_FOURCC)) {
+ qWarning("Invalid DDS pixel format");
+ return QByteArrayList();
+ }
+ if (header.pixelFormat.fourCC != FOURCC('D', 'X', 'T', '1')) {
+ qWarning("Only DXT1 (BC1) is supported");
+ return QByteArrayList();
+ }
+
+ QByteArrayList data;
+ QSize sz(header.width, header.height);
+ for (quint32 level = 0; level < header.mipMapCount; ++level) {
+ data.append(f.read(unalignedDxt1Size(sz)));
+ sz.setWidth(qMax(1, sz.width() / 2));
+ sz.setHeight(qMax(1, sz.height() / 2));
+ }
+
+ *format = DXGI_FORMAT_BC1_UNORM;
+ *size = QSize(header.width, header.height);
+ *mipLevelCount = header.mipMapCount;
+
+ return data;
+}
+
+void Window::initializeD3D()
+{
+ DXGI_FORMAT textureFormat;
+ QSize textureSize;
+ int mipLevels;
+ QByteArrayList texData = loadDXT1(QStringLiteral(":/qt.dds"), &textureFormat, &textureSize, &mipLevels);
+ if (texData.isEmpty())
+ return;
+
+ f = createFence();
+ ID3D12Device *dev = device();
+
+ // One static sampler (no sampler heap is needed).
+ D3D12_STATIC_SAMPLER_DESC sampler = {};
+ sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
+ sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.MinLOD = 0.0f;
+ sampler.MaxLOD = D3D12_FLOAT32_MAX;
+ sampler.ShaderRegister = 0;
+ sampler.RegisterSpace = 0;
+ sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
+
+ // In addition to the constant buffer view we will now also have a shader
+ // resource view in order to expose the texture to the pixel shader.
+ D3D12_DESCRIPTOR_RANGE descRange[2];
+ descRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
+ descRange[0].NumDescriptors = 1;
+ descRange[0].BaseShaderRegister = 0; // b0
+ descRange[0].RegisterSpace = 0;
+ descRange[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+ descRange[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
+ descRange[1].NumDescriptors = 1;
+ descRange[1].BaseShaderRegister = 0; // t0
+ descRange[1].RegisterSpace = 0;
+ descRange[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+
+ D3D12_ROOT_PARAMETER rootParameter;
+ rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rootParameter.DescriptorTable.NumDescriptorRanges = 2;
+ rootParameter.DescriptorTable.pDescriptorRanges = descRange;
+
+ D3D12_ROOT_SIGNATURE_DESC desc;
+ desc.NumParameters = 1;
+ desc.pParameters = &rootParameter;
+ desc.NumStaticSamplers = 1;
+ desc.pStaticSamplers = &sampler;
+ desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ qWarning("Failed to serialize root signature");
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&rootSignature)))) {
+ qWarning("Failed to create root signature");
+ return;
+ }
+
+ D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
+ };
+
+ D3D12_SHADER_BYTECODE vshader;
+ vshader.pShaderBytecode = g_VS_Texture;
+ vshader.BytecodeLength = sizeof(g_VS_Texture);
+ D3D12_SHADER_BYTECODE pshader;
+ pshader.pShaderBytecode = g_PS_Texture;
+ pshader.BytecodeLength = sizeof(g_PS_Texture);
+
+ D3D12_RASTERIZER_DESC rastDesc = {};
+ rastDesc.FillMode = D3D12_FILL_MODE_SOLID;
+ rastDesc.CullMode = D3D12_CULL_MODE_BACK;
+ rastDesc.FrontCounterClockwise = TRUE; // Vertices are given CCW
+ rastDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
+ rastDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
+ rastDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
+ rastDesc.DepthClipEnable = TRUE;
+
+ // Our material is transparent (the image has alpha < 255). Enable blending.
+ const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {
+ TRUE, FALSE,
+ D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD,
+ D3D12_BLEND_ZERO, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
+ D3D12_LOGIC_OP_NOOP,
+ D3D12_COLOR_WRITE_ENABLE_ALL
+ };
+ D3D12_BLEND_DESC blendDesc = {};
+ blendDesc.RenderTarget[0] = defaultRenderTargetBlendDesc;
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
+ psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
+ psoDesc.pRootSignature = rootSignature.Get();
+ psoDesc.VS = vshader;
+ psoDesc.PS = pshader;
+ psoDesc.RasterizerState = rastDesc;
+ psoDesc.BlendState = blendDesc;
+ psoDesc.DepthStencilState.DepthEnable = TRUE;
+ psoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
+ psoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
+ psoDesc.DepthStencilState.StencilEnable = FALSE;
+ psoDesc.SampleMask = UINT_MAX;
+ psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ psoDesc.NumRenderTargets = 1;
+ psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
+ psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
+ psoDesc.SampleDesc.Count = 1;
+ if (FAILED(dev->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pipelineState)))) {
+ qWarning("Failed to create graphics pipeline state");
+ return;
+ }
+
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator(), Q_NULLPTR, IID_PPV_ARGS(&commandList)))) {
+ qWarning("Failed to create command list");
+ return;
+ }
+
+ // Vertex buffer
+ const float vertices[] = {
+ -0.5f, -0.5f, 0, /* coords */ 0, 1, // the image was not flipped so accommodate for it here
+ 0.5f, -0.5f, 0, 1, 1,
+ -0.5f, 0.5f, 0, 0, 0,
+
+ -0.5f, 0.5f, 0, 0, 0,
+ 0.5f, -0.5f, 0, 1, 1,
+ 0.5f, 0.5f, 0, 1, 0
+ };
+ const UINT vertexBufferSize = sizeof(vertices);
+
+ D3D12_HEAP_PROPERTIES defaultHeapProp = {};
+ defaultHeapProp.Type = D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_HEAP_PROPERTIES uploadHeapProp = defaultHeapProp;
+ uploadHeapProp.Type = D3D12_HEAP_TYPE_UPLOAD;
+
+ D3D12_RESOURCE_DESC bufDesc = {};
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufDesc.Width = vertexBufferSize;
+ bufDesc.Height = 1;
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufDesc.SampleDesc.Count = 1;
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&vertexBuffer)))) {
+ qWarning("Failed to create committed resource (vertex buffer)");
+ return;
+ }
+
+ quint8 *p = Q_NULLPTR;
+ D3D12_RANGE readRange = { 0, 0 };
+ if (FAILED(vertexBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (vertex buffer)");
+ return;
+ }
+ memcpy(p, vertices, vertexBufferSize);
+ vertexBuffer->Unmap(0, Q_NULLPTR);
+
+ vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();
+ vertexBufferView.StrideInBytes = (3 + 2) * sizeof(float);
+ vertexBufferView.SizeInBytes = vertexBufferSize;
+
+ // Constant buffer
+ const UINT CB_SIZE = alignedCBSize(128); // 2 * float4x4
+ bufDesc.Width = CB_SIZE;
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&constantBuffer)))) {
+ qWarning("Failed to create committed resource (constant buffer)");
+ return;
+ }
+
+ if (FAILED(constantBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (constant buffer)");
+ return;
+ }
+ cbPtr = p; // won't Unmap() this here
+
+ // Texture (with mipmaps, if the DDS file provided them)
+ D3D12_RESOURCE_DESC textureDesc = {};
+ textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+ textureDesc.Width = textureSize.width();
+ textureDesc.Height = textureSize.height();
+ textureDesc.DepthOrArraySize = 1;
+ textureDesc.MipLevels = mipLevels;
+ textureDesc.Format = textureFormat;
+ textureDesc.SampleDesc.Count = 1;
+ textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
+
+ // Ignore UMA for now and do the discrete-friendly upload via an upload buffer (no CPU access to the texture).
+ if (FAILED(dev->CreateCommittedResource(&defaultHeapProp, D3D12_HEAP_FLAG_NONE, &textureDesc,
+ D3D12_RESOURCE_STATE_COPY_DEST, Q_NULLPTR, IID_PPV_ARGS(&texture)))) {
+ qWarning("Failed to create texture resource");
+ return;
+ }
+
+ ComPtr<ID3D12Resource> textureUploadBuffer;
+ const int MAX_MIP_LEVELS = 16;
+ Q_ASSERT(mipLevels <= MAX_MIP_LEVELS);
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT textureLayout[MAX_MIP_LEVELS];
+ quint32 unalignedPitch[MAX_MIP_LEVELS], pitch[MAX_MIP_LEVELS], vertBlocks[MAX_MIP_LEVELS];
+ int mipOffset = 0;
+ QSize mipSize = textureSize;
+ // Fill out the offset and footprint info ourselves as GetCopyableFootprints does not seem to work with compressed formats.
+ // Offset and pitch must be aligned as required.
+ for (int level = 0; level < mipLevels; ++level) {
+ unalignedDxt1Size(mipSize, &unalignedPitch[level], &vertBlocks[level]);
+ pitch[level] = alignedTexturePitch(unalignedPitch[level]);
+ textureLayout[level].Offset = mipOffset;
+ textureLayout[level].Footprint.Format = DXGI_FORMAT_BC1_UNORM;
+ textureLayout[level].Footprint.Width = mipSize.width();
+ textureLayout[level].Footprint.Height = mipSize.height();
+ textureLayout[level].Footprint.Depth = 1;
+ textureLayout[level].Footprint.RowPitch = pitch[level];
+ mipOffset += alignedTextureOffset(pitch[level] * vertBlocks[level]);
+ mipSize.setWidth(qMax(1, mipSize.width() / 2));
+ mipSize.setHeight(qMax(1, mipSize.height() / 2));
+ }
+ bufDesc.Width = mipOffset;
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&textureUploadBuffer)))) {
+ qWarning("Failed to create texture upload buffer resource");
+ return;
+ }
+
+ if (FAILED(textureUploadBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (texture upload buffer)");
+ return;
+ }
+ // Have to copy line-by-line to account for the potentially bigger row pitch in the upload buffer.
+ for (int level = 0; level < mipLevels; ++level) {
+ quint8 *dst = p + textureLayout[level].Offset;
+ const quint8 *src = (const quint8 *) texData[level].constData();
+ for (quint32 y = 0; y < vertBlocks[level]; ++y) {
+ memcpy(dst, src, unalignedPitch[level]);
+ src += unalignedPitch[level];
+ dst += pitch[level];
+ }
+ }
+ textureUploadBuffer->Unmap(0, Q_NULLPTR);
+
+ for (int level = 0; level < mipLevels; ++level) {
+ D3D12_TEXTURE_COPY_LOCATION dstLoc;
+ dstLoc.pResource = texture.Get();
+ dstLoc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ dstLoc.SubresourceIndex = level;
+ D3D12_TEXTURE_COPY_LOCATION srcLoc;
+ srcLoc.pResource = textureUploadBuffer.Get();
+ srcLoc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ srcLoc.PlacedFootprint = textureLayout[level];
+ commandList->CopyTextureRegion(&dstLoc, 0, 0, 0, &srcLoc, Q_NULLPTR);
+ }
+
+ // once the copy is done the texture is ready to be used from the pixel shader
+ transitionResource(texture.Get(), commandList.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
+
+ // Constant buffer view and shader resource view descriptors are stored in the same heap.
+ const UINT cbvSrvStride = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+ D3D12_DESCRIPTOR_HEAP_DESC cbvSrvHeapDesc = {};
+ cbvSrvHeapDesc.NumDescriptors = 2;
+ cbvSrvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
+ cbvSrvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
+ if (FAILED(dev->CreateDescriptorHeap(&cbvSrvHeapDesc, IID_PPV_ARGS(&cbvSrvHeap)))) {
+ qWarning("Failed to create CBV/SRV/UAV descriptor heap");
+ return;
+ }
+
+ D3D12_CPU_DESCRIPTOR_HANDLE cbvSrvHandle = cbvSrvHeap->GetCPUDescriptorHandleForHeapStart();
+ D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
+ cbvDesc.BufferLocation = constantBuffer->GetGPUVirtualAddress();
+ cbvDesc.SizeInBytes = CB_SIZE;
+ dev->CreateConstantBufferView(&cbvDesc, cbvSrvHandle);
+ cbvSrvHandle.ptr += cbvSrvStride;
+
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
+ srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ srvDesc.Format = textureDesc.Format;
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
+ srvDesc.Texture2D.MipLevels = mipLevels;
+ dev->CreateShaderResourceView(texture.Get(), &srvDesc, cbvSrvHandle);
+
+ // Execute the texture upload.
+ commandList->Close();
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ // Block until all the above has finished.
+ waitForGPU(f);
+
+ setupProjection();
+}
+
+void Window::resizeD3D(const QSize &)
+{
+ setupProjection();
+}
+
+void Window::setupProjection()
+{
+ projection.setToIdentity();
+ projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::paintD3D()
+{
+ modelview.setToIdentity();
+ modelview.translate(0, 0, -2);
+ // our highly sophisticated animation
+ modelview.rotate(rotationAngle, 0, 0, 1);
+ rotationAngle += 1;
+
+ memcpy(cbPtr, modelview.constData(), 16 * sizeof(float));
+ memcpy(cbPtr + 16 * sizeof(float), projection.constData(), 16 * sizeof(float));
+
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), pipelineState.Get());
+
+ commandList->SetGraphicsRootSignature(rootSignature.Get());
+
+ ID3D12DescriptorHeap *heaps[] = { cbvSrvHeap.Get() };
+ commandList->SetDescriptorHeaps(_countof(heaps), heaps);
+ commandList->SetGraphicsRootDescriptorTable(0, cbvSrvHeap->GetGPUDescriptorHandleForHeapStart());
+
+ D3D12_VIEWPORT viewport = { 0, 0, float(width()), float(height()), 0, 1 };
+ commandList->RSSetViewports(1, &viewport);
+ D3D12_RECT scissorRect = { 0, 0, width() - 1, height() - 1 };
+ commandList->RSSetScissorRects(1, &scissorRect);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
+
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = backBufferRenderTargetCPUHandle();
+ D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = depthStencilCPUHandle();
+ commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
+
+ const float clearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };
+ commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, Q_NULLPTR);
+ commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, Q_NULLPTR);
+
+ commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ commandList->IASetVertexBuffers(0, 1, &vertexBufferView);
+ commandList->DrawInstanced(6, 1, 0, 0);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
+ commandList->Close();
+
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ update();
+}
+
+void Window::afterPresent()
+{
+ waitForGPU(f);
+}
diff --git a/examples/hellocompressedtexture/window.h b/examples/hellocompressedtexture/window.h
new file mode 100644
index 0000000..a0fef7b
--- /dev/null
+++ b/examples/hellocompressedtexture/window.h
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QD3D12Window>
+#include <QMatrix4x4>
+
+class Window : public QD3D12Window
+{
+public:
+ Window();
+ ~Window();
+
+ void initializeD3D() Q_DECL_OVERRIDE;
+ void resizeD3D(const QSize &size) Q_DECL_OVERRIDE;
+ void paintD3D() Q_DECL_OVERRIDE;
+ void afterPresent() Q_DECL_OVERRIDE;
+
+private:
+ void setupProjection();
+
+ Fence *f;
+ ComPtr<ID3D12GraphicsCommandList> commandList;
+ ComPtr<ID3D12PipelineState> pipelineState;
+ ComPtr<ID3D12RootSignature> rootSignature;
+ ComPtr<ID3D12Resource> vertexBuffer;
+ ComPtr<ID3D12Resource> constantBuffer;
+ ComPtr<ID3D12Resource> texture;
+ ComPtr<ID3D12DescriptorHeap> cbvSrvHeap;
+ D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
+
+ QMatrix4x4 projection;
+ QMatrix4x4 modelview;
+ quint8 *cbPtr;
+ float rotationAngle;
+};
diff --git a/examples/hellodevicereset/hellodevicereset.pro b/examples/hellodevicereset/hellodevicereset.pro
new file mode 100644
index 0000000..bf95b25
--- /dev/null
+++ b/examples/hellodevicereset/hellodevicereset.pro
@@ -0,0 +1,17 @@
+TEMPLATE = app
+QT += d3d12window widgets
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
+
+LIBS = -ld3d12
+
+CS = tdr.hlsl
+
+shader.input = CS
+shader.header = tdr.h
+shader.entry = timeout
+shader.type = cs_5_0
+
+HLSL_SHADERS = shader
+load(hlsl)
diff --git a/examples/hellodevicereset/main.cpp b/examples/hellodevicereset/main.cpp
new file mode 100644
index 0000000..fb301b2
--- /dev/null
+++ b/examples/hellodevicereset/main.cpp
@@ -0,0 +1,69 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QWidget>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QLabel>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Window *d3dw = new Window;
+ QWidget w;
+ QVBoxLayout *vl = new QVBoxLayout;
+ QPushButton *btn = new QPushButton("Generate a timeout and reset the GPU");
+ QObject::connect(btn, &QPushButton::clicked, d3dw, &Window::timeout);
+ vl->addWidget(btn);
+ vl->addWidget(new QLabel("Due to handling device removed errors and correctly releasing and reinitializing,\n"
+ "the application should be able to survive. Watch the debug output."));
+ QWidget *ww = QWidget::createWindowContainer(d3dw);
+ ww->setMinimumHeight(300);
+ vl->addWidget(ww);
+ vl->setStretchFactor(ww, 1.0f);
+ w.resize(400, 400);
+ w.setLayout(vl);
+ w.show();
+
+ return app.exec();
+}
diff --git a/examples/hellodevicereset/tdr.hlsl b/examples/hellodevicereset/tdr.hlsl
new file mode 100644
index 0000000..f32d4fb
--- /dev/null
+++ b/examples/hellodevicereset/tdr.hlsl
@@ -0,0 +1,11 @@
+// http://gamedev.stackexchange.com/questions/108141/how-can-i-test-dxgi-error-device-removed-error-handling
+
+RWBuffer<uint> uav;
+cbuffer ConstantBuffer { uint zero; }
+
+[numthreads(256, 1, 1)]
+void timeout(uint3 id: SV_DispatchThreadID)
+{
+ while (zero == 0)
+ uav[id.x] = zero;
+}
diff --git a/examples/hellodevicereset/window.cpp b/examples/hellodevicereset/window.cpp
new file mode 100644
index 0000000..ff7f313
--- /dev/null
+++ b/examples/hellodevicereset/window.cpp
@@ -0,0 +1,155 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+#include "tdr.h"
+
+void Window::initializeD3D()
+{
+ f.reset(createFence());
+ ID3D12Device *dev = device();
+
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator(), Q_NULLPTR,
+ IID_PPV_ARGS(&commandList)))) {
+ qWarning("Failed to create command list");
+ return;
+ }
+ commandList->Close();
+
+ D3D12_DESCRIPTOR_RANGE descRange[2];
+ descRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
+ descRange[0].NumDescriptors = 1;
+ descRange[0].BaseShaderRegister = 0;
+ descRange[0].RegisterSpace = 0;
+ descRange[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+ descRange[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
+ descRange[1].NumDescriptors = 1;
+ descRange[1].BaseShaderRegister = 0;
+ descRange[1].RegisterSpace = 0;
+ descRange[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+
+ D3D12_ROOT_PARAMETER param;
+ param.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ param.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ param.DescriptorTable.NumDescriptorRanges = 2;
+ param.DescriptorTable.pDescriptorRanges = descRange;
+
+ D3D12_ROOT_SIGNATURE_DESC desc = {};
+ desc.NumParameters = 1;
+ desc.pParameters = &param;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ QByteArray msg(static_cast<const char *>(error->GetBufferPointer()), error->GetBufferSize());
+ qWarning("Failed to serialize compute root signature: %s", qPrintable(msg));
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(),
+ IID_PPV_ARGS(&computeRootSignature)))) {
+ qWarning("Failed to create compute root signature");
+ return;
+ }
+
+ D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {};
+ psoDesc.pRootSignature = computeRootSignature.Get();
+ psoDesc.CS.pShaderBytecode = g_timeout;
+ psoDesc.CS.BytecodeLength = sizeof(g_timeout);
+
+ if (FAILED(dev->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&computeState)))) {
+ qWarning("Failed to create compute pipeline state");
+ return;
+ }
+}
+
+void Window::releaseD3D()
+{
+ // Release all resources. initializeD3D() will get invoked later on.
+ commandList = Q_NULLPTR;
+ computeState = Q_NULLPTR;
+ computeRootSignature = Q_NULLPTR;
+ f.reset();
+}
+
+void Window::resizeD3D(const QSize &)
+{
+}
+
+void Window::paintD3D()
+{
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), Q_NULLPTR);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
+
+ green += 0.01f;
+ if (green > 1.0f)
+ green = 0.0f;
+ const float clearColor[] = { 0.0f, green, 0.0f, 1.0f };
+ commandList->ClearRenderTargetView(backBufferRenderTargetCPUHandle(), clearColor, 0, Q_NULLPTR);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
+
+ commandList->Close();
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ update();
+}
+
+void Window::afterPresent()
+{
+ waitForGPU(f.data());
+}
+
+void Window::timeout()
+{
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), computeState.Get());
+
+ commandList->SetComputeRootSignature(computeRootSignature.Get());
+ commandList->Dispatch(256, 1, 1);
+
+ commandList->Close();
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ waitForGPU(f.data());
+}
diff --git a/examples/hellodevicereset/window.h b/examples/hellodevicereset/window.h
new file mode 100644
index 0000000..2de75bc
--- /dev/null
+++ b/examples/hellodevicereset/window.h
@@ -0,0 +1,68 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QD3D12Window>
+
+class Window : public QD3D12Window
+{
+ Q_OBJECT
+
+public:
+ Window() : green(0) { }
+
+ void initializeD3D() Q_DECL_OVERRIDE;
+ void releaseD3D() Q_DECL_OVERRIDE;
+ void resizeD3D(const QSize &size) Q_DECL_OVERRIDE;
+ void paintD3D() Q_DECL_OVERRIDE;
+ void afterPresent() Q_DECL_OVERRIDE;
+
+public slots:
+ void timeout();
+
+private:
+ void setupProjection();
+
+ QScopedPointer<Fence> f;
+ ComPtr<ID3D12GraphicsCommandList> commandList;
+ ComPtr<ID3D12PipelineState> computeState;
+ ComPtr<ID3D12RootSignature> computeRootSignature;
+
+ float green;
+};
diff --git a/examples/hellogpumipmap/hellogpumipmap.pro b/examples/hellogpumipmap/hellogpumipmap.pro
new file mode 100644
index 0000000..286784e
--- /dev/null
+++ b/examples/hellogpumipmap/hellogpumipmap.pro
@@ -0,0 +1,29 @@
+TEMPLATE = app
+QT += d3d12window widgets
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
+RESOURCES = hellogpumipmap.qrc
+
+LIBS = -ld3d12
+
+VSPS = shader.hlsl
+CS = mipmapgen.hlsl
+
+vshader.input = VSPS
+vshader.header = shader_vs.h
+vshader.entry = VS_Texture
+vshader.type = vs_5_0
+
+pshader.input = VSPS
+pshader.header = shader_ps.h
+pshader.entry = PS_Texture
+pshader.type = ps_5_0
+
+cshader.input = CS
+cshader.header = shader_cs.h
+cshader.entry = CS_Generate4MipMaps
+cshader.type = cs_5_0
+
+HLSL_SHADERS = vshader pshader cshader
+load(hlsl)
diff --git a/examples/hellogpumipmap/hellogpumipmap.qrc b/examples/hellogpumipmap/hellogpumipmap.qrc
new file mode 100644
index 0000000..ff1d0e5
--- /dev/null
+++ b/examples/hellogpumipmap/hellogpumipmap.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>qt.png</file>
+</qresource>
+</RCC>
diff --git a/examples/hellogpumipmap/main.cpp b/examples/hellogpumipmap/main.cpp
new file mode 100644
index 0000000..57830fa
--- /dev/null
+++ b/examples/hellogpumipmap/main.cpp
@@ -0,0 +1,67 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QWidget>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QLabel>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Window *d3dw = new Window;
+ QWidget w;
+ QVBoxLayout *vl = new QVBoxLayout;
+ vl->addWidget(new QPushButton("Widgets + a native child window with D3D12"));
+ vl->addWidget(new QLabel("Like hellotexture but this time the mipmaps are generated via a compute shader"));
+ QWidget *ww = QWidget::createWindowContainer(d3dw);
+ ww->setMinimumWidth(200);
+ ww->setMinimumHeight(200);
+ vl->addWidget(ww);
+ vl->setStretchFactor(ww, 1.0f);
+ w.resize(800, 800);
+ w.setLayout(vl);
+ w.show();
+
+ return app.exec();
+}
diff --git a/examples/hellogpumipmap/mipmapgen.hlsl b/examples/hellogpumipmap/mipmapgen.hlsl
new file mode 100644
index 0000000..6793b53
--- /dev/null
+++ b/examples/hellogpumipmap/mipmapgen.hlsl
@@ -0,0 +1,60 @@
+static const uint GROUP_DIM = 8; // 2 ^ (out_mip_count - 1)
+
+Texture2D tex : register(t0);
+SamplerState samp : register(s0);
+
+cbuffer ConstantBuffer : register(b0)
+{
+ uint2 mip1Size;
+ uint sampleLevel;
+ uint totalMips;
+}
+
+RWTexture2D<float4> mip1 : register(u0);
+RWTexture2D<float4> mip2 : register(u1);
+RWTexture2D<float4> mip3 : register(u2);
+RWTexture2D<float4> mip4 : register(u3);
+
+groupshared float4 groupColor[GROUP_DIM][GROUP_DIM];
+
+[numthreads(GROUP_DIM, GROUP_DIM, 1)]
+void CS_Generate4MipMaps(uint3 localId: SV_GroupThreadId, uint3 globalId: SV_DispatchThreadID)
+{
+ const float2 coord = float2(1.0f / float(mip1Size.x), 1.0f / float(mip1Size.y)) * (globalId.xy + 0.5);
+ float4 c = tex.SampleLevel(samp, coord, sampleLevel);
+
+ mip1[globalId.xy] = c;
+ groupColor[localId.y][localId.x] = c;
+
+ if (sampleLevel + 1 >= totalMips)
+ return;
+
+ GroupMemoryBarrierWithGroupSync();
+
+ if ((localId.x & 1) == 0 && (localId.y & 1) == 0) {
+ c = (c + groupColor[localId.y][localId.x + 1] + groupColor[localId.y + 1][localId.x] + groupColor[localId.y + 1][localId.x + 1]) / 4.0;
+ mip2[globalId.xy / 2] = c;
+ groupColor[localId.y][localId.x] = c;
+ }
+
+ if (sampleLevel + 2 >= totalMips)
+ return;
+
+ GroupMemoryBarrierWithGroupSync();
+
+ if ((localId.x & 3) == 0 && (localId.y & 3) == 0) {
+ c = (c + groupColor[localId.y][localId.x + 2] + groupColor[localId.y + 2][localId.x] + groupColor[localId.y + 2][localId.x + 2]) / 4.0;
+ mip3[globalId.xy / 4] = c;
+ groupColor[localId.y][localId.x] = c;
+ }
+
+ if (sampleLevel + 3 >= totalMips)
+ return;
+
+ GroupMemoryBarrierWithGroupSync();
+
+ if ((localId.x & 7) == 0 && (localId.y & 7) == 0) {
+ c = (c + groupColor[localId.y][localId.x + 3] + groupColor[localId.y + 3][localId.x] + groupColor[localId.y + 3][localId.x + 3]) / 4.0;
+ mip4[globalId.xy / 8] = c;
+ }
+}
diff --git a/examples/hellogpumipmap/qt.png b/examples/hellogpumipmap/qt.png
new file mode 100644
index 0000000..f30eec0
--- /dev/null
+++ b/examples/hellogpumipmap/qt.png
Binary files differ
diff --git a/examples/hellogpumipmap/shader.hlsl b/examples/hellogpumipmap/shader.hlsl
new file mode 100644
index 0000000..be69b39
--- /dev/null
+++ b/examples/hellogpumipmap/shader.hlsl
@@ -0,0 +1,36 @@
+cbuffer ConstantBuffer : register(b0)
+{
+ float4x4 modelview;
+ float4x4 projection;
+};
+
+struct VSInput
+{
+ float4 position : POSITION;
+ float2 coord : TEXCOORD0;
+};
+
+struct PSInput
+{
+ float4 position : SV_POSITION;
+ float2 coord : TEXCOORD0;
+};
+
+Texture2D tex : register(t0);
+SamplerState samp : register(s0);
+
+PSInput VS_Texture(VSInput input)
+{
+ PSInput result;
+
+ float4x4 mvp = mul(projection, modelview);
+ result.position = mul(mvp, input.position);
+ result.coord = input.coord;
+
+ return result;
+}
+
+float4 PS_Texture(PSInput input) : SV_TARGET
+{
+ return tex.Sample(samp, input.coord);
+}
diff --git a/examples/hellogpumipmap/window.cpp b/examples/hellogpumipmap/window.cpp
new file mode 100644
index 0000000..c87de78
--- /dev/null
+++ b/examples/hellogpumipmap/window.cpp
@@ -0,0 +1,525 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+#include "shader_vs.h"
+#include "shader_ps.h"
+#include "shader_cs.h"
+
+// size must be a power of two due to the way mipmap generation is done
+static const int TEXTURE_WIDTH = 512;
+static const int TEXTURE_HEIGHT = 512;
+
+static const int TEXTURE_MIP_LEVELS = 10; // ceil(log2(max(width, height))) + 1
+
+Window::Window()
+ : f(Q_NULLPTR),
+ cbPtr(Q_NULLPTR),
+ rotationAngle(0)
+{
+}
+
+Window::~Window()
+{
+ if (cbPtr)
+ constantBuffer->Unmap(0, Q_NULLPTR);
+
+ delete f;
+}
+
+void Window::initializeD3D()
+{
+ QImage qtLogo = QImage(QStringLiteral(":/qt.png")).convertToFormat(QImage::Format_RGBA8888).scaled(TEXTURE_WIDTH, TEXTURE_HEIGHT);
+ if (qtLogo.isNull()) {
+ qWarning("Failed to load image data");
+ return;
+ }
+
+ f = createFence();
+ ID3D12Device *dev = device();
+
+ // One static sampler (no sampler heap is needed).
+ D3D12_STATIC_SAMPLER_DESC sampler = {};
+ sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
+ sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.MinLOD = 0.0f;
+ sampler.MaxLOD = D3D12_FLOAT32_MAX;
+ sampler.ShaderRegister = 0;
+ sampler.RegisterSpace = 0;
+ sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
+
+ // In addition to the constant buffer view we will now also have a shader
+ // resource view in order to expose the texture to the pixel shader.
+ D3D12_DESCRIPTOR_RANGE descRange[2];
+ descRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
+ descRange[0].NumDescriptors = 1;
+ descRange[0].BaseShaderRegister = 0; // b0
+ descRange[0].RegisterSpace = 0;
+ descRange[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+ descRange[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
+ descRange[1].NumDescriptors = 1;
+ descRange[1].BaseShaderRegister = 0; // t0
+ descRange[1].RegisterSpace = 0;
+ descRange[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+
+ D3D12_ROOT_PARAMETER rootParameter;
+ rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rootParameter.DescriptorTable.NumDescriptorRanges = 2;
+ rootParameter.DescriptorTable.pDescriptorRanges = descRange;
+
+ D3D12_ROOT_SIGNATURE_DESC desc;
+ desc.NumParameters = 1;
+ desc.pParameters = &rootParameter;
+ desc.NumStaticSamplers = 1;
+ desc.pStaticSamplers = &sampler;
+ desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ QByteArray msg(static_cast<const char *>(error->GetBufferPointer()), error->GetBufferSize());
+ qWarning("Failed to serialize root signature: %s", qPrintable(msg));
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&rootSignature)))) {
+ qWarning("Failed to create root signature");
+ return;
+ }
+
+ D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
+ };
+
+ D3D12_SHADER_BYTECODE vshader;
+ vshader.pShaderBytecode = g_VS_Texture;
+ vshader.BytecodeLength = sizeof(g_VS_Texture);
+ D3D12_SHADER_BYTECODE pshader;
+ pshader.pShaderBytecode = g_PS_Texture;
+ pshader.BytecodeLength = sizeof(g_PS_Texture);
+
+ D3D12_RASTERIZER_DESC rastDesc = {};
+ rastDesc.FillMode = D3D12_FILL_MODE_SOLID;
+ rastDesc.CullMode = D3D12_CULL_MODE_BACK;
+ rastDesc.FrontCounterClockwise = TRUE; // Vertices are given CCW
+ rastDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
+ rastDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
+ rastDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
+ rastDesc.DepthClipEnable = TRUE;
+
+ // Our material is transparent (the image has alpha < 255). Enable blending.
+ const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {
+ TRUE, FALSE,
+ D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD,
+ D3D12_BLEND_ZERO, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
+ D3D12_LOGIC_OP_NOOP,
+ D3D12_COLOR_WRITE_ENABLE_ALL
+ };
+ D3D12_BLEND_DESC blendDesc = {};
+ blendDesc.RenderTarget[0] = defaultRenderTargetBlendDesc;
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
+ psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
+ psoDesc.pRootSignature = rootSignature.Get();
+ psoDesc.VS = vshader;
+ psoDesc.PS = pshader;
+ psoDesc.RasterizerState = rastDesc;
+ psoDesc.BlendState = blendDesc;
+ psoDesc.DepthStencilState.DepthEnable = TRUE;
+ psoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
+ psoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
+ psoDesc.DepthStencilState.StencilEnable = FALSE;
+ psoDesc.SampleMask = UINT_MAX;
+ psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ psoDesc.NumRenderTargets = 1;
+ psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
+ psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
+ psoDesc.SampleDesc.Count = 1;
+ if (FAILED(dev->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pipelineState)))) {
+ qWarning("Failed to create graphics pipeline state");
+ return;
+ }
+
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator(), Q_NULLPTR, IID_PPV_ARGS(&commandList)))) {
+ qWarning("Failed to create command list");
+ return;
+ }
+
+ // Vertex buffer
+ const float vertices[] = {
+ -0.5f, -0.5f, 0, /* coords */ 0, 1, // the image was not flipped so accommodate for it here
+ 0.5f, -0.5f, 0, 1, 1,
+ -0.5f, 0.5f, 0, 0, 0,
+
+ -0.5f, 0.5f, 0, 0, 0,
+ 0.5f, -0.5f, 0, 1, 1,
+ 0.5f, 0.5f, 0, 1, 0
+ };
+ const UINT vertexBufferSize = sizeof(vertices);
+
+ D3D12_HEAP_PROPERTIES defaultHeapProp = {};
+ defaultHeapProp.Type = D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_HEAP_PROPERTIES uploadHeapProp = defaultHeapProp;
+ uploadHeapProp.Type = D3D12_HEAP_TYPE_UPLOAD;
+
+ D3D12_RESOURCE_DESC bufDesc = {};
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufDesc.Width = vertexBufferSize;
+ bufDesc.Height = 1;
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufDesc.SampleDesc.Count = 1;
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&vertexBuffer)))) {
+ qWarning("Failed to create committed resource (vertex buffer)");
+ return;
+ }
+
+ quint8 *p = Q_NULLPTR;
+ D3D12_RANGE readRange = { 0, 0 };
+ if (FAILED(vertexBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (vertex buffer)");
+ return;
+ }
+ memcpy(p, vertices, vertexBufferSize);
+ vertexBuffer->Unmap(0, Q_NULLPTR);
+
+ vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();
+ vertexBufferView.StrideInBytes = (3 + 2) * sizeof(float);
+ vertexBufferView.SizeInBytes = vertexBufferSize;
+
+ // Constant buffer
+ const UINT CB_SIZE = alignedCBSize(128); // 2 * float4x4
+ bufDesc.Width = CB_SIZE;
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&constantBuffer)))) {
+ qWarning("Failed to create committed resource (constant buffer)");
+ return;
+ }
+
+ if (FAILED(constantBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (constant buffer)");
+ return;
+ }
+ cbPtr = p; // won't Unmap() this here
+
+ // Constant buffer view and shader resource view descriptors are stored in the same heap.
+ cbvSrvUavStride = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+ D3D12_DESCRIPTOR_HEAP_DESC cbvSrvUavHeapDesc = {};
+ // CBV + SRV + (TEXTURE_MIP_LEVELS - 1) * UAV
+ cbvSrvUavHeapDesc.NumDescriptors = 1 + 1 + (TEXTURE_MIP_LEVELS - 1);
+ cbvSrvUavHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
+ cbvSrvUavHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
+ if (FAILED(dev->CreateDescriptorHeap(&cbvSrvUavHeapDesc, IID_PPV_ARGS(&cbvSrvUavHeap)))) {
+ qWarning("Failed to create CBV/SRV/UAV descriptor heap");
+ return;
+ }
+
+ // CBV for the pixel shader
+ D3D12_CPU_DESCRIPTOR_HANDLE cbvSrvUavHandle = cbvSrvUavHeap->GetCPUDescriptorHandleForHeapStart();
+ D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
+ cbvDesc.BufferLocation = constantBuffer->GetGPUVirtualAddress();
+ cbvDesc.SizeInBytes = CB_SIZE;
+ dev->CreateConstantBufferView(&cbvDesc, cbvSrvUavHandle);
+ cbvSrvUavHandle.ptr += cbvSrvUavStride;
+
+ // Texture (with mipmaps and allowing read/write via UAVs)
+ D3D12_RESOURCE_DESC textureDesc = {};
+ textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+ textureDesc.Width = TEXTURE_WIDTH;
+ textureDesc.Height = TEXTURE_HEIGHT;
+ textureDesc.DepthOrArraySize = 1;
+ textureDesc.MipLevels = TEXTURE_MIP_LEVELS;
+ textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ textureDesc.SampleDesc.Count = 1;
+ textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
+ textureDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
+
+ if (FAILED(dev->CreateCommittedResource(&defaultHeapProp, D3D12_HEAP_FLAG_NONE, &textureDesc,
+ D3D12_RESOURCE_STATE_COPY_DEST, Q_NULLPTR, IID_PPV_ARGS(&texture)))) {
+ qWarning("Failed to create texture resource");
+ return;
+ }
+
+ // Shader resource view for exposing the texture to the compute and pixel shaders
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
+ srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ srvDesc.Format = textureDesc.Format;
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
+ srvDesc.Texture2D.MipLevels = TEXTURE_MIP_LEVELS;
+ dev->CreateShaderResourceView(texture.Get(), &srvDesc, cbvSrvUavHandle);
+ cbvSrvUavHandle.ptr += cbvSrvUavStride;
+
+ // Mipmap generation will need an UAV for each level that needs to be generated.
+ for (int level = 1; level < TEXTURE_MIP_LEVELS; ++level) {
+ D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
+ uavDesc.Format = textureDesc.Format;
+ uavDesc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D;
+ uavDesc.Texture2D.MipSlice = level;
+ dev->CreateUnorderedAccessView(texture.Get(), Q_NULLPTR, &uavDesc, cbvSrvUavHandle);
+ cbvSrvUavHandle.ptr += cbvSrvUavStride;
+ }
+
+ ComPtr<ID3D12Resource> textureUploadBuffer;
+ UINT64 textureUploadBufferSize;
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT textureLayout;
+ dev->GetCopyableFootprints(&textureDesc, 0, 1, 0, &textureLayout, Q_NULLPTR, Q_NULLPTR, &textureUploadBufferSize);
+ bufDesc.Width = textureUploadBufferSize;
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&textureUploadBuffer)))) {
+ qWarning("Failed to create texture upload buffer resource");
+ return;
+ }
+
+ // Unlike hellotexture, upload only level 0. Leave the rest to a compute shader.
+ if (FAILED(textureUploadBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (texture upload buffer)");
+ return;
+ }
+ p += textureLayout.Offset;
+ for (int y = 0; y < TEXTURE_HEIGHT; ++y) {
+ memcpy(p, qtLogo.scanLine(y), TEXTURE_WIDTH * 4);
+ p += textureLayout.Footprint.RowPitch;
+ }
+ textureUploadBuffer->Unmap(0, Q_NULLPTR);
+
+ D3D12_TEXTURE_COPY_LOCATION dstLoc;
+ dstLoc.pResource = texture.Get();
+ dstLoc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ dstLoc.SubresourceIndex = 0;
+ D3D12_TEXTURE_COPY_LOCATION srcLoc;
+ srcLoc.pResource = textureUploadBuffer.Get();
+ srcLoc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ srcLoc.PlacedFootprint = textureLayout;
+ commandList->CopyTextureRegion(&dstLoc, 0, 0, 0, &srcLoc, Q_NULLPTR);
+
+ // once the copy is done, the texture is ready to be used in the compute shader...
+ transitionResource(texture.Get(), commandList.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
+ uavBarrier(texture.Get(), commandList.Get());
+
+ initMipMaps();
+ generateMipMaps();
+
+ // ...and then in the pixel shader
+ uavBarrier(texture.Get(), commandList.Get());
+ transitionResource(texture.Get(), commandList.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
+
+ // Execute the texture upload and mipmap generation.
+ commandList->Close();
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ // Block until all the above has finished.
+ waitForGPU(f);
+
+ setupProjection();
+}
+
+void Window::initMipMaps()
+{
+ ID3D12Device *dev = device();
+
+ D3D12_STATIC_SAMPLER_DESC sampler = {};
+ sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
+ sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.MinLOD = 0.0f;
+ sampler.MaxLOD = D3D12_FLOAT32_MAX;
+
+ D3D12_DESCRIPTOR_RANGE descRange[2];
+ descRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
+ descRange[0].NumDescriptors = 1;
+ descRange[0].BaseShaderRegister = 0; // t0
+ descRange[0].RegisterSpace = 0;
+ descRange[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+ descRange[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV;
+ descRange[1].NumDescriptors = 4;
+ descRange[1].BaseShaderRegister = 0; // u0..u3
+ descRange[1].RegisterSpace = 0;
+ descRange[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+
+ // Split into two to allow switching between the first and second set of UAVs later.
+ D3D12_ROOT_PARAMETER rootParameters[3];
+ rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rootParameters[0].DescriptorTable.NumDescriptorRanges = 1;
+ rootParameters[0].DescriptorTable.pDescriptorRanges = &descRange[0];
+
+ rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rootParameters[1].DescriptorTable.NumDescriptorRanges = 1;
+ rootParameters[1].DescriptorTable.pDescriptorRanges = &descRange[1];
+
+ rootParameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS;
+ rootParameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rootParameters[2].Constants.Num32BitValues = 4; // uint2 mip1Size, uint sampleLevel, uint totalMips
+ rootParameters[2].Constants.ShaderRegister = 0; // b0
+ rootParameters[2].Constants.RegisterSpace = 0;
+
+ D3D12_ROOT_SIGNATURE_DESC desc = {};
+ desc.NumParameters = 3;
+ desc.pParameters = rootParameters;
+ desc.NumStaticSamplers = 1;
+ desc.pStaticSamplers = &sampler;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ QByteArray msg(static_cast<const char *>(error->GetBufferPointer()), error->GetBufferSize());
+ qWarning("Failed to serialize compute root signature: %s", qPrintable(msg));
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(),
+ IID_PPV_ARGS(&computeRootSignature)))) {
+ qWarning("Failed to create compute root signature");
+ return;
+ }
+
+ D3D12_COMPUTE_PIPELINE_STATE_DESC psoDesc = {};
+ psoDesc.pRootSignature = computeRootSignature.Get();
+ psoDesc.CS.pShaderBytecode = g_CS_Generate4MipMaps;
+ psoDesc.CS.BytecodeLength = sizeof(g_CS_Generate4MipMaps);
+
+ if (FAILED(dev->CreateComputePipelineState(&psoDesc, IID_PPV_ARGS(&computeState)))) {
+ qWarning("Failed to create compute pipeline state");
+ return;
+ }
+}
+
+void Window::generateMipMaps()
+{
+ commandList->SetPipelineState(computeState.Get());
+ commandList->SetComputeRootSignature(computeRootSignature.Get());
+
+ ID3D12DescriptorHeap *heaps[] = { cbvSrvUavHeap.Get() };
+ commandList->SetDescriptorHeaps(_countof(heaps), heaps);
+
+ D3D12_GPU_DESCRIPTOR_HANDLE h = cbvSrvUavHeap->GetGPUDescriptorHandleForHeapStart(); // CBV, not needed here
+ h.ptr += cbvSrvUavStride; // SRV
+ commandList->SetComputeRootDescriptorTable(0, h);
+
+ h.ptr += cbvSrvUavStride; // now points to the first of (TEXTURE_MIP_LEVELS - 1) UAV descriptors
+
+ for (quint32 level = 1; level < TEXTURE_MIP_LEVELS; level += 4, h.ptr += cbvSrvUavStride * 4) {
+ commandList->SetComputeRootDescriptorTable(1, h);
+
+ QSize sz(TEXTURE_WIDTH, TEXTURE_HEIGHT);
+ sz.setWidth(qMax(1, sz.width() >> level));
+ sz.setHeight(qMax(1, sz.height() >> level));
+
+ const quint32 constants[4] = { quint32(sz.width()), quint32(sz.height()),
+ level - 1,
+ TEXTURE_MIP_LEVELS - 1 };
+ commandList->SetComputeRoot32BitConstants(2, 4, constants, 0);
+
+ commandList->Dispatch(sz.width(), sz.height(), 1);
+ }
+}
+
+void Window::resizeD3D(const QSize &)
+{
+ setupProjection();
+}
+
+void Window::setupProjection()
+{
+ projection.setToIdentity();
+ projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::paintD3D()
+{
+ modelview.setToIdentity();
+ modelview.translate(0, 0, -2);
+ // our highly sophisticated animation
+ modelview.rotate(rotationAngle, 0, 0, 1);
+ rotationAngle += 1;
+
+ memcpy(cbPtr, modelview.constData(), 16 * sizeof(float));
+ memcpy(cbPtr + 16 * sizeof(float), projection.constData(), 16 * sizeof(float));
+
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), pipelineState.Get());
+
+ commandList->SetGraphicsRootSignature(rootSignature.Get());
+
+ ID3D12DescriptorHeap *heaps[] = { cbvSrvUavHeap.Get() };
+ commandList->SetDescriptorHeaps(_countof(heaps), heaps);
+ commandList->SetGraphicsRootDescriptorTable(0, cbvSrvUavHeap->GetGPUDescriptorHandleForHeapStart());
+
+ D3D12_VIEWPORT viewport = { 0, 0, float(width()), float(height()), 0, 1 };
+ commandList->RSSetViewports(1, &viewport);
+ D3D12_RECT scissorRect = { 0, 0, width() - 1, height() - 1 };
+ commandList->RSSetScissorRects(1, &scissorRect);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
+
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = backBufferRenderTargetCPUHandle();
+ D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = depthStencilCPUHandle();
+ commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
+
+ const float clearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };
+ commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, Q_NULLPTR);
+ commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, Q_NULLPTR);
+
+ commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ commandList->IASetVertexBuffers(0, 1, &vertexBufferView);
+ commandList->DrawInstanced(6, 1, 0, 0);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
+
+ commandList->Close();
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ update();
+}
+
+void Window::afterPresent()
+{
+ waitForGPU(f);
+}
diff --git a/examples/hellogpumipmap/window.h b/examples/hellogpumipmap/window.h
new file mode 100644
index 0000000..db3c4ea
--- /dev/null
+++ b/examples/hellogpumipmap/window.h
@@ -0,0 +1,78 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QD3D12Window>
+#include <QMatrix4x4>
+
+class Window : public QD3D12Window
+{
+public:
+ Window();
+ ~Window();
+
+ void initializeD3D() Q_DECL_OVERRIDE;
+ void resizeD3D(const QSize &size) Q_DECL_OVERRIDE;
+ void paintD3D() Q_DECL_OVERRIDE;
+ void afterPresent() Q_DECL_OVERRIDE;
+
+private:
+ void setupProjection();
+ void initMipMaps();
+ void generateMipMaps();
+
+ Fence *f;
+ ComPtr<ID3D12GraphicsCommandList> commandList;
+ ComPtr<ID3D12PipelineState> pipelineState;
+ ComPtr<ID3D12RootSignature> rootSignature;
+ ComPtr<ID3D12Resource> vertexBuffer;
+ ComPtr<ID3D12Resource> constantBuffer;
+ ComPtr<ID3D12Resource> texture;
+ ComPtr<ID3D12DescriptorHeap> cbvSrvUavHeap;
+ UINT cbvSrvUavStride;
+ D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
+
+ ComPtr<ID3D12PipelineState> computeState;
+ ComPtr<ID3D12RootSignature> computeRootSignature;
+
+ QMatrix4x4 projection;
+ QMatrix4x4 modelview;
+ quint8 *cbPtr;
+ float rotationAngle;
+};
diff --git a/examples/hellomultisample/hellomultisample.pro b/examples/hellomultisample/hellomultisample.pro
new file mode 100644
index 0000000..0d36378
--- /dev/null
+++ b/examples/hellomultisample/hellomultisample.pro
@@ -0,0 +1,22 @@
+TEMPLATE = app
+QT += d3d12window widgets
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
+
+LIBS = -ld3d12
+
+VSPS = shader.hlsl
+
+vshader.input = VSPS
+vshader.header = shader_vs.h
+vshader.entry = VS_Simple
+vshader.type = vs_5_0
+
+pshader.input = VSPS
+pshader.header = shader_ps.h
+pshader.entry = PS_Simple
+pshader.type = ps_5_0
+
+HLSL_SHADERS = vshader pshader
+load(hlsl)
diff --git a/examples/hellomultisample/main.cpp b/examples/hellomultisample/main.cpp
new file mode 100644
index 0000000..4c9c255
--- /dev/null
+++ b/examples/hellomultisample/main.cpp
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QWidget>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QGroupBox>
+#include <QLabel>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Window *d3dw = new Window;
+ QWidget w;
+
+ QGroupBox *gb = new QGroupBox("A triangle again", &w);
+ QVBoxLayout *vl = new QVBoxLayout;
+ vl->addWidget(new QPushButton("Widgets + a native child window with D3D12"));
+ vl->addWidget(gb);
+ QVBoxLayout *gbl = new QVBoxLayout;
+ gbl->addWidget(new QLabel("but this time rendered into a 4x MSAA buffer first"));
+ QWidget *ww = QWidget::createWindowContainer(d3dw);
+ ww->setMinimumHeight(300);
+ gbl->addWidget(ww);
+ gbl->setStretchFactor(ww, 1.0);
+ gb->setLayout(gbl);
+
+ w.setLayout(vl);
+ w.resize(400, 400);
+ w.show();
+
+ return app.exec();
+}
diff --git a/examples/hellomultisample/shader.hlsl b/examples/hellomultisample/shader.hlsl
new file mode 100644
index 0000000..8b9b9ff
--- /dev/null
+++ b/examples/hellomultisample/shader.hlsl
@@ -0,0 +1,27 @@
+cbuffer ConstantBuffer : register(b0)
+{
+ float4x4 modelview;
+ float4x4 projection;
+};
+
+struct PSInput
+{
+ float4 position : SV_POSITION;
+ float4 color : COLOR;
+};
+
+PSInput VS_Simple(float4 position : POSITION, float4 color : COLOR)
+{
+ PSInput result;
+
+ float4x4 mvp = mul(projection, modelview);
+ result.position = mul(mvp, position);
+ result.color = color;
+
+ return result;
+}
+
+float4 PS_Simple(PSInput input) : SV_TARGET
+{
+ return input.color;
+}
diff --git a/examples/hellomultisample/window.cpp b/examples/hellomultisample/window.cpp
new file mode 100644
index 0000000..d2d6350
--- /dev/null
+++ b/examples/hellomultisample/window.cpp
@@ -0,0 +1,274 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+#include "shader_vs.h"
+#include "shader_ps.h"
+
+static const int OFFSCREEN_SAMPLES = 4;
+
+static const float offscreenClearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };
+
+Window::Window()
+ : f(Q_NULLPTR),
+ cbPtr(Q_NULLPTR),
+ rotationAngle(0)
+{
+ setExtraRenderTargetCount(1);
+}
+
+Window::~Window()
+{
+ if (cbPtr)
+ constantBuffer->Unmap(0, Q_NULLPTR);
+
+ delete f;
+}
+
+void Window::setupOffscreenWithMatchingSize()
+{
+ msaaRT = Q_NULLPTR;
+ msaaDS = Q_NULLPTR;
+ msaaRT.Attach(createExtraRenderTargetAndView(extraRenderTargetCPUHandle(0), size(), offscreenClearColor, OFFSCREEN_SAMPLES));
+ msaaDS.Attach(createExtraDepthStencilAndView(extraDepthStencilCPUHandle(0), size(), OFFSCREEN_SAMPLES));
+
+ projection.setToIdentity();
+ projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::initializeD3D()
+{
+ f = createFence();
+ ID3D12Device *dev = device();
+
+ setupOffscreenWithMatchingSize();
+
+ D3D12_ROOT_PARAMETER rootParameter;
+ rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
+ rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
+ rootParameter.Descriptor.ShaderRegister = 0; // b0
+ rootParameter.Descriptor.RegisterSpace = 0;
+
+ D3D12_ROOT_SIGNATURE_DESC desc;
+ desc.NumParameters = 1;
+ desc.pParameters = &rootParameter;
+ desc.NumStaticSamplers = 0;
+ desc.pStaticSamplers = Q_NULLPTR;
+ desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ qWarning("Failed to serialize root signature");
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&rootSignature)))) {
+ qWarning("Failed to create root signature");
+ return;
+ }
+
+ D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
+ { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
+ };
+
+ D3D12_SHADER_BYTECODE vshader;
+ vshader.pShaderBytecode = g_VS_Simple;
+ vshader.BytecodeLength = sizeof(g_VS_Simple);
+ D3D12_SHADER_BYTECODE pshader;
+ pshader.pShaderBytecode = g_PS_Simple;
+ pshader.BytecodeLength = sizeof(g_PS_Simple);
+
+ D3D12_RASTERIZER_DESC rastDesc = {};
+ rastDesc.FillMode = D3D12_FILL_MODE_SOLID;
+ rastDesc.CullMode = D3D12_CULL_MODE_BACK;
+ rastDesc.FrontCounterClockwise = TRUE; // Vertices are given CCW
+ rastDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
+ rastDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
+ rastDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
+ rastDesc.DepthClipEnable = TRUE;
+
+ // No blending, just enable color write.
+ D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {};
+ defaultRenderTargetBlendDesc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
+ D3D12_BLEND_DESC blendDesc = {};
+ blendDesc.RenderTarget[0] = defaultRenderTargetBlendDesc;
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
+ psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
+ psoDesc.pRootSignature = rootSignature.Get();
+ psoDesc.VS = vshader;
+ psoDesc.PS = pshader;
+ psoDesc.RasterizerState = rastDesc;
+ psoDesc.BlendState = blendDesc;
+ psoDesc.DepthStencilState.DepthEnable = TRUE;
+ psoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
+ psoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
+ psoDesc.DepthStencilState.StencilEnable = FALSE;
+ psoDesc.SampleMask = UINT_MAX;
+ psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ psoDesc.NumRenderTargets = 1;
+ psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
+ psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
+ psoDesc.SampleDesc = msaaRT->GetDesc().SampleDesc; // use multisampling
+ if (FAILED(dev->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pipelineState)))) {
+ qWarning("Failed to create graphics pipeline state");
+ return;
+ }
+
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator(), Q_NULLPTR, IID_PPV_ARGS(&commandList)))) {
+ qWarning("Failed to create command list");
+ return;
+ }
+ commandList->Close();
+
+ const float vertices[] = {
+ 0.0f, 0.707f, 0.0f, /* color */ 1.0f, 0.0f, 0.0f, 1.0f,
+ -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
+ 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f
+ };
+ const UINT vertexBufferSize = sizeof(vertices);
+
+ D3D12_HEAP_PROPERTIES heapProp = {};
+ heapProp.Type = D3D12_HEAP_TYPE_UPLOAD;
+
+ D3D12_RESOURCE_DESC bufDesc;
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufDesc.Alignment = 0;
+ bufDesc.Width = vertexBufferSize;
+ bufDesc.Height = 1;
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufDesc.SampleDesc.Count = 1;
+ bufDesc.SampleDesc.Quality = 0;
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ bufDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
+
+ if (FAILED(dev->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&vertexBuffer)))) {
+ qWarning("Failed to create committed resource (vertex buffer)");
+ return;
+ }
+
+ quint8 *p = Q_NULLPTR;
+ D3D12_RANGE readRange = { 0, 0 };
+ if (FAILED(vertexBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed");
+ return;
+ }
+ memcpy(p, vertices, vertexBufferSize);
+ vertexBuffer->Unmap(0, Q_NULLPTR);
+
+ vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();
+ vertexBufferView.StrideInBytes = (3 + 4) * sizeof(float);
+ vertexBufferView.SizeInBytes = vertexBufferSize;
+
+ const UINT CB_SIZE = alignedCBSize(128); // 2 * float4x4
+ bufDesc.Width = CB_SIZE;
+ if (FAILED(dev->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&constantBuffer)))) {
+ qWarning("Failed to create committed resource (constant buffer)");
+ return;
+ }
+
+ if (FAILED(constantBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (constant buffer)");
+ return;
+ }
+ cbPtr = p;
+}
+
+void Window::resizeD3D(const QSize &)
+{
+ setupOffscreenWithMatchingSize();
+}
+
+void Window::paintD3D()
+{
+ modelview.setToIdentity();
+ modelview.translate(0, 0, -2);
+ // our highly sophisticated animation
+ modelview.rotate(rotationAngle, 0, 0, 1);
+ rotationAngle += 1;
+
+ memcpy(cbPtr, modelview.constData(), 16 * sizeof(float));
+ memcpy(cbPtr + 16 * sizeof(float), projection.constData(), 16 * sizeof(float));
+
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), pipelineState.Get());
+
+ commandList->SetGraphicsRootSignature(rootSignature.Get());
+
+ commandList->SetGraphicsRootConstantBufferView(0, constantBuffer->GetGPUVirtualAddress());
+
+ D3D12_VIEWPORT viewport = { 0, 0, float(width()), float(height()), 0, 1 };
+ commandList->RSSetViewports(1, &viewport);
+ D3D12_RECT scissorRect = { 0, 0, width() - 1, height() - 1 };
+ commandList->RSSetScissorRects(1, &scissorRect);
+
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = extraRenderTargetCPUHandle(0);
+ D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = extraDepthStencilCPUHandle(0);
+ commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
+
+ commandList->ClearRenderTargetView(rtvHandle, offscreenClearColor, 0, Q_NULLPTR);
+ commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, Q_NULLPTR);
+
+ commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ commandList->IASetVertexBuffers(0, 1, &vertexBufferView);
+ commandList->DrawInstanced(3, 1, 0, 0);
+
+ transitionResource(msaaRT.Get(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_RESOLVE_SOURCE);
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RESOLVE_DEST);
+ commandList->ResolveSubresource(backBufferRenderTarget(), 0, msaaRT.Get(), 0, DXGI_FORMAT_R8G8B8A8_UNORM);
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_RESOLVE_DEST, D3D12_RESOURCE_STATE_PRESENT);
+ transitionResource(msaaRT.Get(), commandList.Get(), D3D12_RESOURCE_STATE_RESOLVE_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
+ commandList->Close();
+
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ update();
+}
+
+void Window::afterPresent()
+{
+ waitForGPU(f);
+}
diff --git a/examples/hellomultisample/window.h b/examples/hellomultisample/window.h
new file mode 100644
index 0000000..4c0c544
--- /dev/null
+++ b/examples/hellomultisample/window.h
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QD3D12Window>
+#include <QMatrix4x4>
+
+class Window : public QD3D12Window
+{
+public:
+ Window();
+ ~Window();
+
+ void initializeD3D() Q_DECL_OVERRIDE;
+ void resizeD3D(const QSize &size) Q_DECL_OVERRIDE;
+ void paintD3D() Q_DECL_OVERRIDE;
+ void afterPresent() Q_DECL_OVERRIDE;
+
+private:
+ void setupOffscreenWithMatchingSize();
+
+ Fence *f;
+ ComPtr<ID3D12Resource> msaaRT;
+ ComPtr<ID3D12Resource> msaaDS;
+ ComPtr<ID3D12GraphicsCommandList> commandList;
+ ComPtr<ID3D12PipelineState> pipelineState;
+ ComPtr<ID3D12RootSignature> rootSignature;
+ ComPtr<ID3D12Resource> vertexBuffer;
+ ComPtr<ID3D12Resource> constantBuffer;
+ D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
+
+ QMatrix4x4 projection;
+ QMatrix4x4 modelview;
+ quint8 *cbPtr;
+ float rotationAngle;
+};
diff --git a/examples/hellooffscreen/hellooffscreen.pro b/examples/hellooffscreen/hellooffscreen.pro
new file mode 100644
index 0000000..809e618
--- /dev/null
+++ b/examples/hellooffscreen/hellooffscreen.pro
@@ -0,0 +1,32 @@
+TEMPLATE = app
+QT += d3d12window widgets
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
+
+LIBS = -ld3d12
+
+VSPS = shader.hlsl
+
+vshader1.input = VSPS
+vshader1.header = shader_vs_off.h
+vshader1.entry = VS_Offscreen
+vshader1.type = vs_5_0
+
+pshader1.input = VSPS
+pshader1.header = shader_ps_off.h
+pshader1.entry = PS_Offscreen
+pshader1.type = ps_5_0
+
+vshader2.input = VSPS
+vshader2.header = shader_vs_on.h
+vshader2.entry = VS_Onscreen
+vshader2.type = vs_5_0
+
+pshader2.input = VSPS
+pshader2.header = shader_ps_on.h
+pshader2.entry = PS_Onscreen
+pshader2.type = ps_5_0
+
+HLSL_SHADERS = vshader1 pshader1 vshader2 pshader2
+load(hlsl)
diff --git a/examples/hellooffscreen/main.cpp b/examples/hellooffscreen/main.cpp
new file mode 100644
index 0000000..00827b2
--- /dev/null
+++ b/examples/hellooffscreen/main.cpp
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QMainWindow>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QLabel>
+#include <QMenuBar>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Window *d3dw = new Window;
+ QMainWindow mw;
+ QWidget *w = new QWidget;
+ QVBoxLayout *vl = new QVBoxLayout;
+ vl->addWidget(new QPushButton("Widgets + a native child window with D3D12"));
+ vl->addWidget(new QLabel("Offscreen rendering to a render target that is then used as a texture.\nNow with bundles!"));
+ QWidget *ww = QWidget::createWindowContainer(d3dw);
+ ww->setMinimumHeight(300);
+ vl->addWidget(ww);
+ vl->setStretchFactor(ww, 1.0);
+ w->setLayout(vl);
+
+ QMenu *fileMenu = mw.menuBar()->addMenu("&File");
+ fileMenu->addAction("&Save image", d3dw, &Window::readbackAndSave);
+ fileMenu->addAction("E&xit", &app, &QApplication::quit);
+
+ mw.setCentralWidget(w);
+ mw.resize(400, 400);
+ mw.show();
+
+ return app.exec();
+}
diff --git a/examples/hellooffscreen/shader.hlsl b/examples/hellooffscreen/shader.hlsl
new file mode 100644
index 0000000..c626447
--- /dev/null
+++ b/examples/hellooffscreen/shader.hlsl
@@ -0,0 +1,52 @@
+cbuffer ConstantBuffer : register(b0)
+{
+ float4x4 modelview;
+ float4x4 projection;
+};
+
+struct PSInput
+{
+ float4 position : SV_POSITION;
+ float4 color : COLOR;
+};
+
+PSInput VS_Offscreen(float4 position : POSITION, float4 color : COLOR)
+{
+ PSInput result;
+
+ float4x4 mvp = mul(projection, modelview);
+ result.position = mul(mvp, position);
+ result.color = color;
+
+ return result;
+}
+
+float4 PS_Offscreen(PSInput input) : SV_TARGET
+{
+ return input.color;
+}
+
+struct PSInput2
+{
+ float4 position : SV_POSITION;
+ float2 coord : TEXCOORD0;
+};
+
+PSInput2 VS_Onscreen(float4 position : POSITION, float2 coord : TEXCOORD0)
+{
+ PSInput2 result;
+
+ float4x4 mvp = mul(projection, modelview);
+ result.position = mul(mvp, position);
+ result.coord = coord;
+
+ return result;
+}
+
+Texture2D tex : register(t0);
+SamplerState samp : register(s0);
+
+float4 PS_Onscreen(PSInput2 input) : SV_TARGET
+{
+ return tex.Sample(samp, input.coord);
+}
diff --git a/examples/hellooffscreen/window.cpp b/examples/hellooffscreen/window.cpp
new file mode 100644
index 0000000..3dbe583
--- /dev/null
+++ b/examples/hellooffscreen/window.cpp
@@ -0,0 +1,541 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+#include "shader_vs_off.h"
+#include "shader_ps_off.h"
+#include "shader_vs_on.h"
+#include "shader_ps_on.h"
+#include <QFileDialog>
+#include <QMessageBox>
+
+static const int OFFSCREEN_WIDTH = 512;
+static const int OFFSCREEN_HEIGHT = 512;
+
+static const float offscreenClearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };
+static const float onscreenClearColor[] = { 0.4f, 0.5f, 0.5f, 1.0f };
+
+Window::Window()
+ : f(Q_NULLPTR)
+{
+ setExtraRenderTargetCount(1);
+}
+
+Window::~Window()
+{
+ if (offscreen.cbPtr)
+ offscreen.constantBuffer->Unmap(0, Q_NULLPTR);
+ if (onscreen.cbPtr)
+ onscreen.constantBuffer->Unmap(0, Q_NULLPTR);
+
+ delete f;
+}
+
+void Window::initializeD3D()
+{
+ f = createFence();
+ ID3D12Device *dev = device();
+
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator(), Q_NULLPTR, IID_PPV_ARGS(&commandList)))) {
+ qWarning("Failed to create command list");
+ return;
+ }
+ commandList->Close(); // created in recording state, close it for now
+
+ D3D12_DESCRIPTOR_HEAP_DESC cbvHeapDesc = {};
+ cbvHeapDesc.NumDescriptors = 1;
+ cbvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
+ cbvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
+ if (FAILED(dev->CreateDescriptorHeap(&cbvHeapDesc, IID_PPV_ARGS(&cbvSrvHeap)))) {
+ qWarning("Failed to create CBV/SRV/UAV descriptor heap");
+ return;
+ }
+
+ initializeOffscreen();
+ initializeOnscreen();
+}
+
+static inline D3D12_GRAPHICS_PIPELINE_STATE_DESC pso()
+{
+ D3D12_RASTERIZER_DESC rastDesc = {};
+ rastDesc.FillMode = D3D12_FILL_MODE_SOLID;
+ rastDesc.CullMode = D3D12_CULL_MODE_BACK;
+ rastDesc.FrontCounterClockwise = TRUE;
+ rastDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
+ rastDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
+ rastDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
+ rastDesc.DepthClipEnable = TRUE;
+
+ // No blending, just enable color write.
+ D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {};
+ defaultRenderTargetBlendDesc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
+ D3D12_BLEND_DESC blendDesc = {};
+ blendDesc.RenderTarget[0] = defaultRenderTargetBlendDesc;
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
+ psoDesc.RasterizerState = rastDesc;
+ psoDesc.BlendState = blendDesc;
+ psoDesc.DepthStencilState.DepthEnable = TRUE;
+ psoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
+ psoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
+ psoDesc.DepthStencilState.StencilEnable = FALSE;
+ psoDesc.SampleMask = UINT_MAX;
+ psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ psoDesc.NumRenderTargets = 1;
+ psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
+ psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
+ psoDesc.SampleDesc.Count = 1;
+
+ return psoDesc;
+}
+
+void Window::initializeOffscreen()
+{
+ ID3D12Device *dev = device();
+
+ // Create an offscreen render target of size 512x512. Pass the clear color to avoid performance warnings.
+ // Have a depth-stencil buffer as well with the matching size.
+ QSize sz(OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT);
+ offscreen.rt.Attach(createExtraRenderTargetAndView(extraRenderTargetCPUHandle(0), sz, offscreenClearColor));
+ offscreen.ds.Attach(createExtraDepthStencilAndView(extraDepthStencilCPUHandle(0), sz));
+
+ D3D12_ROOT_PARAMETER rootParameter;
+ rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
+ rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
+ rootParameter.Descriptor.ShaderRegister = 0; // b0
+ rootParameter.Descriptor.RegisterSpace = 0;
+
+ D3D12_ROOT_SIGNATURE_DESC desc;
+ desc.NumParameters = 1;
+ desc.pParameters = &rootParameter;
+ desc.NumStaticSamplers = 0;
+ desc.pStaticSamplers = Q_NULLPTR;
+ desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ qWarning("Failed to serialize root signature");
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(),
+ IID_PPV_ARGS(&offscreen.rootSignature)))) {
+ qWarning("Failed to create root signature");
+ return;
+ }
+
+ const D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
+ { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
+ };
+
+ D3D12_SHADER_BYTECODE vshader;
+ vshader.pShaderBytecode = g_VS_Offscreen;
+ vshader.BytecodeLength = sizeof(g_VS_Offscreen);
+ D3D12_SHADER_BYTECODE pshader;
+ pshader.pShaderBytecode = g_PS_Offscreen;
+ pshader.BytecodeLength = sizeof(g_PS_Offscreen);
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = pso();
+ psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
+ psoDesc.pRootSignature = offscreen.rootSignature.Get();
+ psoDesc.VS = vshader;
+ psoDesc.PS = pshader;
+
+ if (FAILED(dev->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&offscreen.pipelineState)))) {
+ qWarning("Failed to create graphics pipeline state");
+ return;
+ }
+
+ const float vertices[] = {
+ 0.0f, 0.707f, 0.0f, /* color */ 1.0f, 0.0f, 0.0f, 1.0f,
+ -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
+ 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f
+ };
+ const UINT vertexBufferSize = sizeof(vertices);
+
+ D3D12_HEAP_PROPERTIES heapProp = {};
+ heapProp.Type = D3D12_HEAP_TYPE_UPLOAD;
+
+ D3D12_RESOURCE_DESC bufDesc = {};
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufDesc.Width = vertexBufferSize;
+ bufDesc.Height = 1;
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufDesc.SampleDesc.Count = 1;
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+
+ if (FAILED(dev->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR,
+ IID_PPV_ARGS(&offscreen.vertexBuffer)))) {
+ qWarning("Failed to create committed resource (vertex buffer for triangle)");
+ return;
+ }
+
+ quint8 *p = Q_NULLPTR;
+ D3D12_RANGE readRange = { 0, 0 };
+ if (FAILED(offscreen.vertexBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (vertex buffer for triangle)");
+ return;
+ }
+ memcpy(p, vertices, vertexBufferSize);
+ offscreen.vertexBuffer->Unmap(0, Q_NULLPTR);
+
+ offscreen.vertexBufferView.BufferLocation = offscreen.vertexBuffer->GetGPUVirtualAddress();
+ offscreen.vertexBufferView.StrideInBytes = (3 + 4) * sizeof(float);
+ offscreen.vertexBufferView.SizeInBytes = vertexBufferSize;
+
+ const UINT CB_SIZE = alignedCBSize(128); // 2 * float4x4
+ bufDesc.Width = CB_SIZE;
+ if (FAILED(dev->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR,
+ IID_PPV_ARGS(&offscreen.constantBuffer)))) {
+ qWarning("Failed to create committed resource (constant buffer for triangle)");
+ return;
+ }
+
+ if (FAILED(offscreen.constantBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (constant buffer for triangle)");
+ return;
+ }
+ offscreen.cbPtr = p;
+
+ offscreen.projection.perspective(60.0f, OFFSCREEN_WIDTH / float(OFFSCREEN_HEIGHT), 0.1f, 100.0f);
+
+ // Create a bundle for drawing a triangle.
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundleAllocator(), Q_NULLPTR, IID_PPV_ARGS(&offscreen.bundle)))) {
+ qWarning("Failed to create offscreen command bundle");
+ return;
+ }
+ offscreen.bundle->SetPipelineState(offscreen.pipelineState.Get());
+ offscreen.bundle->SetGraphicsRootSignature(offscreen.rootSignature.Get());
+ offscreen.bundle->SetGraphicsRootConstantBufferView(0, offscreen.constantBuffer->GetGPUVirtualAddress());
+ offscreen.bundle->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ offscreen.bundle->IASetVertexBuffers(0, 1, &offscreen.vertexBufferView);
+ offscreen.bundle->DrawInstanced(3, 1, 0, 0);
+ offscreen.bundle->Close();
+}
+
+void Window::initializeOnscreen()
+{
+ // Set up a cube that is textured with the render target from the offscreen step.
+
+ ID3D12Device *dev = device();
+
+ D3D12_STATIC_SAMPLER_DESC sampler = {};
+ sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_POINT;
+ sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.MinLOD = 0.0f;
+ sampler.MaxLOD = D3D12_FLOAT32_MAX;
+ sampler.ShaderRegister = 0; // s0
+ sampler.RegisterSpace = 0;
+ sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
+
+ D3D12_ROOT_PARAMETER rootParameters[2];
+ rootParameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
+ rootParameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
+ rootParameters[0].Descriptor.ShaderRegister = 0; // b0
+ rootParameters[0].Descriptor.RegisterSpace = 0;
+
+ D3D12_DESCRIPTOR_RANGE descRange;
+ descRange.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
+ descRange.NumDescriptors = 1;
+ descRange.BaseShaderRegister = 0; // t0
+ descRange.RegisterSpace = 0;
+ descRange.OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+
+ rootParameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rootParameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
+ rootParameters[1].DescriptorTable.NumDescriptorRanges = 1;
+ rootParameters[1].DescriptorTable.pDescriptorRanges = &descRange;
+
+ D3D12_ROOT_SIGNATURE_DESC desc;
+ desc.NumParameters = 2;
+ desc.pParameters = rootParameters;
+ desc.NumStaticSamplers = 1;
+ desc.pStaticSamplers = &sampler;
+ desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ qWarning("Failed to serialize root signature");
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(),
+ IID_PPV_ARGS(&onscreen.rootSignature)))) {
+ qWarning("Failed to create root signature");
+ return;
+ }
+
+ // We have a non-interleaved layout.
+ const D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 1, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
+ };
+
+ D3D12_SHADER_BYTECODE vshader;
+ vshader.pShaderBytecode = g_VS_Onscreen;
+ vshader.BytecodeLength = sizeof(g_VS_Onscreen);
+ D3D12_SHADER_BYTECODE pshader;
+ pshader.pShaderBytecode = g_PS_Onscreen;
+ pshader.BytecodeLength = sizeof(g_PS_Onscreen);
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = pso();
+ psoDesc.RasterizerState.FrontCounterClockwise = FALSE; // winding order for the cube data below is CW
+ psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
+ psoDesc.pRootSignature = onscreen.rootSignature.Get();
+ psoDesc.VS = vshader;
+ psoDesc.PS = pshader;
+
+ if (FAILED(dev->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&onscreen.pipelineState)))) {
+ qWarning("Failed to create graphics pipeline state");
+ return;
+ }
+
+ // borrowed from qtdeclarative/examples/quick/rendercontrol
+ const float v[] = {
+ -0.5, 0.5, 0.5, 0.5,-0.5,0.5,-0.5,-0.5,0.5,
+ 0.5, -0.5, 0.5, -0.5,0.5,0.5,0.5,0.5,0.5,
+ -0.5, -0.5, -0.5, 0.5,-0.5,-0.5,-0.5,0.5,-0.5,
+ 0.5, 0.5, -0.5, -0.5,0.5,-0.5,0.5,-0.5,-0.5,
+
+ 0.5, -0.5, -0.5, 0.5,-0.5,0.5,0.5,0.5,-0.5,
+ 0.5, 0.5, 0.5, 0.5,0.5,-0.5,0.5,-0.5,0.5,
+ -0.5, 0.5, -0.5, -0.5,-0.5,0.5,-0.5,-0.5,-0.5,
+ -0.5, -0.5, 0.5, -0.5,0.5,-0.5,-0.5,0.5,0.5,
+
+ 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5,
+ -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5,
+ -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5,
+ 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5
+ };
+ const float texCoords[] = {
+ 0.0f,0.0f, 1.0f,1.0f, 1.0f,0.0f,
+ 1.0f,1.0f, 0.0f,0.0f, 0.0f,1.0f,
+ 1.0f,1.0f, 1.0f,0.0f, 0.0f,1.0f,
+ 0.0f,0.0f, 0.0f,1.0f, 1.0f,0.0f,
+
+ 1.0f,1.0f, 1.0f,0.0f, 0.0f,1.0f,
+ 0.0f,0.0f, 0.0f,1.0f, 1.0f,0.0f,
+ 0.0f,0.0f, 1.0f,1.0f, 1.0f,0.0f,
+ 1.0f,1.0f, 0.0f,0.0f, 0.0f,1.0f,
+
+ 0.0f,1.0f, 1.0f,0.0f, 1.0f,1.0f,
+ 1.0f,0.0f, 0.0f,1.0f, 0.0f,0.0f,
+ 1.0f,0.0f, 1.0f,1.0f, 0.0f,0.0f,
+ 0.0f,1.0f, 0.0f,0.0f, 1.0f,1.0f
+ };
+
+ const UINT vertexBufferSize = sizeof(v) + sizeof(texCoords);
+
+ D3D12_HEAP_PROPERTIES heapProp = {};
+ heapProp.Type = D3D12_HEAP_TYPE_UPLOAD;
+
+ D3D12_RESOURCE_DESC bufDesc = {};
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufDesc.Width = vertexBufferSize;
+ bufDesc.Height = 1;
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufDesc.SampleDesc.Count = 1;
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+
+ if (FAILED(dev->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR,
+ IID_PPV_ARGS(&onscreen.vertexBuffer)))) {
+ qWarning("Failed to create committed resource (vertex buffer for cube)");
+ return;
+ }
+
+ quint8 *p = Q_NULLPTR;
+ D3D12_RANGE readRange = { 0, 0 };
+ if (FAILED(onscreen.vertexBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (vertex buffer for cube)");
+ return;
+ }
+ memcpy(p, v, sizeof(v));
+ memcpy(p + sizeof(v), texCoords, sizeof(texCoords));
+ onscreen.vertexBuffer->Unmap(0, Q_NULLPTR);
+
+ onscreen.vertexBufferView[0].BufferLocation = onscreen.vertexBuffer->GetGPUVirtualAddress();
+ onscreen.vertexBufferView[0].StrideInBytes = 3 * sizeof(float);
+ onscreen.vertexBufferView[0].SizeInBytes = sizeof(v);
+ onscreen.vertexBufferView[1].BufferLocation = onscreen.vertexBuffer->GetGPUVirtualAddress() + sizeof(v);
+ onscreen.vertexBufferView[1].StrideInBytes = 2 * sizeof(float);
+ onscreen.vertexBufferView[1].SizeInBytes = sizeof(texCoords);
+
+ const UINT CB_SIZE = alignedCBSize(128); // 2 * float4x4
+ bufDesc.Width = CB_SIZE;
+ if (FAILED(dev->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR,
+ IID_PPV_ARGS(&onscreen.constantBuffer)))) {
+ qWarning("Failed to create committed resource (constant buffer for cube)");
+ return;
+ }
+
+ if (FAILED(onscreen.constantBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (constant buffer for cube)");
+ return;
+ }
+ onscreen.cbPtr = p;
+
+ dev->CreateShaderResourceView(offscreen.rt.Get(), Q_NULLPTR, cbvSrvHeap->GetCPUDescriptorHandleForHeapStart());
+
+ // Create a bundle for drawing a cube.
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_BUNDLE, bundleAllocator(), Q_NULLPTR, IID_PPV_ARGS(&onscreen.bundle)))) {
+ qWarning("Failed to create onscreen command bundle");
+ return;
+ }
+ onscreen.bundle->SetPipelineState(onscreen.pipelineState.Get());
+ onscreen.bundle->SetGraphicsRootSignature(onscreen.rootSignature.Get());
+ onscreen.bundle->SetGraphicsRootConstantBufferView(0, onscreen.constantBuffer->GetGPUVirtualAddress());
+ // This is only here to be able to add the SetGraphicsRootDescriptorTable call below.
+ // Must match the heap set on the direct command list.
+ ID3D12DescriptorHeap *heaps[] = { cbvSrvHeap.Get() };
+ onscreen.bundle->SetDescriptorHeaps(_countof(heaps), heaps);
+ // cbvSrvHeap has a single SRV descriptor only so the start address is just what we need
+ onscreen.bundle->SetGraphicsRootDescriptorTable(1, cbvSrvHeap->GetGPUDescriptorHandleForHeapStart());
+ onscreen.bundle->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ onscreen.bundle->IASetVertexBuffers(0, 2, onscreen.vertexBufferView);
+ onscreen.bundle->DrawInstanced(36, 1, 0, 0);
+ onscreen.bundle->Close();
+
+ onscreen.projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::resizeD3D(const QSize &)
+{
+ onscreen.projection.setToIdentity();
+ onscreen.projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::paintD3D()
+{
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), Q_NULLPTR);
+
+ paintOffscreen();
+ paintOnscreen();
+
+ commandList->Close();
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ update();
+}
+
+void Window::paintOffscreen()
+{
+ QMatrix4x4 modelview;
+ modelview.translate(0, 0, -2);
+ modelview.rotate(offscreen.rotationAngle, 0, 0, 1);
+ offscreen.rotationAngle += 1;
+ memcpy(offscreen.cbPtr, modelview.constData(), 16 * sizeof(float));
+ memcpy(offscreen.cbPtr + 16 * sizeof(float), offscreen.projection.constData(), 16 * sizeof(float));
+
+ D3D12_VIEWPORT viewport = { 0, 0, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, 0, 1 };
+ commandList->RSSetViewports(1, &viewport);
+ D3D12_RECT scissorRect = { 0, 0, OFFSCREEN_WIDTH - 1, OFFSCREEN_HEIGHT - 1 };
+ commandList->RSSetScissorRects(1, &scissorRect);
+
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = extraRenderTargetCPUHandle(0);
+ D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = extraDepthStencilCPUHandle(0);
+ commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
+
+ commandList->ClearRenderTargetView(rtvHandle, offscreenClearColor, 0, Q_NULLPTR);
+ commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, Q_NULLPTR);
+
+ commandList->ExecuteBundle(offscreen.bundle.Get());
+}
+
+void Window::paintOnscreen()
+{
+ QMatrix4x4 modelview;
+ modelview.translate(0, 0, -2);
+ modelview.rotate(onscreen.rotationAngle, 1, 0.5, 0);
+ onscreen.rotationAngle += 1;
+ memcpy(onscreen.cbPtr, modelview.constData(), 16 * sizeof(float));
+ memcpy(onscreen.cbPtr + 16 * sizeof(float), onscreen.projection.constData(), 16 * sizeof(float));
+
+ D3D12_VIEWPORT viewport = { 0, 0, float(width()), float(height()), 0, 1 };
+ commandList->RSSetViewports(1, &viewport);
+ D3D12_RECT scissorRect = { 0, 0, width() - 1, height() - 1 };
+ commandList->RSSetScissorRects(1, &scissorRect);
+
+ transitionResource(offscreen.rt.Get(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
+
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = backBufferRenderTargetCPUHandle();
+ D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = depthStencilCPUHandle();
+ commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
+
+ commandList->ClearRenderTargetView(rtvHandle, onscreenClearColor, 0, Q_NULLPTR);
+ commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, Q_NULLPTR);
+
+ ID3D12DescriptorHeap *heaps[] = { cbvSrvHeap.Get() };
+ commandList->SetDescriptorHeaps(_countof(heaps), heaps);
+
+ commandList->ExecuteBundle(onscreen.bundle.Get());
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
+ transitionResource(offscreen.rt.Get(), commandList.Get(), D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
+}
+
+void Window::afterPresent()
+{
+ waitForGPU(f);
+}
+
+void Window::readbackAndSave()
+{
+ commandList->Reset(commandAllocator(), Q_NULLPTR);
+ QImage img = readbackRGBA8888(offscreen.rt.Get(), D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, commandList.Get());
+ QString fn = QFileDialog::getSaveFileName(Q_NULLPTR, QStringLiteral("Save PNG"), QString(), QStringLiteral("PNG files (*.png)"));
+ if (!fn.isEmpty()) {
+ img.save(fn);
+ QMessageBox::information(Q_NULLPTR, QStringLiteral("Saved"), QStringLiteral("Offscreen render target read back and saved to ") + fn);
+ }
+}
diff --git a/examples/hellooffscreen/window.h b/examples/hellooffscreen/window.h
new file mode 100644
index 0000000..530d6a3
--- /dev/null
+++ b/examples/hellooffscreen/window.h
@@ -0,0 +1,95 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QD3D12Window>
+#include <QMatrix4x4>
+
+class Window : public QD3D12Window
+{
+public:
+ Window();
+ ~Window();
+
+ void initializeD3D() Q_DECL_OVERRIDE;
+ void resizeD3D(const QSize &size) Q_DECL_OVERRIDE;
+ void paintD3D() Q_DECL_OVERRIDE;
+ void afterPresent() Q_DECL_OVERRIDE;
+
+public slots:
+ void readbackAndSave();
+
+private:
+ void initializeOffscreen();
+ void initializeOnscreen();
+ void paintOffscreen();
+ void paintOnscreen();
+
+ Fence *f;
+ ComPtr<ID3D12GraphicsCommandList> commandList;
+ ComPtr<ID3D12DescriptorHeap> cbvSrvHeap;
+
+ struct OffscreenData {
+ OffscreenData() : cbPtr(Q_NULLPTR), rotationAngle(0) { }
+ ComPtr<ID3D12Resource> rt;
+ ComPtr<ID3D12Resource> ds;
+ ComPtr<ID3D12GraphicsCommandList> bundle;
+ ComPtr<ID3D12PipelineState> pipelineState;
+ ComPtr<ID3D12RootSignature> rootSignature;
+ ComPtr<ID3D12Resource> vertexBuffer;
+ ComPtr<ID3D12Resource> constantBuffer;
+ quint8 *cbPtr;
+ D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
+ QMatrix4x4 projection;
+ float rotationAngle;
+ } offscreen;
+
+ struct OnscreenData {
+ OnscreenData() : cbPtr(Q_NULLPTR), rotationAngle(0) { }
+ ComPtr<ID3D12GraphicsCommandList> bundle;
+ ComPtr<ID3D12PipelineState> pipelineState;
+ ComPtr<ID3D12RootSignature> rootSignature;
+ ComPtr<ID3D12Resource> vertexBuffer;
+ ComPtr<ID3D12Resource> constantBuffer;
+ quint8 *cbPtr;
+ D3D12_VERTEX_BUFFER_VIEW vertexBufferView[2];
+ QMatrix4x4 projection;
+ float rotationAngle;
+ } onscreen;
+};
diff --git a/examples/hellooffscreen_opengl/hellooffscreen_opengl.pro b/examples/hellooffscreen_opengl/hellooffscreen_opengl.pro
new file mode 100644
index 0000000..f368a99
--- /dev/null
+++ b/examples/hellooffscreen_opengl/hellooffscreen_opengl.pro
@@ -0,0 +1,6 @@
+TEMPLATE = app
+QT += widgets
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
+RESOURCES = hellooffscreen_opengl.qrc
diff --git a/examples/hellooffscreen_opengl/hellooffscreen_opengl.qrc b/examples/hellooffscreen_opengl/hellooffscreen_opengl.qrc
new file mode 100644
index 0000000..bbbcc61
--- /dev/null
+++ b/examples/hellooffscreen_opengl/hellooffscreen_opengl.qrc
@@ -0,0 +1,8 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>shader_offscreen.vert</file>
+ <file>shader_offscreen.frag</file>
+ <file>shader_onscreen.vert</file>
+ <file>shader_onscreen.frag</file>
+</qresource>
+</RCC>
diff --git a/examples/hellooffscreen_opengl/main.cpp b/examples/hellooffscreen_opengl/main.cpp
new file mode 100644
index 0000000..3cab53f
--- /dev/null
+++ b/examples/hellooffscreen_opengl/main.cpp
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QMainWindow>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QLabel>
+#include <QMenuBar>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Window *glw = new Window;
+ QMainWindow mw;
+ QWidget *w = new QWidget;
+ QVBoxLayout *vl = new QVBoxLayout;
+ vl->addWidget(new QPushButton("Widgets + a native child window with OpenGL"));
+ vl->addWidget(new QLabel("Offscreen rendering via an FBO."));
+ QWidget *ww = QWidget::createWindowContainer(glw);
+ ww->setMinimumHeight(300);
+ vl->addWidget(ww);
+ vl->setStretchFactor(ww, 1.0);
+ w->setLayout(vl);
+
+ QMenu *fileMenu = mw.menuBar()->addMenu("&File");
+ fileMenu->addAction("&Save image", glw, &Window::readbackAndSave);
+ fileMenu->addAction("E&xit", &app, &QApplication::quit);
+
+ mw.setCentralWidget(w);
+ mw.resize(400, 400);
+ mw.show();
+
+ return app.exec();
+}
diff --git a/examples/hellooffscreen_opengl/shader_offscreen.frag b/examples/hellooffscreen_opengl/shader_offscreen.frag
new file mode 100644
index 0000000..7bb5db2
--- /dev/null
+++ b/examples/hellooffscreen_opengl/shader_offscreen.frag
@@ -0,0 +1,6 @@
+varying highp vec4 vColor;
+
+void main()
+{
+ gl_FragColor = vColor;
+}
diff --git a/examples/hellooffscreen_opengl/shader_offscreen.vert b/examples/hellooffscreen_opengl/shader_offscreen.vert
new file mode 100644
index 0000000..2dc9fe1
--- /dev/null
+++ b/examples/hellooffscreen_opengl/shader_offscreen.vert
@@ -0,0 +1,13 @@
+attribute vec4 position;
+attribute vec4 color;
+
+varying vec4 vColor;
+
+uniform mat4 projection;
+uniform mat4 modelview;
+
+void main()
+{
+ vColor = color;
+ gl_Position = projection * modelview * position;
+}
diff --git a/examples/hellooffscreen_opengl/shader_onscreen.frag b/examples/hellooffscreen_opengl/shader_onscreen.frag
new file mode 100644
index 0000000..dab1dc4
--- /dev/null
+++ b/examples/hellooffscreen_opengl/shader_onscreen.frag
@@ -0,0 +1,8 @@
+varying highp vec2 vTexCoord;
+
+uniform sampler2D sampler;
+
+void main()
+{
+ gl_FragColor = vec4(texture2D(sampler, vTexCoord).rgb, 1.0);
+}
diff --git a/examples/hellooffscreen_opengl/shader_onscreen.vert b/examples/hellooffscreen_opengl/shader_onscreen.vert
new file mode 100644
index 0000000..094ca59
--- /dev/null
+++ b/examples/hellooffscreen_opengl/shader_onscreen.vert
@@ -0,0 +1,13 @@
+attribute vec4 position;
+attribute vec2 texcoord;
+
+varying vec2 vTexCoord;
+
+uniform mat4 projection;
+uniform mat4 modelview;
+
+void main()
+{
+ vTexCoord = texcoord;
+ gl_Position = projection * modelview * position;
+}
diff --git a/examples/hellooffscreen_opengl/window.cpp b/examples/hellooffscreen_opengl/window.cpp
new file mode 100644
index 0000000..31bc098
--- /dev/null
+++ b/examples/hellooffscreen_opengl/window.cpp
@@ -0,0 +1,286 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+#include <QFileDialog>
+#include <QMessageBox>
+#include <QOpenGLFramebufferObject>
+#include <QOpenGLShaderProgram>
+#include <QOpenGLFunctions>
+#include <QOpenGLBuffer>
+#include <QOpenGLVertexArrayObject>
+
+static const int OFFSCREEN_WIDTH = 512;
+static const int OFFSCREEN_HEIGHT = 512;
+
+static const float offscreenClearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };
+static const float onscreenClearColor[] = { 0.4f, 0.5f, 0.5f, 1.0f };
+
+Window::Window()
+{
+ QSurfaceFormat fmt;
+ fmt.setDepthBufferSize(24);
+ setFormat(fmt);
+}
+
+Window::~Window()
+{
+ makeCurrent();
+
+ delete offscreen.fbo;
+ delete offscreen.prog;
+ delete offscreen.vbo;
+ delete offscreen.vao;
+
+ delete onscreen.prog;
+ delete onscreen.vbo;
+ delete onscreen.vao;
+}
+
+void Window::initializeGL()
+{
+ initializeOffscreen();
+ initializeOnscreen();
+
+ QOpenGLFunctions *f = context()->functions();
+ f->glEnable(GL_DEPTH_TEST);
+ f->glEnable(GL_CULL_FACE);
+}
+
+void Window::initializeOffscreen()
+{
+ offscreen.fbo = new QOpenGLFramebufferObject(OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT, QOpenGLFramebufferObject::CombinedDepthStencil);
+
+ offscreen.prog = new QOpenGLShaderProgram;
+ offscreen.prog->addShaderFromSourceFile(QOpenGLShader::Vertex, QStringLiteral(":/shader_offscreen.vert"));
+ offscreen.prog->addShaderFromSourceFile(QOpenGLShader::Fragment, QStringLiteral(":/shader_offscreen.frag"));
+ offscreen.prog->bindAttributeLocation("position", 0);
+ offscreen.prog->bindAttributeLocation("color", 1);
+ offscreen.prog->link();
+
+ offscreen.modelviewLoc = offscreen.prog->uniformLocation("modelview");
+ offscreen.projectionLoc = offscreen.prog->uniformLocation("projection");
+
+ offscreen.vao = new QOpenGLVertexArrayObject;
+ offscreen.vao->create();
+ QOpenGLVertexArrayObject::Binder vaoBinder(offscreen.vao);
+
+ offscreen.vbo = new QOpenGLBuffer;
+ offscreen.vbo->create();
+ offscreen.vbo->bind();
+
+ const float vertices[] = {
+ 0.0f, 0.707f, 0.0f, /* color */ 1.0f, 0.0f, 0.0f, 1.0f,
+ -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
+ 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f
+ };
+
+ const int vertexCount = 3;
+ offscreen.vbo->allocate(sizeof(GLfloat) * vertexCount * 7);
+ offscreen.vbo->write(0, vertices, sizeof(GLfloat) * vertexCount * 7);
+
+ if (offscreen.vao->isCreated())
+ setupOffscreenVertexAttribs();
+
+ offscreen.projection.perspective(60.0f, OFFSCREEN_WIDTH / float(OFFSCREEN_HEIGHT), 0.1f, 100.0f);
+}
+
+void Window::initializeOnscreen()
+{
+ onscreen.prog = new QOpenGLShaderProgram;
+ onscreen.prog->addShaderFromSourceFile(QOpenGLShader::Vertex, QStringLiteral(":/shader_onscreen.vert"));
+ onscreen.prog->addShaderFromSourceFile(QOpenGLShader::Fragment, QStringLiteral(":/shader_onscreen.frag"));
+ onscreen.prog->bindAttributeLocation("position", 0);
+ onscreen.prog->bindAttributeLocation("texcoord", 1);
+ onscreen.prog->link();
+
+ onscreen.modelviewLoc = onscreen.prog->uniformLocation("modelview");
+ onscreen.projectionLoc = onscreen.prog->uniformLocation("projection");
+
+ onscreen.vao = new QOpenGLVertexArrayObject;
+ onscreen.vao->create();
+ QOpenGLVertexArrayObject::Binder vaoBinder(onscreen.vao);
+
+ onscreen.vbo = new QOpenGLBuffer;
+ onscreen.vbo->create();
+ onscreen.vbo->bind();
+
+ GLfloat v[] = {
+ -0.5, 0.5, 0.5, 0.5,-0.5,0.5,-0.5,-0.5,0.5,
+ 0.5, -0.5, 0.5, -0.5,0.5,0.5,0.5,0.5,0.5,
+ -0.5, -0.5, -0.5, 0.5,-0.5,-0.5,-0.5,0.5,-0.5,
+ 0.5, 0.5, -0.5, -0.5,0.5,-0.5,0.5,-0.5,-0.5,
+
+ 0.5, -0.5, -0.5, 0.5,-0.5,0.5,0.5,0.5,-0.5,
+ 0.5, 0.5, 0.5, 0.5,0.5,-0.5,0.5,-0.5,0.5,
+ -0.5, 0.5, -0.5, -0.5,-0.5,0.5,-0.5,-0.5,-0.5,
+ -0.5, -0.5, 0.5, -0.5,0.5,-0.5,-0.5,0.5,0.5,
+
+ 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5,
+ -0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5,
+ -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5,
+ 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5
+ };
+ GLfloat texCoords[] = {
+ 0.0f,0.0f, 1.0f,1.0f, 1.0f,0.0f,
+ 1.0f,1.0f, 0.0f,0.0f, 0.0f,1.0f,
+ 1.0f,1.0f, 1.0f,0.0f, 0.0f,1.0f,
+ 0.0f,0.0f, 0.0f,1.0f, 1.0f,0.0f,
+
+ 1.0f,1.0f, 1.0f,0.0f, 0.0f,1.0f,
+ 0.0f,0.0f, 0.0f,1.0f, 1.0f,0.0f,
+ 0.0f,0.0f, 1.0f,1.0f, 1.0f,0.0f,
+ 1.0f,1.0f, 0.0f,0.0f, 0.0f,1.0f,
+
+ 0.0f,1.0f, 1.0f,0.0f, 1.0f,1.0f,
+ 1.0f,0.0f, 0.0f,1.0f, 0.0f,0.0f,
+ 1.0f,0.0f, 1.0f,1.0f, 0.0f,0.0f,
+ 0.0f,1.0f, 0.0f,0.0f, 1.0f,1.0f
+ };
+
+ const int vertexCount = 36;
+ onscreen.vbo->allocate(sizeof(GLfloat) * vertexCount * 5);
+ onscreen.vbo->write(0, v, sizeof(GLfloat) * vertexCount * 3);
+ onscreen.vbo->write(sizeof(GLfloat) * vertexCount * 3, texCoords, sizeof(GLfloat) * vertexCount * 2);
+
+ if (onscreen.vao->isCreated())
+ setupOnscreenVertexAttribs();
+
+ onscreen.projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::resizeGL(int, int)
+{
+ onscreen.projection.setToIdentity();
+ onscreen.projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::paintGL()
+{
+ paintOffscreen();
+ paintOnscreen();
+
+ update();
+}
+
+void Window::setupOffscreenVertexAttribs()
+{
+ QOpenGLFunctions *f = context()->functions();
+ offscreen.vbo->bind();
+ offscreen.prog->enableAttributeArray(0);
+ offscreen.prog->enableAttributeArray(1);
+ f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), 0);
+ f->glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(GLfloat), (const void *)(3 * sizeof(GLfloat)));
+ offscreen.vbo->release();
+}
+
+void Window::paintOffscreen()
+{
+ QOpenGLFunctions *f = context()->functions();
+
+ offscreen.fbo->bind();
+ offscreen.prog->bind();
+ QOpenGLVertexArrayObject::Binder vaoBinder(offscreen.vao);
+ if (!offscreen.vao->isCreated())
+ setupOffscreenVertexAttribs();
+
+ QMatrix4x4 modelview;
+ modelview.translate(0, 0, -2);
+ modelview.rotate(offscreen.rotationAngle, 0, 0, 1);
+ offscreen.rotationAngle += 1;
+ offscreen.prog->setUniformValue(offscreen.modelviewLoc, modelview);
+ offscreen.prog->setUniformValue(offscreen.projectionLoc, offscreen.projection);
+
+ f->glViewport(0, 0, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT);
+ f->glClearColor(offscreenClearColor[0], offscreenClearColor[1], offscreenClearColor[2], offscreenClearColor[3]);
+ f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ f->glFrontFace(GL_CCW);
+ f->glDrawArrays(GL_TRIANGLES, 0, 3);
+
+ offscreen.fbo->release();
+}
+
+void Window::setupOnscreenVertexAttribs()
+{
+ QOpenGLFunctions *f = context()->functions();
+ onscreen.vbo->bind();
+ onscreen.prog->enableAttributeArray(0);
+ onscreen.prog->enableAttributeArray(1);
+ f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
+ f->glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (const void *)(36 * 3 * sizeof(GLfloat)));
+ onscreen.vbo->release();
+}
+
+void Window::paintOnscreen()
+{
+ QOpenGLFunctions *f = context()->functions();
+
+ onscreen.prog->bind();
+ QOpenGLVertexArrayObject::Binder vaoBinder(onscreen.vao);
+ if (!onscreen.vao->isCreated())
+ setupOnscreenVertexAttribs();
+
+ f->glBindTexture(GL_TEXTURE_2D, offscreen.fbo->texture());
+
+ QMatrix4x4 modelview;
+ modelview.translate(0, 0, -2);
+ modelview.rotate(onscreen.rotationAngle, 1, 0.5, 0);
+ onscreen.rotationAngle += 1;
+ onscreen.prog->setUniformValue(onscreen.modelviewLoc, modelview);
+ onscreen.prog->setUniformValue(onscreen.projectionLoc, onscreen.projection);
+
+ f->glViewport(0, 0, width(), height());
+ f->glClearColor(onscreenClearColor[0], onscreenClearColor[1], onscreenClearColor[2], onscreenClearColor[3]);
+ f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
+
+ f->glFrontFace(GL_CW);
+ f->glDrawArrays(GL_TRIANGLES, 0, 36);
+}
+
+void Window::readbackAndSave()
+{
+ QImage img = offscreen.fbo->toImage();
+ QString fn = QFileDialog::getSaveFileName(Q_NULLPTR, QStringLiteral("Save PNG"), QString(), QStringLiteral("PNG files (*.png)"));
+ if (!fn.isEmpty()) {
+ img.save(fn);
+ QMessageBox::information(Q_NULLPTR, QStringLiteral("Saved"), QStringLiteral("Offscreen render target read back and saved to ") + fn);
+ }
+}
diff --git a/examples/hellooffscreen_opengl/window.h b/examples/hellooffscreen_opengl/window.h
new file mode 100644
index 0000000..4d7538c
--- /dev/null
+++ b/examples/hellooffscreen_opengl/window.h
@@ -0,0 +1,94 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QOpenGLWindow>
+#include <QMatrix4x4>
+
+QT_BEGIN_NAMESPACE
+class QOpenGLFramebufferObject;
+class QOpenGLShaderProgram;
+class QOpenGLBuffer;
+class QOpenGLVertexArrayObject;
+QT_END_NAMESPACE
+
+class Window : public QOpenGLWindow
+{
+public:
+ Window();
+ ~Window();
+
+ void initializeGL() Q_DECL_OVERRIDE;
+ void resizeGL(int w, int h) Q_DECL_OVERRIDE;
+ void paintGL() Q_DECL_OVERRIDE;
+
+public slots:
+ void readbackAndSave();
+
+private:
+ void initializeOffscreen();
+ void initializeOnscreen();
+ void setupOffscreenVertexAttribs();
+ void paintOffscreen();
+ void setupOnscreenVertexAttribs();
+ void paintOnscreen();
+
+ struct OffscreenData {
+ OffscreenData() : rotationAngle(0), fbo(Q_NULLPTR), prog(Q_NULLPTR), vbo(Q_NULLPTR), vao(Q_NULLPTR) { }
+ QMatrix4x4 projection;
+ float rotationAngle;
+ QOpenGLFramebufferObject *fbo;
+ QOpenGLShaderProgram *prog;
+ QOpenGLBuffer *vbo;
+ QOpenGLVertexArrayObject *vao;
+ int modelviewLoc;
+ int projectionLoc;
+ } offscreen;
+
+ struct OnscreenData {
+ OnscreenData() : rotationAngle(0), prog(Q_NULLPTR), vbo(Q_NULLPTR), vao(Q_NULLPTR) { }
+ QMatrix4x4 projection;
+ float rotationAngle;
+ QOpenGLShaderProgram *prog;
+ QOpenGLBuffer *vbo;
+ QOpenGLVertexArrayObject *vao;
+ int modelviewLoc;
+ int projectionLoc;
+ } onscreen;
+};
diff --git a/examples/hellotexture/hellotexture.pro b/examples/hellotexture/hellotexture.pro
new file mode 100644
index 0000000..b173c9c
--- /dev/null
+++ b/examples/hellotexture/hellotexture.pro
@@ -0,0 +1,23 @@
+TEMPLATE = app
+QT += d3d12window widgets
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
+RESOURCES = hellotexture.qrc
+
+LIBS = -ld3d12
+
+VSPS = shader.hlsl
+
+vshader.input = VSPS
+vshader.header = shader_vs.h
+vshader.entry = VS_Texture
+vshader.type = vs_5_0
+
+pshader.input = VSPS
+pshader.header = shader_ps.h
+pshader.entry = PS_Texture
+pshader.type = ps_5_0
+
+HLSL_SHADERS = vshader pshader
+load(hlsl)
diff --git a/examples/hellotexture/hellotexture.qrc b/examples/hellotexture/hellotexture.qrc
new file mode 100644
index 0000000..ff1d0e5
--- /dev/null
+++ b/examples/hellotexture/hellotexture.qrc
@@ -0,0 +1,5 @@
+<!DOCTYPE RCC><RCC version="1.0">
+<qresource>
+ <file>qt.png</file>
+</qresource>
+</RCC>
diff --git a/examples/hellotexture/main.cpp b/examples/hellotexture/main.cpp
new file mode 100644
index 0000000..be2ebb7
--- /dev/null
+++ b/examples/hellotexture/main.cpp
@@ -0,0 +1,71 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QWidget>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QLabel>
+#include <QScrollArea>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Window *d3dw = new Window;
+ QWidget w;
+ QVBoxLayout *vl = new QVBoxLayout;
+ vl->addWidget(new QPushButton("Widgets + a native child window with D3D12, this time in a scroll area"));
+ vl->addWidget(new QLabel("Now with a texture and mipmaps!"));
+ QWidget *ww = QWidget::createWindowContainer(d3dw);
+ ww->setMinimumWidth(1000);
+ ww->setMinimumHeight(1000);
+ // NB using a scroll area will result in creating a native window for every
+ // widget in the parent chain in order to ensure proper clipping.
+ QScrollArea *sa = new QScrollArea;
+ sa->setWidget(ww);
+ vl->addWidget(sa);
+ w.resize(400, 400);
+ w.setLayout(vl);
+ w.show();
+
+ return app.exec();
+}
diff --git a/examples/hellotexture/qt.png b/examples/hellotexture/qt.png
new file mode 100644
index 0000000..f30eec0
--- /dev/null
+++ b/examples/hellotexture/qt.png
Binary files differ
diff --git a/examples/hellotexture/shader.hlsl b/examples/hellotexture/shader.hlsl
new file mode 100644
index 0000000..be69b39
--- /dev/null
+++ b/examples/hellotexture/shader.hlsl
@@ -0,0 +1,36 @@
+cbuffer ConstantBuffer : register(b0)
+{
+ float4x4 modelview;
+ float4x4 projection;
+};
+
+struct VSInput
+{
+ float4 position : POSITION;
+ float2 coord : TEXCOORD0;
+};
+
+struct PSInput
+{
+ float4 position : SV_POSITION;
+ float2 coord : TEXCOORD0;
+};
+
+Texture2D tex : register(t0);
+SamplerState samp : register(s0);
+
+PSInput VS_Texture(VSInput input)
+{
+ PSInput result;
+
+ float4x4 mvp = mul(projection, modelview);
+ result.position = mul(mvp, input.position);
+ result.coord = input.coord;
+
+ return result;
+}
+
+float4 PS_Texture(PSInput input) : SV_TARGET
+{
+ return tex.Sample(samp, input.coord);
+}
diff --git a/examples/hellotexture/window.cpp b/examples/hellotexture/window.cpp
new file mode 100644
index 0000000..0dfb31a
--- /dev/null
+++ b/examples/hellotexture/window.cpp
@@ -0,0 +1,406 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+#include "shader_vs.h"
+#include "shader_ps.h"
+
+static const int TEXTURE_WIDTH = 512;
+static const int TEXTURE_HEIGHT = 512;
+static const int TEXTURE_MIP_LEVELS = 8;
+
+Window::Window()
+ : f(Q_NULLPTR),
+ cbPtr(Q_NULLPTR),
+ rotationAngle(0)
+{
+}
+
+Window::~Window()
+{
+ if (cbPtr)
+ constantBuffer->Unmap(0, Q_NULLPTR);
+
+ delete f;
+}
+
+void Window::initializeD3D()
+{
+ QImage qtLogo = QImage(QStringLiteral(":/qt.png")).convertToFormat(QImage::Format_RGBA8888).scaled(TEXTURE_WIDTH, TEXTURE_HEIGHT);
+ if (qtLogo.isNull()) {
+ qWarning("Failed to load image data");
+ return;
+ }
+
+ f = createFence();
+ ID3D12Device *dev = device();
+
+ // One static sampler (no sampler heap is needed).
+ D3D12_STATIC_SAMPLER_DESC sampler = {};
+ sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
+ sampler.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP;
+ sampler.MinLOD = 0.0f;
+ sampler.MaxLOD = D3D12_FLOAT32_MAX;
+ sampler.ShaderRegister = 0;
+ sampler.RegisterSpace = 0;
+ sampler.ShaderVisibility = D3D12_SHADER_VISIBILITY_PIXEL;
+
+ // In addition to the constant buffer view we will now also have a shader
+ // resource view in order to expose the texture to the pixel shader.
+ D3D12_DESCRIPTOR_RANGE descRange[2];
+ descRange[0].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_CBV;
+ descRange[0].NumDescriptors = 1;
+ descRange[0].BaseShaderRegister = 0; // b0
+ descRange[0].RegisterSpace = 0;
+ descRange[0].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+ descRange[1].RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV;
+ descRange[1].NumDescriptors = 1;
+ descRange[1].BaseShaderRegister = 0; // t0
+ descRange[1].RegisterSpace = 0;
+ descRange[1].OffsetInDescriptorsFromTableStart = D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
+
+ D3D12_ROOT_PARAMETER rootParameter;
+ rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE;
+ rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
+ rootParameter.DescriptorTable.NumDescriptorRanges = 2;
+ rootParameter.DescriptorTable.pDescriptorRanges = descRange;
+
+ D3D12_ROOT_SIGNATURE_DESC desc;
+ desc.NumParameters = 1;
+ desc.pParameters = &rootParameter;
+ desc.NumStaticSamplers = 1;
+ desc.pStaticSamplers = &sampler;
+ desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ qWarning("Failed to serialize root signature");
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&rootSignature)))) {
+ qWarning("Failed to create root signature");
+ return;
+ }
+
+ D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
+ { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
+ };
+
+ D3D12_SHADER_BYTECODE vshader;
+ vshader.pShaderBytecode = g_VS_Texture;
+ vshader.BytecodeLength = sizeof(g_VS_Texture);
+ D3D12_SHADER_BYTECODE pshader;
+ pshader.pShaderBytecode = g_PS_Texture;
+ pshader.BytecodeLength = sizeof(g_PS_Texture);
+
+ D3D12_RASTERIZER_DESC rastDesc = {};
+ rastDesc.FillMode = D3D12_FILL_MODE_SOLID;
+ rastDesc.CullMode = D3D12_CULL_MODE_BACK;
+ rastDesc.FrontCounterClockwise = TRUE; // Vertices are given CCW
+ rastDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
+ rastDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
+ rastDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
+ rastDesc.DepthClipEnable = TRUE;
+
+ // Our material is transparent (the image has alpha < 255). Enable blending.
+ const D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {
+ TRUE, FALSE,
+ D3D12_BLEND_SRC_ALPHA, D3D12_BLEND_INV_SRC_ALPHA, D3D12_BLEND_OP_ADD,
+ D3D12_BLEND_ZERO, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD,
+ D3D12_LOGIC_OP_NOOP,
+ D3D12_COLOR_WRITE_ENABLE_ALL
+ };
+ D3D12_BLEND_DESC blendDesc = {};
+ blendDesc.RenderTarget[0] = defaultRenderTargetBlendDesc;
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
+ psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
+ psoDesc.pRootSignature = rootSignature.Get();
+ psoDesc.VS = vshader;
+ psoDesc.PS = pshader;
+ psoDesc.RasterizerState = rastDesc;
+ psoDesc.BlendState = blendDesc;
+ psoDesc.DepthStencilState.DepthEnable = TRUE;
+ psoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
+ psoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
+ psoDesc.DepthStencilState.StencilEnable = FALSE;
+ psoDesc.SampleMask = UINT_MAX;
+ psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ psoDesc.NumRenderTargets = 1;
+ psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
+ psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
+ psoDesc.SampleDesc.Count = 1;
+ if (FAILED(dev->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pipelineState)))) {
+ qWarning("Failed to create graphics pipeline state");
+ return;
+ }
+
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator(), Q_NULLPTR, IID_PPV_ARGS(&commandList)))) {
+ qWarning("Failed to create command list");
+ return;
+ }
+
+ // Vertex buffer
+ const float vertices[] = {
+ -0.5f, -0.5f, 0, /* coords */ 0, 1, // the image was not flipped so accommodate for it here
+ 0.5f, -0.5f, 0, 1, 1,
+ -0.5f, 0.5f, 0, 0, 0,
+
+ -0.5f, 0.5f, 0, 0, 0,
+ 0.5f, -0.5f, 0, 1, 1,
+ 0.5f, 0.5f, 0, 1, 0
+ };
+ const UINT vertexBufferSize = sizeof(vertices);
+
+ D3D12_HEAP_PROPERTIES defaultHeapProp = {};
+ defaultHeapProp.Type = D3D12_HEAP_TYPE_DEFAULT;
+ D3D12_HEAP_PROPERTIES uploadHeapProp = defaultHeapProp;
+ uploadHeapProp.Type = D3D12_HEAP_TYPE_UPLOAD;
+
+ D3D12_RESOURCE_DESC bufDesc = {};
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufDesc.Width = vertexBufferSize;
+ bufDesc.Height = 1;
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufDesc.SampleDesc.Count = 1;
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&vertexBuffer)))) {
+ qWarning("Failed to create committed resource (vertex buffer)");
+ return;
+ }
+
+ quint8 *p = Q_NULLPTR;
+ D3D12_RANGE readRange = { 0, 0 };
+ if (FAILED(vertexBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (vertex buffer)");
+ return;
+ }
+ memcpy(p, vertices, vertexBufferSize);
+ vertexBuffer->Unmap(0, Q_NULLPTR);
+
+ vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();
+ vertexBufferView.StrideInBytes = (3 + 2) * sizeof(float);
+ vertexBufferView.SizeInBytes = vertexBufferSize;
+
+ // Constant buffer
+ const UINT CB_SIZE = alignedCBSize(128); // 2 * float4x4
+ bufDesc.Width = CB_SIZE;
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&constantBuffer)))) {
+ qWarning("Failed to create committed resource (constant buffer)");
+ return;
+ }
+
+ if (FAILED(constantBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (constant buffer)");
+ return;
+ }
+ cbPtr = p; // won't Unmap() this here
+
+ // Texture (with mipmaps, to make it more exciting)
+ D3D12_RESOURCE_DESC textureDesc = {};
+ textureDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+ textureDesc.Width = TEXTURE_WIDTH;
+ textureDesc.Height = TEXTURE_HEIGHT;
+ textureDesc.DepthOrArraySize = 1;
+ textureDesc.MipLevels = TEXTURE_MIP_LEVELS;
+ textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ textureDesc.SampleDesc.Count = 1;
+ textureDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
+
+ // Ignore UMA for now and do the discrete-friendly upload via an upload buffer (no CPU access to the texture).
+ if (FAILED(dev->CreateCommittedResource(&defaultHeapProp, D3D12_HEAP_FLAG_NONE, &textureDesc,
+ D3D12_RESOURCE_STATE_COPY_DEST, Q_NULLPTR, IID_PPV_ARGS(&texture)))) {
+ qWarning("Failed to create texture resource");
+ return;
+ }
+
+ ComPtr<ID3D12Resource> textureUploadBuffer;
+ UINT64 textureUploadBufferSize;
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT textureLayout[TEXTURE_MIP_LEVELS];
+ dev->GetCopyableFootprints(&textureDesc, 0, TEXTURE_MIP_LEVELS, 0, textureLayout,
+ Q_NULLPTR, Q_NULLPTR, &textureUploadBufferSize);
+ bufDesc.Width = textureUploadBufferSize;
+ if (FAILED(dev->CreateCommittedResource(&uploadHeapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&textureUploadBuffer)))) {
+ qWarning("Failed to create texture upload buffer resource");
+ return;
+ }
+
+ if (FAILED(textureUploadBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (texture upload buffer)");
+ return;
+ }
+ int mipW = qtLogo.width(), mipH = qtLogo.height();
+ for (int level = 0; level < TEXTURE_MIP_LEVELS; ++level) {
+ quint8 *mipP = p + textureLayout[level].Offset;
+ // This is not quite how mipmaps are created ideally, but will do for now...
+ QImage img = qtLogo.scaled(mipW, mipH);
+ for (int y = 0; y < mipH; ++y) {
+ memcpy(mipP, img.scanLine(y), mipW * 4);
+ mipP += textureLayout[level].Footprint.RowPitch; // stride is at least 256 here
+ }
+ mipW /= 2;
+ mipH /= 2;
+ }
+ textureUploadBuffer->Unmap(0, Q_NULLPTR);
+
+ for (int level = 0; level < TEXTURE_MIP_LEVELS; ++level) {
+ D3D12_TEXTURE_COPY_LOCATION dstLoc;
+ dstLoc.pResource = texture.Get();
+ dstLoc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ dstLoc.SubresourceIndex = level;
+ D3D12_TEXTURE_COPY_LOCATION srcLoc;
+ srcLoc.pResource = textureUploadBuffer.Get();
+ srcLoc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ srcLoc.PlacedFootprint = textureLayout[level];
+ commandList->CopyTextureRegion(&dstLoc, 0, 0, 0, &srcLoc, Q_NULLPTR); // upload buffer -> texture
+ }
+
+ // once the copy is done the texture is ready to be used from the pixel shader
+ transitionResource(texture.Get(), commandList.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
+
+ // Constant buffer view and shader resource view descriptors are stored in the same heap.
+ const UINT cbvSrvStride = dev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
+ D3D12_DESCRIPTOR_HEAP_DESC cbvSrvHeapDesc = {};
+ cbvSrvHeapDesc.NumDescriptors = 2;
+ cbvSrvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
+ cbvSrvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
+ if (FAILED(dev->CreateDescriptorHeap(&cbvSrvHeapDesc, IID_PPV_ARGS(&cbvSrvHeap)))) {
+ qWarning("Failed to create CBV/SRV/UAV descriptor heap");
+ return;
+ }
+
+ D3D12_CPU_DESCRIPTOR_HANDLE cbvSrvHandle = cbvSrvHeap->GetCPUDescriptorHandleForHeapStart();
+ D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
+ cbvDesc.BufferLocation = constantBuffer->GetGPUVirtualAddress();
+ cbvDesc.SizeInBytes = CB_SIZE;
+ dev->CreateConstantBufferView(&cbvDesc, cbvSrvHandle);
+ cbvSrvHandle.ptr += cbvSrvStride;
+
+ D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
+ srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
+ srvDesc.Format = textureDesc.Format;
+ srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D;
+ srvDesc.Texture2D.MipLevels = TEXTURE_MIP_LEVELS;
+ dev->CreateShaderResourceView(texture.Get(), &srvDesc, cbvSrvHandle);
+
+ // Execute the texture upload.
+ commandList->Close();
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ // Block until all the above has finished.
+ waitForGPU(f);
+
+ setupProjection();
+}
+
+void Window::resizeD3D(const QSize &)
+{
+ setupProjection();
+}
+
+void Window::setupProjection()
+{
+ projection.setToIdentity();
+ projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::paintD3D()
+{
+ modelview.setToIdentity();
+ modelview.translate(0, 0, -2);
+ // our highly sophisticated animation
+ modelview.rotate(rotationAngle, 0, 0, 1);
+ rotationAngle += 1;
+
+ memcpy(cbPtr, modelview.constData(), 16 * sizeof(float));
+ memcpy(cbPtr + 16 * sizeof(float), projection.constData(), 16 * sizeof(float));
+
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), pipelineState.Get());
+
+ commandList->SetGraphicsRootSignature(rootSignature.Get());
+
+ ID3D12DescriptorHeap *heaps[] = { cbvSrvHeap.Get() };
+ commandList->SetDescriptorHeaps(_countof(heaps), heaps);
+ commandList->SetGraphicsRootDescriptorTable(0, cbvSrvHeap->GetGPUDescriptorHandleForHeapStart());
+
+ D3D12_VIEWPORT viewport = { 0, 0, float(width()), float(height()), 0, 1 };
+ commandList->RSSetViewports(1, &viewport);
+ D3D12_RECT scissorRect = { 0, 0, width() - 1, height() - 1 };
+ commandList->RSSetScissorRects(1, &scissorRect);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
+
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = backBufferRenderTargetCPUHandle();
+ D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = depthStencilCPUHandle();
+ commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
+
+ const float clearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };
+ commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, Q_NULLPTR);
+ commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, Q_NULLPTR);
+
+ commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ commandList->IASetVertexBuffers(0, 1, &vertexBufferView);
+ commandList->DrawInstanced(6, 1, 0, 0);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
+ commandList->Close();
+
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ update();
+}
+
+void Window::afterPresent()
+{
+ waitForGPU(f);
+}
diff --git a/examples/hellotexture/window.h b/examples/hellotexture/window.h
new file mode 100644
index 0000000..a0fef7b
--- /dev/null
+++ b/examples/hellotexture/window.h
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QD3D12Window>
+#include <QMatrix4x4>
+
+class Window : public QD3D12Window
+{
+public:
+ Window();
+ ~Window();
+
+ void initializeD3D() Q_DECL_OVERRIDE;
+ void resizeD3D(const QSize &size) Q_DECL_OVERRIDE;
+ void paintD3D() Q_DECL_OVERRIDE;
+ void afterPresent() Q_DECL_OVERRIDE;
+
+private:
+ void setupProjection();
+
+ Fence *f;
+ ComPtr<ID3D12GraphicsCommandList> commandList;
+ ComPtr<ID3D12PipelineState> pipelineState;
+ ComPtr<ID3D12RootSignature> rootSignature;
+ ComPtr<ID3D12Resource> vertexBuffer;
+ ComPtr<ID3D12Resource> constantBuffer;
+ ComPtr<ID3D12Resource> texture;
+ ComPtr<ID3D12DescriptorHeap> cbvSrvHeap;
+ D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
+
+ QMatrix4x4 projection;
+ QMatrix4x4 modelview;
+ quint8 *cbPtr;
+ float rotationAngle;
+};
diff --git a/examples/hellotriangle/hellotriangle.pro b/examples/hellotriangle/hellotriangle.pro
new file mode 100644
index 0000000..0d36378
--- /dev/null
+++ b/examples/hellotriangle/hellotriangle.pro
@@ -0,0 +1,22 @@
+TEMPLATE = app
+QT += d3d12window widgets
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
+
+LIBS = -ld3d12
+
+VSPS = shader.hlsl
+
+vshader.input = VSPS
+vshader.header = shader_vs.h
+vshader.entry = VS_Simple
+vshader.type = vs_5_0
+
+pshader.input = VSPS
+pshader.header = shader_ps.h
+pshader.entry = PS_Simple
+pshader.type = ps_5_0
+
+HLSL_SHADERS = vshader pshader
+load(hlsl)
diff --git a/examples/hellotriangle/main.cpp b/examples/hellotriangle/main.cpp
new file mode 100644
index 0000000..94f9ae7
--- /dev/null
+++ b/examples/hellotriangle/main.cpp
@@ -0,0 +1,65 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QWidget>
+#include <QPushButton>
+#include <QVBoxLayout>
+#include <QCalendarWidget>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QApplication app(argc, argv);
+
+ Window *d3dw = new Window;
+ QWidget w;
+ QVBoxLayout *vl = new QVBoxLayout;
+ vl->addWidget(new QPushButton("Widgets + a native child window with D3D12"));
+ vl->addWidget(new QCalendarWidget);
+ QWidget *ww = QWidget::createWindowContainer(d3dw);
+ ww->setMinimumHeight(300);
+ vl->addWidget(ww);
+ w.resize(400, 400);
+ w.setLayout(vl);
+ w.show();
+
+ return app.exec();
+}
diff --git a/examples/hellotriangle/shader.hlsl b/examples/hellotriangle/shader.hlsl
new file mode 100644
index 0000000..8b9b9ff
--- /dev/null
+++ b/examples/hellotriangle/shader.hlsl
@@ -0,0 +1,27 @@
+cbuffer ConstantBuffer : register(b0)
+{
+ float4x4 modelview;
+ float4x4 projection;
+};
+
+struct PSInput
+{
+ float4 position : SV_POSITION;
+ float4 color : COLOR;
+};
+
+PSInput VS_Simple(float4 position : POSITION, float4 color : COLOR)
+{
+ PSInput result;
+
+ float4x4 mvp = mul(projection, modelview);
+ result.position = mul(mvp, position);
+ result.color = color;
+
+ return result;
+}
+
+float4 PS_Simple(PSInput input) : SV_TARGET
+{
+ return input.color;
+}
diff --git a/examples/hellotriangle/window.cpp b/examples/hellotriangle/window.cpp
new file mode 100644
index 0000000..049b467
--- /dev/null
+++ b/examples/hellotriangle/window.cpp
@@ -0,0 +1,263 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+#include "shader_vs.h"
+#include "shader_ps.h"
+
+Window::Window()
+ : f(Q_NULLPTR),
+ cbPtr(Q_NULLPTR),
+ rotationAngle(0)
+{
+}
+
+Window::~Window()
+{
+ if (cbPtr)
+ constantBuffer->Unmap(0, Q_NULLPTR);
+
+ delete f;
+}
+
+void Window::initializeD3D()
+{
+ f = createFence();
+ ID3D12Device *dev = device();
+
+ D3D12_ROOT_PARAMETER rootParameter;
+ rootParameter.ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV;
+ rootParameter.ShaderVisibility = D3D12_SHADER_VISIBILITY_VERTEX;
+ rootParameter.Descriptor.ShaderRegister = 0; // b0
+ rootParameter.Descriptor.RegisterSpace = 0;
+
+ D3D12_ROOT_SIGNATURE_DESC desc;
+ desc.NumParameters = 1;
+ desc.pParameters = &rootParameter;
+ desc.NumStaticSamplers = 0;
+ desc.pStaticSamplers = Q_NULLPTR;
+ desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT;
+
+ ComPtr<ID3DBlob> signature;
+ ComPtr<ID3DBlob> error;
+ if (FAILED(D3D12SerializeRootSignature(&desc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error))) {
+ qWarning("Failed to serialize root signature");
+ return;
+ }
+ if (FAILED(dev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&rootSignature)))) {
+ qWarning("Failed to create root signature");
+ return;
+ }
+
+ D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
+ { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 },
+ { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0 }
+ };
+
+ D3D12_SHADER_BYTECODE vshader;
+ vshader.pShaderBytecode = g_VS_Simple;
+ vshader.BytecodeLength = sizeof(g_VS_Simple);
+ D3D12_SHADER_BYTECODE pshader;
+ pshader.pShaderBytecode = g_PS_Simple;
+ pshader.BytecodeLength = sizeof(g_PS_Simple);
+
+ D3D12_RASTERIZER_DESC rastDesc = {};
+ rastDesc.FillMode = D3D12_FILL_MODE_SOLID;
+ rastDesc.CullMode = D3D12_CULL_MODE_BACK;
+ rastDesc.FrontCounterClockwise = TRUE; // Vertices are given CCW
+ rastDesc.DepthBias = D3D12_DEFAULT_DEPTH_BIAS;
+ rastDesc.DepthBiasClamp = D3D12_DEFAULT_DEPTH_BIAS_CLAMP;
+ rastDesc.SlopeScaledDepthBias = D3D12_DEFAULT_SLOPE_SCALED_DEPTH_BIAS;
+ rastDesc.DepthClipEnable = TRUE;
+
+ // No blending, just enable color write.
+ D3D12_RENDER_TARGET_BLEND_DESC defaultRenderTargetBlendDesc = {};
+ defaultRenderTargetBlendDesc.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
+ D3D12_BLEND_DESC blendDesc = {};
+ blendDesc.RenderTarget[0] = defaultRenderTargetBlendDesc;
+
+ D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
+ psoDesc.InputLayout = { inputElementDescs, _countof(inputElementDescs) };
+ psoDesc.pRootSignature = rootSignature.Get();
+ psoDesc.VS = vshader;
+ psoDesc.PS = pshader;
+ psoDesc.RasterizerState = rastDesc;
+ psoDesc.BlendState = blendDesc;
+ psoDesc.DepthStencilState.DepthEnable = TRUE;
+ psoDesc.DepthStencilState.DepthWriteMask = D3D12_DEPTH_WRITE_MASK_ALL;
+ psoDesc.DepthStencilState.DepthFunc = D3D12_COMPARISON_FUNC_LESS;
+ psoDesc.DepthStencilState.StencilEnable = FALSE;
+ psoDesc.SampleMask = UINT_MAX;
+ psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
+ psoDesc.NumRenderTargets = 1;
+ psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
+ psoDesc.DSVFormat = DXGI_FORMAT_D32_FLOAT;
+ psoDesc.SampleDesc.Count = 1;
+ if (FAILED(dev->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&pipelineState)))) {
+ qWarning("Failed to create graphics pipeline state");
+ return;
+ }
+
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator(), Q_NULLPTR, IID_PPV_ARGS(&commandList)))) {
+ qWarning("Failed to create command list");
+ return;
+ }
+ commandList->Close();
+
+ const float vertices[] = {
+ 0.0f, 0.707f, 0.0f, /* color */ 1.0f, 0.0f, 0.0f, 1.0f,
+ -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
+ 0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f
+ };
+ const UINT vertexBufferSize = sizeof(vertices);
+
+ D3D12_HEAP_PROPERTIES heapProp = {};
+ heapProp.Type = D3D12_HEAP_TYPE_UPLOAD;
+
+ D3D12_RESOURCE_DESC bufDesc;
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufDesc.Alignment = 0;
+ bufDesc.Width = vertexBufferSize;
+ bufDesc.Height = 1;
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufDesc.SampleDesc.Count = 1;
+ bufDesc.SampleDesc.Quality = 0;
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+ bufDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
+
+ if (FAILED(dev->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&vertexBuffer)))) {
+ qWarning("Failed to create committed resource (vertex buffer)");
+ return;
+ }
+
+ quint8 *p = Q_NULLPTR;
+ D3D12_RANGE readRange = { 0, 0 };
+ if (FAILED(vertexBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed");
+ return;
+ }
+ memcpy(p, vertices, vertexBufferSize);
+ vertexBuffer->Unmap(0, Q_NULLPTR);
+
+ vertexBufferView.BufferLocation = vertexBuffer->GetGPUVirtualAddress();
+ vertexBufferView.StrideInBytes = (3 + 4) * sizeof(float);
+ vertexBufferView.SizeInBytes = vertexBufferSize;
+
+ const UINT CB_SIZE = alignedCBSize(128); // 2 * float4x4
+ bufDesc.Width = CB_SIZE;
+ if (FAILED(dev->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_GENERIC_READ, Q_NULLPTR, IID_PPV_ARGS(&constantBuffer)))) {
+ qWarning("Failed to create committed resource (constant buffer)");
+ return;
+ }
+
+ if (FAILED(constantBuffer->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Map failed (constant buffer)");
+ return;
+ }
+ cbPtr = p;
+
+ setupProjection();
+}
+
+void Window::resizeD3D(const QSize &)
+{
+ setupProjection();
+}
+
+void Window::setupProjection()
+{
+ projection.setToIdentity();
+ projection.perspective(60.0f, width() / float(height()), 0.1f, 100.0f);
+}
+
+void Window::paintD3D()
+{
+ modelview.setToIdentity();
+ modelview.translate(0, 0, -2);
+ // our highly sophisticated animation
+ modelview.rotate(rotationAngle, 0, 0, 1);
+ rotationAngle += 1;
+
+ memcpy(cbPtr, modelview.constData(), 16 * sizeof(float));
+ memcpy(cbPtr + 16 * sizeof(float), projection.constData(), 16 * sizeof(float));
+
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), pipelineState.Get());
+
+ commandList->SetGraphicsRootSignature(rootSignature.Get()); // invalidates bindings
+
+ commandList->SetGraphicsRootConstantBufferView(0, constantBuffer->GetGPUVirtualAddress());
+
+ D3D12_VIEWPORT viewport = { 0, 0, float(width()), float(height()), 0, 1 };
+ commandList->RSSetViewports(1, &viewport);
+ D3D12_RECT scissorRect = { 0, 0, width() - 1, height() - 1 };
+ commandList->RSSetScissorRects(1, &scissorRect);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
+
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = backBufferRenderTargetCPUHandle();
+ D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle = depthStencilCPUHandle();
+ commandList->OMSetRenderTargets(1, &rtvHandle, FALSE, &dsvHandle);
+
+ const float clearColor[] = { 0.0f, 0.2f, 0.4f, 1.0f };
+ commandList->ClearRenderTargetView(rtvHandle, clearColor, 0, Q_NULLPTR);
+ commandList->ClearDepthStencilView(dsvHandle, D3D12_CLEAR_FLAG_DEPTH, 1.0f, 0, 0, Q_NULLPTR);
+
+ commandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
+ commandList->IASetVertexBuffers(0, 1, &vertexBufferView);
+ commandList->DrawInstanced(3, 1, 0, 0);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
+ commandList->Close();
+
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ update();
+}
+
+void Window::afterPresent()
+{
+ waitForGPU(f);
+}
diff --git a/examples/hellotriangle/window.h b/examples/hellotriangle/window.h
new file mode 100644
index 0000000..d50a5a4
--- /dev/null
+++ b/examples/hellotriangle/window.h
@@ -0,0 +1,70 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QD3D12Window>
+#include <QMatrix4x4>
+
+class Window : public QD3D12Window
+{
+public:
+ Window();
+ ~Window();
+
+ void initializeD3D() Q_DECL_OVERRIDE;
+ void resizeD3D(const QSize &size) Q_DECL_OVERRIDE;
+ void paintD3D() Q_DECL_OVERRIDE;
+ void afterPresent() Q_DECL_OVERRIDE;
+
+private:
+ void setupProjection();
+
+ Fence *f;
+ ComPtr<ID3D12GraphicsCommandList> commandList;
+ ComPtr<ID3D12PipelineState> pipelineState;
+ ComPtr<ID3D12RootSignature> rootSignature;
+ ComPtr<ID3D12Resource> vertexBuffer;
+ ComPtr<ID3D12Resource> constantBuffer;
+ D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
+
+ QMatrix4x4 projection;
+ QMatrix4x4 modelview;
+ quint8 *cbPtr;
+ float rotationAngle;
+};
diff --git a/examples/hellowindow/hellowindow.pro b/examples/hellowindow/hellowindow.pro
new file mode 100644
index 0000000..6922627
--- /dev/null
+++ b/examples/hellowindow/hellowindow.pro
@@ -0,0 +1,5 @@
+TEMPLATE = app
+QT += d3d12window
+
+SOURCES = main.cpp window.cpp
+HEADERS = window.h
diff --git a/examples/hellowindow/main.cpp b/examples/hellowindow/main.cpp
new file mode 100644
index 0000000..08baaff
--- /dev/null
+++ b/examples/hellowindow/main.cpp
@@ -0,0 +1,51 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QGuiApplication>
+#include "window.h"
+
+int main(int argc, char **argv)
+{
+ QGuiApplication app(argc, argv);
+ Window window;
+ window.resize(1024, 768);
+ window.show();
+ return app.exec();
+}
diff --git a/examples/hellowindow/window.cpp b/examples/hellowindow/window.cpp
new file mode 100644
index 0000000..9682d56
--- /dev/null
+++ b/examples/hellowindow/window.cpp
@@ -0,0 +1,95 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include "window.h"
+
+Window::Window()
+ : f(Q_NULLPTR),
+ green(0)
+{
+}
+
+Window::~Window()
+{
+ delete f;
+}
+
+void Window::initializeD3D()
+{
+ f = createFence();
+ ID3D12Device *dev = device();
+ if (FAILED(dev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, commandAllocator(), Q_NULLPTR, IID_PPV_ARGS(&commandList)))) {
+ qWarning("Failed to create command list");
+ return;
+ }
+ commandList->Close();
+}
+
+void Window::resizeD3D(const QSize &size)
+{
+ qDebug("resize %d %d", size.width(), size.height());
+}
+
+void Window::paintD3D()
+{
+ commandAllocator()->Reset();
+ commandList->Reset(commandAllocator(), Q_NULLPTR);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET);
+
+ green += 0.01f;
+ if (green > 1.0f)
+ green = 0.0f;
+ const float clearColor[] = { 0.0f, green, 0.0f, 1.0f };
+ commandList->ClearRenderTargetView(backBufferRenderTargetCPUHandle(), clearColor, 0, Q_NULLPTR);
+
+ transitionResource(backBufferRenderTarget(), commandList.Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT);
+ commandList->Close();
+
+ ID3D12CommandList *commandLists[] = { commandList.Get() };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+
+ update(); // schedule the next frame by posting an UpdateRequest event
+}
+
+void Window::afterPresent()
+{
+ waitForGPU(f);
+}
diff --git a/examples/hellowindow/window.h b/examples/hellowindow/window.h
new file mode 100644
index 0000000..9114e00
--- /dev/null
+++ b/examples/hellowindow/window.h
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the examples of the QtD3D12Window 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$
+**
+****************************************************************************/
+
+#include <QD3D12Window>
+
+class Window : public QD3D12Window
+{
+public:
+ Window();
+ ~Window();
+
+ void initializeD3D() Q_DECL_OVERRIDE;
+ void resizeD3D(const QSize &size) Q_DECL_OVERRIDE;
+ void paintD3D() Q_DECL_OVERRIDE;
+ void afterPresent() Q_DECL_OVERRIDE;
+
+private:
+ Fence *f;
+ ComPtr<ID3D12GraphicsCommandList> commandList;
+ float green;
+};
diff --git a/features/hlsl.prf b/features/hlsl.prf
new file mode 100644
index 0000000..0fa27a7
--- /dev/null
+++ b/features/hlsl.prf
@@ -0,0 +1,10 @@
+for (SHADER, HLSL_SHADERS) {
+ INPUT = $$eval($${SHADER}.input)
+ fxc_$${SHADER}.input = $$INPUT
+ fxc_$${SHADER}.commands = fxc.exe /nologo /E $$eval($${SHADER}.entry) /T $$eval($${SHADER}.type) /Fh ${QMAKE_FILE_OUT} ${QMAKE_FILE_NAME}
+ fxc_$${SHADER}.output = $$eval($${SHADER}.header)
+ fxc_$${SHADER}.dependency_type = TYPE_C
+ fxc_$${SHADER}.variable_out = HEADERS
+ fxc_$${SHADER}.CONFIG += target_predeps
+ QMAKE_EXTRA_COMPILERS += fxc_$${SHADER}
+}
diff --git a/qd3d12window.pro b/qd3d12window.pro
new file mode 100644
index 0000000..58c33f2
--- /dev/null
+++ b/qd3d12window.pro
@@ -0,0 +1 @@
+load(qt_parts)
diff --git a/src/d3d12window/d3d12window.pro b/src/d3d12window/d3d12window.pro
new file mode 100644
index 0000000..380947a
--- /dev/null
+++ b/src/d3d12window/d3d12window.pro
@@ -0,0 +1,14 @@
+TEMPLATE = lib
+QT += core-private gui-private
+TARGET = QtD3D12Window
+
+load(qt_module)
+
+DEFINES += QD3D12_BUILD_DLL
+
+SOURCES += $$PWD/qd3d12window.cpp
+
+HEADERS += $$PWD/qd3d12window.h \
+ $$PWD/qd3d12windowglobal.h
+
+LIBS += -ldxgi -ld3d12
diff --git a/src/d3d12window/qd3d12window.cpp b/src/d3d12window/qd3d12window.cpp
new file mode 100644
index 0000000..27354a5
--- /dev/null
+++ b/src/d3d12window/qd3d12window.cpp
@@ -0,0 +1,677 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtD3D12Window 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 "qd3d12window.h"
+#include <QtGui/private/qpaintdevicewindow_p.h>
+
+QT_BEGIN_NAMESPACE
+
+class QD3D12WindowPrivate : public QPaintDeviceWindowPrivate
+{
+ Q_DECLARE_PUBLIC(QD3D12Window)
+
+public:
+ QD3D12WindowPrivate()
+ : initialized(false),
+ extraRenderTargetCount(0)
+ { }
+ ~QD3D12WindowPrivate();
+
+ void beginPaint(const QRegion &region) Q_DECL_OVERRIDE;
+ void flush(const QRegion &region) Q_DECL_OVERRIDE;
+
+ void initialize();
+ void setupRenderTargets();
+ void resize();
+ void deviceLost();
+ DXGI_SAMPLE_DESC makeSampleDesc(DXGI_FORMAT format, int samples);
+ ID3D12Resource *createOffscreenRenderTarget(D3D12_CPU_DESCRIPTOR_HANDLE viewHandle,
+ const QSize &size, const float *clearColor, int samples);
+ ID3D12Resource *createDepthStencil(D3D12_CPU_DESCRIPTOR_HANDLE viewHandle, const QSize &size, int samples);
+
+ bool initialized;
+ int swapChainBufferCount;
+ int extraRenderTargetCount;
+ ComPtr<ID3D12Device> device;
+ ComPtr<ID3D12CommandQueue> commandQueue;
+ ComPtr<IDXGISwapChain3> swapChain;
+ ComPtr<ID3D12DescriptorHeap> rtvHeap;
+ ComPtr<ID3D12DescriptorHeap> dsvHeap;
+ ComPtr<ID3D12Resource> renderTargets[2];
+ ComPtr<ID3D12Resource> depthStencil;
+ UINT rtvStride;
+ UINT dsvStride;
+ ComPtr<ID3D12CommandAllocator> commandAllocator;
+ ComPtr<ID3D12CommandAllocator> bundleAllocator;
+};
+
+static void getHardwareAdapter(IDXGIFactory1 *factory, IDXGIAdapter1 **outAdapter)
+{
+ ComPtr<IDXGIAdapter1> adapter;
+
+ for (int adapterIndex = 0; factory->EnumAdapters1(adapterIndex, &adapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) {
+ DXGI_ADAPTER_DESC1 desc;
+ adapter->GetDesc1(&desc);
+
+ if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
+ continue;
+
+ if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), Q_NULLPTR))) {
+ const QString name = QString::fromUtf16((char16_t *) desc.Description);
+ qDebug("Using adapter '%s'", qPrintable(name));
+ break;
+ }
+ }
+
+ *outAdapter = adapter.Detach();
+}
+
+void QD3D12WindowPrivate::initialize()
+{
+ Q_Q(QD3D12Window);
+
+ if (initialized)
+ return;
+
+ swapChainBufferCount = 2;
+
+ HWND hwnd = reinterpret_cast<HWND>(q->winId());
+
+ ComPtr<ID3D12Debug> debugController;
+ if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
+ debugController->EnableDebugLayer();
+
+ ComPtr<IDXGIFactory4> factory;
+ if (FAILED(CreateDXGIFactory2(0, IID_PPV_ARGS(&factory)))) {
+ qWarning("Failed to create DXGI");
+ return;
+ }
+
+ ComPtr<IDXGIAdapter1> adapter;
+ getHardwareAdapter(factory.Get(), &adapter);
+
+ bool warp = true;
+ if (adapter) {
+ HRESULT hr = D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device));
+ if (SUCCEEDED(hr))
+ warp = false;
+ else
+ qWarning("Failed to create device: 0x%x", hr);
+ } else {
+ qWarning("No usable hardware adapters found");
+ }
+
+ if (warp) {
+ qDebug("Using WARP");
+ ComPtr<IDXGIAdapter> warpAdapter;
+ factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter));
+ HRESULT hr = D3D12CreateDevice(warpAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device));
+ if (FAILED(hr)) {
+ qWarning("Failed to create WARP device: 0x%x", hr);
+ return;
+ }
+ }
+
+ D3D12_COMMAND_QUEUE_DESC queueDesc = {};
+ queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
+
+ if (FAILED(device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&commandQueue)))) {
+ qWarning("Failed to create command queue");
+ return;
+ }
+
+ DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
+ swapChainDesc.BufferCount = swapChainBufferCount;
+ swapChainDesc.BufferDesc.Width = q->width() * q->devicePixelRatio();
+ swapChainDesc.BufferDesc.Height = q->height() * q->devicePixelRatio();
+ swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
+ swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // D3D12 requires the flip model
+ swapChainDesc.OutputWindow = hwnd;
+ swapChainDesc.SampleDesc.Count = 1; // Flip does not support MSAA so no choice here
+ swapChainDesc.Windowed = TRUE;
+
+ ComPtr<IDXGISwapChain> baseSwapChain;
+ HRESULT hr = factory->CreateSwapChain(commandQueue.Get(), &swapChainDesc, &baseSwapChain);
+ if (FAILED(hr)) {
+ qWarning("Failed to create swap chain: 0x%x", hr);
+ return;
+ }
+ if (FAILED(baseSwapChain.As(&swapChain))) {
+ qWarning("Failed to cast swap chain");
+ return;
+ }
+
+ factory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER);
+
+ if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&commandAllocator)))) {
+ qWarning("Failed to create command allocator");
+ return;
+ }
+
+ if (FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_BUNDLE, IID_PPV_ARGS(&bundleAllocator)))) {
+ qWarning("Failed to create command bundle allocator");
+ return;
+ }
+
+ D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
+ rtvHeapDesc.NumDescriptors = swapChainBufferCount + extraRenderTargetCount;
+ rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
+ if (FAILED(device->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&rtvHeap)))) {
+ qWarning("Failed to create render target view descriptor heap");
+ return;
+ }
+ rtvStride = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
+
+ D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
+ dsvHeapDesc.NumDescriptors = 1 + extraRenderTargetCount;
+ dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
+ if (FAILED(device->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&dsvHeap)))) {
+ qWarning("Failed to create depth stencil heap");
+ return;
+ }
+ dsvStride = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
+
+ setupRenderTargets();
+
+ initialized = true;
+
+ q->initializeD3D();
+}
+
+DXGI_SAMPLE_DESC QD3D12WindowPrivate::makeSampleDesc(DXGI_FORMAT format, int samples)
+{
+ DXGI_SAMPLE_DESC sampleDesc;
+ sampleDesc.Count = 1;
+ sampleDesc.Quality = 0;
+
+ if (samples > 1) {
+ D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS msaaInfo = {};
+ msaaInfo.Format = format;
+ msaaInfo.SampleCount = samples;
+ if (SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &msaaInfo, sizeof(msaaInfo)))) {
+ if (msaaInfo.NumQualityLevels > 0) {
+ sampleDesc.Count = samples;
+ sampleDesc.Quality = msaaInfo.NumQualityLevels - 1;
+ } else {
+ qWarning("No quality levels for multisampling?");
+ }
+ } else {
+ qWarning("Failed to query multisample quality levels");
+ }
+ }
+
+ return sampleDesc;
+}
+
+ID3D12Resource *QD3D12WindowPrivate::createOffscreenRenderTarget(D3D12_CPU_DESCRIPTOR_HANDLE viewHandle,
+ const QSize &size, const float *clearColor, int samples)
+{
+ D3D12_CLEAR_VALUE clearValue = {};
+ clearValue.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ if (clearColor)
+ memcpy(clearValue.Color, clearColor, 4 * sizeof(float));
+
+ D3D12_HEAP_PROPERTIES heapProp = {};
+ heapProp.Type = D3D12_HEAP_TYPE_DEFAULT;
+
+ D3D12_RESOURCE_DESC rtDesc = {};
+ rtDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+ rtDesc.Width = size.width();
+ rtDesc.Height = size.height();
+ rtDesc.DepthOrArraySize = 1;
+ rtDesc.MipLevels = 1;
+ rtDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
+ rtDesc.SampleDesc = makeSampleDesc(rtDesc.Format, samples); // MSAA works here, unlike the backbuffer
+ rtDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
+
+ ID3D12Resource *resource = Q_NULLPTR;
+ if (FAILED(device->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &rtDesc,
+ D3D12_RESOURCE_STATE_RENDER_TARGET, &clearValue, IID_PPV_ARGS(&resource)))) {
+ qWarning("Failed to create offscreen render target of size %dx%d", size.width(), size.height());
+ return Q_NULLPTR;
+ }
+
+ device->CreateRenderTargetView(resource, Q_NULLPTR, viewHandle);
+
+ return resource;
+}
+
+ID3D12Resource *QD3D12WindowPrivate::createDepthStencil(D3D12_CPU_DESCRIPTOR_HANDLE viewHandle, const QSize &size, int samples)
+{
+ D3D12_CLEAR_VALUE depthClearValue = {};
+ depthClearValue.Format = DXGI_FORMAT_D32_FLOAT;
+ depthClearValue.DepthStencil.Depth = 1.0f;
+ depthClearValue.DepthStencil.Stencil = 0;
+
+ D3D12_HEAP_PROPERTIES heapProp = {};
+ heapProp.Type = D3D12_HEAP_TYPE_DEFAULT;
+
+ D3D12_RESOURCE_DESC bufDesc = {};
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
+ bufDesc.Width = size.width();
+ bufDesc.Height = size.height();
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_D32_FLOAT;
+ bufDesc.SampleDesc = makeSampleDesc(bufDesc.Format, samples);
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
+ bufDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
+
+ ID3D12Resource *resource = Q_NULLPTR;
+ if (FAILED(device->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_DEPTH_WRITE, &depthClearValue, IID_PPV_ARGS(&resource)))) {
+ qWarning("Failed to create depth-stencil buffer of size %dx%d", size.width(), size.height());
+ return Q_NULLPTR;
+ }
+
+ D3D12_DEPTH_STENCIL_VIEW_DESC depthStencilDesc = {};
+ depthStencilDesc.Format = DXGI_FORMAT_D32_FLOAT;
+ depthStencilDesc.ViewDimension = bufDesc.SampleDesc.Count <= 1 ? D3D12_DSV_DIMENSION_TEXTURE2D : D3D12_DSV_DIMENSION_TEXTURE2DMS;
+
+ device->CreateDepthStencilView(resource, &depthStencilDesc, viewHandle);
+
+ return resource;
+}
+
+void QD3D12WindowPrivate::setupRenderTargets()
+{
+ Q_Q(QD3D12Window);
+
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle(rtvHeap->GetCPUDescriptorHandleForHeapStart());
+ for (int i = 0; i < swapChainBufferCount; ++i) {
+ if (FAILED(swapChain->GetBuffer(i, IID_PPV_ARGS(&renderTargets[i])))) {
+ qWarning("Failed to get buffer %d from swap chain", i);
+ return;
+ }
+ device->CreateRenderTargetView(renderTargets[i].Get(), Q_NULLPTR, rtvHandle);
+ rtvHandle.ptr += rtvStride;
+ }
+
+ ID3D12Resource *ds = createDepthStencil(dsvHeap->GetCPUDescriptorHandleForHeapStart(), q->size(), 0);
+ if (ds)
+ depthStencil.Attach(ds);
+}
+
+void QD3D12WindowPrivate::resize()
+{
+ Q_Q(QD3D12Window);
+
+ if (!initialized)
+ return;
+
+ // Clear these, otherwise resizing will fail.
+ depthStencil = Q_NULLPTR;
+ for (int i = 0; i < swapChainBufferCount; ++i)
+ renderTargets[i] = Q_NULLPTR;
+
+ HRESULT hr = swapChain->ResizeBuffers(swapChainBufferCount, q->width(), q->height(), DXGI_FORMAT_R8G8B8A8_UNORM, 0);
+ if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
+ deviceLost();
+ return;
+ } else if (FAILED(hr)) {
+ qWarning("Failed to resize buffers: 0x%x", hr);
+ return;
+ }
+
+ setupRenderTargets();
+}
+
+void QD3D12WindowPrivate::deviceLost()
+{
+ Q_Q(QD3D12Window);
+ qWarning("D3D device lost");
+
+ // Release all resources. This is important because otherwise reinitialization may fail.
+
+ q->releaseD3D();
+
+ bundleAllocator = Q_NULLPTR;
+ commandAllocator = Q_NULLPTR;
+ rtvStride = dsvStride = 0;
+ depthStencil = Q_NULLPTR;
+ for (int i = 0; i < swapChainBufferCount; ++i)
+ renderTargets[i] = Q_NULLPTR;
+ dsvHeap = Q_NULLPTR;
+ rtvHeap = Q_NULLPTR;
+ commandQueue = Q_NULLPTR;
+ swapChain = Q_NULLPTR;
+ device = Q_NULLPTR;
+
+ initialized = false;
+ initialize();
+}
+
+QD3D12WindowPrivate::~QD3D12WindowPrivate()
+{
+}
+
+void QD3D12WindowPrivate::beginPaint(const QRegion &region)
+{
+ Q_UNUSED(region);
+
+ initialize();
+}
+
+void QD3D12WindowPrivate::flush(const QRegion &region)
+{
+ Q_Q(QD3D12Window);
+ Q_UNUSED(region);
+
+ HRESULT hr = swapChain->Present(1, 0);
+ if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) {
+ deviceLost();
+ return;
+ } else if (FAILED(hr)) {
+ qWarning("Present failed: 0x%x", hr);
+ return;
+ }
+
+ q->afterPresent();
+}
+
+QD3D12Window::QD3D12Window(QWindow *parent)
+ : QPaintDeviceWindow(*(new QD3D12WindowPrivate), parent)
+{
+ setSurfaceType(QSurface::OpenGLSurface);
+}
+
+void QD3D12Window::setExtraRenderTargetCount(int count)
+{
+ Q_D(QD3D12Window);
+ if (d->initialized) {
+ qWarning("setExtraRenderTargetCount: Already initialized, request ignored.");
+ return;
+ }
+ d->extraRenderTargetCount = qMax(0, count);
+}
+
+void QD3D12Window::paintEvent(QPaintEvent *event)
+{
+ Q_UNUSED(event);
+
+ paintD3D();
+}
+
+void QD3D12Window::resizeEvent(QResizeEvent *event)
+{
+ Q_UNUSED(event);
+ Q_D(QD3D12Window);
+
+ if (!isExposed() || size().isEmpty())
+ return;
+
+ d->resize();
+ resizeD3D(size());
+ paintD3D();
+ afterPresent();
+}
+
+ID3D12Device *QD3D12Window::device() const
+{
+ Q_D(const QD3D12Window);
+ return d->device.Get();
+}
+
+ID3D12CommandQueue *QD3D12Window::commandQueue() const
+{
+ Q_D(const QD3D12Window);
+ return d->commandQueue.Get();
+}
+
+ID3D12CommandAllocator *QD3D12Window::commandAllocator() const
+{
+ Q_D(const QD3D12Window);
+ return d->commandAllocator.Get();
+}
+
+ID3D12CommandAllocator *QD3D12Window::bundleAllocator() const
+{
+ Q_D(const QD3D12Window);
+ return d->bundleAllocator.Get();
+}
+
+QD3D12Window::Fence *QD3D12Window::createFence() const
+{
+ Q_D(const QD3D12Window);
+ Fence *f = new Fence;
+ if (FAILED(d->device->CreateFence(f->value, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&f->fence)))) {
+ qWarning("Failed to create fence");
+ return f;
+ }
+ f->event = CreateEvent(Q_NULLPTR, FALSE, FALSE, Q_NULLPTR);
+ return f;
+}
+
+void QD3D12Window::waitForGPU(Fence *f) const
+{
+ Q_D(const QD3D12Window);
+ const UINT64 newValue = f->value.fetchAndAddAcquire(1) + 1;
+ d->commandQueue->Signal(f->fence.Get(), newValue);
+ if (f->fence->GetCompletedValue() < newValue) {
+ if (FAILED(f->fence->SetEventOnCompletion(newValue, f->event))) {
+ qWarning("SetEventOnCompletion failed");
+ return;
+ }
+ WaitForSingleObject(f->event, INFINITE);
+ }
+}
+
+void QD3D12Window::transitionResource(ID3D12Resource *resource, ID3D12GraphicsCommandList *commandList,
+ D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const
+{
+ D3D12_RESOURCE_BARRIER barrier;
+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
+ barrier.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
+ barrier.Transition.pResource = resource;
+ barrier.Transition.StateBefore = before;
+ barrier.Transition.StateAfter = after;
+ barrier.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
+
+ commandList->ResourceBarrier(1, &barrier);
+}
+
+void QD3D12Window::uavBarrier(ID3D12Resource *resource, ID3D12GraphicsCommandList *commandList) const
+{
+ D3D12_RESOURCE_BARRIER barrier = {};
+ barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV;
+ barrier.UAV.pResource = resource;
+
+ commandList->ResourceBarrier(1, &barrier);
+}
+
+ID3D12Resource *QD3D12Window::backBufferRenderTarget() const
+{
+ Q_D(const QD3D12Window);
+ return d->renderTargets[d->swapChain->GetCurrentBackBufferIndex()].Get();
+}
+
+D3D12_CPU_DESCRIPTOR_HANDLE QD3D12Window::backBufferRenderTargetCPUHandle() const
+{
+ Q_D(const QD3D12Window);
+ const int frameIndex = d->swapChain->GetCurrentBackBufferIndex();
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle(d->rtvHeap->GetCPUDescriptorHandleForHeapStart());
+ rtvHandle.ptr += frameIndex * d->rtvStride;
+ return rtvHandle;
+}
+
+D3D12_CPU_DESCRIPTOR_HANDLE QD3D12Window::depthStencilCPUHandle() const
+{
+ Q_D(const QD3D12Window);
+ return d->dsvHeap->GetCPUDescriptorHandleForHeapStart();
+}
+
+D3D12_CPU_DESCRIPTOR_HANDLE QD3D12Window::extraRenderTargetCPUHandle(int idx) const
+{
+ Q_D(const QD3D12Window);
+ Q_ASSERT(idx >= 0 && idx < d->extraRenderTargetCount);
+ D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle(d->rtvHeap->GetCPUDescriptorHandleForHeapStart());
+ rtvHandle.ptr += (d->swapChainBufferCount + idx) * d->rtvStride;
+ return rtvHandle;
+}
+
+D3D12_CPU_DESCRIPTOR_HANDLE QD3D12Window::extraDepthStencilCPUHandle(int idx) const
+{
+ Q_D(const QD3D12Window);
+ Q_ASSERT(idx >= 0 && idx < d->extraRenderTargetCount);
+ D3D12_CPU_DESCRIPTOR_HANDLE dsvHandle(d->dsvHeap->GetCPUDescriptorHandleForHeapStart());
+ dsvHandle.ptr += (1 + idx) * d->dsvStride;
+ return dsvHandle;
+}
+
+ID3D12Resource *QD3D12Window::createExtraRenderTargetAndView(D3D12_CPU_DESCRIPTOR_HANDLE viewHandle,
+ const QSize &size,
+ const float *clearColor,
+ int samples)
+{
+ Q_D(QD3D12Window);
+ return d->createOffscreenRenderTarget(viewHandle, size, clearColor, samples);
+}
+
+ID3D12Resource *QD3D12Window::createExtraDepthStencilAndView(D3D12_CPU_DESCRIPTOR_HANDLE viewHandle,
+ const QSize &size,
+ int samples)
+{
+ Q_D(QD3D12Window);
+ return d->createDepthStencil(viewHandle, size, samples);
+}
+
+quint32 QD3D12Window::alignedCBSize(quint32 size) const
+{
+ return (size + D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1) & ~(D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT - 1);
+}
+
+quint32 QD3D12Window::alignedTexturePitch(quint32 rowPitch) const
+{
+ return (rowPitch + D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1) & ~(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - 1);
+}
+
+quint32 QD3D12Window::alignedTextureOffset(quint32 offset) const
+{
+ return (offset + D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT - 1) & ~(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT - 1);
+}
+
+QImage QD3D12Window::readbackRGBA8888(ID3D12Resource *rt, D3D12_RESOURCE_STATES rtState, ID3D12GraphicsCommandList *commandList)
+{
+ ComPtr<ID3D12Resource> readbackBuf;
+
+ D3D12_RESOURCE_DESC rtDesc = rt->GetDesc();
+ UINT64 textureByteSize = 0;
+ D3D12_PLACED_SUBRESOURCE_FOOTPRINT textureLayout = {};
+ device()->GetCopyableFootprints(&rtDesc, 0, 1, 0, &textureLayout, Q_NULLPTR, Q_NULLPTR, &textureByteSize);
+
+ D3D12_HEAP_PROPERTIES heapProp = {};
+ heapProp.Type = D3D12_HEAP_TYPE_READBACK;
+
+ D3D12_RESOURCE_DESC bufDesc = {};
+ bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
+ bufDesc.Width = textureByteSize;
+ bufDesc.Height = 1;
+ bufDesc.DepthOrArraySize = 1;
+ bufDesc.MipLevels = 1;
+ bufDesc.Format = DXGI_FORMAT_UNKNOWN;
+ bufDesc.SampleDesc.Count = 1;
+ bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
+
+ if (FAILED(device()->CreateCommittedResource(&heapProp, D3D12_HEAP_FLAG_NONE, &bufDesc,
+ D3D12_RESOURCE_STATE_COPY_DEST, Q_NULLPTR, IID_PPV_ARGS(&readbackBuf)))) {
+ qWarning("Failed to create committed resource (readback buffer)");
+ return QImage();
+ }
+
+ D3D12_TEXTURE_COPY_LOCATION dstLoc;
+ dstLoc.pResource = readbackBuf.Get();
+ dstLoc.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
+ dstLoc.PlacedFootprint = textureLayout;
+ D3D12_TEXTURE_COPY_LOCATION srcLoc;
+ srcLoc.pResource = rt;
+ srcLoc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
+ srcLoc.SubresourceIndex = 0;
+
+ transitionResource(rt, commandList, rtState, D3D12_RESOURCE_STATE_COPY_SOURCE);
+ commandList->CopyTextureRegion(&dstLoc, 0, 0, 0, &srcLoc, Q_NULLPTR);
+ transitionResource(rt, commandList, D3D12_RESOURCE_STATE_COPY_SOURCE, rtState);
+ commandList->Close();
+
+ ID3D12CommandList *commandLists[] = { commandList };
+ commandQueue()->ExecuteCommandLists(_countof(commandLists), commandLists);
+ QScopedPointer<Fence> f(createFence());
+ waitForGPU(f.data());
+
+ QImage img(rtDesc.Width, rtDesc.Height, QImage::Format_RGBA8888);
+ quint8 *p = Q_NULLPTR;
+ D3D12_RANGE readRange = { 0, 0 };
+ if (FAILED(readbackBuf->Map(0, &readRange, reinterpret_cast<void **>(&p)))) {
+ qWarning("Mapping the readback buffer failed");
+ return QImage();
+ }
+ for (UINT y = 0; y < rtDesc.Height; ++y) {
+ quint8 *dst = img.scanLine(y);
+ memcpy(dst, p, rtDesc.Width * 4);
+ p += textureLayout.Footprint.RowPitch;
+ }
+ readbackBuf->Unmap(0, Q_NULLPTR);
+
+ return img;
+}
+
+void QD3D12Window::initializeD3D()
+{
+}
+
+void QD3D12Window::releaseD3D()
+{
+}
+
+void QD3D12Window::resizeD3D(const QSize &)
+{
+}
+
+void QD3D12Window::paintD3D()
+{
+}
+
+void QD3D12Window::afterPresent()
+{
+}
+
+QD3D12Window::Fence::~Fence()
+{
+ if (event)
+ CloseHandle(event);
+}
+
+QT_END_NAMESPACE
diff --git a/src/d3d12window/qd3d12window.h b/src/d3d12window/qd3d12window.h
new file mode 100644
index 0000000..0fc455f
--- /dev/null
+++ b/src/d3d12window/qd3d12window.h
@@ -0,0 +1,127 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtD3D12Window 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 QD3D12WINDOW_H
+#define QD3D12WINDOW_H
+
+#include <QAtomicInt>
+#include <QPaintDeviceWindow>
+#include <QImage>
+#include <QtD3D12Window/qd3d12windowglobal.h>
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <d3d12.h>
+#include <dxgi1_4.h>
+#include <wrl/client.h>
+
+using namespace Microsoft::WRL;
+
+QT_BEGIN_NAMESPACE
+
+class QD3D12WindowPrivate;
+
+class QD3D12_EXPORT QD3D12Window : public QPaintDeviceWindow
+{
+ Q_OBJECT
+ Q_DECLARE_PRIVATE(QD3D12Window)
+
+public:
+ struct QD3D12_EXPORT Fence {
+ Fence() : event(Q_NULLPTR) { }
+ ~Fence();
+ ComPtr<ID3D12Fence> fence;
+ HANDLE event;
+ QAtomicInt value;
+ private:
+ Q_DISABLE_COPY(Fence)
+ };
+
+ QD3D12Window(QWindow *parent = Q_NULLPTR);
+
+ void setExtraRenderTargetCount(int count);
+
+ virtual void initializeD3D();
+ virtual void releaseD3D();
+ virtual void resizeD3D(const QSize &size);
+ virtual void paintD3D();
+ virtual void afterPresent();
+
+ ID3D12Device *device() const;
+ ID3D12CommandQueue *commandQueue() const;
+ ID3D12CommandAllocator *commandAllocator() const;
+ ID3D12CommandAllocator *bundleAllocator() const;
+
+ Fence *createFence() const;
+ void waitForGPU(Fence *f) const;
+
+ void transitionResource(ID3D12Resource *resource, ID3D12GraphicsCommandList *commandList,
+ D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) const;
+ void uavBarrier(ID3D12Resource *resource, ID3D12GraphicsCommandList *commandList) const;
+
+ ID3D12Resource *backBufferRenderTarget() const;
+ D3D12_CPU_DESCRIPTOR_HANDLE backBufferRenderTargetCPUHandle() const;
+
+ D3D12_CPU_DESCRIPTOR_HANDLE depthStencilCPUHandle() const;
+
+ D3D12_CPU_DESCRIPTOR_HANDLE extraRenderTargetCPUHandle(int idx) const;
+ D3D12_CPU_DESCRIPTOR_HANDLE extraDepthStencilCPUHandle(int idx) const;
+
+ ID3D12Resource *createExtraRenderTargetAndView(D3D12_CPU_DESCRIPTOR_HANDLE viewHandle,
+ const QSize &size,
+ const float *clearColor = Q_NULLPTR,
+ int samples = 0);
+ ID3D12Resource *createExtraDepthStencilAndView(D3D12_CPU_DESCRIPTOR_HANDLE viewHandle,
+ const QSize &size,
+ int samples = 0);
+
+ quint32 alignedCBSize(quint32 size) const;
+ quint32 alignedTexturePitch(quint32 rowPitch) const;
+ quint32 alignedTextureOffset(quint32 offset) const;
+
+ QImage readbackRGBA8888(ID3D12Resource *rt, D3D12_RESOURCE_STATES rtState, ID3D12GraphicsCommandList *commandList);
+
+protected:
+ void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
+ void resizeEvent(QResizeEvent *) Q_DECL_OVERRIDE;
+
+private:
+ Q_DISABLE_COPY(QD3D12Window)
+};
+
+QT_END_NAMESPACE
+
+#endif
diff --git a/src/d3d12window/qd3d12windowglobal.h b/src/d3d12window/qd3d12windowglobal.h
new file mode 100644
index 0000000..8fdc923
--- /dev/null
+++ b/src/d3d12window/qd3d12windowglobal.h
@@ -0,0 +1,52 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 The Qt Company Ltd.
+** Contact: http://www.qt.io/licensing/
+**
+** This file is part of the QtD3D12Window 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 QD3D12WINDOWGLOBAL_H
+#define QD3D12WINDOWGLOBAL_H
+
+#include <qglobal.h>
+
+QT_BEGIN_NAMESPACE
+
+#if defined(QD3D12_BUILD_DLL)
+#define QD3D12_EXPORT Q_DECL_EXPORT
+#else
+#define QD3D12_EXPORT Q_DECL_IMPORT
+#endif
+
+QT_END_NAMESPACE
+
+#endif // QD3D12WINDOWGLOBAL_H
diff --git a/src/src.pro b/src/src.pro
new file mode 100644
index 0000000..0baa931
--- /dev/null
+++ b/src/src.pro
@@ -0,0 +1,2 @@
+TEMPLATE = subdirs
+SUBDIRS += d3d12window
diff --git a/sync.profile b/sync.profile
new file mode 100644
index 0000000..b5b52c8
--- /dev/null
+++ b/sync.profile
@@ -0,0 +1,6 @@
+%modules = (
+ "QtD3D12Window" => "$basedir/src/d3d12window",
+);
+%dependencies = (
+ "qtbase" => "refs/heads/stable",
+);