1 //
2 // Copyright 2016 The ANGLE Project Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style license that can be
4 // found in the LICENSE file.
5 //
6 // FramebufferVk.cpp:
7 // Implements the class methods for FramebufferVk.
8 //
9
10 #include "libANGLE/renderer/vulkan/FramebufferVk.h"
11
12 #include <array>
13
14 #include "common/debug.h"
15 #include "common/vulkan/vk_headers.h"
16 #include "libANGLE/Context.h"
17 #include "libANGLE/Display.h"
18 #include "libANGLE/ErrorStrings.h"
19 #include "libANGLE/formatutils.h"
20 #include "libANGLE/renderer/renderer_utils.h"
21 #include "libANGLE/renderer/vulkan/ContextVk.h"
22 #include "libANGLE/renderer/vulkan/DisplayVk.h"
23 #include "libANGLE/renderer/vulkan/RenderTargetVk.h"
24 #include "libANGLE/renderer/vulkan/SurfaceVk.h"
25 #include "libANGLE/renderer/vulkan/vk_format_utils.h"
26 #include "libANGLE/renderer/vulkan/vk_renderer.h"
27 #include "libANGLE/renderer/vulkan/vk_resource.h"
28
29 namespace rx
30 {
31
32 namespace
33 {
34 // Clear values are only used when loadOp=Clear is set in clearWithRenderPassOp. When starting a
35 // new render pass, the clear value is set to an unlikely value (bright pink) to stand out better
36 // in case of a bug.
37 constexpr VkClearValue kUninitializedClearValue = {{{0.95, 0.05, 0.95, 0.95}}};
38
39 // The value to assign an alpha channel that's emulated. The type is unsigned int, though it will
40 // automatically convert to the actual data type.
41 constexpr unsigned int kEmulatedAlphaValue = 1;
42
HasSrcBlitFeature(vk::Renderer * renderer,RenderTargetVk * srcRenderTarget)43 bool HasSrcBlitFeature(vk::Renderer *renderer, RenderTargetVk *srcRenderTarget)
44 {
45 angle::FormatID srcFormatID = srcRenderTarget->getImageActualFormatID();
46 return renderer->hasImageFormatFeatureBits(srcFormatID, VK_FORMAT_FEATURE_BLIT_SRC_BIT);
47 }
48
HasDstBlitFeature(vk::Renderer * renderer,RenderTargetVk * dstRenderTarget)49 bool HasDstBlitFeature(vk::Renderer *renderer, RenderTargetVk *dstRenderTarget)
50 {
51 angle::FormatID dstFormatID = dstRenderTarget->getImageActualFormatID();
52 return renderer->hasImageFormatFeatureBits(dstFormatID, VK_FORMAT_FEATURE_BLIT_DST_BIT);
53 }
54
55 // Returns false if destination has any channel the source doesn't. This means that channel was
56 // emulated and using the Vulkan blit command would overwrite that emulated channel.
AreSrcAndDstColorChannelsBlitCompatible(RenderTargetVk * srcRenderTarget,RenderTargetVk * dstRenderTarget)57 bool AreSrcAndDstColorChannelsBlitCompatible(RenderTargetVk *srcRenderTarget,
58 RenderTargetVk *dstRenderTarget)
59 {
60 const angle::Format &srcFormat = srcRenderTarget->getImageIntendedFormat();
61 const angle::Format &dstFormat = dstRenderTarget->getImageIntendedFormat();
62
63 // Luminance/alpha formats are not renderable, so they can't have ended up in a framebuffer to
64 // participate in a blit.
65 ASSERT(!dstFormat.isLUMA() && !srcFormat.isLUMA());
66
67 // All color formats have the red channel.
68 ASSERT(dstFormat.redBits > 0 && srcFormat.redBits > 0);
69
70 return (dstFormat.greenBits > 0 || srcFormat.greenBits == 0) &&
71 (dstFormat.blueBits > 0 || srcFormat.blueBits == 0) &&
72 (dstFormat.alphaBits > 0 || srcFormat.alphaBits == 0);
73 }
74
75 // Returns false if formats are not identical. vkCmdResolveImage and resolve attachments both
76 // require identical formats between source and destination. vkCmdBlitImage additionally requires
77 // the same for depth/stencil formats.
AreSrcAndDstFormatsIdentical(RenderTargetVk * srcRenderTarget,RenderTargetVk * dstRenderTarget)78 bool AreSrcAndDstFormatsIdentical(RenderTargetVk *srcRenderTarget, RenderTargetVk *dstRenderTarget)
79 {
80 angle::FormatID srcFormatID = srcRenderTarget->getImageActualFormatID();
81 angle::FormatID dstFormatID = dstRenderTarget->getImageActualFormatID();
82
83 return srcFormatID == dstFormatID;
84 }
85
AreSrcAndDstDepthStencilChannelsBlitCompatible(RenderTargetVk * srcRenderTarget,RenderTargetVk * dstRenderTarget)86 bool AreSrcAndDstDepthStencilChannelsBlitCompatible(RenderTargetVk *srcRenderTarget,
87 RenderTargetVk *dstRenderTarget)
88 {
89 const angle::Format &srcFormat = srcRenderTarget->getImageIntendedFormat();
90 const angle::Format &dstFormat = dstRenderTarget->getImageIntendedFormat();
91
92 return (dstFormat.depthBits > 0 || srcFormat.depthBits == 0) &&
93 (dstFormat.stencilBits > 0 || srcFormat.stencilBits == 0);
94 }
95
EarlyAdjustFlipYForPreRotation(SurfaceRotation blitAngleIn,SurfaceRotation * blitAngleOut,bool * blitFlipYOut)96 void EarlyAdjustFlipYForPreRotation(SurfaceRotation blitAngleIn,
97 SurfaceRotation *blitAngleOut,
98 bool *blitFlipYOut)
99 {
100 switch (blitAngleIn)
101 {
102 case SurfaceRotation::Identity:
103 // No adjustments needed
104 break;
105 case SurfaceRotation::Rotated90Degrees:
106 *blitAngleOut = SurfaceRotation::Rotated90Degrees;
107 *blitFlipYOut = false;
108 break;
109 case SurfaceRotation::Rotated180Degrees:
110 *blitAngleOut = SurfaceRotation::Rotated180Degrees;
111 break;
112 case SurfaceRotation::Rotated270Degrees:
113 *blitAngleOut = SurfaceRotation::Rotated270Degrees;
114 *blitFlipYOut = false;
115 break;
116 default:
117 UNREACHABLE();
118 break;
119 }
120 }
121
AdjustBlitAreaForPreRotation(SurfaceRotation framebufferAngle,const gl::Rectangle & blitAreaIn,const gl::Rectangle & framebufferDimensions,gl::Rectangle * blitAreaOut)122 void AdjustBlitAreaForPreRotation(SurfaceRotation framebufferAngle,
123 const gl::Rectangle &blitAreaIn,
124 const gl::Rectangle &framebufferDimensions,
125 gl::Rectangle *blitAreaOut)
126 {
127 switch (framebufferAngle)
128 {
129 case SurfaceRotation::Identity:
130 // No adjustments needed
131 break;
132 case SurfaceRotation::Rotated90Degrees:
133 blitAreaOut->x = blitAreaIn.y;
134 blitAreaOut->y = blitAreaIn.x;
135 std::swap(blitAreaOut->width, blitAreaOut->height);
136 break;
137 case SurfaceRotation::Rotated180Degrees:
138 blitAreaOut->x = framebufferDimensions.width - blitAreaIn.x - blitAreaIn.width;
139 blitAreaOut->y = framebufferDimensions.height - blitAreaIn.y - blitAreaIn.height;
140 break;
141 case SurfaceRotation::Rotated270Degrees:
142 blitAreaOut->x = framebufferDimensions.height - blitAreaIn.y - blitAreaIn.height;
143 blitAreaOut->y = framebufferDimensions.width - blitAreaIn.x - blitAreaIn.width;
144 std::swap(blitAreaOut->width, blitAreaOut->height);
145 break;
146 default:
147 UNREACHABLE();
148 break;
149 }
150 }
151
AdjustDimensionsAndFlipForPreRotation(SurfaceRotation framebufferAngle,gl::Rectangle * framebufferDimensions,bool * flipX,bool * flipY)152 void AdjustDimensionsAndFlipForPreRotation(SurfaceRotation framebufferAngle,
153 gl::Rectangle *framebufferDimensions,
154 bool *flipX,
155 bool *flipY)
156 {
157 switch (framebufferAngle)
158 {
159 case SurfaceRotation::Identity:
160 // No adjustments needed
161 break;
162 case SurfaceRotation::Rotated90Degrees:
163 std::swap(framebufferDimensions->width, framebufferDimensions->height);
164 std::swap(*flipX, *flipY);
165 break;
166 case SurfaceRotation::Rotated180Degrees:
167 break;
168 case SurfaceRotation::Rotated270Degrees:
169 std::swap(framebufferDimensions->width, framebufferDimensions->height);
170 std::swap(*flipX, *flipY);
171 break;
172 default:
173 UNREACHABLE();
174 break;
175 }
176 }
177
178 // When blitting, the source and destination areas are viewed like UVs. For example, a 64x64
179 // texture if flipped should have an offset of 64 in either X or Y which corresponds to U or V of 1.
180 // On the other hand, when resolving, the source and destination areas are used as fragment
181 // coordinates to fetch from. In that case, when flipped, the texture in the above example must
182 // have an offset of 63.
AdjustBlitResolveParametersForResolve(const gl::Rectangle & sourceArea,const gl::Rectangle & destArea,UtilsVk::BlitResolveParameters * params)183 void AdjustBlitResolveParametersForResolve(const gl::Rectangle &sourceArea,
184 const gl::Rectangle &destArea,
185 UtilsVk::BlitResolveParameters *params)
186 {
187 params->srcOffset[0] = sourceArea.x;
188 params->srcOffset[1] = sourceArea.y;
189 params->dstOffset[0] = destArea.x;
190 params->dstOffset[1] = destArea.y;
191
192 if (sourceArea.isReversedX())
193 {
194 ASSERT(sourceArea.x > 0);
195 --params->srcOffset[0];
196 }
197 if (sourceArea.isReversedY())
198 {
199 ASSERT(sourceArea.y > 0);
200 --params->srcOffset[1];
201 }
202 if (destArea.isReversedX())
203 {
204 ASSERT(destArea.x > 0);
205 --params->dstOffset[0];
206 }
207 if (destArea.isReversedY())
208 {
209 ASSERT(destArea.y > 0);
210 --params->dstOffset[1];
211 }
212 }
213
214 // Potentially make adjustments for pre-rotatation. Depending on the angle some of the params need
215 // to be swapped and/or changes made to which axis are flipped.
AdjustBlitResolveParametersForPreRotation(SurfaceRotation framebufferAngle,SurfaceRotation srcFramebufferAngle,UtilsVk::BlitResolveParameters * params)216 void AdjustBlitResolveParametersForPreRotation(SurfaceRotation framebufferAngle,
217 SurfaceRotation srcFramebufferAngle,
218 UtilsVk::BlitResolveParameters *params)
219 {
220 switch (framebufferAngle)
221 {
222 case SurfaceRotation::Identity:
223 break;
224 case SurfaceRotation::Rotated90Degrees:
225 std::swap(params->stretch[0], params->stretch[1]);
226 std::swap(params->srcOffset[0], params->srcOffset[1]);
227 std::swap(params->rotatedOffsetFactor[0], params->rotatedOffsetFactor[1]);
228 std::swap(params->flipX, params->flipY);
229 if (srcFramebufferAngle == framebufferAngle)
230 {
231 std::swap(params->dstOffset[0], params->dstOffset[1]);
232 std::swap(params->stretch[0], params->stretch[1]);
233 }
234 break;
235 case SurfaceRotation::Rotated180Degrees:
236 // Combine flip info with api flip.
237 params->flipX = !params->flipX;
238 params->flipY = !params->flipY;
239 break;
240 case SurfaceRotation::Rotated270Degrees:
241 std::swap(params->stretch[0], params->stretch[1]);
242 std::swap(params->srcOffset[0], params->srcOffset[1]);
243 std::swap(params->rotatedOffsetFactor[0], params->rotatedOffsetFactor[1]);
244 if (srcFramebufferAngle == framebufferAngle)
245 {
246 std::swap(params->stretch[0], params->stretch[1]);
247 }
248 // Combine flip info with api flip.
249 params->flipX = !params->flipX;
250 params->flipY = !params->flipY;
251 std::swap(params->flipX, params->flipY);
252
253 break;
254 default:
255 UNREACHABLE();
256 break;
257 }
258 }
259
MakeUnresolveAttachmentMask(const vk::RenderPassDesc & desc)260 vk::FramebufferNonResolveAttachmentMask MakeUnresolveAttachmentMask(const vk::RenderPassDesc &desc)
261 {
262 vk::FramebufferNonResolveAttachmentMask unresolveMask(
263 desc.getColorUnresolveAttachmentMask().bits());
264 if (desc.hasDepthUnresolveAttachment() || desc.hasStencilUnresolveAttachment())
265 {
266 // This mask only needs to know if the depth/stencil attachment needs to be unresolved, and
267 // is agnostic of the aspect.
268 unresolveMask.set(vk::kUnpackedDepthIndex);
269 }
270 return unresolveMask;
271 }
272
IsAnyAttachment3DWithoutAllLayers(const RenderTargetCache<RenderTargetVk> & renderTargetCache,gl::DrawBufferMask colorAttachmentsMask,uint32_t framebufferLayerCount)273 bool IsAnyAttachment3DWithoutAllLayers(const RenderTargetCache<RenderTargetVk> &renderTargetCache,
274 gl::DrawBufferMask colorAttachmentsMask,
275 uint32_t framebufferLayerCount)
276 {
277 const auto &colorRenderTargets = renderTargetCache.getColors();
278 for (size_t colorIndexGL : colorAttachmentsMask)
279 {
280 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
281 ASSERT(colorRenderTarget);
282
283 const vk::ImageHelper &image = colorRenderTarget->getImageForRenderPass();
284
285 if (image.getType() == VK_IMAGE_TYPE_3D && image.getExtents().depth > framebufferLayerCount)
286 {
287 return true;
288 }
289 }
290
291 // Depth/stencil attachments cannot be 3D.
292 ASSERT(renderTargetCache.getDepthStencil() == nullptr ||
293 renderTargetCache.getDepthStencil()->getImageForRenderPass().getType() !=
294 VK_IMAGE_TYPE_3D);
295
296 return false;
297 }
298
299 // Should be called when the image type is VK_IMAGE_TYPE_3D. Typically, the subresource, offsets
300 // and extents are filled in as if images are 2D layers (because depth slices of 3D images are also
301 // specified through "layers" everywhere, particularly by gl::ImageIndex). This function adjusts
302 // the layer base/count and offsets.z/extents.z appropriately after these structs are set up.
AdjustLayersAndDepthFor3DImages(VkImageSubresourceLayers * subresource,VkOffset3D * offsetsStart,VkOffset3D * offsetsEnd)303 void AdjustLayersAndDepthFor3DImages(VkImageSubresourceLayers *subresource,
304 VkOffset3D *offsetsStart,
305 VkOffset3D *offsetsEnd)
306 {
307 // The struct must be set up as if the image was 2D array.
308 ASSERT(offsetsStart->z == 0);
309 ASSERT(offsetsEnd->z == 1);
310
311 offsetsStart->z = subresource->baseArrayLayer;
312 offsetsEnd->z = subresource->baseArrayLayer + subresource->layerCount;
313
314 subresource->baseArrayLayer = 0;
315 subresource->layerCount = 1;
316 }
317
AllowAddingResolveAttachmentsToSubpass(const vk::RenderPassDesc & desc)318 bool AllowAddingResolveAttachmentsToSubpass(const vk::RenderPassDesc &desc)
319 {
320 // When in render-to-texture emulation mode, there are already resolve attachments present, and
321 // render pass compatibility rules would require packing those first before packing resolve
322 // attachments that may be added later (through glBlitFramebuffer). While supporting that is
323 // not onerous, the code is simplified by not supporting this combination. In practice no
324 // application should be mixing MSRTT textures and and truly multisampled textures in the same
325 // framebuffer (they could be using MSRTT for both).
326 //
327 // For the same reason, adding resolve attachments after the fact is disabled with YUV resolve.
328 return !desc.isRenderToTexture() && !desc.hasYUVResolveAttachment();
329 }
330 } // anonymous namespace
331
FramebufferVk(vk::Renderer * renderer,const gl::FramebufferState & state)332 FramebufferVk::FramebufferVk(vk::Renderer *renderer, const gl::FramebufferState &state)
333 : FramebufferImpl(state), mBackbuffer(nullptr), mActiveColorComponentMasksForClear(0)
334 {
335 if (mState.isDefault())
336 {
337 // These are immutable for system default framebuffer.
338 mCurrentFramebufferDesc.updateLayerCount(1);
339 mCurrentFramebufferDesc.updateIsMultiview(false);
340 }
341
342 mIsCurrentFramebufferCached = !renderer->getFeatures().supportsImagelessFramebuffer.enabled;
343 mIsYUVResolve = false;
344 }
345
346 FramebufferVk::~FramebufferVk() = default;
347
destroy(const gl::Context * context)348 void FramebufferVk::destroy(const gl::Context *context)
349 {
350 ContextVk *contextVk = vk::GetImpl(context);
351
352 if (mFragmentShadingRateImage.valid())
353 {
354 vk::Renderer *renderer = contextVk->getRenderer();
355 mFragmentShadingRateImageView.release(renderer, mFragmentShadingRateImage.getResourceUse());
356 mFragmentShadingRateImage.releaseImage(renderer);
357 }
358
359 releaseCurrentFramebuffer(contextVk);
360 }
361
insertCache(ContextVk * contextVk,const vk::FramebufferDesc & desc,vk::FramebufferHelper && newFramebuffer)362 void FramebufferVk::insertCache(ContextVk *contextVk,
363 const vk::FramebufferDesc &desc,
364 vk::FramebufferHelper &&newFramebuffer)
365 {
366 // Add it into per share group cache
367 contextVk->getShareGroup()->getFramebufferCache().insert(contextVk, desc,
368 std::move(newFramebuffer));
369
370 // Create a refcounted cache key object and have each attachment keep a refcount to it so that
371 // it can be destroyed promptly if those attachments change.
372 const vk::SharedFramebufferCacheKey sharedFramebufferCacheKey =
373 vk::CreateSharedFramebufferCacheKey(desc);
374
375 // Ask each attachment to hold a reference to the cache so that when any attachment is
376 // released, the cache can be destroyed.
377 const auto &colorRenderTargets = mRenderTargetCache.getColors();
378 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
379 {
380 colorRenderTargets[colorIndexGL]->onNewFramebuffer(sharedFramebufferCacheKey);
381 }
382
383 if (getDepthStencilRenderTarget())
384 {
385 getDepthStencilRenderTarget()->onNewFramebuffer(sharedFramebufferCacheKey);
386 }
387 }
388
discard(const gl::Context * context,size_t count,const GLenum * attachments)389 angle::Result FramebufferVk::discard(const gl::Context *context,
390 size_t count,
391 const GLenum *attachments)
392 {
393 return invalidate(context, count, attachments);
394 }
395
invalidate(const gl::Context * context,size_t count,const GLenum * attachments)396 angle::Result FramebufferVk::invalidate(const gl::Context *context,
397 size_t count,
398 const GLenum *attachments)
399 {
400 ContextVk *contextVk = vk::GetImpl(context);
401
402 ANGLE_TRY(invalidateImpl(contextVk, count, attachments, false,
403 getRotatedCompleteRenderArea(contextVk)));
404 return angle::Result::Continue;
405 }
406
invalidateSub(const gl::Context * context,size_t count,const GLenum * attachments,const gl::Rectangle & area)407 angle::Result FramebufferVk::invalidateSub(const gl::Context *context,
408 size_t count,
409 const GLenum *attachments,
410 const gl::Rectangle &area)
411 {
412 ContextVk *contextVk = vk::GetImpl(context);
413
414 const gl::Rectangle nonRotatedCompleteRenderArea = getNonRotatedCompleteRenderArea();
415 gl::Rectangle rotatedInvalidateArea;
416 RotateRectangle(contextVk->getRotationDrawFramebuffer(),
417 contextVk->isViewportFlipEnabledForDrawFBO(),
418 nonRotatedCompleteRenderArea.width, nonRotatedCompleteRenderArea.height, area,
419 &rotatedInvalidateArea);
420
421 // If invalidateSub() covers the whole framebuffer area, make it behave as invalidate().
422 // The invalidate area is clipped to the render area for use inside invalidateImpl.
423 const gl::Rectangle completeRenderArea = getRotatedCompleteRenderArea(contextVk);
424 if (ClipRectangle(rotatedInvalidateArea, completeRenderArea, &rotatedInvalidateArea) &&
425 rotatedInvalidateArea == completeRenderArea)
426 {
427 return invalidate(context, count, attachments);
428 }
429
430 // If there are deferred clears, restage them. syncState may have accumulated deferred clears,
431 // but if the framebuffer's attachments are used after this call not through the framebuffer,
432 // those clears wouldn't get flushed otherwise (for example as the destination of
433 // glCopyTex[Sub]Image, shader storage image, etc).
434 restageDeferredClears(contextVk);
435
436 if (contextVk->hasActiveRenderPass() &&
437 rotatedInvalidateArea.encloses(contextVk->getStartedRenderPassCommands().getRenderArea()))
438 {
439 // Because the render pass's render area is within the invalidated area, it is fine for
440 // invalidateImpl() to use a storeOp of DONT_CARE (i.e. fine to not store the contents of
441 // the invalidated area).
442 ANGLE_TRY(invalidateImpl(contextVk, count, attachments, true, rotatedInvalidateArea));
443 }
444 else
445 {
446 ANGLE_VK_PERF_WARNING(
447 contextVk, GL_DEBUG_SEVERITY_LOW,
448 "InvalidateSubFramebuffer ignored due to area not covering the render area");
449 }
450
451 return angle::Result::Continue;
452 }
453
clear(const gl::Context * context,GLbitfield mask)454 angle::Result FramebufferVk::clear(const gl::Context *context, GLbitfield mask)
455 {
456 ANGLE_TRACE_EVENT0("gpu.angle", "FramebufferVk::clear");
457 ContextVk *contextVk = vk::GetImpl(context);
458
459 bool clearColor = IsMaskFlagSet(mask, static_cast<GLbitfield>(GL_COLOR_BUFFER_BIT));
460 bool clearDepth = IsMaskFlagSet(mask, static_cast<GLbitfield>(GL_DEPTH_BUFFER_BIT));
461 bool clearStencil = IsMaskFlagSet(mask, static_cast<GLbitfield>(GL_STENCIL_BUFFER_BIT));
462 gl::DrawBufferMask clearColorBuffers;
463 if (clearColor)
464 {
465 clearColorBuffers = mState.getEnabledDrawBuffers();
466 }
467
468 const VkClearColorValue &clearColorValue = contextVk->getClearColorValue().color;
469 const VkClearDepthStencilValue &clearDepthStencilValue =
470 contextVk->getClearDepthStencilValue().depthStencil;
471
472 return clearImpl(context, clearColorBuffers, clearDepth, clearStencil, clearColorValue,
473 clearDepthStencilValue);
474 }
475
adjustFloatClearColorPrecision(const VkClearColorValue & color,const angle::Format & colorFormat)476 VkClearColorValue adjustFloatClearColorPrecision(const VkClearColorValue &color,
477 const angle::Format &colorFormat)
478 {
479 // Truncate x to b bits: round(x * (2^b-1)) / (2^b-1)
480 // Implemented as floor(x * ((1 << b) - 1) + 0.5) / ((1 << b) - 1)
481
482 float floatClearColorRed = color.float32[0];
483 GLuint targetRedBits = colorFormat.redBits;
484 floatClearColorRed = floor(floatClearColorRed * ((1 << targetRedBits) - 1) + 0.5f);
485 floatClearColorRed = floatClearColorRed / ((1 << targetRedBits) - 1);
486
487 float floatClearColorGreen = color.float32[1];
488 GLuint targetGreenBits = colorFormat.greenBits;
489 floatClearColorGreen = floor(floatClearColorGreen * ((1 << targetGreenBits) - 1) + 0.5f);
490 floatClearColorGreen = floatClearColorGreen / ((1 << targetGreenBits) - 1);
491
492 float floatClearColorBlue = color.float32[2];
493 GLuint targetBlueBits = colorFormat.blueBits;
494 floatClearColorBlue = floor(floatClearColorBlue * ((1 << targetBlueBits) - 1) + 0.5f);
495 floatClearColorBlue = floatClearColorBlue / ((1 << targetBlueBits) - 1);
496
497 float floatClearColorAlpha = color.float32[3];
498 GLuint targetAlphaBits = colorFormat.alphaBits;
499 floatClearColorAlpha = floor(floatClearColorAlpha * ((1 << targetAlphaBits) - 1) + 0.5f);
500 floatClearColorAlpha = floatClearColorAlpha / ((1 << targetAlphaBits) - 1);
501
502 VkClearColorValue adjustedClearColor = color;
503 adjustedClearColor.float32[0] = floatClearColorRed;
504 adjustedClearColor.float32[1] = floatClearColorGreen;
505 adjustedClearColor.float32[2] = floatClearColorBlue;
506 adjustedClearColor.float32[3] = floatClearColorAlpha;
507
508 return adjustedClearColor;
509 }
510
clearImpl(const gl::Context * context,gl::DrawBufferMask clearColorBuffers,bool clearDepth,bool clearStencil,const VkClearColorValue & clearColorValue,const VkClearDepthStencilValue & clearDepthStencilValue)511 angle::Result FramebufferVk::clearImpl(const gl::Context *context,
512 gl::DrawBufferMask clearColorBuffers,
513 bool clearDepth,
514 bool clearStencil,
515 const VkClearColorValue &clearColorValue,
516 const VkClearDepthStencilValue &clearDepthStencilValue)
517 {
518 ContextVk *contextVk = vk::GetImpl(context);
519
520 const gl::Rectangle scissoredRenderArea = getRotatedScissoredRenderArea(contextVk);
521 if (scissoredRenderArea.width == 0 || scissoredRenderArea.height == 0)
522 {
523 restageDeferredClears(contextVk);
524 return angle::Result::Continue;
525 }
526
527 // This function assumes that only enabled attachments are asked to be cleared.
528 ASSERT((clearColorBuffers & mState.getEnabledDrawBuffers()) == clearColorBuffers);
529 ASSERT(!clearDepth || mState.getDepthAttachment() != nullptr);
530 ASSERT(!clearStencil || mState.getStencilAttachment() != nullptr);
531
532 gl::BlendStateExt::ColorMaskStorage::Type colorMasks = contextVk->getClearColorMasks();
533 bool clearColor = clearColorBuffers.any();
534
535 // When this function is called, there should always be something to clear.
536 ASSERT(clearColor || clearDepth || clearStencil);
537
538 gl::DrawBuffersArray<VkClearColorValue> adjustedClearColorValues;
539 const gl::DrawBufferMask colorAttachmentMask = mState.getColorAttachmentsMask();
540 const auto &colorRenderTargets = mRenderTargetCache.getColors();
541 bool anyAttachmentWithColorspaceOverride = false;
542 for (size_t colorIndexGL = 0; colorIndexGL < colorAttachmentMask.size(); ++colorIndexGL)
543 {
544 if (colorAttachmentMask[colorIndexGL])
545 {
546 adjustedClearColorValues[colorIndexGL] = clearColorValue;
547
548 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
549 ASSERT(colorRenderTarget);
550
551 // If a rendertarget has colorspace overrides, we need to clear with a draw
552 // to make sure the colorspace override is honored.
553 anyAttachmentWithColorspaceOverride =
554 anyAttachmentWithColorspaceOverride ||
555 colorRenderTarget->hasColorspaceOverrideForWrite();
556
557 if (colorRenderTarget->isYuvResolve())
558 {
559 // OpenGLES spec says "clear color should be defined in yuv color space and so
560 // floating point r, g, and b value will be mapped to corresponding y, u and v
561 // value" https://registry.khronos.org/OpenGL/extensions/EXT/EXT_YUV_target.txt.
562 // But vulkan spec says "Values in the G, B, and R channels of the color
563 // attachment will be written to the Y, CB, and CR channels of the external
564 // format image, respectively." So we have to adjust the component mapping from
565 // GL order to vulkan order.
566 adjustedClearColorValues[colorIndexGL].float32[0] = clearColorValue.float32[2];
567 adjustedClearColorValues[colorIndexGL].float32[1] = clearColorValue.float32[0];
568 adjustedClearColorValues[colorIndexGL].float32[2] = clearColorValue.float32[1];
569 }
570 else if (contextVk->getFeatures().adjustClearColorPrecision.enabled)
571 {
572 const angle::FormatID colorRenderTargetFormat =
573 colorRenderTarget->getImageForRenderPass().getActualFormatID();
574 if (colorRenderTargetFormat == angle::FormatID::R5G5B5A1_UNORM)
575 {
576 // Temporary workaround for https://issuetracker.google.com/292282210 to avoid
577 // dithering being automatically applied
578 adjustedClearColorValues[colorIndexGL] = adjustFloatClearColorPrecision(
579 clearColorValue, angle::Format::Get(colorRenderTargetFormat));
580 }
581 }
582 }
583 }
584
585 const uint8_t stencilMask =
586 static_cast<uint8_t>(contextVk->getState().getDepthStencilState().stencilWritemask);
587
588 // The front-end should ensure we don't attempt to clear color if all channels are masked.
589 ASSERT(!clearColor || colorMasks != 0);
590 // The front-end should ensure we don't attempt to clear depth if depth write is disabled.
591 ASSERT(!clearDepth || contextVk->getState().getDepthStencilState().depthMask);
592 // The front-end should ensure we don't attempt to clear stencil if all bits are masked.
593 ASSERT(!clearStencil || stencilMask != 0);
594
595 // Make sure to close the render pass now if in read-only depth/stencil feedback loop mode and
596 // depth/stencil is being cleared.
597 if (clearDepth || clearStencil)
598 {
599 ANGLE_TRY(contextVk->updateRenderPassDepthFeedbackLoopMode(
600 clearDepth ? UpdateDepthFeedbackLoopReason::Clear : UpdateDepthFeedbackLoopReason::None,
601 clearStencil ? UpdateDepthFeedbackLoopReason::Clear
602 : UpdateDepthFeedbackLoopReason::None));
603 }
604
605 const bool scissoredClear = scissoredRenderArea != getRotatedCompleteRenderArea(contextVk);
606
607 // We use the draw path if scissored clear, or color or stencil are masked. Note that depth
608 // clearing is already disabled if there's a depth mask.
609 const bool maskedClearColor = clearColor && (mActiveColorComponentMasksForClear & colorMasks) !=
610 mActiveColorComponentMasksForClear;
611 const bool maskedClearStencil = clearStencil && stencilMask != 0xFF;
612
613 bool clearColorWithDraw =
614 clearColor && (maskedClearColor || scissoredClear || anyAttachmentWithColorspaceOverride);
615 bool clearDepthWithDraw = clearDepth && scissoredClear;
616 bool clearStencilWithDraw = clearStencil && (maskedClearStencil || scissoredClear);
617
618 const bool isMidRenderPassClear =
619 contextVk->hasStartedRenderPassWithQueueSerial(mLastRenderPassQueueSerial) &&
620 !contextVk->getStartedRenderPassCommands().getCommandBuffer().empty();
621 if (isMidRenderPassClear)
622 {
623 // Emit debug-util markers for this mid-render-pass clear
624 ANGLE_TRY(
625 contextVk->handleGraphicsEventLog(rx::GraphicsEventCmdBuf::InRenderPassCmdBufQueryCmd));
626 }
627 else
628 {
629 ASSERT(!contextVk->hasActiveRenderPass() ||
630 contextVk->hasStartedRenderPassWithQueueSerial(mLastRenderPassQueueSerial));
631 // Emit debug-util markers for this outside-render-pass clear
632 ANGLE_TRY(
633 contextVk->handleGraphicsEventLog(rx::GraphicsEventCmdBuf::InOutsideCmdBufQueryCmd));
634 }
635
636 const bool preferDrawOverClearAttachments =
637 contextVk->getFeatures().preferDrawClearOverVkCmdClearAttachments.enabled;
638
639 // Merge current clears with the deferred clears, then proceed with only processing deferred
640 // clears. This simplifies the clear paths such that they don't need to consider both the
641 // current and deferred clears. Additionally, it avoids needing to undo an unresolve
642 // operation; say attachment A is deferred cleared and multisampled-render-to-texture
643 // attachment B is currently cleared. Assuming a render pass needs to start (because for
644 // example attachment C needs to clear with a draw path), starting one with only deferred
645 // clears and then applying the current clears won't work as attachment B is unresolved, and
646 // there are no facilities to undo that.
647 if (preferDrawOverClearAttachments && isMidRenderPassClear)
648 {
649 // On buggy hardware, prefer to clear with a draw call instead of vkCmdClearAttachments.
650 // Note that it's impossible to have deferred clears in the middle of the render pass.
651 ASSERT(!mDeferredClears.any());
652
653 clearColorWithDraw = clearColor;
654 clearDepthWithDraw = clearDepth;
655 clearStencilWithDraw = clearStencil;
656 }
657 else
658 {
659 gl::DrawBufferMask clearColorDrawBuffersMask;
660 if (clearColor && !clearColorWithDraw)
661 {
662 clearColorDrawBuffersMask = clearColorBuffers;
663 }
664
665 mergeClearsWithDeferredClears(clearColorDrawBuffersMask, clearDepth && !clearDepthWithDraw,
666 clearStencil && !clearStencilWithDraw,
667 adjustedClearColorValues, clearDepthStencilValue);
668 }
669
670 // If any deferred clears, we can further defer them, clear them with vkCmdClearAttachments or
671 // flush them if necessary.
672 if (mDeferredClears.any())
673 {
674 const bool clearAnyWithDraw =
675 clearColorWithDraw || clearDepthWithDraw || clearStencilWithDraw;
676
677 bool isAnyAttachment3DWithoutAllLayers =
678 IsAnyAttachment3DWithoutAllLayers(mRenderTargetCache, mState.getColorAttachmentsMask(),
679 mCurrentFramebufferDesc.getLayerCount());
680
681 // If we are in an active renderpass that has recorded commands and the framebuffer hasn't
682 // changed, inline the clear.
683 if (isMidRenderPassClear)
684 {
685 ANGLE_VK_PERF_WARNING(
686 contextVk, GL_DEBUG_SEVERITY_LOW,
687 "Clear effectively discarding previous draw call results. Suggest earlier Clear "
688 "followed by masked color or depth/stencil draw calls instead, or "
689 "glInvalidateFramebuffer to discard data instead");
690
691 ASSERT(!preferDrawOverClearAttachments);
692
693 // clearWithCommand will operate on deferred clears.
694 clearWithCommand(contextVk, scissoredRenderArea, ClearWithCommand::OptimizeWithLoadOp,
695 &mDeferredClears);
696
697 // clearWithCommand will clear only those attachments that have been used in the render
698 // pass, and removes them from mDeferredClears. Any deferred clears that are left can
699 // be performed with a renderpass loadOp.
700 if (mDeferredClears.any())
701 {
702 clearWithLoadOp(contextVk);
703 }
704 }
705 else
706 {
707 if (contextVk->hasActiveRenderPass())
708 {
709 // Typically, clears are deferred such that it's impossible to have a render pass
710 // opened without any additional commands recorded on it. This is not true for some
711 // corner cases, such as with 3D or external attachments. In those cases, a clear
712 // can open a render pass that's otherwise empty, and additional clears can continue
713 // to be accumulated in the render pass loadOps.
714 ASSERT(isAnyAttachment3DWithoutAllLayers || hasAnyExternalAttachments());
715 clearWithLoadOp(contextVk);
716 }
717
718 // This path will defer the current clears along with deferred clears. This won't work
719 // if any attachment needs to be subsequently cleared with a draw call. In that case,
720 // flush deferred clears, which will start a render pass with deferred clear values.
721 // The subsequent draw call will then operate on the cleared attachments.
722 //
723 // Additionally, if the framebuffer is layered, any attachment is 3D and it has a larger
724 // depth than the framebuffer layers, clears cannot be deferred. This is because the
725 // clear may later need to be flushed with vkCmdClearColorImage, which cannot partially
726 // clear the 3D texture. In that case, the clears are flushed immediately too.
727 //
728 // For external images such as from AHBs, the clears are not deferred so that they are
729 // definitely applied before the application uses them outside of the control of ANGLE.
730 if (clearAnyWithDraw || isAnyAttachment3DWithoutAllLayers ||
731 hasAnyExternalAttachments())
732 {
733 ANGLE_TRY(flushDeferredClears(contextVk));
734 }
735 else
736 {
737 restageDeferredClears(contextVk);
738 }
739 }
740
741 // If nothing left to clear, early out.
742 if (!clearAnyWithDraw)
743 {
744 ASSERT(mDeferredClears.empty());
745 return angle::Result::Continue;
746 }
747 }
748
749 if (!clearColorWithDraw)
750 {
751 clearColorBuffers.reset();
752 }
753
754 // If we reach here simply because the clear is scissored (as opposed to masked), use
755 // vkCmdClearAttachments to clear the attachments. The attachments that are masked will
756 // continue to use a draw call. For depth, vkCmdClearAttachments can always be used, and no
757 // shader/pipeline support would then be required (though this is pending removal of the
758 // preferDrawOverClearAttachments workaround).
759 //
760 // A potential optimization is to use loadOp=Clear for scissored clears, but care needs to be
761 // taken to either break the render pass on growRenderArea(), or to turn the op back to Load and
762 // revert to vkCmdClearAttachments. This is not currently deemed necessary.
763 if (((clearColorBuffers.any() && !mEmulatedAlphaAttachmentMask.any() && !maskedClearColor) ||
764 clearDepthWithDraw || (clearStencilWithDraw && !maskedClearStencil)) &&
765 !preferDrawOverClearAttachments && !anyAttachmentWithColorspaceOverride)
766 {
767 if (!contextVk->hasActiveRenderPass())
768 {
769 // Start a new render pass if necessary to record the commands.
770 vk::RenderPassCommandBuffer *commandBuffer;
771 gl::Rectangle renderArea = getRenderArea(contextVk);
772 ANGLE_TRY(contextVk->startRenderPass(renderArea, &commandBuffer, nullptr));
773 }
774
775 // Build clear values
776 vk::ClearValuesArray clears;
777 if (!maskedClearColor && !mEmulatedAlphaAttachmentMask.any())
778 {
779 VkClearValue colorClearValue = {};
780 for (size_t colorIndexGL : clearColorBuffers)
781 {
782 colorClearValue.color = adjustedClearColorValues[colorIndexGL];
783 clears.store(static_cast<uint32_t>(colorIndexGL), VK_IMAGE_ASPECT_COLOR_BIT,
784 colorClearValue);
785 }
786 clearColorBuffers.reset();
787 }
788 VkImageAspectFlags dsAspectFlags = 0;
789 if (clearDepthWithDraw)
790 {
791 dsAspectFlags |= VK_IMAGE_ASPECT_DEPTH_BIT;
792 clearDepthWithDraw = false;
793 }
794 if (clearStencilWithDraw && !maskedClearStencil)
795 {
796 dsAspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
797 clearStencilWithDraw = false;
798 }
799 if (dsAspectFlags != 0)
800 {
801 VkClearValue dsClearValue = {};
802 dsClearValue.depthStencil = clearDepthStencilValue;
803 clears.store(vk::kUnpackedDepthIndex, dsAspectFlags, dsClearValue);
804 }
805
806 clearWithCommand(contextVk, scissoredRenderArea, ClearWithCommand::Always, &clears);
807
808 if (!clearColorBuffers.any() && !clearStencilWithDraw)
809 {
810 ASSERT(!clearDepthWithDraw);
811 return angle::Result::Continue;
812 }
813 }
814
815 // The most costly clear mode is when we need to mask out specific color channels or stencil
816 // bits. This can only be done with a draw call.
817 return clearWithDraw(contextVk, scissoredRenderArea, clearColorBuffers, clearDepthWithDraw,
818 clearStencilWithDraw, colorMasks, stencilMask, adjustedClearColorValues,
819 clearDepthStencilValue);
820 }
821
clearBufferfv(const gl::Context * context,GLenum buffer,GLint drawbuffer,const GLfloat * values)822 angle::Result FramebufferVk::clearBufferfv(const gl::Context *context,
823 GLenum buffer,
824 GLint drawbuffer,
825 const GLfloat *values)
826 {
827 VkClearValue clearValue = {};
828
829 bool clearDepth = false;
830 gl::DrawBufferMask clearColorBuffers;
831
832 if (buffer == GL_DEPTH)
833 {
834 clearDepth = true;
835 clearValue.depthStencil.depth = values[0];
836 }
837 else
838 {
839 clearColorBuffers.set(drawbuffer);
840 clearValue.color.float32[0] = values[0];
841 clearValue.color.float32[1] = values[1];
842 clearValue.color.float32[2] = values[2];
843 clearValue.color.float32[3] = values[3];
844 }
845
846 return clearImpl(context, clearColorBuffers, clearDepth, false, clearValue.color,
847 clearValue.depthStencil);
848 }
849
clearBufferuiv(const gl::Context * context,GLenum buffer,GLint drawbuffer,const GLuint * values)850 angle::Result FramebufferVk::clearBufferuiv(const gl::Context *context,
851 GLenum buffer,
852 GLint drawbuffer,
853 const GLuint *values)
854 {
855 VkClearValue clearValue = {};
856
857 gl::DrawBufferMask clearColorBuffers;
858 clearColorBuffers.set(drawbuffer);
859
860 clearValue.color.uint32[0] = values[0];
861 clearValue.color.uint32[1] = values[1];
862 clearValue.color.uint32[2] = values[2];
863 clearValue.color.uint32[3] = values[3];
864
865 return clearImpl(context, clearColorBuffers, false, false, clearValue.color,
866 clearValue.depthStencil);
867 }
868
clearBufferiv(const gl::Context * context,GLenum buffer,GLint drawbuffer,const GLint * values)869 angle::Result FramebufferVk::clearBufferiv(const gl::Context *context,
870 GLenum buffer,
871 GLint drawbuffer,
872 const GLint *values)
873 {
874 VkClearValue clearValue = {};
875
876 bool clearStencil = false;
877 gl::DrawBufferMask clearColorBuffers;
878
879 if (buffer == GL_STENCIL)
880 {
881 clearStencil = true;
882 clearValue.depthStencil.stencil = static_cast<uint8_t>(values[0]);
883 }
884 else
885 {
886 clearColorBuffers.set(drawbuffer);
887 clearValue.color.int32[0] = values[0];
888 clearValue.color.int32[1] = values[1];
889 clearValue.color.int32[2] = values[2];
890 clearValue.color.int32[3] = values[3];
891 }
892
893 return clearImpl(context, clearColorBuffers, false, clearStencil, clearValue.color,
894 clearValue.depthStencil);
895 }
896
clearBufferfi(const gl::Context * context,GLenum buffer,GLint drawbuffer,GLfloat depth,GLint stencil)897 angle::Result FramebufferVk::clearBufferfi(const gl::Context *context,
898 GLenum buffer,
899 GLint drawbuffer,
900 GLfloat depth,
901 GLint stencil)
902 {
903 VkClearValue clearValue = {};
904
905 clearValue.depthStencil.depth = depth;
906 clearValue.depthStencil.stencil = static_cast<uint8_t>(stencil);
907
908 return clearImpl(context, gl::DrawBufferMask(), true, true, clearValue.color,
909 clearValue.depthStencil);
910 }
911
getImplementationColorReadFormat(const gl::Context * context) const912 const gl::InternalFormat &FramebufferVk::getImplementationColorReadFormat(
913 const gl::Context *context) const
914 {
915 ContextVk *contextVk = vk::GetImpl(context);
916 GLenum sizedFormat = mState.getReadAttachment()->getFormat().info->sizedInternalFormat;
917 const vk::Format &vkFormat = contextVk->getRenderer()->getFormat(sizedFormat);
918 GLenum implFormat = vkFormat.getActualRenderableImageFormat().fboImplementationInternalFormat;
919 return gl::GetSizedInternalFormatInfo(implFormat);
920 }
921
readPixels(const gl::Context * context,const gl::Rectangle & area,GLenum format,GLenum type,const gl::PixelPackState & pack,gl::Buffer * packBuffer,void * pixels)922 angle::Result FramebufferVk::readPixels(const gl::Context *context,
923 const gl::Rectangle &area,
924 GLenum format,
925 GLenum type,
926 const gl::PixelPackState &pack,
927 gl::Buffer *packBuffer,
928 void *pixels)
929 {
930 // Clip read area to framebuffer.
931 const gl::Extents &fbSize = getState().getReadPixelsAttachment(format)->getSize();
932 const gl::Rectangle fbRect(0, 0, fbSize.width, fbSize.height);
933 ContextVk *contextVk = vk::GetImpl(context);
934
935 gl::Rectangle clippedArea;
936 if (!ClipRectangle(area, fbRect, &clippedArea))
937 {
938 // nothing to read
939 return angle::Result::Continue;
940 }
941
942 // Flush any deferred clears.
943 ANGLE_TRY(flushDeferredClears(contextVk));
944
945 GLuint outputSkipBytes = 0;
946 PackPixelsParams params;
947 ANGLE_TRY(vk::ImageHelper::GetReadPixelsParams(contextVk, pack, packBuffer, format, type, area,
948 clippedArea, ¶ms, &outputSkipBytes));
949
950 bool flipY = contextVk->isViewportFlipEnabledForReadFBO();
951 switch (params.rotation = contextVk->getRotationReadFramebuffer())
952 {
953 case SurfaceRotation::Identity:
954 // Do not rotate gl_Position (surface matches the device's orientation):
955 if (flipY)
956 {
957 params.area.y = fbRect.height - clippedArea.y - clippedArea.height;
958 }
959 break;
960 case SurfaceRotation::Rotated90Degrees:
961 // Rotate gl_Position 90 degrees:
962 params.area.x = clippedArea.y;
963 params.area.y =
964 flipY ? clippedArea.x : fbRect.width - clippedArea.x - clippedArea.width;
965 std::swap(params.area.width, params.area.height);
966 break;
967 case SurfaceRotation::Rotated180Degrees:
968 // Rotate gl_Position 180 degrees:
969 params.area.x = fbRect.width - clippedArea.x - clippedArea.width;
970 params.area.y =
971 flipY ? clippedArea.y : fbRect.height - clippedArea.y - clippedArea.height;
972 break;
973 case SurfaceRotation::Rotated270Degrees:
974 // Rotate gl_Position 270 degrees:
975 params.area.x = fbRect.height - clippedArea.y - clippedArea.height;
976 params.area.y =
977 flipY ? fbRect.width - clippedArea.x - clippedArea.width : clippedArea.x;
978 std::swap(params.area.width, params.area.height);
979 break;
980 default:
981 UNREACHABLE();
982 break;
983 }
984 if (flipY)
985 {
986 params.reverseRowOrder = !params.reverseRowOrder;
987 }
988
989 ANGLE_TRY(readPixelsImpl(contextVk, params.area, params, getReadPixelsAspectFlags(format),
990 getReadPixelsRenderTarget(format),
991 static_cast<uint8_t *>(pixels) + outputSkipBytes));
992 return angle::Result::Continue;
993 }
994
getDepthStencilRenderTarget() const995 RenderTargetVk *FramebufferVk::getDepthStencilRenderTarget() const
996 {
997 return mRenderTargetCache.getDepthStencil();
998 }
999
getColorDrawRenderTarget(size_t colorIndexGL) const1000 RenderTargetVk *FramebufferVk::getColorDrawRenderTarget(size_t colorIndexGL) const
1001 {
1002 RenderTargetVk *renderTarget = mRenderTargetCache.getColorDraw(mState, colorIndexGL);
1003 ASSERT(renderTarget && renderTarget->getImageForRenderPass().valid());
1004 return renderTarget;
1005 }
1006
getColorReadRenderTarget() const1007 RenderTargetVk *FramebufferVk::getColorReadRenderTarget() const
1008 {
1009 RenderTargetVk *renderTarget = mRenderTargetCache.getColorRead(mState);
1010 ASSERT(renderTarget && renderTarget->getImageForRenderPass().valid());
1011 return renderTarget;
1012 }
1013
getReadPixelsRenderTarget(GLenum format) const1014 RenderTargetVk *FramebufferVk::getReadPixelsRenderTarget(GLenum format) const
1015 {
1016 switch (format)
1017 {
1018 case GL_DEPTH_COMPONENT:
1019 case GL_STENCIL_INDEX_OES:
1020 case GL_DEPTH_STENCIL_OES:
1021 return getDepthStencilRenderTarget();
1022 default:
1023 return getColorReadRenderTarget();
1024 }
1025 }
1026
getReadPixelsAspectFlags(GLenum format) const1027 VkImageAspectFlagBits FramebufferVk::getReadPixelsAspectFlags(GLenum format) const
1028 {
1029 switch (format)
1030 {
1031 case GL_DEPTH_COMPONENT:
1032 return VK_IMAGE_ASPECT_DEPTH_BIT;
1033 case GL_STENCIL_INDEX_OES:
1034 return VK_IMAGE_ASPECT_STENCIL_BIT;
1035 case GL_DEPTH_STENCIL_OES:
1036 return vk::IMAGE_ASPECT_DEPTH_STENCIL;
1037 default:
1038 return VK_IMAGE_ASPECT_COLOR_BIT;
1039 }
1040 }
1041
blitWithCommand(ContextVk * contextVk,const gl::Rectangle & sourceArea,const gl::Rectangle & destArea,RenderTargetVk * readRenderTarget,RenderTargetVk * drawRenderTarget,GLenum filter,bool colorBlit,bool depthBlit,bool stencilBlit,bool flipX,bool flipY)1042 angle::Result FramebufferVk::blitWithCommand(ContextVk *contextVk,
1043 const gl::Rectangle &sourceArea,
1044 const gl::Rectangle &destArea,
1045 RenderTargetVk *readRenderTarget,
1046 RenderTargetVk *drawRenderTarget,
1047 GLenum filter,
1048 bool colorBlit,
1049 bool depthBlit,
1050 bool stencilBlit,
1051 bool flipX,
1052 bool flipY)
1053 {
1054 // Since blitRenderbufferRect is called for each render buffer that needs to be blitted,
1055 // it should never be the case that both color and depth/stencil need to be blitted at
1056 // at the same time.
1057 ASSERT(colorBlit != (depthBlit || stencilBlit));
1058
1059 vk::ImageHelper *srcImage = &readRenderTarget->getImageForCopy();
1060 vk::ImageHelper *dstImage = &drawRenderTarget->getImageForWrite();
1061
1062 VkImageAspectFlags imageAspectMask = srcImage->getAspectFlags();
1063 VkImageAspectFlags blitAspectMask = imageAspectMask;
1064
1065 // Remove depth or stencil aspects if they are not requested to be blitted.
1066 if (!depthBlit)
1067 {
1068 blitAspectMask &= ~VK_IMAGE_ASPECT_DEPTH_BIT;
1069 }
1070 if (!stencilBlit)
1071 {
1072 blitAspectMask &= ~VK_IMAGE_ASPECT_STENCIL_BIT;
1073 }
1074
1075 vk::CommandBufferAccess access;
1076 access.onImageTransferRead(imageAspectMask, srcImage);
1077 access.onImageTransferWrite(drawRenderTarget->getLevelIndex(), 1,
1078 drawRenderTarget->getLayerIndex(), 1, imageAspectMask, dstImage);
1079 vk::OutsideRenderPassCommandBuffer *commandBuffer;
1080 ANGLE_TRY(contextVk->getOutsideRenderPassCommandBuffer(access, &commandBuffer));
1081
1082 VkImageBlit blit = {};
1083 blit.srcSubresource.aspectMask = blitAspectMask;
1084 blit.srcSubresource.mipLevel = srcImage->toVkLevel(readRenderTarget->getLevelIndex()).get();
1085 blit.srcSubresource.baseArrayLayer = readRenderTarget->getLayerIndex();
1086 blit.srcSubresource.layerCount = 1;
1087 blit.srcOffsets[0] = {sourceArea.x0(), sourceArea.y0(), 0};
1088 blit.srcOffsets[1] = {sourceArea.x1(), sourceArea.y1(), 1};
1089 blit.dstSubresource.aspectMask = blitAspectMask;
1090 blit.dstSubresource.mipLevel = dstImage->toVkLevel(drawRenderTarget->getLevelIndex()).get();
1091 blit.dstSubresource.baseArrayLayer = drawRenderTarget->getLayerIndex();
1092 blit.dstSubresource.layerCount = 1;
1093 blit.dstOffsets[0] = {destArea.x0(), destArea.y0(), 0};
1094 blit.dstOffsets[1] = {destArea.x1(), destArea.y1(), 1};
1095
1096 // Note: vkCmdBlitImage doesn't actually work between 3D and 2D array images due to Vulkan valid
1097 // usage restrictions (https://gitlab.khronos.org/vulkan/vulkan/-/issues/3490), but drivers seem
1098 // to work as expected anyway. ANGLE continues to use vkCmdBlitImage in that case.
1099
1100 const bool isSrc3D = srcImage->getType() == VK_IMAGE_TYPE_3D;
1101 const bool isDst3D = dstImage->getType() == VK_IMAGE_TYPE_3D;
1102 if (isSrc3D)
1103 {
1104 AdjustLayersAndDepthFor3DImages(&blit.srcSubresource, &blit.srcOffsets[0],
1105 &blit.srcOffsets[1]);
1106 }
1107 if (isDst3D)
1108 {
1109 AdjustLayersAndDepthFor3DImages(&blit.dstSubresource, &blit.dstOffsets[0],
1110 &blit.dstOffsets[1]);
1111 }
1112
1113 commandBuffer->blitImage(srcImage->getImage(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
1114 dstImage->getImage(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
1115 gl_vk::GetFilter(filter));
1116
1117 return angle::Result::Continue;
1118 }
1119
blit(const gl::Context * context,const gl::Rectangle & sourceAreaIn,const gl::Rectangle & destAreaIn,GLbitfield mask,GLenum filter)1120 angle::Result FramebufferVk::blit(const gl::Context *context,
1121 const gl::Rectangle &sourceAreaIn,
1122 const gl::Rectangle &destAreaIn,
1123 GLbitfield mask,
1124 GLenum filter)
1125 {
1126 ContextVk *contextVk = vk::GetImpl(context);
1127 vk::Renderer *renderer = contextVk->getRenderer();
1128 UtilsVk &utilsVk = contextVk->getUtils();
1129
1130 // If any clears were picked up when syncing the read framebuffer (as the blit source), restage
1131 // them. They correspond to attachments that are not used in the blit. This will cause the
1132 // read framebuffer to become dirty, so the attachments will be synced again on the next command
1133 // that might be using them.
1134 const gl::State &glState = contextVk->getState();
1135 const gl::Framebuffer *srcFramebuffer = glState.getReadFramebuffer();
1136 FramebufferVk *srcFramebufferVk = vk::GetImpl(srcFramebuffer);
1137 if (srcFramebufferVk->mDeferredClears.any())
1138 {
1139 srcFramebufferVk->restageDeferredClearsForReadFramebuffer(contextVk);
1140 }
1141
1142 // We can sometimes end up in a blit with some clear commands saved. Ensure all clear commands
1143 // are issued before we issue the blit command.
1144 ANGLE_TRY(flushDeferredClears(contextVk));
1145
1146 const bool blitColorBuffer = (mask & GL_COLOR_BUFFER_BIT) != 0;
1147 const bool blitDepthBuffer = (mask & GL_DEPTH_BUFFER_BIT) != 0;
1148 const bool blitStencilBuffer = (mask & GL_STENCIL_BUFFER_BIT) != 0;
1149
1150 // If a framebuffer contains a mixture of multisampled and multisampled-render-to-texture
1151 // attachments, this function could be simultaneously doing a blit on one attachment and resolve
1152 // on another. For the most part, this means resolve semantics apply. However, as the resolve
1153 // path cannot be taken for multisampled-render-to-texture attachments, the distinction of
1154 // whether resolve is done for each attachment or blit is made.
1155 const bool isColorResolve =
1156 blitColorBuffer &&
1157 srcFramebufferVk->getColorReadRenderTarget()->getImageForCopy().getSamples() > 1;
1158 const bool isDepthStencilResolve =
1159 (blitDepthBuffer || blitStencilBuffer) &&
1160 srcFramebufferVk->getDepthStencilRenderTarget()->getImageForCopy().getSamples() > 1;
1161 const bool isResolve = isColorResolve || isDepthStencilResolve;
1162
1163 bool srcFramebufferFlippedY = contextVk->isViewportFlipEnabledForReadFBO();
1164 bool dstFramebufferFlippedY = contextVk->isViewportFlipEnabledForDrawFBO();
1165
1166 gl::Rectangle sourceArea = sourceAreaIn;
1167 gl::Rectangle destArea = destAreaIn;
1168
1169 // Note: GLES (all 3.x versions) require source and destination area to be identical when
1170 // resolving.
1171 ASSERT(!isResolve ||
1172 (sourceArea.x == destArea.x && sourceArea.y == destArea.y &&
1173 sourceArea.width == destArea.width && sourceArea.height == destArea.height));
1174
1175 gl::Rectangle srcFramebufferDimensions = srcFramebufferVk->getNonRotatedCompleteRenderArea();
1176 gl::Rectangle dstFramebufferDimensions = getNonRotatedCompleteRenderArea();
1177
1178 // If the destination is flipped in either direction, we will flip the source instead so that
1179 // the destination area is always unflipped.
1180 sourceArea = sourceArea.flip(destArea.isReversedX(), destArea.isReversedY());
1181 destArea = destArea.removeReversal();
1182
1183 // Calculate the stretch factor prior to any clipping, as it needs to remain constant.
1184 const double stretch[2] = {
1185 std::abs(sourceArea.width / static_cast<double>(destArea.width)),
1186 std::abs(sourceArea.height / static_cast<double>(destArea.height)),
1187 };
1188
1189 // Potentially make adjustments for pre-rotatation. To handle various cases (e.g. clipping)
1190 // and to not interrupt the normal flow of the code, different adjustments are made in
1191 // different parts of the code. These first adjustments are for whether or not to flip the
1192 // y-axis, and to note the overall rotation (regardless of whether it is the source or
1193 // destination that is rotated).
1194 SurfaceRotation srcFramebufferRotation = contextVk->getRotationReadFramebuffer();
1195 SurfaceRotation dstFramebufferRotation = contextVk->getRotationDrawFramebuffer();
1196 SurfaceRotation rotation = SurfaceRotation::Identity;
1197 // Both the source and destination cannot be rotated (which would indicate both are the default
1198 // framebuffer (i.e. swapchain image).
1199 ASSERT((srcFramebufferRotation == SurfaceRotation::Identity) ||
1200 (dstFramebufferRotation == SurfaceRotation::Identity));
1201 EarlyAdjustFlipYForPreRotation(srcFramebufferRotation, &rotation, &srcFramebufferFlippedY);
1202 EarlyAdjustFlipYForPreRotation(dstFramebufferRotation, &rotation, &dstFramebufferFlippedY);
1203
1204 // First, clip the source area to framebuffer. That requires transforming the destination area
1205 // to match the clipped source.
1206 gl::Rectangle absSourceArea = sourceArea.removeReversal();
1207 gl::Rectangle clippedSourceArea;
1208 if (!gl::ClipRectangle(srcFramebufferDimensions, absSourceArea, &clippedSourceArea))
1209 {
1210 return angle::Result::Continue;
1211 }
1212
1213 // Resize the destination area based on the new size of source. Note again that stretch is
1214 // calculated as SrcDimension/DestDimension.
1215 gl::Rectangle srcClippedDestArea;
1216 if (isResolve)
1217 {
1218 // Source and destination areas are identical in resolve (except rotate it, if appropriate).
1219 srcClippedDestArea = clippedSourceArea;
1220 AdjustBlitAreaForPreRotation(dstFramebufferRotation, clippedSourceArea,
1221 dstFramebufferDimensions, &srcClippedDestArea);
1222 }
1223 else if (clippedSourceArea == absSourceArea)
1224 {
1225 // If there was no clipping, keep destination area as is (except rotate it, if appropriate).
1226 srcClippedDestArea = destArea;
1227 AdjustBlitAreaForPreRotation(dstFramebufferRotation, destArea, dstFramebufferDimensions,
1228 &srcClippedDestArea);
1229 }
1230 else
1231 {
1232 // Shift destination area's x0,y0,x1,y1 by as much as the source area's got shifted (taking
1233 // stretching into account). Note that double is used as float doesn't have enough
1234 // precision near the end of int range.
1235 double x0Shift = std::round((clippedSourceArea.x - absSourceArea.x) / stretch[0]);
1236 double y0Shift = std::round((clippedSourceArea.y - absSourceArea.y) / stretch[1]);
1237 double x1Shift = std::round((absSourceArea.x1() - clippedSourceArea.x1()) / stretch[0]);
1238 double y1Shift = std::round((absSourceArea.y1() - clippedSourceArea.y1()) / stretch[1]);
1239
1240 // If the source area was reversed in any direction, the shift should be applied in the
1241 // opposite direction as well.
1242 if (sourceArea.isReversedX())
1243 {
1244 std::swap(x0Shift, x1Shift);
1245 }
1246
1247 if (sourceArea.isReversedY())
1248 {
1249 std::swap(y0Shift, y1Shift);
1250 }
1251
1252 srcClippedDestArea.x = destArea.x0() + static_cast<int>(x0Shift);
1253 srcClippedDestArea.y = destArea.y0() + static_cast<int>(y0Shift);
1254 int x1 = destArea.x1() - static_cast<int>(x1Shift);
1255 int y1 = destArea.y1() - static_cast<int>(y1Shift);
1256
1257 srcClippedDestArea.width = x1 - srcClippedDestArea.x;
1258 srcClippedDestArea.height = y1 - srcClippedDestArea.y;
1259
1260 // Rotate srcClippedDestArea if the destination is rotated
1261 if (dstFramebufferRotation != SurfaceRotation::Identity)
1262 {
1263 gl::Rectangle originalSrcClippedDestArea = srcClippedDestArea;
1264 AdjustBlitAreaForPreRotation(dstFramebufferRotation, originalSrcClippedDestArea,
1265 dstFramebufferDimensions, &srcClippedDestArea);
1266 }
1267 }
1268
1269 // If framebuffers are flipped in Y, flip the source and destination area (which define the
1270 // transformation regardless of clipping), as well as the blit area (which is the clipped
1271 // destination area).
1272 if (srcFramebufferFlippedY)
1273 {
1274 sourceArea.y = srcFramebufferDimensions.height - sourceArea.y;
1275 sourceArea.height = -sourceArea.height;
1276 }
1277 if (dstFramebufferFlippedY)
1278 {
1279 destArea.y = dstFramebufferDimensions.height - destArea.y;
1280 destArea.height = -destArea.height;
1281
1282 srcClippedDestArea.y =
1283 dstFramebufferDimensions.height - srcClippedDestArea.y - srcClippedDestArea.height;
1284 }
1285
1286 bool flipX = sourceArea.isReversedX() != destArea.isReversedX();
1287 bool flipY = sourceArea.isReversedY() != destArea.isReversedY();
1288
1289 // GLES doesn't allow flipping the parameters of glBlitFramebuffer if performing a resolve.
1290 ASSERT(!isResolve ||
1291 (flipX == false && flipY == (srcFramebufferFlippedY != dstFramebufferFlippedY)));
1292
1293 // Again, transfer the destination flip to source, so destination is unflipped. Note that
1294 // destArea was not reversed until the final possible Y-flip.
1295 ASSERT(!destArea.isReversedX());
1296 sourceArea = sourceArea.flip(false, destArea.isReversedY());
1297 destArea = destArea.removeReversal();
1298
1299 // Now that clipping and flipping is done, rotate certain values that will be used for
1300 // UtilsVk::BlitResolveParameters
1301 gl::Rectangle sourceAreaOld = sourceArea;
1302 gl::Rectangle destAreaOld = destArea;
1303 if (srcFramebufferRotation == rotation)
1304 {
1305 AdjustBlitAreaForPreRotation(srcFramebufferRotation, sourceAreaOld,
1306 srcFramebufferDimensions, &sourceArea);
1307 AdjustDimensionsAndFlipForPreRotation(srcFramebufferRotation, &srcFramebufferDimensions,
1308 &flipX, &flipY);
1309 }
1310 SurfaceRotation rememberDestFramebufferRotation = dstFramebufferRotation;
1311 if (srcFramebufferRotation == SurfaceRotation::Rotated90Degrees)
1312 {
1313 dstFramebufferRotation = rotation;
1314 }
1315 AdjustBlitAreaForPreRotation(dstFramebufferRotation, destAreaOld, dstFramebufferDimensions,
1316 &destArea);
1317 dstFramebufferRotation = rememberDestFramebufferRotation;
1318
1319 // Clip the destination area to the framebuffer size and scissor. Note that we don't care
1320 // about the source area anymore. The offset translation is done based on the original source
1321 // and destination rectangles. The stretch factor is already calculated as well.
1322 gl::Rectangle blitArea;
1323 if (!gl::ClipRectangle(getRotatedScissoredRenderArea(contextVk), srcClippedDestArea, &blitArea))
1324 {
1325 return angle::Result::Continue;
1326 }
1327
1328 bool noClip = blitArea == destArea && stretch[0] == 1.0f && stretch[1] == 1.0f;
1329 bool noFlip = !flipX && !flipY;
1330 bool disableFlippingBlitWithCommand =
1331 renderer->getFeatures().disableFlippingBlitWithCommand.enabled;
1332
1333 UtilsVk::BlitResolveParameters commonParams;
1334 commonParams.srcOffset[0] = sourceArea.x;
1335 commonParams.srcOffset[1] = sourceArea.y;
1336 commonParams.dstOffset[0] = destArea.x;
1337 commonParams.dstOffset[1] = destArea.y;
1338 commonParams.rotatedOffsetFactor[0] = std::abs(sourceArea.width);
1339 commonParams.rotatedOffsetFactor[1] = std::abs(sourceArea.height);
1340 commonParams.stretch[0] = static_cast<float>(stretch[0]);
1341 commonParams.stretch[1] = static_cast<float>(stretch[1]);
1342 commonParams.srcExtents[0] = srcFramebufferDimensions.width;
1343 commonParams.srcExtents[1] = srcFramebufferDimensions.height;
1344 commonParams.blitArea = blitArea;
1345 commonParams.linear = filter == GL_LINEAR && !isResolve;
1346 commonParams.flipX = flipX;
1347 commonParams.flipY = flipY;
1348 commonParams.rotation = rotation;
1349
1350 if (blitColorBuffer)
1351 {
1352 RenderTargetVk *readRenderTarget = srcFramebufferVk->getColorReadRenderTarget();
1353 UtilsVk::BlitResolveParameters params = commonParams;
1354 params.srcLayer = readRenderTarget->getLayerIndex();
1355
1356 // Multisampled images are not allowed to have mips.
1357 ASSERT(!isColorResolve || readRenderTarget->getLevelIndex() == gl::LevelIndex(0));
1358
1359 // If there was no clipping and the format capabilities allow us, use Vulkan's builtin blit.
1360 // The reason clipping is prohibited in this path is that due to rounding errors, it would
1361 // be hard to guarantee the image stretching remains perfect. That also allows us not to
1362 // have to transform back the destination clipping to source.
1363 //
1364 // Non-identity pre-rotation cases do not use Vulkan's builtin blit. Additionally, blits
1365 // between 3D and non-3D-non-layer-0 images are forbidden (possibly due to an oversight:
1366 // https://gitlab.khronos.org/vulkan/vulkan/-/issues/3490)
1367 //
1368 // For simplicity, we either blit all render targets with a Vulkan command, or none.
1369 bool canBlitWithCommand =
1370 !isColorResolve && noClip && (noFlip || !disableFlippingBlitWithCommand) &&
1371 HasSrcBlitFeature(renderer, readRenderTarget) && rotation == SurfaceRotation::Identity;
1372
1373 // If we need to reinterpret the colorspace of the read RenderTarget then the blit must be
1374 // done through a shader
1375 bool reinterpretsColorspace = readRenderTarget->hasColorspaceOverrideForRead();
1376 bool areChannelsBlitCompatible = true;
1377 bool areFormatsIdentical = true;
1378 bool colorAttachmentAlreadyInUse = false;
1379 for (size_t colorIndexGL : mState.getEnabledDrawBuffers())
1380 {
1381 RenderTargetVk *drawRenderTarget = mRenderTargetCache.getColors()[colorIndexGL];
1382 canBlitWithCommand =
1383 canBlitWithCommand && HasDstBlitFeature(renderer, drawRenderTarget);
1384 areChannelsBlitCompatible =
1385 areChannelsBlitCompatible &&
1386 AreSrcAndDstColorChannelsBlitCompatible(readRenderTarget, drawRenderTarget);
1387 areFormatsIdentical = areFormatsIdentical &&
1388 AreSrcAndDstFormatsIdentical(readRenderTarget, drawRenderTarget);
1389
1390 // If any color attachment of the draw framebuffer was already in use in the currently
1391 // started renderpass, don't reuse the renderpass for blit.
1392 colorAttachmentAlreadyInUse =
1393 colorAttachmentAlreadyInUse || contextVk->isRenderPassStartedAndUsesImage(
1394 drawRenderTarget->getImageForRenderPass());
1395
1396 // If we need to reinterpret the colorspace of the draw RenderTarget then the blit must
1397 // be done through a shader
1398 reinterpretsColorspace =
1399 reinterpretsColorspace || drawRenderTarget->hasColorspaceOverrideForWrite();
1400 }
1401
1402 // Now that all flipping is done, adjust the offsets for resolve and prerotation
1403 if (isColorResolve)
1404 {
1405 AdjustBlitResolveParametersForResolve(sourceArea, destArea, ¶ms);
1406 }
1407 AdjustBlitResolveParametersForPreRotation(rotation, srcFramebufferRotation, ¶ms);
1408
1409 if (canBlitWithCommand && areChannelsBlitCompatible && !reinterpretsColorspace)
1410 {
1411 for (size_t colorIndexGL : mState.getEnabledDrawBuffers())
1412 {
1413 RenderTargetVk *drawRenderTarget = mRenderTargetCache.getColors()[colorIndexGL];
1414 ANGLE_TRY(blitWithCommand(contextVk, sourceArea, destArea, readRenderTarget,
1415 drawRenderTarget, filter, true, false, false, flipX,
1416 flipY));
1417 }
1418 }
1419 // If we're not flipping or rotating, use Vulkan's builtin resolve.
1420 else if (isColorResolve && !flipX && !flipY && areChannelsBlitCompatible &&
1421 areFormatsIdentical && rotation == SurfaceRotation::Identity &&
1422 !reinterpretsColorspace)
1423 {
1424 // Resolving with a subpass resolve attachment has a few restrictions:
1425 // 1.) glBlitFramebuffer() needs to copy the read color attachment to all enabled
1426 // attachments in the draw framebuffer, but Vulkan requires a 1:1 relationship for
1427 // multisample attachments to resolve attachments in the render pass subpass.
1428 // Due to this, we currently only support using resolve attachments when there is a
1429 // single draw attachment enabled.
1430 // 2.) Using a subpass resolve attachment relies on using the render pass that performs
1431 // the draw to still be open, so it can be updated to use the resolve attachment to draw
1432 // into. If there's no render pass with commands, then the multisampled render pass is
1433 // already done and whose data is already flushed from the tile (in a tile-based
1434 // renderer), so there's no chance for the resolve attachment to take advantage of the
1435 // data already being present in the tile.
1436
1437 // Additionally, when resolving with a resolve attachment, the src and destination
1438 // offsets must match, the render area must match the resolve area, and there should be
1439 // no flipping or rotation. Fortunately, in GLES the blit source and destination areas
1440 // are already required to be identical.
1441 ASSERT(params.srcOffset[0] == params.dstOffset[0] &&
1442 params.srcOffset[1] == params.dstOffset[1]);
1443 bool canResolveWithSubpass = mState.getEnabledDrawBuffers().count() == 1 &&
1444 mCurrentFramebufferDesc.getLayerCount() == 1 &&
1445 contextVk->hasStartedRenderPassWithQueueSerial(
1446 srcFramebufferVk->getLastRenderPassQueueSerial()) &&
1447 !colorAttachmentAlreadyInUse;
1448
1449 if (canResolveWithSubpass)
1450 {
1451 const vk::RenderPassCommandBufferHelper &renderPassCommands =
1452 contextVk->getStartedRenderPassCommands();
1453 const vk::RenderPassDesc &renderPassDesc = renderPassCommands.getRenderPassDesc();
1454
1455 // Make sure that:
1456 // - The blit and render areas are identical
1457 // - There is no resolve attachment for the corresponding index already
1458 // Additionally, disable the optimization for a few corner cases that are
1459 // unrealistic and inconvenient.
1460 const uint32_t readColorIndexGL = srcFramebuffer->getState().getReadIndex();
1461 canResolveWithSubpass =
1462 blitArea == renderPassCommands.getRenderArea() &&
1463 !renderPassDesc.hasColorResolveAttachment(readColorIndexGL) &&
1464 AllowAddingResolveAttachmentsToSubpass(renderPassDesc);
1465 }
1466
1467 if (canResolveWithSubpass)
1468 {
1469 ANGLE_TRY(resolveColorWithSubpass(contextVk, params));
1470 }
1471 else
1472 {
1473 ANGLE_TRY(resolveColorWithCommand(contextVk, params,
1474 &readRenderTarget->getImageForCopy()));
1475 }
1476 }
1477 else
1478 {
1479 // Otherwise use a shader to do blit or resolve.
1480
1481 // Flush the render pass, which may incur a vkQueueSubmit, before taking any views.
1482 // Otherwise the view serials would not reflect the render pass they are really used in.
1483 // http://crbug.com/1272266#c22
1484 ANGLE_TRY(
1485 contextVk->flushCommandsAndEndRenderPass(RenderPassClosureReason::PrepareForBlit));
1486
1487 const vk::ImageView *copyImageView = nullptr;
1488 ANGLE_TRY(readRenderTarget->getCopyImageView(contextVk, ©ImageView));
1489 ANGLE_TRY(utilsVk.colorBlitResolve(
1490 contextVk, this, &readRenderTarget->getImageForCopy(), copyImageView, params));
1491 }
1492 }
1493
1494 if (blitDepthBuffer || blitStencilBuffer)
1495 {
1496 RenderTargetVk *readRenderTarget = srcFramebufferVk->getDepthStencilRenderTarget();
1497 RenderTargetVk *drawRenderTarget = mRenderTargetCache.getDepthStencil();
1498 UtilsVk::BlitResolveParameters params = commonParams;
1499 params.srcLayer = readRenderTarget->getLayerIndex();
1500
1501 // Multisampled images are not allowed to have mips.
1502 ASSERT(!isDepthStencilResolve || readRenderTarget->getLevelIndex() == gl::LevelIndex(0));
1503
1504 // Similarly, only blit if there's been no clipping or rotating.
1505 bool canBlitWithCommand =
1506 !isDepthStencilResolve && noClip && (noFlip || !disableFlippingBlitWithCommand) &&
1507 HasSrcBlitFeature(renderer, readRenderTarget) &&
1508 HasDstBlitFeature(renderer, drawRenderTarget) && rotation == SurfaceRotation::Identity;
1509 bool areChannelsBlitCompatible =
1510 AreSrcAndDstDepthStencilChannelsBlitCompatible(readRenderTarget, drawRenderTarget);
1511
1512 // glBlitFramebuffer requires that depth/stencil blits have matching formats.
1513 ASSERT(AreSrcAndDstFormatsIdentical(readRenderTarget, drawRenderTarget));
1514
1515 if (canBlitWithCommand && areChannelsBlitCompatible)
1516 {
1517 ANGLE_TRY(blitWithCommand(contextVk, sourceArea, destArea, readRenderTarget,
1518 drawRenderTarget, filter, false, blitDepthBuffer,
1519 blitStencilBuffer, flipX, flipY));
1520 }
1521 else
1522 {
1523 vk::ImageHelper *depthStencilImage = &readRenderTarget->getImageForCopy();
1524
1525 VkImageAspectFlags resolveAspects = 0;
1526 if (blitDepthBuffer)
1527 {
1528 resolveAspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
1529 }
1530 if (blitStencilBuffer)
1531 {
1532 resolveAspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
1533 }
1534
1535 // See comment on canResolveWithSubpass for the color path.
1536 bool canResolveWithSubpass =
1537 isDepthStencilResolve &&
1538 !renderer->getFeatures().disableDepthStencilResolveThroughAttachment.enabled &&
1539 areChannelsBlitCompatible && mCurrentFramebufferDesc.getLayerCount() == 1 &&
1540 contextVk->hasStartedRenderPassWithQueueSerial(
1541 srcFramebufferVk->getLastRenderPassQueueSerial()) &&
1542 !contextVk->isRenderPassStartedAndUsesImage(
1543 drawRenderTarget->getImageForRenderPass()) &&
1544 noFlip && rotation == SurfaceRotation::Identity;
1545
1546 if (canResolveWithSubpass)
1547 {
1548 const vk::RenderPassCommandBufferHelper &renderPassCommands =
1549 contextVk->getStartedRenderPassCommands();
1550 const vk::RenderPassDesc &renderPassDesc = renderPassCommands.getRenderPassDesc();
1551
1552 const VkImageAspectFlags depthStencilImageAspects =
1553 depthStencilImage->getAspectFlags();
1554 const bool resolvesAllAspects =
1555 (resolveAspects & depthStencilImageAspects) == depthStencilImageAspects;
1556
1557 // Make sure that:
1558 // - The blit and render areas are identical
1559 // - There is no resolve attachment already
1560 // Additionally, disable the optimization for a few corner cases that are
1561 // unrealistic and inconvenient.
1562 //
1563 // Note: currently, if two separate `glBlitFramebuffer` calls are made for each
1564 // aspect, only the first one is optimized as a resolve attachment. Applications
1565 // should use one `glBlitFramebuffer` call with both aspects if they want to resolve
1566 // both.
1567 canResolveWithSubpass =
1568 blitArea == renderPassCommands.getRenderArea() &&
1569 (resolvesAllAspects ||
1570 renderer->getFeatures().supportsDepthStencilIndependentResolveNone.enabled) &&
1571 !renderPassDesc.hasDepthStencilResolveAttachment() &&
1572 AllowAddingResolveAttachmentsToSubpass(renderPassDesc);
1573 }
1574
1575 if (canResolveWithSubpass)
1576 {
1577 ANGLE_TRY(resolveDepthStencilWithSubpass(contextVk, params, resolveAspects));
1578 }
1579 else
1580 {
1581 // See comment for the draw-based color blit. The render pass must be flushed
1582 // before creating the views.
1583 ANGLE_TRY(contextVk->flushCommandsAndEndRenderPass(
1584 RenderPassClosureReason::PrepareForBlit));
1585
1586 // Now that all flipping is done, adjust the offsets for resolve and prerotation
1587 if (isDepthStencilResolve)
1588 {
1589 AdjustBlitResolveParametersForResolve(sourceArea, destArea, ¶ms);
1590 }
1591 AdjustBlitResolveParametersForPreRotation(rotation, srcFramebufferRotation,
1592 ¶ms);
1593
1594 // Get depth- and stencil-only views for reading.
1595 const vk::ImageView *depthView = nullptr;
1596 const vk::ImageView *stencilView = nullptr;
1597
1598 if (blitDepthBuffer)
1599 {
1600 ANGLE_TRY(readRenderTarget->getDepthOrStencilImageViewForCopy(
1601 contextVk, VK_IMAGE_ASPECT_DEPTH_BIT, &depthView));
1602 }
1603
1604 if (blitStencilBuffer)
1605 {
1606 ANGLE_TRY(readRenderTarget->getDepthOrStencilImageViewForCopy(
1607 contextVk, VK_IMAGE_ASPECT_STENCIL_BIT, &stencilView));
1608 }
1609
1610 // If shader stencil export is not possible, defer stencil blit/resolve to another
1611 // pass.
1612 const bool hasShaderStencilExport =
1613 renderer->getFeatures().supportsShaderStencilExport.enabled;
1614
1615 // Blit depth. If shader stencil export is present, blit stencil as well.
1616 if (blitDepthBuffer || (blitStencilBuffer && hasShaderStencilExport))
1617 {
1618 ANGLE_TRY(utilsVk.depthStencilBlitResolve(
1619 contextVk, this, depthStencilImage, depthView,
1620 hasShaderStencilExport ? stencilView : nullptr, params));
1621 }
1622
1623 // If shader stencil export is not present, blit stencil through a different path.
1624 if (blitStencilBuffer && !hasShaderStencilExport)
1625 {
1626 ANGLE_VK_PERF_WARNING(
1627 contextVk, GL_DEBUG_SEVERITY_LOW,
1628 "Inefficient BlitFramebuffer operation on the stencil aspect "
1629 "due to lack of shader stencil export support");
1630 ANGLE_TRY(utilsVk.stencilBlitResolveNoShaderExport(
1631 contextVk, this, depthStencilImage, stencilView, params));
1632 }
1633 }
1634 }
1635 }
1636
1637 return angle::Result::Continue;
1638 }
1639
releaseCurrentFramebuffer(ContextVk * contextVk)1640 void FramebufferVk::releaseCurrentFramebuffer(ContextVk *contextVk)
1641 {
1642 if (mIsCurrentFramebufferCached)
1643 {
1644 mCurrentFramebuffer.release();
1645 }
1646 else
1647 {
1648 contextVk->addGarbage(&mCurrentFramebuffer);
1649 }
1650 }
1651
updateLayerCount()1652 void FramebufferVk::updateLayerCount()
1653 {
1654 uint32_t layerCount = std::numeric_limits<uint32_t>::max();
1655
1656 // Color attachments.
1657 const auto &colorRenderTargets = mRenderTargetCache.getColors();
1658 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
1659 {
1660 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
1661 ASSERT(colorRenderTarget);
1662 layerCount = std::min(layerCount, colorRenderTarget->getLayerCount());
1663 }
1664
1665 // Depth/stencil attachment.
1666 RenderTargetVk *depthStencilRenderTarget = getDepthStencilRenderTarget();
1667 if (depthStencilRenderTarget)
1668 {
1669 layerCount = std::min(layerCount, depthStencilRenderTarget->getLayerCount());
1670 }
1671
1672 if (layerCount == std::numeric_limits<uint32_t>::max())
1673 {
1674 layerCount = mState.getDefaultLayers();
1675 }
1676
1677 // While layer count and view count are mutually exclusive, they result in different render
1678 // passes (and thus framebuffers). For multiview, layer count is set to view count and a flag
1679 // signifies that the framebuffer is multiview (as opposed to layered).
1680 const bool isMultiview = mState.isMultiview();
1681 if (isMultiview)
1682 {
1683 layerCount = mState.getNumViews();
1684 }
1685
1686 mCurrentFramebufferDesc.updateLayerCount(layerCount);
1687 mCurrentFramebufferDesc.updateIsMultiview(isMultiview);
1688 }
1689
ensureFragmentShadingRateImageAndViewInitialized(ContextVk * contextVk,const uint32_t fragmentShadingRateAttachmentWidth,const uint32_t fragmentShadingRateAttachmentHeight)1690 angle::Result FramebufferVk::ensureFragmentShadingRateImageAndViewInitialized(
1691 ContextVk *contextVk,
1692 const uint32_t fragmentShadingRateAttachmentWidth,
1693 const uint32_t fragmentShadingRateAttachmentHeight)
1694 {
1695 vk::Renderer *renderer = contextVk->getRenderer();
1696
1697 // Release current valid image iff attachment extents need to change.
1698 if (mFragmentShadingRateImage.valid() &&
1699 (mFragmentShadingRateImage.getExtents().width != fragmentShadingRateAttachmentWidth ||
1700 mFragmentShadingRateImage.getExtents().height != fragmentShadingRateAttachmentHeight))
1701 {
1702 mFragmentShadingRateImageView.release(renderer, mFragmentShadingRateImage.getResourceUse());
1703 mFragmentShadingRateImage.releaseImage(renderer);
1704 }
1705
1706 if (!mFragmentShadingRateImage.valid())
1707 {
1708 VkImageUsageFlags imageUsageFlags =
1709 VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR |
1710 VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1711 // Add storage usage iff we intend to generate data using compute shader
1712 if (!contextVk->getFeatures().generateFragmentShadingRateAttchementWithCpu.enabled)
1713 {
1714 imageUsageFlags |= VK_IMAGE_USAGE_STORAGE_BIT;
1715 }
1716
1717 ANGLE_TRY(mFragmentShadingRateImage.init(
1718 contextVk, gl::TextureType::_2D,
1719 VkExtent3D{fragmentShadingRateAttachmentWidth, fragmentShadingRateAttachmentHeight, 1},
1720 renderer->getFormat(angle::FormatID::R8_UINT), 1, imageUsageFlags, gl::LevelIndex(0), 1,
1721 1, false, contextVk->getProtectionType() == vk::ProtectionType::Protected));
1722
1723 ANGLE_TRY(contextVk->initImageAllocation(
1724 &mFragmentShadingRateImage, false, renderer->getMemoryProperties(),
1725 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vk::MemoryAllocationType::TextureImage));
1726
1727 mFragmentShadingRateImageView.init(renderer);
1728 ANGLE_TRY(mFragmentShadingRateImageView.initFragmentShadingRateView(
1729 contextVk, &mFragmentShadingRateImage));
1730 }
1731
1732 return angle::Result::Continue;
1733 }
1734
generateFragmentShadingRateWithCPU(ContextVk * contextVk,const uint32_t fragmentShadingRateWidth,const uint32_t fragmentShadingRateHeight,const uint32_t fragmentShadingRateBlockWidth,const uint32_t fragmentShadingRateBlockHeight,const uint32_t foveatedAttachmentWidth,const uint32_t foveatedAttachmentHeight,const std::vector<gl::FocalPoint> & activeFocalPoints)1735 angle::Result FramebufferVk::generateFragmentShadingRateWithCPU(
1736 ContextVk *contextVk,
1737 const uint32_t fragmentShadingRateWidth,
1738 const uint32_t fragmentShadingRateHeight,
1739 const uint32_t fragmentShadingRateBlockWidth,
1740 const uint32_t fragmentShadingRateBlockHeight,
1741 const uint32_t foveatedAttachmentWidth,
1742 const uint32_t foveatedAttachmentHeight,
1743 const std::vector<gl::FocalPoint> &activeFocalPoints)
1744 {
1745 // Fill in image with fragment shading rate data
1746 size_t bufferSize = fragmentShadingRateWidth * fragmentShadingRateHeight;
1747 VkBufferCreateInfo bufferCreateInfo = {};
1748 bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1749 bufferCreateInfo.size = bufferSize;
1750 bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
1751 bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1752 vk::RendererScoped<vk::BufferHelper> stagingBuffer(contextVk->getRenderer());
1753 vk::BufferHelper *buffer = &stagingBuffer.get();
1754 ANGLE_TRY(buffer->init(contextVk, bufferCreateInfo, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT));
1755 uint8_t *mappedBuffer;
1756 ANGLE_TRY(buffer->map(contextVk, &mappedBuffer));
1757 uint8_t val = 0;
1758 memset(mappedBuffer, 0, bufferSize);
1759
1760 // The spec requires min_pixel_density to be computed thusly -
1761 //
1762 // min_pixel_density=0.;
1763 // for(int i=0;i<focalPointsPerLayer;++i)
1764 // {
1765 // focal_point_density = 1./max((focalX[i]-px)^2*gainX[i]^2+
1766 // (focalY[i]-py)^2*gainY[i]^2-foveaArea[i],1.);
1767 //
1768 // min_pixel_density=max(min_pixel_density,focal_point_density);
1769 // }
1770 float minPixelDensity = 0.0f;
1771 float focalPointDensity = 0.0f;
1772 for (uint32_t y = 0; y < fragmentShadingRateHeight; y++)
1773 {
1774 for (uint32_t x = 0; x < fragmentShadingRateWidth; x++)
1775 {
1776 minPixelDensity = 0.0f;
1777 float px =
1778 (static_cast<float>(x) * fragmentShadingRateBlockWidth / foveatedAttachmentWidth -
1779 0.5f) *
1780 2.0f;
1781 float py =
1782 (static_cast<float>(y) * fragmentShadingRateBlockHeight / foveatedAttachmentHeight -
1783 0.5f) *
1784 2.0f;
1785 focalPointDensity = 0.0f;
1786 for (const gl::FocalPoint &focalPoint : activeFocalPoints)
1787 {
1788 float density = 1.0f / std::max(std::pow(focalPoint.focalX - px, 2.0f) *
1789 std::pow(focalPoint.gainX, 2.0f) +
1790 std::pow(focalPoint.focalY - py, 2.0f) *
1791 std::pow(focalPoint.gainY, 2.0f) -
1792 focalPoint.foveaArea,
1793 1.0f);
1794
1795 // When focal points are overlapping choose the highest quality of all
1796 if (density > focalPointDensity)
1797 {
1798 focalPointDensity = density;
1799 }
1800 }
1801 minPixelDensity = std::max(minPixelDensity, focalPointDensity);
1802
1803 // https://docs.vulkan.org/spec/latest/chapters/primsrast.html#primsrast-fragment-shading-rate-attachment
1804 //
1805 // w = 2^((texel/4) & 3)
1806 // h = 2^(texel & 3)
1807 // `texel` would then be => log2(w) << 2 | log2(h).
1808 //
1809 // 1) The supported shading rates are - 1x1, 1x2, 2x1, 2x2
1810 // 2) log2(1) == 0, log2(2) == 1
1811 if (minPixelDensity > 0.75f)
1812 {
1813 // Use shading rate 1x1
1814 val = 0;
1815 }
1816 else if (minPixelDensity > 0.5f)
1817 {
1818 // Use shading rate 2x1
1819 val = (1 << 2);
1820 }
1821 else
1822 {
1823 // Use shading rate 2x2
1824 val = (1 << 2) | 1;
1825 }
1826 mappedBuffer[y * fragmentShadingRateWidth + x] = val;
1827 }
1828 }
1829
1830 ANGLE_TRY(buffer->flush(contextVk->getRenderer(), 0, buffer->getSize()));
1831 buffer->unmap(contextVk->getRenderer());
1832 // copy data from staging buffer to image
1833 vk::CommandBufferAccess access;
1834 access.onBufferTransferRead(buffer);
1835 access.onImageTransferWrite(gl::LevelIndex(0), 1, 0, 1, VK_IMAGE_ASPECT_COLOR_BIT,
1836 &mFragmentShadingRateImage);
1837 vk::OutsideRenderPassCommandBuffer *dataUpload;
1838 ANGLE_TRY(contextVk->getOutsideRenderPassCommandBuffer(access, &dataUpload));
1839 VkBufferImageCopy copy = {};
1840 copy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1841 copy.imageSubresource.layerCount = 1;
1842 copy.imageExtent.depth = 1;
1843 copy.imageExtent.width = fragmentShadingRateWidth;
1844 copy.imageExtent.height = fragmentShadingRateHeight;
1845 dataUpload->copyBufferToImage(buffer->getBuffer().getHandle(),
1846 mFragmentShadingRateImage.getImage(),
1847 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©);
1848
1849 return angle::Result::Continue;
1850 }
1851
generateFragmentShadingRateWithCompute(ContextVk * contextVk,const uint32_t fragmentShadingRateWidth,const uint32_t fragmentShadingRateHeight,const uint32_t fragmentShadingRateBlockWidth,const uint32_t fragmentShadingRateBlockHeight,const uint32_t foveatedAttachmentWidth,const uint32_t foveatedAttachmentHeight,const std::vector<gl::FocalPoint> & activeFocalPoints)1852 angle::Result FramebufferVk::generateFragmentShadingRateWithCompute(
1853 ContextVk *contextVk,
1854 const uint32_t fragmentShadingRateWidth,
1855 const uint32_t fragmentShadingRateHeight,
1856 const uint32_t fragmentShadingRateBlockWidth,
1857 const uint32_t fragmentShadingRateBlockHeight,
1858 const uint32_t foveatedAttachmentWidth,
1859 const uint32_t foveatedAttachmentHeight,
1860 const std::vector<gl::FocalPoint> &activeFocalPoints)
1861 {
1862 ASSERT(activeFocalPoints.size() < gl::IMPLEMENTATION_MAX_FOCAL_POINTS);
1863
1864 UtilsVk::GenerateFragmentShadingRateParameters shadingRateParams;
1865 shadingRateParams.textureWidth = foveatedAttachmentWidth;
1866 shadingRateParams.textureHeight = foveatedAttachmentHeight;
1867 shadingRateParams.attachmentBlockWidth = fragmentShadingRateBlockWidth;
1868 shadingRateParams.attachmentBlockHeight = fragmentShadingRateBlockHeight;
1869 shadingRateParams.attachmentWidth = fragmentShadingRateWidth;
1870 shadingRateParams.attachmentHeight = fragmentShadingRateHeight;
1871 shadingRateParams.numFocalPoints = 0;
1872
1873 for (const gl::FocalPoint &focalPoint : activeFocalPoints)
1874 {
1875 ASSERT(focalPoint.valid());
1876 shadingRateParams.focalPoints[shadingRateParams.numFocalPoints] = focalPoint;
1877 shadingRateParams.numFocalPoints++;
1878 }
1879
1880 return contextVk->getUtils().generateFragmentShadingRate(
1881 contextVk, &mFragmentShadingRateImage, &mFragmentShadingRateImageView, shadingRateParams);
1882 }
1883
updateFragmentShadingRateAttachment(ContextVk * contextVk,const gl::FoveationState & foveationState,const gl::Extents & foveatedAttachmentSize)1884 angle::Result FramebufferVk::updateFragmentShadingRateAttachment(
1885 ContextVk *contextVk,
1886 const gl::FoveationState &foveationState,
1887 const gl::Extents &foveatedAttachmentSize)
1888 {
1889 const VkExtent2D fragmentShadingRateExtent =
1890 contextVk->getRenderer()->getMaxFragmentShadingRateAttachmentTexelSize();
1891 const uint32_t fragmentShadingRateBlockWidth = fragmentShadingRateExtent.width;
1892 const uint32_t fragmentShadingRateBlockHeight = fragmentShadingRateExtent.height;
1893 const uint32_t foveatedAttachmentWidth = foveatedAttachmentSize.width;
1894 const uint32_t foveatedAttachmentHeight = foveatedAttachmentSize.height;
1895 const uint32_t fragmentShadingRateWidth =
1896 UnsignedCeilDivide(foveatedAttachmentWidth, fragmentShadingRateBlockWidth);
1897 const uint32_t fragmentShadingRateHeight =
1898 UnsignedCeilDivide(foveatedAttachmentHeight, fragmentShadingRateBlockHeight);
1899
1900 ANGLE_TRY(ensureFragmentShadingRateImageAndViewInitialized(contextVk, fragmentShadingRateWidth,
1901 fragmentShadingRateHeight));
1902 ASSERT(mFragmentShadingRateImage.valid());
1903
1904 std::vector<gl::FocalPoint> activeFocalPoints;
1905 for (uint32_t point = 0; point < gl::IMPLEMENTATION_MAX_FOCAL_POINTS; point++)
1906 {
1907 const gl::FocalPoint &focalPoint = foveationState.getFocalPoint(0, point);
1908 if (focalPoint.valid())
1909 {
1910 activeFocalPoints.push_back(focalPoint);
1911 }
1912 }
1913 ASSERT(activeFocalPoints.size() > 0);
1914
1915 if (contextVk->getFeatures().generateFragmentShadingRateAttchementWithCpu.enabled)
1916 {
1917 ANGLE_TRY(generateFragmentShadingRateWithCPU(
1918 contextVk, fragmentShadingRateWidth, fragmentShadingRateHeight,
1919 fragmentShadingRateBlockWidth, fragmentShadingRateBlockHeight, foveatedAttachmentWidth,
1920 foveatedAttachmentHeight, activeFocalPoints));
1921 }
1922 else
1923 {
1924 ANGLE_TRY(generateFragmentShadingRateWithCompute(
1925 contextVk, fragmentShadingRateWidth, fragmentShadingRateHeight,
1926 fragmentShadingRateBlockWidth, fragmentShadingRateBlockHeight, foveatedAttachmentWidth,
1927 foveatedAttachmentHeight, activeFocalPoints));
1928 }
1929
1930 return angle::Result::Continue;
1931 }
1932
updateFoveationState(ContextVk * contextVk,const gl::FoveationState & newFoveationState,const gl::Extents & foveatedAttachmentSize)1933 angle::Result FramebufferVk::updateFoveationState(ContextVk *contextVk,
1934 const gl::FoveationState &newFoveationState,
1935 const gl::Extents &foveatedAttachmentSize)
1936 {
1937 const bool isFoveationEnabled = newFoveationState.isFoveated();
1938 vk::ImageOrBufferViewSubresourceSerial serial = vk::kInvalidImageOrBufferViewSubresourceSerial;
1939 if (isFoveationEnabled)
1940 {
1941 ANGLE_TRY(updateFragmentShadingRateAttachment(contextVk, newFoveationState,
1942 foveatedAttachmentSize));
1943 ASSERT(mFragmentShadingRateImage.valid());
1944
1945 serial = mFragmentShadingRateImageView.getSubresourceSerial(gl::LevelIndex(0), 1, 0,
1946 vk::LayerMode::All);
1947 }
1948
1949 // Update state after the possible failure point.
1950 mFoveationState = newFoveationState;
1951 mCurrentFramebufferDesc.updateFragmentShadingRate(serial);
1952 // mRenderPassDesc will be updated later in updateRenderPassDesc() in case if
1953 // mCurrentFramebufferDesc was changed.
1954 return angle::Result::Continue;
1955 }
1956
resolveColorWithSubpass(ContextVk * contextVk,const UtilsVk::BlitResolveParameters & params)1957 angle::Result FramebufferVk::resolveColorWithSubpass(ContextVk *contextVk,
1958 const UtilsVk::BlitResolveParameters ¶ms)
1959 {
1960 // Vulkan requires a 1:1 relationship for multisample attachments to resolve attachments in the
1961 // render pass subpass. Due to this, we currently only support using resolve attachments when
1962 // there is a single draw attachment enabled.
1963 ASSERT(mState.getEnabledDrawBuffers().count() == 1);
1964 uint32_t drawColorIndexGL = static_cast<uint32_t>(*mState.getEnabledDrawBuffers().begin());
1965 RenderTargetVk *drawRenderTarget = mRenderTargetCache.getColors()[drawColorIndexGL];
1966 const vk::ImageView *resolveImageView = nullptr;
1967 ANGLE_TRY(drawRenderTarget->getImageView(contextVk, &resolveImageView));
1968
1969 const gl::Framebuffer *srcFramebuffer = contextVk->getState().getReadFramebuffer();
1970 uint32_t readColorIndexGL = srcFramebuffer->getState().getReadIndex();
1971
1972 vk::RenderPassCommandBufferHelper &renderPassCommands =
1973 contextVk->getStartedRenderPassCommands();
1974 ASSERT(!renderPassCommands.getRenderPassDesc().hasColorResolveAttachment(readColorIndexGL));
1975
1976 drawRenderTarget->onColorResolve(contextVk, mCurrentFramebufferDesc.getLayerCount(),
1977 readColorIndexGL, *resolveImageView);
1978
1979 // The render pass is already closed because of the change in the draw buffer. Just don't let
1980 // it reactivate now that it has a resolve attachment.
1981 contextVk->disableRenderPassReactivation();
1982
1983 return angle::Result::Continue;
1984 }
1985
resolveDepthStencilWithSubpass(ContextVk * contextVk,const UtilsVk::BlitResolveParameters & params,VkImageAspectFlags aspects)1986 angle::Result FramebufferVk::resolveDepthStencilWithSubpass(
1987 ContextVk *contextVk,
1988 const UtilsVk::BlitResolveParameters ¶ms,
1989 VkImageAspectFlags aspects)
1990 {
1991 RenderTargetVk *drawRenderTarget = mRenderTargetCache.getDepthStencil();
1992 const vk::ImageView *resolveImageView = nullptr;
1993 ANGLE_TRY(drawRenderTarget->getImageView(contextVk, &resolveImageView));
1994
1995 vk::RenderPassCommandBufferHelper &renderPassCommands =
1996 contextVk->getStartedRenderPassCommands();
1997 ASSERT(!renderPassCommands.getRenderPassDesc().hasDepthStencilResolveAttachment());
1998
1999 drawRenderTarget->onDepthStencilResolve(contextVk, mCurrentFramebufferDesc.getLayerCount(),
2000 aspects, *resolveImageView);
2001
2002 // The render pass is already closed because of the change in the draw buffer. Just don't let
2003 // it reactivate now that it has a resolve attachment.
2004 contextVk->disableRenderPassReactivation();
2005
2006 return angle::Result::Continue;
2007 }
2008
resolveColorWithCommand(ContextVk * contextVk,const UtilsVk::BlitResolveParameters & params,vk::ImageHelper * srcImage)2009 angle::Result FramebufferVk::resolveColorWithCommand(ContextVk *contextVk,
2010 const UtilsVk::BlitResolveParameters ¶ms,
2011 vk::ImageHelper *srcImage)
2012 {
2013 vk::CommandBufferAccess access;
2014 access.onImageTransferRead(VK_IMAGE_ASPECT_COLOR_BIT, srcImage);
2015
2016 for (size_t colorIndexGL : mState.getEnabledDrawBuffers())
2017 {
2018 RenderTargetVk *drawRenderTarget = mRenderTargetCache.getColors()[colorIndexGL];
2019 vk::ImageHelper &dstImage = drawRenderTarget->getImageForWrite();
2020
2021 access.onImageTransferWrite(drawRenderTarget->getLevelIndex(), 1,
2022 drawRenderTarget->getLayerIndex(), 1, VK_IMAGE_ASPECT_COLOR_BIT,
2023 &dstImage);
2024 }
2025
2026 vk::OutsideRenderPassCommandBuffer *commandBuffer;
2027 ANGLE_TRY(contextVk->getOutsideRenderPassCommandBuffer(access, &commandBuffer));
2028
2029 VkImageResolve resolveRegion = {};
2030 resolveRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2031 resolveRegion.srcSubresource.mipLevel = 0;
2032 resolveRegion.srcSubresource.baseArrayLayer = params.srcLayer;
2033 resolveRegion.srcSubresource.layerCount = 1;
2034 resolveRegion.srcOffset.x = params.blitArea.x;
2035 resolveRegion.srcOffset.y = params.blitArea.y;
2036 resolveRegion.srcOffset.z = 0;
2037 resolveRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
2038 resolveRegion.dstSubresource.layerCount = 1;
2039 resolveRegion.dstOffset.x = params.blitArea.x;
2040 resolveRegion.dstOffset.y = params.blitArea.y;
2041 resolveRegion.dstOffset.z = 0;
2042 resolveRegion.extent.width = params.blitArea.width;
2043 resolveRegion.extent.height = params.blitArea.height;
2044 resolveRegion.extent.depth = 1;
2045
2046 angle::VulkanPerfCounters &perfCounters = contextVk->getPerfCounters();
2047 for (size_t colorIndexGL : mState.getEnabledDrawBuffers())
2048 {
2049 RenderTargetVk *drawRenderTarget = mRenderTargetCache.getColors()[colorIndexGL];
2050 vk::ImageHelper &dstImage = drawRenderTarget->getImageForWrite();
2051
2052 vk::LevelIndex levelVk = dstImage.toVkLevel(drawRenderTarget->getLevelIndex());
2053 resolveRegion.dstSubresource.mipLevel = levelVk.get();
2054 resolveRegion.dstSubresource.baseArrayLayer = drawRenderTarget->getLayerIndex();
2055
2056 srcImage->resolve(&dstImage, resolveRegion, commandBuffer);
2057
2058 perfCounters.resolveImageCommands++;
2059 }
2060
2061 return angle::Result::Continue;
2062 }
2063
checkStatus(const gl::Context * context) const2064 gl::FramebufferStatus FramebufferVk::checkStatus(const gl::Context *context) const
2065 {
2066 // if we have both a depth and stencil buffer, they must refer to the same object
2067 // since we only support packed_depth_stencil and not separate depth and stencil
2068 if (mState.hasSeparateDepthAndStencilAttachments())
2069 {
2070 return gl::FramebufferStatus::Incomplete(
2071 GL_FRAMEBUFFER_UNSUPPORTED,
2072 gl::err::kFramebufferIncompleteUnsupportedSeparateDepthStencilBuffers);
2073 }
2074
2075 return gl::FramebufferStatus::Complete();
2076 }
2077
invalidateImpl(ContextVk * contextVk,size_t count,const GLenum * attachments,bool isSubInvalidate,const gl::Rectangle & invalidateArea)2078 angle::Result FramebufferVk::invalidateImpl(ContextVk *contextVk,
2079 size_t count,
2080 const GLenum *attachments,
2081 bool isSubInvalidate,
2082 const gl::Rectangle &invalidateArea)
2083 {
2084 gl::DrawBufferMask invalidateColorBuffers;
2085 bool invalidateDepthBuffer = false;
2086 bool invalidateStencilBuffer = false;
2087
2088 for (size_t i = 0; i < count; ++i)
2089 {
2090 const GLenum attachment = attachments[i];
2091
2092 switch (attachment)
2093 {
2094 case GL_DEPTH:
2095 case GL_DEPTH_ATTACHMENT:
2096 invalidateDepthBuffer = true;
2097 break;
2098 case GL_STENCIL:
2099 case GL_STENCIL_ATTACHMENT:
2100 invalidateStencilBuffer = true;
2101 break;
2102 case GL_DEPTH_STENCIL_ATTACHMENT:
2103 invalidateDepthBuffer = true;
2104 invalidateStencilBuffer = true;
2105 break;
2106 default:
2107 ASSERT(
2108 (attachment >= GL_COLOR_ATTACHMENT0 && attachment <= GL_COLOR_ATTACHMENT15) ||
2109 (attachment == GL_COLOR));
2110
2111 invalidateColorBuffers.set(
2112 attachment == GL_COLOR ? 0u : (attachment - GL_COLOR_ATTACHMENT0));
2113 }
2114 }
2115
2116 // Shouldn't try to issue deferred clears if invalidating sub framebuffer.
2117 ASSERT(mDeferredClears.empty() || !isSubInvalidate);
2118
2119 // Remove deferred clears for the invalidated attachments.
2120 if (invalidateDepthBuffer)
2121 {
2122 mDeferredClears.reset(vk::kUnpackedDepthIndex);
2123 }
2124 if (invalidateStencilBuffer)
2125 {
2126 mDeferredClears.reset(vk::kUnpackedStencilIndex);
2127 }
2128 for (size_t colorIndexGL : mState.getEnabledDrawBuffers())
2129 {
2130 if (invalidateColorBuffers.test(colorIndexGL))
2131 {
2132 mDeferredClears.reset(colorIndexGL);
2133 }
2134 }
2135
2136 // If there are still deferred clears, restage them. See relevant comment in invalidateSub.
2137 restageDeferredClears(contextVk);
2138
2139 const auto &colorRenderTargets = mRenderTargetCache.getColors();
2140 RenderTargetVk *depthStencilRenderTarget = mRenderTargetCache.getDepthStencil();
2141
2142 // If not a partial invalidate, mark the contents of the invalidated attachments as undefined,
2143 // so their loadOp can be set to DONT_CARE in the following render pass.
2144 if (!isSubInvalidate)
2145 {
2146 for (size_t colorIndexGL : mState.getEnabledDrawBuffers())
2147 {
2148 if (invalidateColorBuffers.test(colorIndexGL))
2149 {
2150 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
2151 ASSERT(colorRenderTarget);
2152
2153 bool preferToKeepContentsDefined = false;
2154 colorRenderTarget->invalidateEntireContent(contextVk, &preferToKeepContentsDefined);
2155 if (preferToKeepContentsDefined)
2156 {
2157 invalidateColorBuffers.reset(colorIndexGL);
2158 }
2159 }
2160 }
2161
2162 // If we have a depth / stencil render target, invalidate its aspects.
2163 if (depthStencilRenderTarget)
2164 {
2165 if (invalidateDepthBuffer)
2166 {
2167 bool preferToKeepContentsDefined = false;
2168 depthStencilRenderTarget->invalidateEntireContent(contextVk,
2169 &preferToKeepContentsDefined);
2170 if (preferToKeepContentsDefined)
2171 {
2172 invalidateDepthBuffer = false;
2173 }
2174 }
2175 if (invalidateStencilBuffer)
2176 {
2177 bool preferToKeepContentsDefined = false;
2178 depthStencilRenderTarget->invalidateEntireStencilContent(
2179 contextVk, &preferToKeepContentsDefined);
2180 if (preferToKeepContentsDefined)
2181 {
2182 invalidateStencilBuffer = false;
2183 }
2184 }
2185 }
2186 }
2187
2188 // To ensure we invalidate the right renderpass we require that the current framebuffer be the
2189 // same as the current renderpass' framebuffer. E.g. prevent sequence like:
2190 //- Bind FBO 1, draw
2191 //- Bind FBO 2, draw
2192 //- Bind FBO 1, invalidate D/S
2193 // to invalidate the D/S of FBO 2 since it would be the currently active renderpass.
2194 if (contextVk->hasStartedRenderPassWithQueueSerial(mLastRenderPassQueueSerial))
2195 {
2196 // Mark the invalidated attachments in the render pass for loadOp and storeOp determination
2197 // at its end.
2198 vk::PackedAttachmentIndex colorIndexVk(0);
2199 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
2200 {
2201 if (mState.getEnabledDrawBuffers()[colorIndexGL] &&
2202 invalidateColorBuffers.test(colorIndexGL))
2203 {
2204 contextVk->getStartedRenderPassCommands().invalidateRenderPassColorAttachment(
2205 contextVk->getState(), colorIndexGL, colorIndexVk, invalidateArea);
2206 }
2207 ++colorIndexVk;
2208 }
2209
2210 if (depthStencilRenderTarget)
2211 {
2212 const gl::DepthStencilState &dsState = contextVk->getState().getDepthStencilState();
2213 if (invalidateDepthBuffer)
2214 {
2215 contextVk->getStartedRenderPassCommands().invalidateRenderPassDepthAttachment(
2216 dsState, invalidateArea);
2217 }
2218
2219 if (invalidateStencilBuffer)
2220 {
2221 contextVk->getStartedRenderPassCommands().invalidateRenderPassStencilAttachment(
2222 dsState, mState.getStencilBitCount(), invalidateArea);
2223 }
2224 }
2225 }
2226
2227 return angle::Result::Continue;
2228 }
2229
updateColorAttachment(const gl::Context * context,uint32_t colorIndexGL)2230 angle::Result FramebufferVk::updateColorAttachment(const gl::Context *context,
2231 uint32_t colorIndexGL)
2232 {
2233 ANGLE_TRY(mRenderTargetCache.updateColorRenderTarget(context, mState, colorIndexGL));
2234
2235 // Update cached masks for masked clears.
2236 RenderTargetVk *renderTarget = mRenderTargetCache.getColors()[colorIndexGL];
2237 if (renderTarget)
2238 {
2239 const angle::Format &actualFormat = renderTarget->getImageActualFormat();
2240 updateActiveColorMasks(colorIndexGL, actualFormat.redBits > 0, actualFormat.greenBits > 0,
2241 actualFormat.blueBits > 0, actualFormat.alphaBits > 0);
2242
2243 const angle::Format &intendedFormat = renderTarget->getImageIntendedFormat();
2244 mEmulatedAlphaAttachmentMask.set(
2245 colorIndexGL, intendedFormat.alphaBits == 0 && actualFormat.alphaBits > 0);
2246 }
2247 else
2248 {
2249 updateActiveColorMasks(colorIndexGL, false, false, false, false);
2250 }
2251
2252 const bool enabledColor =
2253 renderTarget && mState.getColorAttachments()[colorIndexGL].isAttached();
2254 const bool enabledResolve = enabledColor && renderTarget->hasResolveAttachment();
2255
2256 if (enabledColor)
2257 {
2258 mCurrentFramebufferDesc.updateColor(colorIndexGL, renderTarget->getDrawSubresourceSerial());
2259 const bool isExternalImage =
2260 mState.getColorAttachments()[colorIndexGL].isExternalImageWithoutIndividualSync();
2261 mIsExternalColorAttachments.set(colorIndexGL, isExternalImage);
2262 mAttachmentHasFrontBufferUsage.set(
2263 colorIndexGL, mState.getColorAttachments()[colorIndexGL].hasFrontBufferUsage());
2264 }
2265 else
2266 {
2267 mCurrentFramebufferDesc.updateColor(colorIndexGL,
2268 vk::kInvalidImageOrBufferViewSubresourceSerial);
2269 }
2270
2271 if (enabledResolve)
2272 {
2273 mCurrentFramebufferDesc.updateColorResolve(colorIndexGL,
2274 renderTarget->getResolveSubresourceSerial());
2275 }
2276 else
2277 {
2278 mCurrentFramebufferDesc.updateColorResolve(colorIndexGL,
2279 vk::kInvalidImageOrBufferViewSubresourceSerial);
2280 }
2281
2282 return angle::Result::Continue;
2283 }
2284
updateColorAttachmentColorspace(gl::SrgbWriteControlMode srgbWriteControlMode)2285 void FramebufferVk::updateColorAttachmentColorspace(gl::SrgbWriteControlMode srgbWriteControlMode)
2286 {
2287 // Update colorspace of color attachments.
2288 const auto &colorRenderTargets = mRenderTargetCache.getColors();
2289 const gl::DrawBufferMask colorAttachmentMask = mState.getColorAttachmentsMask();
2290 for (size_t colorIndexGL : colorAttachmentMask)
2291 {
2292 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
2293 ASSERT(colorRenderTarget);
2294 colorRenderTarget->updateWriteColorspace(srgbWriteControlMode);
2295 }
2296 }
2297
updateDepthStencilAttachment(const gl::Context * context)2298 angle::Result FramebufferVk::updateDepthStencilAttachment(const gl::Context *context)
2299 {
2300 ANGLE_TRY(mRenderTargetCache.updateDepthStencilRenderTarget(context, mState));
2301
2302 ContextVk *contextVk = vk::GetImpl(context);
2303 updateDepthStencilAttachmentSerial(contextVk);
2304
2305 return angle::Result::Continue;
2306 }
2307
updateDepthStencilAttachmentSerial(ContextVk * contextVk)2308 void FramebufferVk::updateDepthStencilAttachmentSerial(ContextVk *contextVk)
2309 {
2310 RenderTargetVk *depthStencilRT = getDepthStencilRenderTarget();
2311
2312 if (depthStencilRT != nullptr)
2313 {
2314 mCurrentFramebufferDesc.updateDepthStencil(depthStencilRT->getDrawSubresourceSerial());
2315 }
2316 else
2317 {
2318 mCurrentFramebufferDesc.updateDepthStencil(vk::kInvalidImageOrBufferViewSubresourceSerial);
2319 }
2320
2321 if (depthStencilRT != nullptr && depthStencilRT->hasResolveAttachment())
2322 {
2323 mCurrentFramebufferDesc.updateDepthStencilResolve(
2324 depthStencilRT->getResolveSubresourceSerial());
2325 }
2326 else
2327 {
2328 mCurrentFramebufferDesc.updateDepthStencilResolve(
2329 vk::kInvalidImageOrBufferViewSubresourceSerial);
2330 }
2331 }
2332
flushColorAttachmentUpdates(const gl::Context * context,bool deferClears,uint32_t colorIndexGL)2333 angle::Result FramebufferVk::flushColorAttachmentUpdates(const gl::Context *context,
2334 bool deferClears,
2335 uint32_t colorIndexGL)
2336 {
2337 ContextVk *contextVk = vk::GetImpl(context);
2338 RenderTargetVk *readRenderTarget = nullptr;
2339 RenderTargetVk *drawRenderTarget = nullptr;
2340
2341 // It's possible for the read and draw color attachments to be different if different surfaces
2342 // are bound, so we need to flush any staged updates to both.
2343
2344 // Draw
2345 drawRenderTarget = mRenderTargetCache.getColorDraw(mState, colorIndexGL);
2346 if (drawRenderTarget)
2347 {
2348 if (deferClears)
2349 {
2350 ANGLE_TRY(
2351 drawRenderTarget->flushStagedUpdates(contextVk, &mDeferredClears, colorIndexGL,
2352 mCurrentFramebufferDesc.getLayerCount()));
2353 }
2354 else
2355 {
2356 ANGLE_TRY(drawRenderTarget->flushStagedUpdates(
2357 contextVk, nullptr, 0, mCurrentFramebufferDesc.getLayerCount()));
2358 }
2359 }
2360
2361 // Read
2362 if (mState.getReadBufferState() != GL_NONE && mState.getReadIndex() == colorIndexGL)
2363 {
2364 // Flush staged updates to the read render target as well, but only if it's not the same as
2365 // the draw render target. This can happen when the read render target is bound to another
2366 // surface.
2367 readRenderTarget = mRenderTargetCache.getColorRead(mState);
2368 if (readRenderTarget && readRenderTarget != drawRenderTarget)
2369 {
2370 ANGLE_TRY(readRenderTarget->flushStagedUpdates(
2371 contextVk, nullptr, 0, mCurrentFramebufferDesc.getLayerCount()));
2372 }
2373 }
2374
2375 return angle::Result::Continue;
2376 }
2377
flushDepthStencilAttachmentUpdates(const gl::Context * context,bool deferClears)2378 angle::Result FramebufferVk::flushDepthStencilAttachmentUpdates(const gl::Context *context,
2379 bool deferClears)
2380 {
2381 ContextVk *contextVk = vk::GetImpl(context);
2382
2383 RenderTargetVk *depthStencilRT = getDepthStencilRenderTarget();
2384 if (depthStencilRT == nullptr)
2385 {
2386 return angle::Result::Continue;
2387 }
2388
2389 if (deferClears)
2390 {
2391 return depthStencilRT->flushStagedUpdates(contextVk, &mDeferredClears,
2392 vk::kUnpackedDepthIndex,
2393 mCurrentFramebufferDesc.getLayerCount());
2394 }
2395
2396 return depthStencilRT->flushStagedUpdates(contextVk, nullptr, 0,
2397 mCurrentFramebufferDesc.getLayerCount());
2398 }
2399
syncState(const gl::Context * context,GLenum binding,const gl::Framebuffer::DirtyBits & dirtyBits,gl::Command command)2400 angle::Result FramebufferVk::syncState(const gl::Context *context,
2401 GLenum binding,
2402 const gl::Framebuffer::DirtyBits &dirtyBits,
2403 gl::Command command)
2404 {
2405 ContextVk *contextVk = vk::GetImpl(context);
2406
2407 vk::FramebufferDesc priorFramebufferDesc = mCurrentFramebufferDesc;
2408
2409 // Keep track of which attachments have dirty content and need their staged updates flushed.
2410 // The respective functions depend on |mCurrentFramebufferDesc::mLayerCount| which is updated
2411 // after all attachment render targets are updated.
2412 gl::DrawBufferMask dirtyColorAttachments;
2413 bool dirtyDepthStencilAttachment = false;
2414
2415 bool shouldUpdateColorMaskAndBlend = false;
2416 bool shouldUpdateLayerCount = false;
2417
2418 // Cache new foveation state, if any
2419 const gl::FoveationState *newFoveationState = nullptr;
2420 gl::Extents foveatedAttachmentSize;
2421
2422 // For any updated attachments we'll update their Serials below
2423 ASSERT(dirtyBits.any());
2424 for (size_t dirtyBit : dirtyBits)
2425 {
2426 switch (dirtyBit)
2427 {
2428 case gl::Framebuffer::DIRTY_BIT_DEPTH_ATTACHMENT:
2429 case gl::Framebuffer::DIRTY_BIT_DEPTH_BUFFER_CONTENTS:
2430 case gl::Framebuffer::DIRTY_BIT_STENCIL_ATTACHMENT:
2431 case gl::Framebuffer::DIRTY_BIT_STENCIL_BUFFER_CONTENTS:
2432 ANGLE_TRY(updateDepthStencilAttachment(context));
2433 shouldUpdateLayerCount = true;
2434 dirtyDepthStencilAttachment = true;
2435 break;
2436 case gl::Framebuffer::DIRTY_BIT_READ_BUFFER:
2437 ANGLE_TRY(mRenderTargetCache.update(context, mState, dirtyBits));
2438 break;
2439 case gl::Framebuffer::DIRTY_BIT_DRAW_BUFFERS:
2440 shouldUpdateColorMaskAndBlend = true;
2441 shouldUpdateLayerCount = true;
2442 break;
2443 case gl::Framebuffer::DIRTY_BIT_DEFAULT_WIDTH:
2444 case gl::Framebuffer::DIRTY_BIT_DEFAULT_HEIGHT:
2445 case gl::Framebuffer::DIRTY_BIT_DEFAULT_SAMPLES:
2446 case gl::Framebuffer::DIRTY_BIT_DEFAULT_FIXED_SAMPLE_LOCATIONS:
2447 // Invalidate the cache. If we have performance critical code hitting this path we
2448 // can add related data (such as width/height) to the cache
2449 releaseCurrentFramebuffer(contextVk);
2450 break;
2451 case gl::Framebuffer::DIRTY_BIT_FRAMEBUFFER_SRGB_WRITE_CONTROL_MODE:
2452 break;
2453 case gl::Framebuffer::DIRTY_BIT_DEFAULT_LAYERS:
2454 shouldUpdateLayerCount = true;
2455 break;
2456 case gl::Framebuffer::DIRTY_BIT_FOVEATION:
2457 // This dirty bit is set iff the framebuffer itself is foveated
2458 ASSERT(mState.isFoveationEnabled());
2459
2460 newFoveationState = &mState.getFoveationState();
2461 foveatedAttachmentSize = mState.getExtents();
2462 break;
2463 default:
2464 {
2465 static_assert(gl::Framebuffer::DIRTY_BIT_COLOR_ATTACHMENT_0 == 0, "FB dirty bits");
2466 uint32_t colorIndexGL;
2467 if (dirtyBit < gl::Framebuffer::DIRTY_BIT_COLOR_ATTACHMENT_MAX)
2468 {
2469 colorIndexGL = static_cast<uint32_t>(
2470 dirtyBit - gl::Framebuffer::DIRTY_BIT_COLOR_ATTACHMENT_0);
2471 }
2472 else
2473 {
2474 ASSERT(dirtyBit >= gl::Framebuffer::DIRTY_BIT_COLOR_BUFFER_CONTENTS_0 &&
2475 dirtyBit < gl::Framebuffer::DIRTY_BIT_COLOR_BUFFER_CONTENTS_MAX);
2476 colorIndexGL = static_cast<uint32_t>(
2477 dirtyBit - gl::Framebuffer::DIRTY_BIT_COLOR_BUFFER_CONTENTS_0);
2478 }
2479
2480 ANGLE_TRY(updateColorAttachment(context, colorIndexGL));
2481
2482 // Check if attachment has foveated rendering, if so grab foveation state
2483 const gl::FramebufferAttachment *attachment =
2484 mState.getColorAttachment(colorIndexGL);
2485 if (attachment && attachment->hasFoveatedRendering())
2486 {
2487 // If attachment is foveated the framebuffer must not be.
2488 ASSERT(!mState.isFoveationEnabled());
2489
2490 newFoveationState = attachment->getFoveationState();
2491 ASSERT(newFoveationState != nullptr);
2492
2493 foveatedAttachmentSize = attachment->getSize();
2494 }
2495
2496 // Window system framebuffer only have one color attachment and its property should
2497 // never change unless via DIRTY_BIT_DRAW_BUFFERS bit.
2498 if (!mState.isDefault())
2499 {
2500 shouldUpdateColorMaskAndBlend = true;
2501 shouldUpdateLayerCount = true;
2502 }
2503 dirtyColorAttachments.set(colorIndexGL);
2504
2505 break;
2506 }
2507 }
2508 }
2509
2510 // A shared attachment's colospace could have been modified in another context, update
2511 // colorspace of all attachments to reflect current context's colorspace.
2512 gl::SrgbWriteControlMode srgbWriteControlMode = mState.getWriteControlMode();
2513 updateColorAttachmentColorspace(srgbWriteControlMode);
2514 // Update current framebuffer descriptor to reflect the new state.
2515 mCurrentFramebufferDesc.setWriteControlMode(srgbWriteControlMode);
2516
2517 if (shouldUpdateColorMaskAndBlend)
2518 {
2519 contextVk->updateColorMasks();
2520 contextVk->updateBlendFuncsAndEquations();
2521 }
2522
2523 if (shouldUpdateLayerCount)
2524 {
2525 updateLayerCount();
2526 }
2527
2528 if (newFoveationState && mFoveationState != *newFoveationState)
2529 {
2530 ANGLE_TRY(updateFoveationState(contextVk, *newFoveationState, foveatedAttachmentSize));
2531 }
2532
2533 // Defer clears for draw framebuffer ops. Note that this will result in a render area that
2534 // completely covers the framebuffer, even if the operation that follows is scissored.
2535 //
2536 // Additionally, defer clears for read framebuffer attachments that are not taking part in a
2537 // blit operation.
2538 const bool isBlitCommand = command >= gl::Command::Blit && command <= gl::Command::BlitAll;
2539
2540 bool deferColorClears = binding == GL_DRAW_FRAMEBUFFER;
2541 bool deferDepthStencilClears = binding == GL_DRAW_FRAMEBUFFER;
2542 if (binding == GL_READ_FRAMEBUFFER && isBlitCommand)
2543 {
2544 uint32_t blitMask =
2545 static_cast<uint32_t>(command) - static_cast<uint32_t>(gl::Command::Blit);
2546 if ((blitMask & gl::CommandBlitBufferColor) == 0)
2547 {
2548 deferColorClears = true;
2549 }
2550 if ((blitMask & (gl::CommandBlitBufferDepth | gl::CommandBlitBufferStencil)) == 0)
2551 {
2552 deferDepthStencilClears = true;
2553 }
2554 }
2555
2556 // If we are notified that any attachment is dirty, but we have deferred clears for them, a
2557 // flushDeferredClears() call is missing somewhere. ASSERT this to catch these bugs.
2558 vk::ClearValuesArray previousDeferredClears = mDeferredClears;
2559
2560 for (size_t colorIndexGL : dirtyColorAttachments)
2561 {
2562 ASSERT(!previousDeferredClears.test(colorIndexGL));
2563 ANGLE_TRY(flushColorAttachmentUpdates(context, deferColorClears,
2564 static_cast<uint32_t>(colorIndexGL)));
2565 }
2566 if (dirtyDepthStencilAttachment)
2567 {
2568 ASSERT(!previousDeferredClears.testDepth());
2569 ASSERT(!previousDeferredClears.testStencil());
2570 ANGLE_TRY(flushDepthStencilAttachmentUpdates(context, deferDepthStencilClears));
2571 }
2572
2573 // No-op redundant changes to prevent closing the RenderPass.
2574 if (mCurrentFramebufferDesc == priorFramebufferDesc &&
2575 mCurrentFramebufferDesc.attachmentCount() > 0)
2576 {
2577 return angle::Result::Continue;
2578 }
2579
2580 // ContextVk::onFramebufferChange will end up calling onRenderPassFinished if necessary,
2581 // which will trigger ending of current render pass. |mLastRenderPassQueueSerial| is reset
2582 // so that the render pass will not get reactivated, since |mCurrentFramebufferDesc| has
2583 // changed.
2584 mLastRenderPassQueueSerial = QueueSerial();
2585
2586 updateRenderPassDesc(contextVk);
2587
2588 // Deactivate Framebuffer
2589 releaseCurrentFramebuffer(contextVk);
2590
2591 // Notify the ContextVk to update the pipeline desc.
2592 return contextVk->onFramebufferChange(this, command);
2593 }
2594
updateRenderPassDesc(ContextVk * contextVk)2595 void FramebufferVk::updateRenderPassDesc(ContextVk *contextVk)
2596 {
2597 mRenderPassDesc = {};
2598 mRenderPassDesc.setSamples(getSamples());
2599 mRenderPassDesc.setViewCount(
2600 mState.isMultiview() && mState.getNumViews() > 1 ? mState.getNumViews() : 0);
2601
2602 // Color attachments.
2603 const auto &colorRenderTargets = mRenderTargetCache.getColors();
2604 const gl::DrawBufferMask colorAttachmentMask = mState.getColorAttachmentsMask();
2605 for (size_t colorIndexGL = 0; colorIndexGL < colorAttachmentMask.size(); ++colorIndexGL)
2606 {
2607 if (colorAttachmentMask[colorIndexGL])
2608 {
2609 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
2610 ASSERT(colorRenderTarget);
2611
2612 if (colorRenderTarget->isYuvResolve())
2613 {
2614 // If this is YUV resolve target, we use resolveImage's format since image maybe
2615 // nullptr
2616 auto const &resolveImage = colorRenderTarget->getResolveImageForRenderPass();
2617 mRenderPassDesc.packColorAttachment(colorIndexGL, resolveImage.getActualFormatID());
2618 mRenderPassDesc.packYUVResolveAttachment(colorIndexGL);
2619 }
2620 else
2621 {
2622 // Account for attachments with colorspace override
2623 angle::FormatID actualFormat =
2624 colorRenderTarget->getImageForRenderPass().getActualFormatID();
2625 if (colorRenderTarget->hasColorspaceOverrideForWrite())
2626 {
2627 actualFormat =
2628 colorRenderTarget->getColorspaceOverrideFormatForWrite(actualFormat);
2629 }
2630
2631 mRenderPassDesc.packColorAttachment(colorIndexGL, actualFormat);
2632 // Add the resolve attachment, if any.
2633 if (colorRenderTarget->hasResolveAttachment())
2634 {
2635 mRenderPassDesc.packColorResolveAttachment(colorIndexGL);
2636 }
2637 }
2638 }
2639 else
2640 {
2641 mRenderPassDesc.packColorAttachmentGap(colorIndexGL);
2642 }
2643 }
2644
2645 // Depth/stencil attachment.
2646 RenderTargetVk *depthStencilRenderTarget = getDepthStencilRenderTarget();
2647 if (depthStencilRenderTarget)
2648 {
2649 mRenderPassDesc.packDepthStencilAttachment(
2650 depthStencilRenderTarget->getImageForRenderPass().getActualFormatID());
2651
2652 // Add the resolve attachment, if any.
2653 if (depthStencilRenderTarget->hasResolveAttachment())
2654 {
2655 mRenderPassDesc.packDepthResolveAttachment();
2656 mRenderPassDesc.packStencilResolveAttachment();
2657 }
2658 }
2659
2660 if (!contextVk->getFeatures().preferDynamicRendering.enabled &&
2661 contextVk->isInColorFramebufferFetchMode())
2662 {
2663 mRenderPassDesc.setFramebufferFetchMode(vk::FramebufferFetchMode::Color);
2664 }
2665
2666 if (contextVk->getFeatures().enableMultisampledRenderToTexture.enabled)
2667 {
2668 // Update descriptions regarding multisampled-render-to-texture use.
2669 bool isRenderToTexture = false;
2670 for (size_t colorIndexGL : mState.getEnabledDrawBuffers())
2671 {
2672 const gl::FramebufferAttachment *color = mState.getColorAttachment(colorIndexGL);
2673 ASSERT(color);
2674
2675 if (color->isRenderToTexture())
2676 {
2677 isRenderToTexture = true;
2678 break;
2679 }
2680 }
2681 const gl::FramebufferAttachment *depthStencil = mState.getDepthStencilAttachment();
2682 if (depthStencil && depthStencil->isRenderToTexture())
2683 {
2684 isRenderToTexture = true;
2685 }
2686
2687 mCurrentFramebufferDesc.updateRenderToTexture(isRenderToTexture);
2688 mRenderPassDesc.updateRenderToTexture(isRenderToTexture);
2689 }
2690
2691 mCurrentFramebufferDesc.updateUnresolveMask({});
2692 mRenderPassDesc.setWriteControlMode(mCurrentFramebufferDesc.getWriteControlMode());
2693 mRenderPassDesc.setFragmentShadingAttachment(
2694 mCurrentFramebufferDesc.hasFragmentShadingRateAttachment());
2695
2696 updateLegacyDither(contextVk);
2697 }
2698
getAttachmentsAndRenderTargets(vk::Context * context,vk::FramebufferAttachmentsVector<VkImageView> * unpackedAttachments,vk::FramebufferAttachmentsVector<RenderTargetInfo> * packedRenderTargetsInfoOut)2699 angle::Result FramebufferVk::getAttachmentsAndRenderTargets(
2700 vk::Context *context,
2701 vk::FramebufferAttachmentsVector<VkImageView> *unpackedAttachments,
2702 vk::FramebufferAttachmentsVector<RenderTargetInfo> *packedRenderTargetsInfoOut)
2703 {
2704 // Color attachments.
2705 mIsYUVResolve = false;
2706 const auto &colorRenderTargets = mRenderTargetCache.getColors();
2707 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
2708 {
2709 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
2710 ASSERT(colorRenderTarget);
2711
2712 if (colorRenderTarget->isYuvResolve())
2713 {
2714 mIsYUVResolve = true;
2715 if (context->getRenderer()->nullColorAttachmentWithExternalFormatResolve())
2716 {
2717 continue;
2718 }
2719 }
2720 const vk::ImageView *imageView = nullptr;
2721 ANGLE_TRY(colorRenderTarget->getImageViewWithColorspace(
2722 context, mCurrentFramebufferDesc.getWriteControlMode(), &imageView));
2723 unpackedAttachments->push_back(imageView->getHandle());
2724
2725 packedRenderTargetsInfoOut->emplace_back(
2726 RenderTargetInfo(colorRenderTarget, RenderTargetImage::Attachment));
2727 }
2728
2729 // Depth/stencil attachment.
2730 RenderTargetVk *depthStencilRenderTarget = getDepthStencilRenderTarget();
2731 if (depthStencilRenderTarget)
2732 {
2733 const vk::ImageView *imageView = nullptr;
2734 ANGLE_TRY(depthStencilRenderTarget->getImageView(context, &imageView));
2735
2736 unpackedAttachments->push_back(imageView->getHandle());
2737 packedRenderTargetsInfoOut->emplace_back(
2738 RenderTargetInfo(depthStencilRenderTarget, RenderTargetImage::Attachment));
2739 }
2740
2741 // Fragment shading rate attachment.
2742 if (mCurrentFramebufferDesc.hasFragmentShadingRateAttachment())
2743 {
2744 const vk::ImageViewHelper *imageViewHelper = &mFragmentShadingRateImageView;
2745 unpackedAttachments->push_back(
2746 imageViewHelper->getFragmentShadingRateImageView().getHandle());
2747 packedRenderTargetsInfoOut->emplace_back(nullptr, RenderTargetImage::FragmentShadingRate);
2748 }
2749
2750 // Color resolve attachments. From here on, the views are placed at sparse indices because of
2751 // |RenderPassFramebuffer|. That allows more resolve attachments to be added later.
2752 unpackedAttachments->resize(vk::kMaxFramebufferAttachments, VK_NULL_HANDLE);
2753 static_assert(vk::RenderPassFramebuffer::kColorResolveAttachmentBegin <
2754 vk::kMaxFramebufferAttachments);
2755 static_assert(vk::RenderPassFramebuffer::kDepthStencilResolveAttachment <
2756 vk::kMaxFramebufferAttachments);
2757
2758 bool anyResolveAttachments = false;
2759
2760 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
2761 {
2762 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
2763 ASSERT(colorRenderTarget);
2764
2765 if (colorRenderTarget->hasResolveAttachment())
2766 {
2767 const vk::ImageView *resolveImageView = nullptr;
2768 ANGLE_TRY(colorRenderTarget->getResolveImageView(context, &resolveImageView));
2769
2770 constexpr size_t kBaseIndex = vk::RenderPassFramebuffer::kColorResolveAttachmentBegin;
2771 (*unpackedAttachments)[kBaseIndex + colorIndexGL] = resolveImageView->getHandle();
2772 packedRenderTargetsInfoOut->emplace_back(
2773 RenderTargetInfo(colorRenderTarget, RenderTargetImage::Resolve));
2774
2775 anyResolveAttachments = true;
2776 }
2777 }
2778
2779 // Depth/stencil resolve attachment.
2780 if (depthStencilRenderTarget && depthStencilRenderTarget->hasResolveAttachment())
2781 {
2782 const vk::ImageView *imageView = nullptr;
2783 ANGLE_TRY(depthStencilRenderTarget->getResolveImageView(context, &imageView));
2784
2785 (*unpackedAttachments)[vk::RenderPassFramebuffer::kDepthStencilResolveAttachment] =
2786 imageView->getHandle();
2787 packedRenderTargetsInfoOut->emplace_back(
2788 RenderTargetInfo(depthStencilRenderTarget, RenderTargetImage::Resolve));
2789
2790 anyResolveAttachments = true;
2791 }
2792
2793 // Make sure |AllowAddingResolveAttachmentsToSubpass()| is guarding against all cases where a
2794 // resolve attachment is pre-present in the render pass.
2795 if (anyResolveAttachments)
2796 {
2797 ASSERT(!AllowAddingResolveAttachmentsToSubpass(mRenderPassDesc));
2798 }
2799
2800 return angle::Result::Continue;
2801 }
2802
createNewFramebuffer(ContextVk * contextVk,uint32_t framebufferWidth,const uint32_t framebufferHeight,const uint32_t framebufferLayers,const vk::FramebufferAttachmentsVector<VkImageView> & unpackedAttachments,const vk::FramebufferAttachmentsVector<RenderTargetInfo> & renderTargetsInfo)2803 angle::Result FramebufferVk::createNewFramebuffer(
2804 ContextVk *contextVk,
2805 uint32_t framebufferWidth,
2806 const uint32_t framebufferHeight,
2807 const uint32_t framebufferLayers,
2808 const vk::FramebufferAttachmentsVector<VkImageView> &unpackedAttachments,
2809 const vk::FramebufferAttachmentsVector<RenderTargetInfo> &renderTargetsInfo)
2810 {
2811 ASSERT(!contextVk->getFeatures().preferDynamicRendering.enabled);
2812
2813 // The backbuffer framebuffer is cached in WindowSurfaceVk instead.
2814 ASSERT(mBackbuffer == nullptr);
2815 // Called only when a new framebuffer is needed.
2816 ASSERT(!mCurrentFramebuffer.valid());
2817
2818 // When using imageless framebuffers, the framebuffer cache is not utilized.
2819 const bool useImagelessFramebuffer =
2820 contextVk->getFeatures().supportsImagelessFramebuffer.enabled;
2821
2822 // Try to retrieve a framebuffer from the cache.
2823 if (!useImagelessFramebuffer && contextVk->getShareGroup()->getFramebufferCache().get(
2824 contextVk, mCurrentFramebufferDesc, mCurrentFramebuffer))
2825 {
2826 ASSERT(mCurrentFramebuffer.valid());
2827 mIsCurrentFramebufferCached = true;
2828 return angle::Result::Continue;
2829 }
2830
2831 const vk::RenderPass *compatibleRenderPass = nullptr;
2832 ANGLE_TRY(contextVk->getCompatibleRenderPass(mRenderPassDesc, &compatibleRenderPass));
2833
2834 // Create a new framebuffer.
2835 vk::FramebufferHelper newFramebuffer;
2836
2837 VkFramebufferCreateInfo framebufferInfo = {};
2838 framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
2839 framebufferInfo.flags = 0;
2840 framebufferInfo.renderPass = compatibleRenderPass->getHandle();
2841 framebufferInfo.attachmentCount = static_cast<uint32_t>(renderTargetsInfo.size());
2842 framebufferInfo.width = framebufferWidth;
2843 framebufferInfo.height = framebufferHeight;
2844 framebufferInfo.layers = framebufferLayers;
2845
2846 // Check that our description matches our attachments. Can catch implementation bugs.
2847 ASSERT((mIsYUVResolve &&
2848 contextVk->getRenderer()->nullColorAttachmentWithExternalFormatResolve()) ||
2849 static_cast<uint32_t>(renderTargetsInfo.size()) ==
2850 mCurrentFramebufferDesc.attachmentCount());
2851
2852 if (!useImagelessFramebuffer)
2853 {
2854 vk::FramebufferAttachmentsVector<VkImageView> packedAttachments = unpackedAttachments;
2855 vk::RenderPassFramebuffer::PackViews(&packedAttachments);
2856
2857 ASSERT(renderTargetsInfo.size() == packedAttachments.size());
2858 framebufferInfo.pAttachments = packedAttachments.data();
2859
2860 // The cache key (|FramebufferDesc|) can't distinguish between two framebuffers with 0
2861 // attachments but with different sizes. For simplicity, 0-attachment framebuffers are not
2862 // cached.
2863 ANGLE_TRY(newFramebuffer.init(contextVk, framebufferInfo));
2864 if (packedAttachments.empty())
2865 {
2866 mCurrentFramebuffer = std::move(newFramebuffer.getFramebuffer());
2867 mIsCurrentFramebufferCached = false;
2868 }
2869 else
2870 {
2871 insertCache(contextVk, mCurrentFramebufferDesc, std::move(newFramebuffer));
2872
2873 const bool result = contextVk->getShareGroup()->getFramebufferCache().get(
2874 contextVk, mCurrentFramebufferDesc, mCurrentFramebuffer);
2875 ASSERT(result);
2876 mIsCurrentFramebufferCached = true;
2877 }
2878
2879 return angle::Result::Continue;
2880 }
2881
2882 // For imageless framebuffers, attachment image and create info objects should be defined
2883 // when creating the new framebuffer.
2884 vk::FramebufferAttachmentsVector<VkFramebufferAttachmentImageInfo> attachmentImageInfos(
2885 renderTargetsInfo.size(), {});
2886
2887 for (size_t index = 0; index < renderTargetsInfo.size(); ++index)
2888 {
2889 const RenderTargetInfo &info = renderTargetsInfo[index];
2890 VkFramebufferAttachmentImageInfo &attachmentInfo = attachmentImageInfos[index];
2891
2892 attachmentInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENT_IMAGE_INFO;
2893
2894 // The fragment shading rate attachment does not have a corresponding render target, and is
2895 // handled specially.
2896 if (info.renderTargetImage == RenderTargetImage::FragmentShadingRate)
2897 {
2898 attachmentInfo.width = mFragmentShadingRateImage.getExtents().width;
2899 attachmentInfo.height = mFragmentShadingRateImage.getExtents().height;
2900
2901 attachmentInfo.layerCount = 1;
2902 attachmentInfo.flags = mFragmentShadingRateImage.getCreateFlags();
2903 attachmentInfo.usage = mFragmentShadingRateImage.getUsage();
2904 attachmentInfo.viewFormatCount =
2905 static_cast<uint32_t>(mFragmentShadingRateImage.getViewFormats().size());
2906 attachmentInfo.pViewFormats = mFragmentShadingRateImage.getViewFormats().data();
2907 continue;
2908 }
2909
2910 vk::ImageHelper *image = (info.renderTargetImage == RenderTargetImage::Resolve ||
2911 info.renderTarget->isYuvResolve())
2912 ? &info.renderTarget->getResolveImageForRenderPass()
2913 : &info.renderTarget->getImageForRenderPass();
2914
2915 const gl::LevelIndex level = info.renderTarget->getLevelIndexForImage(*image);
2916 const uint32_t layerCount = info.renderTarget->getLayerCount();
2917 const gl::Extents extents = image->getLevelExtents2D(image->toVkLevel(level));
2918
2919 attachmentInfo.width = std::max(extents.width, 1);
2920 attachmentInfo.height = std::max(extents.height, 1);
2921 attachmentInfo.layerCount = mCurrentFramebufferDesc.isMultiview()
2922 ? std::max<uint32_t>(mRenderPassDesc.viewCount(), 1u)
2923 : layerCount;
2924 attachmentInfo.flags = image->getCreateFlags();
2925 attachmentInfo.usage = image->getUsage();
2926 attachmentInfo.viewFormatCount = static_cast<uint32_t>(image->getViewFormats().size());
2927 attachmentInfo.pViewFormats = image->getViewFormats().data();
2928 }
2929
2930 VkFramebufferAttachmentsCreateInfo attachmentsCreateInfo = {};
2931 attachmentsCreateInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENTS_CREATE_INFO;
2932 attachmentsCreateInfo.attachmentImageInfoCount =
2933 static_cast<uint32_t>(attachmentImageInfos.size());
2934 attachmentsCreateInfo.pAttachmentImageInfos = attachmentImageInfos.data();
2935
2936 framebufferInfo.flags |= VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT;
2937 vk::AddToPNextChain(&framebufferInfo, &attachmentsCreateInfo);
2938
2939 ANGLE_TRY(newFramebuffer.init(contextVk, framebufferInfo));
2940 mCurrentFramebuffer = std::move(newFramebuffer.getFramebuffer());
2941
2942 return angle::Result::Continue;
2943 }
2944
getFramebuffer(ContextVk * contextVk,vk::RenderPassFramebuffer * framebufferOut)2945 angle::Result FramebufferVk::getFramebuffer(ContextVk *contextVk,
2946 vk::RenderPassFramebuffer *framebufferOut)
2947 {
2948 ASSERT(!mRenderPassDesc.hasDepthStencilFramebufferFetch());
2949 ASSERT(mCurrentFramebufferDesc.hasColorFramebufferFetch() ==
2950 mRenderPassDesc.hasColorFramebufferFetch());
2951
2952 const gl::Extents attachmentsSize = mState.getExtents();
2953 ASSERT(attachmentsSize.width != 0 && attachmentsSize.height != 0);
2954
2955 uint32_t framebufferWidth = static_cast<uint32_t>(attachmentsSize.width);
2956 uint32_t framebufferHeight = static_cast<uint32_t>(attachmentsSize.height);
2957 const uint32_t framebufferLayers = !mCurrentFramebufferDesc.isMultiview()
2958 ? std::max(mCurrentFramebufferDesc.getLayerCount(), 1u)
2959 : 1;
2960
2961 vk::FramebufferAttachmentsVector<VkImageView> unpackedAttachments;
2962 vk::FramebufferAttachmentsVector<RenderTargetInfo> renderTargetsInfo;
2963 ANGLE_TRY(getAttachmentsAndRenderTargets(contextVk, &unpackedAttachments, &renderTargetsInfo));
2964
2965 vk::Framebuffer framebufferHandle;
2966 if (contextVk->getFeatures().preferDynamicRendering.enabled)
2967 {
2968 // Nothing to do with dynamic rendering. The image views and other info are still placed in
2969 // |framebufferOut| to be passed to |vkCmdBeginRendering| similarly to how they are used
2970 // with imageless framebuffers with render pass objects.
2971 }
2972 else if (mCurrentFramebuffer.valid())
2973 {
2974 // If a valid framebuffer is already created, use it. This is not done when the swapchain
2975 // is being resolved, because the appropriate framebuffer needs to be queried from the back
2976 // buffer.
2977 framebufferHandle.setHandle(mCurrentFramebuffer.getHandle());
2978 }
2979 else
2980 {
2981 // For the default framebuffer attached to a window surface, WindowSurfaceVk caches a
2982 // handful of framebuffer objects which are queried here. For the rest, a framebuffer needs
2983 // to be created based on the current attachments to the FBO.
2984 if (mBackbuffer == nullptr)
2985 {
2986 // Create a new framebuffer
2987 ANGLE_TRY(createNewFramebuffer(contextVk, framebufferWidth, framebufferHeight,
2988 framebufferLayers, unpackedAttachments,
2989 renderTargetsInfo));
2990 ASSERT(mCurrentFramebuffer.valid());
2991 framebufferHandle.setHandle(mCurrentFramebuffer.getHandle());
2992 }
2993 else
2994 {
2995 const vk::RenderPass *compatibleRenderPass = nullptr;
2996 ANGLE_TRY(contextVk->getCompatibleRenderPass(mRenderPassDesc, &compatibleRenderPass));
2997
2998 // If there is a backbuffer, query the framebuffer from WindowSurfaceVk instead.
2999 ANGLE_TRY(mBackbuffer->getCurrentFramebuffer(
3000 contextVk,
3001 mRenderPassDesc.hasColorFramebufferFetch() ? vk::FramebufferFetchMode::Color
3002 : vk::FramebufferFetchMode::None,
3003 *compatibleRenderPass, &framebufferHandle));
3004 }
3005 }
3006
3007 if (mBackbuffer != nullptr)
3008 {
3009 // Account for swapchain pre-rotation
3010 framebufferWidth = renderTargetsInfo[0].renderTarget->getRotatedExtents().width;
3011 framebufferHeight = renderTargetsInfo[0].renderTarget->getRotatedExtents().height;
3012 }
3013
3014 const vk::ImagelessFramebuffer imagelessFramebuffer =
3015 contextVk->getFeatures().preferDynamicRendering.enabled ||
3016 (contextVk->getFeatures().supportsImagelessFramebuffer.enabled &&
3017 mBackbuffer == nullptr)
3018 ? vk::ImagelessFramebuffer::Yes
3019 : vk::ImagelessFramebuffer::No;
3020 const vk::RenderPassSource source = mBackbuffer == nullptr
3021 ? vk::RenderPassSource::FramebufferObject
3022 : vk::RenderPassSource::DefaultFramebuffer;
3023
3024 framebufferOut->setFramebuffer(
3025 contextVk, std::move(framebufferHandle), std::move(unpackedAttachments), framebufferWidth,
3026 framebufferHeight, framebufferLayers, imagelessFramebuffer, source);
3027
3028 return angle::Result::Continue;
3029 }
3030
mergeClearsWithDeferredClears(gl::DrawBufferMask clearColorBuffers,bool clearDepth,bool clearStencil,const gl::DrawBuffersArray<VkClearColorValue> & clearColorValues,const VkClearDepthStencilValue & clearDepthStencilValue)3031 void FramebufferVk::mergeClearsWithDeferredClears(
3032 gl::DrawBufferMask clearColorBuffers,
3033 bool clearDepth,
3034 bool clearStencil,
3035 const gl::DrawBuffersArray<VkClearColorValue> &clearColorValues,
3036 const VkClearDepthStencilValue &clearDepthStencilValue)
3037 {
3038 // Apply clears to mDeferredClears. Note that clears override deferred clears.
3039
3040 // Color clears.
3041 for (size_t colorIndexGL : clearColorBuffers)
3042 {
3043 ASSERT(mState.getEnabledDrawBuffers().test(colorIndexGL));
3044 VkClearValue clearValue =
3045 getCorrectedColorClearValue(colorIndexGL, clearColorValues[colorIndexGL]);
3046 mDeferredClears.store(static_cast<uint32_t>(colorIndexGL), VK_IMAGE_ASPECT_COLOR_BIT,
3047 clearValue);
3048 }
3049
3050 // Depth and stencil clears.
3051 VkImageAspectFlags dsAspectFlags = 0;
3052 VkClearValue dsClearValue = {};
3053 dsClearValue.depthStencil = clearDepthStencilValue;
3054 if (clearDepth)
3055 {
3056 dsAspectFlags |= VK_IMAGE_ASPECT_DEPTH_BIT;
3057 }
3058 if (clearStencil)
3059 {
3060 dsAspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
3061 }
3062
3063 if (dsAspectFlags != 0)
3064 {
3065 mDeferredClears.store(vk::kUnpackedDepthIndex, dsAspectFlags, dsClearValue);
3066 }
3067 }
3068
clearWithDraw(ContextVk * contextVk,const gl::Rectangle & clearArea,gl::DrawBufferMask clearColorBuffers,bool clearDepth,bool clearStencil,gl::BlendStateExt::ColorMaskStorage::Type colorMasks,uint8_t stencilMask,const gl::DrawBuffersArray<VkClearColorValue> & clearColorValues,const VkClearDepthStencilValue & clearDepthStencilValue)3069 angle::Result FramebufferVk::clearWithDraw(
3070 ContextVk *contextVk,
3071 const gl::Rectangle &clearArea,
3072 gl::DrawBufferMask clearColorBuffers,
3073 bool clearDepth,
3074 bool clearStencil,
3075 gl::BlendStateExt::ColorMaskStorage::Type colorMasks,
3076 uint8_t stencilMask,
3077 const gl::DrawBuffersArray<VkClearColorValue> &clearColorValues,
3078 const VkClearDepthStencilValue &clearDepthStencilValue)
3079 {
3080 // All deferred clears should be handled already.
3081 ASSERT(mDeferredClears.empty());
3082
3083 UtilsVk::ClearFramebufferParameters params = {};
3084 params.clearArea = clearArea;
3085 params.depthStencilClearValue = clearDepthStencilValue;
3086 params.stencilMask = stencilMask;
3087
3088 params.clearColor = true;
3089 params.clearDepth = clearDepth;
3090 params.clearStencil = clearStencil;
3091
3092 const auto &colorRenderTargets = mRenderTargetCache.getColors();
3093 for (size_t colorIndexGL : clearColorBuffers)
3094 {
3095 const RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
3096 ASSERT(colorRenderTarget);
3097
3098 params.colorClearValue = clearColorValues[colorIndexGL];
3099 params.colorFormat = &colorRenderTarget->getImageForRenderPass().getActualFormat();
3100 params.colorAttachmentIndexGL = static_cast<uint32_t>(colorIndexGL);
3101 params.colorMaskFlags =
3102 gl::BlendStateExt::ColorMaskStorage::GetValueIndexed(colorIndexGL, colorMasks);
3103 if (mEmulatedAlphaAttachmentMask[colorIndexGL])
3104 {
3105 params.colorMaskFlags &= ~VK_COLOR_COMPONENT_A_BIT;
3106 }
3107
3108 // TODO: implement clear of layered framebuffers. UtilsVk::clearFramebuffer should add a
3109 // geometry shader that is instanced layerCount times (or loops layerCount times), each time
3110 // selecting a different layer.
3111 // http://anglebug.com/42263992
3112 ASSERT(mCurrentFramebufferDesc.isMultiview() || colorRenderTarget->getLayerCount() == 1);
3113
3114 ANGLE_TRY(contextVk->getUtils().clearFramebuffer(contextVk, this, params));
3115
3116 // Clear depth/stencil only once!
3117 params.clearDepth = false;
3118 params.clearStencil = false;
3119 }
3120
3121 // If there was no color clear, clear depth/stencil alone.
3122 if (params.clearDepth || params.clearStencil)
3123 {
3124 params.clearColor = false;
3125 ANGLE_TRY(contextVk->getUtils().clearFramebuffer(contextVk, this, params));
3126 }
3127
3128 return angle::Result::Continue;
3129 }
3130
getCorrectedColorClearValue(size_t colorIndexGL,const VkClearColorValue & clearColor) const3131 VkClearValue FramebufferVk::getCorrectedColorClearValue(size_t colorIndexGL,
3132 const VkClearColorValue &clearColor) const
3133 {
3134 VkClearValue clearValue = {};
3135 clearValue.color = clearColor;
3136
3137 if (!mEmulatedAlphaAttachmentMask[colorIndexGL])
3138 {
3139 return clearValue;
3140 }
3141
3142 // If the render target doesn't have alpha, but its emulated format has it, clear the alpha
3143 // to 1.
3144 RenderTargetVk *renderTarget = getColorDrawRenderTarget(colorIndexGL);
3145 const angle::Format &format = renderTarget->getImageActualFormat();
3146
3147 if (format.isUint())
3148 {
3149 clearValue.color.uint32[3] = kEmulatedAlphaValue;
3150 }
3151 else if (format.isSint())
3152 {
3153 clearValue.color.int32[3] = kEmulatedAlphaValue;
3154 }
3155 else
3156 {
3157 clearValue.color.float32[3] = kEmulatedAlphaValue;
3158 }
3159
3160 return clearValue;
3161 }
3162
restageDeferredClears(ContextVk * contextVk)3163 void FramebufferVk::restageDeferredClears(ContextVk *contextVk)
3164 {
3165 // Called when restaging clears of the draw framebuffer. In that case, there can't be any
3166 // render passes open, otherwise the clear would have applied to the render pass. In the
3167 // exceptional occasion in blit where the read framebuffer accumulates deferred clears, it can
3168 // be deferred while this assumption doesn't hold (and restageDeferredClearsForReadFramebuffer
3169 // should be used instead).
3170 ASSERT(!contextVk->hasActiveRenderPass() || !mDeferredClears.any());
3171 restageDeferredClearsImpl(contextVk);
3172 }
3173
restageDeferredClearsForReadFramebuffer(ContextVk * contextVk)3174 void FramebufferVk::restageDeferredClearsForReadFramebuffer(ContextVk *contextVk)
3175 {
3176 restageDeferredClearsImpl(contextVk);
3177 }
3178
restageDeferredClearsImpl(ContextVk * contextVk)3179 void FramebufferVk::restageDeferredClearsImpl(ContextVk *contextVk)
3180 {
3181 // Set the appropriate aspect and clear values for depth and stencil.
3182 VkImageAspectFlags dsAspectFlags = 0;
3183 VkClearValue dsClearValue = {};
3184 dsClearValue.depthStencil.depth = mDeferredClears.getDepthValue();
3185 dsClearValue.depthStencil.stencil = mDeferredClears.getStencilValue();
3186
3187 if (mDeferredClears.testDepth())
3188 {
3189 dsAspectFlags |= VK_IMAGE_ASPECT_DEPTH_BIT;
3190 mDeferredClears.reset(vk::kUnpackedDepthIndex);
3191 }
3192
3193 if (mDeferredClears.testStencil())
3194 {
3195 dsAspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
3196 mDeferredClears.reset(vk::kUnpackedStencilIndex);
3197 }
3198
3199 // Go through deferred clears and stage the clears for future.
3200 for (size_t colorIndexGL : mDeferredClears.getColorMask())
3201 {
3202 RenderTargetVk *renderTarget = getColorDrawRenderTarget(colorIndexGL);
3203 gl::ImageIndex imageIndex =
3204 renderTarget->getImageIndexForClear(mCurrentFramebufferDesc.getLayerCount());
3205 renderTarget->getImageForWrite().stageClear(imageIndex, VK_IMAGE_ASPECT_COLOR_BIT,
3206 mDeferredClears[colorIndexGL]);
3207 mDeferredClears.reset(colorIndexGL);
3208 }
3209
3210 if (dsAspectFlags)
3211 {
3212 RenderTargetVk *renderTarget = getDepthStencilRenderTarget();
3213 ASSERT(renderTarget);
3214
3215 gl::ImageIndex imageIndex =
3216 renderTarget->getImageIndexForClear(mCurrentFramebufferDesc.getLayerCount());
3217 renderTarget->getImageForWrite().stageClear(imageIndex, dsAspectFlags, dsClearValue);
3218 }
3219 }
3220
clearWithCommand(ContextVk * contextVk,const gl::Rectangle & scissoredRenderArea,ClearWithCommand behavior,vk::ClearValuesArray * clears)3221 void FramebufferVk::clearWithCommand(ContextVk *contextVk,
3222 const gl::Rectangle &scissoredRenderArea,
3223 ClearWithCommand behavior,
3224 vk::ClearValuesArray *clears)
3225 {
3226 // Clear is not affected by viewport, so ContextVk::updateScissor may have decided on a smaller
3227 // render area. Grow the render area to the full framebuffer size as this clear path is taken
3228 // when not scissored.
3229 vk::RenderPassCommandBufferHelper *renderPassCommands =
3230 &contextVk->getStartedRenderPassCommands();
3231 renderPassCommands->growRenderArea(contextVk, scissoredRenderArea);
3232
3233 gl::AttachmentVector<VkClearAttachment> attachments;
3234
3235 const bool optimizeWithLoadOp = behavior == ClearWithCommand::OptimizeWithLoadOp;
3236
3237 // Go through deferred clears and add them to the list of attachments to clear. If any
3238 // attachment is unused, skip the clear. clearWithLoadOp will follow and move the remaining
3239 // clears up to loadOp.
3240 vk::PackedAttachmentIndex colorIndexVk(0);
3241 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
3242 {
3243 if (clears->getColorMask().test(colorIndexGL))
3244 {
3245 if (renderPassCommands->hasAnyColorAccess(colorIndexVk) ||
3246 renderPassCommands->getRenderPassDesc().hasColorUnresolveAttachment(colorIndexGL) ||
3247 !optimizeWithLoadOp)
3248 {
3249 // With render pass objects, the clears are indexed by the subpass-mapped locations.
3250 // With dynamic rendering, they are indexed by the actual attachment index.
3251 const uint32_t clearAttachmentIndex =
3252 contextVk->getFeatures().preferDynamicRendering.enabled
3253 ? colorIndexVk.get()
3254 : static_cast<uint32_t>(colorIndexGL);
3255
3256 attachments.emplace_back(VkClearAttachment{
3257 VK_IMAGE_ASPECT_COLOR_BIT, clearAttachmentIndex, (*clears)[colorIndexGL]});
3258 clears->reset(colorIndexGL);
3259 ++contextVk->getPerfCounters().colorClearAttachments;
3260
3261 renderPassCommands->onColorAccess(colorIndexVk, vk::ResourceAccess::ReadWrite);
3262 }
3263 else
3264 {
3265 // Skip this attachment, so we can use a renderpass loadOp to clear it instead.
3266 // Note that if loadOp=Clear was already used for this color attachment, it will be
3267 // overriden by the new clear, which is valid because the attachment wasn't used in
3268 // between.
3269 }
3270 }
3271 ++colorIndexVk;
3272 }
3273
3274 // Add depth and stencil to list of attachments as needed.
3275 VkImageAspectFlags dsAspectFlags = 0;
3276 VkClearValue dsClearValue = {};
3277 dsClearValue.depthStencil.depth = clears->getDepthValue();
3278 dsClearValue.depthStencil.stencil = clears->getStencilValue();
3279 if (clears->testDepth() &&
3280 (renderPassCommands->hasAnyDepthAccess() ||
3281 renderPassCommands->getRenderPassDesc().hasDepthUnresolveAttachment() ||
3282 !optimizeWithLoadOp))
3283 {
3284 dsAspectFlags |= VK_IMAGE_ASPECT_DEPTH_BIT;
3285 // Explicitly mark a depth write because we are clearing the depth buffer.
3286 renderPassCommands->onDepthAccess(vk::ResourceAccess::ReadWrite);
3287 clears->reset(vk::kUnpackedDepthIndex);
3288 ++contextVk->getPerfCounters().depthClearAttachments;
3289 }
3290
3291 if (clears->testStencil() &&
3292 (renderPassCommands->hasAnyStencilAccess() ||
3293 renderPassCommands->getRenderPassDesc().hasStencilUnresolveAttachment() ||
3294 !optimizeWithLoadOp))
3295 {
3296 dsAspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT;
3297 // Explicitly mark a stencil write because we are clearing the stencil buffer.
3298 renderPassCommands->onStencilAccess(vk::ResourceAccess::ReadWrite);
3299 clears->reset(vk::kUnpackedStencilIndex);
3300 ++contextVk->getPerfCounters().stencilClearAttachments;
3301 }
3302
3303 if (dsAspectFlags != 0)
3304 {
3305 attachments.emplace_back(VkClearAttachment{dsAspectFlags, 0, dsClearValue});
3306
3307 // Because we may have changed the depth/stencil access mode, update read only depth/stencil
3308 // mode.
3309 renderPassCommands->updateDepthStencilReadOnlyMode(
3310 contextVk->getDepthStencilAttachmentFlags(), dsAspectFlags);
3311 }
3312
3313 if (attachments.empty())
3314 {
3315 // If called with the intent to definitely clear something with vkCmdClearAttachments, there
3316 // must have been something to clear!
3317 ASSERT(optimizeWithLoadOp);
3318 return;
3319 }
3320
3321 const uint32_t layerCount = mState.isMultiview() ? 1 : mCurrentFramebufferDesc.getLayerCount();
3322
3323 VkClearRect rect = {};
3324 rect.rect.offset.x = scissoredRenderArea.x;
3325 rect.rect.offset.y = scissoredRenderArea.y;
3326 rect.rect.extent.width = scissoredRenderArea.width;
3327 rect.rect.extent.height = scissoredRenderArea.height;
3328 rect.layerCount = layerCount;
3329 vk::RenderPassCommandBuffer *renderPassCommandBuffer = &renderPassCommands->getCommandBuffer();
3330
3331 renderPassCommandBuffer->clearAttachments(static_cast<uint32_t>(attachments.size()),
3332 attachments.data(), 1, &rect);
3333 return;
3334 }
3335
clearWithLoadOp(ContextVk * contextVk)3336 void FramebufferVk::clearWithLoadOp(ContextVk *contextVk)
3337 {
3338 vk::RenderPassCommandBufferHelper *renderPassCommands =
3339 &contextVk->getStartedRenderPassCommands();
3340
3341 // Update the render pass loadOps to clear the attachments.
3342 vk::PackedAttachmentIndex colorIndexVk(0);
3343 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
3344 {
3345 if (!mDeferredClears.test(colorIndexGL))
3346 {
3347 ++colorIndexVk;
3348 continue;
3349 }
3350
3351 ASSERT(!renderPassCommands->hasAnyColorAccess(colorIndexVk));
3352
3353 renderPassCommands->updateRenderPassColorClear(colorIndexVk, mDeferredClears[colorIndexGL]);
3354
3355 mDeferredClears.reset(colorIndexGL);
3356
3357 ++colorIndexVk;
3358 }
3359
3360 VkClearValue dsClearValue = {};
3361 dsClearValue.depthStencil.depth = mDeferredClears.getDepthValue();
3362 dsClearValue.depthStencil.stencil = mDeferredClears.getStencilValue();
3363 VkImageAspectFlags dsAspects = 0;
3364
3365 if (mDeferredClears.testDepth())
3366 {
3367 ASSERT(!renderPassCommands->hasAnyDepthAccess());
3368 dsAspects |= VK_IMAGE_ASPECT_DEPTH_BIT;
3369 mDeferredClears.reset(vk::kUnpackedDepthIndex);
3370 }
3371
3372 if (mDeferredClears.testStencil())
3373 {
3374 ASSERT(!renderPassCommands->hasAnyStencilAccess());
3375 dsAspects |= VK_IMAGE_ASPECT_STENCIL_BIT;
3376 mDeferredClears.reset(vk::kUnpackedStencilIndex);
3377 }
3378
3379 if (dsAspects != 0)
3380 {
3381 renderPassCommands->updateRenderPassDepthStencilClear(dsAspects, dsClearValue);
3382
3383 // The render pass can no longer be in read-only depth/stencil mode.
3384 renderPassCommands->updateDepthStencilReadOnlyMode(
3385 contextVk->getDepthStencilAttachmentFlags(), dsAspects);
3386 }
3387 }
3388
getSamplePosition(const gl::Context * context,size_t index,GLfloat * xy) const3389 angle::Result FramebufferVk::getSamplePosition(const gl::Context *context,
3390 size_t index,
3391 GLfloat *xy) const
3392 {
3393 int sampleCount = getSamples();
3394 rx::GetSamplePosition(sampleCount, index, xy);
3395 return angle::Result::Continue;
3396 }
3397
startNewRenderPass(ContextVk * contextVk,const gl::Rectangle & renderArea,vk::RenderPassCommandBuffer ** commandBufferOut,bool * renderPassDescChangedOut)3398 angle::Result FramebufferVk::startNewRenderPass(ContextVk *contextVk,
3399 const gl::Rectangle &renderArea,
3400 vk::RenderPassCommandBuffer **commandBufferOut,
3401 bool *renderPassDescChangedOut)
3402 {
3403 ANGLE_TRY(contextVk->flushCommandsAndEndRenderPass(RenderPassClosureReason::NewRenderPass));
3404
3405 // Initialize RenderPass info.
3406 vk::AttachmentOpsArray renderPassAttachmentOps;
3407 vk::PackedClearValuesArray packedClearValues;
3408 gl::DrawBufferMask previousUnresolveColorMask =
3409 mRenderPassDesc.getColorUnresolveAttachmentMask();
3410 const bool hasDeferredClears = mDeferredClears.any();
3411 const bool previousUnresolveDepth = mRenderPassDesc.hasDepthUnresolveAttachment();
3412 const bool previousUnresolveStencil = mRenderPassDesc.hasStencilUnresolveAttachment();
3413
3414 // Make sure render pass and framebuffer are in agreement w.r.t unresolve attachments.
3415 ASSERT(mCurrentFramebufferDesc.getUnresolveAttachmentMask() ==
3416 MakeUnresolveAttachmentMask(mRenderPassDesc));
3417 // ... w.r.t sRGB write control.
3418 ASSERT(mCurrentFramebufferDesc.getWriteControlMode() ==
3419 mRenderPassDesc.getSRGBWriteControlMode());
3420 // ... w.r.t foveation.
3421 ASSERT(mCurrentFramebufferDesc.hasFragmentShadingRateAttachment() ==
3422 mRenderPassDesc.hasFragmentShadingAttachment());
3423
3424 // Color attachments.
3425 const auto &colorRenderTargets = mRenderTargetCache.getColors();
3426 vk::PackedAttachmentIndex colorIndexVk(0);
3427 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
3428 {
3429 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
3430 ASSERT(colorRenderTarget);
3431
3432 // Color render targets are never entirely transient. Only depth/stencil
3433 // multisampled-render-to-texture textures can be so.
3434 ASSERT(!colorRenderTarget->isEntirelyTransient());
3435 const vk::RenderPassStoreOp storeOp = colorRenderTarget->isImageTransient()
3436 ? vk::RenderPassStoreOp::DontCare
3437 : vk::RenderPassStoreOp::Store;
3438
3439 if (mDeferredClears.test(colorIndexGL))
3440 {
3441 renderPassAttachmentOps.setOps(colorIndexVk, vk::RenderPassLoadOp::Clear, storeOp);
3442 packedClearValues.storeColor(colorIndexVk, mDeferredClears[colorIndexGL]);
3443 mDeferredClears.reset(colorIndexGL);
3444 }
3445 else
3446 {
3447 const vk::RenderPassLoadOp loadOp = colorRenderTarget->hasDefinedContent()
3448 ? vk::RenderPassLoadOp::Load
3449 : vk::RenderPassLoadOp::DontCare;
3450
3451 renderPassAttachmentOps.setOps(colorIndexVk, loadOp, storeOp);
3452 packedClearValues.storeColor(colorIndexVk, kUninitializedClearValue);
3453 }
3454 renderPassAttachmentOps.setStencilOps(colorIndexVk, vk::RenderPassLoadOp::DontCare,
3455 vk::RenderPassStoreOp::DontCare);
3456
3457 // If there's a resolve attachment, and loadOp needs to be LOAD, the multisampled attachment
3458 // needs to take its value from the resolve attachment. In this case, an initial subpass is
3459 // added for this very purpose which uses the resolve attachment as input attachment. As a
3460 // result, loadOp of the multisampled attachment can remain DONT_CARE.
3461 //
3462 // Note that this only needs to be done if the multisampled image and the resolve attachment
3463 // come from the same source. isImageTransient() indicates whether this should happen.
3464 if (colorRenderTarget->hasResolveAttachment() && colorRenderTarget->isImageTransient())
3465 {
3466 if (renderPassAttachmentOps[colorIndexVk].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD)
3467 {
3468 renderPassAttachmentOps[colorIndexVk].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
3469
3470 // Update the render pass desc to specify that this attachment should be unresolved.
3471 mRenderPassDesc.packColorUnresolveAttachment(colorIndexGL);
3472 }
3473 else
3474 {
3475 mRenderPassDesc.removeColorUnresolveAttachment(colorIndexGL);
3476 }
3477 }
3478 else
3479 {
3480 ASSERT(!mRenderPassDesc.getColorUnresolveAttachmentMask().test(colorIndexGL));
3481 }
3482
3483 ++colorIndexVk;
3484 }
3485
3486 // Depth/stencil attachment.
3487 vk::PackedAttachmentIndex depthStencilAttachmentIndex = vk::kAttachmentIndexInvalid;
3488 RenderTargetVk *depthStencilRenderTarget = getDepthStencilRenderTarget();
3489 if (depthStencilRenderTarget)
3490 {
3491 // depth stencil attachment always immediately follows color attachment
3492 depthStencilAttachmentIndex = colorIndexVk;
3493
3494 vk::RenderPassLoadOp depthLoadOp = vk::RenderPassLoadOp::Load;
3495 vk::RenderPassLoadOp stencilLoadOp = vk::RenderPassLoadOp::Load;
3496 vk::RenderPassStoreOp depthStoreOp = vk::RenderPassStoreOp::Store;
3497 vk::RenderPassStoreOp stencilStoreOp = vk::RenderPassStoreOp::Store;
3498
3499 // If the image data was previously discarded (with no update in between), don't attempt to
3500 // load the image. Additionally, if the multisampled image data is transient and there is
3501 // no resolve attachment, there's no data to load. The latter is the case with
3502 // depth/stencil texture attachments per GL_EXT_multisampled_render_to_texture2.
3503 if (!depthStencilRenderTarget->hasDefinedContent() ||
3504 depthStencilRenderTarget->isEntirelyTransient())
3505 {
3506 depthLoadOp = vk::RenderPassLoadOp::DontCare;
3507 }
3508 if (!depthStencilRenderTarget->hasDefinedStencilContent() ||
3509 depthStencilRenderTarget->isEntirelyTransient())
3510 {
3511 stencilLoadOp = vk::RenderPassLoadOp::DontCare;
3512 }
3513
3514 // If depth/stencil image is transient, no need to store its data at the end of the render
3515 // pass.
3516 if (depthStencilRenderTarget->isImageTransient())
3517 {
3518 depthStoreOp = vk::RenderPassStoreOp::DontCare;
3519 stencilStoreOp = vk::RenderPassStoreOp::DontCare;
3520 }
3521
3522 if (mDeferredClears.testDepth() || mDeferredClears.testStencil())
3523 {
3524 VkClearValue clearValue = {};
3525
3526 if (mDeferredClears.testDepth())
3527 {
3528 depthLoadOp = vk::RenderPassLoadOp::Clear;
3529 clearValue.depthStencil.depth = mDeferredClears.getDepthValue();
3530 mDeferredClears.reset(vk::kUnpackedDepthIndex);
3531 }
3532
3533 if (mDeferredClears.testStencil())
3534 {
3535 stencilLoadOp = vk::RenderPassLoadOp::Clear;
3536 clearValue.depthStencil.stencil = mDeferredClears.getStencilValue();
3537 mDeferredClears.reset(vk::kUnpackedStencilIndex);
3538 }
3539
3540 packedClearValues.storeDepthStencil(depthStencilAttachmentIndex, clearValue);
3541 }
3542 else
3543 {
3544 packedClearValues.storeDepthStencil(depthStencilAttachmentIndex,
3545 kUninitializedClearValue);
3546 }
3547
3548 const angle::Format &format = depthStencilRenderTarget->getImageIntendedFormat();
3549 // If the format we picked has stencil but user did not ask for it due to hardware
3550 // limitations, use DONT_CARE for load/store. The same logic for depth follows.
3551 if (format.stencilBits == 0)
3552 {
3553 stencilLoadOp = vk::RenderPassLoadOp::DontCare;
3554 stencilStoreOp = vk::RenderPassStoreOp::DontCare;
3555 }
3556 if (format.depthBits == 0)
3557 {
3558 depthLoadOp = vk::RenderPassLoadOp::DontCare;
3559 depthStoreOp = vk::RenderPassStoreOp::DontCare;
3560 }
3561
3562 // Similar to color attachments, if there's a resolve attachment and the multisampled image
3563 // is transient, depth/stencil data need to be unresolved in an initial subpass.
3564 if (depthStencilRenderTarget->hasResolveAttachment() &&
3565 depthStencilRenderTarget->isImageTransient())
3566 {
3567 const bool unresolveDepth = depthLoadOp == vk::RenderPassLoadOp::Load;
3568 const bool unresolveStencil = stencilLoadOp == vk::RenderPassLoadOp::Load;
3569
3570 if (unresolveDepth)
3571 {
3572 depthLoadOp = vk::RenderPassLoadOp::DontCare;
3573 }
3574
3575 if (unresolveStencil)
3576 {
3577 stencilLoadOp = vk::RenderPassLoadOp::DontCare;
3578
3579 // If VK_EXT_shader_stencil_export is not supported, stencil unresolve is done
3580 // through a method that requires stencil to have been cleared.
3581 if (!contextVk->getFeatures().supportsShaderStencilExport.enabled)
3582 {
3583 stencilLoadOp = vk::RenderPassLoadOp::Clear;
3584
3585 VkClearValue clearValue = packedClearValues[depthStencilAttachmentIndex];
3586 clearValue.depthStencil.stencil = 0;
3587 packedClearValues.storeDepthStencil(depthStencilAttachmentIndex, clearValue);
3588 }
3589 }
3590
3591 if (unresolveDepth || unresolveStencil)
3592 {
3593 if (unresolveDepth)
3594 {
3595 mRenderPassDesc.packDepthUnresolveAttachment();
3596 }
3597 if (unresolveStencil)
3598 {
3599 mRenderPassDesc.packStencilUnresolveAttachment();
3600 }
3601 }
3602 else
3603 {
3604 mRenderPassDesc.removeDepthStencilUnresolveAttachment();
3605 }
3606 }
3607
3608 renderPassAttachmentOps.setOps(depthStencilAttachmentIndex, depthLoadOp, depthStoreOp);
3609 renderPassAttachmentOps.setStencilOps(depthStencilAttachmentIndex, stencilLoadOp,
3610 stencilStoreOp);
3611 }
3612
3613 // If render pass description is changed, the previous render pass desc is no longer compatible.
3614 // Tell the context so that the graphics pipelines can be recreated.
3615 //
3616 // Note that render passes are compatible only if the differences are in loadOp/storeOp values,
3617 // or the existence of resolve attachments in single subpass render passes. The modification
3618 // here can add/remove a subpass, or modify its input attachments.
3619 gl::DrawBufferMask unresolveColorMask = mRenderPassDesc.getColorUnresolveAttachmentMask();
3620 const bool unresolveDepth = mRenderPassDesc.hasDepthUnresolveAttachment();
3621 const bool unresolveStencil = mRenderPassDesc.hasStencilUnresolveAttachment();
3622 const bool unresolveChanged = previousUnresolveColorMask != unresolveColorMask ||
3623 previousUnresolveDepth != unresolveDepth ||
3624 previousUnresolveStencil != unresolveStencil;
3625 if (unresolveChanged)
3626 {
3627 // Make sure framebuffer is recreated.
3628 releaseCurrentFramebuffer(contextVk);
3629
3630 mCurrentFramebufferDesc.updateUnresolveMask(MakeUnresolveAttachmentMask(mRenderPassDesc));
3631 }
3632
3633 vk::RenderPassFramebuffer framebuffer = {};
3634 ANGLE_TRY(getFramebuffer(contextVk, &framebuffer));
3635
3636 // If deferred clears were used in the render pass, the render area must cover the whole
3637 // framebuffer.
3638 ASSERT(!hasDeferredClears || renderArea == getRotatedCompleteRenderArea(contextVk));
3639
3640 ANGLE_TRY(contextVk->beginNewRenderPass(
3641 std::move(framebuffer), renderArea, mRenderPassDesc, renderPassAttachmentOps, colorIndexVk,
3642 depthStencilAttachmentIndex, packedClearValues, commandBufferOut));
3643 mLastRenderPassQueueSerial = contextVk->getStartedRenderPassCommands().getQueueSerial();
3644
3645 // Add the images to the renderpass tracking list (through onColorDraw).
3646 vk::PackedAttachmentIndex colorAttachmentIndex(0);
3647 for (size_t colorIndexGL : mState.getColorAttachmentsMask())
3648 {
3649 RenderTargetVk *colorRenderTarget = colorRenderTargets[colorIndexGL];
3650 colorRenderTarget->onColorDraw(contextVk, mCurrentFramebufferDesc.getLayerCount(),
3651 colorAttachmentIndex);
3652 ++colorAttachmentIndex;
3653 }
3654
3655 if (depthStencilRenderTarget)
3656 {
3657 // This must be called after hasDefined*Content() since it will set content to valid. If
3658 // the attachment ends up not used in the render pass, contents will be marked undefined at
3659 // endRenderPass. The actual layout determination is also deferred until the same time.
3660 depthStencilRenderTarget->onDepthStencilDraw(contextVk,
3661 mCurrentFramebufferDesc.getLayerCount());
3662 }
3663
3664 const bool anyUnresolve = unresolveColorMask.any() || unresolveDepth || unresolveStencil;
3665 if (anyUnresolve)
3666 {
3667 // Unresolve attachments if any.
3668 UtilsVk::UnresolveParameters params;
3669 params.unresolveColorMask = unresolveColorMask;
3670 params.unresolveDepth = unresolveDepth;
3671 params.unresolveStencil = unresolveStencil;
3672
3673 ANGLE_TRY(contextVk->getUtils().unresolve(contextVk, this, params));
3674
3675 // The unresolve subpass has only one draw call.
3676 ANGLE_TRY(contextVk->startNextSubpass());
3677 }
3678
3679 if (unresolveChanged || anyUnresolve)
3680 {
3681 contextVk->onDrawFramebufferRenderPassDescChange(this, renderPassDescChangedOut);
3682 }
3683
3684 // Add fragment shading rate to the tracking list.
3685 if (mCurrentFramebufferDesc.hasFragmentShadingRateAttachment())
3686 {
3687 contextVk->onFragmentShadingRateRead(&mFragmentShadingRateImage);
3688 }
3689
3690 return angle::Result::Continue;
3691 }
3692
getRenderArea(ContextVk * contextVk) const3693 gl::Rectangle FramebufferVk::getRenderArea(ContextVk *contextVk) const
3694 {
3695 if (hasDeferredClears())
3696 {
3697 return getRotatedCompleteRenderArea(contextVk);
3698 }
3699 else
3700 {
3701 return getRotatedScissoredRenderArea(contextVk);
3702 }
3703 }
3704
updateActiveColorMasks(size_t colorIndexGL,bool r,bool g,bool b,bool a)3705 void FramebufferVk::updateActiveColorMasks(size_t colorIndexGL, bool r, bool g, bool b, bool a)
3706 {
3707 gl::BlendStateExt::ColorMaskStorage::SetValueIndexed(
3708 colorIndexGL, gl::BlendStateExt::PackColorMask(r, g, b, a),
3709 &mActiveColorComponentMasksForClear);
3710 }
3711
getEmulatedAlphaAttachmentMask() const3712 const gl::DrawBufferMask &FramebufferVk::getEmulatedAlphaAttachmentMask() const
3713 {
3714 return mEmulatedAlphaAttachmentMask;
3715 }
3716
readPixelsImpl(ContextVk * contextVk,const gl::Rectangle & area,const PackPixelsParams & packPixelsParams,VkImageAspectFlagBits copyAspectFlags,RenderTargetVk * renderTarget,void * pixels)3717 angle::Result FramebufferVk::readPixelsImpl(ContextVk *contextVk,
3718 const gl::Rectangle &area,
3719 const PackPixelsParams &packPixelsParams,
3720 VkImageAspectFlagBits copyAspectFlags,
3721 RenderTargetVk *renderTarget,
3722 void *pixels)
3723 {
3724 ANGLE_TRACE_EVENT0("gpu.angle", "FramebufferVk::readPixelsImpl");
3725 gl::LevelIndex levelGL = renderTarget->getLevelIndex();
3726 uint32_t layer = renderTarget->getLayerIndex();
3727 return renderTarget->getImageForCopy().readPixels(contextVk, area, packPixelsParams,
3728 copyAspectFlags, levelGL, layer, pixels);
3729 }
3730
getReadImageExtents() const3731 gl::Extents FramebufferVk::getReadImageExtents() const
3732 {
3733 RenderTargetVk *readRenderTarget = mRenderTargetCache.getColorRead(mState);
3734 return readRenderTarget->getExtents();
3735 }
3736
3737 // Return the framebuffer's non-rotated render area. This is a gl::Rectangle that is based on the
3738 // dimensions of the framebuffer, IS NOT rotated, and IS NOT y-flipped
getNonRotatedCompleteRenderArea() const3739 gl::Rectangle FramebufferVk::getNonRotatedCompleteRenderArea() const
3740 {
3741 const gl::Box &dimensions = mState.getDimensions();
3742 return gl::Rectangle(0, 0, dimensions.width, dimensions.height);
3743 }
3744
3745 // Return the framebuffer's rotated render area. This is a gl::Rectangle that is based on the
3746 // dimensions of the framebuffer, IS ROTATED for the draw FBO, and IS NOT y-flipped
3747 //
3748 // Note: Since the rectangle is not scissored (i.e. x and y are guaranteed to be zero), only the
3749 // width and height must be swapped if the rotation is 90 or 270 degrees.
getRotatedCompleteRenderArea(ContextVk * contextVk) const3750 gl::Rectangle FramebufferVk::getRotatedCompleteRenderArea(ContextVk *contextVk) const
3751 {
3752 gl::Rectangle renderArea = getNonRotatedCompleteRenderArea();
3753 if (contextVk->isRotatedAspectRatioForDrawFBO())
3754 {
3755 // The surface is rotated 90/270 degrees. This changes the aspect ratio of the surface.
3756 std::swap(renderArea.width, renderArea.height);
3757 }
3758 return renderArea;
3759 }
3760
3761 // Return the framebuffer's scissored and rotated render area. This is a gl::Rectangle that is
3762 // based on the dimensions of the framebuffer, is clipped to the scissor, IS ROTATED and IS
3763 // Y-FLIPPED for the draw FBO.
3764 //
3765 // Note: Since the rectangle is scissored, it must be fully rotated, and not just have the width
3766 // and height swapped.
getRotatedScissoredRenderArea(ContextVk * contextVk) const3767 gl::Rectangle FramebufferVk::getRotatedScissoredRenderArea(ContextVk *contextVk) const
3768 {
3769 const gl::Rectangle renderArea = getNonRotatedCompleteRenderArea();
3770 bool invertViewport = contextVk->isViewportFlipEnabledForDrawFBO();
3771 gl::Rectangle scissoredArea = ClipRectToScissor(contextVk->getState(), renderArea, false);
3772 gl::Rectangle rotatedScissoredArea;
3773 RotateRectangle(contextVk->getRotationDrawFramebuffer(), invertViewport, renderArea.width,
3774 renderArea.height, scissoredArea, &rotatedScissoredArea);
3775 return rotatedScissoredArea;
3776 }
3777
getSamples() const3778 GLint FramebufferVk::getSamples() const
3779 {
3780 const gl::FramebufferAttachment *lastAttachment = nullptr;
3781
3782 for (size_t colorIndexGL : mState.getEnabledDrawBuffers() & mState.getColorAttachmentsMask())
3783 {
3784 const gl::FramebufferAttachment *color = mState.getColorAttachment(colorIndexGL);
3785 ASSERT(color);
3786
3787 if (color->isRenderToTexture())
3788 {
3789 return color->getSamples();
3790 }
3791
3792 lastAttachment = color;
3793 }
3794 const gl::FramebufferAttachment *depthStencil = mState.getDepthOrStencilAttachment();
3795 if (depthStencil)
3796 {
3797 if (depthStencil->isRenderToTexture())
3798 {
3799 return depthStencil->getSamples();
3800 }
3801 lastAttachment = depthStencil;
3802 }
3803
3804 // If none of the attachments are multisampled-render-to-texture, take the sample count from the
3805 // last attachment (any would have worked, as they would all have the same sample count).
3806 return std::max(lastAttachment ? lastAttachment->getSamples() : 1, 1);
3807 }
3808
flushDepthStencilDeferredClear(ContextVk * contextVk,VkImageAspectFlagBits aspect)3809 angle::Result FramebufferVk::flushDepthStencilDeferredClear(ContextVk *contextVk,
3810 VkImageAspectFlagBits aspect)
3811 {
3812 const bool isDepth = aspect == VK_IMAGE_ASPECT_DEPTH_BIT;
3813
3814 // Pick out the deferred clear for the given aspect, and issue it ahead of the render pass.
3815 // This is used when switching this aspect to read-only mode, in which case the clear operation
3816 // for the aspect cannot be done as part of the render pass loadOp.
3817 ASSERT(!isDepth || hasDeferredDepthClear());
3818 ASSERT(isDepth || hasDeferredStencilClear());
3819 ASSERT(mState.getDepthOrStencilAttachment() != nullptr);
3820
3821 RenderTargetVk *renderTarget = getDepthStencilRenderTarget();
3822 vk::ImageHelper &image = renderTarget->getImageForCopy();
3823
3824 // Depth/stencil attachments cannot be 3D.
3825 ASSERT(!renderTarget->is3DImage());
3826
3827 vk::CommandBufferAccess access;
3828 access.onImageTransferWrite(renderTarget->getLevelIndex(), 1, renderTarget->getLayerIndex(), 1,
3829 image.getAspectFlags(), &image);
3830 vk::OutsideRenderPassCommandBuffer *commandBuffer;
3831 ANGLE_TRY(contextVk->getOutsideRenderPassCommandBuffer(access, &commandBuffer));
3832
3833 VkImageSubresourceRange range = {};
3834 range.aspectMask = aspect;
3835 range.baseMipLevel = image.toVkLevel(renderTarget->getLevelIndex()).get();
3836 range.levelCount = 1;
3837 range.baseArrayLayer = renderTarget->getLayerIndex();
3838 range.layerCount = 1;
3839
3840 VkClearDepthStencilValue clearValue = {};
3841
3842 if (isDepth)
3843 {
3844 clearValue.depth = mDeferredClears.getDepthValue();
3845 mDeferredClears.reset(vk::kUnpackedDepthIndex);
3846 }
3847 else
3848 {
3849 clearValue.stencil = mDeferredClears.getStencilValue();
3850 mDeferredClears.reset(vk::kUnpackedStencilIndex);
3851 }
3852
3853 commandBuffer->clearDepthStencilImage(
3854 image.getImage(), image.getCurrentLayout(contextVk->getRenderer()), clearValue, 1, &range);
3855 return angle::Result::Continue;
3856 }
3857
flushDeferredClears(ContextVk * contextVk)3858 angle::Result FramebufferVk::flushDeferredClears(ContextVk *contextVk)
3859 {
3860 if (mDeferredClears.empty())
3861 {
3862 return angle::Result::Continue;
3863 }
3864
3865 return contextVk->startRenderPass(getRotatedCompleteRenderArea(contextVk), nullptr, nullptr);
3866 }
3867
switchToColorFramebufferFetchMode(ContextVk * contextVk,bool hasColorFramebufferFetch)3868 void FramebufferVk::switchToColorFramebufferFetchMode(ContextVk *contextVk,
3869 bool hasColorFramebufferFetch)
3870 {
3871 // Framebuffer fetch use by the shader does not affect the framebuffer object in any way with
3872 // dynamic rendering.
3873 ASSERT(!contextVk->getFeatures().preferDynamicRendering.enabled);
3874
3875 // The switch happens once, and is permanent.
3876 if (mCurrentFramebufferDesc.hasColorFramebufferFetch() == hasColorFramebufferFetch)
3877 {
3878 return;
3879 }
3880
3881 mCurrentFramebufferDesc.setColorFramebufferFetchMode(hasColorFramebufferFetch);
3882
3883 mRenderPassDesc.setFramebufferFetchMode(hasColorFramebufferFetch
3884 ? vk::FramebufferFetchMode::Color
3885 : vk::FramebufferFetchMode::None);
3886 contextVk->onDrawFramebufferRenderPassDescChange(this, nullptr);
3887
3888 // Make sure framebuffer is recreated.
3889 releaseCurrentFramebuffer(contextVk);
3890
3891 // Clear the framebuffer cache, as none of the old framebuffers are usable.
3892 if (contextVk->getFeatures().permanentlySwitchToFramebufferFetchMode.enabled)
3893 {
3894 ASSERT(hasColorFramebufferFetch);
3895 releaseCurrentFramebuffer(contextVk);
3896 }
3897 }
3898
updateLegacyDither(ContextVk * contextVk)3899 bool FramebufferVk::updateLegacyDither(ContextVk *contextVk)
3900 {
3901 if (contextVk->getFeatures().supportsLegacyDithering.enabled &&
3902 mRenderPassDesc.isLegacyDitherEnabled() != contextVk->isDitherEnabled())
3903 {
3904 mRenderPassDesc.setLegacyDither(contextVk->isDitherEnabled());
3905 return true;
3906 }
3907
3908 return false;
3909 }
3910 } // namespace rx
3911