Skip to content

Commit d49dfae

Browse files
committed
Add example to advanced_postprocessing.rst
Adds a complete example. Also removes an unneeded varying.
1 parent b54f912 commit d49dfae

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

tutorials/shaders/advanced_postprocessing.rst

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -137,22 +137,51 @@ the distance to the point.
137137
Because the camera is facing the negative ``z`` direction, the position will have a negative ``z`` value.
138138
In order to get a usable depth value, we have to negate ``view.z``.
139139

140-
The world position can be constructed from the depth buffer using the following code. Note
141-
that the ``INV_VIEW_MATRIX`` is needed to transform the position from view space into world space, so
142-
it needs to be passed to the fragment shader with a varying.
140+
The world position can be constructed from the depth buffer using the following code, using the
141+
``INV_VIEW_MATRIX`` to transform the position from view space into world space.
143142

144143
.. code-block:: glsl
145144
146-
varying mat4 CAMERA;
145+
void fragment() {
146+
...
147+
vec4 world = INV_VIEW_MATRIX * INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
148+
vec3 world_position = world.xyz / world.w;
149+
}
150+
151+
Example shader
152+
--------------
153+
154+
Once we add a line to output to ``ALBEDO``, we have a complete shader that looks something like this.
155+
This shader lets you visualize the linear depth or world space coordinates, depending on which
156+
line is commented out.
157+
158+
.. code-block:: glsl
159+
160+
shader_type spatial;
161+
// Prevent the quad from being affected by lighting and fog. This also improves performance.
162+
render_mode unshaded, fog_disabled;
163+
164+
uniform sampler2D depth_texture : source_color, hint_depth_texture;
147165
148166
void vertex() {
149-
CAMERA = INV_VIEW_MATRIX;
167+
POSITION = vec4(VERTEX.xy, 1.0, 1.0);
150168
}
151169
152170
void fragment() {
153-
...
154-
vec4 world = CAMERA * INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
171+
float depth = texture(depth_texture, SCREEN_UV).x;
172+
vec3 ndc = vec3(SCREEN_UV * 2.0 - 1.0, depth);
173+
vec4 view = INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
174+
view.xyz /= view.w;
175+
float linear_depth = -view.z;
176+
177+
vec4 world = INV_VIEW_MATRIX * INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
155178
vec3 world_position = world.xyz / world.w;
179+
180+
// Visualize linear depth
181+
ALBEDO.rgb = vec3(fract(linear_depth));
182+
183+
// Visualize world coordinates
184+
//ALBEDO.rgb = fract(world_position).xyz;
156185
}
157186
158187
An optimization

0 commit comments

Comments
 (0)