Debian Codegraph @

src/gpu/graphite/ClipStack.h

raw
1 /*
2 * Copyright 2022 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_ClipStack_DEFINED
9 #define skgpu_graphite_ClipStack_DEFINED
10
11 #include "include/core/SkRefCnt.h"
12 #include "include/core/SkShader.h"
13 #include "include/private/base/SkAssert.h"
14 #include "include/private/base/SkTArray.h"
15 #include "src/base/SkTBlockList.h"
16 #include "src/gpu/graphite/DrawOrder.h"
17 #include "src/gpu/graphite/DrawParams.h"
18 #include "src/gpu/graphite/geom/Rect.h"
19 #include "src/gpu/graphite/geom/Shape.h"
20 #include "src/gpu/graphite/geom/Transform.h"
21
22 #include <cstdint>
23
24 class SkStrokeRec;
25 enum class SkClipOp;
26
27 namespace skgpu::graphite {
28
29 class BoundsManager;
30 class Device;
31 class Geometry;
32
33 // TODO: Port over many of the unit tests for skgpu/v1/ClipStack defined in GrClipStackTest since
34 // those tests do a thorough job of enumerating the different element combinations.
35 class ClipStack {
36 public:
37 // TODO: Some of these states reflect what SkDevice requires. Others are based on what Ganesh
38 // could handle analytically. They will likely change as graphite's clips are sorted out
39 enum class ClipState : uint8_t {
40 kEmpty, kWideOpen, kDeviceRect, kDeviceRRect, kComplex
41 };
42
43 // All data describing a geometric modification to the clip
44 struct Element {
45 Shape fShape;
46 Transform fLocalToDevice; // TODO: reference a cached Transform like DrawList?
47 SkClipOp fOp;
48 };
49
50 // 'owningDevice' must outlive the clip stack.
51 ClipStack(Device* owningDevice);
52
53 ~ClipStack();
54
55 ClipStack(const ClipStack&) = delete;
56 ClipStack& operator=(const ClipStack&) = delete;
57
58 ClipState clipState() const { return this->currentSaveRecord().state(); }
59 int maxDeferredClipDraws() const { return fElements.count(); }
60 Rect conservativeBounds() const;
61
62 class ElementIter;
63 // Provides for-range over active, valid clip elements from most recent to oldest.
64 // The iterator provides items as "const Element&".
65 inline ElementIter begin() const;
66 inline ElementIter end() const;
67
68 // Clip stack manipulation
69 void save();
70 void restore();
71
72 // The clip stack does not have a notion of AA vs. non-AA. However, if PixelSnapping::kYes is
73 // used and the right conditions are met, it can adjust the clip geometry to align with the
74 // pixel grid and emulate some aspects of non-AA behavior.
75 enum class PixelSnapping : bool {
76 kNo = false,
77 kYes = true
78 };
79 void clipShape(const Transform& localToDevice, const Shape& shape, SkClipOp op,
80 PixelSnapping = PixelSnapping::kNo);
81 void clipShader(sk_sp<SkShader> shader);
82
83 // Compute the bounds and the effective elements of the clip stack when applied to the draw
84 // described by the provided transform, shape, and stroke.
85 //
86 // Applying clips to a draw is a mostly lazy operation except for what is returned:
87 // - The Clip's scissor is set to 'conservativeBounds()'.
88 // - The Clip stores the draw's clipped bounds, taking into account its transform, styling, and
89 // the above scissor.
90 // - The Clip also stores the draw's fill-style invariant clipped bounds which is used in atlas
91 // draws and may differ from the draw bounds.
92 // - The Clip may contain an analytic clip (geometry or texture mask) that must be included in
93 // the draw's PaintParams.
94 // - The draw's Geometry may be intersected geometrically with clip elements, potentially
95 // impacting the final choice of Renderer.
96 //
97 // All remaining clip elements that affect the draw will be returned in `outEffectiveElements`.
98 // The per-clip element state has to be explicitly updated by calling `updateClipStateForDraw()`
99 // which prepares the clip stack for later rendering.
100 using ElementList = skia_private::STArray<4, const Element*>;
101 Clip visitClipStackForDraw(const Transform&,
102 Geometry*,
103 const SkStrokeRec&,
104 ElementList* outEffectiveElements) const;
105
106 // Update the per-clip element state for later rendering using pre-computed clip state data for
107 // a particular draw. The provided 'z' value is the depth value that the draw will use if it's
108 // not clipped out entirely.
109 //
110 // The returned CompressedPaintersOrder is the largest order that will be used by any of the
111 // clip elements that affect the draw.
112 //
113 // If the provided `clipState` indicates that the draw will be clipped out, then this method has
114 // no effect and returns DrawOrder::kNoIntersection.
115 CompressedPaintersOrder updateClipStateForDraw(const Clip& clip,
116 const ElementList& effectiveElements,
117 const BoundsManager*,
118 PaintersDepth z);
119
120 void recordDeferredClipDraws();
121
122 private:
123 // SaveRecords and Elements are stored in two parallel stacks. The top-most SaveRecord is the
124 // active record, older records represent earlier save points and aren't modified until they
125 // become active again. Elements may be owned by the active SaveRecord, in which case they are
126 // fully mutable, or they may be owned by a prior SaveRecord. However, Elements from both the
127 // active SaveRecord and older records can be valid and affect draw operations. Elements are
128 // marked inactive when new elements are determined to supersede their effect completely.
129 // Inactive elements of the active SaveRecord can be deleted immediately; inactive elements of
130 // older SaveRecords may become active again as the save stack is popped back.
131 //
132 // See go/grclipstack-2.0 for additional details and visualization of the data structures.
133 class SaveRecord;
134
135 // Internally, a lot of clip reasoning is based on an op, outer bounds, and whether a shape
136 // contains another (possibly just conservatively based on inner/outer device-space bounds).
137 // Element and SaveRecord store this information directly. A regular draw is equivalent to a
138 // clip element with the intersection op; an inverse-filled draw is the difference op.
139 //
140 // TransformedShape is a lightweight wrapper that can convert these different types into a
141 // common type that Simplify() can reason about.
142 struct TransformedShape;
143 class DrawShape;
144
145 // This captures which of the two elements in (A op B) would be required when they are combined,
146 // where op is intersect or difference.
147 enum class SimplifyResult {
148 kEmpty,
149 kAOnly,
150 kBOnly,
151 kBoth
152 };
153 static SimplifyResult Simplify(const TransformedShape& a, const TransformedShape& b);
154
155 // Returns how this element affects the draw after more detailed analysis.
156 enum class DrawInfluence {
157 kClipsOutDraw, // The element causes the draw shape to be entirely clipped out
158 kReplacesDraw, // The element is fully covered, so the draw's shape can be ignored
159 kNone, // The element does not affect the draw
160 kComplexInteraction, // The element affects the draw shape in a complex way
161 };
162 static DrawInfluence SimplifyForDraw(const TransformedShape& clip,
163 const TransformedShape& draw);
164
165 // Wraps the geometric Element data with logic for containment and bounds testing.
166 class RawElement : public Element {
167 public:
168 using Stack = SkTBlockList<RawElement, 1>;
169
170 RawElement(const Rect& deviceBounds,
171 const Transform& localToDevice,
172 const Shape& shape,
173 SkClipOp op,
174 PixelSnapping);
175
176 ~RawElement() {
177 // A pending draw means the element affects something already recorded, so its own
178 // shape needs to be recorded as a draw. Since recording requires the Device (and
179 // DrawContext), it must happen before we destroy the element itself.
180 SkASSERT(!this->hasPendingDraw());
181 }
182
183 // Silence warnings about implicit copy ctor/assignment because we're declaring a dtor
184 RawElement(const RawElement&) = default;
185 RawElement& operator=(const RawElement&) = default;
186
187 operator TransformedShape() const;
188
189 bool hasPendingDraw() const { return fOrder != DrawOrder::kNoIntersection; }
190 const Shape& shape() const { return fShape; }
191 const Transform& localToDevice() const { return fLocalToDevice; }
192 const Rect& outerBounds() const { return fOuterBounds; }
193 const Rect& innerBounds() const { return fInnerBounds; }
194 SkClipOp op() const { return fOp; }
195 ClipState clipType() const;
196
197 // As new elements are pushed on to the stack, they may make older elements redundant.
198 // The old elements are marked invalid so they are skipped during clip application, but may
199 // become active again when a save record is restored.
200 bool isInvalid() const { return fInvalidatedByIndex >= 0; }
201 void markInvalid(const SaveRecord& current);
202 void restoreValid(const SaveRecord& current);
203
204 // 'added' represents a new op added to the element stack. Its combination with this element
205 // can result in a number of possibilities:
206 // 1. The entire clip is empty (signaled by both this and 'added' being invalidated).
207 // 2. The 'added' op supercedes this element (this element is invalidated).
208 // 3. This op supercedes the 'added' element (the added element is marked invalidated).
209 // 4. Their combination can be represented by a single new op (in which case this
210 // element should be invalidated, and the combined shape stored in 'added').
211 // 5. Or both elements remain needed to describe the clip (both are valid and unchanged).
212 //
213 // The calling element will only modify its invalidation index since it could belong
214 // to part of the inactive stack (that might be restored later). All merged state/geometry
215 // is handled by modifying 'added'.
216 void updateForElement(RawElement* added, const SaveRecord& current);
217
218 DrawInfluence testForDraw(const TransformedShape& draw) const;
219
220 // Updates usage tracking to incorporate the bounds and Z value for the new draw call.
221 // If this element hasn't affected any prior draws, it will use the bounds manager to
222 // assign itself a compressed painters order for later rendering.
223 //
224 // This method assumes that this element affects the draw in a complex way, such that
225 // calling `testForDraw()` on the same draw would return `DrawInfluence::kIntersect`. It is
226 // assumed that `testForDraw()` was called beforehand to ensure that this is the case.
227 //
228 // Assuming that this element does not clip out the draw, returns the painters order the
229 // draw must sort after.
230 CompressedPaintersOrder updateForDraw(const BoundsManager* boundsManager,
231 const Rect& deviceBounds,
232 const Rect& drawBounds,
233 PaintersDepth drawZ);
234
235 // Record a depth-only draw to the given device, restricted to the portion of the clip that
236 // is actually required based on prior recorded draws. Resets usage tracking for subsequent
237 // passes.
238 void drawClip(Device*);
239
240 void validate() const;
241
242 private:
243 // TODO: Should only combine elements within the same save record, that don't have pending
244 // draws already. Otherwise, we're changing the geometry that will be rasterized and it
245 // could lead to gaps even if in a perfect the world the analytically intersected shape was
246 // equivalent. Can't combine with other save records, since they *might* become pending
247 // later on.
248 bool combine(const RawElement& other, const SaveRecord& current);
249
250 // Device space bounds. These bounds are not snapped to pixels with the assumption that if
251 // a relation (intersects, contains, etc.) is true for the bounds it will be true for the
252 // rasterization of the coordinates that produced those bounds.
253 Rect fInnerBounds;
254 Rect fOuterBounds;
255 // TODO: Convert fOuterBounds to a ComplementRect to make intersection tests faster?
256 // Would need to store both original and complement, since the intersection test is
257 // Rect + ComplementRect and Element/SaveRecord could be on either side of operation.
258
259 // State tracking how this clip element needs to be recorded into the draw context. As the
260 // clip stack is applied to additional draws, the clip's Z and usage bounds grow to account
261 // for it; its compressed painter's order is selected the first time a draw is affected.
262 Rect fUsageBounds;
263 CompressedPaintersOrder fOrder;
264 PaintersDepth fMaxZ;
265
266 // Elements are invalidated by SaveRecords as the record is updated with new elements that
267 // override old geometry. An invalidated element stores the index of the first element of
268 // the save record that invalidated it. This makes it easy to undo when the save record is
269 // popped from the stack, and is stable as the current save record is modified.
270 int fInvalidatedByIndex;
271 };
272
273 // Represents a saved point in the clip stack, and manages the life time of elements added to
274 // stack within the record's life time. Also provides the logic for determining active elements
275 // given a draw query.
276 class SaveRecord {
277 public:
278 using Stack = SkTBlockList<SaveRecord, 2>;
279
280 explicit SaveRecord(const Rect& deviceBounds);
281
282 SaveRecord(const SaveRecord& prior, int startingElementIndex);
283
284 const SkShader* shader() const { return fShader.get(); }
285 const Rect& outerBounds() const { return fOuterBounds; }
286 const Rect& innerBounds() const { return fInnerBounds; }
287 SkClipOp op() const { return fStackOp; }
288 ClipState state() const;
289 uint32_t genID() const;
290
291 int firstActiveElementIndex() const { return fStartingElementIndex; }
292 int oldestElementIndex() const { return fOldestValidIndex; }
293 bool canBeUpdated() const { return (fDeferredSaveCount == 0); }
294
295 DrawInfluence testForDraw(const TransformedShape& draw) const;
296
297 // Deferred save manipulation
298 void pushSave() {
299 SkASSERT(fDeferredSaveCount >= 0);
300 fDeferredSaveCount++;
301 }
302 // Returns true if the record should stay alive. False means the ClipStack must delete it
303 bool popSave() {
304 fDeferredSaveCount--;
305 SkASSERT(fDeferredSaveCount >= -1);
306 return fDeferredSaveCount >= 0;
307 }
308
309 // Return true if the element was added to 'elements', or otherwise affected the save record
310 // (e.g. turned it empty).
311 bool addElement(RawElement&& toAdd, RawElement::Stack* elements, Device*);
312
313 void addShader(sk_sp<SkShader> shader);
314
315 // Remove the elements owned by this save record, which must happen before the save record
316 // itself is removed from the clip stack. Records draws for any removed elements that have
317 // draw usages.
318 void removeElements(RawElement::Stack* elements, Device*);
319
320 // Restore element validity now that this record is the new top of the stack.
321 void restoreElements(RawElement::Stack* elements);
322
323 private:
324 // These functions modify 'elements' and element-dependent state of the record
325 // (such as valid index and fState). Records draws for any clips that have deferred usages
326 // that are inactivated and cannot be restored (i.e. part of the active save record).
327 bool appendElement(RawElement&& toAdd, RawElement::Stack* elements, Device*);
328 void replaceWithElement(RawElement&& toAdd, RawElement::Stack* elements, Device*);
329
330 // Inner bounds is always contained in outer bounds, or it is empty. All bounds will be
331 // contained in the device bounds.
332 Rect fInnerBounds; // Inside is full coverage (stack op == intersect) or 0 cov (diff)
333 Rect fOuterBounds; // Outside is 0 coverage (op == intersect) or full cov (diff)
334
335 // A save record can have up to one shader, multiple shaders are automatically blended
336 sk_sp<SkShader> fShader;
337
338 const int fStartingElementIndex; // First element owned by this save record
339 int fOldestValidIndex; // Index of oldest element that's valid for this record
340 int fDeferredSaveCount; // Number of save() calls without modifications (yet)
341
342 // Will be kIntersect unless every valid element is kDifference, which is significant
343 // because if kDifference then there is an implicit extra outer bounds at the device edges.
344 SkClipOp fStackOp;
345 ClipState fState;
346 uint32_t fGenID;
347 };
348
349 Rect deviceBounds() const;
350
351 const SaveRecord& currentSaveRecord() const {
352 SkASSERT(!fSaves.empty());
353 return fSaves.back();
354 }
355
356 // Will return the current save record, properly updating deferred saves
357 // and initializing a first record if it were empty.
358 SaveRecord& writableSaveRecord(bool* wasDeferred);
359
360 RawElement::Stack fElements;
361 SaveRecord::Stack fSaves; // always has one wide open record at the top
362
363 Device* fDevice; // the device this clip stack is coupled with
364 };
365
366 // Clip element iteration
367 class ClipStack::ElementIter {
368 public:
369 bool operator!=(const ElementIter& o) const {
370 return o.fItem != fItem && o.fRemaining != fRemaining;
371 }
372
373 const Element& operator*() const { return *fItem; }
374
375 ElementIter& operator++() {
376 // Skip over invalidated elements
377 do {
378 fRemaining--;
379 ++fItem;
380 } while(fRemaining > 0 && (*fItem).isInvalid());
381
382 return *this;
383 }
384
385 ElementIter(RawElement::Stack::CRIter::Item item, int r) : fItem(item), fRemaining(r) {}
386
387 RawElement::Stack::CRIter::Item fItem;
388 int fRemaining;
389
390 friend class ClipStack;
391 };
392
393 ClipStack::ElementIter ClipStack::begin() const {
394 if (this->currentSaveRecord().state() == ClipState::kEmpty ||
395 this->currentSaveRecord().state() == ClipState::kWideOpen) {
396 // No visible clip elements when empty or wide open
397 return this->end();
398 }
399 int count = fElements.count() - this->currentSaveRecord().oldestElementIndex();
400 return ElementIter(fElements.ritems().begin(), count);
401 }
402
403 ClipStack::ElementIter ClipStack::end() const {
404 return ElementIter(fElements.ritems().end(), 0);
405 }
406
407 } // namespace skgpu::graphite
408
409 #endif // skgpu_graphite_ClipStack_DEFINED