1 /*
2 * Copyright 2021 Google LLC
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef skgpu_graphite_Renderer_DEFINED
9 #define skgpu_graphite_Renderer_DEFINED
10
11 #include "include/core/SkSpan.h"
12 #include "include/core/SkString.h"
13 #include "include/core/SkTypes.h"
14 #include "include/gpu/graphite/GraphiteTypes.h"
15 #include "src/base/SkEnumBitMask.h"
16 #include "src/base/SkVx.h"
17 #include "src/gpu/graphite/Attribute.h"
18 #include "src/gpu/graphite/DrawTypes.h"
19 #include "src/gpu/graphite/ResourceTypes.h"
20 #include "src/gpu/graphite/Uniform.h"
21
22 #include <array>
23 #include <initializer_list>
24 #include <string>
25 #include <string_view>
26 #include <vector>
27
28 enum class SkPathFillType;
29
30 namespace skgpu { enum class MaskFormat; }
31
32 namespace skgpu::graphite {
33
34 class DrawWriter;
35 class DrawParams;
36 class PipelineDataGatherer;
37 class Rect;
38 class ResourceProvider;
39 class TextureDataBlock;
40 class Transform;
41
42 struct ResourceBindingRequirements;
43
44 enum class Coverage { kNone, kSingleChannel, kLCD };
45
46 /**
47 * The actual technique for rasterizing a high-level draw recorded in a DrawList is handled by a
48 * specific Renderer. Each technique has an associated singleton Renderer that decomposes the
49 * technique into a series of RenderSteps that must be executed in the specified order for the draw.
50 * However, the RenderStep executions for multiple draws can be re-arranged so batches of each
51 * step can be performed in a larger GPU operation. This re-arranging relies on accurate
52 * determination of the DisjointStencilIndex for each draw so that stencil steps are not corrupted
53 * by another draw before its cover step is executed. It also relies on the CompressedPaintersOrder
54 * for each draw to ensure steps are not re-arranged in a way that violates the original draw order.
55 *
56 * Renderer itself is non-virtual since it simply has to point to a list of RenderSteps. RenderSteps
57 * on the other hand are virtual implement the technique specific functionality. It is entirely
58 * possible for certain types of steps, e.g. a bounding box cover, to be re-used across different
59 * Renderers even if the preceeding steps were different.
60 *
61 * All Renderers are accessed through the SharedContext's RendererProvider.
62 */
63 class RenderStep {
64 public:
65 virtual ~RenderStep() = default;
66
67 // The DrawWriter is configured with the vertex and instance strides of the RenderStep, and its
68 // primitive type. The recorded draws will be executed with a graphics pipeline compatible with
69 // this RenderStep.
70 virtual void writeVertices(DrawWriter*, const DrawParams&, skvx::uint2 ssboIndices) const = 0;
71
72 // Write out the uniform values (aligned for the layout), textures, and samplers. The uniform
73 // values will be de-duplicated across all draws using the RenderStep before uploading to the
74 // GPU, but it can be assumed the uniforms will be bound before the draws recorded in
75 // 'writeVertices' are executed.
76 virtual void writeUniformsAndTextures(const DrawParams&, PipelineDataGatherer*) const = 0;
77
78 // Returns the body of a vertex function, which must define a float4 devPosition variable and
79 // must write to an already-defined float2 stepLocalCoords variable. This will be automatically
80 // set to a varying for the fragment shader if the paint requires local coords. This SkSL has
81 // access to the variables declared by vertexAttributes(), instanceAttributes(), and uniforms().
82 // The 'devPosition' variable's z must store the PaintDepth normalized to a float from [0, 1],
83 // for each processed draw although the RenderStep can choose to upload it in any manner.
84 //
85 // NOTE: The above contract is mainly so that the entire SkSL program can be created by just str
86 // concatenating struct definitions generated from the RenderStep and paint Combination
87 // and then including the function bodies returned here.
88 virtual std::string vertexSkSL() const = 0;
89
90 // Emits code to set up textures and samplers. Should only be defined if hasTextures is true.
texturesAndSamplersSkSL(const ResourceBindingRequirements &,int * nextBindingIndex)91 virtual std::string texturesAndSamplersSkSL(const ResourceBindingRequirements&,
92 int* nextBindingIndex) const {
93 return R"()";
94 }
95
96 // Emits code to set up coverage value. Should only be defined if overridesCoverage is true.
97 // When implemented the returned SkSL fragment should write its coverage into a
98 // 'half4 outputCoverage' variable (defined in the calling code) with the actual
99 // coverage splatted out into all four channels.
fragmentCoverageSkSL()100 virtual const char* fragmentCoverageSkSL() const { return R"()"; }
101
102 // Emits code to set up a primitive color value. Should only be defined if emitsPrimitiveColor
103 // is true. When implemented, the returned SkSL fragment should write its color into a
104 // 'half4 primitiveColor' variable (defined in the calling code).
fragmentColorSkSL()105 virtual const char* fragmentColorSkSL() const { return R"()"; }
106
uniqueID()107 uint32_t uniqueID() const { return fUniqueID; }
108
109 // Returns a name formatted as "Subclass[variant]", where "Subclass" matches the C++ class name
110 // and variant is a unique term describing instance's specific configuration.
name()111 const char* name() const { return fName.c_str(); }
112
requiresMSAA()113 bool requiresMSAA() const { return SkToBool(fFlags & Flags::kRequiresMSAA); }
performsShading()114 bool performsShading() const { return SkToBool(fFlags & Flags::kPerformsShading); }
hasTextures()115 bool hasTextures() const { return SkToBool(fFlags & Flags::kHasTextures); }
emitsPrimitiveColor()116 bool emitsPrimitiveColor() const { return SkToBool(fFlags & Flags::kEmitsPrimitiveColor); }
outsetBoundsForAA()117 bool outsetBoundsForAA() const { return SkToBool(fFlags & Flags::kOutsetBoundsForAA); }
useNonAAInnerFill()118 bool useNonAAInnerFill() const { return SkToBool(fFlags & Flags::kUseNonAAInnerFill); }
119
coverage()120 Coverage coverage() const { return RenderStep::GetCoverage(fFlags); }
121
primitiveType()122 PrimitiveType primitiveType() const { return fPrimitiveType; }
vertexStride()123 size_t vertexStride() const { return fVertexStride; }
instanceStride()124 size_t instanceStride() const { return fInstanceStride; }
125
numUniforms()126 size_t numUniforms() const { return fUniforms.size(); }
numVertexAttributes()127 size_t numVertexAttributes() const { return fVertexAttrs.size(); }
numInstanceAttributes()128 size_t numInstanceAttributes() const { return fInstanceAttrs.size(); }
129
130 // Name of an attribute containing both render step and shading SSBO indices, if used.
ssboIndicesAttribute()131 static const char* ssboIndicesAttribute() { return "ssboIndices"; }
132
133 // Name of a varying to pass SSBO indices to fragment shader. Both render step and shading
134 // indices are passed, because render step uniforms are sometimes used for coverage.
ssboIndicesVarying()135 static const char* ssboIndicesVarying() { return "ssboIndicesVar"; }
136
137 // The uniforms of a RenderStep are bound to the kRenderStep slot, the rest of the pipeline
138 // may still use uniforms bound to other slots.
uniforms()139 SkSpan<const Uniform> uniforms() const { return SkSpan(fUniforms); }
vertexAttributes()140 SkSpan<const Attribute> vertexAttributes() const { return SkSpan(fVertexAttrs); }
instanceAttributes()141 SkSpan<const Attribute> instanceAttributes() const { return SkSpan(fInstanceAttrs); }
varyings()142 SkSpan<const Varying> varyings() const { return SkSpan(fVaryings); }
143
depthStencilSettings()144 const DepthStencilSettings& depthStencilSettings() const { return fDepthStencilSettings; }
145
depthStencilFlags()146 SkEnumBitMask<DepthStencilFlags> depthStencilFlags() const {
147 return (fDepthStencilSettings.fStencilTestEnabled
148 ? DepthStencilFlags::kStencil : DepthStencilFlags::kNone) |
149 (fDepthStencilSettings.fDepthTestEnabled || fDepthStencilSettings.fDepthWriteEnabled
150 ? DepthStencilFlags::kDepth : DepthStencilFlags::kNone);
151 }
152
153 // TODO: Actual API to do things
154 // 6. Some Renderers benefit from being able to share vertices between RenderSteps. Must find a
155 // way to support that. It may mean that RenderSteps get state per draw.
156 // - Does Renderer make RenderStepFactories that create steps for each DrawList::Draw?
157 // - Does DrawList->DrawPass conversion build a separate array of blind data that the
158 // stateless Renderstep can refer to for {draw,step} pairs?
159 // - Does each DrawList::Draw have extra space (e.g. 8 bytes) that steps can cache data in?
160 protected:
161 enum class Flags : unsigned {
162 kNone = 0b00000000,
163 kRequiresMSAA = 0b00000001,
164 kPerformsShading = 0b00000010,
165 kHasTextures = 0b00000100,
166 kEmitsCoverage = 0b00001000,
167 kLCDCoverage = 0b00010000,
168 kEmitsPrimitiveColor = 0b00100000,
169 kOutsetBoundsForAA = 0b01000000,
170 kUseNonAAInnerFill = 0b10000000,
171 };
172 SK_DECL_BITMASK_OPS_FRIENDS(Flags)
173
174 // While RenderStep does not define the full program that's run for a draw, it defines the
175 // entire vertex layout of the pipeline. This is not allowed to change, so can be provided to
176 // the RenderStep constructor by subclasses.
177 RenderStep(std::string_view className,
178 std::string_view variantName,
179 SkEnumBitMask<Flags> flags,
180 std::initializer_list<Uniform> uniforms,
181 PrimitiveType primitiveType,
182 DepthStencilSettings depthStencilSettings,
183 SkSpan<const Attribute> vertexAttrs,
184 SkSpan<const Attribute> instanceAttrs,
185 SkSpan<const Varying> varyings = {});
186
187 private:
188 friend class Renderer; // for Flags
189
190 // Cannot copy or move
191 RenderStep(const RenderStep&) = delete;
192 RenderStep(RenderStep&&) = delete;
193
194 static Coverage GetCoverage(SkEnumBitMask<Flags>);
195
196 uint32_t fUniqueID;
197 SkEnumBitMask<Flags> fFlags;
198 PrimitiveType fPrimitiveType;
199
200 DepthStencilSettings fDepthStencilSettings;
201
202 // TODO: When we always use C++17 for builds, we should be able to just let subclasses declare
203 // constexpr arrays and point to those, but we need explicit storage for C++14.
204 // Alternatively, if we imposed a max attr count, similar to Renderer's num render steps, we
205 // could just have this be std::array and keep all attributes inline with the RenderStep memory.
206 // On the other hand, the attributes are only needed when creating a new pipeline so it's not
207 // that performance sensitive.
208 std::vector<Uniform> fUniforms;
209 std::vector<Attribute> fVertexAttrs;
210 std::vector<Attribute> fInstanceAttrs;
211 std::vector<Varying> fVaryings;
212
213 size_t fVertexStride; // derived from vertex attribute set
214 size_t fInstanceStride; // derived from instance attribute set
215
216 std::string fName;
217 };
SK_MAKE_BITMASK_OPS(RenderStep::Flags)218 SK_MAKE_BITMASK_OPS(RenderStep::Flags)
219
220 class Renderer {
221 using StepFlags = RenderStep::Flags;
222 public:
223 // The maximum number of render steps that any Renderer is allowed to have.
224 static constexpr int kMaxRenderSteps = 4;
225
226 const RenderStep& step(int i) const {
227 SkASSERT(i >= 0 && i < fStepCount);
228 return *fSteps[i];
229 }
230 SkSpan<const RenderStep* const> steps() const {
231 SkASSERT(fStepCount > 0); // steps() should only be called on valid Renderers.
232 return {fSteps.data(), static_cast<size_t>(fStepCount) };
233 }
234
235 const char* name() const { return fName.c_str(); }
236 DrawTypeFlags drawTypes() const { return fDrawTypes; }
237 int numRenderSteps() const { return fStepCount; }
238
239 bool requiresMSAA() const {
240 return SkToBool(fStepFlags & StepFlags::kRequiresMSAA);
241 }
242 bool emitsPrimitiveColor() const {
243 return SkToBool(fStepFlags & StepFlags::kEmitsPrimitiveColor);
244 }
245 bool outsetBoundsForAA() const {
246 return SkToBool(fStepFlags & StepFlags::kOutsetBoundsForAA);
247 }
248 bool useNonAAInnerFill() const {
249 return SkToBool(fStepFlags & StepFlags::kUseNonAAInnerFill);
250 }
251
252 SkEnumBitMask<DepthStencilFlags> depthStencilFlags() const { return fDepthStencilFlags; }
253
254 Coverage coverage() const { return RenderStep::GetCoverage(fStepFlags); }
255
256 private:
257 friend class RendererProvider; // for ctors
258
259 // Max render steps is 4, so just spell the options out for now...
260 Renderer(std::string_view name, DrawTypeFlags drawTypes, const RenderStep* s1)
261 : Renderer(name, drawTypes, std::array<const RenderStep*, 1>{s1}) {}
262
263 Renderer(std::string_view name, DrawTypeFlags drawTypes,
264 const RenderStep* s1, const RenderStep* s2)
265 : Renderer(name, drawTypes, std::array<const RenderStep*, 2>{s1, s2}) {}
266
267 Renderer(std::string_view name, DrawTypeFlags drawTypes,
268 const RenderStep* s1, const RenderStep* s2, const RenderStep* s3)
269 : Renderer(name, drawTypes, std::array<const RenderStep*, 3>{s1, s2, s3}) {}
270
271 Renderer(std::string_view name, DrawTypeFlags drawTypes,
272 const RenderStep* s1, const RenderStep* s2, const RenderStep* s3, const RenderStep* s4)
273 : Renderer(name, drawTypes, std::array<const RenderStep*, 4>{s1, s2, s3, s4}) {}
274
275 template<size_t N>
276 Renderer(std::string_view name, DrawTypeFlags drawTypes, std::array<const RenderStep*, N> steps)
277 : fName(name)
278 , fDrawTypes(drawTypes)
279 , fStepCount(SkTo<int>(N)) {
280 static_assert(N <= kMaxRenderSteps);
281 for (int i = 0 ; i < fStepCount; ++i) {
282 fSteps[i] = steps[i];
283 fStepFlags |= fSteps[i]->fFlags;
284 fDepthStencilFlags |= fSteps[i]->depthStencilFlags();
285 }
286 // At least one step needs to actually shade.
287 SkASSERT(fStepFlags & RenderStep::Flags::kPerformsShading);
288 // A render step using non-AA inner fills with a second draw should not also be part of a
289 // multi-step renderer (to keep reasoning simple) and must use the GREATER depth test.
290 SkASSERT(!this->useNonAAInnerFill() ||
291 (fStepCount == 1 && fSteps[0]->depthStencilSettings().fDepthTestEnabled &&
292 fSteps[0]->depthStencilSettings().fDepthCompareOp == CompareOp::kGreater));
293 }
294
295 // For RendererProvider to manage initialization; it will never expose a Renderer that is only
296 // default-initialized and not replaced because it's algorithm is disabled by caps/options.
297 Renderer() : fSteps(), fName(""), fStepCount(0) {}
298 Renderer& operator=(Renderer&&) = default;
299
300 std::array<const RenderStep*, kMaxRenderSteps> fSteps;
301 std::string fName;
302 DrawTypeFlags fDrawTypes = DrawTypeFlags::kNone;
303 int fStepCount;
304
305 SkEnumBitMask<StepFlags> fStepFlags = StepFlags::kNone;
306 SkEnumBitMask<DepthStencilFlags> fDepthStencilFlags = DepthStencilFlags::kNone;
307 };
308
309 } // namespace skgpu::graphite
310
311 #endif // skgpu_graphite_Renderer_DEFINED
312