Thinking in Shader(5)

Thinking in Shader(5)

分类: 图形学 Cg 936人阅读 评论(0) 收藏 举报

Thinking in Shader(5)

 

开发环境

Window7

CgToolkit

VS2008

 

 

        羽化的第二十二篇博客,据说Unity3D官网注册超过了70万,是去年的3倍,再者网上的教程也慢慢变多,各种质量的教程也相继出现,但大多数都是英文版,貌似看过中文视频一个做坦克的,只可借鉴,制作方法实在不敢恭维。。。羽化认为Unity作为一款引擎来说还不算成熟,在开发过程中也许会遇到各种奇怪问题,而且稳定性无法保证,但作为像羽化这种新手来说,开发简单很适合用来学习,而且新版本也许会改进很多问题,希望Unity3D越做越好。最近腾讯在大力宣传一款叫做《艾尔之光》的游戏,在公司看到有人在玩,看了看貌似做得不错,3D横版卡通渲染漫画风格的游戏,有点看到《龙之谷》的感觉,可惜物是人非,提不起劲来- -这种游戏若没喜欢的朋友一起玩,也就3分钟热度,韩国很适合做这类休闲游戏,可能是因为没文化底蕴又不受文化约束。。。游戏在推动世界进步,推荐大家去看看“[道兰][NHK纪录片]世界游戏革命”,可以对比自己心中的游戏,感觉还差多远。

 

Parameter Shadowing参数映射

       当一个统一的参数通过一些OpenGL Cgruntime功能允许的时候,通常会被保存在内存,这样每次使用时就不需要重新设置,这种行为就叫做参数映射,缺点在于消耗内存大小,但依然值得使用,其允许所有参数设置在纹理状态阶段和纹理模式下。

 

OpenGL Cg Runtime

      这里介绍一些基本参数,一般有两个版本,一个是float操作的标为“f”,另一个是以double操作的,设为“d”。

  1. //设置统一标量和统一向量参数,通过cgGLSetParameter功能:   
  2. void cgGLSetParameter1f(CGparameter parameter, float x);  
  3. void cgGLSetParameter1fv(CGparameter parameter, const float* array);  
  4. void cgGLSetParameter1d(CGparameter parameter, double x);  
  5. void cgGLSetParameter1dv(CGparameter parameter, const double* array);  
  6. void cgGLSetParameter2f(CGparameter parameter, float x, float y);  
  7. void cgGLSetParameter2fv(CGparameter parameter, const float* array);  
  8. void cgGLSetParameter2d(CGparameter parameter, double x, double y);  
  9. void cgGLSetParameter2dv(CGparameter parameter, const double* array);  
  10. void cgGLSetParameter3f(CGparameter parameter, float x, float y, float z);  
  11. void cgGLSetParameter3fv(CGparameter parameter, const float* array);  
  12. void cgGLSetParameter3d(CGparameter parameter, double x, double y, double z);  
  13. void cgGLSetParameter3dv(CGparameter parameter, const double* array);  
  14. void cgGLSetParameter4f(CGparameter parameter, float x, float y, float z, float w);  
  15. void cgGLSetParameter4fv(CGparameter parameter, const float* array);  
  16. void cgGLSetParameter4d(CGparameter parameter, double x, double y, double z, double w);  
  17. void cgGLSetParameter4dv(CGparameter parameter, const double* array);  
  18.   
  19.   
  20. //相对应的检索功能   
  21. cgGLGetParameter1f(CGparameter parameter, float* array);  
  22. cgGLGetParameter1d(CGparameter parameter, double* array);  
  23. cgGLGetParameter2f(CGparameter parameter, float* array);  
  24. cgGLGetParameter2d(CGparameter parameter, double* array);  
  25. cgGLGetParameter3f(CGparameter parameter, float* array);  
  26. cgGLGetParameter3d(CGparameter parameter, double* array);  
  27. cgGLGetParameter4f(CGparameter parameter, double* array);  
  28. cgGLGetParameter4d(CGparameter parameter, type* array);  
  29.   
  30. //设置统一的矩阵参数   
  31. void cgGLSetMatrixParameterfr(CGparameter parameter, const float* matrix);  
  32. void cgGLSetMatrixParameterfc(CGparameter parameter, const float* matrix);  
  33. void cgGLSetMatrixParameterdr(CGparameter parameter, const double* matrix);  
  34. void cgGLSetMatrixParameterdc(CGparameter parameter, const double* matrix);  
  35.   
  36. //相应矩阵的检索功能   
  37. void cgGLGetMatrixParameterfr(CGparameter parameter, float* matrix);  
  38. void cgGLGetMatrixParameterfc(CGparameter parameter, float* matrix);  
  39. void cgGLGetMatrixParameterdr(CGparameter parameter, double* matrix);  
  40. void cgGLGetMatrixParameterdc(CGparameter parameter, double* matrix);  
  41.   
  42. //获得4X4的矩阵   
  43. void cgGLSetStateMatrixParameter(CGparameter parameter, GLenum stateMatrixType, GLenum transform);  
  44. //这里的stateMatrixType,可能为CG_GL_MODELVIEW_MATRIX、CG_GL_PROJECTION_MATRIX、CG_GL_TEXTURE_MATRIX、CG_GL_MODELVIEW_PROJECTION_MATRIX   
  45. //后面的transform可能为CG_GL_MATRIX_IDENTITY、CG_GL_MATRIX_TRANSPOSE、CG_GL_MATRIX_INVERSE、CG_GL_MATRIX_INVERSE_TRANSPOSE   
  46.   
  47. //设置统一标量数组,向量,和矩阵参数   
  48. void cgGLSetParameterArray1f(CGparameter parameter, long startIndex, long numberOfElements,  
  49. const float* array);  
  50. void cgGLSetParameterArray1d(CGparameter parameter, long startIndex, long numberOfElements, const double* array);  
  51. void cgGLSetParameterArray2f(CGparameter parameter, long startIndex, long numberOfElements, const float* array);  
  52. void cgGLSetParameterArray2d(CGparameter parameter, long startIndex, long numberOfElements, const double* array);  
  53. void cgGLSetParameterArray3f(CGparameter parameter, long startIndex, long numberOfElements, const float* array);  
  54. void cgGLSetParameterArray3d(CGparameter parameter, long startIndex, long numberOfElements, const double* array);  
  55. void cgGLSetParameterArray4f(CGparameter parameter, long startIndex, long numberOfElements, const float* array);  
  56. void cgGLSetParameterArray4d(CGparameter parameter, long startIndex, long numberOfElements, const double* array);  
  57.   
  58. //相应的检索   
  59. void cgGLGetParameterArray1f(CGparameter parameter, long startIndex, long numberOfElements, float* array);  
  60. void cgGLGetParameterArray1d(CGparameter parameter, long startIndex, long numberOfElements, double* array);  
  61. void cgGLGetParameterArray2f(CGparameter parameter, long startIndex, long numberOfElements, float* array);  
  62. void cgGLGetParameterArray2d(CGparameter parameter, long startIndex, long numberOfElements, double* array);  
  63. void cgGLGetParameterArray3f(CGparameter parameter, long startIndex, long numberOfElements, float* array);  
  64. void cgGLGetParameterArray3d(CGparameter parameter, long startIndex, long numberOfElements, double* array);  
  65. void cgGLGetParameterArray4f(CGparameter parameter, long startIndex, long numberOfElements, float* array);  
  66. void cgGLGetParameterArray4d(CGparameter parameter, long startIndex, long numberOfElements, double* array);  
  67.   
  68. //类似的功能设置矩阵数组   
  69. void cgGLSetMatrixParameterArrayfr(CGparameter parameter, long startIndex, long numberOfElements, const float* array);  
  70. void cgGLSetMatrixParameterArrayfc(CGparameter parameter, long startIndex, long numberOfElements, const float* array);  
  71. void cgGLSetMatrixParameterArraydc(CGparameter parameter, long startIndex, long numberOfElements, const double* array);  
  72. void cgGLSetMatrixParameterArraydc(CGparameter parameter, long startIndex, long numberOfElements, const double* array);  
  73.   
  74. //检索   
  75. void cgGLGetMatrixParameterArrayfr(CGparameter parameter, long startIndex, long numberOfElements, float* array);  
  76. void cgGLGetMatrixParameterArrayfc(CGparameter parameter, long startIndex, long numberOfElements, float* array);  
  77. void cgGLGetMatrixParameterArraydc(CGparameter parameter, long startIndex, long numberOfElements, double* array);  
  78. void cgGLGetMatrixParameterArraydc(CGparameter parameter, long startIndex, long numberOfElements, double* array);  
  79. //这里的c和r后缀其实是行column和列row   
  80.   
  81. //设置不同的参数   
  82. void cgGLSetParameterPointer(CGparameter parameter, GLint size, GLenum type, GLsizei stride, GLvoid* array);  //第一步   
  83. void cgGLEnableClientState(CGparameter parameter); //第二步   
  84. void cgGLDisableClientState(CGparameter parameter); //逆第二步。。。   
  85.   
  86. //设置单一参数   
  87. void cgGLSetTextureParameter(CGparameter parameter, GLuint textureName);//第一步   
  88. void cgGLSetManageTextureParameters(CGcontext context, CGbool enable); //第二步   
  89. void cgGLEnableTextureParameter(CGparameter parameter);//第三步   
  90. void cgGLDisableTextureParameter(CGparameter parameter);//逆第三步   
  91. GLuint cgGLGetTextureParameter(CGparameter parameter);//检索物件   
  92. GLenum cgGLGetTextureEnum(CGparameter parameter); //检索枚举器  
