Debian Codegraph @

src/gpu/graphite/Renderer.h

raw
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/SkPathTypes.h"
12 #include "include/core/SkSpan.h"
13 #include "include/core/SkString.h"
14 #include "include/core/SkTypes.h"
15 #include "include/gpu/graphite/GraphiteTypes.h"
16 #include "src/base/SkEnumBitMask.h"
17 #include "src/base/SkVx.h"
18 #include "src/gpu/graphite/Attribute.h"
19 #include "src/gpu/graphite/DrawTypes.h"
20 #include "src/gpu/graphite/ResourceTypes.h"
21 #include "src/gpu/graphite/Uniform.h"
22
23 #include <array>
24 #include <initializer_list>
25 #include <optional>
26 #include <string>
27 #include <string_view>
28 #include <vector>
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 class UniformOffsetCalculator;
42
43 struct ResourceBindingRequirements;
44
45 enum class Coverage { kNone, kSingleChannel, kLCD };
46
47 // If this list is modified in any way, please increment the
48 // RenderStep::kRenderStepIDVersion value. The enum values generated from this
49 // list are serialized and the kRenderStepIDVersion value is the signal to
50 // abandon older serialized data.
51 #define SKGPU_RENDERSTEP_TYPES(M1, M2) \
52 M1(Invalid) \
53 M1(CircularArc) \
54 M1(AnalyticRRect) \
55 M1(AnalyticBlur) \
56 M1(PerEdgeAAQuad) \
57 M2(CoverBounds, NonAAFill) \
58 M2(CoverBounds, RegularCover) \
59 M2(CoverBounds, InverseCover) \
60 M1(CoverageMask) \
61 M2(BitmapText, Mask) \
62 M2(BitmapText, LCD) \
63 M2(BitmapText, Color) \
64 M2(MiddleOutFan, EvenOdd) \
65 M2(MiddleOutFan, Winding) \
66 M1(SDFTextLCD) \
67 M1(SDFText) \
68 M2(TessellateCurves, EvenOdd) \
69 M2(TessellateCurves, Winding) \
70 M1(TessellateStrokes) \
71 M2(TessellateWedges, Convex) \
72 M2(TessellateWedges, EvenOdd) \
73 M2(TessellateWedges, Winding) \
74 M2(Vertices, Tris) \
75 M2(Vertices, TrisColor) \
76 M2(Vertices, TrisTexCoords) \
77 M2(Vertices, TrisColorTexCoords) \
78 M2(Vertices, Tristrips) \
79 M2(Vertices, TristripsColor) \
80 M2(Vertices, TristripsTexCoords) \
81 M2(Vertices, TristripsColorTexCoords)
82
83 /**
84 * The actual technique for rasterizing a high-level draw recorded in a DrawList is handled by a
85 * specific Renderer. Each technique has an associated singleton Renderer that decomposes the
86 * technique into a series of RenderSteps that must be executed in the specified order for the draw.
87 * However, the RenderStep executions for multiple draws can be re-arranged so batches of each
88 * step can be performed in a larger GPU operation. This re-arranging relies on accurate
89 * determination of the DisjointStencilIndex for each draw so that stencil steps are not corrupted
90 * by another draw before its cover step is executed. It also relies on the CompressedPaintersOrder
91 * for each draw to ensure steps are not re-arranged in a way that violates the original draw order.
92 *
93 * Renderer itself is non-virtual since it simply has to point to a list of RenderSteps. RenderSteps
94 * on the other hand are virtual implement the technique specific functionality. It is entirely
95 * possible for certain types of steps, e.g. a bounding box cover, to be re-used across different
96 * Renderers even if the preceeding steps were different.
97 *
98 * All Renderers are accessed through the SharedContext's RendererProvider.
99 */
100 /**
101 * Each RenderStep may have "Static" data and/or "Append" data. Each type of data has associated
102 * attributes, strides, and layouts (see fStaticAttrs, fAppendAttrs, etc.), and resides on a
103 * specific binding on the GPU. This minimizes the number of bindings during a draw pass.
104 * - Static data is information that is fixed in count, does not change between calls of the same
105 * RenderStep, and known after recieving device capabilities. Consequently, it is uploaded ONCE by
106 * the StaticBufferManager prior to any drawPasses, and is initialized during the constructor of a
107 * RenderStep. Currently, static data can be either Indices or Vertices.
108 * - Append data might not be fixed in count and its' usage is not known prior to the draw pass.
109 * Instead, it is uploaded as needed during drawPass through the overload of the writeVertices()
110 * function. Currently, either Vertices or Instances can be appended, and this can be queried by
111 * getRenderStateFlags().
112 */
113 class RenderStep {
114 public:
115 virtual ~RenderStep() = default;
116
117 // Returns an empty result if no state change is necessary, otherwise returns the scissor rect
118 // that should be active for all draws recorded by a subsequent call to writeVertices().
119 std::optional<SkIRect> getScissor(const DrawParams&,
120 SkIRect currentScissor,
121 SkIRect deviceBounds) const;
122
123 // The DrawWriter is configured with the vertex and instance strides of the RenderStep, and its
124 // primitive type. The recorded draws will be executed with a graphics pipeline compatible with
125 // this RenderStep.
126 virtual void writeVertices(DrawWriter*, const DrawParams&, uint32_t ssboIndex) const = 0;
127
128 // Write out the uniform values (aligned for the layout), textures, and samplers. The uniform
129 // values will be de-duplicated across all draws using the RenderStep before uploading to the
130 // GPU, but it can be assumed the uniforms will be bound before the draws recorded in
131 // 'writeVertices' are executed.
132 virtual void writeUniformsAndTextures(const DrawParams&, PipelineDataGatherer*) const = 0;
133
134 // Returns the body of a vertex function, which must define a float4 devPosition variable and
135 // must write to an already-defined float2 stepLocalCoords variable. This will be automatically
136 // set to a varying for the fragment shader if the paint requires local coords. This SkSL has
137 // access to the variables declared by vertexAttributes(), instanceAttributes(), and uniforms().
138 // The 'devPosition' variable's z must store the PaintDepth normalized to a float from [0, 1],
139 // for each processed draw although the RenderStep can choose to upload it in any manner.
140 //
141 // NOTE: The above contract is mainly so that the entire SkSL program can be created by just str
142 // concatenating struct definitions generated from the RenderStep and paint Combination
143 // and then including the function bodies returned here.
144 virtual std::string vertexSkSL() const = 0;
145
146 // Emits code to set up textures and samplers. Should only be defined if hasTextures is true.
147 virtual std::string texturesAndSamplersSkSL(const ResourceBindingRequirements&,
148 int* nextBindingIndex) const {
149 return "";
150 }
151
152 // Emits code to set up coverage value. Should only be defined if overridesCoverage is true.
153 // When implemented the returned SkSL fragment should write its coverage into a
154 // 'half4 outputCoverage' variable (defined in the calling code) with the actual
155 // coverage splatted out into all four channels.
156 virtual const char* fragmentCoverageSkSL() const { return ""; }
157
158 // Emits code to set up a primitive color value. Should only be defined if emitsPrimitiveColor
159 // is true. When implemented, the returned SkSL fragment should write its color into a
160 // 'half4 primitiveColor' variable (defined in the calling code).
161 virtual const char* fragmentColorSkSL() const { return ""; }
162
163 // Indicates whether this RenderStep's uniforms are referenced in its fragment shader code.
164 // If not, its uniforms can be omitted from the fragment shader entirely.
165 // By default, we assume that RenderSteps use their uniforms for emitting coverage or primitive
166 // colors.
167 virtual bool usesUniformsInFragmentSkSL() const {
168 return this->coverage() != Coverage::kNone || this->emitsPrimitiveColor();
169 }
170
171 // Returns a name formatted as "Subclass[variant]", where "Subclass" matches the C++ class name
172 // and variant is a unique term describing instance's specific configuration.
173 const char* name() const { return RenderStepName(fRenderStepID); }
174
175 bool requiresMSAA() const { return SkToBool(fFlags & Flags::kRequiresMSAA); }
176 bool performsShading() const { return SkToBool(fFlags & Flags::kPerformsShading); }
177 bool hasTextures() const { return SkToBool(fFlags & Flags::kHasTextures); }
178 bool emitsPrimitiveColor() const { return SkToBool(fFlags & Flags::kEmitsPrimitiveColor); }
179 bool outsetBoundsForAA() const { return SkToBool(fFlags & Flags::kOutsetBoundsForAA); }
180 bool useNonAAInnerFill() const { return SkToBool(fFlags & Flags::kUseNonAAInnerFill); }
181 bool appendsVertices() const { return SkToBool(fFlags & Flags::kAppendVertices); }
182 SkEnumBitMask<RenderStateFlags> getRenderStateFlags() const {
183 SkEnumBitMask<RenderStateFlags> rs = RenderStateFlags::kNone;
184 if (fFlags & Flags::kFixed) { rs |= RenderStateFlags::kFixed; }
185 if (fFlags & Flags::kAppendVertices) { rs |= RenderStateFlags::kAppendVertices; }
186 if (fFlags & Flags::kAppendInstances) { rs |= RenderStateFlags::kAppendInstances; }
187 if (fFlags & Flags::kAppendDynamicInstances) {
188 rs |= RenderStateFlags::kAppendDynamicInstances;
189 }
190 return rs;
191 }
192
193 Coverage coverage() const { return RenderStep::GetCoverage(fFlags); }
194
195 PrimitiveType primitiveType() const { return fPrimitiveType; }
196 size_t staticDataStride() const { return fStaticDataStride; }
197 size_t appendDataStride() const { return fAppendDataStride; }
198
199 size_t numUniforms() const { return fUniforms.size(); }
200 int uniformAlignment() const { return fUniformAlignment; }
201 size_t numStaticAttributes() const { return fStaticAttrs.size(); }
202 size_t numAppendAttributes() const { return fAppendAttrs.size(); }
203
204 // Name of an attribute containing both the render step and shading SSBO index, if used.
205 static const char* ssboIndexAttribute() { return "ssboIndex"; }
206
207 // Name of a varying to pass the SSBO index to fragment shader
208 static const char* ssboIndexVarying() { return "ssboIndexVar"; }
209
210 // The uniforms of a RenderStep are bound to the kRenderStep slot, the rest of the pipeline
211 // may still use uniforms bound to other slots.
212 SkSpan<const Uniform> uniforms() const { return SkSpan(fUniforms); }
213 SkSpan<const Attribute> staticAttributes() const { return SkSpan(fStaticAttrs); }
214 SkSpan<const Attribute> appendAttributes() const { return SkSpan(fAppendAttrs); }
215 SkSpan<const Varying> varyings() const { return SkSpan(fVaryings); }
216
217 const DepthStencilSettings& depthStencilSettings() const { return fDepthStencilSettings; }
218
219 SkEnumBitMask<DepthStencilFlags> depthStencilFlags() const {
220 return (fDepthStencilSettings.fStencilTestEnabled
221 ? DepthStencilFlags::kStencil : DepthStencilFlags::kNone) |
222 (fDepthStencilSettings.fDepthTestEnabled || fDepthStencilSettings.fDepthWriteEnabled
223 ? DepthStencilFlags::kDepth : DepthStencilFlags::kNone);
224 }
225
226 static const int kRenderStepIDVersion = 1;
227
228 #define ENUM1(BaseName) k##BaseName,
229 #define ENUM2(BaseName, VariantName) k##BaseName##_##VariantName,
230 enum class RenderStepID : uint32_t {
231 SKGPU_RENDERSTEP_TYPES(ENUM1, ENUM2)
232
233 kLast = kVertices_TristripsColorTexCoords,
234 };
235 #undef ENUM1
236 #undef ENUM2
237 static const int kNumRenderSteps = static_cast<int>(RenderStepID::kLast) + 1;
238
239 RenderStepID renderStepID() const { return fRenderStepID; }
240
241 static const char* RenderStepName(RenderStepID);
242 static bool IsValidRenderStepID(uint32_t);
243
244 // TODO: Actual API to do things
245 // 6. Some Renderers benefit from being able to share vertices between RenderSteps. Must find a
246 // way to support that. It may mean that RenderSteps get state per draw.
247 // - Does Renderer make RenderStepFactories that create steps for each DrawList::Draw?
248 // - Does DrawList->DrawPass conversion build a separate array of blind data that the
249 // stateless Renderstep can refer to for {draw,step} pairs?
250 // - Does each DrawList::Draw have extra space (e.g. 8 bytes) that steps can cache data in?
251 protected:
252 enum class Flags : unsigned {
253 kNone = 0x0000,
254 kFixed = 0x0001, // Uses explicit DrawWriter::draw functions
255 kAppendVertices = 0x0002, // Appends vertices
256 kAppendInstances = 0x0004, // Appends instances with static vertex count
257 kAppendDynamicInstances = 0x0008, // Appends instances with a flexible vertex count
258 kRequiresMSAA = 0x0010, // MSAA is required for anti-aliasing
259 kPerformsShading = 0x0020, // This step is responsible for shading/color output
260 kHasTextures = 0x0040, // Adds textures via overridden texturesAndSamplersSkSL()
261 kEmitsCoverage = 0x0080, // Adds analytic coverage via fragmentCoverageSkSL()
262 kLCDCoverage = 0x0100, // The added analytic coverage is LCD, not single channel
263 kEmitsPrimitiveColor = 0x0200, // Injects primitive color via fragmentColorSkSL()
264 kOutsetBoundsForAA = 0x0400, // Drawn geometry will be outset beyond shape's bounds for AA
265 kUseNonAAInnerFill = 0x0800, // Opt into Device recording extra inner fill draws
266 kIgnoreInverseFill = 0x1000, // Rasterization treats all shapes as non-inverted for scissor
267 kInverseFillsScissor = 0x2000, // Rasterization of inverse fills scissor geometrically
268 };
269 SK_DECL_BITMASK_OPS_FRIENDS(Flags)
270
271 // While RenderStep does not define the full program that's run for a draw, it defines the
272 // entire vertex layout of the pipeline. This is not allowed to change, so can be provided to
273 // the RenderStep constructor by subclasses.
274 RenderStep(Layout layout,
275 RenderStepID renderStepID,
276 SkEnumBitMask<Flags> flags,
277 std::initializer_list<Uniform> uniforms,
278 PrimitiveType primitiveType,
279 DepthStencilSettings depthStencilSettings,
280 SkSpan<const Attribute> staticAttrs,
281 SkSpan<const Attribute> appendAttrs,
282 SkSpan<const Varying> varyings = {});
283
284 private:
285 friend class Renderer; // for Flags
286
287 // Cannot copy or move
288 RenderStep(const RenderStep&) = delete;
289 RenderStep(RenderStep&&) = delete;
290
291 static Coverage GetCoverage(SkEnumBitMask<Flags>);
292
293 RenderStepID fRenderStepID;
294 SkEnumBitMask<Flags> fFlags;
295 PrimitiveType fPrimitiveType;
296
297 DepthStencilSettings fDepthStencilSettings;
298
299 // TODO: When we always use C++17 for builds, we should be able to just let subclasses declare
300 // constexpr arrays and point to those, but we need explicit storage for C++14.
301 // Alternatively, if we imposed a max attr count, similar to Renderer's num render steps, we
302 // could just have this be std::array and keep all attributes inline with the RenderStep memory.
303 // On the other hand, the attributes are only needed when creating a new pipeline so it's not
304 // that performance sensitive.
305 std::vector<Uniform> fUniforms;
306 std::vector<Attribute> fStaticAttrs;
307 std::vector<Attribute> fAppendAttrs;
308 std::vector<Varying> fVaryings;
309
310 int fUniformAlignment; // derived from the renderstep uniforms
311 size_t fStaticDataStride; // derived from vertex attribute set
312 size_t fAppendDataStride; // derived from instance attribute set
313 };
314 SK_MAKE_BITMASK_OPS(RenderStep::Flags)
315
316 class Renderer {
317 using StepFlags = RenderStep::Flags;
318 public:
319 // The maximum number of render steps that any Renderer is allowed to have.
320 static constexpr int kMaxRenderSteps = 4;
321
322 const RenderStep& step(int i) const {
323 SkASSERT(i >= 0 && i < fStepCount);
324 return *fSteps[i];
325 }
326 SkSpan<const RenderStep* const> steps() const {
327 SkASSERT(fStepCount > 0); // steps() should only be called on valid Renderers.
328 return {fSteps.data(), static_cast<size_t>(fStepCount) };
329 }
330
331 const char* name() const { return fName.c_str(); }
332 DrawTypeFlags drawTypes() const { return fDrawTypes; }
333 int numRenderSteps() const { return fStepCount; }
334
335 bool requiresMSAA() const {
336 return SkToBool(fStepFlags & StepFlags::kRequiresMSAA);
337 }
338 bool emitsPrimitiveColor() const {
339 return SkToBool(fStepFlags & StepFlags::kEmitsPrimitiveColor);
340 }
341 bool outsetBoundsForAA() const {
342 return SkToBool(fStepFlags & StepFlags::kOutsetBoundsForAA);
343 }
344 bool useNonAAInnerFill() const {
345 return SkToBool(fStepFlags & StepFlags::kUseNonAAInnerFill);
346 }
347
348 SkEnumBitMask<DepthStencilFlags> depthStencilFlags() const { return fDepthStencilFlags; }
349
350 Coverage coverage() const { return RenderStep::GetCoverage(fStepFlags); }
351
352 private:
353 friend class RendererProvider; // for ctors
354
355 // Max render steps is 4, so just spell the options out for now...
356 Renderer(std::string_view name, DrawTypeFlags drawTypes, const RenderStep* s1)
357 : Renderer(name, drawTypes, std::array<const RenderStep*, 1>{s1}) {}
358
359 Renderer(std::string_view name, DrawTypeFlags drawTypes,
360 const RenderStep* s1, const RenderStep* s2)
361 : Renderer(name, drawTypes, std::array<const RenderStep*, 2>{s1, s2}) {}
362
363 Renderer(std::string_view name, DrawTypeFlags drawTypes,
364 const RenderStep* s1, const RenderStep* s2, const RenderStep* s3)
365 : Renderer(name, drawTypes, std::array<const RenderStep*, 3>{s1, s2, s3}) {}
366
367 Renderer(std::string_view name, DrawTypeFlags drawTypes,
368 const RenderStep* s1, const RenderStep* s2, const RenderStep* s3, const RenderStep* s4)
369 : Renderer(name, drawTypes, std::array<const RenderStep*, 4>{s1, s2, s3, s4}) {}
370
371 template<size_t N>
372 Renderer(std::string_view name, DrawTypeFlags drawTypes, std::array<const RenderStep*, N> steps)
373 : fName(name)
374 , fDrawTypes(drawTypes)
375 , fStepCount(SkTo<int>(N)) {
376 static_assert(N <= kMaxRenderSteps);
377 for (int i = 0 ; i < fStepCount; ++i) {
378 fSteps[i] = steps[i];
379 fStepFlags |= fSteps[i]->fFlags;
380 fDepthStencilFlags |= fSteps[i]->depthStencilFlags();
381 }
382 // At least one step needs to actually shade.
383 SkASSERT(fStepFlags & RenderStep::Flags::kPerformsShading);
384 // A render step using non-AA inner fills with a second draw should not also be part of a
385 // multi-step renderer (to keep reasoning simple) and must use the LESS depth test.
386 SkASSERT(!this->useNonAAInnerFill() ||
387 (fStepCount == 1 && fSteps[0]->depthStencilSettings().fDepthTestEnabled &&
388 fSteps[0]->depthStencilSettings().fDepthCompareOp == CompareOp::kLess));
389 }
390
391 // For RendererProvider to manage initialization; it will never expose a Renderer that is only
392 // default-initialized and not replaced because it's algorithm is disabled by caps/options.
393 Renderer() : fSteps(), fName(""), fStepCount(0) {}
394 Renderer& operator=(Renderer&&) = default;
395
396 std::array<const RenderStep*, kMaxRenderSteps> fSteps;
397 std::string fName;
398 DrawTypeFlags fDrawTypes = DrawTypeFlags::kNone;
399 int fStepCount;
400
401 SkEnumBitMask<StepFlags> fStepFlags = StepFlags::kNone;
402 SkEnumBitMask<DepthStencilFlags> fDepthStencilFlags = DepthStencilFlags::kNone;
403 };
404
405 } // namespace skgpu::graphite
406
407 #endif // skgpu_graphite_Renderer_DEFINED