3 * Copyright 2011 Google Inc.
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
8 #ifndef SkPictureFlat_DEFINED
9 #define SkPictureFlat_DEFINED
11 //#define SK_DEBUG_SIZE
14 #include "SkBitmapHeap.h"
15 #include "SkChecksum.h"
16 #include "SkChunkAlloc.h"
18 #include "SkOrderedReadBuffer.h"
19 #include "SkOrderedWriteBuffer.h"
22 #include "SkPicture.h"
23 #include "SkPtrRecorder.h"
25 #include "SkTDynamicHash.h"
26 #include "SkTRefArray.h"
27 #include "SkTSearch.h"
39 DRAW_BITMAP_RECT_TO_RECT,
48 DRAW_POS_TEXT_TOP_BOTTOM, // fast variant of DRAW_POS_TEXT
50 DRAW_POS_TEXT_H_TOP_BOTTOM, // fast variant of DRAW_POS_TEXT_H
56 DRAW_TEXT_TOP_BOTTOM, // fast variant of DRAW_TEXT
71 LAST_DRAWTYPE_ENUM = END_COMMENT_GROUP
74 // In the 'match' method, this constant will match any flavor of DRAW_BITMAP*
75 static const int kDRAW_BITMAP_FLAVOR = LAST_DRAWTYPE_ENUM+1;
77 enum DrawVertexFlags {
78 DRAW_VERTICES_HAS_TEXS = 0x01,
79 DRAW_VERTICES_HAS_COLORS = 0x02,
80 DRAW_VERTICES_HAS_INDICES = 0x04
83 ///////////////////////////////////////////////////////////////////////////////
84 // clipparams are packed in 5 bits
85 // doAA:1 | regionOp:4
87 static inline uint32_t ClipParams_pack(SkRegion::Op op, bool doAA) {
88 unsigned doAABit = doAA ? 1 : 0;
89 return (doAABit << 4) | op;
92 static inline SkRegion::Op ClipParams_unpackRegionOp(uint32_t packed) {
93 return (SkRegion::Op)(packed & 0xF);
96 static inline bool ClipParams_unpackDoAA(uint32_t packed) {
97 return SkToBool((packed >> 4) & 1);
100 ///////////////////////////////////////////////////////////////////////////////
102 class SkTypefacePlayback {
104 SkTypefacePlayback();
105 virtual ~SkTypefacePlayback();
107 int count() const { return fCount; }
109 void reset(const SkRefCntSet*);
111 void setCount(int count);
112 SkRefCnt* set(int index, SkRefCnt*);
114 void setupBuffer(SkOrderedReadBuffer& buffer) const {
115 buffer.setTypefaceArray((SkTypeface**)fArray, fCount);
123 class SkFactoryPlayback {
125 SkFactoryPlayback(int count) : fCount(count) {
126 fArray = SkNEW_ARRAY(SkFlattenable::Factory, count);
129 ~SkFactoryPlayback() {
130 SkDELETE_ARRAY(fArray);
133 SkFlattenable::Factory* base() const { return fArray; }
135 void setupBuffer(SkOrderedReadBuffer& buffer) const {
136 buffer.setFactoryPlayback(fArray, fCount);
141 SkFlattenable::Factory* fArray;
144 ///////////////////////////////////////////////////////////////////////////////
147 // The following templated classes provide an efficient way to store and compare
148 // objects that have been flattened (i.e. serialized in an ordered binary
151 // SkFlatData: is a simple indexable container for the flattened data
152 // which is agnostic to the type of data is is indexing. It is
153 // also responsible for flattening/unflattening objects but
154 // details of that operation are hidden in the provided procs
155 // SkFlatDictionary: is an abstract templated dictionary that maintains a
156 // searchable set of SkFlatData objects of type T.
157 // SkFlatController: is an interface provided to SkFlatDictionary which handles
158 // allocation (and unallocation in some cases). It also holds
159 // ref count recorders and the like.
161 // NOTE: any class that wishes to be used in conjunction with SkFlatDictionary
162 // must subclass the dictionary and provide the necessary flattening procs.
163 // The end of this header contains dictionary subclasses for some common classes
164 // like SkBitmap, SkMatrix, SkPaint, and SkRegion. SkFlatController must also
165 // be implemented, or SkChunkFlatController can be used to use an
166 // SkChunkAllocator and never do replacements.
169 ///////////////////////////////////////////////////////////////////////////////
173 class SkFlatController : public SkRefCnt {
175 SK_DECLARE_INST_COUNT(SkFlatController)
178 virtual ~SkFlatController();
180 * Return a new block of memory for the SkFlatDictionary to use.
181 * This memory is owned by the controller and has the same lifetime unless you
182 * call unalloc(), in which case it may be freed early.
184 virtual void* allocThrow(size_t bytes) = 0;
187 * Hint that this block, which was allocated with allocThrow, is no longer needed.
188 * The implementation may choose to free this memory any time beteween now and destruction.
190 virtual void unalloc(void* ptr) = 0;
193 * Used during creation and unflattening of SkFlatData objects. If the
194 * objects being flattened contain bitmaps they are stored in this heap
195 * and the flattenable stores the index to the bitmap on the heap.
196 * This should be set by the protected setBitmapHeap.
198 SkBitmapHeap* getBitmapHeap() { return fBitmapHeap; }
201 * Used during creation of SkFlatData objects. If a typeface recorder is
202 * required to flatten the objects being flattened (i.e. for SkPaints), this
203 * should be set by the protected setTypefaceSet.
205 SkRefCntSet* getTypefaceSet() { return fTypefaceSet; }
208 * Used during unflattening of the SkFlatData objects in the
209 * SkFlatDictionary. Needs to be set by the protected setTypefacePlayback
210 * and needs to be reset to the SkRefCntSet passed to setTypefaceSet.
212 SkTypefacePlayback* getTypefacePlayback() { return fTypefacePlayback; }
215 * Optional factory recorder used during creation of SkFlatData objects. Set
216 * using the protected method setNamedFactorySet.
218 SkNamedFactorySet* getNamedFactorySet() { return fFactorySet; }
221 * Flags to use during creation of SkFlatData objects. Defaults to zero.
223 uint32_t getWriteBufferFlags() { return fWriteBufferFlags; }
227 * Set an SkBitmapHeap to be used to store/read SkBitmaps. Ref counted.
229 void setBitmapHeap(SkBitmapHeap*);
232 * Set an SkRefCntSet to be used to store SkTypefaces during flattening. Ref
235 void setTypefaceSet(SkRefCntSet*);
238 * Set an SkTypefacePlayback to be used to find references to SkTypefaces
239 * during unflattening. Should be reset to the set provided to
242 void setTypefacePlayback(SkTypefacePlayback*);
245 * Set an SkNamedFactorySet to be used to store Factorys and their
246 * corresponding names during flattening. Ref counted. Returns the same
247 * set as a convenience.
249 SkNamedFactorySet* setNamedFactorySet(SkNamedFactorySet*);
252 * Set the flags to be used during flattening.
254 void setWriteBufferFlags(uint32_t flags) { fWriteBufferFlags = flags; }
257 SkBitmapHeap* fBitmapHeap;
258 SkRefCntSet* fTypefaceSet;
259 SkTypefacePlayback* fTypefacePlayback;
260 SkNamedFactorySet* fFactorySet;
261 uint32_t fWriteBufferFlags;
263 typedef SkRefCnt INHERITED;
268 // Flatten obj into an SkFlatData with this index. controller owns the SkFlatData*.
269 static SkFlatData* Create(SkFlatController* controller,
272 void (*flattenProc)(SkOrderedWriteBuffer&, const void*));
274 // Unflatten this into result, using bitmapHeap and facePlayback for bitmaps and fonts if given.
275 void unflatten(void* result,
276 void (*unflattenProc)(SkOrderedReadBuffer&, void*),
277 SkBitmapHeap* bitmapHeap = NULL,
278 SkTypefacePlayback* facePlayback = NULL) const;
280 // Do these contain the same data? Ignores index() and topBot().
281 bool operator==(const SkFlatData& that) const {
282 if (this->checksum() != that.checksum() || this->flatSize() != that.flatSize()) {
285 return memcmp(this->data(), that.data(), this->flatSize()) == 0;
288 int index() const { return fIndex; }
289 const uint8_t* data() const { return (const uint8_t*)this + sizeof(*this); }
290 size_t flatSize() const { return fFlatSize; }
291 uint32_t checksum() const { return fChecksum; }
293 // Returns true if fTopBot[] has been recorded.
294 bool isTopBotWritten() const {
295 return !SkScalarIsNaN(fTopBot[0]);
298 // Returns fTopBot array, so it can be passed to a routine to compute them.
299 // For efficiency, we assert that fTopBot have not been recorded yet.
300 SkScalar* writableTopBot() const {
301 SkASSERT(!this->isTopBotWritten());
305 // Return the topbot[] after it has been recorded.
306 const SkScalar* topBot() const {
307 SkASSERT(this->isTopBotWritten());
312 // For SkTDynamicHash.
313 static const SkFlatData& Identity(const SkFlatData& flat) { return flat; }
314 static uint32_t Hash(const SkFlatData& flat) { return flat.checksum(); }
315 static bool Equal(const SkFlatData& a, const SkFlatData& b) { return a == b; }
317 void setIndex(int index) { fIndex = index; }
318 uint8_t* data() { return (uint8_t*)this + sizeof(*this); }
320 // This assumes the payload flat data has already been written and does not modify it.
321 void stampHeader(int index, int32_t size) {
322 SkASSERT(SkIsAlign4(size));
325 fTopBot[0] = SK_ScalarNaN; // Mark as unwritten.
326 fChecksum = SkChecksum::Compute((uint32_t*)this->data(), size);
332 mutable SkScalar fTopBot[2]; // Cache of FontMetrics fTop, fBottom. Starts as [NaN,?].
333 // uint32_t flattenedData[] implicitly hangs off the end.
335 template <class T> friend class SkFlatDictionary;
339 class SkFlatDictionary {
340 static const size_t kWriteBufferGrowthBytes = 1024;
343 SkFlatDictionary(SkFlatController* controller, size_t scratchSizeGuess = 0)
345 , fUnflattenProc(NULL)
346 , fController(SkRef(controller))
347 , fScratchSize(scratchSizeGuess)
348 , fScratch(AllocScratch(fScratchSize))
349 , fWriteBuffer(kWriteBufferGrowthBytes)
350 , fWriteBufferReady(false) {
355 * Clears the dictionary of all entries. However, it does NOT free the
356 * memory that was allocated for each entry (that's owned by controller).
359 fIndexedData.rewind();
360 // TODO(mtklein): There's no reason to have the index start from 1. Clean this up.
361 // index 0 is always empty since it is used as a signal that find failed
362 fIndexedData.push(NULL);
366 ~SkFlatDictionary() {
371 SkASSERT(fIndexedData.count() == fNextIndex);
372 SkASSERT(fHash.count() == fNextIndex - 1);
373 return fNextIndex - 1;
376 // For testing only. Index is zero-based.
377 const SkFlatData* operator[](int index) {
378 return fIndexedData[index+1];
382 * Given an element of type T return its 1-based index in the dictionary. If
383 * the element wasn't previously in the dictionary it is automatically
387 int find(const T& element) {
388 return this->findAndReturnFlat(element)->index();
392 * Similar to find. Allows the caller to specify an SkFlatData to replace in
393 * the case of an add. Also tells the caller whether a new SkFlatData was
394 * added and whether the old one was replaced. The parameters added and
395 * replaced are required to be non-NULL. Rather than returning the index of
396 * the entry in the dictionary, it returns the actual SkFlatData.
398 const SkFlatData* findAndReplace(const T& element,
399 const SkFlatData* toReplace,
402 SkASSERT(added != NULL && replaced != NULL);
404 const int oldCount = this->count();
405 SkFlatData* flat = this->findAndReturnMutableFlat(element);
406 *added = this->count() > oldCount;
408 // If we don't want to replace anything, we're done.
409 if (!*added || toReplace == NULL) {
414 // If we don't have the thing to replace, we're done.
415 const SkFlatData* found = fHash.find(*toReplace);
421 // findAndReturnMutableFlat gave us index (fNextIndex-1), but we'll use the old one.
422 fIndexedData.remove(flat->index());
424 flat->setIndex(found->index());
425 fIndexedData[flat->index()] = flat;
427 // findAndReturnMutableFlat already called fHash.add(), so we just clean up the old entry.
428 fHash.remove(*found);
429 fController->unalloc((void*)found);
430 SkASSERT(this->count() == oldCount);
437 * Unflatten the objects and return them in SkTRefArray, or return NULL
438 * if there no objects. Caller takes ownership of result.
440 SkTRefArray<T>* unflattenToArray() const {
441 const int count = this->count();
445 SkTRefArray<T>* array = SkTRefArray<T>::Create(count);
446 for (int i = 0; i < count; i++) {
447 this->unflatten(&array->writableAt(i), fIndexedData[i+1]);
453 * Unflatten the specific object at the given index.
454 * Caller takes ownership of the result.
456 T* unflatten(int index) const {
457 const SkFlatData* element = fIndexedData[index];
458 SkASSERT(index == element->index());
461 this->unflatten(dst, element);
466 * Find or insert a flattened version of element into the dictionary.
467 * Caller does not take ownership of the result. This will not return NULL.
469 const SkFlatData* findAndReturnFlat(const T& element) {
470 return this->findAndReturnMutableFlat(element);
474 void (*fFlattenProc)(SkOrderedWriteBuffer&, const void*);
475 void (*fUnflattenProc)(SkOrderedReadBuffer&, void*);
478 // Layout: [ SkFlatData header, 20 bytes ] [ data ..., 4-byte aligned ]
479 static size_t SizeWithPadding(size_t flatDataSize) {
480 SkASSERT(SkIsAlign4(flatDataSize));
481 return sizeof(SkFlatData) + flatDataSize;
484 // Allocate a new scratch SkFlatData. Must be sk_freed.
485 static SkFlatData* AllocScratch(size_t scratchSize) {
486 return (SkFlatData*) sk_malloc_throw(SizeWithPadding(scratchSize));
489 // We have to delay fWriteBuffer's initialization until its first use; fController might not
490 // be fully set up by the time we get it in the constructor.
491 void lazyWriteBufferInit() {
492 if (fWriteBufferReady) {
495 // Without a bitmap heap, we'll flatten bitmaps into paints. That's never what you want.
496 SkASSERT(fController->getBitmapHeap() != NULL);
497 fWriteBuffer.setBitmapHeap(fController->getBitmapHeap());
498 fWriteBuffer.setTypefaceRecorder(fController->getTypefaceSet());
499 fWriteBuffer.setNamedFactoryRecorder(fController->getNamedFactorySet());
500 fWriteBuffer.setFlags(fController->getWriteBufferFlags());
501 fWriteBufferReady = true;
504 // As findAndReturnFlat, but returns a mutable pointer for internal use.
505 SkFlatData* findAndReturnMutableFlat(const T& element) {
506 // Only valid until the next call to resetScratch().
507 const SkFlatData& scratch = this->resetScratch(element, fNextIndex);
509 SkFlatData* candidate = fHash.find(scratch);
510 if (candidate != NULL) return candidate;
512 SkFlatData* detached = this->detachScratch();
514 *fIndexedData.insert(fNextIndex) = detached;
519 // This reference is valid only until the next call to resetScratch() or detachScratch().
520 const SkFlatData& resetScratch(const T& element, int index) {
521 this->lazyWriteBufferInit();
523 // Flatten element into fWriteBuffer (using fScratch as storage).
524 fWriteBuffer.reset(fScratch->data(), fScratchSize);
525 fFlattenProc(fWriteBuffer, &element);
526 const size_t bytesWritten = fWriteBuffer.bytesWritten();
528 // If all the flattened bytes fit into fScratch, we can skip a call to writeToMemory.
529 if (!fWriteBuffer.wroteOnlyToStorage()) {
530 SkASSERT(bytesWritten > fScratchSize);
531 // It didn't all fit. Copy into a larger replacement SkFlatData.
532 // We can't just realloc because it might move the pointer and confuse writeToMemory.
533 SkFlatData* larger = AllocScratch(bytesWritten);
534 fWriteBuffer.writeToMemory(larger->data());
536 // Carry on with this larger scratch to minimize the likelihood of future resizing.
538 fScratchSize = bytesWritten;
542 // The data is in fScratch now but we need to stamp its header.
543 fScratch->stampHeader(index, bytesWritten);
547 // This result is owned by fController and lives as long as it does (unless unalloc'd).
548 SkFlatData* detachScratch() {
549 // Allocate a new SkFlatData exactly big enough to hold our current scratch.
550 // We use the controller for this allocation to extend the allocation's lifetime and allow
551 // the controller to do whatever memory management it wants.
552 const size_t paddedSize = SizeWithPadding(fScratch->flatSize());
553 SkFlatData* detached = (SkFlatData*)fController->allocThrow(paddedSize);
555 // Copy scratch into the new SkFlatData.
556 memcpy(detached, fScratch, paddedSize);
558 // We can now reuse fScratch, and detached will live until fController dies.
562 void unflatten(T* dst, const SkFlatData* element) const {
563 element->unflatten(dst,
565 fController->getBitmapHeap(),
566 fController->getTypefacePlayback());
569 // All SkFlatData* stored in fIndexedData and fHash are owned by the controller.
570 SkAutoTUnref<SkFlatController> fController;
571 size_t fScratchSize; // How many bytes fScratch has allocated for data itself.
572 SkFlatData* fScratch; // Owned, must be freed with sk_free.
573 SkOrderedWriteBuffer fWriteBuffer;
574 bool fWriteBufferReady;
576 // We map between SkFlatData and a 1-based integer index.
579 // For index -> SkFlatData. fIndexedData[0] is always NULL.
580 SkTDArray<const SkFlatData*> fIndexedData;
582 // For SkFlatData -> cached SkFlatData, which has index().
583 SkTDynamicHash<SkFlatData, SkFlatData,
584 SkFlatData::Identity, SkFlatData::Hash, SkFlatData::Equal> fHash;
587 ///////////////////////////////////////////////////////////////////////////////
588 // Some common dictionaries are defined here for both reference and convenience
589 ///////////////////////////////////////////////////////////////////////////////
592 static void SkFlattenObjectProc(SkOrderedWriteBuffer& buffer, const void* obj) {
593 ((T*)obj)->flatten(buffer);
597 static void SkUnflattenObjectProc(SkOrderedReadBuffer& buffer, void* obj) {
598 ((T*)obj)->unflatten(buffer);
601 class SkChunkFlatController : public SkFlatController {
603 SkChunkFlatController(size_t minSize)
605 , fTypefaceSet(SkNEW(SkRefCntSet))
606 , fLastAllocated(NULL) {
607 this->setTypefaceSet(fTypefaceSet);
608 this->setTypefacePlayback(&fTypefacePlayback);
611 virtual void* allocThrow(size_t bytes) SK_OVERRIDE {
612 fLastAllocated = fHeap.allocThrow(bytes);
613 return fLastAllocated;
616 virtual void unalloc(void* ptr) SK_OVERRIDE {
617 // fHeap can only free a pointer if it was the last one allocated. Otherwise, we'll just
618 // have to wait until fHeap is destroyed.
619 if (ptr == fLastAllocated) (void)fHeap.unalloc(ptr);
622 void setupPlaybacks() const {
623 fTypefacePlayback.reset(fTypefaceSet.get());
626 void setBitmapStorage(SkBitmapHeap* heap) {
627 this->setBitmapHeap(heap);
632 SkAutoTUnref<SkRefCntSet> fTypefaceSet;
633 void* fLastAllocated;
634 mutable SkTypefacePlayback fTypefacePlayback;
637 class SkMatrixDictionary : public SkFlatDictionary<SkMatrix> {
639 // All matrices fit in 36 bytes.
640 SkMatrixDictionary(SkFlatController* controller)
641 : SkFlatDictionary<SkMatrix>(controller, 36) {
642 fFlattenProc = &flattenMatrix;
643 fUnflattenProc = &unflattenMatrix;
646 static void flattenMatrix(SkOrderedWriteBuffer& buffer, const void* obj) {
647 buffer.getWriter32()->writeMatrix(*(SkMatrix*)obj);
650 static void unflattenMatrix(SkOrderedReadBuffer& buffer, void* obj) {
651 buffer.getReader32()->readMatrix((SkMatrix*)obj);
655 class SkPaintDictionary : public SkFlatDictionary<SkPaint> {
657 // The largest paint across ~60 .skps was 500 bytes.
658 SkPaintDictionary(SkFlatController* controller)
659 : SkFlatDictionary<SkPaint>(controller, 512) {
660 fFlattenProc = &SkFlattenObjectProc<SkPaint>;
661 fUnflattenProc = &SkUnflattenObjectProc<SkPaint>;
665 class SkRegionDictionary : public SkFlatDictionary<SkRegion> {
667 SkRegionDictionary(SkFlatController* controller)
668 : SkFlatDictionary<SkRegion>(controller) {
669 fFlattenProc = &flattenRegion;
670 fUnflattenProc = &unflattenRegion;
673 static void flattenRegion(SkOrderedWriteBuffer& buffer, const void* obj) {
674 buffer.getWriter32()->writeRegion(*(SkRegion*)obj);
677 static void unflattenRegion(SkOrderedReadBuffer& buffer, void* obj) {
678 buffer.getReader32()->readRegion((SkRegion*)obj);