//设置统一标量和统一向量参数,通过cgGLSetParameter功能:
void cgGLSetParameter1f(CGparameter parameter, float x);
void cgGLSetParameter1fv(CGparameter parameter, const float* array);
void cgGLSetParameter1d(CGparameter parameter, double x);
void cgGLSetParameter1dv(CGparameter parameter, const double* array);
void cgGLSetParameter2f(CGparameter parameter, float x, float y);
void cgGLSetParameter2fv(CGparameter parameter, const float* array);
void cgGLSetParameter2d(CGparameter parameter, double x, double y);
void cgGLSetParameter2dv(CGparameter parameter, const double* array);
void cgGLSetParameter3f(CGparameter parameter, float x, float y, float z);
void cgGLSetParameter3fv(CGparameter parameter, const float* array);
void cgGLSetParameter3d(CGparameter parameter, double x, double y, double z);
void cgGLSetParameter3dv(CGparameter parameter, const double* array);
void cgGLSetParameter4f(CGparameter parameter, float x, float y, float z, float w);
void cgGLSetParameter4fv(CGparameter parameter, const float* array);
void cgGLSetParameter4d(CGparameter parameter, double x, double y, double z, double w);
void cgGLSetParameter4dv(CGparameter parameter, const double* array);


//相对应的检索功能
cgGLGetParameter1f(CGparameter parameter, float* array);
cgGLGetParameter1d(CGparameter parameter, double* array);
cgGLGetParameter2f(CGparameter parameter, float* array);
cgGLGetParameter2d(CGparameter parameter, double* array);
cgGLGetParameter3f(CGparameter parameter, float* array);
cgGLGetParameter3d(CGparameter parameter, double* array);
cgGLGetParameter4f(CGparameter parameter, double* array);
cgGLGetParameter4d(CGparameter parameter, type* array);

//设置统一的矩阵参数
void cgGLSetMatrixParameterfr(CGparameter parameter, const float* matrix);
void cgGLSetMatrixParameterfc(CGparameter parameter, const float* matrix);
void cgGLSetMatrixParameterdr(CGparameter parameter, const double* matrix);
void cgGLSetMatrixParameterdc(CGparameter parameter, const double* matrix);

//相应矩阵的检索功能
void cgGLGetMatrixParameterfr(CGparameter parameter, float* matrix);
void cgGLGetMatrixParameterfc(CGparameter parameter, float* matrix);
void cgGLGetMatrixParameterdr(CGparameter parameter, double* matrix);
void cgGLGetMatrixParameterdc(CGparameter parameter, double* matrix);

//获得4X4的矩阵
void cgGLSetStateMatrixParameter(CGparameter parameter, GLenum stateMatrixType, GLenum transform);
//这里的stateMatrixType,可能为CG_GL_MODELVIEW_MATRIX、CG_GL_PROJECTION_MATRIX、CG_GL_TEXTURE_MATRIX、CG_GL_MODELVIEW_PROJECTION_MATRIX
//后面的transform可能为CG_GL_MATRIX_IDENTITY、CG_GL_MATRIX_TRANSPOSE、CG_GL_MATRIX_INVERSE、CG_GL_MATRIX_INVERSE_TRANSPOSE

//设置统一标量数组,向量,和矩阵参数
void cgGLSetParameterArray1f(CGparameter parameter, long startIndex, long numberOfElements,
const float* array);
void cgGLSetParameterArray1d(CGparameter parameter, long startIndex, long numberOfElements, const double* array);
void cgGLSetParameterArray2f(CGparameter parameter, long startIndex, long numberOfElements, const float* array);
void cgGLSetParameterArray2d(CGparameter parameter, long startIndex, long numberOfElements, const double* array);
void cgGLSetParameterArray3f(CGparameter parameter, long startIndex, long numberOfElements, const float* array);
void cgGLSetParameterArray3d(CGparameter parameter, long startIndex, long numberOfElements, const double* array);
void cgGLSetParameterArray4f(CGparameter parameter, long startIndex, long numberOfElements, const float* array);
void cgGLSetParameterArray4d(CGparameter parameter, long startIndex, long numberOfElements, const double* array);

//相应的检索
void cgGLGetParameterArray1f(CGparameter parameter, long startIndex, long numberOfElements, float* array);
void cgGLGetParameterArray1d(CGparameter parameter, long startIndex, long numberOfElements, double* array);
void cgGLGetParameterArray2f(CGparameter parameter, long startIndex, long numberOfElements, float* array);
void cgGLGetParameterArray2d(CGparameter parameter, long startIndex, long numberOfElements, double* array);
void cgGLGetParameterArray3f(CGparameter parameter, long startIndex, long numberOfElements, float* array);
void cgGLGetParameterArray3d(CGparameter parameter, long startIndex, long numberOfElements, double* array);
void cgGLGetParameterArray4f(CGparameter parameter, long startIndex, long numberOfElements, float* array);
void cgGLGetParameterArray4d(CGparameter parameter, long startIndex, long numberOfElements, double* array);

//类似的功能设置矩阵数组
void cgGLSetMatrixParameterArrayfr(CGparameter parameter, long startIndex, long numberOfElements, const float* array);
void cgGLSetMatrixParameterArrayfc(CGparameter parameter, long startIndex, long numberOfElements, const float* array);
void cgGLSetMatrixParameterArraydc(CGparameter parameter, long startIndex, long numberOfElements, const double* array);
void cgGLSetMatrixParameterArraydc(CGparameter parameter, long startIndex, long numberOfElements, const double* array);

//检索
void cgGLGetMatrixParameterArrayfr(CGparameter parameter, long startIndex, long numberOfElements, float* array);
void cgGLGetMatrixParameterArrayfc(CGparameter parameter, long startIndex, long numberOfElements, float* array);
void cgGLGetMatrixParameterArraydc(CGparameter parameter, long startIndex, long numberOfElements, double* array);
void cgGLGetMatrixParameterArraydc(CGparameter parameter, long startIndex, long numberOfElements, double* array);
//这里的c和r后缀其实是行column和列row

//设置不同的参数
void cgGLSetParameterPointer(CGparameter parameter, GLint size, GLenum type, GLsizei stride, GLvoid* array);  //第一步
void cgGLEnableClientState(CGparameter parameter); //第二步
void cgGLDisableClientState(CGparameter parameter); //逆第二步。。。

//设置单一参数
void cgGLSetTextureParameter(CGparameter parameter, GLuint textureName);//第一步
void cgGLSetManageTextureParameters(CGcontext context, CGbool enable); //第二步
void cgGLEnableTextureParameter(CGparameter parameter);//第三步
void cgGLDisableTextureParameter(CGparameter parameter);//逆第三步
GLuint cgGLGetTextureParameter(CGparameter parameter);//检索物件
GLenum cgGLGetTextureEnum(CGparameter parameter); //检索枚举器

OpenGL Profile Support配置文件支持

        一个方便的方法拿最有用的属性文件针对顶点或者片段程序:

  1. CGprofile cgGLGetLatestProfile(CGGLenum profileType);  
  2. void cgGLSetOptimalOptions(CGprofile profile);//优化编译  
CGprofile cgGLGetLatestProfile(CGGLenum profileType);
void cgGLSetOptimalOptions(CGprofile profile);//优化编译

OpenGL Program Execution程序运行

       过程很简单如下:(*为可选项)

  1. void cgGLLoadProgram(CGprogram program); //所以程序先必须读取   
  2. void cgGLEnableProfile(CGprofile profile); // 配置文件启用   
  3. void cgGLDisableProfile(CGprofile profile);//配置文件不启用*   
  4. void cgGLBindProgram(CGprogram program); //绑定配置文件   
  5. CGbool cgGLIsProfileSupported(CGprofile profile);//判断配置文件是否支持*  
void cgGLLoadProgram(CGprogram program); //所以程序先必须读取
void cgGLEnableProfile(CGprofile profile); // 配置文件启用
void cgGLDisableProfile(CGprofile profile);//配置文件不启用*
void cgGLBindProgram(CGprogram program); //绑定配置文件
CGbool cgGLIsProfileSupported(CGprofile profile);//判断配置文件是否支持*

