Debian Codegraph @

src/gpu/BufferWriter.h

raw
1 /*
2 * Copyright 2010 Google Inc.
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_BufferWriter_DEFINED
9 #define skgpu_BufferWriter_DEFINED
10
11 #include "include/core/SkImageInfo.h"
12 #include "include/core/SkRect.h"
13 #include "include/private/base/SkAssert.h"
14 #include "include/private/base/SkDebug.h"
15 #include "include/private/base/SkTemplates.h"
16 #include "include/private/base/SkTo.h"
17 #include "src/base/SkRectMemcpy.h"
18 #include "src/core/SkColorData.h"
19 #include "src/core/SkConvertPixels.h"
20
21 #include <array>
22 #include <cstddef>
23 #include <cstdint>
24 #include <cstring>
25 #include <type_traits>
26 #include <utility>
27
28 namespace skgpu {
29
30 namespace graphite {
31 class VelloRenderer;
32 }
33
34 struct BufferWriter {
35 public:
36 // Marks a read-only position in the underlying buffer
37 struct Mark {
38 public:
39 Mark() : Mark(nullptr) {}
40 Mark(void* ptr, size_t offset = 0)
41 : fMark(reinterpret_cast<uintptr_t>(ptr) + offset) {
42 SkASSERT(ptr || offset == 0);
43 }
44
45 bool operator< (const Mark& o) const { return fMark < o.fMark; }
46 bool operator<=(const Mark& o) const { return fMark <= o.fMark; }
47 bool operator==(const Mark& o) const { return fMark == o.fMark; }
48 bool operator!=(const Mark& o) const { return fMark != o.fMark; }
49 bool operator>=(const Mark& o) const { return fMark >= o.fMark; }
50 bool operator> (const Mark& o) const { return fMark > o.fMark; }
51
52 ptrdiff_t operator-(const Mark& o) const { return fMark - o.fMark; }
53
54 explicit operator bool() const { return *this != Mark(); }
55 private:
56 uintptr_t fMark;
57 };
58
59 BufferWriter() = default;
60 BufferWriter(BufferWriter&& w) { *this = std::move(w); }
61
62 BufferWriter(void* ptr, size_t size) : fPtr(ptr) {
63 SkDEBUGCODE(fEnd = Mark(ptr, ptr ? size : 0);)
64 }
65 BufferWriter(void* ptr, Mark end = {}) : fPtr(ptr) {
66 SkDEBUGCODE(fEnd = end;)
67 }
68
69 BufferWriter& operator=(const BufferWriter&) = delete;
70 BufferWriter& operator=(BufferWriter&& that) {
71 fPtr = that.fPtr;
72 that.fPtr = nullptr;
73 SkDEBUGCODE(fEnd = that.fEnd;)
74 SkDEBUGCODE(that.fEnd = Mark();)
75 return *this;
76 }
77
78 explicit operator bool() const { return fPtr != nullptr; }
79
80 Mark mark(size_t offset=0) const {
81 this->validate(offset);
82 return Mark(fPtr, offset);
83 }
84
85 void zeroBytes(size_t bytes) {
86 auto s = this->slice(bytes);
87 memset(s.data(), 0, s.size_bytes());
88 }
89
90 void write(const void* src, size_t bytes) {
91 auto s = this->slice(bytes);
92 memcpy(s.data(), src, s.size_bytes());
93 }
94
95 template <typename T>
96 void write(SkSpan<const T> data) { this->write(data.data(), data.size_bytes()); }
97 template <typename T>
98 void write(T data) { this->write(&data, sizeof(T)); }
99
100 protected:
101 // For integration with Rust, to expose slice() directly
102 friend class skgpu::graphite::VelloRenderer;
103
104 // makeOffset effectively splits the current writer from {fPtr, fEnd} into {fPtr, p} and
105 // a new writer {p, fEnd}. The same data range is accessible, but each byte can only be
106 // set by a single writer. Automatically validates that there is enough bytes remaining in this
107 // writer to do such a split.
108 //
109 // This splitting and validation means that providers of BufferWriters to callers can easily
110 // and correctly track everything in a single BufferWriter field and use
111 // return std::exchange(fCurrWriter, fCurrWriter.makeOffset(requestedBytes));
112 // This exposes the current writer position to the caller and sets the provider's new current
113 // position to be just after the requested bytes.
114 //
115 // Templated so that it can create subclasses directly.
116 template<typename W>
117 W makeOffset(size_t offsetInBytes) const {
118 this->validate(offsetInBytes);
119 void* p = SkTAddOffset<void>(fPtr, offsetInBytes);
120 Mark end{SkDEBUGCODE(fEnd)};
121 SkDEBUGCODE(fEnd = Mark(p);)
122 return W{p, end};
123 }
124
125 // The Writer's pointer is advanced by `bytes` just as though `write()` had been called. The
126 // returned pointer should not be used for reading, and should only write to each index once, in
127 // order, for optimal performance.
128 SkSpan<uint8_t> slice(size_t bytes) {
129 this->validate(bytes);
130 SkSpan<uint8_t> slice{static_cast<uint8_t*>(fPtr), bytes};
131 fPtr = SkTAddOffset<void>(fPtr, bytes);
132 return slice;
133 }
134
135 void validate(size_t bytesToWrite) const {
136 // If the buffer writer had an end marked, make sure we're not crossing it.
137 // Ideally, all creators of BufferWriters mark the end, but a lot of legacy code is not set
138 // up to easily do this.
139 SkASSERT(fPtr || bytesToWrite == 0);
140 SkASSERT(!fEnd || Mark(fPtr, bytesToWrite) <= fEnd);
141 }
142
143 void* fPtr = nullptr;
144 SkDEBUGCODE(mutable Mark fEnd = {};)
145 };
146
147 #define BUFFER_WRITER_OVERLOADS(Writer) \
148 Writer() = default; \
149 Writer(void* ptr, size_t size) : BufferWriter(ptr, size) {} \
150 Writer(void* ptr, Mark end) : BufferWriter(ptr, end) {} \
151 Writer(const Writer&) = delete; \
152 Writer(Writer&& that) { *this = std::move(that); } \
153 Writer(BufferWriter&& that) { *this = std::move(that); } \
154 Writer& operator=(const Writer&) = delete; \
155 Writer& operator=(Writer&& that) { \
156 BufferWriter::operator=(std::move(that)); \
157 return *this; \
158 } \
159 Writer& operator=(BufferWriter&& that) { \
160 BufferWriter::operator=(std::move(that)); \
161 return *this; \
162 } \
163 using BufferWriter::operator bool;
164
165 /**
166 * Helper for writing vertex data to a buffer. Usage:
167 * VertexWriter vertices{target->makeVertexSpace(...)};
168 * vertices << A0 << B0 << C0 << ...;
169 * vertices << A1 << B1 << C1 << ...;
170 *
171 * Each value must be POD (plain old data), or have a specialization of the "<<" operator.
172 */
173 struct VertexWriter : private BufferWriter {
174 inline constexpr static uint32_t kIEEE_32_infinity = 0x7f800000;
175
176 // DEPRECATED: Prefer specifying the size of the buffer being written to as well
177 explicit VertexWriter(void* ptr) : BufferWriter(ptr, Mark()) {}
178
179 BUFFER_WRITER_OVERLOADS(VertexWriter)
180
181 using BufferWriter::mark;
182 using BufferWriter::zeroBytes;
183
184 VertexWriter makeOffset(size_t offsetInBytes) const {
185 return this->BufferWriter::makeOffset<VertexWriter>(offsetInBytes);
186 }
187
188 template <typename T>
189 struct Conditional {
190 bool fCondition;
191 T fValue;
192 };
193
194 template <typename T>
195 static Conditional<T> If(bool condition, const T& value) {
196 return {condition, value};
197 }
198
199 template <typename T>
200 struct Skip {};
201
202 template<typename T>
203 struct ArrayDesc {
204 const T* fArray;
205 int fCount;
206 };
207
208 template <typename T>
209 static ArrayDesc<T> Array(const T* array, int count) {
210 return {array, count};
211 }
212
213 template<int kCount, typename T>
214 struct RepeatDesc {
215 const T& fVal;
216 };
217
218 template <int kCount, typename T>
219 static RepeatDesc<kCount, T> Repeat(const T& val) {
220 return {val};
221 }
222
223 /**
224 * Specialized utilities for writing a four-vertices, with some data being replicated at each
225 * vertex, and other data being the appropriate 2-components from an SkRect to construct a
226 * triangle strip.
227 *
228 * - Four sets of data will be written
229 *
230 * - For any arguments where is_quad<Type>::value is true, a unique point will be written at
231 * each vertex. To make a custom type be emitted as a quad, declare:
232 *
233 * template<> struct VertexWriter::is_quad<MyQuadClass> : std::true_type {};
234 *
235 * and define:
236 *
237 * MyQuadClass::writeVertex(int cornerIdx, VertexWriter&) const { ... }
238 *
239 * - For any arguments where is_quad<Type>::value is false, its value will be replicated at each
240 * vertex.
241 */
242 template <typename T>
243 struct is_quad : std::false_type {};
244
245 template <typename T>
246 struct TriStrip {
247 void writeVertex(int cornerIdx, VertexWriter& w) const {
248 switch (cornerIdx) {
249 case 0: w << l << t; return;
250 case 1: w << l << b; return;
251 case 2: w << r << t; return;
252 case 3: w << r << b; return;
253 }
254 SkUNREACHABLE;
255 }
256 T l, t, r, b;
257 };
258
259 static TriStrip<float> TriStripFromRect(const SkRect& r) {
260 return { r.fLeft, r.fTop, r.fRight, r.fBottom };
261 }
262
263 static TriStrip<uint16_t> TriStripFromUVs(const std::array<uint16_t, 4>& rect) {
264 return { rect[0], rect[1], rect[2], rect[3] };
265 }
266
267 template <typename T>
268 struct TriFan {
269 void writeVertex(int cornerIdx, VertexWriter& w) const {
270 switch (cornerIdx) {
271 case 0: w << l << t; return;
272 case 1: w << l << b; return;
273 case 2: w << r << b; return;
274 case 3: w << r << t; return;
275 }
276 SkUNREACHABLE;
277 }
278 T l, t, r, b;
279 };
280
281 static TriFan<float> TriFanFromRect(const SkRect& r) {
282 return { r.fLeft, r.fTop, r.fRight, r.fBottom };
283 }
284
285 template <typename... Args>
286 void writeQuad(const Args&... remainder) {
287 this->writeQuadVertex<0>(remainder...);
288 this->writeQuadVertex<1>(remainder...);
289 this->writeQuadVertex<2>(remainder...);
290 this->writeQuadVertex<3>(remainder...);
291 }
292
293 private:
294 template <int kCornerIdx, typename T, typename... Args>
295 std::enable_if_t<!is_quad<T>::value, void> writeQuadVertex(const T& val,
296 const Args&... remainder) {
297 *this << val; // Non-quads duplicate their value.
298 this->writeQuadVertex<kCornerIdx>(remainder...);
299 }
300
301 template <int kCornerIdx, typename Q, typename... Args>
302 std::enable_if_t<is_quad<Q>::value, void> writeQuadVertex(const Q& quad,
303 const Args&... remainder) {
304 quad.writeVertex(kCornerIdx, *this); // Quads emit a different corner each time.
305 this->writeQuadVertex<kCornerIdx>(remainder...);
306 }
307
308 template <int kCornerIdx>
309 void writeQuadVertex() {}
310
311 template <typename T>
312 friend VertexWriter& operator<<(VertexWriter&, const T&);
313
314 template <typename T>
315 friend VertexWriter& operator<<(VertexWriter&, const ArrayDesc<T>&);
316 };
317
318 template <typename T>
319 inline VertexWriter& operator<<(VertexWriter& w, const T& val) {
320 static_assert(std::is_trivially_copyable<T>::value, "");
321 w.write(&val, sizeof(T));
322 return w;
323 }
324
325 template <typename T>
326 inline VertexWriter& operator<<(VertexWriter& w, const VertexWriter::Conditional<T>& val) {
327 static_assert(std::is_trivially_copyable<T>::value, "");
328 if (val.fCondition) {
329 w << val.fValue;
330 }
331 return w;
332 }
333
334 template <typename T>
335 inline VertexWriter& operator<<(VertexWriter& w, const VertexWriter::Skip<T>& val) {
336 w = w.makeOffset(sizeof(T));
337 return w;
338 }
339
340 template <typename T>
341 inline VertexWriter& operator<<(VertexWriter& w, const VertexWriter::ArrayDesc<T>& array) {
342 static_assert(std::is_trivially_copyable<T>::value, "");
343 w.write(SkSpan<const T>{array.fArray, (size_t)array.fCount});
344 return w;
345 }
346
347 template <int kCount, typename T>
348 inline VertexWriter& operator<<(VertexWriter& w, const VertexWriter::RepeatDesc<kCount,T>& repeat) {
349 for (int i = 0; i < kCount; ++i) {
350 w << repeat.fVal;
351 }
352 return w;
353 }
354
355 // Allow r-value/temporary writers to be appended to
356 template <typename T>
357 inline VertexWriter& operator<<(VertexWriter&& w, const T& val) { return w << val; }
358
359 template <typename T>
360 struct VertexWriter::is_quad<VertexWriter::TriStrip<T>> : std::true_type {};
361
362 template <typename T>
363 struct VertexWriter::is_quad<VertexWriter::TriFan<T>> : std::true_type {};
364
365 /**
366 * VertexColor is a helper for writing colors to a vertex buffer. It outputs either four bytes or
367 * or four float32 channels, depending on the wideColor parameter. Note that the GP needs to have
368 * been constructed with the correct attribute type for colors, to match the usage here.
369 */
370 class VertexColor {
371 public:
372 VertexColor() = default;
373
374 explicit VertexColor(const SkPMColor4f& color, bool wideColor) {
375 this->set(color, wideColor);
376 }
377
378 void set(const SkPMColor4f& color, bool wideColor) {
379 if (wideColor) {
380 memcpy(fColor, color.vec(), sizeof(fColor));
381 } else {
382 fColor[0] = color.toBytes_RGBA();
383 }
384 fWideColor = wideColor;
385 }
386
387 size_t size() const { return fWideColor ? 16 : 4; }
388
389 private:
390 template <typename T>
391 friend VertexWriter& operator<<(VertexWriter&, const T&);
392
393 uint32_t fColor[4];
394 bool fWideColor;
395 };
396
397 template <>
398 [[maybe_unused]] inline VertexWriter& operator<<(VertexWriter& w, const VertexColor& color) {
399 w << color.fColor[0];
400 if (color.fWideColor) {
401 w << color.fColor[1]
402 << color.fColor[2]
403 << color.fColor[3];
404 }
405 return w;
406 }
407
408 ///////////////////////////////////////////////////////////////////////////////////////////////////
409
410 struct IndexWriter : private BufferWriter {
411 BUFFER_WRITER_OVERLOADS(IndexWriter)
412
413 IndexWriter makeOffset(int numIndices) const {
414 return this->BufferWriter::makeOffset<IndexWriter>(numIndices * sizeof(uint16_t));
415 }
416
417 void writeArray(SkSpan<const uint16_t> indices) {
418 this->write(indices);
419 }
420
421 friend IndexWriter& operator<<(IndexWriter& w, uint16_t val);
422 };
423
424 inline IndexWriter& operator<<(IndexWriter& w, uint16_t val) {
425 w.write(&val, sizeof(uint16_t));
426 return w;
427 }
428
429 inline IndexWriter& operator<<(IndexWriter& w, int val) { return (w << SkTo<uint16_t>(val)); }
430
431 ///////////////////////////////////////////////////////////////////////////////////////////////////
432
433 struct TextureUploadWriter : private BufferWriter {
434 BUFFER_WRITER_OVERLOADS(TextureUploadWriter)
435
436 // TODO(michaelludwig): This API doesn't prevent the underlying buffer from being written
437 // multiple times, which would be nice to do.
438
439 // Writes a block of image data to the upload buffer, starting at `offset`. The source image is
440 // `srcRowBytes` wide, and the written block is `dstRowBytes` wide and `rowCount` bytes tall.
441 void write(size_t offset, const void* src, size_t srcRowBytes, size_t dstRowBytes,
442 size_t trimRowBytes, int rowCount) {
443 this->validate(offset + dstRowBytes * rowCount);
444 void* dst = SkTAddOffset<void>(fPtr, offset);
445 SkRectMemcpy(dst, dstRowBytes, src, srcRowBytes, trimRowBytes, rowCount);
446 }
447
448 void convertAndWrite(size_t offset,
449 const SkImageInfo& srcInfo, const void* src, size_t srcRowBytes,
450 const SkImageInfo& dstInfo, size_t dstRowBytes) {
451 SkASSERT(srcInfo.width() == dstInfo.width() && srcInfo.height() == dstInfo.height());
452 this->validate(offset + dstRowBytes * dstInfo.height());
453 void* dst = SkTAddOffset<void>(fPtr, offset);
454 SkAssertResult(SkConvertPixels(dstInfo, dst, dstRowBytes, srcInfo, src, srcRowBytes));
455 }
456
457 // Writes a block of image data to the upload buffer. It converts src data of RGB_888x
458 // colorType into a 3 channel RGB_888 format.
459 void writeRGBFromRGBx(size_t offset, const void* src, size_t srcRowBytes, size_t dstRowBytes,
460 int rowPixels, int rowCount) {
461 this->validate(offset + dstRowBytes * rowCount);
462 void* dst = SkTAddOffset<void>(fPtr, offset);
463 auto* sRow = reinterpret_cast<const char*>(src);
464 auto* dRow = reinterpret_cast<char*>(dst);
465
466 for (int y = 0; y < rowCount; ++y) {
467 for (int x = 0; x < rowPixels; ++x) {
468 memcpy(dRow + 3*x, sRow+4*x, 3);
469 }
470 sRow += srcRowBytes;
471 dRow += dstRowBytes;
472 }
473 }
474 };
475
476 } // namespace skgpu
477
478 #endif // skgpu_BufferWriter_DEFINED