• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 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 SkShaderBase_DEFINED
9 #define SkShaderBase_DEFINED
10 
11 #include "include/core/SkMatrix.h"
12 #include "include/core/SkPaint.h"
13 #include "include/core/SkSamplingOptions.h"
14 #include "include/core/SkShader.h"
15 #include "include/private/SkNoncopyable.h"
16 #include "src/core/SkEffectPriv.h"
17 #include "src/core/SkMask.h"
18 #include "src/core/SkTLazy.h"
19 #include "src/core/SkVM_fwd.h"
20 
21 #if SK_SUPPORT_GPU
22 #include "src/gpu/GrFPArgs.h"
23 #endif
24 
25 class GrFragmentProcessor;
26 class SkArenaAlloc;
27 class SkColorSpace;
28 class SkImage;
29 struct SkImageInfo;
30 class SkPaint;
31 class SkRasterPipeline;
32 class SkRuntimeEffect;
33 class SkStageUpdater;
34 
35 class SkUpdatableShader;
36 
37 class SkShaderBase : public SkShader {
38 public:
39     ~SkShaderBase() override;
40 
41     sk_sp<SkShader> makeInvertAlpha() const;
42     sk_sp<SkShader> makeWithCTM(const SkMatrix&) const;  // owns its own ctm
43 
44     /**
45      *  Returns true if the shader is guaranteed to produce only a single color.
46      *  Subclasses can override this to allow loop-hoisting optimization.
47      */
isConstant()48     virtual bool isConstant() const { return false; }
49 
getLocalMatrix()50     const SkMatrix& getLocalMatrix() const { return fLocalMatrix; }
51 
52     enum Flags {
53         //!< set if all of the colors will be opaque
54         kOpaqueAlpha_Flag = 1 << 0,
55 
56         /** set if the spans only vary in X (const in Y).
57             e.g. an Nx1 bitmap that is being tiled in Y, or a linear-gradient
58             that varies from left-to-right. This flag specifies this for
59             shadeSpan().
60          */
61         kConstInY32_Flag = 1 << 1,
62 
63         /** hint for the blitter that 4f is the preferred shading mode.
64          */
65         kPrefers4f_Flag  = 1 << 2,
66     };
67 
68     /**
69      *  ContextRec acts as a parameter bundle for creating Contexts.
70      */
71     struct ContextRec {
ContextRecContextRec72         ContextRec(const SkPaint& paint, const SkMatrix& matrix, const SkMatrix* localM,
73                    SkColorType dstColorType, SkColorSpace* dstColorSpace)
74             : fMatrix(&matrix)
75             , fLocalMatrix(localM)
76             , fDstColorType(dstColorType)
77             , fDstColorSpace(dstColorSpace) {
78                 fPaintAlpha = paint.getAlpha();
79                 fPaintDither = paint.isDither();
80             }
81 
82         const SkMatrix* fMatrix;           // the current matrix in the canvas
83         const SkMatrix* fLocalMatrix;      // optional local matrix
84         SkColorType     fDstColorType;     // the color type of the dest surface
85         SkColorSpace*   fDstColorSpace;    // the color space of the dest surface (if any)
86         SkAlpha         fPaintAlpha;
87         bool            fPaintDither;
88 
89         bool isLegacyCompatible(SkColorSpace* shadersColorSpace) const;
90     };
91 
92     class Context : public ::SkNoncopyable {
93     public:
94         Context(const SkShaderBase& shader, const ContextRec&);
95 
96         virtual ~Context();
97 
98         /**
99          *  Called sometimes before drawing with this shader. Return the type of
100          *  alpha your shader will return. The default implementation returns 0.
101          *  Your subclass should override if it can (even sometimes) report a
102          *  non-zero value, since that will enable various blitters to perform
103          *  faster.
104          */
getFlags()105         virtual uint32_t getFlags() const { return 0; }
106 
107         /**
108          *  Called for each span of the object being drawn. Your subclass should
109          *  set the appropriate colors (with premultiplied alpha) that correspond
110          *  to the specified device coordinates.
111          */
112         virtual void shadeSpan(int x, int y, SkPMColor[], int count) = 0;
113 
114     protected:
115         // Reference to shader, so we don't have to dupe information.
116         const SkShaderBase& fShader;
117 
getPaintAlpha()118         uint8_t         getPaintAlpha() const { return fPaintAlpha; }
getTotalInverse()119         const SkMatrix& getTotalInverse() const { return fTotalInverse; }
getCTM()120         const SkMatrix& getCTM() const { return fCTM; }
121 
122     private:
123         SkMatrix    fCTM;
124         SkMatrix    fTotalInverse;
125         uint8_t     fPaintAlpha;
126 
127         using INHERITED = SkNoncopyable;
128     };
129 
130     /**
131      * Make a context using the memory provided by the arena.
132      *
133      * @return pointer to context or nullptr if can't be created
134      */
135     Context* makeContext(const ContextRec&, SkArenaAlloc*) const;
136 
137 #if SK_SUPPORT_GPU
138     /**
139      *  Returns a GrFragmentProcessor that implements the shader for the GPU backend. nullptr is
140      *  returned if there is no GPU implementation.
141      *
142      *  The GPU device does not call SkShader::createContext(), instead we pass the view matrix,
143      *  local matrix, and filter quality directly.
144      *
145      *  The GrRecordingContext may be used by the to create textures that are required by the
146      *  returned processor.
147      *
148      *  The returned GrFragmentProcessor should expect an unpremultiplied input color and
149      *  produce a premultiplied output.
150      */
151     virtual std::unique_ptr<GrFragmentProcessor> asFragmentProcessor(const GrFPArgs&) const;
152 #endif
153 
154     /**
155      *  If the shader can represent its "average" luminance in a single color, return true and
156      *  if color is not NULL, return that color. If it cannot, return false and ignore the color
157      *  parameter.
158      *
159      *  Note: if this returns true, the returned color will always be opaque, as only the RGB
160      *  components are used to compute luminance.
161      */
162     bool asLuminanceColor(SkColor*) const;
163 
164     // If this returns false, then we draw nothing (do not fall back to shader context)
165     SK_WARN_UNUSED_RESULT
166     bool appendStages(const SkStageRec&) const;
167 
168     bool SK_WARN_UNUSED_RESULT computeTotalInverse(const SkMatrix& ctm,
169                                                    const SkMatrix* outerLocalMatrix,
170                                                    SkMatrix* totalInverse) const;
171 
172     // Returns the total local matrix for this shader:
173     //
174     //   M = postLocalMatrix x shaderLocalMatrix x preLocalMatrix
175     //
176     SkTCopyOnFirstWrite<SkMatrix> totalLocalMatrix(const SkMatrix* preLocalMatrix) const;
177 
onIsAImage(SkMatrix *,SkTileMode[2])178     virtual SkImage* onIsAImage(SkMatrix*, SkTileMode[2]) const {
179         return nullptr;
180     }
181 
asRuntimeEffect()182     virtual SkRuntimeEffect* asRuntimeEffect() const { return nullptr; }
183 
GetFlattenableType()184     static Type GetFlattenableType() { return kSkShader_Type; }
getFlattenableType()185     Type getFlattenableType() const override { return GetFlattenableType(); }
186 
187     static sk_sp<SkShaderBase> Deserialize(const void* data, size_t size,
188                                              const SkDeserialProcs* procs = nullptr) {
189         return sk_sp<SkShaderBase>(static_cast<SkShaderBase*>(
190                 SkFlattenable::Deserialize(GetFlattenableType(), data, size, procs).release()));
191     }
192     static void RegisterFlattenables();
193 
194     /** DEPRECATED. skbug.com/8941
195      *  If this shader can be represented by another shader + a localMatrix, return that shader and
196      *  the localMatrix. If not, return nullptr and ignore the localMatrix parameter.
197      */
198     virtual sk_sp<SkShader> makeAsALocalMatrixShader(SkMatrix* localMatrix) const;
199 
200     SkUpdatableShader* updatableShader(SkArenaAlloc* alloc) const;
201     virtual SkUpdatableShader* onUpdatableShader(SkArenaAlloc* alloc) const;
202 
appendUpdatableStages(const SkStageRec & rec)203     SkStageUpdater* appendUpdatableStages(const SkStageRec& rec) const {
204         return this->onAppendUpdatableStages(rec);
205     }
206 
207     SK_WARN_UNUSED_RESULT
208     skvm::Color program(skvm::Builder*, skvm::Coord device, skvm::Coord local, skvm::Color paint,
209                         const SkMatrixProvider&, const SkMatrix* localM, const SkColorInfo& dst,
210                         skvm::Uniforms* uniforms, SkArenaAlloc* alloc) const;
211 
212 protected:
213     SkShaderBase(const SkMatrix* localMatrix = nullptr);
214 
215     void flatten(SkWriteBuffer&) const override;
216 
217 #ifdef SK_ENABLE_LEGACY_SHADERCONTEXT
218     /**
219      * Specialize creating a SkShader context using the supplied allocator.
220      * @return pointer to context owned by the arena allocator.
221      */
onMakeContext(const ContextRec &,SkArenaAlloc *)222     virtual Context* onMakeContext(const ContextRec&, SkArenaAlloc*) const {
223         return nullptr;
224     }
225 #endif
226 
onAsLuminanceColor(SkColor *)227     virtual bool onAsLuminanceColor(SkColor*) const {
228         return false;
229     }
230 
231     // Default impl creates shadercontext and calls that (not very efficient)
232     virtual bool onAppendStages(const SkStageRec&) const;
233 
onAppendUpdatableStages(const SkStageRec &)234     virtual SkStageUpdater* onAppendUpdatableStages(const SkStageRec&) const { return nullptr; }
235 
236 protected:
237     static skvm::Coord ApplyMatrix(skvm::Builder*, const SkMatrix&, skvm::Coord, skvm::Uniforms*);
238 
239 private:
240     // This is essentially const, but not officially so it can be modified in constructors.
241     SkMatrix fLocalMatrix;
242 
243     virtual skvm::Color onProgram(skvm::Builder*,
244                                   skvm::Coord device, skvm::Coord local, skvm::Color paint,
245                                   const SkMatrixProvider&, const SkMatrix* localM,
246                                   const SkColorInfo& dst, skvm::Uniforms*, SkArenaAlloc*) const = 0;
247 
248     using INHERITED = SkShader;
249 };
250 
251 /**
252  *  Shaders can optionally return a subclass of this when appending their stages.
253  *  Doing so tells the caller that the stages can be reused with different CTMs (but nothing
254  *  else can change), by calling the updater's update() method before each use.
255  *
256  *  This can be a perf-win bulk draws like drawAtlas and drawVertices, where most of the setup
257  *  (i.e. uniforms) are constant, and only something small is changing (i.e. matrices). This
258  *  reuse skips the cost of computing the stages (and/or avoids having to allocate a separate
259  *  shader for each small draw.
260  */
261 class SkStageUpdater {
262 public:
~SkStageUpdater()263     virtual ~SkStageUpdater() {}
264     virtual bool SK_WARN_UNUSED_RESULT update(const SkMatrix& ctm) const = 0;
265 };
266 
267 // TODO: use the SkStageUpdater as an interface until all the code is converted over to use
268 //       SkUpdatableShader.
269 class SkUpdatableShader : public SkShaderBase, public SkStageUpdater {
270 private:
271     // For serialization.  This will never be called.
getFactory()272     Factory getFactory() const override { return nullptr; }
getTypeName()273     const char* getTypeName() const override { return nullptr; }
274 };
275 
as_SB(SkShader * shader)276 inline SkShaderBase* as_SB(SkShader* shader) {
277     return static_cast<SkShaderBase*>(shader);
278 }
279 
as_SB(const SkShader * shader)280 inline const SkShaderBase* as_SB(const SkShader* shader) {
281     return static_cast<const SkShaderBase*>(shader);
282 }
283 
as_SB(const sk_sp<SkShader> & shader)284 inline const SkShaderBase* as_SB(const sk_sp<SkShader>& shader) {
285     return static_cast<SkShaderBase*>(shader.get());
286 }
287 
288 #endif // SkShaderBase_DEFINED
289