st/mesa: simplify st_generate_mipmap()
[mesa.git] / src / mesa / drivers / common / meta_blit.c
1 /*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 2009 VMware, Inc. All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 * OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25 #include "main/glheader.h"
26 #include "main/mtypes.h"
27 #include "main/imports.h"
28 #include "main/arbprogram.h"
29 #include "main/arrayobj.h"
30 #include "main/blend.h"
31 #include "main/condrender.h"
32 #include "main/depth.h"
33 #include "main/enable.h"
34 #include "main/enums.h"
35 #include "main/fbobject.h"
36 #include "main/image.h"
37 #include "main/macros.h"
38 #include "main/matrix.h"
39 #include "main/multisample.h"
40 #include "main/objectlabel.h"
41 #include "main/readpix.h"
42 #include "main/scissor.h"
43 #include "main/shaderapi.h"
44 #include "main/texobj.h"
45 #include "main/texenv.h"
46 #include "main/teximage.h"
47 #include "main/texparam.h"
48 #include "main/uniforms.h"
49 #include "main/varray.h"
50 #include "main/viewport.h"
51 #include "swrast/swrast.h"
52 #include "drivers/common/meta.h"
53 #include "util/ralloc.h"
54
55 /** Return offset in bytes of the field within a vertex struct */
56 #define OFFSET(FIELD) ((void *) offsetof(struct vertex, FIELD))
57
58 static void
59 setup_glsl_msaa_blit_scaled_shader(struct gl_context *ctx,
60 struct blit_state *blit,
61 struct gl_renderbuffer *src_rb,
62 GLenum target, GLenum filter)
63 {
64 GLint loc_src_width, loc_src_height;
65 int i, samples;
66 int shader_offset = 0;
67 void *mem_ctx = ralloc_context(NULL);
68 char *fs_source;
69 char *name, *sample_number;
70 const uint8_t *sample_map;
71 char *sample_map_str = rzalloc_size(mem_ctx, 1);
72 char *sample_map_expr = rzalloc_size(mem_ctx, 1);
73 char *texel_fetch_macro = rzalloc_size(mem_ctx, 1);
74 const char *sampler_array_suffix = "";
75 float x_scale, y_scale;
76 enum blit_msaa_shader shader_index;
77
78 assert(src_rb);
79 samples = MAX2(src_rb->NumSamples, 1);
80
81 if (samples == 16)
82 x_scale = 4.0;
83 else
84 x_scale = 2.0;
85 y_scale = samples / x_scale;
86
87 /* We expect only power of 2 samples in source multisample buffer. */
88 assert(samples > 0 && _mesa_is_pow_two(samples));
89 while (samples >> (shader_offset + 1)) {
90 shader_offset++;
91 }
92 /* Update the assert if we plan to support more than 16X MSAA. */
93 assert(shader_offset > 0 && shader_offset <= 4);
94
95 assert(target == GL_TEXTURE_2D_MULTISAMPLE ||
96 target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY);
97
98 shader_index = BLIT_2X_MSAA_SHADER_2D_MULTISAMPLE_SCALED_RESOLVE +
99 shader_offset - 1;
100
101 if (target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) {
102 shader_index += BLIT_2X_MSAA_SHADER_2D_MULTISAMPLE_ARRAY_SCALED_RESOLVE -
103 BLIT_2X_MSAA_SHADER_2D_MULTISAMPLE_SCALED_RESOLVE;
104 sampler_array_suffix = "Array";
105 }
106
107 if (blit->msaa_shaders[shader_index]) {
108 _mesa_meta_use_program(ctx, blit->msaa_shaders[shader_index]);
109 /* Update the uniform values. */
110 loc_src_width =
111 _mesa_program_resource_location(blit->msaa_shaders[shader_index], GL_UNIFORM, "src_width");
112 loc_src_height =
113 _mesa_program_resource_location(blit->msaa_shaders[shader_index], GL_UNIFORM, "src_height");
114 _mesa_Uniform1f(loc_src_width, src_rb->Width);
115 _mesa_Uniform1f(loc_src_height, src_rb->Height);
116 return;
117 }
118
119 name = ralloc_asprintf(mem_ctx, "vec4 MSAA scaled resolve");
120
121 /* Below switch is used to setup the shader expression, which computes
122 * sample index and map it to to a sample number on hardware.
123 */
124 switch(samples) {
125 case 2:
126 sample_number = "sample_map[int(2 * fract(coord.x))]";
127 sample_map = ctx->Const.SampleMap2x;
128 break;
129 case 4:
130 sample_number = "sample_map[int(2 * fract(coord.x) + 4 * fract(coord.y))]";
131 sample_map = ctx->Const.SampleMap4x;
132 break;
133 case 8:
134 sample_number = "sample_map[int(2 * fract(coord.x) + 8 * fract(coord.y))]";
135 sample_map = ctx->Const.SampleMap8x;
136 break;
137 case 16:
138 sample_number = "sample_map[int(4 * fract(coord.x) + 16 * fract(coord.y))]";
139 sample_map = ctx->Const.SampleMap16x;
140 break;
141 default:
142 sample_number = NULL;
143 sample_map = NULL;
144 _mesa_problem(ctx, "Unsupported sample count %d\n", samples);
145 unreachable("Unsupported sample count");
146 }
147
148 /* Create sample map string. */
149 for (i = 0 ; i < samples - 1; i++) {
150 ralloc_asprintf_append(&sample_map_str, "%d, ", sample_map[i]);
151 }
152 ralloc_asprintf_append(&sample_map_str, "%d", sample_map[samples - 1]);
153
154 /* Create sample map expression using above string. */
155 ralloc_asprintf_append(&sample_map_expr,
156 " const int sample_map[%d] = int[%d](%s);\n",
157 samples, samples, sample_map_str);
158
159 if (target == GL_TEXTURE_2D_MULTISAMPLE) {
160 ralloc_asprintf_append(&texel_fetch_macro,
161 "#define TEXEL_FETCH(coord) texelFetch(texSampler, ivec2(coord), %s);\n",
162 sample_number);
163 } else {
164 ralloc_asprintf_append(&texel_fetch_macro,
165 "#define TEXEL_FETCH(coord) texelFetch(texSampler, ivec3(coord, layer), %s);\n",
166 sample_number);
167 }
168
169 static const char vs_source[] =
170 "#version 130\n"
171 "#extension GL_ARB_explicit_attrib_location: enable\n"
172 "layout(location = 0) in vec2 position;\n"
173 "layout(location = 1) in vec3 textureCoords;\n"
174 "out vec2 texCoords;\n"
175 "flat out int layer;\n"
176 "void main()\n"
177 "{\n"
178 " texCoords = textureCoords.xy;\n"
179 " layer = int(textureCoords.z);\n"
180 " gl_Position = vec4(position, 0.0, 1.0);\n"
181 "}\n"
182 ;
183
184 fs_source = ralloc_asprintf(mem_ctx,
185 "#version 130\n"
186 "#extension GL_ARB_texture_multisample : enable\n"
187 "uniform sampler2DMS%s texSampler;\n"
188 "uniform float src_width, src_height;\n"
189 "in vec2 texCoords;\n"
190 "flat in int layer;\n"
191 "out vec4 out_color;\n"
192 "\n"
193 "void main()\n"
194 "{\n"
195 "%s"
196 " vec2 interp;\n"
197 " const vec2 scale = vec2(%ff, %ff);\n"
198 " const vec2 scale_inv = vec2(%ff, %ff);\n"
199 " const vec2 s_0_offset = vec2(%ff, %ff);\n"
200 " vec2 s_0_coord, s_1_coord, s_2_coord, s_3_coord;\n"
201 " vec4 s_0_color, s_1_color, s_2_color, s_3_color;\n"
202 " vec4 x_0_color, x_1_color;\n"
203 " vec2 tex_coord = texCoords - s_0_offset;\n"
204 "\n"
205 " tex_coord *= scale;\n"
206 " tex_coord.x = clamp(tex_coord.x, 0.0f, scale.x * src_width - 1.0f);\n"
207 " tex_coord.y = clamp(tex_coord.y, 0.0f, scale.y * src_height - 1.0f);\n"
208 " interp = fract(tex_coord);\n"
209 " tex_coord = ivec2(tex_coord) * scale_inv;\n"
210 "\n"
211 " /* Compute the sample coordinates used for filtering. */\n"
212 " s_0_coord = tex_coord;\n"
213 " s_1_coord = tex_coord + vec2(scale_inv.x, 0.0f);\n"
214 " s_2_coord = tex_coord + vec2(0.0f, scale_inv.y);\n"
215 " s_3_coord = tex_coord + vec2(scale_inv.x, scale_inv.y);\n"
216 "\n"
217 " /* Fetch sample color values. */\n"
218 "%s"
219 " s_0_color = TEXEL_FETCH(s_0_coord)\n"
220 " s_1_color = TEXEL_FETCH(s_1_coord)\n"
221 " s_2_color = TEXEL_FETCH(s_2_coord)\n"
222 " s_3_color = TEXEL_FETCH(s_3_coord)\n"
223 "#undef TEXEL_FETCH\n"
224 "\n"
225 " /* Do bilinear filtering on sample colors. */\n"
226 " x_0_color = mix(s_0_color, s_1_color, interp.x);\n"
227 " x_1_color = mix(s_2_color, s_3_color, interp.x);\n"
228 " out_color = mix(x_0_color, x_1_color, interp.y);\n"
229 "}\n",
230 sampler_array_suffix,
231 sample_map_expr,
232 x_scale, y_scale,
233 1.0f / x_scale, 1.0f / y_scale,
234 0.5f / x_scale, 0.5f / y_scale,
235 texel_fetch_macro);
236
237 _mesa_meta_compile_and_link_program(ctx, vs_source, fs_source, name,
238 &blit->msaa_shaders[shader_index]);
239 loc_src_width =
240 _mesa_program_resource_location(blit->msaa_shaders[shader_index], GL_UNIFORM, "src_width");
241 loc_src_height =
242 _mesa_program_resource_location(blit->msaa_shaders[shader_index], GL_UNIFORM, "src_height");
243 _mesa_Uniform1f(loc_src_width, src_rb->Width);
244 _mesa_Uniform1f(loc_src_height, src_rb->Height);
245
246 ralloc_free(mem_ctx);
247 }
248
249 static void
250 setup_glsl_msaa_blit_shader(struct gl_context *ctx,
251 struct blit_state *blit,
252 const struct gl_framebuffer *drawFb,
253 struct gl_renderbuffer *src_rb,
254 GLenum target)
255 {
256 const char *vs_source;
257 char *fs_source;
258 void *mem_ctx;
259 enum blit_msaa_shader shader_index;
260 bool dst_is_msaa = false;
261 GLenum src_datatype;
262 const char *vec4_prefix;
263 const char *sampler_array_suffix = "";
264 char *name;
265 const char *texcoord_type = "vec2";
266 int samples;
267 int shader_offset = 0;
268
269 if (src_rb) {
270 samples = MAX2(src_rb->NumSamples, 1);
271 src_datatype = _mesa_get_format_datatype(src_rb->Format);
272 } else {
273 /* depth-or-color glCopyTexImage fallback path that passes a NULL rb and
274 * doesn't handle integer.
275 */
276 samples = 1;
277 src_datatype = GL_UNSIGNED_NORMALIZED;
278 }
279
280 /* We expect only power of 2 samples in source multisample buffer. */
281 assert(samples > 0 && _mesa_is_pow_two(samples));
282 while (samples >> (shader_offset + 1)) {
283 shader_offset++;
284 }
285 /* Update the assert if we plan to support more than 16X MSAA. */
286 assert(shader_offset >= 0 && shader_offset <= 4);
287
288 if (drawFb->Visual.samples > 1) {
289 /* If you're calling meta_BlitFramebuffer with the destination
290 * multisampled, this is the only path that will work -- swrast and
291 * CopyTexImage won't work on it either.
292 */
293 assert(ctx->Extensions.ARB_sample_shading);
294
295 dst_is_msaa = true;
296
297 /* We need shader invocation per sample, not per pixel */
298 _mesa_set_enable(ctx, GL_MULTISAMPLE, GL_TRUE);
299 _mesa_set_enable(ctx, GL_SAMPLE_SHADING, GL_TRUE);
300 _mesa_MinSampleShading(1.0);
301 }
302
303 switch (target) {
304 case GL_TEXTURE_2D_MULTISAMPLE:
305 case GL_TEXTURE_2D_MULTISAMPLE_ARRAY:
306 if (src_rb && (src_rb->_BaseFormat == GL_DEPTH_COMPONENT ||
307 src_rb->_BaseFormat == GL_DEPTH_STENCIL)) {
308 if (dst_is_msaa)
309 shader_index = BLIT_MSAA_SHADER_2D_MULTISAMPLE_DEPTH_COPY;
310 else
311 shader_index = BLIT_MSAA_SHADER_2D_MULTISAMPLE_DEPTH_RESOLVE;
312 } else {
313 if (dst_is_msaa)
314 shader_index = BLIT_MSAA_SHADER_2D_MULTISAMPLE_COPY;
315 else {
316 shader_index = BLIT_1X_MSAA_SHADER_2D_MULTISAMPLE_RESOLVE +
317 shader_offset;
318 }
319 }
320
321 if (target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY) {
322 shader_index += (BLIT_1X_MSAA_SHADER_2D_MULTISAMPLE_ARRAY_RESOLVE -
323 BLIT_1X_MSAA_SHADER_2D_MULTISAMPLE_RESOLVE);
324 sampler_array_suffix = "Array";
325 texcoord_type = "vec3";
326 }
327 break;
328 default:
329 _mesa_problem(ctx, "Unknown texture target %s\n",
330 _mesa_enum_to_string(target));
331 shader_index = BLIT_2X_MSAA_SHADER_2D_MULTISAMPLE_RESOLVE;
332 }
333
334 /* We rely on the enum being sorted this way. */
335 STATIC_ASSERT(BLIT_1X_MSAA_SHADER_2D_MULTISAMPLE_RESOLVE_INT ==
336 BLIT_1X_MSAA_SHADER_2D_MULTISAMPLE_RESOLVE + 5);
337 STATIC_ASSERT(BLIT_1X_MSAA_SHADER_2D_MULTISAMPLE_RESOLVE_UINT ==
338 BLIT_1X_MSAA_SHADER_2D_MULTISAMPLE_RESOLVE + 10);
339 if (src_datatype == GL_INT) {
340 shader_index += 5;
341 vec4_prefix = "i";
342 } else if (src_datatype == GL_UNSIGNED_INT) {
343 shader_index += 10;
344 vec4_prefix = "u";
345 } else {
346 vec4_prefix = "";
347 }
348
349 if (blit->msaa_shaders[shader_index]) {
350 _mesa_meta_use_program(ctx, blit->msaa_shaders[shader_index]);
351 return;
352 }
353
354 mem_ctx = ralloc_context(NULL);
355
356 if (shader_index == BLIT_MSAA_SHADER_2D_MULTISAMPLE_DEPTH_RESOLVE ||
357 shader_index == BLIT_MSAA_SHADER_2D_MULTISAMPLE_ARRAY_DEPTH_RESOLVE ||
358 shader_index == BLIT_MSAA_SHADER_2D_MULTISAMPLE_ARRAY_DEPTH_COPY ||
359 shader_index == BLIT_MSAA_SHADER_2D_MULTISAMPLE_DEPTH_COPY) {
360 char *sample_index;
361 const char *tex_coords = "texCoords";
362
363 if (dst_is_msaa) {
364 sample_index = "gl_SampleID";
365 name = "depth MSAA copy";
366
367 if (ctx->Extensions.ARB_gpu_shader5 && samples >= 16) {
368 /* See comment below for the color copy */
369 tex_coords = "interpolateAtOffset(texCoords, vec2(0.0))";
370 }
371 } else {
372 /* From the GL 4.3 spec:
373 *
374 * "If there is a multisample buffer (the value of SAMPLE_BUFFERS
375 * is one), then values are obtained from the depth samples in
376 * this buffer. It is recommended that the depth value of the
377 * centermost sample be used, though implementations may choose
378 * any function of the depth sample values at each pixel.
379 *
380 * We're slacking and instead of choosing centermost, we've got 0.
381 */
382 sample_index = "0";
383 name = "depth MSAA resolve";
384 }
385
386 vs_source = ralloc_asprintf(mem_ctx,
387 "#version 130\n"
388 "#extension GL_ARB_explicit_attrib_location: enable\n"
389 "layout(location = 0) in vec2 position;\n"
390 "layout(location = 1) in %s textureCoords;\n"
391 "out %s texCoords;\n"
392 "void main()\n"
393 "{\n"
394 " texCoords = textureCoords;\n"
395 " gl_Position = vec4(position, 0.0, 1.0);\n"
396 "}\n",
397 texcoord_type,
398 texcoord_type);
399 fs_source = ralloc_asprintf(mem_ctx,
400 "#version 130\n"
401 "#extension GL_ARB_texture_multisample : enable\n"
402 "#extension GL_ARB_sample_shading : enable\n"
403 "#extension GL_ARB_gpu_shader5 : enable\n"
404 "uniform sampler2DMS%s texSampler;\n"
405 "in %s texCoords;\n"
406 "out vec4 out_color;\n"
407 "\n"
408 "void main()\n"
409 "{\n"
410 " gl_FragDepth = texelFetch(texSampler, i%s(%s), %s).r;\n"
411 "}\n",
412 sampler_array_suffix,
413 texcoord_type,
414 texcoord_type,
415 tex_coords,
416 sample_index);
417 } else {
418 /* You can create 2D_MULTISAMPLE textures with 0 sample count (meaning 1
419 * sample). Yes, this is ridiculous.
420 */
421 char *sample_resolve;
422 const char *merge_function;
423 name = ralloc_asprintf(mem_ctx, "%svec4 MSAA %s",
424 vec4_prefix,
425 dst_is_msaa ? "copy" : "resolve");
426
427 if (dst_is_msaa) {
428 const char *tex_coords;
429
430 if (ctx->Extensions.ARB_gpu_shader5 && samples >= 16) {
431 /* If interpolateAtOffset is available then it will be used to
432 * force the interpolation to the center. This is required at
433 * least on Intel hardware because it is possible to have a sample
434 * position on the 0 x or y axis which means it will lie exactly
435 * on the pixel boundary. If we let the hardware interpolate the
436 * coordinates at one of these positions then it is possible for
437 * it to jump to a neighboring texel when converting to ints due
438 * to rounding errors. This is only done for >= 16x MSAA because
439 * it probably has some overhead. It is more likely that some
440 * hardware will use one of these problematic positions at 16x
441 * MSAA because in that case in D3D they are defined to be at
442 * these positions.
443 */
444 tex_coords = "interpolateAtOffset(texCoords, vec2(0.0))";
445 } else {
446 tex_coords = "texCoords";
447 }
448
449 sample_resolve =
450 ralloc_asprintf(mem_ctx,
451 " out_color = texelFetch(texSampler, "
452 "i%s(%s), gl_SampleID);",
453 texcoord_type, tex_coords);
454
455 merge_function = "";
456 } else {
457 int i;
458 int step;
459
460 if (src_datatype == GL_INT || src_datatype == GL_UNSIGNED_INT) {
461 merge_function =
462 "gvec4 merge(gvec4 a, gvec4 b) { return (a >> gvec4(1)) + (b >> gvec4(1)) + (a & b & gvec4(1)); }\n";
463 } else {
464 /* The divide will happen at the end for floats. */
465 merge_function =
466 "vec4 merge(vec4 a, vec4 b) { return (a + b); }\n";
467 }
468
469 /* We're assuming power of two samples for this resolution procedure.
470 *
471 * To avoid losing any floating point precision if the samples all
472 * happen to have the same value, we merge pairs of values at a time
473 * (so the floating point exponent just gets increased), rather than
474 * doing a naive sum and dividing.
475 */
476 assert(_mesa_is_pow_two(samples));
477 /* Fetch each individual sample. */
478 sample_resolve = rzalloc_size(mem_ctx, 1);
479 for (i = 0; i < samples; i++) {
480 ralloc_asprintf_append(&sample_resolve,
481 " gvec4 sample_1_%d = texelFetch(texSampler, i%s(texCoords), %d);\n",
482 i, texcoord_type, i);
483 }
484 /* Now, merge each pair of samples, then merge each pair of those,
485 * etc.
486 */
487 for (step = 2; step <= samples; step *= 2) {
488 for (i = 0; i < samples; i += step) {
489 ralloc_asprintf_append(&sample_resolve,
490 " gvec4 sample_%d_%d = merge(sample_%d_%d, sample_%d_%d);\n",
491 step, i,
492 step / 2, i,
493 step / 2, i + step / 2);
494 }
495 }
496
497 /* Scale the final result. */
498 if (src_datatype == GL_UNSIGNED_INT || src_datatype == GL_INT) {
499 ralloc_asprintf_append(&sample_resolve,
500 " out_color = sample_%d_0;\n",
501 samples);
502 } else {
503 ralloc_asprintf_append(&sample_resolve,
504 " gl_FragColor = sample_%d_0 / %f;\n",
505 samples, (float)samples);
506 }
507 }
508
509 vs_source = ralloc_asprintf(mem_ctx,
510 "#version 130\n"
511 "#extension GL_ARB_explicit_attrib_location: enable\n"
512 "layout(location = 0) in vec2 position;\n"
513 "layout(location = 1) in %s textureCoords;\n"
514 "out %s texCoords;\n"
515 "void main()\n"
516 "{\n"
517 " texCoords = textureCoords;\n"
518 " gl_Position = vec4(position, 0.0, 1.0);\n"
519 "}\n",
520 texcoord_type,
521 texcoord_type);
522 fs_source = ralloc_asprintf(mem_ctx,
523 "#version 130\n"
524 "#extension GL_ARB_texture_multisample : enable\n"
525 "#extension GL_ARB_sample_shading : enable\n"
526 "#extension GL_ARB_gpu_shader5 : enable\n"
527 "#define gvec4 %svec4\n"
528 "uniform %ssampler2DMS%s texSampler;\n"
529 "in %s texCoords;\n"
530 "out gvec4 out_color;\n"
531 "\n"
532 "%s" /* merge_function */
533 "void main()\n"
534 "{\n"
535 "%s\n" /* sample_resolve */
536 "}\n",
537 vec4_prefix,
538 vec4_prefix,
539 sampler_array_suffix,
540 texcoord_type,
541 merge_function,
542 sample_resolve);
543 }
544
545 _mesa_meta_compile_and_link_program(ctx, vs_source, fs_source, name,
546 &blit->msaa_shaders[shader_index]);
547
548 ralloc_free(mem_ctx);
549 }
550
551 static void
552 setup_glsl_blit_framebuffer(struct gl_context *ctx,
553 struct blit_state *blit,
554 const struct gl_framebuffer *drawFb,
555 struct gl_renderbuffer *src_rb,
556 GLenum target, GLenum filter,
557 bool is_scaled_blit,
558 bool do_depth)
559 {
560 unsigned texcoord_size;
561 bool is_target_multisample = target == GL_TEXTURE_2D_MULTISAMPLE ||
562 target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
563 bool is_filter_scaled_resolve = filter == GL_SCALED_RESOLVE_FASTEST_EXT ||
564 filter == GL_SCALED_RESOLVE_NICEST_EXT;
565
566 /* target = GL_TEXTURE_RECTANGLE is not supported in GLES 3.0 */
567 assert(_mesa_is_desktop_gl(ctx) || target == GL_TEXTURE_2D);
568
569 texcoord_size = 2 + (src_rb->Depth > 1 ? 1 : 0);
570
571 _mesa_meta_setup_vertex_objects(ctx, &blit->VAO, &blit->buf_obj, true,
572 2, texcoord_size, 0);
573
574 if (is_target_multisample && is_filter_scaled_resolve && is_scaled_blit) {
575 setup_glsl_msaa_blit_scaled_shader(ctx, blit, src_rb, target, filter);
576 } else if (is_target_multisample) {
577 setup_glsl_msaa_blit_shader(ctx, blit, drawFb, src_rb, target);
578 } else {
579 _mesa_meta_setup_blit_shader(ctx, target, do_depth,
580 do_depth ? &blit->shaders_with_depth
581 : &blit->shaders_without_depth);
582 }
583 }
584
585 /**
586 * Try to do a color or depth glBlitFramebuffer using texturing.
587 *
588 * We can do this when the src renderbuffer is actually a texture, or when the
589 * driver exposes BindRenderbufferTexImage().
590 */
591 static bool
592 blitframebuffer_texture(struct gl_context *ctx,
593 const struct gl_framebuffer *readFb,
594 const struct gl_framebuffer *drawFb,
595 GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
596 GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
597 GLenum filter, GLint flipX, GLint flipY,
598 GLboolean glsl_version, GLboolean do_depth)
599 {
600 struct save_state *save = &ctx->Meta->Save[ctx->Meta->SaveStackDepth - 1];
601 int att_index = do_depth ? BUFFER_DEPTH : readFb->_ColorReadBufferIndex;
602 const struct gl_renderbuffer_attachment *readAtt =
603 &readFb->Attachment[att_index];
604 struct blit_state *blit = &ctx->Meta->Blit;
605 struct fb_tex_blit_state fb_tex_blit;
606 const GLint dstX = MIN2(dstX0, dstX1);
607 const GLint dstY = MIN2(dstY0, dstY1);
608 const GLint dstW = abs(dstX1 - dstX0);
609 const GLint dstH = abs(dstY1 - dstY0);
610 const int srcW = abs(srcX1 - srcX0);
611 const int srcH = abs(srcY1 - srcY0);
612 bool scaled_blit = false;
613 struct gl_texture_object *texObj;
614 GLuint srcLevel;
615 GLenum target;
616 struct gl_renderbuffer *rb = readAtt->Renderbuffer;
617 struct temp_texture *meta_temp_texture;
618
619 if (rb->NumSamples && !ctx->Extensions.ARB_texture_multisample)
620 return false;
621
622 _mesa_meta_fb_tex_blit_begin(ctx, &fb_tex_blit);
623
624 if (readAtt->Texture &&
625 (readAtt->Texture->Target == GL_TEXTURE_2D ||
626 readAtt->Texture->Target == GL_TEXTURE_RECTANGLE ||
627 readAtt->Texture->Target == GL_TEXTURE_2D_MULTISAMPLE ||
628 readAtt->Texture->Target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY)) {
629 /* If there's a texture attached of a type we can handle, then just use
630 * it directly.
631 */
632 srcLevel = readAtt->TextureLevel;
633 texObj = readAtt->Texture;
634 target = texObj->Target;
635 } else if (!readAtt->Texture && ctx->Driver.BindRenderbufferTexImage) {
636 if (!_mesa_meta_bind_rb_as_tex_image(ctx, rb, &fb_tex_blit.tempTex,
637 &texObj, &target))
638 return false;
639
640 srcLevel = 0;
641 if (_mesa_is_winsys_fbo(readFb)) {
642 GLint temp = srcY0;
643 srcY0 = rb->Height - srcY1;
644 srcY1 = rb->Height - temp;
645 flipY = -flipY;
646 }
647 } else {
648 GLenum tex_base_format;
649 /* Fall back to doing a CopyTexSubImage to get the destination
650 * renderbuffer into a texture.
651 */
652 if (ctx->Meta->Blit.no_ctsi_fallback)
653 return false;
654
655 if (rb->NumSamples > 1)
656 return false;
657
658 if (do_depth) {
659 meta_temp_texture = _mesa_meta_get_temp_depth_texture(ctx);
660 tex_base_format = GL_DEPTH_COMPONENT;
661 } else {
662 meta_temp_texture = _mesa_meta_get_temp_texture(ctx);
663 tex_base_format =
664 _mesa_base_tex_format(ctx, rb->InternalFormat);
665 }
666
667 srcLevel = 0;
668 target = meta_temp_texture->Target;
669 texObj = _mesa_lookup_texture(ctx, meta_temp_texture->TexObj);
670 if (texObj == NULL) {
671 return false;
672 }
673
674 _mesa_meta_setup_copypix_texture(ctx, meta_temp_texture,
675 srcX0, srcY0,
676 srcW, srcH,
677 tex_base_format,
678 filter);
679
680
681 srcX0 = 0;
682 srcY0 = 0;
683 srcX1 = srcW;
684 srcY1 = srcH;
685 }
686
687 fb_tex_blit.baseLevelSave = texObj->BaseLevel;
688 fb_tex_blit.maxLevelSave = texObj->MaxLevel;
689 fb_tex_blit.stencilSamplingSave = texObj->StencilSampling;
690
691 scaled_blit = dstW != srcW || dstH != srcH;
692
693 if (glsl_version) {
694 setup_glsl_blit_framebuffer(ctx, blit, drawFb, rb, target, filter, scaled_blit,
695 do_depth);
696 }
697 else {
698 _mesa_meta_setup_ff_tnl_for_blit(ctx,
699 &ctx->Meta->Blit.VAO,
700 &ctx->Meta->Blit.buf_obj,
701 2);
702 }
703
704 /*
705 printf("Blit from texture!\n");
706 printf(" srcAtt %p dstAtt %p\n", readAtt, drawAtt);
707 printf(" srcTex %p dstText %p\n", texObj, drawAtt->Texture);
708 */
709
710 fb_tex_blit.samp_obj = _mesa_meta_setup_sampler(ctx, texObj, target, filter,
711 srcLevel);
712
713 /* For desktop GL, we do our blits with no net sRGB decode or encode.
714 *
715 * However, if both the src and dst can be srgb decode/encoded, enable them
716 * so that we do any blending (from scaling or from MSAA resolves) in the
717 * right colorspace.
718 *
719 * Our choice of not doing any net encode/decode is from the GL 3.0
720 * specification:
721 *
722 * "Blit operations bypass the fragment pipeline. The only fragment
723 * operations which affect a blit are the pixel ownership test and the
724 * scissor test."
725 *
726 * The GL 4.4 specification disagrees and says that the sRGB part of the
727 * fragment pipeline applies, but this was found to break applications
728 * (such as Left 4 Dead 2).
729 *
730 * However, for ES 3.0, we follow the specification and perform sRGB
731 * decoding and encoding. The specification has always been clear in
732 * the ES world, and hasn't changed over time.
733 */
734 if (ctx->Extensions.EXT_texture_sRGB_decode) {
735 bool src_srgb = _mesa_get_format_color_encoding(rb->Format) == GL_SRGB;
736 if (save->API == API_OPENGLES2 && ctx->Version >= 30) {
737 /* From the ES 3.0.4 specification, page 198:
738 * "When values are taken from the read buffer, if the value of
739 * FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING for the framebuffer
740 * attachment corresponding to the read buffer is SRGB (see section
741 * 6.1.13), the red, green, and blue components are converted from
742 * the non-linear sRGB color space according to equation 3.24.
743 *
744 * When values are written to the draw buffers, blit operations
745 * bypass the fragment pipeline. The only fragment operations which
746 * affect a blit are the pixel ownership test, the scissor test,
747 * and sRGB conversion (see section 4.1.8)."
748 */
749 _mesa_set_sampler_srgb_decode(ctx, fb_tex_blit.samp_obj,
750 src_srgb ? GL_DECODE_EXT
751 : GL_SKIP_DECODE_EXT);
752 _mesa_set_framebuffer_srgb(ctx, drawFb->Visual.sRGBCapable);
753 } else {
754 if (src_srgb && drawFb->Visual.sRGBCapable) {
755 _mesa_set_sampler_srgb_decode(ctx, fb_tex_blit.samp_obj,
756 GL_DECODE_EXT);
757 _mesa_set_framebuffer_srgb(ctx, GL_TRUE);
758 } else {
759 _mesa_set_sampler_srgb_decode(ctx, fb_tex_blit.samp_obj,
760 GL_SKIP_DECODE_EXT);
761 /* set_framebuffer_srgb was set by _mesa_meta_begin(). */
762 }
763 }
764 }
765
766 if (!glsl_version) {
767 _mesa_TexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
768 _mesa_set_enable(ctx, target, GL_TRUE);
769 }
770
771 /* Prepare vertex data (the VBO was previously created and bound) */
772 {
773 struct vertex verts[4];
774 GLfloat s0, t0, s1, t1;
775
776 if (target == GL_TEXTURE_2D) {
777 const struct gl_texture_image *texImage
778 = _mesa_select_tex_image(texObj, target, srcLevel);
779 s0 = srcX0 / (float) texImage->Width;
780 s1 = srcX1 / (float) texImage->Width;
781 t0 = srcY0 / (float) texImage->Height;
782 t1 = srcY1 / (float) texImage->Height;
783 }
784 else {
785 assert(target == GL_TEXTURE_RECTANGLE_ARB ||
786 target == GL_TEXTURE_2D_MULTISAMPLE ||
787 target == GL_TEXTURE_2D_MULTISAMPLE_ARRAY);
788 s0 = (float) srcX0;
789 s1 = (float) srcX1;
790 t0 = (float) srcY0;
791 t1 = (float) srcY1;
792 }
793
794 /* Silence valgrind warnings about reading uninitialized stack. */
795 memset(verts, 0, sizeof(verts));
796
797 /* setup vertex positions */
798 verts[0].x = -1.0F * flipX;
799 verts[0].y = -1.0F * flipY;
800 verts[1].x = 1.0F * flipX;
801 verts[1].y = -1.0F * flipY;
802 verts[2].x = 1.0F * flipX;
803 verts[2].y = 1.0F * flipY;
804 verts[3].x = -1.0F * flipX;
805 verts[3].y = 1.0F * flipY;
806
807 verts[0].tex[0] = s0;
808 verts[0].tex[1] = t0;
809 verts[0].tex[2] = readAtt->Zoffset;
810 verts[1].tex[0] = s1;
811 verts[1].tex[1] = t0;
812 verts[1].tex[2] = readAtt->Zoffset;
813 verts[2].tex[0] = s1;
814 verts[2].tex[1] = t1;
815 verts[2].tex[2] = readAtt->Zoffset;
816 verts[3].tex[0] = s0;
817 verts[3].tex[1] = t1;
818 verts[3].tex[2] = readAtt->Zoffset;
819
820 _mesa_buffer_sub_data(ctx, blit->buf_obj, 0, sizeof(verts), verts,
821 __func__);
822 }
823
824 /* setup viewport */
825 _mesa_set_viewport(ctx, 0, dstX, dstY, dstW, dstH);
826 _mesa_ColorMask(!do_depth, !do_depth, !do_depth, !do_depth);
827 _mesa_set_enable(ctx, GL_DEPTH_TEST, do_depth);
828 _mesa_DepthMask(do_depth);
829 _mesa_DepthFunc(GL_ALWAYS);
830
831 _mesa_DrawArrays(GL_TRIANGLE_FAN, 0, 4);
832 _mesa_meta_fb_tex_blit_end(ctx, target, &fb_tex_blit);
833
834 return true;
835 }
836
837 void
838 _mesa_meta_fb_tex_blit_begin(struct gl_context *ctx,
839 struct fb_tex_blit_state *blit)
840 {
841 /* None of the existing callers preinitialize fb_tex_blit_state to zeros,
842 * and both use stack variables. If samp_obj_save is not NULL,
843 * _mesa_reference_sampler_object will try to dereference it. Leaving
844 * random garbage in samp_obj_save can only lead to crashes.
845 *
846 * Since the state isn't persistent across calls, we won't catch ref
847 * counting problems.
848 */
849 blit->samp_obj_save = NULL;
850 _mesa_reference_sampler_object(ctx, &blit->samp_obj_save,
851 ctx->Texture.Unit[ctx->Texture.CurrentUnit].Sampler);
852 blit->tempTex = 0;
853 }
854
855 void
856 _mesa_meta_fb_tex_blit_end(struct gl_context *ctx, GLenum target,
857 struct fb_tex_blit_state *blit)
858 {
859 struct gl_texture_object *const texObj =
860 _mesa_get_current_tex_object(ctx, target);
861
862 /* Restore texture object state, the texture binding will
863 * be restored by _mesa_meta_end().
864 */
865 if (target != GL_TEXTURE_RECTANGLE_ARB) {
866 _mesa_texture_parameteriv(ctx, texObj, GL_TEXTURE_BASE_LEVEL,
867 &blit->baseLevelSave, false);
868 _mesa_texture_parameteriv(ctx, texObj, GL_TEXTURE_MAX_LEVEL,
869 &blit->maxLevelSave, false);
870 }
871
872 /* If ARB_stencil_texturing is not supported, the mode won't have changed. */
873 if (texObj->StencilSampling != blit->stencilSamplingSave) {
874 /* GLint so the compiler won't complain about type signedness mismatch
875 * in the call to _mesa_texture_parameteriv below.
876 */
877 const GLint param = blit->stencilSamplingSave ?
878 GL_STENCIL_INDEX : GL_DEPTH_COMPONENT;
879
880 _mesa_texture_parameteriv(ctx, texObj, GL_DEPTH_STENCIL_TEXTURE_MODE,
881 &param, false);
882 }
883
884 _mesa_bind_sampler(ctx, ctx->Texture.CurrentUnit, blit->samp_obj_save);
885 _mesa_reference_sampler_object(ctx, &blit->samp_obj_save, NULL);
886 _mesa_reference_sampler_object(ctx, &blit->samp_obj, NULL);
887
888 if (blit->tempTex)
889 _mesa_DeleteTextures(1, &blit->tempTex);
890 }
891
892 GLboolean
893 _mesa_meta_bind_rb_as_tex_image(struct gl_context *ctx,
894 struct gl_renderbuffer *rb,
895 GLuint *tex,
896 struct gl_texture_object **texObj,
897 GLenum *target)
898 {
899 struct gl_texture_image *texImage;
900 GLuint tempTex;
901
902 if (rb->NumSamples > 1)
903 *target = GL_TEXTURE_2D_MULTISAMPLE;
904 else
905 *target = GL_TEXTURE_2D;
906
907 tempTex = 0;
908 _mesa_GenTextures(1, &tempTex);
909 if (tempTex == 0)
910 return false;
911
912 *tex = tempTex;
913
914 _mesa_BindTexture(*target, *tex);
915 *texObj = _mesa_lookup_texture(ctx, *tex);
916 texImage = _mesa_get_tex_image(ctx, *texObj, *target, 0);
917
918 if (!ctx->Driver.BindRenderbufferTexImage(ctx, rb, texImage)) {
919 _mesa_DeleteTextures(1, tex);
920 return false;
921 }
922
923 if (ctx->Driver.FinishRenderTexture && !rb->NeedsFinishRenderTexture) {
924 rb->NeedsFinishRenderTexture = true;
925 ctx->Driver.FinishRenderTexture(ctx, rb);
926 }
927
928 return true;
929 }
930
931 struct gl_sampler_object *
932 _mesa_meta_setup_sampler(struct gl_context *ctx,
933 struct gl_texture_object *texObj,
934 GLenum target, GLenum filter, GLuint srcLevel)
935 {
936 struct gl_sampler_object *samp_obj;
937 GLenum tex_filter = (filter == GL_SCALED_RESOLVE_FASTEST_EXT ||
938 filter == GL_SCALED_RESOLVE_NICEST_EXT) ?
939 GL_NEAREST : filter;
940
941 samp_obj = ctx->Driver.NewSamplerObject(ctx, 0xDEADBEEF);
942 if (samp_obj == NULL)
943 return NULL;
944
945 _mesa_bind_sampler(ctx, ctx->Texture.CurrentUnit, samp_obj);
946 _mesa_set_sampler_filters(ctx, samp_obj, tex_filter, tex_filter);
947 _mesa_set_sampler_wrap(ctx, samp_obj, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE,
948 samp_obj->WrapR);
949
950 /* Prepare src texture state */
951 _mesa_BindTexture(target, texObj->Name);
952 if (target != GL_TEXTURE_RECTANGLE_ARB) {
953 _mesa_texture_parameteriv(ctx, texObj, GL_TEXTURE_BASE_LEVEL,
954 (GLint *) &srcLevel, false);
955 _mesa_texture_parameteriv(ctx, texObj, GL_TEXTURE_MAX_LEVEL,
956 (GLint *) &srcLevel, false);
957 }
958
959 return samp_obj;
960 }
961
962 /**
963 * Meta implementation of ctx->Driver.BlitFramebuffer() in terms
964 * of texture mapping and polygon rendering.
965 */
966 GLbitfield
967 _mesa_meta_BlitFramebuffer(struct gl_context *ctx,
968 const struct gl_framebuffer *readFb,
969 const struct gl_framebuffer *drawFb,
970 GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
971 GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
972 GLbitfield mask, GLenum filter)
973 {
974 const GLint dstW = abs(dstX1 - dstX0);
975 const GLint dstH = abs(dstY1 - dstY0);
976 const GLint dstFlipX = (dstX1 - dstX0) / dstW;
977 const GLint dstFlipY = (dstY1 - dstY0) / dstH;
978
979 struct {
980 GLint srcX0, srcY0, srcX1, srcY1;
981 GLint dstX0, dstY0, dstX1, dstY1;
982 } clip = {
983 srcX0, srcY0, srcX1, srcY1,
984 dstX0, dstY0, dstX1, dstY1
985 };
986
987 const GLboolean use_glsl_version = ctx->Extensions.ARB_vertex_shader &&
988 ctx->Extensions.ARB_fragment_shader;
989
990 /* Multisample texture blit support requires texture multisample. */
991 if (readFb->Visual.samples > 0 &&
992 !ctx->Extensions.ARB_texture_multisample) {
993 return mask;
994 }
995
996 /* Clip a copy of the blit coordinates. If these differ from the input
997 * coordinates, then we'll set the scissor.
998 */
999 if (!_mesa_clip_blit(ctx, readFb, drawFb,
1000 &clip.srcX0, &clip.srcY0, &clip.srcX1, &clip.srcY1,
1001 &clip.dstX0, &clip.dstY0, &clip.dstX1, &clip.dstY1)) {
1002 /* clipped/scissored everything away */
1003 return 0;
1004 }
1005
1006 /* Only scissor affects blit, but we're doing to set a custom scissor if
1007 * necessary anyway, so save/clear state.
1008 */
1009 _mesa_meta_begin(ctx, MESA_META_ALL & ~MESA_META_DRAW_BUFFERS);
1010
1011 /* Dithering shouldn't be performed for glBlitFramebuffer */
1012 _mesa_set_enable(ctx, GL_DITHER, GL_FALSE);
1013
1014 /* If the clipping earlier changed the destination rect at all, then
1015 * enable the scissor to clip to it.
1016 */
1017 if (clip.dstX0 != dstX0 || clip.dstY0 != dstY0 ||
1018 clip.dstX1 != dstX1 || clip.dstY1 != dstY1) {
1019 _mesa_set_enable(ctx, GL_SCISSOR_TEST, GL_TRUE);
1020 _mesa_Scissor(MIN2(clip.dstX0, clip.dstX1),
1021 MIN2(clip.dstY0, clip.dstY1),
1022 abs(clip.dstX0 - clip.dstX1),
1023 abs(clip.dstY0 - clip.dstY1));
1024 }
1025
1026 /* Try faster, direct texture approach first */
1027 if (mask & GL_COLOR_BUFFER_BIT) {
1028 if (blitframebuffer_texture(ctx, readFb, drawFb,
1029 srcX0, srcY0, srcX1, srcY1,
1030 dstX0, dstY0, dstX1, dstY1,
1031 filter, dstFlipX, dstFlipY,
1032 use_glsl_version, false)) {
1033 mask &= ~GL_COLOR_BUFFER_BIT;
1034 }
1035 }
1036
1037 if (mask & GL_DEPTH_BUFFER_BIT && use_glsl_version) {
1038 if (blitframebuffer_texture(ctx, readFb, drawFb,
1039 srcX0, srcY0, srcX1, srcY1,
1040 dstX0, dstY0, dstX1, dstY1,
1041 filter, dstFlipX, dstFlipY,
1042 use_glsl_version, true)) {
1043 mask &= ~GL_DEPTH_BUFFER_BIT;
1044 }
1045 }
1046
1047 if (mask & GL_STENCIL_BUFFER_BIT) {
1048 /* XXX can't easily do stencil */
1049 }
1050
1051 _mesa_meta_end(ctx);
1052
1053 return mask;
1054 }
1055
1056 void
1057 _mesa_meta_glsl_blit_cleanup(struct gl_context *ctx, struct blit_state *blit)
1058 {
1059 if (blit->VAO) {
1060 _mesa_DeleteVertexArrays(1, &blit->VAO);
1061 blit->VAO = 0;
1062 _mesa_reference_buffer_object(ctx, &blit->buf_obj, NULL);
1063 }
1064
1065 _mesa_meta_blit_shader_table_cleanup(ctx, &blit->shaders_with_depth);
1066 _mesa_meta_blit_shader_table_cleanup(ctx, &blit->shaders_without_depth);
1067
1068 _mesa_DeleteTextures(1, &blit->depthTex.TexObj);
1069 blit->depthTex.TexObj = 0;
1070 }
1071
1072 void
1073 _mesa_meta_and_swrast_BlitFramebuffer(struct gl_context *ctx,
1074 struct gl_framebuffer *readFb,
1075 struct gl_framebuffer *drawFb,
1076 GLint srcX0, GLint srcY0,
1077 GLint srcX1, GLint srcY1,
1078 GLint dstX0, GLint dstY0,
1079 GLint dstX1, GLint dstY1,
1080 GLbitfield mask, GLenum filter)
1081 {
1082 mask = _mesa_meta_BlitFramebuffer(ctx, readFb, drawFb,
1083 srcX0, srcY0, srcX1, srcY1,
1084 dstX0, dstY0, dstX1, dstY1,
1085 mask, filter);
1086 if (mask == 0x0)
1087 return;
1088
1089 _swrast_BlitFramebuffer(ctx, readFb, drawFb,
1090 srcX0, srcY0, srcX1, srcY1,
1091 dstX0, dstY0, dstX1, dstY1,
1092 mask, filter);
1093 }