2 * Copyright 2012 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #ifndef GrGLShaderBuilder_DEFINED
9 #define GrGLShaderBuilder_DEFINED
11 #include "GrAllocator.h"
12 #include "GrBackendEffectFactory.h"
16 #include "gl/GrGLProgramDesc.h"
17 #include "gl/GrGLProgramEffects.h"
18 #include "gl/GrGLSL.h"
19 #include "gl/GrGLProgramDataManager.h"
23 class GrGLContextInfo;
25 class GrGLProgramDesc;
28 Contains all the incremental state of a shader as it is being built,as well as helpers to
29 manipulate that state.
31 class GrGLShaderBuilder {
33 typedef GrTAllocator<GrGLShaderVar> VarArray;
34 typedef GrGLProgramEffects::TextureSampler TextureSampler;
35 typedef GrGLProgramEffects::TransformedCoordsArray TransformedCoordsArray;
37 enum ShaderVisibility {
38 kVertex_Visibility = 0x1,
39 kGeometry_Visibility = 0x2,
40 kFragment_Visibility = 0x4,
43 typedef GrGLProgramDataManager::UniformHandle UniformHandle;
45 // Handles for program uniforms (other than per-effect uniforms)
46 struct BuiltinUniformHandles {
47 UniformHandle fViewMatrixUni;
48 UniformHandle fRTAdjustmentUni;
49 UniformHandle fColorUni;
50 UniformHandle fCoverageUni;
52 // We use the render target height to provide a y-down frag coord when specifying
53 // origin_upper_left is not supported.
54 UniformHandle fRTHeightUni;
56 // Uniforms for computing texture coords to do the dst-copy lookup
57 UniformHandle fDstCopyTopLeftUni;
58 UniformHandle fDstCopyScaleUni;
59 UniformHandle fDstCopySamplerUni;
63 GrGLShaderVar fVariable;
68 // This uses an allocator rather than array so that the GrGLShaderVars don't move in memory
69 // after they are inserted. Users of GrGLShaderBuilder get refs to the vars and ptrs to their
70 // name strings. Otherwise, we'd have to hand out copies.
71 typedef GrTAllocator<UniformInfo> UniformInfoArray;
73 /** Generates a shader program.
75 * The program implements what is specified in the stages given as input.
76 * After successful generation, the builder result objects are available
78 * @return true if generation was successful.
80 bool genProgram(const GrEffectStage* inColorStages[],
81 const GrEffectStage* inCoverageStages[]);
83 // Below are the results of the shader generation.
85 GrGLProgramEffects* getColorEffects() const { SkASSERT(fProgramID); return fColorEffects.get(); }
86 GrGLProgramEffects* getCoverageEffects() const { SkASSERT(fProgramID); return fCoverageEffects.get(); }
87 const BuiltinUniformHandles& getBuiltinUniformHandles() const {
89 return fUniformHandles;
91 GrGLuint getProgramID() const { SkASSERT(fProgramID); return fProgramID; }
92 bool hasVertexShader() const { SkASSERT(fProgramID); return fHasVertexShader; }
93 int getTexCoordSetCount() const { SkASSERT(fProgramID); return fTexCoordSetCnt; }
94 const UniformInfoArray& getUniformInfos() const { return fUniforms; }
96 virtual ~GrGLShaderBuilder() {}
99 * Use of these features may require a GLSL extension to be enabled. Shaders may not compile
100 * if code is added that uses one of these features without calling enableFeature()
103 kStandardDerivatives_GLSLFeature = 0,
105 kLastGLSLFeature = kStandardDerivatives_GLSLFeature
109 * If the feature is supported then true is returned and any necessary #extension declarations
110 * are added to the shaders. If the feature is not supported then false will be returned.
112 bool enableFeature(GLSLFeature);
115 * Called by GrGLEffects to add code the fragment shader.
117 void fsCodeAppendf(const char format[], ...) SK_PRINTF_LIKE(2, 3) {
119 va_start(args, format);
120 fFSCode.appendVAList(format, args);
124 void fsCodeAppend(const char* str) { fFSCode.append(str); }
126 /** Appends a 2D texture sample with projection if necessary. coordType must either be Vec2f or
127 Vec3f. The latter is interpreted as projective texture coords. The vec length and swizzle
128 order of the result depends on the GrTextureAccess associated with the TextureSampler. */
129 void appendTextureLookup(SkString* out,
130 const TextureSampler&,
131 const char* coordName,
132 GrSLType coordType = kVec2f_GrSLType) const;
134 /** Version of above that appends the result to the fragment shader code instead.*/
135 void fsAppendTextureLookup(const TextureSampler&,
136 const char* coordName,
137 GrSLType coordType = kVec2f_GrSLType);
140 /** Does the work of appendTextureLookup and modulates the result by modulation. The result is
141 always a vec4. modulation and the swizzle specified by TextureSampler must both be vec4 or
142 float. If modulation is "" or NULL it this function acts as though appendTextureLookup were
144 void fsAppendTextureLookupAndModulate(const char* modulation,
145 const TextureSampler&,
146 const char* coordName,
147 GrSLType coordType = kVec2f_GrSLType);
149 /** Emits a helper function outside of main() in the fragment shader. */
150 void fsEmitFunction(GrSLType returnType,
153 const GrGLShaderVar* args,
157 typedef uint8_t DstReadKey;
158 typedef uint8_t FragPosKey;
160 /** Returns a key for adding code to read the copy-of-dst color in service of effects that
161 require reading the dst. It must not return 0 because 0 indicates that there is no dst
162 copy read at all (in which case this function should not be called). */
163 static DstReadKey KeyForDstRead(const GrTexture* dstCopy, const GrGLCaps&);
165 /** Returns a key for reading the fragment location. This should only be called if there is an
166 effect that will requires the fragment position. If the fragment position is not required,
168 static FragPosKey KeyForFragmentPosition(const GrRenderTarget* dst, const GrGLCaps&);
170 /** If texture swizzling is available using tex parameters then it is preferred over mangling
171 the generated shader code. This potentially allows greater reuse of cached shaders. */
172 static const GrGLenum* GetTexParamSwizzle(GrPixelConfig config, const GrGLCaps& caps);
174 /** Add a uniform variable to the current program, that has visibility in one or more shaders.
175 visibility is a bitfield of ShaderVisibility values indicating from which shaders the
176 uniform should be accessible. At least one bit must be set. Geometry shader uniforms are not
177 supported at this time. The actual uniform name will be mangled. If outName is not NULL then
178 it will refer to the final uniform name after return. Use the addUniformArray variant to add
179 an array of uniforms. */
180 GrGLProgramDataManager::UniformHandle addUniform(uint32_t visibility,
183 const char** outName = NULL) {
184 return this->addUniformArray(visibility, type, name, GrGLShaderVar::kNonArray, outName);
186 GrGLProgramDataManager::UniformHandle addUniformArray(uint32_t visibility,
190 const char** outName = NULL);
192 const GrGLShaderVar& getUniformVariable(GrGLProgramDataManager::UniformHandle u) const {
193 return fUniforms[u.toShaderBuilderIndex()].fVariable;
197 * Shortcut for getUniformVariable(u).c_str()
199 const char* getUniformCStr(GrGLProgramDataManager::UniformHandle u) const {
200 return this->getUniformVariable(u).c_str();
204 * This returns a variable name to access the 2D, perspective correct version of the coords in
205 * the fragment shader. If the coordinates at index are 3-dimensional, it immediately emits a
206 * perspective divide into the fragment shader (xy / z) to convert them to 2D.
208 SkString ensureFSCoords2D(const TransformedCoordsArray&, int index);
210 /** Returns a variable name that represents the position of the fragment in the FS. The position
211 is in device space (e.g. 0,0 is the top left and pixel centers are at half-integers). */
212 const char* fragmentPosition();
214 /** Returns the variable name that holds the color of the destination pixel. This may be NULL if
215 no effect advertised that it will read the destination. */
216 const char* dstColor();
218 const GrGLContextInfo& ctxInfo() const;
221 * Helper for begining and ending a block in the fragment code. TODO: Make GrGLShaderBuilder
222 * aware of all blocks and turn single \t's into the correct number of tabs (or spaces) so that
223 * our shaders print pretty without effect writers tracking indentation.
227 FSBlock(GrGLShaderBuilder* builder) : fBuilder(builder) {
228 SkASSERT(NULL != builder);
229 fBuilder->fsCodeAppend("\t{\n");
233 fBuilder->fsCodeAppend("\t}\n");
236 GrGLShaderBuilder* fBuilder;
240 GrGLShaderBuilder(GrGpuGL*, const GrGLProgramDesc&);
242 GrGpuGL* gpu() const { return fGpu; }
244 const GrGLProgramDesc& desc() const { return fDesc; }
246 /** Add input/output variable declarations (i.e. 'varying') to the fragment shader. */
247 GrGLShaderVar& fsInputAppend() { return fFSInputs.push_back(); }
249 // Helper for emitEffects().
250 void createAndEmitEffects(GrGLProgramEffectsBuilder*,
251 const GrEffectStage* effectStages[],
253 const GrGLProgramDesc::EffectKeyProvider&,
254 GrGLSLExpr4* inOutFSColor);
256 // Generates a name for a variable. The generated string will be name prefixed by the prefix
257 // char (unless the prefix is '\0'). It also mangles the name to be stage-specific if we're
258 // generating stage code.
259 void nameVariable(SkString* out, char prefix, const char* name);
261 virtual bool compileAndAttachShaders(GrGLuint programId, SkTDArray<GrGLuint>* shaderIds) const;
263 virtual void bindProgramLocations(GrGLuint programId);
264 void resolveProgramLocations(GrGLuint programId);
266 void appendDecls(const VarArray&, SkString*) const;
267 void appendUniformDecls(ShaderVisibility, SkString*) const;
269 SkAutoTUnref<GrGLProgramEffects> fColorEffects;
270 SkAutoTUnref<GrGLProgramEffects> fCoverageEffects;
271 BuiltinUniformHandles fUniformHandles;
272 bool fHasVertexShader;
276 class CodeStage : SkNoncopyable {
278 CodeStage() : fNextIndex(0), fCurrentIndex(-1), fEffectStage(NULL) {}
280 bool inStageCode() const {
282 return NULL != fEffectStage;
285 const GrEffectStage* effectStage() const {
290 int stageIndex() const {
292 return fCurrentIndex;
295 class AutoStageRestore : SkNoncopyable {
297 AutoStageRestore(CodeStage* codeStage, const GrEffectStage* newStage) {
298 SkASSERT(NULL != codeStage);
299 fSavedIndex = codeStage->fCurrentIndex;
300 fSavedEffectStage = codeStage->fEffectStage;
302 if (NULL == newStage) {
303 codeStage->fCurrentIndex = -1;
305 codeStage->fCurrentIndex = codeStage->fNextIndex++;
307 codeStage->fEffectStage = newStage;
309 fCodeStage = codeStage;
311 ~AutoStageRestore() {
312 fCodeStage->fCurrentIndex = fSavedIndex;
313 fCodeStage->fEffectStage = fSavedEffectStage;
316 CodeStage* fCodeStage;
318 const GrEffectStage* fSavedEffectStage;
321 void validate() const { SkASSERT((NULL == fEffectStage) == (-1 == fCurrentIndex)); }
324 const GrEffectStage* fEffectStage;
328 * The base class will emit the fragment code that precedes the per-effect code and then call
329 * this function. The subclass can use it to insert additional fragment code that should
330 * execute before the effects' code and/or emit other shaders (e.g. geometry, vertex).
332 * The subclass can modify the initial color or coverage
334 virtual void emitCodeBeforeEffects(GrGLSLExpr4* color, GrGLSLExpr4* coverage) = 0;
337 * Adds code for effects and returns a GrGLProgramEffects* object. The caller is responsible for
338 * deleting it when finished. effectStages contains the effects to add. The effect key provider
339 * is used to communicate the key each effect created in its GenKey function. inOutFSColor
340 * specifies the input color to the first stage and is updated to be the output color of the
341 * last stage. The handles to texture samplers for effectStage[i] are added to
342 * effectSamplerHandles[i].
344 virtual GrGLProgramEffects* createAndEmitEffects(const GrEffectStage* effectStages[],
346 const GrGLProgramDesc::EffectKeyProvider&,
347 GrGLSLExpr4* inOutFSColor) = 0;
350 * Similar to emitCodeBeforeEffects() but called after per-effect code is emitted.
352 virtual void emitCodeAfterEffects() = 0;
354 /** Enables using the secondary color output and returns the name of the var in which it is
356 const char* enableSecondaryOutput();
357 /** Gets the name of the primary color output. */
358 const char* getColorOutputName() const;
361 * Compiles all the shaders, links them into a program, and writes the program id to the output
367 * Features that should only be enabled by GrGLShaderBuilder itself.
369 enum GLSLPrivateFeature {
370 kFragCoordConventions_GLSLPrivateFeature = kLastGLSLFeature + 1,
371 kLastGLSLPrivateFeature = kFragCoordConventions_GLSLPrivateFeature
373 bool enablePrivateFeature(GLSLPrivateFeature);
375 // If we ever have VS/GS features we can expand this to take a bitmask of ShaderVisibility and
376 // track the enables separately for each shader.
377 void addFSFeature(uint32_t featureBit, const char* extensionName);
379 // Interpretation of DstReadKey when generating code
381 kNoDstRead_DstReadKey = 0,
382 kYesDstRead_DstReadKeyBit = 0x1, // Set if we do a dst-copy-read.
383 kUseAlphaConfig_DstReadKeyBit = 0x2, // Set if dst-copy config is alpha only.
384 kTopLeftOrigin_DstReadKeyBit = 0x4, // Set if dst-copy origin is top-left.
388 kNoFragPosRead_FragPosKey = 0, // The fragment positition will not be needed.
389 kTopLeftFragPosRead_FragPosKey = 0x1,// Read frag pos relative to top-left.
390 kBottomLeftFragPosRead_FragPosKey = 0x2,// Read frag pos relative to bottom-left.
393 const GrGLProgramDesc& fDesc;
395 uint32_t fFSFeaturesAddedMask;
396 SkString fFSFunctions;
397 SkString fFSExtensions;
400 UniformInfoArray fUniforms;
404 bool fSetupFragPosition;
405 bool fTopLeftFragPosRead;
407 bool fHasCustomColorOutput;
408 bool fHasSecondaryOutput;
411 ////////////////////////////////////////////////////////////////////////////////
413 class GrGLFullShaderBuilder : public GrGLShaderBuilder {
415 GrGLFullShaderBuilder(GrGpuGL*, const GrGLProgramDesc&);
418 * Called by GrGLEffects to add code to one of the shaders.
420 void vsCodeAppendf(const char format[], ...) SK_PRINTF_LIKE(2, 3) {
422 va_start(args, format);
423 fVSCode.appendVAList(format, args);
427 void vsCodeAppend(const char* str) { fVSCode.append(str); }
429 /** Add a vertex attribute to the current program that is passed in from the vertex data.
430 Returns false if the attribute was already there, true otherwise. */
431 bool addAttribute(GrSLType type, const char* name);
433 /** Add a varying variable to the current program to pass values between vertex and fragment
434 shaders. If the last two parameters are non-NULL, they are filled in with the name
436 void addVarying(GrSLType type,
438 const char** vsOutName = NULL,
439 const char** fsInName = NULL);
441 /** Returns a vertex attribute that represents the vertex position in the VS. This is the
442 pre-matrix position and is commonly used by effects to compute texture coords via a matrix.
444 const GrGLShaderVar& positionAttribute() const { return *fPositionVar; }
446 /** Returns a vertex attribute that represents the local coords in the VS. This may be the same
447 as positionAttribute() or it may not be. It depends upon whether the rendering code
448 specified explicit local coords or not in the GrDrawState. */
449 const GrGLShaderVar& localCoordsAttribute() const { return *fLocalCoordsVar; }
452 * Are explicit local coordinates provided as input to the vertex shader.
454 bool hasExplicitLocalCoords() const { return (fLocalCoordsVar != fPositionVar); }
456 bool addEffectAttribute(int attributeIndex, GrSLType type, const SkString& name);
457 const SkString* getEffectAttributeName(int attributeIndex) const;
460 virtual void emitCodeBeforeEffects(GrGLSLExpr4* color, GrGLSLExpr4* coverage) SK_OVERRIDE;
462 virtual GrGLProgramEffects* createAndEmitEffects(const GrEffectStage* effectStages[],
464 const GrGLProgramDesc::EffectKeyProvider&,
465 GrGLSLExpr4* inOutFSColor) SK_OVERRIDE;
467 virtual void emitCodeAfterEffects() SK_OVERRIDE;
469 virtual bool compileAndAttachShaders(GrGLuint programId,
470 SkTDArray<GrGLuint>* shaderIds) const SK_OVERRIDE;
472 virtual void bindProgramLocations(GrGLuint programId) SK_OVERRIDE;
481 struct AttributePair {
482 void set(int index, const SkString& name) {
483 fIndex = index; fName = name;
488 SkSTArray<10, AttributePair, true> fEffectAttributes;
490 GrGLShaderVar* fPositionVar;
491 GrGLShaderVar* fLocalCoordsVar;
493 typedef GrGLShaderBuilder INHERITED;
496 ////////////////////////////////////////////////////////////////////////////////
498 class GrGLFragmentOnlyShaderBuilder : public GrGLShaderBuilder {
500 GrGLFragmentOnlyShaderBuilder(GrGpuGL*, const GrGLProgramDesc&);
502 int addTexCoordSets(int count);
505 virtual void emitCodeBeforeEffects(GrGLSLExpr4* color, GrGLSLExpr4* coverage) SK_OVERRIDE {}
507 virtual GrGLProgramEffects* createAndEmitEffects(const GrEffectStage* effectStages[],
509 const GrGLProgramDesc::EffectKeyProvider&,
510 GrGLSLExpr4* inOutFSColor) SK_OVERRIDE;
512 virtual void emitCodeAfterEffects() SK_OVERRIDE {}
514 typedef GrGLShaderBuilder INHERITED;