OpenGL Program Examples程序实例

  1. // VertexProgram.cg 顶点程序   
  2. void VertexProgram(in float4 position : POSITION,  in float4 color : COLOR0,  
  3.                 in float4 texCoord : TEXCOORD0,  out float4 positionO : POSITION,  
  4.                 out float4 colorO : COLOR0, out float4 texCoordO : TEXCOORD0,  
  5.                 const uniform float4x4 ModelViewMatrix )  
  6. {  
  7.     positionO = mul(position, ModelViewMatrix);  
  8.     colorO = color;  
  9.     texCoordO = texCoord;  
  10. }  
  11.   
  12. // FragmentProgram.cg 片段程序   
  13. void FragmentProgram(in float4 color : COLOR0, in float4 texCoord : TEXCOORD0,  
  14.                     out float4 colorO : COLOR0, const uniform sampler2D BaseTexture,  
  15.                     const uniform float4 SomeColor)  
  16. {  
  17.     colorO = color * tex2D(BaseTexture, texCoord) + SomeColor;  
  18. }  
  19.   
  20. // OpenGL Application OpenGL应用   
  21. #include <cg/cg.h>   
  22. #include <cg/cgGL.h>   
  23. float* vertexPositions; // Initialized somewhere else别的地方初始化   
  24. float* vertexColors; // Initialized somewhere else   
  25. float* vertexTexCoords; // Initialized somewhere else   
  26. GLuint texture; // Initialized somewhere else   
  27. float constantColor[]; // Initialized somewhere else   
  28. CGcontext context;  
  29. CGprogram vertexProgram, fragmentProgram;  
  30. CGprofile vertexProfile, fragmentProfile;  
  31. CGparameter position, color, texCoord, baseTexture, someColor,  
  32.             modelViewMatrix;  
  33. // Called at initialization初始化   
  34. void CgGLInit()  
  35. {  
  36.     // Create context 创建连接   
  37.     context = cgCreateContext();  
  38.   
  39.     // Initialize profiles and compiler options初始化配置文件和编译器   
  40.     vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);  
  41.     cgGLSetOptimalOptions(vertexProfile);  
  42.     fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);  
  43.     cgGLSetOptimalOptions(fragmentProfile);  
  44.   
  45.     // Create the vertex program创建顶点程序   
  46.     vertexProgram = cgCreateProgramFromFile(context, CG_SOURCE, "VertexProgram.cg", vertexProfile, "VertexProgram", 0);  
  47.     // Load the program读取程序   
  48.     cgGLLoadProgram(vertexProgram);  
  49.   
  50.     // Create the fragment program创建片段程序   
  51.     fragmentProgram = cgCreateProgramFromFile(context, CG_SOURCE, "FragmentProgram.cg", fragmentProfile, "FragmentProgram", 0);  
  52.     // Load the program读取程序   
  53.     cgGLLoadProgram(fragmentProgram);  
  54.   
  55.     // Grab some parameters.抓取一些参数   
  56.     position = cgGetNamedParameter(vertexProgram, "position");  
  57.     color = cgGetNamedParameter(vertexProgram, "color");  
  58.     texCoord = cgGetNamedParameter(vertexProgram, "texCoord");  
  59.     modelViewMatrix = cgGetNamedParameter(vertexProgram,"ModelViewMatrix");  
  60.     baseTexture = cgGetNamedParameter(fragmentProgram,  "BaseTexture");  
  61.     someColor = cgGetNamedParameter(fragmentProgram, "SomeColor");  
  62.       
  63.     // Set parameters that don't change:设置参数不再改变   
  64.     // They can be set only once because of parameter shadowing.设置映射   
  65.     cgGLSetTextureParameter(baseTexture, texture);  
  66.     cgGLSetParameter4fv(someColor, constantColor);  
  67. }  
  68.   
  69. // Called to render the scene 打开渲染场景   
  70. void Display()  
  71. {  
  72.     // Set the varying parameters设置不同参数   
  73.     cgGLEnableClientState(position);  
  74.     cgGLSetParameterPointer(position, 3, GL_FLOAT, 0, vertexPositions);  
  75.     cgGLEnableClientState(color);  
  76.     cgGLSetParameterPointer(color, 1, GL_FLOAT, 0, vertexColors);  
  77.     cgGLEnableClientState(texCoord);  
  78.     cgGLSetParameterPointer(texCoord, 2, GL_FLOAT, 0, vertexTexCoords);  
  79.   
  80.     // Set the uniform parameters that change every frame设置统一参数每帧变化   
  81.     cgGLSetStateMatrixParameter(modelViewMatrix,CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY);  
  82.   
  83.     // Enable the profiles打开配置文件   
  84.     cgGLEnableProfile(vertexProfile);  
  85.     cgGLEnableProfile(fragmentProfile);  
  86.     // Bind the programs绑定配置文件   
  87.     cgGLBindProgram(vertexProgram);  
  88.     cgGLBindProgram(fragmentProgram);  
  89.     // Enable texture纹理可用   
  90.     cgGLEnableTextureParameter(baseTexture);  
  91.     // Draw scene 画场景   
  92.     // ...   
  93.     // Disable texture纹理不可用   
  94.     cgGLDisableTextureParameter(baseTexture);  
  95.     // Disable the profiles关闭配置文件   
  96.     cgGLDisableProfile(vertexProfile);  
  97.     cgGLDisableProfile(fragmentProfile);  
  98.   
  99.     // Set the varying parameters设置不同参数状态   
  100.     cgGLDisableClientState(position);  
  101.     cgGLDisableClientState(color);  
  102.     cgGLDisableClientState(texCoord);  
  103. }  
  104.   
  105. // Called before application shuts down 当程序关闭时响应   
  106. void CgShutdown()  
  107. {  
  108.     // This frees any runtime resource.释放所有资源   
  109.     cgDestroyContext(context);  
  110. }  
// VertexProgram.cg 顶点程序
void VertexProgram(in float4 position : POSITION,  in float4 color : COLOR0,
				in float4 texCoord : TEXCOORD0,  out float4 positionO : POSITION,
				out float4 colorO : COLOR0, out float4 texCoordO : TEXCOORD0,
				const uniform float4x4 ModelViewMatrix )
{
	positionO = mul(position, ModelViewMatrix);
	colorO = color;
	texCoordO = texCoord;
}

// FragmentProgram.cg 片段程序
void FragmentProgram(in float4 color : COLOR0, in float4 texCoord : TEXCOORD0,
					out float4 colorO : COLOR0, const uniform sampler2D BaseTexture,
					const uniform float4 SomeColor)
{
	colorO = color * tex2D(BaseTexture, texCoord) + SomeColor;
}

// OpenGL Application OpenGL应用
#include <cg/cg.h>
#include <cg/cgGL.h>
float* vertexPositions; // Initialized somewhere else别的地方初始化
float* vertexColors; // Initialized somewhere else
float* vertexTexCoords; // Initialized somewhere else
GLuint texture; // Initialized somewhere else
float constantColor[]; // Initialized somewhere else
CGcontext context;
CGprogram vertexProgram, fragmentProgram;
CGprofile vertexProfile, fragmentProfile;
CGparameter position, color, texCoord, baseTexture, someColor,
			modelViewMatrix;
// Called at initialization初始化
void CgGLInit()
{
	// Create context 创建连接
	context = cgCreateContext();

	// Initialize profiles and compiler options初始化配置文件和编译器
	vertexProfile = cgGLGetLatestProfile(CG_GL_VERTEX);
	cgGLSetOptimalOptions(vertexProfile);
	fragmentProfile = cgGLGetLatestProfile(CG_GL_FRAGMENT);
	cgGLSetOptimalOptions(fragmentProfile);

	// Create the vertex program创建顶点程序
	vertexProgram = cgCreateProgramFromFile(context, CG_SOURCE, "VertexProgram.cg", vertexProfile, "VertexProgram", 0);
	// Load the program读取程序
	cgGLLoadProgram(vertexProgram);

	// Create the fragment program创建片段程序
	fragmentProgram = cgCreateProgramFromFile(context, CG_SOURCE, "FragmentProgram.cg", fragmentProfile, "FragmentProgram", 0);
	// Load the program读取程序
	cgGLLoadProgram(fragmentProgram);

	// Grab some parameters.抓取一些参数
	position = cgGetNamedParameter(vertexProgram, "position");
	color = cgGetNamedParameter(vertexProgram, "color");
	texCoord = cgGetNamedParameter(vertexProgram, "texCoord");
	modelViewMatrix = cgGetNamedParameter(vertexProgram,"ModelViewMatrix");
	baseTexture = cgGetNamedParameter(fragmentProgram,	"BaseTexture");
	someColor = cgGetNamedParameter(fragmentProgram, "SomeColor");
	
	// Set parameters that don't change:设置参数不再改变
	// They can be set only once because of parameter shadowing.设置映射
	cgGLSetTextureParameter(baseTexture, texture);
	cgGLSetParameter4fv(someColor, constantColor);
}

// Called to render the scene 打开渲染场景
void Display()
{
	// Set the varying parameters设置不同参数
	cgGLEnableClientState(position);
	cgGLSetParameterPointer(position, 3, GL_FLOAT, 0, vertexPositions);
	cgGLEnableClientState(color);
	cgGLSetParameterPointer(color, 1, GL_FLOAT, 0, vertexColors);
	cgGLEnableClientState(texCoord);
	cgGLSetParameterPointer(texCoord, 2, GL_FLOAT, 0, vertexTexCoords);

	// Set the uniform parameters that change every frame设置统一参数每帧变化
	cgGLSetStateMatrixParameter(modelViewMatrix,CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY);

	// Enable the profiles打开配置文件
	cgGLEnableProfile(vertexProfile);
	cgGLEnableProfile(fragmentProfile);
	// Bind the programs绑定配置文件
	cgGLBindProgram(vertexProgram);
	cgGLBindProgram(fragmentProgram);
	// Enable texture纹理可用
	cgGLEnableTextureParameter(baseTexture);
	// Draw scene 画场景
	// ...
	// Disable texture纹理不可用
	cgGLDisableTextureParameter(baseTexture);
	// Disable the profiles关闭配置文件
	cgGLDisableProfile(vertexProfile);
	cgGLDisableProfile(fragmentProfile);

	// Set the varying parameters设置不同参数状态
	cgGLDisableClientState(position);
	cgGLDisableClientState(color);
	cgGLDisableClientState(texCoord);
}

// Called before application shuts down 当程序关闭时响应
void CgShutdown()
{
	// This frees any runtime resource.释放所有资源
	cgDestroyContext(context);
}

OpenGL Error Reporting错误报告

         通过glGetError()方法得到错误报告,一般返回错误有:

         CG_PROGRAM_LOAD_ERROR

         CG_PROGRAM_BIND_ERROR

         CG_PROGRAM_NOT_LOADED_ERROR

         CG_UNSUPPORTED_GL_EXTENSION_ERROR

 

 

 

Direct3D Cg Runtime

         这个Direct3D Cgruntime包含两个接口:

         低配:此接口没有Direct3D自称,当你喜欢保持Direct3D代码在应用中。

         高配:此接口提供了所需的提高程序,参数管理,当你喜欢用Cg runtime 管理Direct3D着色器的时候。

         羽化个人认为高低配置比较适合这两个接口的区别。

 

Direct3D Minimal Interface低配接口

       提供一些方便的功能,把一些信息数据提供给核心运算,再把信息特征送到Direct3D。

