1/*
2 * Copyright 2012 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 GrProcessor_DEFINED
9#define GrProcessor_DEFINED
10
11#include "GrBackendProcessorFactory.h"
12#include "GrColor.h"
13#include "GrProcessorUnitTest.h"
14#include "GrProgramElement.h"
15#include "GrShaderVar.h"
16#include "GrTextureAccess.h"
17#include "GrTypesPriv.h"
18#include "SkString.h"
19
20class GrBackendProcessorFactory;
21class GrContext;
22class GrCoordTransform;
23
24/** Provides custom vertex shader, fragment shader, uniform data for a particular stage of the
25    Ganesh shading pipeline.
26    Subclasses must have a function that produces a human-readable name:
27        static const char* Name();
28    GrProcessor objects *must* be immutable: after being constructed, their fields may not change.
29
30    Dynamically allocated GrProcessors are managed by a per-thread memory pool. The ref count of an
31    effect must reach 0 before the thread terminates and the pool is destroyed. To create a static
32    effect use the macro GR_CREATE_STATIC_EFFECT declared below.
33  */
34class GrProcessor : public GrProgramElement {
35public:
36    SK_DECLARE_INST_COUNT(GrProcessor)
37
38    virtual ~GrProcessor();
39
40    /**
41     * This function is used to perform optimizations. When called the color and validFlags params
42     * indicate whether the input components to this effect in the FS will have known values.
43     * validFlags is a bitfield of GrColorComponentFlags. The function updates both params to
44     * indicate known values of its output. A component of the color param only has meaning if the
45     * corresponding bit in validFlags is set.
46     */
47    virtual void getConstantColorComponents(GrColor* color, uint32_t* validFlags) const = 0;
48
49    /** This object, besides creating back-end-specific helper objects, is used for run-time-type-
50        identification. The factory should be an instance of templated class,
51        GrTBackendEffectFactory. It is templated on the subclass of GrProcessor. The subclass must
52        have a nested type (or typedef) named GLProcessor which will be the subclass of
53        GrGLProcessor created by the factory.
54
55        Example:
56        class MyCustomEffect : public GrProcessor {
57        ...
58            virtual const GrBackendEffectFactory& getFactory() const SK_OVERRIDE {
59                return GrTBackendEffectFactory<MyCustomEffect>::getInstance();
60            }
61        ...
62        };
63     */
64    virtual const GrBackendProcessorFactory& getFactory() const = 0;
65
66    /** Returns true if this and other effect conservatively draw identically. It can only return
67        true when the two effects are of the same subclass (i.e. they return the same object from
68        from getFactory()).
69
70        A return value of true from isEqual() should not be used to test whether the effects would
71        generate the same shader code. To test for identical code generation use the effects' keys
72        computed by the GrBackendEffectFactory.
73     */
74    bool isEqual(const GrProcessor& other) const {
75        if (&this->getFactory() != &other.getFactory()) {
76            return false;
77        }
78        bool result = this->onIsEqual(other);
79#ifdef SK_DEBUG
80        if (result) {
81            this->assertEquality(other);
82        }
83#endif
84        return result;
85    }
86
87    /** Human-meaningful string to identify this effect; may be embedded
88        in generated shader code. */
89    const char* name() const;
90
91    int numTransforms() const { return fCoordTransforms.count(); }
92
93    /** Returns the coordinate transformation at index. index must be valid according to
94        numTransforms(). */
95    const GrCoordTransform& coordTransform(int index) const { return *fCoordTransforms[index]; }
96
97    int numTextures() const { return fTextureAccesses.count(); }
98
99    /** Returns the access pattern for the texture at index. index must be valid according to
100        numTextures(). */
101    const GrTextureAccess& textureAccess(int index) const { return *fTextureAccesses[index]; }
102
103    /** Shortcut for textureAccess(index).texture(); */
104    GrTexture* texture(int index) const { return this->textureAccess(index).getTexture(); }
105
106    /** Will this effect read the fragment position? */
107    bool willReadFragmentPosition() const { return fWillReadFragmentPosition; }
108
109    void* operator new(size_t size);
110    void operator delete(void* target);
111
112    void* operator new(size_t size, void* placement) {
113        return ::operator new(size, placement);
114    }
115    void operator delete(void* target, void* placement) {
116        ::operator delete(target, placement);
117    }
118
119    /**
120      * Helper for down-casting to a GrProcessor subclass
121      */
122    template <typename T> const T& cast() const { return *static_cast<const T*>(this); }
123
124protected:
125    /**
126     * Subclasses call this from their constructor to register coordinate transformations. The
127     * effect subclass manages the lifetime of the transformations (this function only stores a
128     * pointer). The GrCoordTransform is typically a member field of the GrProcessor subclass. When
129     * the matrix has perspective, the transformed coordinates will have 3 components. Otherwise
130     * they'll have 2. This must only be called from the constructor because GrProcessors are
131     * immutable.
132     */
133    void addCoordTransform(const GrCoordTransform* coordTransform);
134
135    /**
136     * Subclasses call this from their constructor to register GrTextureAccesses. The effect
137     * subclass manages the lifetime of the accesses (this function only stores a pointer). The
138     * GrTextureAccess is typically a member field of the GrProcessor subclass. This must only be
139     * called from the constructor because GrProcessors are immutable.
140     */
141    void addTextureAccess(const GrTextureAccess* textureAccess);
142
143    GrProcessor()
144        : fWillReadFragmentPosition(false) {}
145
146    /**
147     * If the effect will generate a backend-specific effect that will read the fragment position
148     * in the FS then it must call this method from its constructor. Otherwise, the request to
149     * access the fragment position will be denied.
150     */
151    void setWillReadFragmentPosition() { fWillReadFragmentPosition = true; }
152
153private:
154    SkDEBUGCODE(void assertEquality(const GrProcessor& other) const;)
155
156    /** Subclass implements this to support isEqual(). It will only be called if it is known that
157        the two effects are of the same subclass (i.e. they return the same object from
158        getFactory()).*/
159    virtual bool onIsEqual(const GrProcessor& other) const = 0;
160
161    friend class GrGeometryProcessor; // to set fRequiresVertexShader and build fVertexAttribTypes.
162
163    SkSTArray<4, const GrCoordTransform*, true>  fCoordTransforms;
164    SkSTArray<4, const GrTextureAccess*, true>   fTextureAccesses;
165    bool                                         fWillReadFragmentPosition;
166
167    typedef GrProgramElement INHERITED;
168};
169
170class GrFragmentProcessor : public GrProcessor {
171public:
172    GrFragmentProcessor()
173        : INHERITED()
174        , fWillReadDstColor(false)
175        , fWillUseInputColor(true) {}
176
177    virtual const GrBackendFragmentProcessorFactory& getFactory() const = 0;
178
179    /** Will this effect read the destination pixel value? */
180    bool willReadDstColor() const { return fWillReadDstColor; }
181
182    /** Will this effect read the source color value? */
183    bool willUseInputColor() const { return fWillUseInputColor; }
184
185protected:
186    /**
187     * If the effect subclass will read the destination pixel value then it must call this function
188     * from its constructor. Otherwise, when its generated backend-specific effect class attempts
189     * to generate code that reads the destination pixel it will fail.
190     */
191    void setWillReadDstColor() { fWillReadDstColor = true; }
192
193    /**
194     * If the effect will generate a result that does not depend on the input color value then it
195     * must call this function from its constructor. Otherwise, when its generated backend-specific
196     * code might fail during variable binding due to unused variables.
197     */
198    void setWillNotUseInputColor() { fWillUseInputColor = false; }
199
200private:
201    bool                                         fWillReadDstColor;
202    bool                                         fWillUseInputColor;
203
204    typedef GrProcessor INHERITED;
205};
206
207/**
208 * This creates an effect outside of the effect memory pool. The effect's destructor will be called
209 * at global destruction time. NAME will be the name of the created GrProcessor.
210 */
211#define GR_CREATE_STATIC_FRAGMENT_PROCESSOR(NAME, EFFECT_CLASS, ARGS)                             \
212static SkAlignedSStorage<sizeof(EFFECT_CLASS)> g_##NAME##_Storage;                                \
213static GrFragmentProcessor*                                                                       \
214NAME SkNEW_PLACEMENT_ARGS(g_##NAME##_Storage.get(), EFFECT_CLASS, ARGS);                          \
215static SkAutoTDestroy<GrFragmentProcessor> NAME##_ad(NAME);
216
217#endif
218