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