Vertex Declaration 顶点声明

         在Direct3D中你必须提供一个顶点声明用来映射一张表在顶点着色器输入寄存器和应用程序数据流之间。

         一个数据流是一个基础的数组数据结构,每一个结构是一个特殊的类型称为顶点格式流,这里有一个顶点声明的例子,对应Direct3D 9:

  1. //Direct3D 9   
  2. const D3DVERTEXELEMENT9 declaration[] = {  
  3. {   0, 0 * sizeof(float),  
  4.     D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  
  5.     D3DDECLUSAGE_POSITION, 0 }, // Position   
  6. {   0, 3 * sizeof(float),  
  7.     D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  
  8.     D3DDECLUSAGE_NORMAL, 0 }, // Normal   
  9. {   0, 8 * sizeof(float),  
  10.     D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,  
  11.     D3DDECLUSAGE_TEXCOORD, 0 }, // Base texture   
  12. {   1, 0 * sizeof(float),  
  13.     D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  
  14.     D3DDECLUSAGE_TEXCOORD, 1 }, // Tangent   
  15.     D3DD3CL_END()  
  16. };  
//Direct3D 9
const D3DVERTEXELEMENT9 declaration[] = {
{ 	0, 0 * sizeof(float),
	D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
	D3DDECLUSAGE_POSITION, 0 }, // Position
{ 	0, 3 * sizeof(float),
	D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
	D3DDECLUSAGE_NORMAL, 0 }, // Normal
{ 	0, 8 * sizeof(float),
	D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,
	D3DDECLUSAGE_TEXCOORD, 0 }, // Base texture
{ 	1, 0 * sizeof(float),
	D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
	D3DDECLUSAGE_TEXCOORD, 1 }, // Tangent
	D3DD3CL_END()
};

         两个声明都告诉Direct3Druntime去寻找:

(1)      顶点坐标在“流0”中,作为第一个3个浮点值的顶点格式。

(2)      法线座位下一个3个浮点值紧随“流0”的3个浮点值。

(3)      贴图坐标作为两个浮点数据用作偏移量相当于一个DWORD的两倍尺寸,在法线数据结尾,在“流0”中。

切线提供在“流1”中作为第二个贴图坐标,被作为第一个3个浮点值的顶点格式。

  1. //Direct3D 9   
  2. CGbool cgD3D9GetVertexDeclaration(CGprogram program,  
  3.                         D3DVERTEXELEMENT9 declaration[MAXD3DDECLLENGTH]);  
  4. //MAXD3DDECLLENGTH 是Direct3D 9的常量,给Direct3 0声明的最大长度,如果程序中没有得到声明,会返回一个CG_FALSE   
  5.   
  6. //返回值对于以下程序   
  7. void main(in float4 position : POSITION,  
  8.         in float4 color : COLOR0,  
  9.         in float4 texCoord : TEXCOORD0,  
  10.         out float4 hpos : POSITION)  
  11. { }  
  12.   
  13. //等同于 Direct3D 9 Cg runtime   
  14. const D3DVERTEXELEMENT9 declaration[] = {  
  15. { 0, 0 * sizeof(float),  
  16. D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT,  
  17. D3DDECLUSAGE_POSITION, 0 },  
  18. { 0, 4 * sizeof(float),  
  19. D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT,  
  20. D3DDECLUSAGE_COLOR, 0 },  
  21. { 0, 8 * sizeof(float),  
  22. D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT,  
  23. D3DDECLUSAGE_TEXCOORD, 0 },  
  24. D3DD3CL_END()  
  25. };  
  26.   
  27. //测试是否兼容程序   
  28. CGbool cgD3D9ValidateVertexDeclaration(CGprogram program,  
  29. const D3DVERTEXELEMENT9* declaration);   //Direct 9    
  30. CGbool cgD3D8ValidateVertexDeclaration(CGprogram program,  
  31. const DWORD* declaration);              //Direct 8    
  32.   
  33. //有效声明例如:   
  34. void main(float4 position : POSITION,  
  35.     float4 color : COLOR0,  
  36.     float4 texCoord : TEXCOORD0)  
  37. { }  
  38.   
  39. //等同于 Derect3D 9   
  40. const D3DVERTEXELEMENT9 declaration[] = {  
  41. { 0, 0 * sizeof(float),  
  42. D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  
  43. D3DDECLUSAGE_POSITION, 0 },  
  44. { 0, 3 * sizeof(float),  
  45. D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,  
  46. D3DDECLUSAGE_COLOR, 0 },  
  47. { 1, 4 * sizeof(float),  
  48. D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,  
  49. D3DDECLUSAGE_TEXCOORD, 0 },  
  50. D3DD3CL_END()  
  51. };  
  52.   
  53. //以上声明也可以写为   
  54. const D3DVERTEXELEMENT9 declaration[] = {  
  55. { 0, 0 * sizeof(float),  
  56. D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  
  57. cgD3D9ResourceToDeclUsage(CG_POSITION), 0 },  
  58. { 0, 3 * sizeof(float),  
  59. D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,  
  60. cgD3D9ResourceToDeclUsage(CG_COLOR0), 0 },  
  61. { 1, 4 * sizeof(float),  
  62. D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,  
  63. cgD3D9ResourceToDeclUsage(CG_TEXCOORD0), 0 },  
  64. D3DD3CL_END()  
  65. };  
  66.   
  67. //如果这么做的话 这个将一个CGresource枚举到一个输入缓存器中   
  68. BYTE cgD3D9ResourceToDeclUsage(CGresource resource);  
  69.   
  70. //写顶点说明必须根据程序参数来,减少引用语义   
  71. CGparameter position = cgGetNamedParameter(program, "position");  
  72. CGparameter color = cgGetNamedParameter(program, "color");  
  73. CGparameter texCoord = cgGetNamedParameter(program, "texCoord");  
  74.   
  75. const D3DVERTEXELEMENT9 declaration[] = {  
  76. { 0, 0 * sizeof(float),  
  77. D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  
  78. cgD3D9ResourceToDeclUsage(  
  79. cgGetParameterResource(position)),  
  80. cgGetParameterResourceIndex(position) },  
  81. { 0, 3 * sizeof(float),  
  82. D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,  
  83. cgD3D9ResourceToDeclUsage(cgGetParameterResource(color)),  
  84. cgGetParameterResourceIndex(color) },  
  85. { 1, 4 * sizeof(float),  
  86. D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,  
  87. cgD3D9ResourceToDeclUsage(  
  88. cgGetParameterResource(texCoord)),  
  89. cgGetParameterResourceIndex(texCoord) },  
  90. D3DD3CL_END()  
  91. };  
  92.   
  93. //检索   
  94. DWORD cgD3D9TypeToSize(CGtype type);  
//Direct3D 9
CGbool cgD3D9GetVertexDeclaration(CGprogram program,
						D3DVERTEXELEMENT9 declaration[MAXD3DDECLLENGTH]);
//MAXD3DDECLLENGTH 是Direct3D 9的常量,给Direct3 0声明的最大长度,如果程序中没有得到声明,会返回一个CG_FALSE

//返回值对于以下程序
void main(in float4 position : POSITION,
		in float4 color : COLOR0,
		in float4 texCoord : TEXCOORD0,
		out float4 hpos : POSITION)
{ }

//等同于 Direct3D 9 Cg runtime
const D3DVERTEXELEMENT9 declaration[] = {
{ 0, 0 * sizeof(float),
D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_POSITION, 0 },
{ 0, 4 * sizeof(float),
D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_COLOR, 0 },
{ 0, 8 * sizeof(float),
D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_TEXCOORD, 0 },
D3DD3CL_END()
};

//测试是否兼容程序
CGbool cgD3D9ValidateVertexDeclaration(CGprogram program,
const D3DVERTEXELEMENT9* declaration);   //Direct 9 
CGbool cgD3D8ValidateVertexDeclaration(CGprogram program,
const DWORD* declaration);  			//Direct 8 

//有效声明例如:
void main(float4 position : POSITION,
	float4 color : COLOR0,
	float4 texCoord : TEXCOORD0)
{ }

//等同于 Derect3D 9
const D3DVERTEXELEMENT9 declaration[] = {
{ 0, 0 * sizeof(float),
D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_POSITION, 0 },
{ 0, 3 * sizeof(float),
D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_COLOR, 0 },
{ 1, 4 * sizeof(float),
D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_TEXCOORD, 0 },
D3DD3CL_END()
};

//以上声明也可以写为
const D3DVERTEXELEMENT9 declaration[] = {
{ 0, 0 * sizeof(float),
D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
cgD3D9ResourceToDeclUsage(CG_POSITION), 0 },
{ 0, 3 * sizeof(float),
D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
cgD3D9ResourceToDeclUsage(CG_COLOR0), 0 },
{ 1, 4 * sizeof(float),
D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,
cgD3D9ResourceToDeclUsage(CG_TEXCOORD0), 0 },
D3DD3CL_END()
};

//如果这么做的话 这个将一个CGresource枚举到一个输入缓存器中
BYTE cgD3D9ResourceToDeclUsage(CGresource resource);

//写顶点说明必须根据程序参数来,减少引用语义
CGparameter position = cgGetNamedParameter(program, "position");
CGparameter color = cgGetNamedParameter(program, "color");
CGparameter texCoord = cgGetNamedParameter(program, "texCoord");

const D3DVERTEXELEMENT9 declaration[] = {
{ 0, 0 * sizeof(float),
D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
cgD3D9ResourceToDeclUsage(
cgGetParameterResource(position)),
cgGetParameterResourceIndex(position) },
{ 0, 3 * sizeof(float),
D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
cgD3D9ResourceToDeclUsage(cgGetParameterResource(color)),
cgGetParameterResourceIndex(color) },
{ 1, 4 * sizeof(float),
D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,
cgD3D9ResourceToDeclUsage(
cgGetParameterResource(texCoord)),
cgGetParameterResourceIndex(texCoord) },
D3DD3CL_END()
};

//检索
DWORD cgD3D9TypeToSize(CGtype type);

