michael@0: /* michael@0: * Copyright 2012 Google Inc. michael@0: * michael@0: * Use of this source code is governed by a BSD-style license that can be michael@0: * found in the LICENSE file. michael@0: */ michael@0: michael@0: #ifndef GrGLShaderBuilder_DEFINED michael@0: #define GrGLShaderBuilder_DEFINED michael@0: michael@0: #include "GrAllocator.h" michael@0: #include "GrBackendEffectFactory.h" michael@0: #include "GrColor.h" michael@0: #include "GrEffect.h" michael@0: #include "SkTypes.h" michael@0: #include "gl/GrGLProgramEffects.h" michael@0: #include "gl/GrGLSL.h" michael@0: #include "gl/GrGLUniformManager.h" michael@0: michael@0: #include michael@0: michael@0: class GrGLContextInfo; michael@0: class GrEffectStage; michael@0: class GrGLProgramDesc; michael@0: michael@0: /** michael@0: Contains all the incremental state of a shader as it is being built,as well as helpers to michael@0: manipulate that state. michael@0: */ michael@0: class GrGLShaderBuilder { michael@0: public: michael@0: typedef GrTAllocator VarArray; michael@0: typedef GrBackendEffectFactory::EffectKey EffectKey; michael@0: typedef GrGLProgramEffects::TextureSampler TextureSampler; michael@0: typedef GrGLProgramEffects::TransformedCoordsArray TransformedCoordsArray; michael@0: typedef GrGLUniformManager::BuilderUniform BuilderUniform; michael@0: michael@0: enum ShaderVisibility { michael@0: kVertex_Visibility = 0x1, michael@0: kGeometry_Visibility = 0x2, michael@0: kFragment_Visibility = 0x4, michael@0: }; michael@0: michael@0: GrGLShaderBuilder(GrGpuGL*, GrGLUniformManager&, const GrGLProgramDesc&); michael@0: virtual ~GrGLShaderBuilder() {} michael@0: michael@0: /** michael@0: * Use of these features may require a GLSL extension to be enabled. Shaders may not compile michael@0: * if code is added that uses one of these features without calling enableFeature() michael@0: */ michael@0: enum GLSLFeature { michael@0: kStandardDerivatives_GLSLFeature = 0, michael@0: michael@0: kLastGLSLFeature = kStandardDerivatives_GLSLFeature michael@0: }; michael@0: michael@0: /** michael@0: * If the feature is supported then true is returned and any necessary #extension declarations michael@0: * are added to the shaders. If the feature is not supported then false will be returned. michael@0: */ michael@0: bool enableFeature(GLSLFeature); michael@0: michael@0: /** michael@0: * Called by GrGLEffects to add code the fragment shader. michael@0: */ michael@0: void fsCodeAppendf(const char format[], ...) SK_PRINTF_LIKE(2, 3) { michael@0: va_list args; michael@0: va_start(args, format); michael@0: fFSCode.appendVAList(format, args); michael@0: va_end(args); michael@0: } michael@0: michael@0: void fsCodeAppend(const char* str) { fFSCode.append(str); } michael@0: michael@0: /** Appends a 2D texture sample with projection if necessary. coordType must either be Vec2f or michael@0: Vec3f. The latter is interpreted as projective texture coords. The vec length and swizzle michael@0: order of the result depends on the GrTextureAccess associated with the TextureSampler. */ michael@0: void appendTextureLookup(SkString* out, michael@0: const TextureSampler&, michael@0: const char* coordName, michael@0: GrSLType coordType = kVec2f_GrSLType) const; michael@0: michael@0: /** Version of above that appends the result to the fragment shader code instead.*/ michael@0: void fsAppendTextureLookup(const TextureSampler&, michael@0: const char* coordName, michael@0: GrSLType coordType = kVec2f_GrSLType); michael@0: michael@0: michael@0: /** Does the work of appendTextureLookup and modulates the result by modulation. The result is michael@0: always a vec4. modulation and the swizzle specified by TextureSampler must both be vec4 or michael@0: float. If modulation is "" or NULL it this function acts as though appendTextureLookup were michael@0: called. */ michael@0: void fsAppendTextureLookupAndModulate(const char* modulation, michael@0: const TextureSampler&, michael@0: const char* coordName, michael@0: GrSLType coordType = kVec2f_GrSLType); michael@0: michael@0: /** Emits a helper function outside of main() in the fragment shader. */ michael@0: void fsEmitFunction(GrSLType returnType, michael@0: const char* name, michael@0: int argCnt, michael@0: const GrGLShaderVar* args, michael@0: const char* body, michael@0: SkString* outName); michael@0: michael@0: typedef uint8_t DstReadKey; michael@0: typedef uint8_t FragPosKey; michael@0: michael@0: /** Returns a key for adding code to read the copy-of-dst color in service of effects that michael@0: require reading the dst. It must not return 0 because 0 indicates that there is no dst michael@0: copy read at all (in which case this function should not be called). */ michael@0: static DstReadKey KeyForDstRead(const GrTexture* dstCopy, const GrGLCaps&); michael@0: michael@0: /** Returns a key for reading the fragment location. This should only be called if there is an michael@0: effect that will requires the fragment position. If the fragment position is not required, michael@0: the key is 0. */ michael@0: static FragPosKey KeyForFragmentPosition(const GrRenderTarget* dst, const GrGLCaps&); michael@0: michael@0: /** If texture swizzling is available using tex parameters then it is preferred over mangling michael@0: the generated shader code. This potentially allows greater reuse of cached shaders. */ michael@0: static const GrGLenum* GetTexParamSwizzle(GrPixelConfig config, const GrGLCaps& caps); michael@0: michael@0: /** Add a uniform variable to the current program, that has visibility in one or more shaders. michael@0: visibility is a bitfield of ShaderVisibility values indicating from which shaders the michael@0: uniform should be accessible. At least one bit must be set. Geometry shader uniforms are not michael@0: supported at this time. The actual uniform name will be mangled. If outName is not NULL then michael@0: it will refer to the final uniform name after return. Use the addUniformArray variant to add michael@0: an array of uniforms. michael@0: */ michael@0: GrGLUniformManager::UniformHandle addUniform(uint32_t visibility, michael@0: GrSLType type, michael@0: const char* name, michael@0: const char** outName = NULL) { michael@0: return this->addUniformArray(visibility, type, name, GrGLShaderVar::kNonArray, outName); michael@0: } michael@0: GrGLUniformManager::UniformHandle addUniformArray(uint32_t visibility, michael@0: GrSLType type, michael@0: const char* name, michael@0: int arrayCount, michael@0: const char** outName = NULL); michael@0: michael@0: const GrGLShaderVar& getUniformVariable(GrGLUniformManager::UniformHandle u) const { michael@0: return fUniformManager.getBuilderUniform(fUniforms, u).fVariable; michael@0: } michael@0: michael@0: /** michael@0: * Shortcut for getUniformVariable(u).c_str() michael@0: */ michael@0: const char* getUniformCStr(GrGLUniformManager::UniformHandle u) const { michael@0: return this->getUniformVariable(u).c_str(); michael@0: } michael@0: michael@0: /** michael@0: * This returns a variable name to access the 2D, perspective correct version of the coords in michael@0: * the fragment shader. If the coordinates at index are 3-dimensional, it immediately emits a michael@0: * perspective divide into the fragment shader (xy / z) to convert them to 2D. michael@0: */ michael@0: SkString ensureFSCoords2D(const TransformedCoordsArray&, int index); michael@0: michael@0: /** Returns a variable name that represents the position of the fragment in the FS. The position michael@0: is in device space (e.g. 0,0 is the top left and pixel centers are at half-integers). */ michael@0: const char* fragmentPosition(); michael@0: michael@0: /** Returns the color of the destination pixel. This may be NULL if no effect advertised michael@0: that it will read the destination. */ michael@0: const char* dstColor(); michael@0: michael@0: /** michael@0: * Interfaces used by GrGLProgram. michael@0: */ michael@0: const GrGLSLExpr4& getInputColor() const { michael@0: return fInputColor; michael@0: } michael@0: const GrGLSLExpr4& getInputCoverage() const { michael@0: return fInputCoverage; michael@0: } michael@0: michael@0: /** michael@0: * Adds code for effects and returns a GrGLProgramEffects* object. The caller is responsible for michael@0: * deleting it when finished. effectStages contains the effects to add. effectKeys[i] is the key michael@0: * generated from effectStages[i]. inOutFSColor specifies the input color to the first stage and michael@0: * is updated to be the output color of the last stage. michael@0: * The handles to texture samplers for effectStage[i] are added to michael@0: * effectSamplerHandles[i]. michael@0: */ michael@0: virtual GrGLProgramEffects* createAndEmitEffects(const GrEffectStage* effectStages[], michael@0: const EffectKey effectKeys[], michael@0: int effectCnt, michael@0: GrGLSLExpr4* inOutFSColor) = 0; michael@0: michael@0: const char* getColorOutputName() const; michael@0: const char* enableSecondaryOutput(); michael@0: michael@0: GrGLUniformManager::UniformHandle getRTHeightUniform() const { return fRTHeightUniform; } michael@0: GrGLUniformManager::UniformHandle getDstCopyTopLeftUniform() const { michael@0: return fDstCopyTopLeftUniform; michael@0: } michael@0: GrGLUniformManager::UniformHandle getDstCopyScaleUniform() const { michael@0: return fDstCopyScaleUniform; michael@0: } michael@0: GrGLUniformManager::UniformHandle getColorUniform() const { return fColorUniform; } michael@0: GrGLUniformManager::UniformHandle getCoverageUniform() const { return fCoverageUniform; } michael@0: GrGLUniformManager::UniformHandle getDstCopySamplerUniform() const { michael@0: return fDstCopySamplerUniform; michael@0: } michael@0: michael@0: bool finish(GrGLuint* outProgramId); michael@0: michael@0: const GrGLContextInfo& ctxInfo() const; michael@0: michael@0: /** michael@0: * Helper for begining and ending a block in the fragment code. TODO: Make GrGLShaderBuilder michael@0: * aware of all blocks and turn single \t's into the correct number of tabs (or spaces) so that michael@0: * our shaders print pretty without effect writers tracking indentation. michael@0: */ michael@0: class FSBlock { michael@0: public: michael@0: FSBlock(GrGLShaderBuilder* builder) : fBuilder(builder) { michael@0: SkASSERT(NULL != builder); michael@0: fBuilder->fsCodeAppend("\t{\n"); michael@0: } michael@0: michael@0: ~FSBlock() { michael@0: fBuilder->fsCodeAppend("\t}\n"); michael@0: } michael@0: private: michael@0: GrGLShaderBuilder* fBuilder; michael@0: }; michael@0: michael@0: protected: michael@0: GrGpuGL* gpu() const { return fGpu; } michael@0: michael@0: void setInputColor(const GrGLSLExpr4& inputColor) { fInputColor = inputColor; } michael@0: void setInputCoverage(const GrGLSLExpr4& inputCoverage) { fInputCoverage = inputCoverage; } michael@0: michael@0: /** Add input/output variable declarations (i.e. 'varying') to the fragment shader. */ michael@0: GrGLShaderVar& fsInputAppend() { return fFSInputs.push_back(); } michael@0: michael@0: // Generates a name for a variable. The generated string will be name prefixed by the prefix michael@0: // char (unless the prefix is '\0'). It also mangles the name to be stage-specific if we're michael@0: // generating stage code. michael@0: void nameVariable(SkString* out, char prefix, const char* name); michael@0: michael@0: // Helper for emitEffects(). michael@0: void createAndEmitEffects(GrGLProgramEffectsBuilder*, michael@0: const GrEffectStage* effectStages[], michael@0: const EffectKey effectKeys[], michael@0: int effectCnt, michael@0: GrGLSLExpr4* inOutFSColor); michael@0: michael@0: virtual bool compileAndAttachShaders(GrGLuint programId, SkTDArray* shaderIds) const; michael@0: virtual void bindProgramLocations(GrGLuint programId) const; michael@0: michael@0: void appendDecls(const VarArray&, SkString*) const; michael@0: void appendUniformDecls(ShaderVisibility, SkString*) const; michael@0: michael@0: private: michael@0: class CodeStage : public SkNoncopyable { michael@0: public: michael@0: CodeStage() : fNextIndex(0), fCurrentIndex(-1), fEffectStage(NULL) {} michael@0: michael@0: bool inStageCode() const { michael@0: this->validate(); michael@0: return NULL != fEffectStage; michael@0: } michael@0: michael@0: const GrEffectStage* effectStage() const { michael@0: this->validate(); michael@0: return fEffectStage; michael@0: } michael@0: michael@0: int stageIndex() const { michael@0: this->validate(); michael@0: return fCurrentIndex; michael@0: } michael@0: michael@0: class AutoStageRestore : public SkNoncopyable { michael@0: public: michael@0: AutoStageRestore(CodeStage* codeStage, const GrEffectStage* newStage) { michael@0: SkASSERT(NULL != codeStage); michael@0: fSavedIndex = codeStage->fCurrentIndex; michael@0: fSavedEffectStage = codeStage->fEffectStage; michael@0: michael@0: if (NULL == newStage) { michael@0: codeStage->fCurrentIndex = -1; michael@0: } else { michael@0: codeStage->fCurrentIndex = codeStage->fNextIndex++; michael@0: } michael@0: codeStage->fEffectStage = newStage; michael@0: michael@0: fCodeStage = codeStage; michael@0: } michael@0: ~AutoStageRestore() { michael@0: fCodeStage->fCurrentIndex = fSavedIndex; michael@0: fCodeStage->fEffectStage = fSavedEffectStage; michael@0: } michael@0: private: michael@0: CodeStage* fCodeStage; michael@0: int fSavedIndex; michael@0: const GrEffectStage* fSavedEffectStage; michael@0: }; michael@0: private: michael@0: void validate() const { SkASSERT((NULL == fEffectStage) == (-1 == fCurrentIndex)); } michael@0: int fNextIndex; michael@0: int fCurrentIndex; michael@0: const GrEffectStage* fEffectStage; michael@0: } fCodeStage; michael@0: michael@0: /** michael@0: * Features that should only be enabled by GrGLShaderBuilder itself. michael@0: */ michael@0: enum GLSLPrivateFeature { michael@0: kFragCoordConventions_GLSLPrivateFeature = kLastGLSLFeature + 1, michael@0: kEXTShaderFramebufferFetch_GLSLPrivateFeature, michael@0: kNVShaderFramebufferFetch_GLSLPrivateFeature, michael@0: }; michael@0: bool enablePrivateFeature(GLSLPrivateFeature); michael@0: michael@0: // If we ever have VS/GS features we can expand this to take a bitmask of ShaderVisibility and michael@0: // track the enables separately for each shader. michael@0: void addFSFeature(uint32_t featureBit, const char* extensionName); michael@0: michael@0: // Interpretation of DstReadKey when generating code michael@0: enum { michael@0: kNoDstRead_DstReadKey = 0, michael@0: kYesDstRead_DstReadKeyBit = 0x1, // Set if we do a dst-copy-read. michael@0: kUseAlphaConfig_DstReadKeyBit = 0x2, // Set if dst-copy config is alpha only. michael@0: kTopLeftOrigin_DstReadKeyBit = 0x4, // Set if dst-copy origin is top-left. michael@0: }; michael@0: michael@0: enum { michael@0: kNoFragPosRead_FragPosKey = 0, // The fragment positition will not be needed. michael@0: kTopLeftFragPosRead_FragPosKey = 0x1,// Read frag pos relative to top-left. michael@0: kBottomLeftFragPosRead_FragPosKey = 0x2,// Read frag pos relative to bottom-left. michael@0: }; michael@0: michael@0: GrGpuGL* fGpu; michael@0: GrGLUniformManager& fUniformManager; michael@0: uint32_t fFSFeaturesAddedMask; michael@0: SkString fFSFunctions; michael@0: SkString fFSExtensions; michael@0: VarArray fFSInputs; michael@0: VarArray fFSOutputs; michael@0: GrGLUniformManager::BuilderUniformArray fUniforms; michael@0: michael@0: SkString fFSCode; michael@0: michael@0: bool fSetupFragPosition; michael@0: GrGLUniformManager::UniformHandle fDstCopySamplerUniform; michael@0: michael@0: GrGLSLExpr4 fInputColor; michael@0: GrGLSLExpr4 fInputCoverage; michael@0: michael@0: bool fHasCustomColorOutput; michael@0: bool fHasSecondaryOutput; michael@0: michael@0: GrGLUniformManager::UniformHandle fRTHeightUniform; michael@0: GrGLUniformManager::UniformHandle fDstCopyTopLeftUniform; michael@0: GrGLUniformManager::UniformHandle fDstCopyScaleUniform; michael@0: GrGLUniformManager::UniformHandle fColorUniform; michael@0: GrGLUniformManager::UniformHandle fCoverageUniform; michael@0: michael@0: bool fTopLeftFragPosRead; michael@0: }; michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: class GrGLFullShaderBuilder : public GrGLShaderBuilder { michael@0: public: michael@0: GrGLFullShaderBuilder(GrGpuGL*, GrGLUniformManager&, const GrGLProgramDesc&); michael@0: michael@0: /** michael@0: * Called by GrGLEffects to add code to one of the shaders. michael@0: */ michael@0: void vsCodeAppendf(const char format[], ...) SK_PRINTF_LIKE(2, 3) { michael@0: va_list args; michael@0: va_start(args, format); michael@0: fVSCode.appendVAList(format, args); michael@0: va_end(args); michael@0: } michael@0: michael@0: void vsCodeAppend(const char* str) { fVSCode.append(str); } michael@0: michael@0: /** Add a vertex attribute to the current program that is passed in from the vertex data. michael@0: Returns false if the attribute was already there, true otherwise. */ michael@0: bool addAttribute(GrSLType type, const char* name); michael@0: michael@0: /** Add a varying variable to the current program to pass values between vertex and fragment michael@0: shaders. If the last two parameters are non-NULL, they are filled in with the name michael@0: generated. */ michael@0: void addVarying(GrSLType type, michael@0: const char* name, michael@0: const char** vsOutName = NULL, michael@0: const char** fsInName = NULL); michael@0: michael@0: /** Returns a vertex attribute that represents the vertex position in the VS. This is the michael@0: pre-matrix position and is commonly used by effects to compute texture coords via a matrix. michael@0: */ michael@0: const GrGLShaderVar& positionAttribute() const { return *fPositionVar; } michael@0: michael@0: /** Returns a vertex attribute that represents the local coords in the VS. This may be the same michael@0: as positionAttribute() or it may not be. It depends upon whether the rendering code michael@0: specified explicit local coords or not in the GrDrawState. */ michael@0: const GrGLShaderVar& localCoordsAttribute() const { return *fLocalCoordsVar; } michael@0: michael@0: /** michael@0: * Are explicit local coordinates provided as input to the vertex shader. michael@0: */ michael@0: bool hasExplicitLocalCoords() const { return (fLocalCoordsVar != fPositionVar); } michael@0: michael@0: bool addEffectAttribute(int attributeIndex, GrSLType type, const SkString& name); michael@0: const SkString* getEffectAttributeName(int attributeIndex) const; michael@0: michael@0: virtual GrGLProgramEffects* createAndEmitEffects( michael@0: const GrEffectStage* effectStages[], michael@0: const EffectKey effectKeys[], michael@0: int effectCnt, michael@0: GrGLSLExpr4* inOutFSColor) SK_OVERRIDE; michael@0: michael@0: GrGLUniformManager::UniformHandle getViewMatrixUniform() const { michael@0: return fViewMatrixUniform; michael@0: } michael@0: michael@0: protected: michael@0: virtual bool compileAndAttachShaders(GrGLuint programId, SkTDArray* shaderIds) const SK_OVERRIDE; michael@0: virtual void bindProgramLocations(GrGLuint programId) const SK_OVERRIDE; michael@0: michael@0: private: michael@0: const GrGLProgramDesc& fDesc; michael@0: VarArray fVSAttrs; michael@0: VarArray fVSOutputs; michael@0: VarArray fGSInputs; michael@0: VarArray fGSOutputs; michael@0: michael@0: SkString fVSCode; michael@0: michael@0: struct AttributePair { michael@0: void set(int index, const SkString& name) { michael@0: fIndex = index; fName = name; michael@0: } michael@0: int fIndex; michael@0: SkString fName; michael@0: }; michael@0: SkSTArray<10, AttributePair, true> fEffectAttributes; michael@0: michael@0: GrGLUniformManager::UniformHandle fViewMatrixUniform; michael@0: michael@0: GrGLShaderVar* fPositionVar; michael@0: GrGLShaderVar* fLocalCoordsVar; michael@0: michael@0: typedef GrGLShaderBuilder INHERITED; michael@0: }; michael@0: michael@0: //////////////////////////////////////////////////////////////////////////////// michael@0: michael@0: class GrGLFragmentOnlyShaderBuilder : public GrGLShaderBuilder { michael@0: public: michael@0: GrGLFragmentOnlyShaderBuilder(GrGpuGL*, GrGLUniformManager&, const GrGLProgramDesc&); michael@0: michael@0: int getNumTexCoordSets() const { return fNumTexCoordSets; } michael@0: int addTexCoordSets(int count); michael@0: michael@0: virtual GrGLProgramEffects* createAndEmitEffects( michael@0: const GrEffectStage* effectStages[], michael@0: const EffectKey effectKeys[], michael@0: int effectCnt, michael@0: GrGLSLExpr4* inOutFSColor) SK_OVERRIDE; michael@0: michael@0: private: michael@0: int fNumTexCoordSets; michael@0: michael@0: typedef GrGLShaderBuilder INHERITED; michael@0: }; michael@0: michael@0: #endif