Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / gpu / GrPictureUtils.cpp
index 089e421..a4f32e7 100644 (file)
  */
 
 #include "GrPictureUtils.h"
-#include "SkDevice.h"
-#include "SkDraw.h"
+
 #include "SkPaintPriv.h"
+#include "SkRecord.h"
+#include "SkRecords.h"
 
-SkPicture::AccelData::Key GPUAccelData::ComputeAccelDataKey() {
+SkPicture::AccelData::Key GrAccelData::ComputeAccelDataKey() {
     static const SkPicture::AccelData::Key gGPUID = SkPicture::AccelData::GenerateDomain();
 
     return gGPUID;
 }
 
-// The GrGather device performs GPU-backend-specific preprocessing on
-// a picture. The results are stored in a GPUAccelData.
-//
-// Currently the only interesting work is done in drawDevice (i.e., when a
-// saveLayer is collapsed back into its parent) and, maybe, in onCreateDevice.
-// All the current work could be done much more efficiently by just traversing the
-// raw op codes in the SkPicture (although we would still need to replay all the
-// clip calls).
-class GrGatherDevice : public SkBaseDevice {
+// SkRecord visitor to gather saveLayer/restore information.
+class CollectLayers {
 public:
-    SK_DECLARE_INST_COUNT(GrGatherDevice)
-
-    GrGatherDevice(int width, int height, SkPicture* picture, GPUAccelData* accelData,
-                   int saveLayerDepth) {
-        fPicture = picture;
-        fSaveLayerDepth = saveLayerDepth;
-        fInfo.fValid = true;
-        fInfo.fSize.set(width, height);
-        fInfo.fPaint = NULL;
-        fInfo.fSaveLayerOpID = fPicture->EXPERIMENTAL_curOpID();
-        fInfo.fRestoreOpID = 0;
-        fInfo.fHasNestedLayers = false;
-        fInfo.fIsNested = (2 == fSaveLayerDepth);
-
-        fEmptyBitmap.setConfig(SkImageInfo::Make(fInfo.fSize.fWidth,
-                                                 fInfo.fSize.fHeight,
-                                                 kUnknown_SkColorType,
-                                                 kIgnore_SkAlphaType));
-        fAccelData = accelData;
-        fAlreadyDrawn = false;
-    }
+    CollectLayers(const SkPicture* pict, GrAccelData* accelData)
+        : fPictureID(pict->uniqueID())
+        , fCTM(&SkMatrix::I())
+        , fSaveLayersInStack(0)
+        , fAccelData(accelData) {
 
-    virtual ~GrGatherDevice() { }
+        pict->cullRect().roundOut(&fCurrentClipBounds);
 
-    virtual int width() const SK_OVERRIDE { return fInfo.fSize.width(); }
-    virtual int height() const SK_OVERRIDE { return fInfo.fSize.height(); }
-    virtual bool isOpaque() const SK_OVERRIDE { return false; }
-    virtual SkBitmap::Config config() const SK_OVERRIDE {
-        return SkBitmap::kNo_Config;
-    }
-    virtual SkImageInfo imageInfo() const SK_OVERRIDE {
-        return fEmptyBitmap.info();
-    }
+        if (NULL == pict->fRecord.get()) {
+            return;
+        }
 
-#ifdef SK_SUPPORT_LEGACY_WRITEPIXELSCONFIG
-    virtual void writePixels(const SkBitmap& bitmap, int x, int y,
-                             SkCanvas::Config8888 config8888) SK_OVERRIDE {
-        NotSupported();
-    }
-#endif
-    virtual GrRenderTarget* accessRenderTarget() SK_OVERRIDE { return NULL; }
+        for (fCurrentOp = 0; fCurrentOp < pict->fRecord->count(); ++fCurrentOp) {
+            pict->fRecord->visit<void>(fCurrentOp, *this);
+        }
 
-protected:
-    virtual bool filterTextFlags(const SkPaint& paint, TextFlags*) SK_OVERRIDE {
-        return false;
-    }
-    virtual void clear(SkColor color) SK_OVERRIDE {
-        NothingToDo();
-    }
-    virtual void drawPaint(const SkDraw& draw, const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawPoints(const SkDraw& draw, SkCanvas::PointMode mode, size_t count,
-                            const SkPoint points[], const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawRect(const SkDraw& draw, const SkRect& rect,
-                          const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawOval(const SkDraw& draw, const SkRect& rect,
-                          const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawRRect(const SkDraw& draw, const SkRRect& rrect,
-                           const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawPath(const SkDraw& draw, const SkPath& path,
-                          const SkPaint& paint, const SkMatrix* prePathMatrix,
-                          bool pathIsMutable) SK_OVERRIDE {
-    }
-    virtual void drawBitmap(const SkDraw& draw, const SkBitmap& bitmap,
-                            const SkMatrix& matrix, const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap,
-                            int x, int y, const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawBitmapRect(const SkDraw& draw, const SkBitmap& bitmap,
-                                const SkRect* srcOrNull, const SkRect& dst,
-                                const SkPaint& paint,
-                                SkCanvas::DrawBitmapRectFlags flags) SK_OVERRIDE {
-    }
-    virtual void drawText(const SkDraw& draw, const void* text, size_t len,
-                          SkScalar x, SkScalar y,
-                          const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawPosText(const SkDraw& draw, const void* text, size_t len,
-                             const SkScalar pos[], SkScalar constY,
-                             int scalarsPerPos, const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawTextOnPath(const SkDraw& draw, const void* text, size_t len,
-                                const SkPath& path, const SkMatrix* matrix,
-                                const SkPaint& paint) SK_OVERRIDE {
-    }
-    virtual void drawVertices(const SkDraw& draw, SkCanvas::VertexMode, int vertexCount,
-                              const SkPoint verts[], const SkPoint texs[],
-                              const SkColor colors[], SkXfermode* xmode,
-                              const uint16_t indices[], int indexCount,
-                              const SkPaint& paint) SK_OVERRIDE {
+        while (!fSaveStack.isEmpty()) {
+            this->popSaveBlock();
+        }
     }
-    virtual void drawDevice(const SkDraw& draw, SkBaseDevice* deviceIn, int x, int y,
-                            const SkPaint& paint) SK_OVERRIDE {
-        // deviceIn is the one that is being "restored" back to its parent
-        GrGatherDevice* device = static_cast<GrGatherDevice*>(deviceIn);
 
-        if (device->fAlreadyDrawn) {
-            return;
-        }
+    template <typename T> void operator()(const T& op) {
+        this->updateCTM(op);
+        this->updateClipBounds(op);
+        this->trackSaveLayers(op);
+    }
 
-        device->fInfo.fRestoreOpID = fPicture->EXPERIMENTAL_curOpID();
-        device->fInfo.fCTM = *draw.fMatrix;
-        device->fInfo.fCTM.postTranslate(SkIntToScalar(-device->getOrigin().fX),
-                                         SkIntToScalar(-device->getOrigin().fY));
+private:
 
-        // We need the x & y values that will yield 'getOrigin' when transformed
-        // by 'draw.fMatrix'.
-        device->fInfo.fOffset.iset(device->getOrigin());
+    class SaveInfo {
+    public:
+        SaveInfo() { }
+        SaveInfo(int opIndex, bool isSaveLayer, const SkPaint* paint, const SkIRect& bounds) 
+            : fStartIndex(opIndex)
+            , fIsSaveLayer(isSaveLayer)
+            , fHasNestedSaveLayer(false)
+            , fPaint(paint)
+            , fBounds(bounds) {
 
-        SkMatrix invMatrix;
-        if (draw.fMatrix->invert(&invMatrix)) {
-            invMatrix.mapPoints(&device->fInfo.fOffset, 1);
-        } else {
-            device->fInfo.fValid = false;
         }
 
-        if (NeedsDeepCopy(paint)) {
-            // This NULL acts as a signal that the paint was uncopyable (for now)
-            device->fInfo.fPaint = NULL;
-            device->fInfo.fValid = false;
-        } else {
-            device->fInfo.fPaint = SkNEW_ARGS(SkPaint, (paint));
+        int            fStartIndex;
+        bool           fIsSaveLayer;
+        bool           fHasNestedSaveLayer;
+        const SkPaint* fPaint;
+        SkIRect        fBounds;
+    };
+
+    uint32_t            fPictureID;
+    unsigned int        fCurrentOp;
+    const SkMatrix*     fCTM;
+    SkIRect             fCurrentClipBounds;
+    int                 fSaveLayersInStack;
+    SkTDArray<SaveInfo> fSaveStack;
+    GrAccelData*        fAccelData;
+
+    template <typename T> void updateCTM(const T&) { /* most ops don't change the CTM */ }
+    void updateCTM(const SkRecords::Restore& op)   { fCTM = &op.matrix; }
+    void updateCTM(const SkRecords::SetMatrix& op) { fCTM = &op.matrix; }
+
+    template <typename T> void updateClipBounds(const T&) { /* most ops don't change the clip */ }
+    // Each of these devBounds fields is the state of the device bounds after the op.
+    // So Restore's devBounds are those bounds saved by its paired Save or SaveLayer.
+    void updateClipBounds(const SkRecords::Restore& op)    { fCurrentClipBounds = op.devBounds; }
+    void updateClipBounds(const SkRecords::ClipPath& op)   { fCurrentClipBounds = op.devBounds; }
+    void updateClipBounds(const SkRecords::ClipRRect& op)  { fCurrentClipBounds = op.devBounds; }
+    void updateClipBounds(const SkRecords::ClipRect& op)   { fCurrentClipBounds = op.devBounds; }
+    void updateClipBounds(const SkRecords::ClipRegion& op) { fCurrentClipBounds = op.devBounds; }
+    void updateClipBounds(const SkRecords::SaveLayer& op)  {
+        if (op.bounds) {
+            fCurrentClipBounds.intersect(this->adjustAndMap(*op.bounds, op.paint));
         }
-
-        fAccelData->addSaveLayerInfo(device->fInfo);
-        device->fAlreadyDrawn = true;
-    }
-    // TODO: allow this call to return failure, or move to SkBitmapDevice only.
-    virtual const SkBitmap& onAccessBitmap() SK_OVERRIDE {
-        return fEmptyBitmap;
     }
-#ifdef SK_SUPPORT_LEGACY_READPIXELSCONFIG
-    virtual bool onReadPixels(const SkBitmap& bitmap,
-                              int x, int y,
-                              SkCanvas::Config8888 config8888) SK_OVERRIDE {
-        NotSupported();
-        return false;
+
+    template <typename T> void trackSaveLayers(const T& op) { 
+        /* most ops aren't involved in saveLayers */ 
+    }
+    void trackSaveLayers(const SkRecords::Save& s) { this->pushSaveBlock(); }
+    void trackSaveLayers(const SkRecords::SaveLayer& sl) { this->pushSaveLayerBlock(sl.paint); }
+    void trackSaveLayers(const SkRecords::Restore& r) { this->popSaveBlock(); }
+    void trackSaveLayers(const SkRecords::DrawPicture& dp) {
+        // For sub-pictures, we wrap their layer information within the parent
+        // picture's rendering hierarchy
+        const GrAccelData* childData = GPUOptimize(dp.picture);
+
+        for (int i = 0; i < childData->numSaveLayers(); ++i) {
+            const GrAccelData::SaveLayerInfo& src = childData->saveLayerInfo(i);
+
+            this->updateStackForSaveLayer();
+
+            // TODO: need to store an SkRect in GrAccelData::SaveLayerInfo?
+            SkRect srcRect = SkRect::MakeXYWH(SkIntToScalar(src.fOffset.fX),
+                                              SkIntToScalar(src.fOffset.fY),
+                                              SkIntToScalar(src.fSize.width()),
+                                              SkIntToScalar(src.fSize.height()));
+            SkIRect newClip(fCurrentClipBounds);
+            newClip.intersect(this->adjustAndMap(srcRect, dp.paint));
+
+            GrAccelData::SaveLayerInfo& dst = fAccelData->addSaveLayerInfo();
+
+            dst.fValid = true;
+            // If src.fPicture is NULL the layer is in dp.picture; otherwise
+            // it belongs to a sub-picture.
+            dst.fPicture = src.fPicture ? src.fPicture : static_cast<const SkPicture*>(dp.picture);
+            dst.fPicture->ref();
+            dst.fSize = SkISize::Make(newClip.width(), newClip.height());
+            dst.fOffset = SkIPoint::Make(newClip.fLeft, newClip.fTop);
+            dst.fOriginXform = *fCTM;
+            dst.fOriginXform.postConcat(src.fOriginXform);
+            if (src.fPaint) {
+                dst.fPaint = SkNEW_ARGS(SkPaint, (*src.fPaint));
+            }
+            dst.fSaveLayerOpID = src.fSaveLayerOpID;
+            dst.fRestoreOpID = src.fRestoreOpID;
+            dst.fHasNestedLayers = src.fHasNestedLayers;
+            dst.fIsNested = fSaveLayersInStack > 0 || src.fIsNested;
+        }
     }
-#endif
-    virtual void lockPixels() SK_OVERRIDE { NothingToDo(); }
-    virtual void unlockPixels() SK_OVERRIDE { NothingToDo(); }
-    virtual bool allowImageFilter(const SkImageFilter*) SK_OVERRIDE { return false; }
-    virtual bool canHandleImageFilter(const SkImageFilter*) SK_OVERRIDE { return false; }
-    virtual bool filterImage(const SkImageFilter*, const SkBitmap&, const SkImageFilter::Context&,
-                             SkBitmap* result, SkIPoint* offset) SK_OVERRIDE {
-        return false;
+
+    void pushSaveBlock() {
+        fSaveStack.push(SaveInfo(fCurrentOp, false, NULL, SkIRect::MakeEmpty()));
     }
 
-private:
-    // The picture being processed
-    SkPicture *fPicture;
+    // Inform all the saveLayers already on the stack that they now have a
+    // nested saveLayer inside them
+    void updateStackForSaveLayer() {
+        for (int index = fSaveStack.count() - 1; index >= 0; --index) {
+            if (fSaveStack[index].fHasNestedSaveLayer) {
+                break;
+            }
+            fSaveStack[index].fHasNestedSaveLayer = true;
+            if (fSaveStack[index].fIsSaveLayer) {
+                break;
+            }
+        }
+    }
 
-    SkBitmap fEmptyBitmap; // legacy -- need to remove
+    void pushSaveLayerBlock(const SkPaint* paint) {
+        this->updateStackForSaveLayer();
 
-    // All information gathered during the gather process is stored here
-    GPUAccelData* fAccelData;
+        fSaveStack.push(SaveInfo(fCurrentOp, true, paint, fCurrentClipBounds));
+        ++fSaveLayersInStack;
+    }
 
-    // true if this device has already been drawn back to its parent(s) at least
-    // once.
-    bool   fAlreadyDrawn;
+    void popSaveBlock() {
+        if (fSaveStack.count() <= 0) {
+            SkASSERT(false);
+            return;
+        }
 
-    // The information regarding the saveLayer call this device represents.
-    GPUAccelData::SaveLayerInfo fInfo;
+        SaveInfo si;
+        fSaveStack.pop(&si);
 
-    // The depth of this device in the saveLayer stack
-    int fSaveLayerDepth;
+        if (!si.fIsSaveLayer) {
+            return;
+        }
 
-    virtual void replaceBitmapBackendForRasterSurface(const SkBitmap&) SK_OVERRIDE {
-        NotSupported();
-    }
+        --fSaveLayersInStack;
 
-    virtual SkBaseDevice* onCreateDevice(const SkImageInfo& info, Usage usage) SK_OVERRIDE {
-        // we expect to only get called via savelayer, in which case it is fine.
-        SkASSERT(kSaveLayer_Usage == usage);
+        GrAccelData::SaveLayerInfo& slInfo = fAccelData->addSaveLayerInfo();
 
-        fInfo.fHasNestedLayers = true;
-        return SkNEW_ARGS(GrGatherDevice, (info.width(), info.height(), fPicture, 
-                                           fAccelData, fSaveLayerDepth+1));
+        slInfo.fValid = true;
+        SkASSERT(NULL == slInfo.fPicture);  // This layer is in the top-most picture
+        slInfo.fSize = SkISize::Make(si.fBounds.width(), si.fBounds.height());
+        slInfo.fOffset = SkIPoint::Make(si.fBounds.fLeft, si.fBounds.fTop);
+        slInfo.fOriginXform = *fCTM;
+        if (si.fPaint) {
+            slInfo.fPaint = SkNEW_ARGS(SkPaint, (*si.fPaint));
+        }
+        slInfo.fSaveLayerOpID = si.fStartIndex;
+        slInfo.fRestoreOpID = fCurrentOp;
+        slInfo.fHasNestedLayers = si.fHasNestedSaveLayer;
+        slInfo.fIsNested = fSaveLayersInStack > 0;
+    }
+
+    // Returns true if rect was meaningfully adjusted for the effects of paint,
+    // false if the paint could affect the rect in unknown ways.
+    static bool AdjustForPaint(const SkPaint* paint, SkRect* rect) {
+        if (paint) {
+            if (paint->canComputeFastBounds()) {
+                *rect = paint->computeFastBounds(*rect, rect);
+                return true;
+            }
+            return false;
+        }
+        return true;
     }
 
-    virtual void flush() SK_OVERRIDE {}
+    // Adjust rect for all paints that may affect its geometry, then map it to device space.
+    SkIRect adjustAndMap(SkRect rect, const SkPaint* paint) const {
+        // Inverted rectangles really confuse our BBHs.
+        rect.sort();
 
-    static void NotSupported() {
-        SkDEBUGFAIL("this method should never be called");
-    }
+        // Adjust the rect for its own paint.
+        if (!AdjustForPaint(paint, &rect)) {
+            // The paint could do anything to our bounds.  The only safe answer is the current clip.
+            return fCurrentClipBounds;
+        }
 
-    static void NothingToDo() {}
+        // Adjust rect for all the paints from the SaveLayers we're inside.
+        for (int i = fSaveStack.count() - 1; i >= 0; i--) {
+            if (!AdjustForPaint(fSaveStack[i].fPaint, &rect)) {
+                // Same deal as above.
+                return fCurrentClipBounds;
+            }
+        }
 
-    typedef SkBaseDevice INHERITED;
-};
+        // Map the rect back to device space.
+        fCTM->mapRect(&rect);
+        SkIRect devRect;
+        rect.roundOut(&devRect);
 
-// The GrGatherCanvas allows saveLayers but simplifies clipping. It is really
-// only intended to be used as:
-//
-//      GrGatherDevice dev(w, h, picture, accelData);
-//      GrGatherCanvas canvas(..., picture);
-//      canvas.gather();
-//
-// which is all just to fill in 'accelData'
-class SK_API GrGatherCanvas : public SkCanvas {
-public:
-    GrGatherCanvas(GrGatherDevice* device, SkPicture* pict)
-        : INHERITED(device)
-        , fPicture(pict) {
+        // Nothing can draw outside the current clip.
+        // (Only bounded ops call into this method, so oddballs like Clear don't matter here.)
+        devRect.intersect(fCurrentClipBounds);
+        return devRect;
     }
+};
 
-    void gather() {
-        if (NULL == fPicture || 0 == fPicture->width() || 0 == fPicture->height()) {
-            return;
-        }
 
-        this->clipRect(SkRect::MakeWH(SkIntToScalar(fPicture->width()),
-                                      SkIntToScalar(fPicture->height())),
-                       SkRegion::kIntersect_Op, false);
-        this->drawPicture(*fPicture);
+// GPUOptimize is only intended to be called within the context of SkGpuDevice's
+// EXPERIMENTAL_optimize method.
+const GrAccelData* GPUOptimize(const SkPicture* pict) {
+    if (NULL == pict || pict->cullRect().isEmpty()) {
+        return NULL;
     }
 
-    virtual void drawPicture(SkPicture& picture) SK_OVERRIDE {
-        picture.draw(this);
-    }
-protected:
-    // disable aa for speed
-    virtual void onClipRect(const SkRect& rect, SkRegion::Op op, ClipEdgeStyle) SK_OVERRIDE {
-        this->INHERITED::onClipRect(rect, op, kHard_ClipEdgeStyle);
-    }
+    SkPicture::AccelData::Key key = GrAccelData::ComputeAccelDataKey();
 
-    // for speed, just respect the bounds, and disable AA. May give us a few
-    // false positives and negatives.
-    virtual void onClipPath(const SkPath& path, SkRegion::Op op, ClipEdgeStyle) SK_OVERRIDE {
-        this->updateClipConservativelyUsingBounds(path.getBounds(), op,
-                                                  path.isInverseFillType());
-    }
-    virtual void onClipRRect(const SkRRect& rrect, SkRegion::Op op, ClipEdgeStyle) SK_OVERRIDE {
-        this->updateClipConservativelyUsingBounds(rrect.getBounds(), op, false);
+    const GrAccelData* existing = 
+                            static_cast<const GrAccelData*>(pict->EXPERIMENTAL_getAccelData(key));
+    if (existing) {
+        return existing;
     }
 
-private:
-    SkPicture* fPicture;
+    SkAutoTUnref<GrAccelData> data(SkNEW_ARGS(GrAccelData, (key)));
 
-    typedef SkCanvas INHERITED;
-};
-
-// GatherGPUInfo is only intended to be called within the context of SkGpuDevice's
-// EXPERIMENTAL_optimize method.
-void GatherGPUInfo(SkPicture* pict, GPUAccelData* accelData) {
-    if (0 == pict->width() || 0 == pict->height()) {
-        return ;
-    }
+    pict->EXPERIMENTAL_addAccelData(data);
 
-    GrGatherDevice device(pict->width(), pict->height(), pict, accelData, 0);
-    GrGatherCanvas canvas(&device, pict);
+    CollectLayers collector(pict, data);
 
-    canvas.gather();
+    return data;
 }