Minimal Interface ProgramExamples 低端接口程序实例

  1. //Vertex Program 顶点程序   
  2. void VertexProgram(  
  3.     in float4 position : POSITION,  
  4.     in float4 color : COLOR0,  
  5.     in float4 texCoord : TEXCOORD0,  
  6.     out float4 positionO : POSITION,  
  7.     out float4 colorO : COLOR0,  
  8.     out float4 texCoordO : TEXCOORD0,  
  9.     const uniform float4x4 ModelViewMatrix)  
  10. {  
  11.     positionO = mul(position, ModelViewMatrix);  
  12.     colorO = color;  
  13.     texCoordO = texCoord;  
  14. }  
  15.   
  16. //Fragment Program 片段程序   
  17. void FragmentProgram(  
  18.     in float4 color : COLOR0,  
  19.     in float4 texCoord : TEXCOORD0,  
  20.     out float4 colorO : COLOR0,  
  21.     const uniform sampler2D BaseTexture,  
  22.     const uniform float4 SomeColor)  
  23. {  
  24.     colorO = color * tex2D(BaseTexture, texCoord) + SomeColor;  
  25. }  
  26.   
  27. //Direct3D 9 Application DX9应用   
  28. #include <cg/cg.h>   
  29. #include <cg/cgD3D9.h>   
  30. IDirect3DDevice9* device; // Initialized somewhere else 别处初始化   
  31. IDirect3DTexture9* texture; // Initialized somewhere else   
  32. D3DXMATRIX matrix; // Initialized somewhere else   
  33. D3DXCOLOR constantColor; // Initialized somewhere else   
  34. CGcontext context;  
  35. CGprogram vertexProgram, fragmentProgram;  
  36. IDirect3DVertexDeclaration9* vertexDeclaration;  
  37. IDirect3DVertexShader9* vertexShader;  
  38. IDirect3DPixelShader9* pixelShader;  
  39. CGparameter baseTexture, someColor, modelViewMatrix;  
  40. // Called at application startup 应用启动   
  41. void OnStartup()  
  42. {  
  43.     // Create context 创建context   
  44.     context = cgCreateContext();  
  45. }  
  46.   
  47. // Called whenever the Direct3D device needs to be created 启动当Direct3D设备需要创建的时候   
  48. void OnCreateDevice()  
  49. {  
  50. // Create the vertex shader 创建顶点着色器   
  51. vertexProgram = cgCreateProgramFromFile(context, CG_SOURCE,  
  52. "VertexProgram.cg", CG_PROFILE_VS_2_0, "VertexProgram", 0);  
  53. CComPtr<ID3DXBuffer> byteCode;  
  54. const char* progSrc = cgGetProgramString(vertexProgram, CG_COMPILED_PROGRAM);  
  55. D3DXAssembleShader(progSrc, strlen(progSrc), 0, 0, 0, &byteCode, 0);  
  56.   
  57. // If your program uses explicit binding semantics (like this one), you can create a vertex declaration using those semantics.如果程序使用明确的约束语义,可以创建一个顶点声明来使用这些语义   
  58. const D3DVERTEXELEMENT9 declaration[] = {  
  59. { 0, 0 * sizeof(float),  
  60. D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  
  61. D3DDECLUSAGE_POSITION, 0 },  
  62. { 0, 3 * sizeof(float),  
  63. D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,  
  64. D3DDECLUSAGE_COLOR, 0 },  
  65. { 0, 4 * sizeof(float),  
  66. D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,  
  67. D3DDECLUSAGE_TEXCOORD, 0 },  
  68. D3DD3CL_END()  
  69. };  
  70.   
  71. // Make sure the resulting declaration is compatible with the shader. This is really just a sanity check. 确保创建的声明是兼容的,这里是一个健全的检查   
  72. assert(cgD3D9ValidateVertexDeclaration(vertexProgram, declaration));  
  73. device->CreateVertexDeclaration(declaration, &vertexDeclaration);  
  74. device->CreateVertexShader(byteCode->GetBufferPointer(), &vertexShader);  
  75.   
  76. // Create the pixel shader.创建像素着色器   
  77. fragmentProgram = cgCreateProgramFromFile(context,  
  78. CG_SOURCE, "FragmentProgram.cg",  
  79. CG_PROFILE_PS_2_0, "FragmentProgram", 0);  
  80. {  
  81.     CComPtr<ID3DXBuffer> byteCode;  
  82. const char* progSrc = cgGetProgramString(fragmentProgram, CG_COMPILED_PROGRAM);  
  83. D3DXAssembleShader(progSrc, strlen(progSrc), 0, 0, 0, &byteCode, 0);  
  84. device->CreatePixelShader(byteCode->GetBufferPointer(), &pixelShader)  
  85. }  
  86.   
  87. // Grab some parameters. 获取一些参数   
  88. modelViewMatrix = cgGetNamedParameter(vertexProgram, "ModelViewMatrix");  
  89. baseTexture = cgGetNamedParameter(fragmentProgram, "BaseTexture");  
  90. someColor = cgGetNamedParameter(fragmentProgram, "SomeColor");  
  91.   
  92. // Sanity check that parameters have the expected size 检查参数的预期大小   
  93. assert(cgD3D9TypeToSize(cgGetParameterType(modelViewMatrix)) == 16);  
  94. assert(cgD3D9TypeToSize(cgGetParameterType(someColor)) == 4);  
  95. }  
  96.   
  97.   
  98.   
  99. // Called to render the scene 渲染场景   
  100. void OnRender()  
  101. {  
  102. // Get the Direct3D resource locations for parameters This can be done earlier and saved 早期获取Direct3D资源参数保存   
  103. DWORD modelViewMatrixRegister = cgGetParameterResourceIndex(modelViewMatrix);  
  104. DWORD baseTextureUnit = cgGetParameterResourceIndex(baseTexture);  
  105. DWORD someColorRegister = cgGetParameterResourceIndex(someColor);  
  106.   
  107. // Set the Direct3D state.设置Direct3D状态   
  108. device->SetVertexShaderConstantF(modelViewMatrixRegister, &matrix, 4);  
  109. device->SetPixelShaderConstantF(someColorRegister, &constantColor, 1);  
  110. device->SetVertexDeclaration(vertexDeclaration);  
  111. device->SetTexture(baseTextureUnit, texture);  
  112. device->SetVertexShader(vertexShader);  
  113. device->SetPixelShader(pixelShader);  
  114. // Draw scene.   
  115. // ...   
  116. }  
  117.   
  118.   
  119. // Called before the device changes or is destroyed调用在设备改变或者终止之前   
  120. void OnDestroyDevice()   
  121. {  
  122.     vertexShader->Release();  
  123.     pixelShader->Release();  
  124.     vertexDeclaration->Release();  
  125. }  
  126.   
  127.   
  128. // Called before application shuts down调用在程序关闭之前   
  129. void OnShutdown()   
  130. {  
  131. // This frees any core runtime resources. The minimal interface has no dynamic storage to free.释放所有资源,低配接口没用动态资源释放   
  132.     cgDestroyContext(context);  
  133. }  
//Vertex Program 顶点程序
void VertexProgram(
	in float4 position : POSITION,
	in float4 color : COLOR0,
	in float4 texCoord : TEXCOORD0,
	out float4 positionO : POSITION,
	out float4 colorO : COLOR0,
	out float4 texCoordO : TEXCOORD0,
	const uniform float4x4 ModelViewMatrix)
{
	positionO = mul(position, ModelViewMatrix);
	colorO = color;
	texCoordO = texCoord;
}

//Fragment Program 片段程序
void FragmentProgram(
	in float4 color : COLOR0,
	in float4 texCoord : TEXCOORD0,
	out float4 colorO : COLOR0,
	const uniform sampler2D BaseTexture,
	const uniform float4 SomeColor)
{
	colorO = color * tex2D(BaseTexture, texCoord) + SomeColor;
}

//Direct3D 9 Application DX9应用
#include <cg/cg.h>
#include <cg/cgD3D9.h>
IDirect3DDevice9* device; // Initialized somewhere else 别处初始化
IDirect3DTexture9* texture; // Initialized somewhere else
D3DXMATRIX matrix; // Initialized somewhere else
D3DXCOLOR constantColor; // Initialized somewhere else
CGcontext context;
CGprogram vertexProgram, fragmentProgram;
IDirect3DVertexDeclaration9* vertexDeclaration;
IDirect3DVertexShader9* vertexShader;
IDirect3DPixelShader9* pixelShader;
CGparameter baseTexture, someColor, modelViewMatrix;
// Called at application startup 应用启动
void OnStartup()
{
	// Create context 创建context
	context = cgCreateContext();
}

// Called whenever the Direct3D device needs to be created 启动当Direct3D设备需要创建的时候
void OnCreateDevice()
{
// Create the vertex shader 创建顶点着色器
vertexProgram = cgCreateProgramFromFile(context, CG_SOURCE,
"VertexProgram.cg", CG_PROFILE_VS_2_0, "VertexProgram", 0);
CComPtr<ID3DXBuffer> byteCode;
const char* progSrc = cgGetProgramString(vertexProgram, CG_COMPILED_PROGRAM);
D3DXAssembleShader(progSrc, strlen(progSrc), 0, 0, 0, &byteCode, 0);

// If your program uses explicit binding semantics (like this one), you can create a vertex declaration using those semantics.如果程序使用明确的约束语义,可以创建一个顶点声明来使用这些语义
const D3DVERTEXELEMENT9 declaration[] = {
{ 0, 0 * sizeof(float),
D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_POSITION, 0 },
{ 0, 3 * sizeof(float),
D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_COLOR, 0 },
{ 0, 4 * sizeof(float),
D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_TEXCOORD, 0 },
D3DD3CL_END()
};

// Make sure the resulting declaration is compatible with the shader. This is really just a sanity check. 确保创建的声明是兼容的,这里是一个健全的检查
assert(cgD3D9ValidateVertexDeclaration(vertexProgram, declaration));
device->CreateVertexDeclaration(declaration, &vertexDeclaration);
device->CreateVertexShader(byteCode->GetBufferPointer(), &vertexShader);

// Create the pixel shader.创建像素着色器
fragmentProgram = cgCreateProgramFromFile(context,
CG_SOURCE, "FragmentProgram.cg",
CG_PROFILE_PS_2_0, "FragmentProgram", 0);
{
	CComPtr<ID3DXBuffer> byteCode;
const char* progSrc = cgGetProgramString(fragmentProgram, CG_COMPILED_PROGRAM);
D3DXAssembleShader(progSrc, strlen(progSrc), 0, 0, 0, &byteCode, 0);
device->CreatePixelShader(byteCode->GetBufferPointer(), &pixelShader)
}

// Grab some parameters. 获取一些参数
modelViewMatrix = cgGetNamedParameter(vertexProgram, "ModelViewMatrix");
baseTexture = cgGetNamedParameter(fragmentProgram, "BaseTexture");
someColor = cgGetNamedParameter(fragmentProgram, "SomeColor");

// Sanity check that parameters have the expected size 检查参数的预期大小
assert(cgD3D9TypeToSize(cgGetParameterType(modelViewMatrix)) == 16);
assert(cgD3D9TypeToSize(cgGetParameterType(someColor)) == 4);
}



