// CreateVertexShaderFromFile Shader* RendererGL::CreateVertexShaderFromFile(const char* VertexFileName, const char* VertexMain, ShaderVersion eVVersion) { CGprogram CgVertexProgram = cgCreateProgramFromFile ( m_CgContext, /* Cg runtime context */ CG_SOURCE, /* Program in human-readable form */ VertexFileName, /* Name of file containing program */ m_CgVertexProfile, /* Profile: OpenGL ARB vertex program */ VertexMain, /* Entry function name */ NULL ); /* No extra compiler options */ checkForCgError("creating vertex program from string"); if (!CgVertexProgram) return NULL; cgGLLoadProgram(CgVertexProgram); checkForCgError("loading vertex program"); Shader *shader = KGE_NEW(ShaderGL)(CgVertexProgram, 0, NULL, NULL); return shader; }
INT WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { g_cgContext = cgCreateContext(); checkForCgError("creating context"); cgSetParameterSettingMode(g_cgContext, CG_DEFERRED_PARAMETER_SETTING); DXUTSetCallbackDeviceReset(OnResetDevice); DXUTSetCallbackDeviceLost(OnLostDevice); DXUTSetCallbackFrameRender(OnFrameRender); /* Parse command line, handle default hotkeys, and show messages. */ DXUTInit(); DXUTCreateWindow(g_strWindowTitleW); /* Display 400x400 window. */ DXUTCreateDevice(D3DADAPTER_DEFAULT, true, 400, 400); DXUTMainLoop(); cgDestroyProgram(g_cgVertexProgram); checkForCgError("destroying vertex program"); cgDestroyContext(g_cgContext); return DXUTGetExitCode(); }
static HRESULT CALLBACK OnResetDevice(IDirect3DDevice9* pDev, const D3DSURFACE_DESC* backBuf, void* userContext) { cgD3D9SetDevice(pDev); checkForCgError("setting Direct3D device"); static int firstTime = 1; if (firstTime) { /* Cg runtime resources such as CGprogram and CGparameter handles survive a device reset so we just need to compile a Cg program just once. We do however need to unload Cg programs with cgD3DUnloadProgram upon when a Direct3D device is lost and load Cg programs every Direct3D device reset with cgD3D9UnloadProgram. */ createCgPrograms(); firstTime = 0; } /* false below means "no parameter shadowing" */ cgD3D9LoadProgram(g_cgVertexProgram, false, 0); checkForCgError("loading vertex program"); bool bRet; bRet = init(pDev); if (bRet) return S_OK; else return S_FALSE; }
void Scene::loadShader() { std::string sourcePtr = read("vshader.cg"); auto optimal = cgD3D11GetOptimalOptions(mCgVertexShaderProfile); mVertexShaderId = cgCreateProgram(mCgContext, CG_SOURCE, sourcePtr.c_str(), mCgVertexShaderProfile, "main", optimal); if(mVertexShaderId != nullptr) { optimal = cgD3D11GetOptimalOptions(mCgFragmentShaderProfile); HRESULT res = cgD3D11LoadProgram(mVertexShaderId, NULL); CGerror error; const char *errorString = cgGetLastErrorString(&error); sourcePtr = read("fshader.cg"); mFragmentShaderId = cgCreateProgram(mCgContext, CG_SOURCE, sourcePtr.c_str(), mCgFragmentShaderProfile, "main", optimal); errorString = cgGetLastErrorString(&error); res = cgD3D11LoadProgram(mFragmentShaderId, NULL); } // here the uniform can be set CGparameter location = cgGetNamedParameter(mVertexShaderId, "ambient"); checkForCgError("could not get uniform color location", mCgContext, false); cgSetParameter4fv(location, glm::value_ptr(glm::vec4(1.0,1.0,1.0,1.0))); checkForCgError("could not set uniform color", mCgContext, false); bindShader(mVertexShaderId, mFragmentShaderId); }
static void setEmissiveLightColorOnly(void) { const float zero[3] = {0.0, 0.0, 0.0}; cgSetParameter3fv(myCgFragmentParam_Ke, myLightColor); checkForCgError("setting Ke parameter"); cgSetParameter3fv(myCgFragmentParam_Ka, zero); checkForCgError("setting Ka parameter"); cgSetParameter3fv(myCgFragmentParam_Kd, zero); checkForCgError("setting Kd parameter"); cgSetParameter3fv(myCgFragmentParam_Ks, zero); checkForCgError("setting Ks parameter"); cgSetParameter1f(myCgFragmentParam_shininess, 0); checkForCgError("setting shininess parameter"); }
//------------------------------------------------------------------------------------ // //------------------------------------------------------------------------------------ bool ShaderGL::SetConstant(ShaderHandle Handler, const int* Values, u32 Count) { cgSetParameterValueir((CGparameter)Handler, Count, Values); checkForCgError("cgSetParameterValueic"); return true; } // SetVarible
//----------------------------------------------------------------------- CgProgramFactory::~CgProgramFactory() { //cgDestroyContext(mCgContext); // Check for errors checkForCgError("CgProgramFactory::~CgProgramFactory", "Unable to destroy Cg context: ", mCgContext); }
//----------------------------------------------------------------------- CgProgramFactory::CgProgramFactory() { mCgContext = cgCreateContext(); // Check for errors checkForCgError("CgProgramFactory::CgProgramFactory", "Unable to create initial Cg context: ", mCgContext); }
//----------------------------------------------------------------------- void CgProgram::loadFromSource(void) { // Create Cg Program selectProfile(); if (mSelectedCgProfile == CG_PROFILE_UNKNOWN) { LogManager::getSingleton().logMessage( "Attempted to load Cg program '" + mName + "', but no suported " "profile was found. "); return; } buildArgs(); // deal with includes String sourceToUse = resolveCgIncludes(mSource, this, mFilename); mCgProgram = cgCreateProgram(mCgContext, CG_SOURCE, sourceToUse.c_str(), mSelectedCgProfile, mEntryPoint.c_str(), const_cast<const char**>(mCgArguments)); // Test //LogManager::getSingleton().logMessage(cgGetProgramString(mCgProgram, CG_COMPILED_PROGRAM)); // Check for errors checkForCgError("CgProgram::loadFromSource", "Unable to compile Cg program " + mName + ": ", mCgContext); }
int main(int argc,char** argv) { diff_seconds(); srand(time(NULL)); glutInit(&argc, argv); glutInitDisplayMode( GLUT_DEPTH | GLUT_DOUBLE |GLUT_RGB); glutInitWindowSize (900,600); glutInitWindowPosition (240, 40); glutCreateWindow ("E16 - Partikelsystem"); glutKeyboardFunc(keyboard); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_COLOR_MATERIAL); init(); glutDisplayFunc(display); glutIdleFunc(idle); glEnable(GL_DEPTH_TEST); /********************************************/ cg_context = cgCreateContext(); checkForCgError("creating context"); cg_vertex_profile = cgGLGetLatestProfile(CG_GL_VERTEX); cgGLSetOptimalOptions(cg_vertex_profile); checkForCgError("selecting vertex profile"); cg_vertex_program = cgCreateProgramFromFile(cg_context, CG_SOURCE, "vertex.cg", cg_vertex_profile, "more_complex_vertex_shader", NULL); checkForCgError("creating vertex program from file"); cgGLLoadProgram(cg_vertex_program); checkForCgError("loading vertex program"); /**************************************************/ cg_parameter_vertex_velocity = cgGetNamedParameter(cg_vertex_program, "Texture0"); cg_parameter_vertex_time = cgGetNamedParameter(cg_vertex_program, "Texture1"); glutMainLoop(); return 0; }
int main(int argc, char **argv) { glutInitWindowSize(600, 600); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInit(&argc, argv); glutCreateWindow("Per vertex lighting (Gouraud shading)"); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutReshapeFunc(reshape); glClearColor(0.0, 0.0, 0.0, 1.0); cg_context = cgCreateContext(); checkForCgError("creating context"); cg_vertex_profile = cgGLGetLatestProfile(CG_GL_VERTEX); cgGLSetOptimalOptions(cg_vertex_profile); checkForCgError("selecting vertex profile"); cg_vertex_program = cgCreateProgramFromFile(cg_context, CG_SOURCE, "E12_vertex.cg", cg_vertex_profile, "per_vertex_lighting", NULL); checkForCgError("creating vertex program from file"); cgGLLoadProgram(cg_vertex_program); checkForCgError("loading vertex program"); GET_PARAM(modelview_proj); GET_PARAM(translation); GET_PARAM(ambient_light); GET_PARAM(light_color); GET_PARAM(light_position); GET_PARAM(camera_position); GET_PARAM(Ke); GET_PARAM(Ka); GET_PARAM(Kd); GET_PARAM(Ks); GET_PARAM(exponent); glEnable(GL_DEPTH_TEST); glutMainLoop(); return 0; }
//------------------------------------------------------------ // Get the pointer for accessing constants in the shader code. //------------------------------------------------------------ ShaderHandle ShaderGL::GetConstatnt(const char* Name) { ShaderHandle sh = (ShaderHandle)cgGetNamedParameter(m_Program, Name); checkForCgError("GetConstant"); if (!sh) io::Logger::Warning("%s shader parameter not found.", Name); return sh; } // GetConstatnt
void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); cgGLBindProgram(cg_vertex_program); checkForCgError("binding vertex program"); cgGLEnableProfile(cg_vertex_profile); checkForCgError("enabling vertex profile"); // parameter //cgGLSetParameter1f(cg_parameter_vertex_scale_factor, 0.7); //cgGLSetParameter1f(cg_parameter_vertex_rotation, rotation); // Zeit die seit dem rendern des letzten Bildes vergangen ist: cgGLEnableTextureParameter(cg_parameter_vertex_time); t = diff_seconds(); glVertex2f(0.0f, 0.0f); glTexCoord1f(Particle->t); cgGLDisableTextureParameter(cg_parameter_vertex_time); // Berechnung der Framerate mit Hilfe der Zeitmessungsfunktion: frames++; timer += t; if (timer > 1.0) { printf("Frames per second: %i\n", frames); timer -= 1.0; frames = 0; printf("Number of particles: %d\n", water_list.size()); } //cgGLEnableTextureParameter(cg_parameter_vertex_velocity); drawParticles(water_list,water_tex); //glVertex2f(0.0f, 0.0f); //glTexCoord3fv(Particle->velocity); //cgGLDisableTextureParameter(cg_parameter_vertex_velocity); cgGLDisableProfile(cg_vertex_profile); checkForCgError("disabling vertex profile"); glutSwapBuffers(); }
void set_light_source_material() { GLfloat zero[3] = {0.0, 0.0, 0.0}; cgSetParameter3fv(cg_vertex_param_Ke, light_color); checkForCgError("setting Ke parameter"); cgSetParameter3fv(cg_vertex_param_Ka, zero); checkForCgError("setting Ka parameter"); cgSetParameter3fv(cg_vertex_param_Kd, zero); checkForCgError("setting Kd parameter"); cgSetParameter3fv(cg_vertex_param_Ks, zero); checkForCgError("setting Ks parameter"); cgSetParameter1f(cg_vertex_param_exponent, 0); checkForCgError("setting exponent parameter"); }
static void setBallMaterial(float x, float y, float z) { const float redPlasticEmissive[3] = {0.0, 0.0, 0.0}, redPlasticAmbient[3] = {0.0, 0.0, 0.0}, redPlasticDiffuse[3] = {x, y, z}, redPlasticSpecular[3] = {0.7, 0.6, 0.6}, redPlasticShininess = 5.0; cgSetParameter3fv(myCgFragmentParam_Ke, redPlasticEmissive); checkForCgError("setting Ke parameter"); cgSetParameter3fv(myCgFragmentParam_Ka, redPlasticAmbient); checkForCgError("setting Ka parameter"); cgSetParameter3fv(myCgFragmentParam_Kd, redPlasticDiffuse); checkForCgError("setting Kd parameter"); cgSetParameter3fv(myCgFragmentParam_Ks, redPlasticSpecular); checkForCgError("setting Ks parameter"); cgSetParameter1f(myCgFragmentParam_shininess, redPlasticShininess); checkForCgError("setting shininess parameter"); }
static void setStickMaterial() { const float redPlasticEmissive[3] = {0.0, 0.0, 0.0}, redPlasticAmbient[3] = {0.0, 0.0, 0.0}, redPlasticDiffuse[3] = {0.9,0.4,0.12}, redPlasticSpecular[3] = {0,0,0}, redPlasticShininess = 0; cgSetParameter3fv(myCgFragmentParam_Ke, redPlasticEmissive); checkForCgError("setting Ke parameter"); cgSetParameter3fv(myCgFragmentParam_Ka, redPlasticAmbient); checkForCgError("setting Ka parameter"); cgSetParameter3fv(myCgFragmentParam_Kd, redPlasticDiffuse); checkForCgError("setting Kd parameter"); cgSetParameter3fv(myCgFragmentParam_Ks, redPlasticSpecular); checkForCgError("setting Ks parameter"); cgSetParameter1f(myCgFragmentParam_shininess, redPlasticShininess); checkForCgError("setting shininess parameter"); }
//----------------------------------------------------------------------- void CgProgram::unloadHighLevelImpl(void) { // Unload Cg Program // Lowlevel program will get unloaded elsewhere if (mCgProgram) { cgDestroyProgram(mCgProgram); checkForCgError("CgProgram::unloadImpl", "Error while unloading Cg program " + mName + ": ", mCgContext); mCgProgram = 0; } }
static void createCgPrograms() { const char **profileOpts; /* Determine the best profile once a device to be set. */ g_cgVertexProfile = cgD3D9GetLatestVertexProfile(); checkForCgError("getting latest profile"); profileOpts = cgD3D9GetOptimalOptions(g_cgVertexProfile); checkForCgError("getting latest profile options"); g_cgVertexProgram = cgCreateProgramFromFile( g_cgContext, /* Cg runtime context */ CG_SOURCE, /* Program in human-readable form */ g_strVertexProgramFileName,/* Name of file containing program */ g_cgVertexProfile, /* Profile: OpenGL ARB vertex program */ g_strVertexProgramName, /* Entry function name */ profileOpts); /* Pass optimal compiler options */ checkForCgError("creating vertex program from file"); //get variable handle g_cgWorldMatrix = cgGetNamedParameter(g_cgVertexProgram, "worldMatrix"); g_cgWorldViewProjMatrix = cgGetNamedParameter(g_cgVertexProgram, "worldViewProjMatrix"); g_cgAmbient = cgGetNamedParameter(g_cgVertexProgram, "ambient"); g_cgLightColor = cgGetNamedParameter(g_cgVertexProgram, "lightColor"); g_cgLightPos = cgGetNamedParameter(g_cgVertexProgram, "lightPos"); g_cgEyePos = cgGetNamedParameter(g_cgVertexProgram, "eyePos"); g_cgKe = cgGetNamedParameter(g_cgVertexProgram, "ke"); g_cgKa = cgGetNamedParameter(g_cgVertexProgram, "ka"); g_cgKd = cgGetNamedParameter(g_cgVertexProgram, "kd"); g_cgKs = cgGetNamedParameter(g_cgVertexProgram, "ks"); g_cgShininess = cgGetNamedParameter(g_cgVertexProgram, "shininess"); assert(g_cgWorldMatrix && g_cgWorldViewProjMatrix && g_cgAmbient && g_cgLightColor && g_cgLightPos && g_cgEyePos && g_cgKe && g_cgKa && g_cgKd && g_cgKs && g_cgShininess); }
void set_plastic_material() { GLfloat Ke[3] = {0.0, 0.0, 0.0}; GLfloat Ka[3] = {0.0, 0.0, 0.0}; GLfloat Kd[3] = {0.7, 0.1, 0.0}; GLfloat Ks[3] = {0.8, 0.7, 0.6}; GLfloat exponent = 33.0; cgSetParameter3fv(cg_vertex_param_Ke, Ke); checkForCgError("setting Ke parameter"); cgSetParameter3fv(cg_vertex_param_Ka, Ka); checkForCgError("setting Ka parameter"); cgSetParameter3fv(cg_vertex_param_Kd, Kd); checkForCgError("setting Kd parameter"); cgSetParameter3fv(cg_vertex_param_Ks, Ks); checkForCgError("setting Ks parameter"); cgSetParameter1f(cg_vertex_param_exponent, exponent); checkForCgError("setting exponent parameter"); }
static void display(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); cgGLBindProgram(myCgVertexProgram); checkForCgError("binding vertex program"); cgGLEnableProfile(myCgVertexProfile); checkForCgError("enabling vertex profile"); /* Rendering code verbatim from Chapter 1, Section 2.4.1 "Rendering a Triangle with OpenGL" (page 57). */ glBegin(GL_TRIANGLES); glVertex2f(-0.8, 0.8); glVertex2f(0.8, 0.8); glVertex2f(0.0, -0.8); glEnd(); cgGLDisableProfile(myCgVertexProfile); checkForCgError("disabling vertex profile"); glutSwapBuffers(); }
void set_brass_material() { GLfloat Ke[3] = {0.0, 0.0, 0.0}; GLfloat Ka[3] = {0.35, 0.23, 0.04}; GLfloat Kd[3] = {0.79, 0.58, 0.12}; GLfloat Ks[3] = {0.99, 0.92, 0.82}; GLfloat exponent = 27.5; cgSetParameter3fv(cg_vertex_param_Ke, Ke); checkForCgError("setting Ke parameter"); cgSetParameter3fv(cg_vertex_param_Ka, Ka); checkForCgError("setting Ka parameter"); cgSetParameter3fv(cg_vertex_param_Kd, Kd); checkForCgError("setting Kd parameter"); cgSetParameter3fv(cg_vertex_param_Ks, Ks); checkForCgError("setting Ks parameter"); cgSetParameter1f(cg_vertex_param_exponent, exponent); checkForCgError("setting exponent parameter"); }
Shader* RendererGL::CreatePixelShaderFromString( const char* PixelCode, const char* PixelMain /*= "PSMain"*/, ShaderVersion ePVersion /*= ESV_PS1_1*/ ) { CGprogram CgPixelProgram = cgCreateProgram ( m_CgContext, CG_SOURCE, PixelCode, m_CgFragmentProfile, PixelMain, NULL ); /* No extra compiler options */ checkForCgError("creating pixel program from string"); if (!CgPixelProgram) return NULL; cgGLLoadProgram(CgPixelProgram); checkForCgError("loading pixel program"); Shader *shader = KGE_NEW(ShaderGL)(CgPixelProgram, 0, NULL, NULL); return shader; }
int main(int argc, char **argv) { glutInitWindowSize(400, 400); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInit(&argc, argv); glutCreateWindow(myProgramName); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glClearColor(0.1, 0.3, 0.6, 0.0); /* Blue background */ myCgContext = cgCreateContext(); checkForCgError("creating context"); cgGLSetDebugMode(CG_FALSE); cgSetParameterSettingMode(myCgContext, CG_DEFERRED_PARAMETER_SETTING); myCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX); cgGLSetOptimalOptions(myCgVertexProfile); checkForCgError("selecting vertex profile"); myCgVertexProgram = cgCreateProgramFromFile( myCgContext, /* Cg runtime context */ CG_SOURCE, /* Program in human-readable form */ myVertexProgramFileName.c_str(), /* Name of file containing program */ myCgVertexProfile, /* Profile: OpenGL ARB vertex program */ myVertexProgramName, /* Entry function name */ NULL); /* No extra compiler options */ checkForCgError("creating vertex program from file"); cgGLLoadProgram(myCgVertexProgram); checkForCgError("loading vertex program"); glutMainLoop(); return 0; }
//----------------------------------------------------------------------- void CgProgram::selectProfile(void) { mSelectedProfile.clear(); mSelectedCgProfile = CG_PROFILE_UNKNOWN; StringVector::iterator i, iend; iend = mProfiles.end(); GpuProgramManager& gpuMgr = GpuProgramManager::getSingleton(); for (i = mProfiles.begin(); i != iend; ++i) { if (gpuMgr.isSyntaxSupported(*i)) { mSelectedProfile = *i; mSelectedCgProfile = cgGetProfile(mSelectedProfile.c_str()); // Check for errors checkForCgError("CgProgram::selectProfile", "Unable to find CG profile enum for program " + mName + ": ", mCgContext); break; } } }
static void CALLBACK OnFrameRender(IDirect3DDevice9* pDev, double time, float elapsedTime, void* userContext) { pDev->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DXCOLOR(0.1f, 0.3f, 0.6f, 0.0f), 1.0f, 0); if (SUCCEEDED(pDev->BeginScene())) { #if 0 pDev->SetTransform(D3DTS_WORLD, &g_matrixWorld); pDev->SetTransform(D3DTS_VIEW, &g_matrixView); pDev->SetTransform(D3DTS_PROJECTION, &g_matrixProjection); pDev->SetLight(0, &g_light); pDev->LightEnable(0, TRUE); pDev->SetMaterial(&g_material); //pDev->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME); pDev->SetRenderState(D3DRS_SPECULARENABLE,TRUE); #else cgD3D9BindProgram(g_cgVertexProgram); checkForCgError("binding vertex program"); #endif cgSetParameterValuefc(g_cgWorldMatrix, 16, g_matrixWorld.m[0]); cgSetParameterValuefc(g_cgWorldViewProjMatrix, 16, g_matrixWorldViewProj.m[0]); cgSetParameterValuefc(g_cgAmbient, 3, (float*)&g_light.Ambient); cgSetParameterValuefc(g_cgLightColor, 3, (float*)&g_light.Diffuse); cgSetParameterValuefc(g_cgLightPos, 3, (float*)&g_light.Position); cgSetParameterValuefc(g_cgEyePos, 3, (float*)&g_eyePos); cgSetParameterValuefc(g_cgKe, 3, (float*)&g_material.Emissive); cgSetParameterValuefc(g_cgKa, 3, (float*)&g_material.Ambient); cgSetParameterValuefc(g_cgKd, 3, (float*)&g_material.Diffuse); cgSetParameterValuefc(g_cgKs, 3, (float*)&g_material.Specular); cgSetParameterValuefc(g_cgShininess, 3, &g_material.Power); g_pMeshSphere->DrawSubset(0); pDev->EndScene(); } }
FFxProgram::FFxProgram(CGdomain aProfileDomain, const char* aFileName, const char* aEntry, const char** aArgs) : mProgramFlags(0), mProgram(0), mSourceBuffer(0), mProfileDomain(aProfileDomain) { #ifdef WIN32 if (GDD->GetClassID() == ClassIDZDisplayDeviceDX9) mProfile = (aProfileDomain == CG_VERTEX_DOMAIN) ?cgD3D9GetLatestVertexProfile():cgD3D9GetLatestPixelProfile(); else #endif { mProfile = (aProfileDomain == CG_VERTEX_DOMAIN) ?cgGLGetLatestProfile(CG_GL_VERTEX):cgGLGetLatestProfile(CG_GL_FRAGMENT ); cgGLSetOptimalOptions(mProfile); checkForCgError("setprofile"); } mFileName = aFileName; mEntry = aEntry; // FIXME mArgs //mArgs = aArgs; }
void InitCG(){ mCgContext = cgCreateContext(); checkForCgError("cgCreateContext()"); cgGLSetDebugMode(CG_FALSE); cgSetParameterSettingMode(mCgContext, CG_DEFERRED_PARAMETER_SETTING); checkForCgError("cgSetParameterSettingMode()"); mCgVertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX); checkForCgError("cgGLGetLatestProfile()"); cgGLSetOptimalOptions(mCgVertexProfile); checkForCgError("cgGLSetOptimalOptions()"); mCgVertexProgram = cgCreateProgramFromFile(mCgContext, CG_SOURCE, "1tex_skin_mesh.cg", mCgVertexProfile, "skinMeshCG", NULL); checkForCgError("cgCreateProgramFromFile()"); cgGLLoadProgram(mCgVertexProgram); checkForCgError("cgGLLoadProgram()"); mBoneParameter = cgGetNamedParameter(mCgVertexProgram, "boneMatrix"); checkForCgError("cgGetNamedParameter(boneMatrix)"); }
bool CGLCG::LoadShader(const TCHAR *shaderFile) { CCGShader cgShader; TCHAR shaderPath[MAX_PATH]; TCHAR tempPath[MAX_PATH]; CGprofile vertexProfile, fragmentProfile; GLenum error; if(!fboFunctionsLoaded) { MessageBox(NULL, TEXT("Your OpenGL graphics driver does not support framebuffer objects.\nYou will not be able to use CG shaders in OpenGL mode."), TEXT("CG Error"), MB_OK|MB_ICONEXCLAMATION); return false; } vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX); fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT); cgGLDisableProfile(vertexProfile); cgGLDisableProfile(fragmentProfile); ClearPasses(); if (shaderFile == NULL || *shaderFile==TEXT('\0')) return true; lstrcpy(shaderPath, shaderFile); ReduceToPath(shaderPath); SetCurrentDirectory(shaderPath); if(!cgShader.LoadShader(_tToChar(shaderFile))) return false; cgGLSetOptimalOptions(vertexProfile); cgGLSetOptimalOptions(fragmentProfile); /* insert dummy pass that will contain the original texture */ shaderPasses.push_back(shaderPass()); for(CCGShader::passVector::iterator it=cgShader.shaderPasses.begin(); it!=cgShader.shaderPasses.end();it++) { shaderPass pass; pass.scaleParams = it->scaleParams; /* if this is the last pass (the only one that can have CG_SCALE_NONE) and no filter has been set use the GUI setting */ if(pass.scaleParams.scaleTypeX==CG_SCALE_NONE && !it->filterSet) { pass.linearFilter = GUI.BilinearFilter; } else { pass.linearFilter = it->linearFilter; } pass.frameCounterMod = it->frameCounterMod; pass.floatFbo = it->floatFbo; // paths in the meta file can be relative _tfullpath(tempPath,_tFromChar(it->cgShaderFile),MAX_PATH); char *fileContents = ReadShaderFileContents(tempPath); if(!fileContents) return false; // individual shader might include files, these should be relative to shader ReduceToPath(tempPath); SetCurrentDirectory(tempPath); pass.cgVertexProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents, vertexProfile, "main_vertex", NULL); checkForCgError("Compiling vertex program"); pass.cgFragmentProgram = cgCreateProgram( cgContext, CG_SOURCE, fileContents, fragmentProfile, "main_fragment", NULL); checkForCgError("Compiling fragment program"); // set path back for next pass SetCurrentDirectory(shaderPath); delete [] fileContents; if(!pass.cgVertexProgram || !pass.cgFragmentProgram) { return false; } cgGLLoadProgram(pass.cgVertexProgram); cgGLLoadProgram(pass.cgFragmentProgram); /* generate framebuffer and texture for this pass and apply default texture settings */ glGenFramebuffers(1,&pass.fbo); glGenTextures(1,&pass.tex); glBindTexture(GL_TEXTURE_2D,pass.tex); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); shaderPasses.push_back(pass); } for(std::vector<CCGShader::lookupTexture>::iterator it=cgShader.lookupTextures.begin();it!=cgShader.lookupTextures.end();it++) { lookupTexture tex; strcpy(tex.id,it->id); /* generate texture for the lut and apply specified filter setting */ glGenTextures(1,&tex.tex); glBindTexture(GL_TEXTURE_2D,tex.tex); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, it->linearfilter?GL_LINEAR:GL_NEAREST); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, it->linearfilter?GL_LINEAR:GL_NEAREST); _tfullpath(tempPath,_tFromChar(it->texturePath),MAX_PATH); // simple file extension png/tga decision int strLen = strlen(it->texturePath); if(strLen>4) { if(!strcasecmp(&it->texturePath[strLen-4],".png")) { int width, height; bool hasAlpha; GLubyte *texData; if(loadPngImage(tempPath,width,height,hasAlpha,&texData)) { glPixelStorei(GL_UNPACK_ROW_LENGTH, width); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, hasAlpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, texData); free(texData); } } else if(!strcasecmp(&it->texturePath[strLen-4],".tga")) { STGA stga; if(loadTGA(tempPath,stga)) { glPixelStorei(GL_UNPACK_ROW_LENGTH, stga.width); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, stga.width, stga.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, stga.data); } } } lookupTextures.push_back(tex); } /* enable texture unit 1 for the lookup textures */ glClientActiveTexture(GL_TEXTURE1); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2,GL_FLOAT,0,lut_coords); glClientActiveTexture(GL_TEXTURE0); /* generate textures and set default values for the pref-filled PREV deque. */ for(int i=0;i<prevPasses.size();i++) { glGenTextures(1,&prevPasses[i].tex); glBindTexture(GL_TEXTURE_2D,prevPasses[i].tex); glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,512,512,0,GL_RGB,GL_UNSIGNED_SHORT_5_6_5,NULL); glBindTexture(GL_TEXTURE_2D,0); prevPasses[i].textureSize.x = prevPasses[i].textureSize.y = prevPasses[i].textureSize.x = prevPasses[i].textureSize.y = 0; memset(prevPasses[i].texCoords,0,sizeof(prevPasses[i].texCoords)); } shaderLoaded = true; return true; }
//----------------------------------------------------------------------- void CgProgram::compileMicrocode(void) { // Create Cg Program /// Program handle CGprogram cgProgram; if (mSelectedCgProfile == CG_PROFILE_UNKNOWN) { LogManager::getSingleton().logMessage( "Attempted to load Cg program '" + mName + "', but no supported " "profile was found. "); return; } buildArgs(); // deal with includes String sourceToUse = resolveCgIncludes(mSource, this, mFilename); cgProgram = cgCreateProgram(mCgContext, CG_SOURCE, sourceToUse.c_str(), mSelectedCgProfile, mEntryPoint.c_str(), const_cast<const char**>(mCgArguments)); // Test //LogManager::getSingleton().logMessage(cgGetProgramString(mCgProgram, CG_COMPILED_PROGRAM)); // Check for errors checkForCgError("CgProgram::compileMicrocode", "Unable to compile Cg program " + mName + ": ", mCgContext); CGerror error = cgGetError(); if (error == CG_NO_ERROR) { // get program string (result of cg compile) mProgramString = cgGetProgramString(cgProgram, CG_COMPILED_PROGRAM); checkForCgError("CgProgram::compileMicrocode", "Unable to retrieve program code for Cg program " + mName + ": ", mCgContext); // get params mParametersMap.clear(); mParametersMapSizeAsBuffer = 0; mSamplerRegisterMap.clear(); recurseParams(cgGetFirstParameter(cgProgram, CG_PROGRAM)); recurseParams(cgGetFirstParameter(cgProgram, CG_GLOBAL)); if (mDelegate) { // Delegating to HLSL or GLSL, need to clean up Cg's output fixHighLevelOutput(mProgramString); if (mSelectedCgProfile == CG_PROFILE_GLSLG) { // need to determine input and output operations mInputOp = cgGetProgramInput(cgProgram); mOutputOp = cgGetProgramOutput(cgProgram); } } // Unload Cg Program - we don't need it anymore cgDestroyProgram(cgProgram); //checkForCgError("CgProgram::unloadImpl", // "Error while unloading Cg program " + mName + ": ", // mCgContext); cgProgram = 0; if ( GpuProgramManager::getSingleton().getSaveMicrocodesToCache()) { addMicrocodeToCache(); } } }
//--------------------------------------------------------------------------------- // init // this function load and compile a vertex/fragment program on the specified context // if the source file is not found, it assigns a default GREEN color shader // if the compile failed, it assigns a default RED color shader //--------------------------------------------------------------------------------- bool FFxProgram::init(CGcontext aContext) { CGenum fileType; // remove existing program (in case a program is already loaded) if (mProgram) { cgDestroyProgram(mProgram); mProgram = 0; } fileType = CG_SOURCE; #ifdef WIN32 HRESULT hr; if (GDD->GetClassID() == ClassIDZDisplayDeviceDX9) { const char** profileOpts; profileOpts = cgD3D9GetOptimalOptions(mProfile); const char *nOpts[16]; nOpts[0] = COMPILE_ARGS[0]; int idx =1; while ( (idx<15) && profileOpts[idx-1]) { nOpts[idx] = profileOpts[idx-1]; idx++; } nOpts[idx] = 0; const char *szDXprofile = NULL; if (mProfile == CG_PROFILE_VS_2_0) { szDXprofile = D3DXGetVertexShaderProfile(GDD->GetD3D9Device()); } else { szDXprofile = D3DXGetPixelShaderProfile(GDD->GetD3D9Device()); } /* //LPD3DXBUFFER mDXShader; D3DXCompileShader( mSourceBuffer, strlen(mSourceBuffer), NULL, NULL, mEntry.c_str(), szDXprofile, 0, &mDXShader, NULL, NULL ); */ mProgram = cgCreateProgram(aContext, fileType, mSourceBuffer, mProfile, mEntry.c_str(), nOpts); hr = cgD3D9LoadProgram(mProgram, true, 0); } else #endif { // opengl //mProgram = cgCreateProgram(aContext, fileType, mSourceBuffer, mProfile, mEntry.c_str(), COMPILE_ARGS); mProfile = (mProfileDomain == CG_VERTEX_DOMAIN) ?cgGLGetLatestProfile(CG_GL_VERTEX):cgGLGetLatestProfile(CG_GL_FRAGMENT ); assert(cgGLIsProfileSupported(mProfile)); mProgram = cgCreateProgramFromFile(aContext, fileType, mFileName, mProfile, mEntry.c_str(), COMPILE_ARGS); if (mProgram == NULL) { CGerror error; const char* errTxt = cgGetLastErrorString(&error); LOG ("ERROR %x: can't compile %s : %s\n", error, mFileName.c_str(), errTxt); useDefaultProgram(aContext); assert(false); return false; } cgGLLoadProgram(mProgram); checkForCgError("loadprog"); } if (mProgram == 0) { CGerror error = cgGetError(); LOG ("ERROR %x: can't load or compile %s : %s\n", error, mFileName.c_str(), cgGetLastErrorString(&error)); useDefaultProgram(aContext); assert(false); return false; } return true; }