Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qquick3deffect.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5
7
8#include <ssg/qssgrendercontextcore.h>
9#include <QtQuick3DRuntimeRender/private/qssgrendereffect_p.h>
10#include <QtQuick3DRuntimeRender/private/qssgshadermaterialadapter_p.h>
11#include <QtQuick3DUtils/private/qssgutils_p.h>
12#include <QtQuick/qquickwindow.h>
13#include <QtQuick3D/private/qquick3dobject_p.h>
14#include <QtQuick3D/private/qquick3dscenemanager_p.h>
15#include <QtCore/qfile.h>
16#include <QtCore/qurl.h>
17
18
20
21/*!
22 \qmltype Effect
23 \inherits Object3D
24 \inqmlmodule QtQuick3D
25 \nativetype QQuick3DEffect
26 \brief Base component for creating a post-processing effect.
27
28 The Effect type allows the user to implement their own post-processing
29 effects for QtQuick3D.
30
31 \section1 Post-processing effects
32
33 A post-processing effect is conceptually very similar to Qt Quick's \l
34 ShaderEffect item. When an effect is present, the scene is rendered into a
35 separate texture first. The effect is then applied by drawing a textured
36 quad to the main render target, depending on the
37 \l{View3D::renderMode}{render mode} of the View3D. The effect can provide a
38 vertex shader, a fragment shader, or both. Effects are always applied on the
39 entire scene, per View3D.
40
41 Effects are associated with the \l SceneEnvironment in the
42 \l{SceneEnvironment::effects} property. The property is a list: effects can
43 be chained together; they are applied in the order they are in the list,
44 using the previous step's output as the input to the next one, with the last
45 effect's output defining the contents of the View3D.
46
47 \note \l SceneEnvironment and \l ExtendedSceneEnvironment provide a set of
48 built-in effects, such as depth of field, glow/bloom, lens flare, color
49 grading, and vignette. Always consider first if these are sufficient for
50 the application's needs, and prefer using the built-in facilities instead
51 of implementing a custom post-processing effect.
52
53 Effects are similar to \l{CustomMaterial}{custom materials} in many
54 ways. However, a custom material is associated with a model and is
55 responsible for the shading of that given mesh. Whereas an effect's vertex
56 shader always gets a quad (for example, two triangles) as its input, while
57 its fragment shader samples the texture with the scene's content.
58
59 Unlike custom materials, effects support multiple passes. For many effects
60 this it not necessary, and when there is a need to apply multiple effects,
61 identical results can often be achieved by chaining together multiple
62 effects in \l{SceneEnvironment::effects}{the SceneEnvironment}. This is
63 demonstrated by the \l{Qt Quick 3D - Custom Effect Example}{Custom Effect
64 example} as well. However, passes have the possibility to request additional
65 color buffers (texture), and specify which of these additional buffers they
66 output to. This allows implementing more complex image processing techniques
67 since subsequent passes can then use one or more of these additional
68 buffers, plus the original scene's content, as their input. If necessary,
69 these additional buffers can have an extended lifetime, meaning their
70 content is preserved between frames, which allows implementing effects that
71 rely on accumulating content from multiple frames, such as, motion blur.
72
73 When compared to Qt Quick's 2D ShaderEffect, the 3D post-processing effects
74 have the advantage of being able to work with depth buffer data, as well as
75 the ability to implement multiple passes with intermediate buffers. In
76 addition, the texture-related capabilities are extended: Qt Quick 3D allows
77 more fine-grained control over filtering modes, and allows effects to work
78 with texture formats other than RGBA8, for example, floating point formats.
79
80 \note Post-processing effects are currently available when the View3D
81 has its \l{View3D::renderMode}{renderMode} set to \c Offscreen,
82 \c Underlay or \c Overlay. Effects will not be rendered for \c Inline mode.
83
84 \note When using post-processing effects, the application-provided shaders
85 should expect linear color data without tonemapping applied. The
86 tonemapping that is performed during the main render pass (or during skybox
87 rendering, if there is a skybox) when
88 \l{SceneEnvironment::tonemapMode}{tonemapMode} is set to a value other than
89 \c SceneEnvironment.TonemapModeNone, is automatically disabled when there
90 is at least one post-processing effect specified in the SceneEnvironment.
91 The last effect in the chain (more precisely, the last pass of the last
92 effect in the chain) will automatically get its fragment shader amended to
93 perform the same tonemapping the main render pass would.
94
95 \note Effects that perform their own tonemapping should be used in a
96 SceneEnvironment that has the built-in tonemapping disabled by setting
97 \l{SceneEnvironment::tonemapMode}{tonemapMode} to \c
98 SceneEnvironment.TonemapModeNone.
99
100 \note By default the texture used as the effects' input is created with a
101 floating point texture format, such as 16-bit floating point RGBA. The
102 output texture's format is the same since by default it follows the input
103 format. This can be overridden using \l Buffer and an empty name. The
104 default RGBA16F is useful because it allows working with non-tonemapped
105 linear data without having the color values outside the 0-1 range clamped.
106
107 \section1 Exposing data to the shaders
108
109 Like with CustomMaterial or ShaderEffect, the dynamic properties of an
110 Effect object can be changed and animated using the usual QML and Qt Quick
111 facilities, and the values are exposed to the shaders automatically. The
112 following list shows how properties are mapped:
113
114 \list
115 \li bool, int, real -> bool, int, float
116 \li QColor, \l{QtQml::Qt::rgba()}{color} -> vec4, and the color gets
117 converted to linear, assuming sRGB space for the color value specified in
118 QML. The built-in Qt colors, such as \c{"green"} are in sRGB color space as
119 well, and the same conversion is performed for all color properties of
120 DefaultMaterial and PrincipledMaterial, so this behavior of Effect
121 matches those.
122 \li QRect, QRectF, \l{QtQml::Qt::rect()}{rect} -> vec4
123 \li QPoint, QPointF, \l{QtQml::Qt::point()}{point}, QSize, QSizeF, \l{QtQml::Qt::size()}{size} -> vec2
124 \li QVector2D, \l{QtQml::Qt::vector2d()}{vector2d} -> vec3
125 \li QVector3D, \l{QtQml::Qt::vector3d()}{vector3d} -> vec3
126 \li QVector4D, \l{QtQml::Qt::vector4d()}{vector4d} -> vec4
127 \li QMatrix4x4, \l{QtQml::Qt::matrix4x4()}{matrix4x4} -> mat4
128 \li QQuaternion, \l{QtQml::Qt::quaternion()}{quaternion} -> vec4, scalar value is \c w
129
130 \li \l Texture -> a sampler whose type follows the texture: samplerCube
131 for a \l CubeMapTexture, sampler3D when the texture data has a depth,
132 and sampler2D otherwise. For a texture with a
133 \l{Texture::textureProvider}{textureProvider}, the provider's
134 \l{TextureProviderExtension::samplerHint}{samplerHint} decides the type
135 instead, which also allows sampler2DArray, samplerCubeArray, and
136 samplerBuffer. Properties of the \l Texture type are supported since
137 Qt 6.13; earlier versions require a \l TextureInput.
138
139 A null property has no texture to take the sampler type from, so the
140 declared type of the property is used: a property declared as
141 \l CubeMapTexture is a samplerCube while it is null, and any other is a
142 sampler2D. Declare a property that will hold a cube map as
143 \l CubeMapTexture, so that the shader code sampling it stays valid before
144 the texture is assigned. A null property exposes a dummy texture of the
145 declared type to the shader, meaning the shaders are still functional
146 but will sample a texture with opaque black image content.
147
148 When it comes to the \l Texture properties, the source, tiling, and
149 filtering related ones are the only ones that are taken into account
150 implicitly with effects, as the rest (such as, UV transformations) is up
151 to the custom shaders to implement as they see fit.
152
153 \li TextureInput -> the same as for the \l Texture it references. This is
154 deprecated, and supported for compatibility. Setting its
155 \l{TextureInput::enabled}{enabled} property to false has the same effect
156 as a null texture.
157
158 \li \l ShaderImage -> a GLSL image (such as \c image2D or
159 \c uimage3D), declared in the shader with the \c SHADER_IMAGE macro.
160 Unlike \l Texture or \l BufferInput, a \l ShaderImage is meant to
161 be read and/or written directly with \c imageLoad()/imageStore() rather
162 than sampled.
163
164 \li \l ShaderStorageBuffer -> a shader storage buffer, declared in
165 the shader with the \c STORAGE_BUFFER macro, exposing the referenced
166 \l ShaderStorageBuffer's content as a GLSL buffer block.
167
168 \endlist
169
170 \note When a uniform referenced in the shader code does not have a
171 corresponding property, it will cause a shader compilation error when
172 processing the effect at run time. There are some exceptions to this,
173 such as, sampler uniforms, that get a dummy texture bound when no
174 corresponding QML property is present, but as a general rule, all uniforms
175 and samplers must have a corresponding property declared in the
176 Effect object.
177
178 \section1 Getting started with user-defined effects
179
180 A custom post-processing effect involves at minimum an Effect object and a
181 fragment shader snippet. Some effects will also want a customized vertex
182 shader as well.
183
184 As a simple example, let's create an effect that combines the scene's
185 content with an image, while further altering the red channel's value in an
186 animated manner:
187
188 \table 70%
189 \row
190 \li \qml
191 Effect {
192 id: simpleEffect
193 property Texture tex: Texture { source: "image.png" }
194 property real redLevel
195 NumberAnimation on redLevel { from: 0; to: 1; duration: 5000; loops: -1 }
196 passes: Pass {
197 shaders: Shader {
198 stage: Shader.Fragment
199 shader: "effect.frag"
200 }
201 }
202 }
203 \endqml
204 \li \badcode
205 void MAIN()
206 {
207 vec4 c = texture(tex, TEXTURE_UV);
208 c.r *= redLevel;
209 FRAGCOLOR = c * texture(INPUT, INPUT_UV);
210 }
211 \endcode
212 \endtable
213
214 Here the texture with the image \c{image.png} is exposed to the shader under
215 the name \c tex. The value of redLevel is available in the shader in a \c
216 float uniform with the same name.
217
218 The fragment shader must contain a function called \c MAIN. The final
219 fragment color is determined by \c FRAGCOLOR. The main input texture, with
220 the contents of the View3D's scene, is accessible under a \c sampler2D with
221 the name \c INPUT. The UV coordinates from the quad are in \c
222 INPUT_UV. These UV values are always suitable for sampling \c INPUT,
223 regardless of the underlying graphics API at run time (and so regardless of
224 the Y axis direction in images since the necessary adjustments are applied
225 automatically by Qt Quick 3D). Sampling the texture with our external image
226 is done using \c TEXTURE_UV. \c INPUT_UV is not suitable in cross-platform
227 applications since V needs to be flipped to cater for the coordinate system
228 differences mentioned before, using a logic that is different for textures
229 based on images and textures used as render targets. Fortunately this is all
230 taken care of by the engine so the shader need no further logic for this.
231
232 Once simpleEffect is available, it can be associated with the effects list
233 of a the View3D's SceneEnvironment:
234
235 \qml
236 environment: SceneEnvironment {
237 effects: [ simpleEffect ]
238 }
239 \endqml
240
241 The results would look something like the following, with the original scene
242 on the left and with the effect applied on the right:
243
244 \table 70%
245 \row
246 \li \image effect_intro_1.png
247 {Three different 3D objects}
248 \li \image effect_intro_2.png
249 {Three different 3D objects with transparent Qt logo overlaid as
250 fullscreen effect}
251 \endtable
252
253 \note The \c shader property value in Shader is a URL, as is the custom in
254 QML and Qt Quick, referencing the file containing the shader snippet, and
255 works very similarly to ShaderEffect or
256 \l{Image::source}{Image.source}. Only the \c file and \c qrc schemes are
257 supported.. It is also possible to omit the \c file scheme, allowing to
258 specify a relative path in a convenient way. Such a path is resolved
259 relative to the component's (the \c{.qml} file's) location.
260
261 \note Shader code is always provided using Vulkan-style GLSL, regardless of
262 the graphics API used by Qt at run time.
263
264 \note The vertex and fragment shader code provided by the effect are not
265 full, complete GLSL shaders on their own. Rather, they provide a \c MAIN
266 function, and optionally a set of \c VARYING declarations, which are then
267 amended with further shader code by the engine.
268
269 \note The above example is not compatible with the optional multiview rendering mode that is used in some VR/AR applications.
270 To make it function both with and without multiview mode, change MAIN() like this:
271 \badcode
272 void MAIN()
273 {
274 vec4 c = texture(tex, TEXTURE_UV);
275 c.r *= redLevel;
276 #if QSHADER_VIEW_COUNT >= 2
277 FRAGCOLOR = c * texture(INPUT, vec3(INPUT_UV, VIEW_INDEX));
278 #else
279 FRAGCOLOR = c * texture(INPUT, INPUT_UV);
280 #endif
281 }
282 \endcode
283
284 \section1 Effects with vertex shaders
285
286 A vertex shader, when present, must provide a function called \c MAIN. In
287 the vast majority of cases the custom vertex shader will not want to provide
288 its own calculation of the homogenous vertex position, but it is possible
289 using \c POSITION, \c VERTEX, and \c MODELVIEWPROJECTION_MATRIX. When
290 \c POSITION is not present in the custom shader code, a statement equivalent to
291 \c{POSITION = MODELVIEWPROJECTION_MATRIX * vec4(VERTEX, 1.0);} will be
292 injected automatically by Qt Quick 3D.
293
294 To pass data between the vertex and fragment shaders, use the VARYING
295 keyword. Internally this will then be transformed into the appropriate
296 vertex output or fragment input declaration. The fragment shader can use the
297 same declaration, which then allows to read the interpolated value for the
298 current fragment.
299
300 Let's look at example, that is in effect very similar to the built-in
301 DistortionSpiral effect:
302
303 \table 70%
304 \row
305 \li \badcode
306 VARYING vec2 center_vec;
307 void MAIN()
308 {
309 center_vec = INPUT_UV - vec2(0.5, 0.5);
310 center_vec.y *= INPUT_SIZE.y / INPUT_SIZE.x;
311 }
312 \endcode
313 \li \badcode
314 VARYING vec2 center_vec;
315 void MAIN()
316 {
317 float radius = 0.25;
318 float dist_to_center = length(center_vec) / radius;
319 vec2 texcoord = INPUT_UV;
320 if (dist_to_center <= 1.0) {
321 float rotation_amount = (1.0 - dist_to_center) * (1.0 - dist_to_center);
322 float r = radians(360.0) * rotation_amount / 4.0 * FRAMEBUFFER_Y_UP;
323 mat2 rotation = mat2(cos(r), sin(r), -sin(r), cos(r));
324 texcoord = vec2(0.5, 0.5) + rotation * (INPUT_UV - vec2(0.5, 0.5));
325 }
326 FRAGCOLOR = texture(INPUT, texcoord);
327 }
328 \endcode
329 \endtable
330
331 The Effect object's \c passes list should now specify both the vertex and
332 fragment snippets:
333
334 \qml
335 passes: Pass {
336 shaders: [
337 Shader {
338 stage: Shader.Vertex
339 shader: "effect.vert"
340 },
341 Shader {
342 stage: Shader.Fragment
343 shader: "effect.frag"
344 }
345 ]
346 }
347 \endqml
348
349 The end result looks like the following:
350
351 \table 70%
352 \row
353 \li \image effect_intro_1.png
354 {Three different 3D objects}
355 \li \image effect_intro_3.png
356 {Warped view of three different 3D objects showing vertex shader
357 effect}
358 \endtable
359
360 \section1 Special keywords in effect shaders
361
362 \list
363
364 \li \c VARYING - Declares a vertex output or fragment input, depending on the type of the current shader.
365 \li \c MAIN - This function must always be present in an effect shader.
366 \li \c FRAGCOLOR - \c vec4 - The final fragment color; the output of the fragment shader. (fragment shader only)
367 \li \c POSITION - \c vec4 - The homogenous position calculated in the vertex shader. (vertex shader only)
368 \li \c MODELVIEWPROJECTION_MATRIX - \c mat4 - The transformation matrix for the screen quad.
369 \li \c VERTEX - \c vec3 - The vertices of the quad; the input to the vertex shader. (vertex shader only)
370
371 \li \c INPUT - \c sampler2D or \c sampler2DArray - The sampler for the input
372 texture with the scene rendered into it, unless a pass redirects its input
373 via a BufferInput object, in which case \c INPUT refers to the additional
374 color buffer's texture referenced by the BufferInput. With \l{Multiview
375 Rendering}{multiview rendering} enabled, which can be relevant for VR/AR
376 applications, this is a sampler2DArray, while the input texture becomes a 2D
377 texture array.
378
379 \li \c INPUT_UV - \c vec2 - UV coordinates for sampling \c INPUT.
380
381 \li \c TEXTURE_UV - \c vec2 - UV coordinates suitable for sampling a Texture
382 with contents loaded from an image file.
383
384 \li \c INPUT_SIZE - \c vec2 - The size of the \c INPUT texture, in pixels.
385
386 \li \c OUTPUT_SIZE - \c vec2 - The size of the output buffer, in
387 pixels. Often the same as \c INPUT_SIZE, unless the pass outputs to an extra
388 Buffer with a size multiplier on it.
389
390 \li \c FRAME - \c float - A frame counter, incremented after each rendered
391 frame in the View3D.
392
393 \li \c DEPTH_TEXTURE - \c sampler2D or \c sampler2DArray - A depth texture
394 with the depth buffer contents with the opaque objects in the scene. Like
395 with CustomMaterial, the presence of this keyword in the shader triggers
396 generating the depth texture automatically.
397
398 \li \c NORMAL_ROUGHNESS_TEXTURE - \c sampler2D - A texture with the
399 world-space normals and material roughness of the opaque objects in the
400 currently visible portion of the scene. Like with CustomMaterial, the
401 presence of this keyword in the shader implies an additional render pass to
402 generate the normal texture.
403
404 \li \c VIEW_INDEX - \c uint - With \l{Multiview Rendering}{multiview
405 rendering} enabled, this is the current view index, available in both vertex
406 and fragment shaders. Always 0 when multiview rendering is not used.
407
408 \li \c PROJECTION_MATRIX - \c mat4, the projection matrix. Note that with
409 \l{Multiview Rendering}{multiview rendering}, this is an array of matrices.
410
411 \li \c INVERSE_PROJECTION_MATRIX - \c mat4, the inverse projection matrix.
412 Note that with \l{Multiview Rendering}{multiview rendering}, this is an array
413 of matrices.
414
415 \li \c VIEW_MATRIX -> \c mat4, the view (camera) matrix.
416 Note that with \l{Multiview Rendering}{multiview rendering}, this is an array
417 of matrices.
418
419 \li float \c NDC_Y_UP - The value is \c 1 when the Y axis points up in
420 normalized device coordinate space, and \c{-1} when the Y axis points down.
421 Y pointing down is the case when rendering happens with Vulkan.
422
423 \li float \c FRAMEBUFFER_Y_UP - The value is \c 1 when the Y axis points up
424 in the coordinate system for framebuffers (textures), meaning \c{(0, 0)} is
425 the bottom-left corner. The value is \c{-1} when the Y axis points down,
426 \c{(0, 0)} being the top-left corner.
427
428 \li float \c NEAR_CLIP_VALUE - The value is \c -1 for when the clipping plane
429 range's starts at \c -1 and goes to \c 1. This is true when using OpenGL for
430 rendering. For other rendering backends the value of this property will be
431 \c 0 meaning the clipping plane range is \c 0 to \c 1.
432
433 \endlist
434
435 \section1 Building multi-pass effects
436
437 A multi-pass effect often uses more than one set of shaders, and takes the
438 \l{Pass::output}{output} and \l{Pass::commands}{commands} properties into
439 use. Each entry in the passes list translates to a render pass drawing a
440 quad into the pass's output texture, while sampling the effect's input texture
441 and optionally other textures as well.
442
443 The typical outline of a multi-pass Effect can look like the following:
444
445 \qml
446 passes: [
447 Pass {
448 shaders: [
449 Shader {
450 stage: Shader.Vertex
451 shader: "pass1.vert"
452 },
453 Shader {
454 stage: Shader.Fragment
455 shader: "pass1.frag"
456 }
457 // This pass outputs to the intermediate texture described
458 // by the Buffer object.
459 output: intermediateColorBuffer
460 ],
461 },
462 Pass {
463 shaders: [
464 Shader {
465 stage: Shader.Vertex
466 shader: "pass2.vert"
467 },
468 Shader {
469 stage: Shader.Fragment
470 shader: "pass2.frag"
471 }
472 // The output of the last pass needs no redirection, it is
473 // the final result of the effect.
474 ],
475 commands: [
476 // This pass reads from the intermediate texture, meaning
477 // INPUT in the shader will refer to the texture associated
478 // with the Buffer.
479 BufferInput {
480 buffer: intermediateColorBuffer
481 }
482 ]
483 }
484 ]
485 \endqml
486
487 What is \c intermediateColorBuffer?
488
489 \qml
490 Buffer {
491 id: intermediateColorBuffer
492 name: "tempBuffer"
493 // format: Buffer.RGBA8
494 // textureFilterOperation: Buffer.Linear
495 // textureCoordOperation: Buffer.ClampToEdge
496 }
497 \endqml
498
499 The commented properties are not necessary if the desired values match the
500 defaults.
501
502 Internally the presence of this Buffer object and referencing it from the \c
503 output property of a Pass leads to creating a texture with a size matching
504 the View3D, and so the size of the implicit input and output textures. When
505 this is not desired, the \l{Buffer::sizeMultiplier}{sizeMultiplier} property
506 can be used to get an intermediate texture with a different size. This can
507 lead to the \c INPUT_SIZE and \c OUTPUT_SIZE uniforms in the shader having
508 different values.
509
510 By default the Effect cannot count on textures preserving their contents
511 between frames. When a new intermediate texture is created, it is cleared to
512 \c{vec4(0.0)}. Afterwards, the same texture can be reused for another
513 purpose. Therefore, effect passes should always write to the entire texture,
514 without making assumptions about their content at the start of the pass.
515 There is an exception to this: Buffer objects with
516 \l{Buffer::bufferFlags}{bufferFlags} set to Buffer.SceneLifetime. This
517 indicates that the texture is permanently associated with a pass of the
518 effect and it will not be reused for other purposes. The contents of such
519 color buffers is preserved between frames. This is typically used in a
520 ping-pong fashion in effects like motion blur: the first pass takes the
521 persistent buffer as its input, in addition to the effects main input
522 texture, outputting to another intermediate buffer, while the second pass
523 outputs to the persistent buffer. This way in the first frame the first pass
524 samples an empty (transparent) texture, whereas in subsequent frames it
525 samples the output of the second pass from the previous frame. A third pass
526 can then blend the effect's input and the second pass' output together.
527
528 The BufferInput command type is used to expose custom texture buffers to the
529 render pass.
530
531 For instance, to access \c someBuffer in the render pass shaders under
532 the name, \c mySampler, the following can be added to its command list:
533 \qml
534 BufferInput { buffer: someBuffer; sampler: "mySampler" }
535 \endqml
536
537 If the \c sampler name is not specified, \c INPUT will be used as default.
538
539 Buffers can be useful to share intermediate results between render passes.
540
541 To expose preloaded textures to the effect, use properties of the \l Texture
542 type instead. These can be defined as properties of the Effect itself, and will
543 automatically be accessible to the shaders by their property names.
544 \qml
545 property Texture tex: Texture { source: "image.png" }
546 \endqml
547
548 Here \c tex is a valid sampler in all shaders of all the passes of the
549 effect.
550
551 When it comes to uniform values from properties, all passes in the Effect
552 read the same values in their shaders. If necessary it is possible to
553 override the value of a uniform just for a given pass. This is achieved by
554 adding the \l SetUniformValue command to the list of commands for the pass.
555
556 \note The \l{SetUniformValue::target}{target} of the pass-specific uniform
557 value setter can only refer to a name that is the name of a property of the
558 effect. It can override the value for a property's corresponding uniform,
559 but it cannot introduce new uniforms.
560
561 \section1 Performance considerations
562
563 Be aware of the increased resource usage and potentially reduced performance
564 when using post-processing effects. Just like with Qt Quick layers and
565 ShaderEffect, rendering the scene into a texture and then using that to
566 texture a quad is not a cheap operation, especially on low-end hardware with
567 limited fragment processing power. The amount of additional graphics memory
568 needed, as well as the increase in GPU load both depend on the size of the
569 View3D (which, on embedded devices without a windowing system, may often be
570 as big as the screen resolution). Multi-pass effects, as well as applying
571 multiple effects increase the resource and performance requirements further.
572
573 Therefore, it is highly advisable to ensure early on in the development
574 lifecycle that the targeted device and graphics stack is able to cope with
575 the effects included in the design of the 3D scene at the final product's
576 screen resolution.
577
578 While unavoidable with techniques that need it, \c DEPTH_TEXTURE implies an
579 additional rendering pass to generate the contents of that texture, which
580 can also present a hit on less capable hardware. Therefore, use \c
581 DEPTH_TEXTURE in the effect's shaders only when essential.
582
583 The complexity of the operations in the shaders is also important. Just like
584 with CustomMaterial, a sub-optimal fragment shader can easily lead to
585 reduced rendering performance.
586
587 Be cautious with \l{Buffer::sizeMultiplier}{sizeMultiplier in Buffer} when
588 values larger than 1 are involved. For example, a multiplier of 4 means
589 creating and then rendering to a texture that is 4 times the size of the
590 View3D. Just like with shadow maps and multi- or supersampling, the
591 increased resource and performance costs can quickly outweigh the benefits
592 from better quality on systems with limited GPU power.
593
594 \section1 VR/AR considerations
595
596 When developing applications for virtual or augmented reality by using Qt
597 Quick 3D XR, postprocessing effects are functional and available to use.
598 However, designers are developers should take special care to understand
599 which and what kind of effects make sense in a virtual reality environment.
600 Some effects, including some of the built-in ones in
601 ExtendedSceneEnvironment or the deprecated Effects module, do not lead to a
602 good visual experience in a VR environment, possibly affecting the user
603 physically even (causing, for example, motion sickness or dizziness).
604
605 When the more efficient \l{Multiview Rendering}{multiview rendering mode} is
606 enabled in a VR/AR application, there is no separate render pass for the
607 left and right eye contents. Instead, it all happens in one pass, using a 2D
608 texture array with two layers instead of two independent 2D textures. This
609 also means that many intermediate buffers, meaning color or depth textures,
610 will need to become texture arrays in this mode. This then has implications
611 for custom materials and postprocessing effects. Textures such as the input
612 texture (\c INPUT) and the depth texture (\c DEPTH_TEXTURE) become 2D texture
613 arrays, exposed in the shader as a \c sampler2DArray instead of \c
614 sampler2D. This has implications for GLSL functions such as texture(),
615 textureLod(), or textureSize(). The UV coordinate is then a vec3, not a
616 vec2. Whereas textureSize() returns a vec3, not a vec2. Effects intended to
617 function regardless of the rendering mode, can be written with an
618 appropriate ifdef:
619 \badcode
620 #if QSHADER_VIEW_COUNT >= 2
621 vec4 c = texture(INPUT, vec3(INPUT_UV, VIEW_INDEX));
622 #else
623 vec4 c = texture(INPUT, INPUT_UV);
624 #endif
625 \endcode
626
627 It can also be useful to define macros that handle both cases. For example:
628 \badcode
629 #if QSHADER_VIEW_COUNT >= 2
630 #define SAMPLE_INPUT(uv) texture(INPUT, vec3(uv, VIEW_INDEX))
631 #define SAMPLE_DEPTH(uv) texture(DEPTH_TEXTURE, vec3(uv, VIEW_INDEX)).r
632 #define PROJECTION PROJECTION_MATRIX[VIEW_INDEX]
633 #define INVERSE_PROJECTION INVERSE_PROJECTION_MATRIX[VIEW_INDEX]
634 #else
635 #define SAMPLE_INPUT(uv) texture(INPUT, uv)
636 #define SAMPLE_DEPTH(uv) texture(DEPTH_TEXTURE, uv).r
637 #define PROJECTION PROJECTION_MATRIX
638 #define INVERSE_PROJECTION INVERSE_PROJECTION_MATRIX
639 #endif
640 \endcode
641
642 This does not apply to \c NORMAL_ROUGHNESS_TEXTURE that is always a 2D texture,
643 even when multiview rendering is active:
644 \badcode
645 #define SAMPLE_NORMAL(uv) normalize(texture(NORMAL_ROUGHNESS_TEXTURE, uv).rgb)
646 \endcode
647
648 \note The presence of keywords such as \c DEPTH_TEXTURE trigger additional
649 render passes, and uniforms such as \c INVERSE_PROJECTION_MATRIX are
650 calculated and set upon the presence of the keyword in the shader snippet
651 anywhere. This is more expensive, both when it comes to performance and
652 resource usage. Hence it is recommended to only add such #defines when the
653 textures and matrices will really be used in the effect.
654
655 \section1 Reading and writing images and buffers
656
657 In addition to sampling textures via \l Texture properties and
658 \l BufferInput, an Effect's shaders can read and/or write a
659 \l ShaderImage or a \l ShaderStorageBuffer directly, using the same
660 \c SHADER_IMAGE/\c STORAGE_BUFFER mechanism available to a
661 \l ComputePass:
662
663 \qml
664 Effect {
665 property ShaderImage myImage: sharedImage
666 property ShaderStorageBuffer myBuffer: sharedBuffer
667 passes: Pass {
668 shaders: Shader { stage: Shader.Fragment; shader: "effect.frag" }
669 }
670 }
671 \endqml
672
673 \badcode
674 SHADER_IMAGE(rgba8, myImage, image2D, readonly);
675 STORAGE_BUFFER(myBuffer, readonly) {
676 vec4 values[];
677 }
678
679 void MAIN()
680 {
681 FRAGCOLOR = imageLoad(myImage, ivec2(0, 0)) * values[0];
682 }
683 \endcode
684
685 A writable \c SHADER_IMAGE (one declared without the \c readonly
686 memory qualifier) is bound the same way as for a
687 \l ComputePass, so an effect's fragment shader can also write to a
688 \l ShaderImage, for example to accumulate data that a later pass in the
689 same \l passes chain (or another Effect further down the chain) reads
690 back. The same applies to a writable \c STORAGE_BUFFER. Each \l Pass is
691 a separate, sequential render pass, and QRhi inserts the necessary
692 barriers before every render (and compute) pass, so a later pass
693 reading such an image or buffer is guaranteed to see the complete
694 result of an earlier pass's writes across the whole framebuffer.
695
696 \note Writing to a \c SHADER_IMAGE or a \c STORAGE_BUFFER from an
697 effect's shaders requires the graphics API to support storage access in
698 the graphics pipeline stages, which is not universally available.
699 Direct3D 11 only allows it in fragment shaders, and OpenGL ES 3.1
700 implementations are not required to support it in vertex or fragment
701 shaders at all. For portable code, do the writing in a \l ComputePass
702 and declare the resources \c readonly in the effect.
703
704 \sa Shader, Pass, Buffer, BufferInput, ComputePass, {Qt Quick 3D - Custom Effect Example}
705*/
706
707/*!
708 \qmlproperty list Effect::passes
709 Contains a list of render \l {Pass}{passes} implemented by the effect.
710*/
711
712QQuick3DEffect::QQuick3DEffect(QQuick3DObject *parent)
713 : QQuick3DObject(*(new QQuick3DObjectPrivate(QQuick3DObjectPrivate::Type::Effect, QQuick3DObjectPrivate::Flags::RequiresSecondaryUpdate)), parent)
714 , QQuick3DPropertyChangedTracker(this, QQuick3DSuperClassInfo<QQuick3DEffect>())
715{
716}
717
718QQmlListProperty<QQuick3DShaderUtilsRenderPass> QQuick3DEffect::passes()
719{
720 return QQmlListProperty<QQuick3DShaderUtilsRenderPass>(this,
721 nullptr,
722 QQuick3DEffect::qmlAppendPass,
723 QQuick3DEffect::qmlPassCount,
724 QQuick3DEffect::qmlPassAt,
725 QQuick3DEffect::qmlPassClear);
726}
727
728// Default vertex and fragment shader code that is used when no corresponding
729// Shader is present in the Effect. These go through the usual processing so
730// should use the user-facing builtins.
731
733 "void MAIN()\n"
734 "{\n"
735 "}\n";
736
738 "void MAIN()\n"
739 "{\n"
740 "#if QSHADER_VIEW_COUNT >= 2\n"
741 " FRAGCOLOR = texture(INPUT, vec3(INPUT_UV, VIEW_INDEX));\n"
742 "#else\n"
743 " FRAGCOLOR = texture(INPUT, INPUT_UV);\n"
744 "#endif\n"
745 "}\n";
746
747static inline void insertVertexMainArgs(QByteArray &snippet)
748{
749 static const char *argKey = "/*%QT_ARGS_MAIN%*/";
750 const int argKeyLen = int(strlen(argKey));
751 const int argKeyPos = snippet.indexOf(argKey);
752 if (argKeyPos >= 0)
753 snippet = snippet.left(argKeyPos) + QByteArrayLiteral("inout vec3 VERTEX") + snippet.mid(argKeyPos + argKeyLen);
754}
755
756static inline void resetShaderDependentEffectFlags(QSSGRenderEffect *effectNode)
757{
758 effectNode->setFlag(QSSGRenderEffect::Flags::UsesDepthTexture, false);
759 effectNode->setFlag(QSSGRenderEffect::Flags::UsesProjectionMatrix, false);
760 effectNode->setFlag(QSSGRenderEffect::Flags::UsesInverseProjectionMatrix, false);
761 effectNode->setFlag(QSSGRenderEffect::Flags::UsesViewMatrix, false);
762 effectNode->setFlag(QSSGRenderEffect::Flags::UsesNormalTexture, false);
763 effectNode->setFlag(QSSGRenderEffect::Flags::UsesMotionVectorTexture, false);
764}
765
766static inline void accumulateEffectFlagsFromShader(QSSGRenderEffect *effectNode, const QSSGCustomShaderMetaData &meta)
767{
768 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesDepthTexture))
769 effectNode->setFlag(QSSGRenderEffect::Flags::UsesDepthTexture);
770 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesProjectionMatrix))
771 effectNode->setFlag(QSSGRenderEffect::Flags::UsesProjectionMatrix);
772 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesInverseProjectionMatrix))
773 effectNode->setFlag(QSSGRenderEffect::Flags::UsesInverseProjectionMatrix);
774 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesViewMatrix))
775 effectNode->setFlag(QSSGRenderEffect::Flags::UsesViewMatrix);
776 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesNormalTexture))
777 effectNode->setFlag(QSSGRenderEffect::Flags::UsesNormalTexture);
778 if (meta.flags.testFlag(QSSGCustomShaderMetaData::UsesMotionVectorTexture))
779 effectNode->setFlag(QSSGRenderEffect::Flags::UsesMotionVectorTexture);
780}
781
782QSSGRenderGraphObject *QQuick3DEffect::updateSpatialNode(QSSGRenderGraphObject *node)
783{
784 using namespace QSSGShaderUtils;
785
786 const auto &renderContext = QQuick3DObjectPrivate::get(this)->sceneManager->wattached->rci();
787 if (!renderContext) {
788 qWarning("QQuick3DEffect: No render context interface?");
789 return nullptr;
790 }
791
792 QSSGRenderEffect *effectNode = static_cast<QSSGRenderEffect *>(node);
793 bool newBackendNode = false;
794 if (!effectNode) {
795 effectNode = new QSSGRenderEffect;
796 newBackendNode = true;
797 }
798
799 bool shadersOrBuffersMayChange = false;
800 if (m_dirtyAttributes & Dirty::EffectChainDirty)
801 shadersOrBuffersMayChange = true;
802
803 bool needsSecondaryUpdate = false;
804
805 const bool fullUpdate = newBackendNode || effectNode->incompleteBuildTimeObject || (m_dirtyAttributes & Dirty::TextureDirty);
806
807 if (fullUpdate || shadersOrBuffersMayChange) {
808 markAllDirty();
809
810 // Need to clear the old list with properties and textures first.
811 effectNode->properties.clear();
812 effectNode->textureProperties.clear();
813
814 // Properties -> uniforms
815 QSSGShaderCustomMaterialAdapter::StringPairList uniforms;
816 QSSGShaderCustomMaterialAdapter::StringPairList multiViewDependentSamplers;
817
818 // Registers a sampler uniform for a texture, optionally wrapped in a TextureInput.
819 // Shared by the tracked and the dynamic property path.
820 const auto addTextureProperty = [&](const QByteArray &name, const QByteArray &samplerType,
821 QQuick3DShaderUtilsTextureInput *texInput, QQuick3DTexture *tex) {
822 QSSGRenderEffect::TextureProperty texProp;
823 texProp.name = name;
824 texProp.shaderDataType = QSSGRenderShaderValue::Texture;
825
826 const bool enabled = !texInput || texInput->enabled;
827 if (enabled && tex) // tex may be null if nothing has been assigned (yet)
828 texProp.texImage = tex->getRenderImage();
829
830 if (tex) {
831 texProp.minFilterType = tex->minFilter() == QQuick3DTexture::Nearest ? QSSGRenderTextureFilterOp::Nearest
832 : QSSGRenderTextureFilterOp::Linear;
833 texProp.magFilterType = tex->magFilter() == QQuick3DTexture::Nearest ? QSSGRenderTextureFilterOp::Nearest
834 : QSSGRenderTextureFilterOp::Linear;
835 texProp.mipFilterType = tex->generateMipmaps() ? (tex->mipFilter() == QQuick3DTexture::Nearest ? QSSGRenderTextureFilterOp::Nearest
836 : QSSGRenderTextureFilterOp::Linear)
837 : QSSGRenderTextureFilterOp::None;
838 texProp.horizontalClampType = tex->horizontalTiling() == QQuick3DTexture::Repeat ? QSSGRenderTextureCoordOp::Repeat
839 : (tex->horizontalTiling() == QQuick3DTexture::ClampToEdge ? QSSGRenderTextureCoordOp::ClampToEdge
840 : QSSGRenderTextureCoordOp::MirroredRepeat);
841 texProp.verticalClampType = tex->verticalTiling() == QQuick3DTexture::Repeat ? QSSGRenderTextureCoordOp::Repeat
842 : (tex->verticalTiling() == QQuick3DTexture::ClampToEdge ? QSSGRenderTextureCoordOp::ClampToEdge
843 : QSSGRenderTextureCoordOp::MirroredRepeat);
844 texProp.zClampType = tex->depthTiling() == QQuick3DTexture::Repeat ? QSSGRenderTextureCoordOp::Repeat
845 : (tex->depthTiling() == QQuick3DTexture::ClampToEdge) ? QSSGRenderTextureCoordOp::ClampToEdge
846 : QSSGRenderTextureCoordOp::MirroredRepeat;
847 }
848
849 // Knowing upfront that a sampler2D needs to be a sampler2DArray in
850 // the multiview-compatible version of the shader is not trivial.
851 // Consider: we know the list of TextureInputs, without any
852 // knowledge about the usage of those textures. Intermediate buffers
853 // (textures) also have a default constructed (no source, no source
854 // item, no texture data) Texture set. What indicates that these are
855 // used as intermediate buffers, is the 'output' property of a Pass,
856 // referencing a Buffer object (which objects we otherwise do not
857 // track), the 'name' of which matches TextureInput property name.
858 // The list of passes may vary dynamically, and some Passes may not
859 // be listed at any point in time if the effect has an
860 // ubershader-ish design. Thus one can have TextureInputs that are
861 // not associated with a Buffer (when scanning through the Passes),
862 // and so we cannot just check the 'output'-referenced Buffers to
863 // decide if a TextureInput's Texture needs to be treated specially
864 // in the generated shader code. (and the type must be correct even
865 // for, from our perspective, "unused" samplers since they are still
866 // in the shader code, and will get a dummy texture bound)
867 //
868 // Therefore, in the absence of more sophisticated options, we just
869 // look at the TextureInput's texture, and if it is something along
870 // the lines of
871 // property TextureInput intermediateColorBuffer1: TextureInput { texture: Texture { } }
872 // then it is added to the special list, indicating the the type is
873 // sampler2D or sampler2DArray, depending on the rendering mode the
874 // shader is targeting.
875 if (tex && !tex->hasSourceData()) {
876 // the type may get adjusted later
877 multiViewDependentSamplers.append({ QByteArrayLiteral("sampler2D"), name });
878 } else {
879 uniforms.append({ samplerType, name });
880 }
881
882 effectNode->textureProperties.push_back(texProp);
883 };
884
885 // Dynamic properties are not covered by the tracker, so changes to those
886 // TextureInputs have to be watched here.
887 const auto addDynamicTextureInput = [&](const QByteArray &name, QQuick3DShaderUtilsTextureInput *texInput) {
888 addTextureProperty(name, samplerTypeName(texInput->texture()), texInput, texInput->texture());
889 if (fullUpdate) {
890 connect(texInput, &QQuick3DShaderUtilsTextureInput::enabledChanged,
891 this, &QQuick3DEffect::onTextureDirty);
892 connect(texInput, &QQuick3DShaderUtilsTextureInput::textureChanged,
893 this, &QQuick3DEffect::onTextureDirty);
894 } // else already connected
895 };
896
897 // The tracker discovers all user-declared properties and watches them, including
898 // the textures (and TextureInputs) they refer to. A tracked texture property is
899 // either a plain Texture or, for compatibility, a TextureInput; the sampler type
900 // was determined by the tracker from the texture.
901 //
902 // The ShaderImage and ShaderStorageBuffer properties are watched by
903 // m_shaderResources rather than by the tracker, and extractProperties() only
904 // re-reads dirty properties, so have it re-read them on every rebuild to pick up
905 // one that gained or lost its object.
906 for (int pid : m_shaderResources.resourceProperties())
907 addDirtyProperty(pid);
908
909 QByteArrayList metadata;
910 for (const auto &prop : extractProperties()) {
911 if (prop.shaderDataType == QSSGRenderShaderValue::StorageBuffer) {
912 const QVariant value = metaObject()->property(prop.pid).read(this);
913 needsSecondaryUpdate |= !handleBufferProperty(value.value<QQuick3DShaderStorageBuffer *>(), prop.name,
914 prop.pid, metadata, effectNode->properties);
915 continue;
916 }
917 if (prop.shaderDataType == QSSGRenderShaderValue::Image) {
918 const QVariant value = metaObject()->property(prop.pid).read(this);
919 needsSecondaryUpdate |= !handleImageProperty(value.value<QQuick3DShaderImage *>(), prop.name,
920 prop.pid, metadata, effectNode->properties);
921 continue;
922 }
923 if (prop.shaderDataType != QSSGRenderShaderValue::Texture) {
924 uniforms.append({ prop.typeName, prop.name });
925 effectNode->properties.push_back(prop);
926 continue;
927 }
928
929 const QVariant propValue = metaObject()->property(prop.pid).read(this);
930 auto *texInput = propValue.value<QQuick3DShaderUtilsTextureInput *>();
931 QQuick3DTexture *tex = texInput ? texInput->texture() : QSSGShaderUtils::textureFromValue(propValue);
932 addTextureProperty(prop.name, prop.typeName, texInput, tex);
933 }
934
935 static const QMetaMethod onResourceDirty = staticMetaObject.method(staticMetaObject.indexOfSlot("onShaderResourceDirty()"));
936 m_shaderResources.trackProperties(staticMetaObject.propertyCount(), onResourceDirty);
937
938 if (effectNode->incompleteBuildTimeObject) { // This object came from the shadergen tool
939 const auto names = dynamicPropertyNames();
940 for (const auto &name : names) {
941 QVariant propValue = property(name.constData());
942 QMetaType propType = propValue.metaType();
943 if (propType == QMetaType(QMetaType::QVariant))
944 propType = propValue.metaType();
945
946 if (propType.id() >= QMetaType::User) {
947 if (propType.id() == qMetaTypeId<QQuick3DShaderUtilsTextureInput *>()) {
948 if (auto *texInput = propValue.value<QQuick3DShaderUtilsTextureInput *>())
949 addDynamicTextureInput(name, texInput);
950 }
951 } else if (propType.id() == QMetaType::QObjectStar) {
952 if (auto *texInput = qobject_cast<QQuick3DShaderUtilsTextureInput *>(propValue.value<QObject *>()))
953 addDynamicTextureInput(name, texInput);
954 } else {
955 const auto type = uniformType(propType);
956 if (type != QSSGRenderShaderValue::Unknown) {
957 uniforms.append({ uniformTypeName(propType), name });
958 effectNode->properties.push_back({ name, uniformTypeName(propType),
959 propValue, uniformType(propType), -1 /* aka. dynamic property */});
960 } else {
961 qWarning("No known uniform conversion found for effect property %s. Skipping", name.constData());
962 }
963 }
964 }
965 }
966
967 // built-ins
968 uniforms.append({ "mat4", "qt_modelViewProjection" });
969 uniforms.append({ "vec2", "qt_inputSize" });
970 uniforms.append({ "vec2", "qt_outputSize" });
971 uniforms.append({ "float", "qt_frame_num" });
972 uniforms.append({ "float", "qt_fps" });
973 uniforms.append({ "vec2", "qt_cameraProperties" });
974 uniforms.append({ "float", "qt_normalAdjustViewportFactor" });
975 uniforms.append({ "float", "qt_nearClipValue" });
976 uniforms.append({ "vec4", "qt_rhi_properties" });
977
978 // qt_inputTexture is not listed in uniforms, will be added by prepareCustomShader()
979 // since the name and type varies between non-multiview and multiview mode
980
981 QSSGShaderCustomMaterialAdapter::StringPairList builtinVertexInputs;
982 builtinVertexInputs.append({ "vec3", "attr_pos" });
983 builtinVertexInputs.append({ "vec2", "attr_uv" });
984
985 QSSGShaderCustomMaterialAdapter::StringPairList builtinVertexOutputs;
986 builtinVertexOutputs.append({ "vec2", "qt_inputUV" });
987 builtinVertexOutputs.append({ "vec2", "qt_textureUV" });
988 builtinVertexOutputs.append({ "flat uint", "qt_viewIndex" });
989
990 // fragOutput is added automatically by the program generator
991
992 resetShaderDependentEffectFlags(effectNode);
993
994 if (!m_passes.isEmpty()) {
995 const QQmlContext *context = qmlContext(this);
996 effectNode->resetCommands();
997 for (QQuick3DShaderUtilsRenderPass *pass : std::as_const(m_passes)) {
998 // Have a key composed more or less of the vertex and fragment filenames.
999 // The shaderLibraryManager uses stage+shaderPathKey as the key.
1000 // Thus shaderPathKey is then sufficient to look up both the vertex and fragment shaders later on.
1001 // Note that this key is not suitable as a unique key for the graphics resources because the same
1002 // set of shader files can be used in multiple different passes, or in multiple active effects.
1003 // But that's the effect system's problem.
1004 QByteArray shaderPathKey("effect pipeline--");
1005 QSSGRenderEffect::ShaderPrepPassData passData;
1006 for (QQuick3DShaderUtilsShader::Stage stage : { QQuick3DShaderUtilsShader::Stage::Vertex, QQuick3DShaderUtilsShader::Stage::Fragment }) {
1007 QQuick3DShaderUtilsShader *shader = nullptr;
1008 for (QQuick3DShaderUtilsShader *s : pass->m_shaders) {
1009 if (s->stage == stage) {
1010 shader = s;
1011 break;
1012 }
1013 }
1014
1015 // just how many enums does one need for the exact same thing...
1016 QSSGShaderCache::ShaderType type = QSSGShaderCache::ShaderType::Vertex;
1017 if (stage == QQuick3DShaderUtilsShader::Stage::Fragment)
1018 type = QSSGShaderCache::ShaderType::Fragment;
1019
1020 // Will just use the custom material infrastructure. Some
1021 // substitutions are common between custom materials and effects.
1022 //
1023 // Substitutions relevant to us here:
1024 // MAIN -> qt_customMain
1025 // FRAGCOLOR -> fragOutput
1026 // POSITION -> gl_Position
1027 // MODELVIEWPROJECTION_MATRIX -> qt_modelViewProjection
1028 // DEPTH_TEXTURE -> qt_depthTexture
1029 // ... other things shared with custom material
1030 //
1031 // INPUT -> qt_inputTexture
1032 // INPUT_UV -> qt_inputUV
1033 // ... other effect specifics
1034 //
1035 // Built-in uniforms, inputs and outputs will be baked into
1036 // metadata comment blocks in the resulting source code.
1037 // Same goes for inputs/outputs declared with VARYING.
1038
1039 QByteArray code;
1040 if (shader) {
1041 code = QSSGShaderUtils::resolveShader(shader->shader, context, shaderPathKey); // appends to shaderPathKey
1042 } else {
1043 if (!shaderPathKey.isEmpty())
1044 shaderPathKey.append('>');
1045 shaderPathKey += "DEFAULT";
1046 if (type == QSSGShaderCache::ShaderType::Vertex)
1047 code = default_effect_vertex_shader;
1048 else
1049 code = default_effect_fragment_shader;
1050 }
1051
1052 QByteArrayList imgBufs;
1053 if (type == QSSGShaderCache::ShaderType::Vertex) {
1054 if (!processMetadata(effectNode->properties, metadata, passData.vertexMetaData[0].imageBufferMetadata, code)) {
1055 qWarning("Effect: Shader Image and/or Buffer processing failed in vertex shader.");
1056 // Leave nothing pending, so that the next change triggers an update again.
1057 m_dirtyAttributes = 0;
1058 return effectNode;
1059 }
1060 imgBufs = passData.vertexMetaData[0].imageBufferMetadata;
1061 } else {
1062 if (!processMetadata(effectNode->properties, metadata, passData.fragmentMetaData[0].imageBufferMetadata, code)) {
1063 qWarning("Effect: Shader Image and/or Buffer processing failed in fragment shader.");
1064 // Leave nothing pending, so that the next change triggers an update again.
1065 m_dirtyAttributes = 0;
1066 return effectNode;
1067 }
1068 imgBufs = passData.fragmentMetaData[0].imageBufferMetadata;
1069 }
1070
1071 for (auto pathKeyIndex : { QSSGRenderCustomMaterial::RegularShaderPathKeyIndex, QSSGRenderCustomMaterial::MultiViewShaderPathKeyIndex }) {
1072 QSSGShaderCustomMaterialAdapter::ShaderCodeAndMetaData result;
1073 QSSGShaderCustomMaterialAdapter::CustomShaderPrepWorkData scratch;
1074
1075 QSSGShaderCustomMaterialAdapter::beginPrepareCustomShader(
1076 &scratch,
1077 &result,
1078 code,
1079 type,
1080 pathKeyIndex == QSSGRenderCustomMaterial::RegularShaderPathKeyIndex ? false : true);
1081
1082 QSSGShaderCustomMaterialAdapter::StringPairList multiViewDependentUniforms;
1083 if (result.second.flags.testFlag(QSSGCustomShaderMetaData::UsesProjectionMatrix)
1084 || result.second.flags.testFlag(QSSGCustomShaderMetaData::UsesInverseProjectionMatrix))
1085 {
1086 multiViewDependentUniforms.append({ "mat4", "qt_projectionMatrix" });
1087 multiViewDependentUniforms.append({ "mat4", "qt_inverseProjectionMatrix" });
1088 }
1089
1090 multiViewDependentUniforms.append({ "mat4", "qt_viewMatrix" });
1091
1092 accumulateEffectFlagsFromShader(effectNode, result.second);
1093
1094 QSSGShaderCustomMaterialAdapter::finishPrepareCustomShader(
1095 &result.first, // effectively appends the QQ3D_SHADER_META block
1096 scratch,
1097 result,
1098 type,
1099 pathKeyIndex == QSSGRenderCustomMaterial::RegularShaderPathKeyIndex ? false : true,
1100 uniforms,
1101 imgBufs,
1102 type == QSSGShaderCache::ShaderType::Vertex ? builtinVertexInputs : builtinVertexOutputs,
1103 type == QSSGShaderCache::ShaderType::Vertex ? builtinVertexOutputs : QSSGShaderCustomMaterialAdapter::StringPairList(),
1104 multiViewDependentSamplers,
1105 multiViewDependentUniforms);
1106
1107 if (type == QSSGShaderCache::ShaderType::Vertex) {
1108 // qt_customMain() has an argument list which gets injected here
1109 insertVertexMainArgs(result.first);
1110 passData.vertexShaderCode[pathKeyIndex] = result.first;
1111 passData.vertexMetaData[pathKeyIndex] = result.second;
1112 passData.vertexMetaData[pathKeyIndex].imageBufferMetadata = imgBufs;
1113 } else {
1114 passData.fragmentShaderCode[pathKeyIndex] = result.first;
1115 passData.fragmentMetaData[pathKeyIndex] = result.second;
1116 passData.fragmentMetaData[pathKeyIndex].imageBufferMetadata = imgBufs;
1117 }
1118 }
1119 }
1120
1121 effectNode->commands.push_back(nullptr); // will be changed to QSSGBindShader in finalizeShaders
1122 passData.bindShaderCmdIndex = effectNode->commands.size() - 1;
1123
1124 // finalizing the shader code happens in a separate step later on by the backend node
1125 passData.shaderPathKeyPrefix = shaderPathKey;
1126 effectNode->shaderPrepData.passes.append(passData);
1127 effectNode->shaderPrepData.valid = true; // trigger reprocessing the shader code later on
1128
1129 effectNode->commands.push_back(new QSSGApplyInstanceValue);
1130
1131 // Buffers
1132 QQuick3DShaderUtilsBuffer *outputBuffer = pass->outputBuffer;
1133 if (outputBuffer) {
1134 const QByteArray &outBufferName = outputBuffer->name;
1135 if (outBufferName.isEmpty()) {
1136 // default output buffer (with settings)
1137 auto outputFormat = QQuick3DShaderUtilsBuffer::mapTextureFormat(outputBuffer->format());
1138 effectNode->commands.push_back(new QSSGBindTarget(outputFormat));
1139 effectNode->outputFormat = outputFormat;
1140 } else {
1141 // Allocate buffer command
1142 effectNode->commands.push_back(outputBuffer->cloneCommand());
1143 connect(outputBuffer, &QQuick3DShaderUtilsBuffer::changed, this, &QQuick3DEffect::onPassDirty, Qt::UniqueConnection);
1144 // bind buffer
1145 effectNode->commands.push_back(new QSSGBindBuffer(outBufferName));
1146 }
1147 } else {
1148 // Use the default output buffer, same format as the source buffer
1149 effectNode->commands.push_back(new QSSGBindTarget(QSSGRenderTextureFormat::Unknown));
1150 effectNode->outputFormat = QSSGRenderTextureFormat::Unknown;
1151 }
1152
1153 // Other commands (BufferInput, Blending ... )
1154 const auto &extraCommands = pass->m_commands;
1155 for (const auto &command : extraCommands) {
1156 const int bufferCount = command->bufferCount();
1157 for (int i = 0; i != bufferCount; ++i) {
1158 effectNode->commands.push_back(command->bufferAt(i)->cloneCommand());
1159 connect(command->bufferAt(i), &QQuick3DShaderUtilsBuffer::changed, this, &QQuick3DEffect::onPassDirty, Qt::UniqueConnection);
1160 }
1161 effectNode->commands.push_back(command->cloneCommand());
1162 }
1163
1164 effectNode->commands.push_back(new QSSGRender);
1165 }
1166 }
1167 }
1168
1169 if (m_dirtyAttributes & Dirty::PropertyDirty) {
1170 // Refresh the values of the tracked properties in place. Dynamic properties
1171 // (pid -1) are not tracked and keep the values recorded when they were added.
1172 const auto props = extractProperties();
1173 for (auto &prop : effectNode->properties) {
1174 if (prop.pid < 0)
1175 continue;
1176 // The value of an image or buffer property is the render side object, not the
1177 // tracker's value. A rebuild has just resolved it.
1178 if (prop.shaderDataType == QSSGRenderShaderValue::StorageBuffer
1179 || prop.shaderDataType == QSSGRenderShaderValue::Image) {
1180 if (newBackendNode || shadersOrBuffersMayChange)
1181 continue;
1182 const QVariant value = metaObject()->property(prop.pid).read(this);
1183 if (prop.shaderDataType == QSSGRenderShaderValue::StorageBuffer)
1184 updateBufferProperty(value.value<QQuick3DShaderStorageBuffer *>(), prop);
1185 else
1186 updateImageProperty(value.value<QQuick3DShaderImage *>(), prop);
1187 continue;
1188 }
1189 const auto it = std::lower_bound(props.cbegin(), props.cend(), prop.pid,
1190 [](const QSSGBaseTypeProperty &p, int pid) { return p.pid < pid; });
1191 if (it != props.cend() && it->pid == prop.pid)
1192 prop.value = it->value;
1193 }
1194 // A swapped-in object may not have been referenced into the scene yet.
1195 if (!fullUpdate && !shadersOrBuffersMayChange)
1196 needsSecondaryUpdate |= !m_shaderResources.updateResources();
1197 }
1198
1199 m_dirtyAttributes = 0;
1200 if (needsSecondaryUpdate) {
1201 markDirty(Dirty::TextureDirty);
1202 QQuick3DObjectPrivate::get(this)->requestSecondaryUpdate();
1203 }
1204
1205 DebugViewHelpers::ensureDebugObjectName(effectNode, this);
1206
1207 return effectNode;
1208}
1209
1210void QQuick3DEffect::markTrackedPropertyDirty(QMetaProperty, DirtyPropertyHint hint)
1211{
1212 if (hint == DirtyPropertyHint::Reference)
1213 markDirty(Dirty::TextureDirty);
1214 else
1215 markDirty(Dirty::PropertyDirty);
1216}
1217
1218void QQuick3DEffect::onTextureDirty()
1219{
1220 markDirty(Dirty::TextureDirty);
1221}
1222
1223void QQuick3DEffect::onShaderResourceDirty()
1224{
1225 // Swapping one object for another only changes the binding, but a property
1226 // gaining or losing its object, or an image of another format, changes the
1227 // generated shader.
1228 markDirty(m_shaderResources.hasResourceLayoutChanged() ? Dirty::TextureDirty : Dirty::PropertyDirty);
1229}
1230
1231void QQuick3DEffect::onPassDirty()
1232{
1233 // changed() signals from not just Passes but Buffers are also hooked up to this.
1234 // Any property change should lead to re-evaluating the whole effect in sync.
1235 markDirty(Dirty::EffectChainDirty);
1236}
1237
1238void QQuick3DEffect::effectChainDirty()
1239{
1240 markDirty(Dirty::EffectChainDirty);
1241}
1242
1243void QQuick3DEffect::markDirty(QQuick3DEffect::Dirty type)
1244{
1245 if (!(m_dirtyAttributes & quint32(type))) {
1246 m_dirtyAttributes |= quint32(type);
1247 update();
1248 }
1249}
1250
1251void QQuick3DEffect::updateSceneManager(QQuick3DSceneManager *sceneManager)
1252{
1253 updateTrackedSceneManager(sceneManager);
1254 if (sceneManager) {
1255 for (const auto &it : std::as_const(m_dynamicTextureMaps)) {
1256 if (auto tex = it->texture())
1257 QQuick3DObjectPrivate::refSceneManager(tex, *sceneManager);
1258 }
1259 } else {
1260 for (const auto &it : std::as_const(m_dynamicTextureMaps)) {
1261 if (auto tex = it->texture())
1262 QQuick3DObjectPrivate::derefSceneManager(tex);
1263 }
1264 }
1265 m_shaderResources.updateSceneManager(sceneManager);
1266}
1267
1268void QQuick3DEffect::itemChange(QQuick3DObject::ItemChange change, const QQuick3DObject::ItemChangeData &value)
1269{
1270 if (change == QQuick3DObject::ItemSceneChange)
1271 updateSceneManager(value.sceneManager);
1272}
1273
1274void QQuick3DEffect::qmlAppendPass(QQmlListProperty<QQuick3DShaderUtilsRenderPass> *list, QQuick3DShaderUtilsRenderPass *pass)
1275{
1276 if (!pass)
1277 return;
1278
1279 QQuick3DEffect *that = qobject_cast<QQuick3DEffect *>(list->object);
1280 that->m_passes.push_back(pass);
1281
1282 connect(pass, &QQuick3DShaderUtilsRenderPass::changed, that, &QQuick3DEffect::onPassDirty);
1283 that->effectChainDirty();
1284}
1285
1286QQuick3DShaderUtilsRenderPass *QQuick3DEffect::qmlPassAt(QQmlListProperty<QQuick3DShaderUtilsRenderPass> *list, qsizetype index)
1287{
1288 QQuick3DEffect *that = qobject_cast<QQuick3DEffect *>(list->object);
1289 return that->m_passes.at(index);
1290}
1291
1292qsizetype QQuick3DEffect::qmlPassCount(QQmlListProperty<QQuick3DShaderUtilsRenderPass> *list)
1293{
1294 QQuick3DEffect *that = qobject_cast<QQuick3DEffect *>(list->object);
1295 return that->m_passes.size();
1296}
1297
1298void QQuick3DEffect::qmlPassClear(QQmlListProperty<QQuick3DShaderUtilsRenderPass> *list)
1299{
1300 QQuick3DEffect *that = qobject_cast<QQuick3DEffect *>(list->object);
1301
1302 for (QQuick3DShaderUtilsRenderPass *pass : std::as_const(that->m_passes))
1303 pass->disconnect(that);
1304
1305 that->m_passes.clear();
1306 that->effectChainDirty();
1307}
1308
1309void QQuick3DEffect::setDynamicTextureMap(QQuick3DShaderUtilsTextureInput *textureMap)
1310{
1311 // There can only be one texture input per property, as the texture input is a combination
1312 // of the texture used and the uniform name!
1313 auto it = m_dynamicTextureMaps.constFind(textureMap);
1314
1315 if (it == m_dynamicTextureMaps.constEnd()) {
1316 // Track the object, if it's destroyed we need to remove it from our table.
1317 connect(textureMap, &QQuick3DShaderUtilsTextureInput::destroyed, this, [this, textureMap]() {
1318 auto it = m_dynamicTextureMaps.constFind(textureMap);
1319 if (it != m_dynamicTextureMaps.constEnd())
1320 m_dynamicTextureMaps.erase(it);
1321 });
1322 m_dynamicTextureMaps.insert(textureMap);
1323
1324 update();
1325 }
1326}
1327
1328QT_END_NAMESPACE
Combined button and popup list for selecting options.
static void resetShaderDependentEffectFlags(QSSGRenderEffect *effectNode)
static const char * default_effect_fragment_shader
static const char * default_effect_vertex_shader
static void insertVertexMainArgs(QByteArray &snippet)
static void accumulateEffectFlagsFromShader(QSSGRenderEffect *effectNode, const QSSGCustomShaderMetaData &meta)