// Called to render the scene 渲染场景
void OnRender()
{
// Get the Direct3D resource locations for parameters This can be done earlier and saved 早期获取Direct3D资源参数保存
DWORD modelViewMatrixRegister = cgGetParameterResourceIndex(modelViewMatrix);
DWORD baseTextureUnit = cgGetParameterResourceIndex(baseTexture);
DWORD someColorRegister = cgGetParameterResourceIndex(someColor);

// Set the Direct3D state.设置Direct3D状态
device->SetVertexShaderConstantF(modelViewMatrixRegister, &matrix, 4);
device->SetPixelShaderConstantF(someColorRegister, &constantColor, 1);
device->SetVertexDeclaration(vertexDeclaration);
device->SetTexture(baseTextureUnit, texture);
device->SetVertexShader(vertexShader);
device->SetPixelShader(pixelShader);
// Draw scene.
// ...
}


// Called before the device changes or is destroyed调用在设备改变或者终止之前
void OnDestroyDevice() 
{
	vertexShader->Release();
	pixelShader->Release();
	vertexDeclaration->Release();
}


// Called before application shuts down调用在程序关闭之前
void OnShutdown() 
{
// This frees any core runtime resources. The minimal interface has no dynamic storage to free.释放所有资源,低配接口没用动态资源释放
	cgDestroyContext(context);
}

 

Direct3D Expanded Interface 高配接口

       如果你想使用高配接口,尽量避免那些意外的错误,明确按照高配接口的相关着色器操作来执行,如着色器设定,着色器活化和参数设定包括设置纹理状态。

  1. //设置Direct3D设备   
  2. HRESULT cgD3D9SetDevice(IDirect3DDevice9* device);  
  3. //获得当前设备关联   
  4. IDirect3DDevice9* cgD3D9GetDevice();  
  5.   
  6. //丢失设备时   
  7. IDirect3DDevice9* device; // Initialized elsewhere   
  8. IDirect3DTexture9* myDefaultPoolTexture;  
  9. CGprogram program;  
  10. void OneTimeLoadScene()  
  11. {  
  12. // Load the program with cgD3D9LoadProgram and enable parameter shadowing读取程序和启动映射   
  13. /* ... */  
  14. cgD3D9LoadProgram(program, TRUE, 0, 0, 0);  
  15. /* ... */  
  16. // Bind sampler parameter 绑定采样参数   
  17. GCparameter parameter;  
  18. parameter = cgGetParameterByName(program, "MySampler");  
  19. cgD3D9SetTexture(parameter, myDefaultPoolTexture);  
  20. }  
  21. void OnLostDevice()  
  22. {  
  23. // First release all necessary resources 第一释放所有所需资源   
  24. PrepareForReset();  
  25. // Next actually reset the Direct3D device下一步重新设置设备   
  26. device->Reset( /* ... */ );  
  27. // Finally recreate all those resource最后重建资源   
  28. OnReset();  
  29. }  
  30. void PrepareForReset()  
  31. {  
  32. /* ... */  
  33. // Release expanded interface reference释放高配接口关联   
  34. cgD3D9SetTexture(mySampler, 0);  
  35. // Release local reference and any other references to the texture释放本地关联和其他任何与纹理有关的关联   
  36. myDefaultPoolTexture->Release();  
  37. /* ... */  
  38. }  
  39. void OnReset()  
  40. {  
  41. // Recreate myDefaultPoolTexture in D3DPOOL_DEFAULT重建纹理池   
  42. /* ... */  
  43. // Since the texture was just recreated,it must be re-bound to the parameter再现纹理必须重新绑定参数   
  44. GCparameter parameter;  
  45. parameter = cgGetParameterByName(prog, "MySampler");  
  46. cgD3D9SetTexture(mySampler, myDefaultPoolTexture);  
  47. /* ... */  
  48. }  
  49.   
  50. //提供参数类型   
  51. HRESULT cgD3D9SetUniform(CGparameter parameter, const void* value);  
  52.   
  53. D3DXVECTOR3 vectorData(1,2,3);  
  54. float matrixData[2][3] = {{1, 2, 3}, {4, 5, 6}};  
  55. float arrayData[3][2][2] ={{{1, 2}, {3, 4}},{{5, 6},{7,8}}, {{9, 10}, {11, 12}}};  
  56. cgD3D9SetUniform(vectorParam, &vectorData);  
  57. cgD3D9SetUniform(matrixParam, matrixData);  
  58. cgD3D9SetUniform(arrayParam, arrayData);  
  59.   
  60. HRESULT cgD3D9SetUniformMatrix(CGparameter parameter, const D3DMATRIX* matrix);  
  61. D3DXMATRIX matrix(  
  62.     1, 1, 1, 0,  
  63.     1, 1, 1, 0,  
  64.     0, 0, 0, 0,  
  65.     0, 0, 0, 0,  
  66. );  
  67. cgD3D9SetUniformMatrix(matrixParam, &matrix);  
  68.   
  69. //设置标量,向量矩阵参数统一数值   
  70. HRESULT cgD3D9SetUniformArray(CGparameter parameter, DWORD startIndex, DWORD                                    numberOfElements,const void* array);  
  71. HRESULT cgD3D9SetUniformMatrixArray(CGparameter parameter, DWORD startIndex,                                DWORD numberOfElements, const D3DMATRIX* matrices);  
  72.   
  73. //采样参数设置   
  74. HRESULT cgD3D9SetTexture(CGparameter parameter, IDirect3DBaseTexture9*                              texture);  
  75. HRESULT cgD3D9SetSamplerState(CGparameter parameter, D3DSAMPLERSTATETYPE type,                          DWORD value);  
  76.   
  77. cgD3D9SetSamplerState(parameter, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);  
  78.   
  79. //纹理包设置   
  80. HRESULT cgD3D9SetTextureWrapMode(CGparameter parameter, DWORD value);  
  81. cgD3D9SetTextureWrapMode(parameter, D3DWRAP_U | D3DWRAP_V);  
  82.   
  83. //参数映射   
  84. HRESULT cgD3D9EnableParameterShadowing(CGprogram program, CGbool enable);  
  85. //是否启用映射   
  86. CGbool cgD3D9IsParameterShadowingEnabled(CGprogam program);  
  87.   
  88. //高配接口程序执行   
  89. HRESULT cgD3D9LoadProgram(CGprogram program, CG_BOOL parameterShadowingEnabled,  
  90.                             DWORD assembleFlags);  
  91.   
  92. HRESULT hresult = cgD3D9LoadProgram(vertexProgram, TRUE, D3DXASM_DEBUG);  
  93. HRESULT hresult = cgD3D9LoadProgram(fragmentProgram, TRUE, 0);  
  94.   
  95. //释放程序   
  96. HRESULT cgD3D9UnloadProgam(CGprogram program);  
  97.   
  98. //绑定程序   
  99. HRESULT cgD3D9BindProgram(CGprogram program);  
  100.   
  101. //高配接口配置文件   
  102. CGprofile cgD3D9GetLatestVertexProfile();  
  103. CGprofile cgD3D9GetLatestPixelProfile();  
  104.   
  105. //返回最佳的编译选项给一个配置文件   
  106. char const* cgD3D9GetOptimalOptions(CGprofile profile);  
  107.   
  108. //高配接口程序实例   
  109.   
  110. //VertexProgram.cg   
  111. void VertexProgram(  
  112. in float4 position : POSITION,  
  113. in float4 color : COLOR0,  
  114. in float4 texCoord : TEXCOORD0,  
  115. out float4 positionO : POSITION,  
  116. out float4 colorO : COLOR0,  
  117. out float4 texCoordO : TEXCOORD0,  
  118. const uniform float4x4 ModelViewMatrix)  
  119. {  
  120.     positionO = mul(position, ModelViewMatrix);  
  121.     colorO = color;  
  122.     texCoordO = texCoord; }  
  123.   
  124. //FragmentProgram.cg   
  125. void FragmentProgram(  
  126. in float4 color : COLOR0,  
  127. in float4 texCoord : TEXCOORD0,  
  128. out float4 colorO : COLOR0,  
  129. const uniform sampler2D BaseTexture,  
  130. const uniform float4 SomeColor)  
  131. {  
  132.     colorO = color * tex2D(BaseTexture, texCoord) + SomeColor;  
  133. }  
  134.   
  135. //Direct3D 9 应用程序   
  136. #include <cg/cg.h>   
  137. #include <cg/cgD3D9.h>   
  138. IDirect3DDevice9* device; // Initialized somewhere else 别处初始化   
  139. IDirect3DTexture9* texture; // Initialized somewhere else   
  140. D3DXCOLOR constantColor; // Initialized somewhere else   
  141. CGcontext context;  
  142. IDirect3DVertexDeclaration9* vertexDeclaration;  
  143. CGprogram vertexProgram, fragmentProgram;  
  144. CGparameter baseTexture, someColor, modelViewMatrix;  
  145. // Called at application startup 应用打开时调用   
  146. void OnStartup()  
  147. {  
  148. // Create context 创建连接   
  149. context = cgCreateContext();  
  150. }  
  151.   
  152. // Called whenever the Direct3D device needs to be created设备连接时调用   
  153. void OnCreateDevice()  
  154. {  
  155. // Pass the Direct3D device to the expanded interface.把高配接口传给设备   
  156. cgD3D9SetDevice(device);  
  157. // Determine the best profiles to use确定最佳配置文件   
  158. CGprofile vertexProfile = cgD3D9GetLatestVertexProfile();  
  159. CGprofile pixelProfile = cgD3D9GetLatestPixelProfile();  
  160.   
  161. // Grab the optimal options for each profile.获取配置文件的最佳选择   
  162. const char* vertexOptions[] = {cgD3D9GetOptimalOptions(vertexProfile), 0 };  
  163. const char* pixelOptions[] = { cgD3D9GetOptimalOptions(pixelProfile), 0 };  
  164.   
  165. // Create the vertex shader.创建顶点着色器   
  166. vertexProgram = cgCreateProgramFromFile(  
  167. context, CG_SOURCE, "VertexProgram.cg",vertexProfile, "VertexProgram", vertexOptions);  
  168.   
  169. // If your program uses explicit binding semantics, you can create a vertex declaration using those semantics.如果你的程序使用明确的约束语义,可以创建一个顶点声明使用这些语义   
  170. const D3DVERTEXELEMENT9 declaration[] = {  
  171. { 0, 0 * sizeof(float),  
  172. D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,  
  173. D3DDECLUSAGE_POSITION, 0 },  
  174. { 0, 3 * sizeof(float),  
  175. D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,  
  176. D3DDECLUSAGE_COLOR, 0 },  
  177. { 0, 4 * sizeof(float),  
  178. D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,  
  179. D3DDECLUSAGE_TEXCOORD, 0 },  
  180. D3DD3CL_END()  
  181. };  
  182.   
  183. // Ensure the resulting declaration is compatible with the shader. This is really just a sanity check. 确保结果声明通过着色器完成,已经通过完全检查   
  184. assert(cgD3D9ValidateVertexDeclaration(vertexProgram, declaration));  
  185. device->CreateVertexDeclaration(declaration, &vertexDeclaration);  
  186.   
  187. // Load the program with the expanded interface. Parameter shadowing is enabled (second parameter = TRUE).从高配接口读取程序,参数映射启用。   
  188. cgD3D9LoadProgram(vertexProgram, TRUE, 0);  
  189.   
  190. // Create the pixel shader.创建像素着色器   
  191. fragmentProgram = cgCreateProgramFromFile( context, CG_SOURCE, "FragmentProgram.cg", pixelProfile, "FragmentProgram", pixelOptions);  
  192.   
  193. // Load the program with the expanded interface. Parameter shadowing is enabled (second parameter = TRUE). Ignore vertex shader specifc flags, such as declaration usage. .从高配接口读取程序,参数映射启用,忽略顶点着色器特殊标志,就像使用声明。   
  194. cgD3D9LoadProgram(fragmentProgram, TRUE, 0);  
  195.   
  196. // Grab some parameters.获取参数   
  197. modelViewMatrix = cgGetNamedParameter(vertexProgram, "ModelViewMatrix");  
  198. baseTexture = cgGetNamedParameter(fragmentProgram,"BaseTexture");  
  199. someColor = cgGetNamedParameter(fragmentProgram, "SomeColor");  
  200.   
  201. // Sanity check that parameters have the expected size明确检查参数的预期大小   
  202. assert(cgD3D9TypeToSize(cgGetParameterType(modelViewMatrix)) == 16);  
  203. assert(cgD3D9TypeToSize(cgGetParameterType(someColor))== 4);  
  204.   
  205. // Set parameters that don't change. They can be set only once since parameter shadowing is enabled 设置参数不能改变,他们设置只能参数绑定启用时   
  206. cgD3D9SetTexture(baseTexture, texture);  
  207. cgD3D9SetUniform(someColor, &constantColor);  
  208. }  
  209.   
  210. // Called to render the scene渲染场景时调用   
  211. void OnRender()  
  212. {  
  213. // Load model-view matrix.读取可视模型矩阵   
  214. D3DXMATRIX modelViewMatrix;  
  215. // ...   
  216. // Set the parameters that change every frame This must be done before binding the programs 设定每帧参数修改,在绑定程序之前   
  217. cgD3D9SetUniformMatrix(modelViewMatrix, &modelViewMatrix);  
  218.   
  219. // Set the vertex declaration设置顶顶声明   
  220. device->SetVertexDeclaration(vertexDeclaration);  
  221.   
  222. // Bind the programs. This downloads any parameter values that have been previously set.绑定程序,下载先前设定的参数   
  223. cgD3D9BindProgram(vertexProgram);  
  224. cgD3D9BindProgram(fragmentProgram);  
  225.   
  226. // Draw scene.绘制场景   
  227. // ...   
  228. }  
  229. // Called before the device changes or is destroyed 设备改变或终止时调用   
  230. void OnDestroyDevice()  
  231. {  
  232. // Calling this function tells the expanded interface to release its internal reference to the Direct3D device and free its Direct3D resources. 释放高配接口的内部关联对Direct3D设备和资源。   
  233.     cgD3D9SetDevice(0);  
  234. }  
  235. // Called before application shuts down 应用关闭时调用   
  236. void OnShutdown()  
  237. {  
  238. // This frees any core runtime resource.释放核心资源   
  239.     cgDestroyContext(context);  
  240. }  
