• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // ContextVk.h:
7 //    Defines the class interface for ContextVk, implementing ContextImpl.
8 //
9 
10 #ifndef LIBANGLE_RENDERER_VULKAN_CONTEXTVK_H_
11 #define LIBANGLE_RENDERER_VULKAN_CONTEXTVK_H_
12 
13 #include <condition_variable>
14 
15 #include "common/PackedEnums.h"
16 #include "common/vulkan/vk_headers.h"
17 #include "image_util/loadimage.h"
18 #include "libANGLE/renderer/ContextImpl.h"
19 #include "libANGLE/renderer/renderer_utils.h"
20 #include "libANGLE/renderer/vulkan/DisplayVk.h"
21 #include "libANGLE/renderer/vulkan/OverlayVk.h"
22 #include "libANGLE/renderer/vulkan/PersistentCommandPool.h"
23 #include "libANGLE/renderer/vulkan/ShareGroupVk.h"
24 #include "libANGLE/renderer/vulkan/vk_helpers.h"
25 #include "libANGLE/renderer/vulkan/vk_renderer.h"
26 
27 namespace angle
28 {
29 struct FeaturesVk;
30 }  // namespace angle
31 
32 namespace rx
33 {
34 namespace vk
35 {
36 class SyncHelper;
37 }  // namespace vk
38 
39 class ConversionBuffer;
40 class ProgramExecutableVk;
41 class WindowSurfaceVk;
42 class OffscreenSurfaceVk;
43 class ShareGroupVk;
44 
45 static constexpr uint32_t kMaxGpuEventNameLen = 32;
46 using EventName                               = std::array<char, kMaxGpuEventNameLen>;
47 
48 using ContextVkDescriptorSetList = angle::PackedEnumMap<PipelineType, uint32_t>;
49 using CounterPipelineTypeMap     = angle::PackedEnumMap<PipelineType, uint32_t>;
50 
51 enum class GraphicsEventCmdBuf
52 {
53     NotInQueryCmd              = 0,
54     InOutsideCmdBufQueryCmd    = 1,
55     InRenderPassCmdBufQueryCmd = 2,
56 
57     InvalidEnum = 3,
58     EnumCount   = 3,
59 };
60 
61 // Why depth/stencil feedback loop is being updated.  Based on whether it's due to a draw or clear,
62 // different GL state affect depth/stencil write.
63 enum class UpdateDepthFeedbackLoopReason
64 {
65     None,
66     Draw,
67     Clear,
68 };
69 
70 static constexpr GLbitfield kBufferMemoryBarrierBits =
71     GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT | GL_ELEMENT_ARRAY_BARRIER_BIT | GL_UNIFORM_BARRIER_BIT |
72     GL_COMMAND_BARRIER_BIT | GL_PIXEL_BUFFER_BARRIER_BIT | GL_BUFFER_UPDATE_BARRIER_BIT |
73     GL_TRANSFORM_FEEDBACK_BARRIER_BIT | GL_ATOMIC_COUNTER_BARRIER_BIT |
74     GL_SHADER_STORAGE_BARRIER_BIT | GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT_EXT;
75 static constexpr GLbitfield kImageMemoryBarrierBits =
76     GL_TEXTURE_FETCH_BARRIER_BIT | GL_SHADER_IMAGE_ACCESS_BARRIER_BIT |
77     GL_TEXTURE_UPDATE_BARRIER_BIT | GL_FRAMEBUFFER_BARRIER_BIT;
78 
79 class ContextVk : public ContextImpl, public vk::Context, public MultisampleTextureInitializer
80 {
81   public:
82     ContextVk(const gl::State &state, gl::ErrorSet *errorSet, vk::Renderer *renderer);
83     ~ContextVk() override;
84 
85     angle::Result initialize(const angle::ImageLoadContext &imageLoadContext) override;
86 
87     void onDestroy(const gl::Context *context) override;
88 
89     // Flush and finish.
90     angle::Result flush(const gl::Context *context) override;
91     angle::Result finish(const gl::Context *context) override;
92 
93     // Drawing methods.
94     angle::Result drawArrays(const gl::Context *context,
95                              gl::PrimitiveMode mode,
96                              GLint first,
97                              GLsizei count) override;
98     angle::Result drawArraysInstanced(const gl::Context *context,
99                                       gl::PrimitiveMode mode,
100                                       GLint first,
101                                       GLsizei count,
102                                       GLsizei instanceCount) override;
103     angle::Result drawArraysInstancedBaseInstance(const gl::Context *context,
104                                                   gl::PrimitiveMode mode,
105                                                   GLint first,
106                                                   GLsizei count,
107                                                   GLsizei instanceCount,
108                                                   GLuint baseInstance) override;
109 
110     angle::Result drawElements(const gl::Context *context,
111                                gl::PrimitiveMode mode,
112                                GLsizei count,
113                                gl::DrawElementsType type,
114                                const void *indices) override;
115     angle::Result drawElementsBaseVertex(const gl::Context *context,
116                                          gl::PrimitiveMode mode,
117                                          GLsizei count,
118                                          gl::DrawElementsType type,
119                                          const void *indices,
120                                          GLint baseVertex) override;
121     angle::Result drawElementsInstanced(const gl::Context *context,
122                                         gl::PrimitiveMode mode,
123                                         GLsizei count,
124                                         gl::DrawElementsType type,
125                                         const void *indices,
126                                         GLsizei instanceCount) override;
127     angle::Result drawElementsInstancedBaseVertex(const gl::Context *context,
128                                                   gl::PrimitiveMode mode,
129                                                   GLsizei count,
130                                                   gl::DrawElementsType type,
131                                                   const void *indices,
132                                                   GLsizei instanceCount,
133                                                   GLint baseVertex) override;
134     angle::Result drawElementsInstancedBaseVertexBaseInstance(const gl::Context *context,
135                                                               gl::PrimitiveMode mode,
136                                                               GLsizei count,
137                                                               gl::DrawElementsType type,
138                                                               const void *indices,
139                                                               GLsizei instances,
140                                                               GLint baseVertex,
141                                                               GLuint baseInstance) override;
142     angle::Result drawRangeElements(const gl::Context *context,
143                                     gl::PrimitiveMode mode,
144                                     GLuint start,
145                                     GLuint end,
146                                     GLsizei count,
147                                     gl::DrawElementsType type,
148                                     const void *indices) override;
149     angle::Result drawRangeElementsBaseVertex(const gl::Context *context,
150                                               gl::PrimitiveMode mode,
151                                               GLuint start,
152                                               GLuint end,
153                                               GLsizei count,
154                                               gl::DrawElementsType type,
155                                               const void *indices,
156                                               GLint baseVertex) override;
157     angle::Result drawArraysIndirect(const gl::Context *context,
158                                      gl::PrimitiveMode mode,
159                                      const void *indirect) override;
160     angle::Result drawElementsIndirect(const gl::Context *context,
161                                        gl::PrimitiveMode mode,
162                                        gl::DrawElementsType type,
163                                        const void *indirect) override;
164 
165     angle::Result multiDrawArrays(const gl::Context *context,
166                                   gl::PrimitiveMode mode,
167                                   const GLint *firsts,
168                                   const GLsizei *counts,
169                                   GLsizei drawcount) override;
170     angle::Result multiDrawArraysInstanced(const gl::Context *context,
171                                            gl::PrimitiveMode mode,
172                                            const GLint *firsts,
173                                            const GLsizei *counts,
174                                            const GLsizei *instanceCounts,
175                                            GLsizei drawcount) override;
176     angle::Result multiDrawArraysIndirect(const gl::Context *context,
177                                           gl::PrimitiveMode mode,
178                                           const void *indirect,
179                                           GLsizei drawcount,
180                                           GLsizei stride) override;
181     angle::Result multiDrawElements(const gl::Context *context,
182                                     gl::PrimitiveMode mode,
183                                     const GLsizei *counts,
184                                     gl::DrawElementsType type,
185                                     const GLvoid *const *indices,
186                                     GLsizei drawcount) override;
187     angle::Result multiDrawElementsInstanced(const gl::Context *context,
188                                              gl::PrimitiveMode mode,
189                                              const GLsizei *counts,
190                                              gl::DrawElementsType type,
191                                              const GLvoid *const *indices,
192                                              const GLsizei *instanceCounts,
193                                              GLsizei drawcount) override;
194     angle::Result multiDrawElementsIndirect(const gl::Context *context,
195                                             gl::PrimitiveMode mode,
196                                             gl::DrawElementsType type,
197                                             const void *indirect,
198                                             GLsizei drawcount,
199                                             GLsizei stride) override;
200     angle::Result multiDrawArraysInstancedBaseInstance(const gl::Context *context,
201                                                        gl::PrimitiveMode mode,
202                                                        const GLint *firsts,
203                                                        const GLsizei *counts,
204                                                        const GLsizei *instanceCounts,
205                                                        const GLuint *baseInstances,
206                                                        GLsizei drawcount) override;
207     angle::Result multiDrawElementsInstancedBaseVertexBaseInstance(const gl::Context *context,
208                                                                    gl::PrimitiveMode mode,
209                                                                    const GLsizei *counts,
210                                                                    gl::DrawElementsType type,
211                                                                    const GLvoid *const *indices,
212                                                                    const GLsizei *instanceCounts,
213                                                                    const GLint *baseVertices,
214                                                                    const GLuint *baseInstances,
215                                                                    GLsizei drawcount) override;
216 
217     // MultiDrawIndirect helper functions
218     angle::Result multiDrawElementsIndirectHelper(const gl::Context *context,
219                                                   gl::PrimitiveMode mode,
220                                                   gl::DrawElementsType type,
221                                                   const void *indirect,
222                                                   GLsizei drawcount,
223                                                   GLsizei stride);
224     angle::Result multiDrawArraysIndirectHelper(const gl::Context *context,
225                                                 gl::PrimitiveMode mode,
226                                                 const void *indirect,
227                                                 GLsizei drawcount,
228                                                 GLsizei stride);
229 
230     // ShareGroup
getShareGroup()231     ShareGroupVk *getShareGroup() { return mShareGroupVk; }
getPipelineLayoutCache()232     PipelineLayoutCache &getPipelineLayoutCache()
233     {
234         return mShareGroupVk->getPipelineLayoutCache();
235     }
getDescriptorSetLayoutCache()236     DescriptorSetLayoutCache &getDescriptorSetLayoutCache()
237     {
238         return mShareGroupVk->getDescriptorSetLayoutCache();
239     }
getMetaDescriptorPools()240     vk::DescriptorSetArray<vk::MetaDescriptorPool> &getMetaDescriptorPools()
241     {
242         return mShareGroupVk->getMetaDescriptorPools();
243     }
244 
245     // Device loss
246     gl::GraphicsResetStatus getResetStatus() override;
247 
isDebugEnabled()248     bool isDebugEnabled()
249     {
250         return mRenderer->enableDebugUtils() || mRenderer->angleDebuggerMode();
251     }
252 
253     // EXT_debug_marker
254     angle::Result insertEventMarker(GLsizei length, const char *marker) override;
255     angle::Result pushGroupMarker(GLsizei length, const char *marker) override;
256     angle::Result popGroupMarker() override;
257 
258     void insertEventMarkerImpl(GLenum source, const char *marker);
259 
260     // KHR_debug
261     angle::Result pushDebugGroup(const gl::Context *context,
262                                  GLenum source,
263                                  GLuint id,
264                                  const std::string &message) override;
265     angle::Result popDebugGroup(const gl::Context *context) override;
266 
267     // Record GL API calls for debuggers
268     void logEvent(const char *eventString);
269     void endEventLog(angle::EntryPoint entryPoint, PipelineType pipelineType);
270     void endEventLogForClearOrQuery();
271 
272     bool isViewportFlipEnabledForDrawFBO() const;
273     bool isViewportFlipEnabledForReadFBO() const;
274     // When the device/surface is rotated such that the surface's aspect ratio is different than
275     // the native device (e.g. 90 degrees), the width and height of the viewport, scissor, and
276     // render area must be swapped.
277     bool isRotatedAspectRatioForDrawFBO() const;
278     bool isRotatedAspectRatioForReadFBO() const;
279     SurfaceRotation getRotationDrawFramebuffer() const;
280     SurfaceRotation getRotationReadFramebuffer() const;
281     SurfaceRotation getSurfaceRotationImpl(const gl::Framebuffer *framebuffer,
282                                            const egl::Surface *surface);
283 
284     // View port (x, y, w, h) will be determined by a combination of -
285     // 1. clip space origin
286     // 2. isViewportFlipEnabledForDrawFBO
287     // For userdefined FBOs it will be based on the value of isViewportFlipEnabledForDrawFBO.
288     // For default FBOs it will be XOR of ClipOrigin and isViewportFlipEnabledForDrawFBO.
289     // isYFlipEnabledForDrawFBO indicates the rendered image is upside-down.
isYFlipEnabledForDrawFBO()290     ANGLE_INLINE bool isYFlipEnabledForDrawFBO() const
291     {
292         return mState.getClipOrigin() == gl::ClipOrigin::UpperLeft
293                    ? !isViewportFlipEnabledForDrawFBO()
294                    : isViewportFlipEnabledForDrawFBO();
295     }
296 
297     // State sync with dirty bits.
298     angle::Result syncState(const gl::Context *context,
299                             const gl::state::DirtyBits dirtyBits,
300                             const gl::state::DirtyBits bitMask,
301                             const gl::state::ExtendedDirtyBits extendedDirtyBits,
302                             const gl::state::ExtendedDirtyBits extendedBitMask,
303                             gl::Command command) override;
304 
305     // Disjoint timer queries
306     GLint getGPUDisjoint() override;
307     GLint64 getTimestamp() override;
308 
309     // Context switching
310     angle::Result onMakeCurrent(const gl::Context *context) override;
311     angle::Result onUnMakeCurrent(const gl::Context *context) override;
312     angle::Result onSurfaceUnMakeCurrent(WindowSurfaceVk *surface);
313     angle::Result onSurfaceUnMakeCurrent(OffscreenSurfaceVk *surface);
314 
315     // Native capabilities, unmodified by gl::Context.
316     gl::Caps getNativeCaps() const override;
317     const gl::TextureCapsMap &getNativeTextureCaps() const override;
318     const gl::Extensions &getNativeExtensions() const override;
319     const gl::Limitations &getNativeLimitations() const override;
320     const ShPixelLocalStorageOptions &getNativePixelLocalStorageOptions() const override;
321 
322     // Shader creation
323     CompilerImpl *createCompiler() override;
324     ShaderImpl *createShader(const gl::ShaderState &state) override;
325     ProgramImpl *createProgram(const gl::ProgramState &state) override;
326     ProgramExecutableImpl *createProgramExecutable(
327         const gl::ProgramExecutable *executable) override;
328 
329     // Framebuffer creation
330     FramebufferImpl *createFramebuffer(const gl::FramebufferState &state) override;
331 
332     // Texture creation
333     TextureImpl *createTexture(const gl::TextureState &state) override;
334 
335     // Renderbuffer creation
336     RenderbufferImpl *createRenderbuffer(const gl::RenderbufferState &state) override;
337 
338     // Buffer creation
339     BufferImpl *createBuffer(const gl::BufferState &state) override;
340 
341     // Vertex Array creation
342     VertexArrayImpl *createVertexArray(const gl::VertexArrayState &state) override;
343 
344     // Query and Fence creation
345     QueryImpl *createQuery(gl::QueryType type) override;
346     FenceNVImpl *createFenceNV() override;
347     SyncImpl *createSync() override;
348 
349     // Transform Feedback creation
350     TransformFeedbackImpl *createTransformFeedback(
351         const gl::TransformFeedbackState &state) override;
352 
353     // Sampler object creation
354     SamplerImpl *createSampler(const gl::SamplerState &state) override;
355 
356     // Program Pipeline object creation
357     ProgramPipelineImpl *createProgramPipeline(const gl::ProgramPipelineState &data) override;
358 
359     // Memory object creation.
360     MemoryObjectImpl *createMemoryObject() override;
361 
362     // Semaphore creation.
363     SemaphoreImpl *createSemaphore() override;
364 
365     // Overlay creation.
366     OverlayImpl *createOverlay(const gl::OverlayState &state) override;
367 
368     angle::Result dispatchCompute(const gl::Context *context,
369                                   GLuint numGroupsX,
370                                   GLuint numGroupsY,
371                                   GLuint numGroupsZ) override;
372     angle::Result dispatchComputeIndirect(const gl::Context *context, GLintptr indirect) override;
373 
374     angle::Result memoryBarrier(const gl::Context *context, GLbitfield barriers) override;
375     angle::Result memoryBarrierByRegion(const gl::Context *context, GLbitfield barriers) override;
376 
invalidateTexture(gl::TextureType target)377     ANGLE_INLINE void invalidateTexture(gl::TextureType target) override {}
378 
hasDisplayTextureShareGroup()379     bool hasDisplayTextureShareGroup() const { return mState.hasDisplayTextureShareGroup(); }
380 
381     // EXT_shader_framebuffer_fetch_non_coherent
382     void framebufferFetchBarrier() override;
383 
384     // KHR_blend_equation_advanced
385     void blendBarrier() override;
386 
387     // GL_ANGLE_vulkan_image
388     angle::Result acquireTextures(const gl::Context *context,
389                                   const gl::TextureBarrierVector &textureBarriers) override;
390     angle::Result releaseTextures(const gl::Context *context,
391                                   gl::TextureBarrierVector *textureBarriers) override;
392 
393     // Sets effective Context Priority. Changed by ShareGroupVk.
setPriority(egl::ContextPriority newPriority)394     void setPriority(egl::ContextPriority newPriority)
395     {
396         mContextPriority  = newPriority;
397         mDeviceQueueIndex = mRenderer->getDeviceQueueIndex(mContextPriority);
398     }
399 
400     VkDevice getDevice() const;
401     // Effective Context Priority
getPriority()402     egl::ContextPriority getPriority() const { return mContextPriority; }
getProtectionType()403     vk::ProtectionType getProtectionType() const { return mProtectionType; }
404 
getFeatures()405     ANGLE_INLINE const angle::FeaturesVk &getFeatures() const { return mRenderer->getFeatures(); }
406 
invalidateVertexAndIndexBuffers()407     ANGLE_INLINE void invalidateVertexAndIndexBuffers()
408     {
409         mGraphicsDirtyBits |= kIndexAndVertexDirtyBits;
410     }
411 
412     angle::Result onVertexBufferChange(const vk::BufferHelper *vertexBuffer);
413 
414     angle::Result onVertexAttributeChange(size_t attribIndex,
415                                           GLuint stride,
416                                           GLuint divisor,
417                                           angle::FormatID format,
418                                           bool compressed,
419                                           GLuint relativeOffset,
420                                           const vk::BufferHelper *vertexBuffer);
421 
422     void invalidateDefaultAttribute(size_t attribIndex);
423     void invalidateDefaultAttributes(const gl::AttributesMask &dirtyMask);
424     angle::Result onFramebufferChange(FramebufferVk *framebufferVk, gl::Command command);
425     void onDrawFramebufferRenderPassDescChange(FramebufferVk *framebufferVk,
426                                                bool *renderPassDescChangedOut);
onHostVisibleBufferWrite()427     void onHostVisibleBufferWrite() { mIsAnyHostVisibleBufferWritten = true; }
428 
429     void invalidateCurrentTransformFeedbackBuffers();
430     void onTransformFeedbackStateChanged();
431     angle::Result onBeginTransformFeedback(
432         size_t bufferCount,
433         const gl::TransformFeedbackBuffersArray<vk::BufferHelper *> &buffers,
434         const gl::TransformFeedbackBuffersArray<vk::BufferHelper> &counterBuffers);
435     void onEndTransformFeedback();
436     angle::Result onPauseTransformFeedback();
437     void pauseTransformFeedbackIfActiveUnpaused();
438 
onColorAccessChange()439     void onColorAccessChange() { mGraphicsDirtyBits |= kColorAccessChangeDirtyBits; }
onDepthStencilAccessChange()440     void onDepthStencilAccessChange() { mGraphicsDirtyBits |= kDepthStencilAccessChangeDirtyBits; }
441 
442     // When UtilsVk issues draw or dispatch calls, it binds a new pipeline and descriptor sets that
443     // the context is not aware of.  These functions are called to make sure the pipeline and
444     // affected descriptor set bindings are dirtied for the next application draw/dispatch call.
445     void invalidateGraphicsPipelineBinding();
446     void invalidateComputePipelineBinding();
447     void invalidateGraphicsDescriptorSet(DescriptorSetIndex usedDescriptorSet);
448     void invalidateComputeDescriptorSet(DescriptorSetIndex usedDescriptorSet);
449     void invalidateAllDynamicState();
450     angle::Result updateRenderPassDepthFeedbackLoopMode(
451         UpdateDepthFeedbackLoopReason depthReason,
452         UpdateDepthFeedbackLoopReason stencilReason);
453 
454     angle::Result optimizeRenderPassForPresent(vk::ImageViewHelper *colorImageView,
455                                                vk::ImageHelper *colorImage,
456                                                vk::ImageHelper *colorImageMS,
457                                                bool isSharedPresentMode,
458                                                bool *imageResolved);
459 
460     vk::DynamicQueryPool *getQueryPool(gl::QueryType queryType);
461 
462     const VkClearValue &getClearColorValue() const;
463     const VkClearValue &getClearDepthStencilValue() const;
464     gl::BlendStateExt::ColorMaskStorage::Type getClearColorMasks() const;
getScissor()465     const VkRect2D &getScissor() const { return mScissor; }
466     angle::Result getIncompleteTexture(const gl::Context *context,
467                                        gl::TextureType type,
468                                        gl::SamplerFormat format,
469                                        gl::Texture **textureOut);
470     void updateColorMasks();
471     void updateBlendFuncsAndEquations();
472 
473     void handleError(VkResult errorCode,
474                      const char *file,
475                      const char *function,
476                      unsigned int line) override;
477 
478     angle::Result onIndexBufferChange(const vk::BufferHelper *currentIndexBuffer);
479 
480     angle::Result flushAndSubmitCommands(const vk::Semaphore *semaphore,
481                                          const vk::SharedExternalFence *externalFence,
482                                          RenderPassClosureReason renderPassClosureReason);
483 
484     angle::Result finishImpl(RenderPassClosureReason renderPassClosureReason);
485 
486     void addWaitSemaphore(VkSemaphore semaphore, VkPipelineStageFlags stageMask);
487 
488     template <typename T>
addGarbage(T * object)489     void addGarbage(T *object)
490     {
491         if (object->valid())
492         {
493             mCurrentGarbage.emplace_back(vk::GetGarbage(object));
494         }
495     }
496 
497     angle::Result getCompatibleRenderPass(const vk::RenderPassDesc &desc,
498                                           const vk::RenderPass **renderPassOut);
499     angle::Result getRenderPassWithOps(const vk::RenderPassDesc &desc,
500                                        const vk::AttachmentOpsArray &ops,
501                                        const vk::RenderPass **renderPassOut);
502 
getShaderLibrary()503     vk::ShaderLibrary &getShaderLibrary() { return mShaderLibrary; }
getUtils()504     UtilsVk &getUtils() { return mUtils; }
505 
506     angle::Result getTimestamp(uint64_t *timestampOut);
507 
508     // Create Begin/End/Instant GPU trace events, which take their timestamps from GPU queries.
509     // The events are queued until the query results are available.  Possible values for `phase`
510     // are TRACE_EVENT_PHASE_*
traceGpuEvent(vk::OutsideRenderPassCommandBuffer * commandBuffer,char phase,const EventName & name)511     ANGLE_INLINE angle::Result traceGpuEvent(vk::OutsideRenderPassCommandBuffer *commandBuffer,
512                                              char phase,
513                                              const EventName &name)
514     {
515         if (mGpuEventsEnabled)
516             return traceGpuEventImpl(commandBuffer, phase, name);
517         return angle::Result::Continue;
518     }
519 
getDebug()520     const gl::Debug &getDebug() const { return mState.getDebug(); }
getOverlay()521     const gl::OverlayType *getOverlay() const { return mState.getOverlay(); }
522 
523     angle::Result onBufferReleaseToExternal(const vk::BufferHelper &buffer);
524     angle::Result onImageReleaseToExternal(const vk::ImageHelper &image);
525 
onImageRenderPassRead(VkImageAspectFlags aspectFlags,vk::ImageLayout imageLayout,vk::ImageHelper * image)526     void onImageRenderPassRead(VkImageAspectFlags aspectFlags,
527                                vk::ImageLayout imageLayout,
528                                vk::ImageHelper *image)
529     {
530         ASSERT(mRenderPassCommands->started());
531         mRenderPassCommands->imageRead(this, aspectFlags, imageLayout, image);
532     }
533 
onImageRenderPassWrite(gl::LevelIndex level,uint32_t layerStart,uint32_t layerCount,VkImageAspectFlags aspectFlags,vk::ImageLayout imageLayout,vk::ImageHelper * image)534     void onImageRenderPassWrite(gl::LevelIndex level,
535                                 uint32_t layerStart,
536                                 uint32_t layerCount,
537                                 VkImageAspectFlags aspectFlags,
538                                 vk::ImageLayout imageLayout,
539                                 vk::ImageHelper *image)
540     {
541         ASSERT(mRenderPassCommands->started());
542         mRenderPassCommands->imageWrite(this, level, layerStart, layerCount, aspectFlags,
543                                         imageLayout, image);
544     }
545 
onColorDraw(gl::LevelIndex level,uint32_t layerStart,uint32_t layerCount,vk::ImageHelper * image,vk::ImageHelper * resolveImage,UniqueSerial imageSiblingSerial,vk::PackedAttachmentIndex packedAttachmentIndex)546     void onColorDraw(gl::LevelIndex level,
547                      uint32_t layerStart,
548                      uint32_t layerCount,
549                      vk::ImageHelper *image,
550                      vk::ImageHelper *resolveImage,
551                      UniqueSerial imageSiblingSerial,
552                      vk::PackedAttachmentIndex packedAttachmentIndex)
553     {
554         ASSERT(mRenderPassCommands->started());
555         mRenderPassCommands->colorImagesDraw(level, layerStart, layerCount, image, resolveImage,
556                                              imageSiblingSerial, packedAttachmentIndex);
557     }
onColorResolve(gl::LevelIndex level,uint32_t layerStart,uint32_t layerCount,vk::ImageHelper * image,VkImageView view,UniqueSerial imageSiblingSerial,size_t colorIndexGL)558     void onColorResolve(gl::LevelIndex level,
559                         uint32_t layerStart,
560                         uint32_t layerCount,
561                         vk::ImageHelper *image,
562                         VkImageView view,
563                         UniqueSerial imageSiblingSerial,
564                         size_t colorIndexGL)
565     {
566         ASSERT(mRenderPassCommands->started());
567         mRenderPassCommands->addColorResolveAttachment(colorIndexGL, image, view, level, layerStart,
568                                                        layerCount, imageSiblingSerial);
569     }
onDepthStencilDraw(gl::LevelIndex level,uint32_t layerStart,uint32_t layerCount,vk::ImageHelper * image,vk::ImageHelper * resolveImage,UniqueSerial imageSiblingSerial)570     void onDepthStencilDraw(gl::LevelIndex level,
571                             uint32_t layerStart,
572                             uint32_t layerCount,
573                             vk::ImageHelper *image,
574                             vk::ImageHelper *resolveImage,
575                             UniqueSerial imageSiblingSerial)
576     {
577         ASSERT(mRenderPassCommands->started());
578         mRenderPassCommands->depthStencilImagesDraw(level, layerStart, layerCount, image,
579                                                     resolveImage, imageSiblingSerial);
580     }
onDepthStencilResolve(gl::LevelIndex level,uint32_t layerStart,uint32_t layerCount,VkImageAspectFlags aspects,vk::ImageHelper * image,VkImageView view,UniqueSerial imageSiblingSerial)581     void onDepthStencilResolve(gl::LevelIndex level,
582                                uint32_t layerStart,
583                                uint32_t layerCount,
584                                VkImageAspectFlags aspects,
585                                vk::ImageHelper *image,
586                                VkImageView view,
587                                UniqueSerial imageSiblingSerial)
588     {
589         ASSERT(mRenderPassCommands->started());
590         mRenderPassCommands->addDepthStencilResolveAttachment(
591             image, view, aspects, level, layerStart, layerCount, imageSiblingSerial);
592     }
593 
onFragmentShadingRateRead(vk::ImageHelper * image)594     void onFragmentShadingRateRead(vk::ImageHelper *image)
595     {
596         ASSERT(mRenderPassCommands->started());
597         mRenderPassCommands->fragmentShadingRateImageRead(image);
598     }
599 
600     void finalizeImageLayout(vk::ImageHelper *image, UniqueSerial imageSiblingSerial);
601 
getOutsideRenderPassCommandBuffer(const vk::CommandBufferAccess & access,vk::OutsideRenderPassCommandBuffer ** commandBufferOut)602     angle::Result getOutsideRenderPassCommandBuffer(
603         const vk::CommandBufferAccess &access,
604         vk::OutsideRenderPassCommandBuffer **commandBufferOut)
605     {
606         ANGLE_TRY(onResourceAccess(access));
607         *commandBufferOut = &mOutsideRenderPassCommands->getCommandBuffer();
608         return angle::Result::Continue;
609     }
610 
getOutsideRenderPassCommandBufferHelper(const vk::CommandBufferAccess & access,vk::OutsideRenderPassCommandBufferHelper ** commandBufferHelperOut)611     angle::Result getOutsideRenderPassCommandBufferHelper(
612         const vk::CommandBufferAccess &access,
613         vk::OutsideRenderPassCommandBufferHelper **commandBufferHelperOut)
614     {
615         ANGLE_TRY(onResourceAccess(access));
616         *commandBufferHelperOut = mOutsideRenderPassCommands;
617         return angle::Result::Continue;
618     }
619 
trackImageWithOutsideRenderPassEvent(vk::ImageHelper * image)620     void trackImageWithOutsideRenderPassEvent(vk::ImageHelper *image)
621     {
622         if (mRenderer->getFeatures().useVkEventForImageBarrier.enabled)
623         {
624             mOutsideRenderPassCommands->trackImageWithEvent(this, image);
625         }
626     }
submitStagedTextureUpdates()627     angle::Result submitStagedTextureUpdates()
628     {
629         // Staged updates are recorded in outside RP command buffer, submit them.
630         return flushOutsideRenderPassCommands();
631     }
632 
633     angle::Result beginNewRenderPass(vk::RenderPassFramebuffer &&framebuffer,
634                                      const gl::Rectangle &renderArea,
635                                      const vk::RenderPassDesc &renderPassDesc,
636                                      const vk::AttachmentOpsArray &renderPassAttachmentOps,
637                                      const vk::PackedAttachmentCount colorAttachmentCount,
638                                      const vk::PackedAttachmentIndex depthStencilAttachmentIndex,
639                                      const vk::PackedClearValuesArray &clearValues,
640                                      vk::RenderPassCommandBuffer **commandBufferOut);
641 
disableRenderPassReactivation()642     void disableRenderPassReactivation() { mAllowRenderPassToReactivate = false; }
643 
644     // Only returns true if we have a started RP and we've run setupDraw.
hasActiveRenderPass()645     bool hasActiveRenderPass() const
646     {
647         // If mRenderPassCommandBuffer is not null, mRenderPassCommands must already started, we
648         // call this active render pass. A started render pass will have null
649         // mRenderPassCommandBuffer after onRenderPassFinished call, we call this state started but
650         // inactive.
651         ASSERT(mRenderPassCommandBuffer == nullptr || mRenderPassCommands->started());
652         // Checking mRenderPassCommandBuffer ensures we've called setupDraw.
653         return mRenderPassCommandBuffer != nullptr;
654     }
655 
hasStartedRenderPassWithQueueSerial(const QueueSerial & queueSerial)656     bool hasStartedRenderPassWithQueueSerial(const QueueSerial &queueSerial) const
657     {
658         return mRenderPassCommands->started() &&
659                mRenderPassCommands->getQueueSerial() == queueSerial;
660     }
hasStartedRenderPassWithDefaultFramebuffer()661     bool hasStartedRenderPassWithDefaultFramebuffer() const
662     {
663         // WindowSurfaceVk caches its own framebuffers and guarantees that render passes are not
664         // kept open between frames (including when a swapchain is recreated and framebuffer handles
665         // change).  It is therefore safe to verify an open render pass just by checking if it
666         // originated from the default framebuffer.
667         return mRenderPassCommands->started() && mRenderPassCommands->isDefault();
668     }
669 
isRenderPassStartedAndUsesBuffer(const vk::BufferHelper & buffer)670     bool isRenderPassStartedAndUsesBuffer(const vk::BufferHelper &buffer) const
671     {
672         return mRenderPassCommands->started() && mRenderPassCommands->usesBuffer(buffer);
673     }
674 
isRenderPassStartedAndUsesBufferForWrite(const vk::BufferHelper & buffer)675     bool isRenderPassStartedAndUsesBufferForWrite(const vk::BufferHelper &buffer) const
676     {
677         return mRenderPassCommands->started() && mRenderPassCommands->usesBufferForWrite(buffer);
678     }
679 
isRenderPassStartedAndUsesImage(const vk::ImageHelper & image)680     bool isRenderPassStartedAndUsesImage(const vk::ImageHelper &image) const
681     {
682         return mRenderPassCommands->started() && mRenderPassCommands->usesImage(image);
683     }
684 
getStartedRenderPassCommands()685     vk::RenderPassCommandBufferHelper &getStartedRenderPassCommands()
686     {
687         ASSERT(mRenderPassCommands->started());
688         return *mRenderPassCommands;
689     }
690 
691     uint32_t getCurrentSubpassIndex() const;
692     uint32_t getCurrentViewCount() const;
693 
694     // Initial Context Priority. Used for EGL_CONTEXT_PRIORITY_LEVEL_IMG attribute.
getContextPriority()695     egl::ContextPriority getContextPriority() const override { return mInitialContextPriority; }
696     angle::Result startRenderPass(gl::Rectangle renderArea,
697                                   vk::RenderPassCommandBuffer **commandBufferOut,
698                                   bool *renderPassDescChangedOut);
699     angle::Result startNextSubpass();
700     angle::Result flushCommandsAndEndRenderPass(RenderPassClosureReason reason);
701     angle::Result flushCommandsAndEndRenderPassWithoutSubmit(RenderPassClosureReason reason);
702     angle::Result flushAndSubmitOutsideRenderPassCommands();
703 
704     angle::Result syncExternalMemory();
705 
706     // Either issue a submission or defer it when a sync object is initialized.  If deferred, a
707     // submission will have to be incurred during client wait.
708     angle::Result onSyncObjectInit(vk::SyncHelper *syncHelper, SyncFenceScope scope);
709     // Called when a sync object is waited on while its submission was deferred in onSyncObjectInit.
710     // It's a no-op if this context doesn't have a pending submission.  Note that due to
711     // mHasDeferredFlush being set, flushing the render pass leads to a submission automatically.
712     angle::Result flushCommandsAndEndRenderPassIfDeferredSyncInit(RenderPassClosureReason reason);
713 
714     void addCommandBufferDiagnostics(const std::string &commandBufferDiagnostics);
715 
716     VkIndexType getVkIndexType(gl::DrawElementsType glIndexType) const;
717     size_t getVkIndexTypeSize(gl::DrawElementsType glIndexType) const;
718     bool shouldConvertUint8VkIndexType(gl::DrawElementsType glIndexType) const;
719 
720     bool isRobustResourceInitEnabled() const;
hasRobustAccess()721     bool hasRobustAccess() const { return mState.hasRobustAccess(); }
722 
723     // Queries that begin and end automatically with render pass start and end
724     angle::Result beginRenderPassQuery(QueryVk *queryVk);
725     angle::Result endRenderPassQuery(QueryVk *queryVk);
726     void pauseRenderPassQueriesIfActive();
727     angle::Result resumeRenderPassQueriesIfActive();
728     angle::Result resumeXfbRenderPassQueriesIfActive();
729     bool doesPrimitivesGeneratedQuerySupportRasterizerDiscard() const;
730     bool isEmulatingRasterizerDiscardDuringPrimitivesGeneratedQuery(
731         bool isPrimitivesGeneratedQueryActive) const;
732 
733     // Used by QueryVk to share query helpers between transform feedback queries.
734     QueryVk *getActiveRenderPassQuery(gl::QueryType queryType) const;
735 
736     void syncObjectPerfCounters(const angle::VulkanPerfCounters &commandQueuePerfCounters);
737     void updateOverlayOnPresent();
738     void addOverlayUsedBuffersCount(vk::CommandBufferHelperCommon *commandBuffer);
739 
740     // For testing only.
741     void setDefaultUniformBlocksMinSizeForTesting(size_t minSize);
742 
getEmptyBuffer()743     vk::BufferHelper &getEmptyBuffer() { return mEmptyBuffer; }
744 
745     // Keeping track of the buffer copy size. Used to determine when to submit the outside command
746     // buffer.
747     angle::Result onCopyUpdate(VkDeviceSize size, bool *commandBufferWasFlushedOut);
748 
749     // Implementation of MultisampleTextureInitializer
750     angle::Result initializeMultisampleTextureToBlack(const gl::Context *context,
751                                                       gl::Texture *glTexture) override;
752 
753     // TODO(http://anglebug.com/42264159): rework updateActiveTextures(), createPipelineLayout(),
754     // handleDirtyGraphicsPipeline(), and ProgramPipelineVk::link().
resetCurrentGraphicsPipeline()755     void resetCurrentGraphicsPipeline()
756     {
757         mCurrentGraphicsPipeline        = nullptr;
758         mCurrentGraphicsPipelineShaders = nullptr;
759     }
760 
761     void onProgramExecutableReset(ProgramExecutableVk *executableVk);
762 
763     angle::Result handleGraphicsEventLog(GraphicsEventCmdBuf queryEventType);
764 
765     void flushDescriptorSetUpdates();
766 
getDefaultBufferPool(VkDeviceSize size,uint32_t memoryTypeIndex,BufferUsageType usageType)767     vk::BufferPool *getDefaultBufferPool(VkDeviceSize size,
768                                          uint32_t memoryTypeIndex,
769                                          BufferUsageType usageType)
770     {
771         return mShareGroupVk->getDefaultBufferPool(size, memoryTypeIndex, usageType);
772     }
773 
allocateStreamedVertexBuffer(size_t attribIndex,size_t bytesToAllocate,vk::BufferHelper ** vertexBufferOut)774     angle::Result allocateStreamedVertexBuffer(size_t attribIndex,
775                                                size_t bytesToAllocate,
776                                                vk::BufferHelper **vertexBufferOut)
777     {
778         bool newBufferOut;
779         ANGLE_TRY(mStreamedVertexBuffers[attribIndex].allocate(this, bytesToAllocate,
780                                                                vertexBufferOut, &newBufferOut));
781         if (newBufferOut)
782         {
783             mHasInFlightStreamedVertexBuffers.set(attribIndex);
784         }
785         return angle::Result::Continue;
786     }
787 
788     // Put the context in framebuffer fetch mode.  If the permanentlySwitchToFramebufferFetchMode
789     // feature is enabled, this is done on first encounter of framebuffer fetch, and makes the
790     // context use framebuffer-fetch-enabled render passes from here on.
791     angle::Result switchToColorFramebufferFetchMode(bool hasColorFramebufferFetch);
isInColorFramebufferFetchMode()792     bool isInColorFramebufferFetchMode() const
793     {
794         ASSERT(!getFeatures().preferDynamicRendering.enabled);
795         return mIsInColorFramebufferFetchMode;
796     }
797 
798     const angle::PerfMonitorCounterGroups &getPerfMonitorCounters() override;
799 
800     void resetPerFramePerfCounters();
801 
802     // Accumulate cache stats for a specific cache
accumulateCacheStats(VulkanCacheType cache,const CacheStats & stats)803     void accumulateCacheStats(VulkanCacheType cache, const CacheStats &stats)
804     {
805         mVulkanCacheStats[cache].accumulate(stats);
806     }
807 
808     // Whether VK_EXT_pipeline_robustness should be used to enable robust buffer access in the
809     // pipeline.
pipelineRobustness()810     vk::PipelineRobustness pipelineRobustness() const
811     {
812         return getFeatures().supportsPipelineRobustness.enabled && mState.hasRobustAccess()
813                    ? vk::PipelineRobustness::Robust
814                    : vk::PipelineRobustness::NonRobust;
815     }
816     // Whether VK_EXT_pipeline_protected_access should be used to restrict the pipeline to protected
817     // command buffers.  Note that when false, if the extension is supported, the pipeline can be
818     // restricted to unprotected command buffers.
pipelineProtectedAccess()819     vk::PipelineProtectedAccess pipelineProtectedAccess() const
820     {
821         return getFeatures().supportsPipelineProtectedAccess.enabled && mState.hasProtectedContent()
822                    ? vk::PipelineProtectedAccess::Protected
823                    : vk::PipelineProtectedAccess::Unprotected;
824     }
825 
getImageLoadContext()826     const angle::ImageLoadContext &getImageLoadContext() const { return mImageLoadContext; }
827 
828     bool hasUnsubmittedUse(const vk::ResourceUse &use) const;
hasUnsubmittedUse(const vk::Resource & resource)829     bool hasUnsubmittedUse(const vk::Resource &resource) const
830     {
831         return hasUnsubmittedUse(resource.getResourceUse());
832     }
hasUnsubmittedUse(const vk::ReadWriteResource & resource)833     bool hasUnsubmittedUse(const vk::ReadWriteResource &resource) const
834     {
835         return hasUnsubmittedUse(resource.getResourceUse());
836     }
837 
getLastSubmittedQueueSerial()838     const QueueSerial &getLastSubmittedQueueSerial() const { return mLastSubmittedQueueSerial; }
getSubmittedResourceUse()839     const vk::ResourceUse &getSubmittedResourceUse() const { return mSubmittedResourceUse; }
840 
841     // Uploading mutable mipmap textures is currently restricted to single-context applications.
isEligibleForMutableTextureFlush()842     bool isEligibleForMutableTextureFlush() const
843     {
844         return getFeatures().mutableMipmapTextureUpload.enabled && !hasDisplayTextureShareGroup() &&
845                mShareGroupVk->getContexts().size() == 1;
846     }
847 
getDepthStencilAttachmentFlags()848     vk::RenderPassUsageFlags getDepthStencilAttachmentFlags() const
849     {
850         return mDepthStencilAttachmentFlags;
851     }
852 
isDitherEnabled()853     bool isDitherEnabled() { return mState.isDitherEnabled(); }
854 
855     // The following functions try to allocate memory for buffers and images. If they fail due to
856     // OOM errors, they will try other options for memory allocation.
857     angle::Result initBufferAllocation(vk::BufferHelper *bufferHelper,
858                                        uint32_t memoryTypeIndex,
859                                        size_t allocationSize,
860                                        size_t alignment,
861                                        BufferUsageType bufferUsageType);
862     angle::Result initImageAllocation(vk::ImageHelper *imageHelper,
863                                       bool hasProtectedContent,
864                                       const vk::MemoryProperties &memoryProperties,
865                                       VkMemoryPropertyFlags flags,
866                                       vk::MemoryAllocationType allocationType);
867 
868     angle::Result releaseBufferAllocation(vk::BufferHelper *bufferHelper);
869 
870     // Helper functions to initialize a buffer for a specific usage
871     // Suballocate a host visible buffer with alignment good for copyBuffer.
872     angle::Result initBufferForBufferCopy(vk::BufferHelper *bufferHelper,
873                                           size_t size,
874                                           vk::MemoryCoherency coherency);
875     // Suballocate a host visible buffer with alignment good for copyImage.
876     angle::Result initBufferForImageCopy(vk::BufferHelper *bufferHelper,
877                                          size_t size,
878                                          vk::MemoryCoherency coherency,
879                                          angle::FormatID formatId,
880                                          VkDeviceSize *offset,
881                                          uint8_t **dataPtr);
882     // Suballocate a buffer with alignment good for shader storage or copyBuffer.
883     angle::Result initBufferForVertexConversion(ConversionBuffer *conversionBuffer,
884                                                 size_t size,
885                                                 vk::MemoryHostVisibility hostVisibility);
886 
887     // In the event of collecting too much garbage, we should flush the garbage so it can be freed.
888     void addToPendingImageGarbage(vk::ResourceUse use, VkDeviceSize size);
889 
890     bool hasExcessPendingGarbage() const;
891 
892     angle::Result onFramebufferBoundary(const gl::Context *contextGL);
893 
getCurrentFrameCount()894     uint32_t getCurrentFrameCount() const { return mShareGroupVk->getCurrentFrameCount(); }
895 
896   private:
897     // Dirty bits.
898     enum DirtyBitType : size_t
899     {
900         // Dirty bits that must be processed before the render pass is started.  The handlers for
901         // these dirty bits don't record any commands.
902 
903         // the AnySamplePassed render pass query has been ended.
904         DIRTY_BIT_ANY_SAMPLE_PASSED_QUERY_END,
905         // A glMemoryBarrier has been called and command buffers may need flushing.
906         DIRTY_BIT_MEMORY_BARRIER,
907         // Update default attribute buffers.
908         DIRTY_BIT_DEFAULT_ATTRIBS,
909         // The pipeline has changed and needs to be recreated.  This dirty bit may close the render
910         // pass.
911         DIRTY_BIT_PIPELINE_DESC,
912         // Support for depth/stencil read-only feedback loop.  When depth/stencil access changes,
913         // the render pass may need closing.
914         DIRTY_BIT_READ_ONLY_DEPTH_FEEDBACK_LOOP_MODE,
915 
916         // Start the render pass.
917         DIRTY_BIT_RENDER_PASS,
918 
919         // Dirty bits that must be processed after the render pass is started.  Their handlers
920         // record commands.
921         DIRTY_BIT_EVENT_LOG,
922         // Update color and depth/stencil accesses in the render pass.
923         DIRTY_BIT_COLOR_ACCESS,
924         DIRTY_BIT_DEPTH_STENCIL_ACCESS,
925         // Pipeline needs to rebind because a new command buffer has been allocated, or UtilsVk has
926         // changed the binding.  The pipeline itself doesn't need to be recreated.
927         DIRTY_BIT_PIPELINE_BINDING,
928         DIRTY_BIT_TEXTURES,
929         DIRTY_BIT_VERTEX_BUFFERS,
930         DIRTY_BIT_INDEX_BUFFER,
931         DIRTY_BIT_UNIFORMS,
932         DIRTY_BIT_DRIVER_UNIFORMS,
933         // Shader resources excluding textures, which are handled separately.
934         DIRTY_BIT_SHADER_RESOURCES,
935         DIRTY_BIT_UNIFORM_BUFFERS,
936         DIRTY_BIT_TRANSFORM_FEEDBACK_BUFFERS,
937         DIRTY_BIT_TRANSFORM_FEEDBACK_RESUME,
938         DIRTY_BIT_DESCRIPTOR_SETS,
939         DIRTY_BIT_FRAMEBUFFER_FETCH_BARRIER,
940         DIRTY_BIT_BLEND_BARRIER,
941 
942         // Dynamic state
943         // - In core Vulkan 1.0
944         DIRTY_BIT_DYNAMIC_VIEWPORT,
945         DIRTY_BIT_DYNAMIC_SCISSOR,
946         DIRTY_BIT_DYNAMIC_LINE_WIDTH,
947         DIRTY_BIT_DYNAMIC_DEPTH_BIAS,
948         DIRTY_BIT_DYNAMIC_BLEND_CONSTANTS,
949         DIRTY_BIT_DYNAMIC_STENCIL_COMPARE_MASK,
950         DIRTY_BIT_DYNAMIC_STENCIL_WRITE_MASK,
951         DIRTY_BIT_DYNAMIC_STENCIL_REFERENCE,
952         // - In VK_EXT_extended_dynamic_state
953         DIRTY_BIT_DYNAMIC_CULL_MODE,
954         DIRTY_BIT_DYNAMIC_FRONT_FACE,
955         DIRTY_BIT_DYNAMIC_DEPTH_TEST_ENABLE,
956         DIRTY_BIT_DYNAMIC_DEPTH_WRITE_ENABLE,
957         DIRTY_BIT_DYNAMIC_DEPTH_COMPARE_OP,
958         DIRTY_BIT_DYNAMIC_STENCIL_TEST_ENABLE,
959         DIRTY_BIT_DYNAMIC_STENCIL_OP,
960         // - In VK_EXT_extended_dynamic_state2
961         DIRTY_BIT_DYNAMIC_RASTERIZER_DISCARD_ENABLE,
962         DIRTY_BIT_DYNAMIC_DEPTH_BIAS_ENABLE,
963         DIRTY_BIT_DYNAMIC_LOGIC_OP,
964         DIRTY_BIT_DYNAMIC_PRIMITIVE_RESTART_ENABLE,
965         // - In VK_KHR_fragment_shading_rate
966         DIRTY_BIT_DYNAMIC_FRAGMENT_SHADING_RATE,
967 
968         DIRTY_BIT_MAX,
969     };
970 
971     // Dirty bit handlers that can break the render pass must always be specified before
972     // DIRTY_BIT_RENDER_PASS.
973     static_assert(
974         DIRTY_BIT_ANY_SAMPLE_PASSED_QUERY_END < DIRTY_BIT_RENDER_PASS,
975         "Render pass breaking dirty bit must be handled before the render pass dirty bit");
976     static_assert(
977         DIRTY_BIT_MEMORY_BARRIER < DIRTY_BIT_RENDER_PASS,
978         "Render pass breaking dirty bit must be handled before the render pass dirty bit");
979     static_assert(
980         DIRTY_BIT_DEFAULT_ATTRIBS < DIRTY_BIT_RENDER_PASS,
981         "Render pass breaking dirty bit must be handled before the render pass dirty bit");
982     static_assert(
983         DIRTY_BIT_PIPELINE_DESC < DIRTY_BIT_RENDER_PASS,
984         "Render pass breaking dirty bit must be handled before the render pass dirty bit");
985     static_assert(
986         DIRTY_BIT_READ_ONLY_DEPTH_FEEDBACK_LOOP_MODE < DIRTY_BIT_RENDER_PASS,
987         "Render pass breaking dirty bit must be handled before the render pass dirty bit");
988 
989     // Dirty bit handlers that record commands or otherwise expect to manipulate the render pass
990     // that will be used for the draw call must be specified after DIRTY_BIT_RENDER_PASS.
991     static_assert(DIRTY_BIT_EVENT_LOG > DIRTY_BIT_RENDER_PASS,
992                   "Render pass using dirty bit must be handled after the render pass dirty bit");
993     static_assert(DIRTY_BIT_COLOR_ACCESS > DIRTY_BIT_RENDER_PASS,
994                   "Render pass using dirty bit must be handled after the render pass dirty bit");
995     static_assert(DIRTY_BIT_DEPTH_STENCIL_ACCESS > DIRTY_BIT_RENDER_PASS,
996                   "Render pass using dirty bit must be handled after the render pass dirty bit");
997     static_assert(DIRTY_BIT_PIPELINE_BINDING > DIRTY_BIT_RENDER_PASS,
998                   "Render pass using dirty bit must be handled after the render pass dirty bit");
999     static_assert(DIRTY_BIT_TEXTURES > DIRTY_BIT_RENDER_PASS,
1000                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1001     static_assert(DIRTY_BIT_VERTEX_BUFFERS > DIRTY_BIT_RENDER_PASS,
1002                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1003     static_assert(DIRTY_BIT_INDEX_BUFFER > DIRTY_BIT_RENDER_PASS,
1004                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1005     static_assert(DIRTY_BIT_DRIVER_UNIFORMS > DIRTY_BIT_RENDER_PASS,
1006                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1007     static_assert(DIRTY_BIT_SHADER_RESOURCES > DIRTY_BIT_RENDER_PASS,
1008                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1009     static_assert(
1010         DIRTY_BIT_UNIFORM_BUFFERS > DIRTY_BIT_SHADER_RESOURCES,
1011         "Uniform buffer using dirty bit must be handled after the shader resource dirty bit");
1012     static_assert(DIRTY_BIT_TRANSFORM_FEEDBACK_BUFFERS > DIRTY_BIT_RENDER_PASS,
1013                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1014     static_assert(DIRTY_BIT_TRANSFORM_FEEDBACK_RESUME > DIRTY_BIT_RENDER_PASS,
1015                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1016     static_assert(DIRTY_BIT_DESCRIPTOR_SETS > DIRTY_BIT_RENDER_PASS,
1017                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1018     static_assert(DIRTY_BIT_UNIFORMS > DIRTY_BIT_RENDER_PASS,
1019                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1020     static_assert(DIRTY_BIT_FRAMEBUFFER_FETCH_BARRIER > DIRTY_BIT_RENDER_PASS,
1021                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1022     static_assert(DIRTY_BIT_BLEND_BARRIER > DIRTY_BIT_RENDER_PASS,
1023                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1024     static_assert(DIRTY_BIT_DYNAMIC_VIEWPORT > DIRTY_BIT_RENDER_PASS,
1025                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1026     static_assert(DIRTY_BIT_DYNAMIC_SCISSOR > DIRTY_BIT_RENDER_PASS,
1027                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1028     static_assert(DIRTY_BIT_DYNAMIC_LINE_WIDTH > DIRTY_BIT_RENDER_PASS,
1029                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1030     static_assert(DIRTY_BIT_DYNAMIC_DEPTH_BIAS > DIRTY_BIT_RENDER_PASS,
1031                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1032     static_assert(DIRTY_BIT_DYNAMIC_BLEND_CONSTANTS > DIRTY_BIT_RENDER_PASS,
1033                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1034     static_assert(DIRTY_BIT_DYNAMIC_STENCIL_COMPARE_MASK > DIRTY_BIT_RENDER_PASS,
1035                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1036     static_assert(DIRTY_BIT_DYNAMIC_STENCIL_WRITE_MASK > DIRTY_BIT_RENDER_PASS,
1037                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1038     static_assert(DIRTY_BIT_DYNAMIC_STENCIL_REFERENCE > DIRTY_BIT_RENDER_PASS,
1039                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1040     static_assert(DIRTY_BIT_DYNAMIC_CULL_MODE > DIRTY_BIT_RENDER_PASS,
1041                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1042     static_assert(DIRTY_BIT_DYNAMIC_FRONT_FACE > DIRTY_BIT_RENDER_PASS,
1043                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1044     static_assert(DIRTY_BIT_DYNAMIC_DEPTH_TEST_ENABLE > DIRTY_BIT_RENDER_PASS,
1045                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1046     static_assert(DIRTY_BIT_DYNAMIC_DEPTH_WRITE_ENABLE > DIRTY_BIT_RENDER_PASS,
1047                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1048     static_assert(DIRTY_BIT_DYNAMIC_DEPTH_COMPARE_OP > DIRTY_BIT_RENDER_PASS,
1049                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1050     static_assert(DIRTY_BIT_DYNAMIC_STENCIL_TEST_ENABLE > DIRTY_BIT_RENDER_PASS,
1051                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1052     static_assert(DIRTY_BIT_DYNAMIC_STENCIL_OP > DIRTY_BIT_RENDER_PASS,
1053                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1054     static_assert(DIRTY_BIT_DYNAMIC_RASTERIZER_DISCARD_ENABLE > DIRTY_BIT_RENDER_PASS,
1055                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1056     static_assert(DIRTY_BIT_DYNAMIC_DEPTH_BIAS_ENABLE > DIRTY_BIT_RENDER_PASS,
1057                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1058     static_assert(DIRTY_BIT_DYNAMIC_LOGIC_OP > DIRTY_BIT_RENDER_PASS,
1059                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1060     static_assert(DIRTY_BIT_DYNAMIC_PRIMITIVE_RESTART_ENABLE > DIRTY_BIT_RENDER_PASS,
1061                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1062     static_assert(DIRTY_BIT_DYNAMIC_FRAGMENT_SHADING_RATE > DIRTY_BIT_RENDER_PASS,
1063                   "Render pass using dirty bit must be handled after the render pass dirty bit");
1064 
1065     using DirtyBits = angle::BitSet<DIRTY_BIT_MAX>;
1066 
1067     using GraphicsDirtyBitHandler = angle::Result (
1068         ContextVk::*)(DirtyBits::Iterator *dirtyBitsIterator, DirtyBits dirtyBitMask);
1069     using ComputeDirtyBitHandler =
1070         angle::Result (ContextVk::*)(DirtyBits::Iterator *dirtyBitsIterator);
1071 
1072     // The GpuEventQuery struct holds together a timestamp query and enough data to create a
1073     // trace event based on that. Use traceGpuEvent to insert such queries.  They will be readback
1074     // when the results are available, without inserting a GPU bubble.
1075     //
1076     // - eventName will be the reported name of the event
1077     // - phase is either 'B' (duration begin), 'E' (duration end) or 'i' (instant // event).
1078     //   See Google's "Trace Event Format":
1079     //   https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU
1080     // - serial is the serial of the batch the query was submitted on.  Until the batch is
1081     //   submitted, the query is not checked to avoid incuring a flush.
1082     struct GpuEventQuery final
1083     {
1084         EventName name;
1085         char phase;
1086         vk::QueryHelper queryHelper;
1087     };
1088 
1089     // Once a query result is available, the timestamp is read and a GpuEvent object is kept until
1090     // the next clock sync, at which point the clock drift is compensated in the results before
1091     // handing them off to the application.
1092     struct GpuEvent final
1093     {
1094         uint64_t gpuTimestampCycles;
1095         std::array<char, kMaxGpuEventNameLen> name;
1096         char phase;
1097     };
1098 
1099     struct GpuClockSyncInfo
1100     {
1101         double gpuTimestampS;
1102         double cpuTimestampS;
1103     };
1104 
1105     class ScopedDescriptorSetUpdates;
1106 
1107     bool isSingleBufferedWindowCurrent() const;
1108     bool hasSomethingToFlush() const;
1109 
1110     angle::Result setupDraw(const gl::Context *context,
1111                             gl::PrimitiveMode mode,
1112                             GLint firstVertexOrInvalid,
1113                             GLsizei vertexOrIndexCount,
1114                             GLsizei instanceCount,
1115                             gl::DrawElementsType indexTypeOrInvalid,
1116                             const void *indices,
1117                             DirtyBits dirtyBitMask);
1118 
1119     angle::Result setupIndexedDraw(const gl::Context *context,
1120                                    gl::PrimitiveMode mode,
1121                                    GLsizei indexCount,
1122                                    GLsizei instanceCount,
1123                                    gl::DrawElementsType indexType,
1124                                    const void *indices);
1125     angle::Result setupIndirectDraw(const gl::Context *context,
1126                                     gl::PrimitiveMode mode,
1127                                     DirtyBits dirtyBitMask,
1128                                     vk::BufferHelper *indirectBuffer);
1129     angle::Result setupIndexedIndirectDraw(const gl::Context *context,
1130                                            gl::PrimitiveMode mode,
1131                                            gl::DrawElementsType indexType,
1132                                            vk::BufferHelper *indirectBuffer);
1133 
1134     angle::Result setupLineLoopIndexedIndirectDraw(const gl::Context *context,
1135                                                    gl::PrimitiveMode mode,
1136                                                    gl::DrawElementsType indexType,
1137                                                    vk::BufferHelper *srcIndexBuffer,
1138                                                    vk::BufferHelper *srcIndirectBuffer,
1139                                                    VkDeviceSize indirectBufferOffset,
1140                                                    vk::BufferHelper **indirectBufferOut);
1141     angle::Result setupLineLoopIndirectDraw(const gl::Context *context,
1142                                             gl::PrimitiveMode mode,
1143                                             vk::BufferHelper *indirectBuffer,
1144                                             VkDeviceSize indirectBufferOffset,
1145                                             vk::BufferHelper **indirectBufferOut);
1146 
1147     angle::Result setupLineLoopDraw(const gl::Context *context,
1148                                     gl::PrimitiveMode mode,
1149                                     GLint firstVertex,
1150                                     GLsizei vertexOrIndexCount,
1151                                     gl::DrawElementsType indexTypeOrInvalid,
1152                                     const void *indices,
1153                                     uint32_t *numIndicesOut);
1154 
1155     angle::Result setupDispatch(const gl::Context *context);
1156 
1157     gl::Rectangle getCorrectedViewport(const gl::Rectangle &viewport) const;
1158     void updateViewport(FramebufferVk *framebufferVk,
1159                         const gl::Rectangle &viewport,
1160                         float nearPlane,
1161                         float farPlane);
1162     void updateFrontFace();
1163     void updateDepthRange(float nearPlane, float farPlane);
1164     void updateMissingAttachments();
1165     void updateSampleMaskWithRasterizationSamples(const uint32_t rasterizationSamples);
1166     void updateAlphaToCoverageWithRasterizationSamples(const uint32_t rasterizationSamples);
1167     void updateFrameBufferFetchSamples(const uint32_t prevSamples, const uint32_t curSamples);
1168     void updateFlipViewportDrawFramebuffer(const gl::State &glState);
1169     void updateFlipViewportReadFramebuffer(const gl::State &glState);
1170     void updateSurfaceRotationDrawFramebuffer(const gl::State &glState,
1171                                               const egl::Surface *currentDrawSurface);
1172     void updateSurfaceRotationReadFramebuffer(const gl::State &glState,
1173                                               const egl::Surface *currentReadSurface);
1174 
1175     angle::Result updateActiveTextures(const gl::Context *context, gl::Command command);
1176     template <typename CommandBufferHelperT>
1177     angle::Result updateActiveImages(CommandBufferHelperT *commandBufferHelper);
1178 
invalidateCurrentGraphicsPipeline()1179     ANGLE_INLINE void invalidateCurrentGraphicsPipeline()
1180     {
1181         // Note: DIRTY_BIT_PIPELINE_BINDING will be automatically set if pipeline bind is necessary.
1182         mGraphicsDirtyBits.set(DIRTY_BIT_PIPELINE_DESC);
1183     }
1184 
invalidateCurrentComputePipeline()1185     ANGLE_INLINE void invalidateCurrentComputePipeline()
1186     {
1187         mComputeDirtyBits |= kPipelineDescAndBindingDirtyBits;
1188         mCurrentComputePipeline = nullptr;
1189     }
1190 
1191     angle::Result invalidateProgramExecutableHelper(const gl::Context *context);
1192 
1193     void invalidateCurrentDefaultUniforms();
1194     angle::Result invalidateCurrentTextures(const gl::Context *context, gl::Command command);
1195     angle::Result invalidateCurrentShaderResources(gl::Command command);
1196     angle::Result invalidateCurrentShaderUniformBuffers(gl::Command command);
1197     void invalidateGraphicsDriverUniforms();
1198     void invalidateDriverUniforms();
1199 
1200     angle::Result handleNoopDrawEvent() override;
1201 
1202     // Handlers for graphics pipeline dirty bits.
1203     angle::Result handleDirtyGraphicsMemoryBarrier(DirtyBits::Iterator *dirtyBitsIterator,
1204                                                    DirtyBits dirtyBitMask);
1205     angle::Result handleDirtyGraphicsDefaultAttribs(DirtyBits::Iterator *dirtyBitsIterator,
1206                                                     DirtyBits dirtyBitMask);
1207     angle::Result handleDirtyGraphicsPipelineDesc(DirtyBits::Iterator *dirtyBitsIterator,
1208                                                   DirtyBits dirtyBitMask);
1209     angle::Result handleDirtyGraphicsReadOnlyDepthFeedbackLoopMode(
1210         DirtyBits::Iterator *dirtyBitsIterator,
1211         DirtyBits dirtyBitMask);
1212     angle::Result handleDirtyAnySamplePassedQueryEnd(DirtyBits::Iterator *dirtyBitsIterator,
1213                                                      DirtyBits dirtyBitMask);
1214     angle::Result handleDirtyGraphicsRenderPass(DirtyBits::Iterator *dirtyBitsIterator,
1215                                                 DirtyBits dirtyBitMask);
1216     angle::Result handleDirtyGraphicsEventLog(DirtyBits::Iterator *dirtyBitsIterator,
1217                                               DirtyBits dirtyBitMask);
1218     angle::Result handleDirtyGraphicsColorAccess(DirtyBits::Iterator *dirtyBitsIterator,
1219                                                  DirtyBits dirtyBitMask);
1220     angle::Result handleDirtyGraphicsDepthStencilAccess(DirtyBits::Iterator *dirtyBitsIterator,
1221                                                         DirtyBits dirtyBitMask);
1222     angle::Result handleDirtyGraphicsPipelineBinding(DirtyBits::Iterator *dirtyBitsIterator,
1223                                                      DirtyBits dirtyBitMask);
1224     angle::Result handleDirtyGraphicsTextures(DirtyBits::Iterator *dirtyBitsIterator,
1225                                               DirtyBits dirtyBitMask);
1226     angle::Result handleDirtyGraphicsVertexBuffers(DirtyBits::Iterator *dirtyBitsIterator,
1227                                                    DirtyBits dirtyBitMask);
1228     angle::Result handleDirtyGraphicsIndexBuffer(DirtyBits::Iterator *dirtyBitsIterator,
1229                                                  DirtyBits dirtyBitMask);
1230     angle::Result handleDirtyGraphicsDriverUniforms(DirtyBits::Iterator *dirtyBitsIterator,
1231                                                     DirtyBits dirtyBitMask);
1232     angle::Result handleDirtyGraphicsShaderResources(DirtyBits::Iterator *dirtyBitsIterator,
1233                                                      DirtyBits dirtyBitMask);
1234     angle::Result handleDirtyGraphicsUniformBuffers(DirtyBits::Iterator *dirtyBitsIterator,
1235                                                     DirtyBits dirtyBitMask);
1236     angle::Result handleDirtyGraphicsFramebufferFetchBarrier(DirtyBits::Iterator *dirtyBitsIterator,
1237                                                              DirtyBits dirtyBitMask);
1238     angle::Result handleDirtyGraphicsBlendBarrier(DirtyBits::Iterator *dirtyBitsIterator,
1239                                                   DirtyBits dirtyBitMask);
1240     angle::Result handleDirtyGraphicsTransformFeedbackBuffersEmulation(
1241         DirtyBits::Iterator *dirtyBitsIterator,
1242         DirtyBits dirtyBitMask);
1243     angle::Result handleDirtyGraphicsTransformFeedbackBuffersExtension(
1244         DirtyBits::Iterator *dirtyBitsIterator,
1245         DirtyBits dirtyBitMask);
1246     angle::Result handleDirtyGraphicsTransformFeedbackResume(DirtyBits::Iterator *dirtyBitsIterator,
1247                                                              DirtyBits dirtyBitMask);
1248     angle::Result handleDirtyGraphicsDescriptorSets(DirtyBits::Iterator *dirtyBitsIterator,
1249                                                     DirtyBits dirtyBitMask);
1250     angle::Result handleDirtyGraphicsUniforms(DirtyBits::Iterator *dirtyBitsIterator,
1251                                               DirtyBits dirtyBitMask);
1252     angle::Result handleDirtyGraphicsDynamicViewport(DirtyBits::Iterator *dirtyBitsIterator,
1253                                                      DirtyBits dirtyBitMask);
1254     angle::Result handleDirtyGraphicsDynamicScissor(DirtyBits::Iterator *dirtyBitsIterator,
1255                                                     DirtyBits dirtyBitMask);
1256     angle::Result handleDirtyGraphicsDynamicLineWidth(DirtyBits::Iterator *dirtyBitsIterator,
1257                                                       DirtyBits dirtyBitMask);
1258     angle::Result handleDirtyGraphicsDynamicDepthBias(DirtyBits::Iterator *dirtyBitsIterator,
1259                                                       DirtyBits dirtyBitMask);
1260     angle::Result handleDirtyGraphicsDynamicBlendConstants(DirtyBits::Iterator *dirtyBitsIterator,
1261                                                            DirtyBits dirtyBitMask);
1262     angle::Result handleDirtyGraphicsDynamicStencilCompareMask(
1263         DirtyBits::Iterator *dirtyBitsIterator,
1264         DirtyBits dirtyBitMask);
1265     angle::Result handleDirtyGraphicsDynamicStencilWriteMask(DirtyBits::Iterator *dirtyBitsIterator,
1266                                                              DirtyBits dirtyBitMask);
1267     angle::Result handleDirtyGraphicsDynamicStencilReference(DirtyBits::Iterator *dirtyBitsIterator,
1268                                                              DirtyBits dirtyBitMask);
1269     angle::Result handleDirtyGraphicsDynamicCullMode(DirtyBits::Iterator *dirtyBitsIterator,
1270                                                      DirtyBits dirtyBitMask);
1271     angle::Result handleDirtyGraphicsDynamicFrontFace(DirtyBits::Iterator *dirtyBitsIterator,
1272                                                       DirtyBits dirtyBitMask);
1273     angle::Result handleDirtyGraphicsDynamicDepthTestEnable(DirtyBits::Iterator *dirtyBitsIterator,
1274                                                             DirtyBits dirtyBitMask);
1275     angle::Result handleDirtyGraphicsDynamicDepthWriteEnable(DirtyBits::Iterator *dirtyBitsIterator,
1276                                                              DirtyBits dirtyBitMask);
1277     angle::Result handleDirtyGraphicsDynamicDepthCompareOp(DirtyBits::Iterator *dirtyBitsIterator,
1278                                                            DirtyBits dirtyBitMask);
1279     angle::Result handleDirtyGraphicsDynamicStencilTestEnable(
1280         DirtyBits::Iterator *dirtyBitsIterator,
1281         DirtyBits dirtyBitMask);
1282     angle::Result handleDirtyGraphicsDynamicStencilOp(DirtyBits::Iterator *dirtyBitsIterator,
1283                                                       DirtyBits dirtyBitMask);
1284     angle::Result handleDirtyGraphicsDynamicRasterizerDiscardEnable(
1285         DirtyBits::Iterator *dirtyBitsIterator,
1286         DirtyBits dirtyBitMask);
1287     angle::Result handleDirtyGraphicsDynamicDepthBiasEnable(DirtyBits::Iterator *dirtyBitsIterator,
1288                                                             DirtyBits dirtyBitMask);
1289     angle::Result handleDirtyGraphicsDynamicLogicOp(DirtyBits::Iterator *dirtyBitsIterator,
1290                                                     DirtyBits dirtyBitMask);
1291     angle::Result handleDirtyGraphicsDynamicPrimitiveRestartEnable(
1292         DirtyBits::Iterator *dirtyBitsIterator,
1293         DirtyBits dirtyBitMask);
1294     angle::Result handleDirtyGraphicsDynamicFragmentShadingRate(
1295         DirtyBits::Iterator *dirtyBitsIterator,
1296         DirtyBits dirtyBitMask);
1297 
1298     // Handlers for compute pipeline dirty bits.
1299     angle::Result handleDirtyComputeMemoryBarrier(DirtyBits::Iterator *dirtyBitsIterator);
1300     angle::Result handleDirtyComputeEventLog(DirtyBits::Iterator *dirtyBitsIterator);
1301     angle::Result handleDirtyComputePipelineDesc(DirtyBits::Iterator *dirtyBitsIterator);
1302     angle::Result handleDirtyComputePipelineBinding(DirtyBits::Iterator *dirtyBitsIterator);
1303     angle::Result handleDirtyComputeTextures(DirtyBits::Iterator *dirtyBitsIterator);
1304     angle::Result handleDirtyComputeDriverUniforms(DirtyBits::Iterator *dirtyBitsIterator);
1305     angle::Result handleDirtyComputeShaderResources(DirtyBits::Iterator *dirtyBitsIterator);
1306     angle::Result handleDirtyComputeUniformBuffers(DirtyBits::Iterator *dirtyBitsIterator);
1307     angle::Result handleDirtyComputeDescriptorSets(DirtyBits::Iterator *dirtyBitsIterator);
1308     angle::Result handleDirtyComputeUniforms(DirtyBits::Iterator *dirtyBitsIterator);
1309 
1310     // Common parts of the common dirty bit handlers.
1311     angle::Result handleDirtyUniformsImpl(DirtyBits::Iterator *dirtyBitsIterator);
1312     angle::Result handleDirtyMemoryBarrierImpl(DirtyBits::Iterator *dirtyBitsIterator,
1313                                                DirtyBits dirtyBitMask);
1314     template <typename CommandBufferT>
1315     angle::Result handleDirtyEventLogImpl(CommandBufferT *commandBuffer);
1316     template <typename CommandBufferHelperT>
1317     angle::Result handleDirtyTexturesImpl(CommandBufferHelperT *commandBufferHelper,
1318                                           PipelineType pipelineType);
1319     template <typename CommandBufferHelperT>
1320     angle::Result handleDirtyShaderResourcesImpl(CommandBufferHelperT *commandBufferHelper,
1321                                                  PipelineType pipelineType,
1322                                                  DirtyBits::Iterator *dirtyBitsIterator);
1323     template <typename CommandBufferHelperT>
1324     angle::Result handleDirtyUniformBuffersImpl(CommandBufferHelperT *commandBufferHelper);
1325     template <typename CommandBufferHelperT>
1326     angle::Result handleDirtyDescriptorSetsImpl(CommandBufferHelperT *commandBufferHelper,
1327                                                 PipelineType pipelineType);
1328     void handleDirtyGraphicsDynamicScissorImpl(bool isPrimitivesGeneratedQueryActive);
1329 
1330     void writeAtomicCounterBufferDriverUniformOffsets(uint32_t *offsetsOut, size_t offsetsSize);
1331 
1332     enum class Submit
1333     {
1334         OutsideRenderPassCommandsOnly,
1335         AllCommands,
1336     };
1337 
1338     angle::Result submitCommands(const vk::Semaphore *signalSemaphore,
1339                                  const vk::SharedExternalFence *externalFence,
1340                                  Submit submission);
1341     angle::Result flushImpl(const gl::Context *context);
1342 
1343     angle::Result synchronizeCpuGpuTime();
1344     angle::Result traceGpuEventImpl(vk::OutsideRenderPassCommandBuffer *commandBuffer,
1345                                     char phase,
1346                                     const EventName &name);
1347     angle::Result checkCompletedGpuEvents();
1348     void flushGpuEvents(double nextSyncGpuTimestampS, double nextSyncCpuTimestampS);
1349     void handleDeviceLost();
1350     bool shouldEmulateSeamfulCubeMapSampling() const;
1351     void clearAllGarbage();
1352     void dumpCommandStreamDiagnostics();
1353     angle::Result flushOutsideRenderPassCommands();
1354     // Flush commands and end render pass without setting any dirty bits.
1355     // flushCommandsAndEndRenderPass() and flushDirtyGraphicsRenderPass() will set the dirty bits
1356     // directly or through the iterator respectively.  Outside those two functions, this shouldn't
1357     // be called directly.
1358     angle::Result flushDirtyGraphicsRenderPass(DirtyBits::Iterator *dirtyBitsIterator,
1359                                                DirtyBits dirtyBitMask,
1360                                                RenderPassClosureReason reason);
1361 
1362     // Mark the render pass to be closed on the next draw call.  The render pass is not actually
1363     // closed and can be restored with restoreFinishedRenderPass if necessary, for example to append
1364     // a resolve attachment.
1365     void onRenderPassFinished(RenderPassClosureReason reason);
1366 
1367     void initIndexTypeMap();
1368 
1369     VertexArrayVk *getVertexArray() const;
1370     FramebufferVk *getDrawFramebuffer() const;
1371 
1372     // Read-after-write hazards are generally handled with |glMemoryBarrier| when the source of
1373     // write is storage output.  When the write is outside render pass, the natural placement of the
1374     // render pass after the current outside render pass commands ensures that the memory barriers
1375     // and image layout transitions automatically take care of such synchronizations.
1376     //
1377     // There are a number of read-after-write cases that require breaking the render pass however to
1378     // preserve the order of operations:
1379     //
1380     // - Transform feedback write (in render pass), then vertex/index read (in render pass)
1381     // - Transform feedback write (in render pass), then ubo read (outside render pass)
1382     // - Framebuffer attachment write (in render pass), then texture sample (outside render pass)
1383     //   * Note that texture sampling inside render pass would cause a feedback loop
1384     //
1385     angle::Result endRenderPassIfTransformFeedbackBuffer(const vk::BufferHelper *buffer);
1386     angle::Result endRenderPassIfComputeReadAfterTransformFeedbackWrite();
1387     angle::Result endRenderPassIfComputeAccessAfterGraphicsImageAccess();
1388 
1389     // Update read-only depth feedback loop mode.  Typically called from
1390     // handleDirtyGraphicsReadOnlyDepthFeedbackLoopMode, but can be called from UtilsVk in functions
1391     // that don't necessarily break the render pass.
1392     angle::Result switchOutReadOnlyDepthStencilMode(DirtyBits::Iterator *dirtyBitsIterator,
1393                                                     DirtyBits dirtyBitMask,
1394                                                     UpdateDepthFeedbackLoopReason depthReason,
1395                                                     UpdateDepthFeedbackLoopReason stencilReason);
1396     angle::Result switchToReadOnlyDepthStencilMode(gl::Texture *texture,
1397                                                    gl::Command command,
1398                                                    FramebufferVk *drawFramebuffer,
1399                                                    bool isStencilTexture);
1400 
1401     angle::Result onResourceAccess(const vk::CommandBufferAccess &access);
1402     angle::Result flushCommandBuffersIfNecessary(const vk::CommandBufferAccess &access);
1403     bool renderPassUsesStorageResources() const;
1404 
1405     angle::Result pushDebugGroupImpl(GLenum source, GLuint id, const char *message);
1406     angle::Result popDebugGroupImpl();
1407 
1408     void updateScissor(const gl::State &glState);
1409 
1410     void updateDepthStencil(const gl::State &glState);
1411     void updateDepthTestEnabled(const gl::State &glState);
1412     void updateDepthWriteEnabled(const gl::State &glState);
1413     void updateDepthFunc(const gl::State &glState);
1414     void updateStencilTestEnabled(const gl::State &glState);
1415 
1416     void updateSampleShadingWithRasterizationSamples(const uint32_t rasterizationSamples);
1417     void updateRasterizationSamples(const uint32_t rasterizationSamples);
1418     void updateRasterizerDiscardEnabled(bool isPrimitivesGeneratedQueryActive);
1419 
1420     void updateAdvancedBlendEquations(const gl::ProgramExecutable *executable);
1421 
1422     void updateDither();
1423 
1424     // For dynamic rendering only, mark the current render pass as being in framebuffer fetch mode.
1425     // In this mode, the FramebufferVk object and its render pass description are unaffected by
1426     // framebuffer fetch use, and the context needs to just configure the command buffer for
1427     // framebuffer fetch.
1428     void onFramebufferFetchUse(vk::FramebufferFetchMode framebufferFetchMode);
1429 
1430     // When the useNonZeroStencilWriteMaskStaticState workaround is enabled, the static state for
1431     // stencil should be non-zero despite the state being dynamic.  This is done when:
1432     //
1433     // - The shader includes discard, or
1434     // - Alpha-to-coverage is enabled.
1435     //
1436     // An alternative could have been to set the static state unconditionally to non-zero.  This is
1437     // avoided however, as on the affected driver that would disable certain optimizations.
1438     void updateStencilWriteWorkaround();
1439 
1440     void updateShaderResourcesWithSharedCacheKey(
1441         const vk::SharedDescriptorSetCacheKey &sharedCacheKey);
1442 
1443     angle::Result createGraphicsPipeline();
1444 
1445     angle::Result allocateQueueSerialIndex();
1446     void releaseQueueSerialIndex();
1447 
1448     void generateOutsideRenderPassCommandsQueueSerial();
1449     void generateRenderPassCommandsQueueSerial(QueueSerial *queueSerialOut);
1450 
1451     angle::Result ensureInterfacePipelineCache();
1452 
1453     angle::ImageLoadContext mImageLoadContext;
1454 
1455     std::array<GraphicsDirtyBitHandler, DIRTY_BIT_MAX> mGraphicsDirtyBitHandlers;
1456     std::array<ComputeDirtyBitHandler, DIRTY_BIT_MAX> mComputeDirtyBitHandlers;
1457 
1458     vk::RenderPassCommandBuffer *mRenderPassCommandBuffer;
1459 
1460     vk::PipelineHelper *mCurrentGraphicsPipeline;
1461     vk::PipelineHelper *mCurrentGraphicsPipelineShaders;
1462     vk::PipelineHelper *mCurrentComputePipeline;
1463     gl::PrimitiveMode mCurrentDrawMode;
1464 
1465     WindowSurfaceVk *mCurrentWindowSurface;
1466     // Records the current rotation of the surface (draw/read) framebuffer, derived from
1467     // mCurrentWindowSurface->getPreTransform().
1468     SurfaceRotation mCurrentRotationDrawFramebuffer;
1469     SurfaceRotation mCurrentRotationReadFramebuffer;
1470 
1471     // Tracks if we are in depth/stencil *read-only* or feedback loop mode. The read only is
1472     // specially allowed as both usages attachment and texture are read-only. When switching away
1473     // from read-only mode, the render pass is broken is to accommodate the new writable layout.
1474     vk::RenderPassUsageFlags mDepthStencilAttachmentFlags;
1475 
1476     // Keep a cached pipeline description structure that can be used to query the pipeline cache.
1477     // Kept in a pointer so allocations can be aligned, and structs can be portably packed.
1478     std::unique_ptr<vk::GraphicsPipelineDesc> mGraphicsPipelineDesc;
1479     // Transition bits indicating which state has changed since last pipeline recreation.  It is
1480     // used to look up pipelines in the cache without iterating over the entire key as a performance
1481     // optimization.
1482     //
1483     // |mGraphicsPipelineTransition| tracks transition bits since the last complete pipeline
1484     // creation/retrieval.  |mGraphicsPipelineLibraryTransition| tracks the same but for the case
1485     // where the pipeline is created through libraries.  The latter accumulates
1486     // |mGraphicsPipelineTransition| while the caches are hit, so that the bits are not lost if a
1487     // partial library needs to be created in the future.
1488     vk::GraphicsPipelineTransitionBits mGraphicsPipelineTransition;
1489     vk::GraphicsPipelineTransitionBits mGraphicsPipelineLibraryTransition;
1490 
1491     // A pipeline cache specifically used for vertex input and fragment output pipelines, when there
1492     // is no blob reuse between libraries and monolithic pipelines.  In that case, there's no point
1493     // in making monolithic pipelines be stored in the same cache as these partial pipelines.
1494     //
1495     // Note additionally that applications only create a handful of vertex input and fragment output
1496     // pipelines, which is also s fast operation, so this cache is both small and ephemeral (i.e.
1497     // not cached to disk).
1498     vk::PipelineCache mInterfacePipelinesCache;
1499 
1500     // These pools are externally synchronized, so cannot be accessed from different
1501     // threads simultaneously. Hence, we keep them in the ContextVk instead of the vk::Renderer.
1502     // Note that this implementation would need to change in shared resource scenarios. Likely
1503     // we'd instead share a single set of pools between the share groups.
1504     gl::QueryTypeMap<vk::DynamicQueryPool> mQueryPools;
1505 
1506     // Queries that need to be closed and reopened with the render pass:
1507     //
1508     // - Occlusion queries
1509     // - Transform feedback queries, if not emulated
1510     gl::QueryTypeMap<QueryVk *> mActiveRenderPassQueries;
1511 
1512     // Dirty bits.
1513     DirtyBits mGraphicsDirtyBits;
1514     DirtyBits mComputeDirtyBits;
1515     DirtyBits mNonIndexedDirtyBitsMask;
1516     DirtyBits mIndexedDirtyBitsMask;
1517     DirtyBits mNewGraphicsCommandBufferDirtyBits;
1518     DirtyBits mNewComputeCommandBufferDirtyBits;
1519     DirtyBits mDynamicStateDirtyBits;
1520     DirtyBits mPersistentGraphicsDirtyBits;
1521     static constexpr DirtyBits kColorAccessChangeDirtyBits{DIRTY_BIT_COLOR_ACCESS};
1522     static constexpr DirtyBits kDepthStencilAccessChangeDirtyBits{
1523         DIRTY_BIT_READ_ONLY_DEPTH_FEEDBACK_LOOP_MODE, DIRTY_BIT_DEPTH_STENCIL_ACCESS};
1524     static constexpr DirtyBits kIndexAndVertexDirtyBits{DIRTY_BIT_VERTEX_BUFFERS,
1525                                                         DIRTY_BIT_INDEX_BUFFER};
1526     static constexpr DirtyBits kPipelineDescAndBindingDirtyBits{DIRTY_BIT_PIPELINE_DESC,
1527                                                                 DIRTY_BIT_PIPELINE_BINDING};
1528     static constexpr DirtyBits kTexturesAndDescSetDirtyBits{DIRTY_BIT_TEXTURES,
1529                                                             DIRTY_BIT_DESCRIPTOR_SETS};
1530     static constexpr DirtyBits kResourcesAndDescSetDirtyBits{DIRTY_BIT_SHADER_RESOURCES,
1531                                                              DIRTY_BIT_DESCRIPTOR_SETS};
1532     static constexpr DirtyBits kUniformBuffersAndDescSetDirtyBits{DIRTY_BIT_UNIFORM_BUFFERS,
1533                                                                   DIRTY_BIT_DESCRIPTOR_SETS};
1534     static constexpr DirtyBits kXfbBuffersAndDescSetDirtyBits{DIRTY_BIT_TRANSFORM_FEEDBACK_BUFFERS,
1535                                                               DIRTY_BIT_DESCRIPTOR_SETS};
1536 
1537     // The offset we had the last time we bound the index buffer.
1538     const GLvoid *mLastIndexBufferOffset;
1539     vk::BufferHelper *mCurrentIndexBuffer;
1540     VkDeviceSize mCurrentIndexBufferOffset;
1541     gl::DrawElementsType mCurrentDrawElementsType;
1542     angle::PackedEnumMap<gl::DrawElementsType, VkIndexType> mIndexTypeMap;
1543 
1544     // Cache the current draw call's firstVertex to be passed to
1545     // TransformFeedbackVk::getBufferOffsets.  Unfortunately, gl_BaseVertex support in Vulkan is
1546     // not yet ubiquitous, which would have otherwise removed the need for this value to be passed
1547     // as a uniform.
1548     GLint mXfbBaseVertex;
1549     // Cache the current draw call's vertex count as well to support instanced draw calls
1550     GLuint mXfbVertexCountPerInstance;
1551 
1552     // Cached clear value/mask for color and depth/stencil.
1553     VkClearValue mClearColorValue;
1554     VkClearValue mClearDepthStencilValue;
1555     gl::BlendStateExt::ColorMaskStorage::Type mClearColorMasks;
1556 
1557     // The unprocessed bits passed in from the previous glMemoryBarrier call
1558     GLbitfield mDeferredMemoryBarriers;
1559 
1560     IncompleteTextureSet mIncompleteTextures;
1561 
1562     // If the current surface bound to this context wants to have all rendering flipped vertically.
1563     // Updated on calls to onMakeCurrent.
1564     bool mFlipYForCurrentSurface;
1565     bool mFlipViewportForDrawFramebuffer;
1566     bool mFlipViewportForReadFramebuffer;
1567 
1568     // If any host-visible buffer is written by the GPU since last submission, a barrier is inserted
1569     // at the end of the command buffer to make that write available to the host.
1570     bool mIsAnyHostVisibleBufferWritten;
1571 
1572     // This info is used in the descriptor update step.
1573     gl::ActiveTextureArray<TextureVk *> mActiveTextures;
1574 
1575     vk::DescriptorSetDescBuilder mShaderBuffersDescriptorDesc;
1576     // The WriteDescriptorDescs from ProgramExecutableVk with InputAttachment update.
1577     vk::WriteDescriptorDescs mShaderBufferWriteDescriptorDescs;
1578 
1579     gl::ActiveTextureArray<TextureVk *> mActiveImages;
1580 
1581     // "Current Value" aka default vertex attribute state.
1582     gl::AttributesMask mDirtyDefaultAttribsMask;
1583 
1584     // DynamicBuffers for streaming vertex data from client memory pointer as well as for default
1585     // attributes. mHasInFlightStreamedVertexBuffers indicates if the dynamic buffer has any
1586     // in-flight buffer or not that we need to release at submission time.
1587     gl::AttribArray<vk::DynamicBuffer> mStreamedVertexBuffers;
1588     gl::AttributesMask mHasInFlightStreamedVertexBuffers;
1589 
1590     // We use a single pool for recording commands. We also keep a free list for pool recycling.
1591     vk::SecondaryCommandPools mCommandPools;
1592 
1593     // Per context queue serial
1594     SerialIndex mCurrentQueueSerialIndex;
1595     QueueSerial mLastFlushedQueueSerial;
1596     QueueSerial mLastSubmittedQueueSerial;
1597     // All submitted queue serials over the life time of this context.
1598     vk::ResourceUse mSubmittedResourceUse;
1599     // Current active transform feedback buffer queue serial. Invalid if TF not active.
1600     QueueSerial mCurrentTransformFeedbackQueueSerial;
1601 
1602     // The garbage list for single context use objects. The list will be GPU tracked by next
1603     // submission queueSerial. Note: Resource based shared object should always be added to
1604     // renderer's mSharedGarbageList.
1605     vk::GarbageObjects mCurrentGarbage;
1606 
1607     RenderPassCache mRenderPassCache;
1608     // Used with dynamic rendering as it doesn't use render passes.
1609     vk::RenderPass mNullRenderPass;
1610 
1611     vk::OutsideRenderPassCommandBufferHelper *mOutsideRenderPassCommands;
1612     vk::RenderPassCommandBufferHelper *mRenderPassCommands;
1613 
1614     // Allocators for the render pass command buffers. They are utilized only when shared ring
1615     // buffer allocators are being used.
1616     vk::SecondaryCommandMemoryAllocator mOutsideRenderPassCommandsAllocator;
1617     vk::SecondaryCommandMemoryAllocator mRenderPassCommandsAllocator;
1618 
1619     // The following is used when creating debug-util markers for graphics debuggers (e.g. AGI).  A
1620     // given gl{Begin|End}Query command may result in commands being submitted to the outside or
1621     // render-pass command buffer.  The ContextVk::handleGraphicsEventLog() method records the
1622     // appropriate command buffer for use by ContextVk::endEventLogForQuery().  The knowledge of
1623     // which command buffer to use depends on the particular type of query (e.g. samples
1624     // vs. timestamp), and is only known by the query code, which is what calls
1625     // ContextVk::handleGraphicsEventLog().  After all back-end processing of the gl*Query command
1626     // is complete, the front-end calls ContextVk::endEventLogForQuery(), which needs to know which
1627     // command buffer to call endDebugUtilsLabelEXT() for.
1628     GraphicsEventCmdBuf mQueryEventType;
1629 
1630     // Internal shader library.
1631     vk::ShaderLibrary mShaderLibrary;
1632     UtilsVk mUtils;
1633 
1634     bool mGpuEventsEnabled;
1635     vk::DynamicQueryPool mGpuEventQueryPool;
1636     // A list of queries that have yet to be turned into an event (their result is not yet
1637     // available).
1638     std::vector<GpuEventQuery> mInFlightGpuEventQueries;
1639     // A list of gpu events since the last clock sync.
1640     std::vector<GpuEvent> mGpuEvents;
1641     // The current frame index, used to generate a submission-encompassing event tagged with it.
1642     uint32_t mPrimaryBufferEventCounter;
1643 
1644     // Cached value of the color attachment mask of the current draw framebuffer.  This is used to
1645     // know which attachment indices have their blend state set in |mGraphicsPipelineDesc|, and
1646     // subsequently is used to clear the blend state for attachments that no longer exist when a new
1647     // framebuffer is bound.
1648     gl::DrawBufferMask mCachedDrawFramebufferColorAttachmentMask;
1649 
1650     // Whether a flush was requested, but is deferred as an optimization to avoid breaking the
1651     // render pass.
1652     bool mHasDeferredFlush;
1653 
1654     // Whether this context has produced any commands so far.  While the renderer already skips
1655     // vkQueueSubmit when there is no command recorded, this variable allows glFlush itself to be
1656     // entirely skipped.  This is particularly needed for an optimization where the Surface is in
1657     // shared-present mode, and the app is unnecessarily calling eglSwapBuffers (which equates
1658     // glFlush in that mode).
1659     bool mHasAnyCommandsPendingSubmission;
1660 
1661     // Whether color framebuffer fetch is active.  When the permanentlySwitchToFramebufferFetchMode
1662     // feature is enabled, if any program uses framebuffer fetch, rendering switches to assuming
1663     // framebuffer fetch could happen in any render pass.  This incurs a potential cost due to usage
1664     // of the GENERAL layout instead of COLOR_ATTACHMENT_OPTIMAL, but has definite benefits of
1665     // avoiding render pass breaks when a framebuffer fetch program is used mid render pass.
1666     //
1667     // This only applies to legacy render passes (i.e. when dynamic rendering is NOT used).  In the
1668     // case of dynamic rendering, every render pass starts with the assumption of not needing input
1669     // attachments and switches later if it needs to with no penalty.
1670     //
1671     // Note that depth/stencil framebuffer fetch does not need this sort of tracking because it is
1672     // only enabled with dynamic rendering.
1673     bool mIsInColorFramebufferFetchMode;
1674 
1675     // True if current started render pass is allowed to reactivate.
1676     bool mAllowRenderPassToReactivate;
1677 
1678     // The size of copy commands issued between buffers and images. Used to submit the command
1679     // buffer for the outside render pass.
1680     VkDeviceSize mTotalBufferToImageCopySize;
1681     VkDeviceSize mEstimatedPendingImageGarbageSize;
1682 
1683     // Semaphores that must be flushed before the current commands. Flushed semaphores will be
1684     // waited on in the next submission.
1685     std::vector<VkSemaphore> mWaitSemaphores;
1686     std::vector<VkPipelineStageFlags> mWaitSemaphoreStageMasks;
1687     // Whether this context has wait semaphores (flushed and unflushed) that must be submitted.
1688     bool mHasWaitSemaphoresPendingSubmission;
1689 
1690     // Hold information from the last gpu clock sync for future gpu-to-cpu timestamp conversions.
1691     GpuClockSyncInfo mGpuClockSync;
1692 
1693     // The very first timestamp queried for a GPU event is used as origin, so event timestamps would
1694     // have a value close to zero, to avoid losing 12 bits when converting these 64 bit values to
1695     // double.
1696     uint64_t mGpuEventTimestampOrigin;
1697 
1698     // A mix of per-frame and per-run counters.
1699     angle::PerfMonitorCounterGroups mPerfMonitorCounters;
1700 
1701     gl::state::DirtyBits mPipelineDirtyBitsMask;
1702 
1703     egl::ContextPriority mInitialContextPriority;
1704     egl::ContextPriority mContextPriority;
1705     vk::ProtectionType mProtectionType;
1706 
1707     ShareGroupVk *mShareGroupVk;
1708 
1709     // This is a special "empty" placeholder buffer for use when we just need a placeholder buffer
1710     // but not the data. Examples are shader that has no uniform or doesn't use all slots in the
1711     // atomic counter buffer array, or places where there is no vertex buffer since Vulkan does not
1712     // allow binding a null vertex buffer.
1713     vk::BufferHelper mEmptyBuffer;
1714 
1715     // Storage for default uniforms of ProgramVks and ProgramPipelineVks.
1716     vk::DynamicBuffer mDefaultUniformStorage;
1717 
1718     std::vector<std::string> mCommandBufferDiagnostics;
1719 
1720     // Record GL API calls for debuggers
1721     std::vector<std::string> mEventLog;
1722 
1723     // Viewport and scissor are handled as dynamic state.
1724     VkViewport mViewport;
1725     VkRect2D mScissor;
1726 
1727     VulkanCacheStats mVulkanCacheStats;
1728 
1729     RangedSerialFactory mOutsideRenderPassSerialFactory;
1730 
1731     uint32_t mCommandsPendingSubmissionCount;
1732 };
1733 
endRenderPassIfTransformFeedbackBuffer(const vk::BufferHelper * buffer)1734 ANGLE_INLINE angle::Result ContextVk::endRenderPassIfTransformFeedbackBuffer(
1735     const vk::BufferHelper *buffer)
1736 {
1737     if (!mCurrentTransformFeedbackQueueSerial.valid() || !buffer ||
1738         !buffer->writtenByCommandBuffer(mCurrentTransformFeedbackQueueSerial))
1739     {
1740         return angle::Result::Continue;
1741     }
1742 
1743     return flushCommandsAndEndRenderPass(RenderPassClosureReason::XfbWriteThenVertexIndexBuffer);
1744 }
1745 
onIndexBufferChange(const vk::BufferHelper * currentIndexBuffer)1746 ANGLE_INLINE angle::Result ContextVk::onIndexBufferChange(
1747     const vk::BufferHelper *currentIndexBuffer)
1748 {
1749     mGraphicsDirtyBits.set(DIRTY_BIT_INDEX_BUFFER);
1750     mLastIndexBufferOffset = reinterpret_cast<const void *>(angle::DirtyPointer);
1751     return endRenderPassIfTransformFeedbackBuffer(currentIndexBuffer);
1752 }
1753 
onVertexBufferChange(const vk::BufferHelper * vertexBuffer)1754 ANGLE_INLINE angle::Result ContextVk::onVertexBufferChange(const vk::BufferHelper *vertexBuffer)
1755 {
1756     mGraphicsDirtyBits.set(DIRTY_BIT_VERTEX_BUFFERS);
1757     return endRenderPassIfTransformFeedbackBuffer(vertexBuffer);
1758 }
1759 
onVertexAttributeChange(size_t attribIndex,GLuint stride,GLuint divisor,angle::FormatID format,bool compressed,GLuint relativeOffset,const vk::BufferHelper * vertexBuffer)1760 ANGLE_INLINE angle::Result ContextVk::onVertexAttributeChange(size_t attribIndex,
1761                                                               GLuint stride,
1762                                                               GLuint divisor,
1763                                                               angle::FormatID format,
1764                                                               bool compressed,
1765                                                               GLuint relativeOffset,
1766                                                               const vk::BufferHelper *vertexBuffer)
1767 {
1768     const GLuint staticStride =
1769         mRenderer->getFeatures().useVertexInputBindingStrideDynamicState.enabled ? 0 : stride;
1770 
1771     if (!getFeatures().supportsVertexInputDynamicState.enabled)
1772     {
1773         invalidateCurrentGraphicsPipeline();
1774 
1775         // Set divisor to 1 for attribs with emulated divisor
1776         mGraphicsPipelineDesc->updateVertexInput(
1777             this, &mGraphicsPipelineTransition, static_cast<uint32_t>(attribIndex), staticStride,
1778             divisor > mRenderer->getMaxVertexAttribDivisor() ? 1 : divisor, format, compressed,
1779             relativeOffset);
1780     }
1781     return onVertexBufferChange(vertexBuffer);
1782 }
1783 
hasUnsubmittedUse(const vk::ResourceUse & use)1784 ANGLE_INLINE bool ContextVk::hasUnsubmittedUse(const vk::ResourceUse &use) const
1785 {
1786     return mCurrentQueueSerialIndex != kInvalidQueueSerialIndex &&
1787            use > QueueSerial(mCurrentQueueSerialIndex,
1788                              mRenderer->getLastSubmittedSerial(mCurrentQueueSerialIndex));
1789 }
1790 
UseLineRaster(const ContextVk * contextVk,gl::PrimitiveMode mode)1791 ANGLE_INLINE bool UseLineRaster(const ContextVk *contextVk, gl::PrimitiveMode mode)
1792 {
1793     return gl::IsLineMode(mode);
1794 }
1795 
1796 uint32_t GetDriverUniformSize(vk::ErrorContext *context, PipelineType pipelineType);
1797 }  // namespace rx
1798 
1799 // Generate a perf warning, and insert an event marker in the command buffer.
1800 #define ANGLE_VK_PERF_WARNING(contextVk, severity, ...)                             \
1801     do                                                                              \
1802     {                                                                               \
1803         ANGLE_PERF_WARNING(contextVk->getDebug(), severity, __VA_ARGS__);           \
1804         if (contextVk->isDebugEnabled())                                            \
1805         {                                                                           \
1806             char ANGLE_MESSAGE[200];                                                \
1807             snprintf(ANGLE_MESSAGE, sizeof(ANGLE_MESSAGE), __VA_ARGS__);            \
1808             contextVk->insertEventMarkerImpl(GL_DEBUG_SOURCE_OTHER, ANGLE_MESSAGE); \
1809         }                                                                           \
1810     } while (0)
1811 
1812 // Generate a trace event for graphics profiler, and insert an event marker in the command buffer.
1813 #define ANGLE_VK_TRACE_EVENT_AND_MARKER(contextVk, ...)                         \
1814     do                                                                          \
1815     {                                                                           \
1816         char ANGLE_MESSAGE[200];                                                \
1817         snprintf(ANGLE_MESSAGE, sizeof(ANGLE_MESSAGE), __VA_ARGS__);            \
1818         ANGLE_TRACE_EVENT0("gpu.angle", ANGLE_MESSAGE);                         \
1819                                                                                 \
1820         contextVk->insertEventMarkerImpl(GL_DEBUG_SOURCE_OTHER, ANGLE_MESSAGE); \
1821     } while (0)
1822 
1823 #endif  // LIBANGLE_RENDERER_VULKAN_CONTEXTVK_H_
1824