//设置Direct3D设备
HRESULT cgD3D9SetDevice(IDirect3DDevice9* device);
//获得当前设备关联
IDirect3DDevice9* cgD3D9GetDevice();

//丢失设备时
IDirect3DDevice9* device; // Initialized elsewhere
IDirect3DTexture9* myDefaultPoolTexture;
CGprogram program;
void OneTimeLoadScene()
{
// Load the program with cgD3D9LoadProgram and enable parameter shadowing读取程序和启动映射
/* ... */
cgD3D9LoadProgram(program, TRUE, 0, 0, 0);
/* ... */
// Bind sampler parameter 绑定采样参数
GCparameter parameter;
parameter = cgGetParameterByName(program, "MySampler");
cgD3D9SetTexture(parameter, myDefaultPoolTexture);
}
void OnLostDevice()
{
// First release all necessary resources 第一释放所有所需资源
PrepareForReset();
// Next actually reset the Direct3D device下一步重新设置设备
device->Reset( /* ... */ );
// Finally recreate all those resource最后重建资源
OnReset();
}
void PrepareForReset()
{
/* ... */
// Release expanded interface reference释放高配接口关联
cgD3D9SetTexture(mySampler, 0);
// Release local reference and any other references to the texture释放本地关联和其他任何与纹理有关的关联
myDefaultPoolTexture->Release();
/* ... */
}
void OnReset()
{
// Recreate myDefaultPoolTexture in D3DPOOL_DEFAULT重建纹理池
/* ... */
// Since the texture was just recreated,it must be re-bound to the parameter再现纹理必须重新绑定参数
GCparameter parameter;
parameter = cgGetParameterByName(prog, "MySampler");
cgD3D9SetTexture(mySampler, myDefaultPoolTexture);
/* ... */
}

//提供参数类型
HRESULT cgD3D9SetUniform(CGparameter parameter, const void* value);

D3DXVECTOR3 vectorData(1,2,3);
float matrixData[2][3] = {{1, 2, 3}, {4, 5, 6}};
float arrayData[3][2][2] ={{{1, 2}, {3, 4}},{{5, 6},{7,8}}, {{9, 10}, {11, 12}}};
cgD3D9SetUniform(vectorParam, &vectorData);
cgD3D9SetUniform(matrixParam, matrixData);
cgD3D9SetUniform(arrayParam, arrayData);

HRESULT cgD3D9SetUniformMatrix(CGparameter parameter, const D3DMATRIX* matrix);
D3DXMATRIX matrix(
	1, 1, 1, 0,
	1, 1, 1, 0,
	0, 0, 0, 0,
	0, 0, 0, 0,
);
cgD3D9SetUniformMatrix(matrixParam, &matrix);

//设置标量,向量矩阵参数统一数值
HRESULT cgD3D9SetUniformArray(CGparameter parameter, DWORD startIndex, DWORD 									numberOfElements,const void* array);
HRESULT cgD3D9SetUniformMatrixArray(CGparameter parameter, DWORD startIndex, 								DWORD numberOfElements, const D3DMATRIX* matrices);

//采样参数设置
HRESULT cgD3D9SetTexture(CGparameter parameter, IDirect3DBaseTexture9* 								texture);
HRESULT cgD3D9SetSamplerState(CGparameter parameter, D3DSAMPLERSTATETYPE type, 							DWORD value);

cgD3D9SetSamplerState(parameter, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);

//纹理包设置
HRESULT cgD3D9SetTextureWrapMode(CGparameter parameter, DWORD value);
cgD3D9SetTextureWrapMode(parameter, D3DWRAP_U | D3DWRAP_V);

//参数映射
HRESULT cgD3D9EnableParameterShadowing(CGprogram program, CGbool enable);
//是否启用映射
CGbool cgD3D9IsParameterShadowingEnabled(CGprogam program);

//高配接口程序执行
HRESULT cgD3D9LoadProgram(CGprogram program, CG_BOOL parameterShadowingEnabled,
							DWORD assembleFlags);

HRESULT hresult = cgD3D9LoadProgram(vertexProgram, TRUE, D3DXASM_DEBUG);
HRESULT hresult = cgD3D9LoadProgram(fragmentProgram, TRUE, 0);

//释放程序
HRESULT cgD3D9UnloadProgam(CGprogram program);

//绑定程序
HRESULT cgD3D9BindProgram(CGprogram program);

//高配接口配置文件
CGprofile cgD3D9GetLatestVertexProfile();
CGprofile cgD3D9GetLatestPixelProfile();

//返回最佳的编译选项给一个配置文件
char const* cgD3D9GetOptimalOptions(CGprofile profile);

//高配接口程序实例

//VertexProgram.cg
void VertexProgram(
in float4 position : POSITION,
in float4 color : COLOR0,
in float4 texCoord : TEXCOORD0,
out float4 positionO : POSITION,
out float4 colorO : COLOR0,
out float4 texCoordO : TEXCOORD0,
const uniform float4x4 ModelViewMatrix)
{
	positionO = mul(position, ModelViewMatrix);
	colorO = color;
	texCoordO = texCoord; }

//FragmentProgram.cg
void FragmentProgram(
in float4 color : COLOR0,
in float4 texCoord : TEXCOORD0,
out float4 colorO : COLOR0,
const uniform sampler2D BaseTexture,
const uniform float4 SomeColor)
{
	colorO = color * tex2D(BaseTexture, texCoord) + SomeColor;
}

//Direct3D 9 应用程序
#include <cg/cg.h>
#include <cg/cgD3D9.h>
IDirect3DDevice9* device; // Initialized somewhere else 别处初始化
IDirect3DTexture9* texture; // Initialized somewhere else
D3DXCOLOR constantColor; // Initialized somewhere else
CGcontext context;
IDirect3DVertexDeclaration9* vertexDeclaration;
CGprogram vertexProgram, fragmentProgram;
CGparameter baseTexture, someColor, modelViewMatrix;
// Called at application startup 应用打开时调用
void OnStartup()
{
// Create context 创建连接
context = cgCreateContext();
}

// Called whenever the Direct3D device needs to be created设备连接时调用
void OnCreateDevice()
{
// Pass the Direct3D device to the expanded interface.把高配接口传给设备
cgD3D9SetDevice(device);
// Determine the best profiles to use确定最佳配置文件
CGprofile vertexProfile = cgD3D9GetLatestVertexProfile();
CGprofile pixelProfile = cgD3D9GetLatestPixelProfile();

// Grab the optimal options for each profile.获取配置文件的最佳选择
const char* vertexOptions[] = {cgD3D9GetOptimalOptions(vertexProfile), 0 };
const char* pixelOptions[] = { cgD3D9GetOptimalOptions(pixelProfile), 0 };

// Create the vertex shader.创建顶点着色器
vertexProgram = cgCreateProgramFromFile(
context, CG_SOURCE, "VertexProgram.cg",vertexProfile, "VertexProgram", vertexOptions);

// If your program uses explicit binding semantics, you can create a vertex declaration using those semantics.如果你的程序使用明确的约束语义,可以创建一个顶点声明使用这些语义
const D3DVERTEXELEMENT9 declaration[] = {
{ 0, 0 * sizeof(float),
D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_POSITION, 0 },
{ 0, 3 * sizeof(float),
D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_COLOR, 0 },
{ 0, 4 * sizeof(float),
D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT,
D3DDECLUSAGE_TEXCOORD, 0 },
D3DD3CL_END()
};

// Ensure the resulting declaration is compatible with the shader. This is really just a sanity check. 确保结果声明通过着色器完成,已经通过完全检查
assert(cgD3D9ValidateVertexDeclaration(vertexProgram, declaration));
device->CreateVertexDeclaration(declaration, &vertexDeclaration);

// Load the program with the expanded interface. Parameter shadowing is enabled (second parameter = TRUE).从高配接口读取程序,参数映射启用。
cgD3D9LoadProgram(vertexProgram, TRUE, 0);

// Create the pixel shader.创建像素着色器
fragmentProgram = cgCreateProgramFromFile( context, CG_SOURCE, "FragmentProgram.cg", pixelProfile, "FragmentProgram", pixelOptions);

// Load the program with the expanded interface. Parameter shadowing is enabled (second parameter = TRUE). Ignore vertex shader specifc flags, such as declaration usage. .从高配接口读取程序,参数映射启用,忽略顶点着色器特殊标志,就像使用声明。
cgD3D9LoadProgram(fragmentProgram, TRUE, 0);

// Grab some parameters.获取参数
modelViewMatrix = cgGetNamedParameter(vertexProgram, "ModelViewMatrix");
baseTexture = cgGetNamedParameter(fragmentProgram,"BaseTexture");
someColor = cgGetNamedParameter(fragmentProgram, "SomeColor");

// Sanity check that parameters have the expected size明确检查参数的预期大小
assert(cgD3D9TypeToSize(cgGetParameterType(modelViewMatrix)) == 16);
assert(cgD3D9TypeToSize(cgGetParameterType(someColor))== 4);

// Set parameters that don't change. They can be set only once since parameter shadowing is enabled 设置参数不能改变,他们设置只能参数绑定启用时
cgD3D9SetTexture(baseTexture, texture);
cgD3D9SetUniform(someColor, &constantColor);
}

// Called to render the scene渲染场景时调用
void OnRender()
{
// Load model-view matrix.读取可视模型矩阵
D3DXMATRIX modelViewMatrix;
// ...
// Set the parameters that change every frame This must be done before binding the programs 设定每帧参数修改,在绑定程序之前
cgD3D9SetUniformMatrix(modelViewMatrix, &modelViewMatrix);

// Set the vertex declaration设置顶顶声明
device->SetVertexDeclaration(vertexDeclaration);

// Bind the programs. This downloads any parameter values that have been previously set.绑定程序,下载先前设定的参数
cgD3D9BindProgram(vertexProgram);
cgD3D9BindProgram(fragmentProgram);

// Draw scene.绘制场景
// ...
}
// Called before the device changes or is destroyed 设备改变或终止时调用
void OnDestroyDevice()
{
// Calling this function tells the expanded interface to release its internal reference to the Direct3D device and free its Direct3D resources. 释放高配接口的内部关联对Direct3D设备和资源。
	cgD3D9SetDevice(0);
}
// Called before application shuts down 应用关闭时调用
void OnShutdown()
{
// This frees any core runtime resource.释放核心资源
	cgDestroyContext(context);
}

 

Direct3D Debugging Mode 调试模式

         使用Debug DLL:

1.      连接应用程序到cgD3D9d.lib代替cgD3D9.lib。

2.      确定应用能找到cgD3D9d.dll。

3.      打开或者关闭跟踪代码

  1. void cgD3D9EnableDebugTracing(CGbool enable);  
void cgD3D9EnableDebugTracing(CGbool enable);

         这里有一个例子

  1. cgD3D9EnableDebugTracing(CG_TRUE);  
  2. // ...   
  3. // Application code that is traced   
  4. // ...   
  5. cgD3D9EnableDebugTracing(CG_FALSE);  
cgD3D9EnableDebugTracing(CG_TRUE);
// ...
// Application code that is traced
// ...
cgD3D9EnableDebugTracing(CG_FALSE);

        

         常见错误类型:

         CGerror:

                  cgD3D9Failed

             cgD3D9DebugTrace

          HRESULT:

             CGD3D9ERR_INVALIDPARAM

             CGD3D9ERR_INVALIDPROFILE

             CGD3D9ERR_INVALIDSAMPLERSTATE

             CGD3D9ERR_INVALIDVEREXDECL

             CGD3D9ERR_NODEVICE

             CGD3D9ERR_NOTMATRIX

             CGD3D9ERR_NOTLOADED

             CGD3D9ERR_NOTSAMPLER

             CGD3D9ERR_NOTUNIFORM

             CGD3D9ERR_NULLVALUE

             CGD3D9ERR_OUTOFRANGE

             CGD3D9_INVALID_REG

 

    测试错误

  1. HRESULT cgD3D9GetLastError();  
  2. const char* cgD3D9TranslateHRESULT(HRESULT hr);//转换成字符串  
HRESULT cgD3D9GetLastError();
const char* cgD3D9TranslateHRESULT(HRESULT hr);//转换成字符串

   

    错误回调

  1. void MyErrorCallback() {  
  2. CGerror error = cgGetError();  
  3. if (error == cgD3D9DebugTrace) {  
  4. // This is a debug trace output.   
  5. // A breakpoint could be set here to step from one   
  6. // debug output to the other.   
  7. return;  
  8. }  
  9. char buffer[1024];  
  10. if (error == cgD3D9Failed)  
  11. sprintf(buffer, "A Direct3D error occurred: %s'\n",  
  12. cgD3D9TranslateHRESULT(cgD3D9GetLastError()));  
  13. else  
  14. sprintf(buffer, "A Cg error occurred: '%s'\n",  
  15. cgD3D9TranslateCGerror(error));  
  16. OutputDebugString(buffer);  
  17. }  
  18. cgSetErrorCallback(MyErrorCallback);  
void MyErrorCallback() {
CGerror error = cgGetError();
if (error == cgD3D9DebugTrace) {
// This is a debug trace output.
// A breakpoint could be set here to step from one
// debug output to the other.
return;
}
char buffer[1024];
if (error == cgD3D9Failed)
sprintf(buffer, "A Direct3D error occurred: %s'\n",
cgD3D9TranslateHRESULT(cgD3D9GetLastError()));
else
sprintf(buffer, "A Cg error occurred: '%s'\n",
cgD3D9TranslateCGerror(error));
OutputDebugString(buffer);
}
cgSetErrorCallback(MyErrorCallback);


下期预告:

         Thinking in Shader(6)

posted @ 2013-03-23 18:27  小薇林  阅读(327)  评论(0编辑  收藏  举报