xna3.1与4.0的区别不小,但也不是很大,在转换一些项目时候下面的tip能给些帮助。原文地址是:http://blogs.msdn.com/b/shawnhar/archive/2011/01/04/xna-3-1-to-4-0-cheat-sheet.aspx?utm_source=twitterfeed&utm_medium=twitter

遇到如下问题,该备忘录将解决的问题:

The name ‘SpriteBlendMode‘ does not exist in the current context
The name ‘SaveStateMode‘ does not exist in the current context

‘Microsoft.Xna.Framework.Graphics.GraphicsDevice‘ does not contain a definition for ‘RenderState‘…

‘Microsoft.Xna.Framework.Graphics.Effect‘ does not contain a definition for ‘Begin‘ …
‘Microsoft.Xna.Framework.Graphics.Effect‘ does not contain a definition for ‘End‘..
‘Microsoft.Xna.Framework.Graphics.Effect‘ does not contain a definition for ‘CommitChanges‘ …
‘Microsoft.Xna.Framework.Graphics.EffectPass‘ does not contain a definition for ‘Begin‘ …
‘Microsoft.Xna.Framework.Graphics.EffectPass‘ does not contain a definition for ‘End‘ ….
No overload for method ‘Clone‘ takes 1 arguments

The name ‘ShaderProfile‘ does not exist in the current context
‘Microsoft.Xna.Framework.GameTime‘ does not contain a definition for ‘TotalRealTime‘ …
‘Microsoft.Xna.Framework.Color‘ does not contain a definition for ‘TransparentBlack‘ …

The type or namespace name ‘ResolveTexture2D‘ could not be found …
‘Microsoft.Xna.Framework.Graphics.GraphicsDevice‘ does not contain a definition for ‘ResolveBackBuffer‘…
The type or namespace name ‘DepthStencilBuffer‘ could not be found …

‘Microsoft.Xna.Framework.Graphics.RenderTarget2D‘ does not contain a constructor that takes 5 arguments
‘Microsoft.Xna.Framework.Graphics.RenderTarget2D‘ does not contain a definition for ‘GetTexture‘ …

‘Microsoft.Xna.Framework.Graphics.PresentationParameters‘ does not contain a definition for ‘MultiSampleType‘ …
‘Microsoft.Xna.Framework.Graphics.PresentationParameters‘ does not contain a definition for ‘MultiSampleQuality‘ …

The best overloaded method match for ‘Microsoft.Xna.Framework.Graphics.GraphicsDevice.SetRenderTarget

‘Microsoft.Xna.Framework.Graphics.GraphicsDevice‘ does not contain a definition for ‘VertexDeclaration
‘Microsoft.Xna.Framework.Graphics.GraphicsDevice‘ does not contain a definition for ‘Vertices

‘Microsoft.Xna.Framework.Graphics.VertexPositionTexture‘ does not contain a definition for ‘SizeInBytes
‘Microsoft.Xna.Framework.Graphics.VertexPositionTexture‘ does not contain a definition for ‘VertexElements

‘Microsoft.Xna.Framework.Graphics.ModelMesh‘ does not contain a definition for ‘IndexBuffer
‘Microsoft.Xna.Framework.Graphics.ModelMesh‘ does not contain a definition for ‘VertexBuffer

‘Microsoft.Xna.Framework.Graphics.ModelMeshPart‘ does not contain a definition for ‘BaseVertex
‘Microsoft.Xna.Framework.Graphics.ModelMeshPart‘ does not contain a definition for ‘StreamOffset
‘Microsoft.Xna.Framework.Graphics.ModelMeshPart‘ does not contain a definition for ‘VertexStride

‘Microsoft.Xna.Framework.Storage.StorageContainer‘ does not contain a definition for ‘TitleLocation
‘Microsoft.Xna.Framework.Storage.StorageContainer‘ does not contain a definition for ‘Path
‘Microsoft.Xna.Framework.Storage.StorageDevice‘ does not contain a definition for ‘OpenContainer
‘Microsoft.Xna.Framework.GamerServices.Guide‘ does not contain a definition for ‘BeginShowStorageDeviceSelector
‘Microsoft.Xna.Framework.GamerServices.Guide‘ does not contain a definition for ‘EndShowStorageDeviceSelector

syntax error: unexpected token ‘VertexShader
syntax error: unexpected token ‘PixelShader
error X3539: ps_1_x is no longer supported

PS:其他问题,如xna模型画出边界,看起来透明或者丢失顶点以及看起来不对劲。

----------------------------------------------------------------------------------------

XNA 3.1 转为 XNA4.0 的例子:

SpriteBlendMode, SaveStateMode

1 // XNA 3.1
2 sprite.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);
3 // XNA 4.0
4 sprite.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
5
6 // XNA 3.1
7 // 通过深度排列场景对象
1 spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront, SaveStateMode.None);
2 // XNA 4.0
3 // 通过深度排列场景对象
1 spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
2
3 // XNA 3.1
4 sprite.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState);
5 // XNA 4.0
6 sprite.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
7
8 // XNA 3.1
9 // 画背景图
1 spriteBatch.Begin(SpriteBlendMode.None);
2 Viewport viewport = GraphicsDevice.Viewport;
3 spriteBatch.Draw(background, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.White);
4 spriteBatch.End();
5 // XNA 4.0
6 // 画背景图
1 spriteBatch.Begin(0, BlendState.Opaque);
2 spriteBatch.Draw(background, GraphicsDevice.Viewport.Bounds, Color.White);
3 spriteBatch.End();

RenderState

1 // XNA 3.1
2 // 启用alpha混合和深度写
01 GraphicsDevice.RenderState.AlphaBlendEnable = true;
02 GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
03 GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
04 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
05 GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
06 GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One;
07 GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.One;
08 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
09 // XNA 4.0
10 // 启用alpha混合和深度写
1 GraphicsDevice.BlendState = BlendState.AlphaBlend;
2 GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
3
4 // XNA 3.1
5 // 重置混合和深度写
1 GraphicsDevice.RenderState.AlphaBlendEnable = false;
2 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
3 GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
4 // XNA 4.0
5 // 重置混合和深度写
1 GraphicsDevice.BlendState = BlendState.Additive;
2 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4 // XNA 3.1
5 // 启用深度缓冲
1 GraphicsDevice.RenderState.DepthBufferEnable = true;
2 // XNA 4.0
3 // 启用深度缓冲
1 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
2
3 // XNA 3.1
4 // 禁用深度缓冲
1 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
2 GraphicsDevice.RenderState.DepthBufferEnable = false;
3 // XNA 4.0
4 // 禁用深度缓冲
01 GraphicsDevice.DepthStencilState = DepthStencilState.None;
02
03 // XNA 3.1
04 // 累加混合(zero on alpha)
05 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
06 GraphicsDevice.RenderState.AlphaBlendEnable = true;
07 GraphicsDevice.RenderState.SourceBlend = Blend.One;
08 GraphicsDevice.RenderState.DestinationBlend = Blend.One;
09 // XNA 4.0
10 // 累加混合(zero on alpha)
11 GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
12 GraphicsDevice.BlendState = BlendState.AlphaBlend;
13
14 // XNA 3.1
15 // 恢复混合模式
1 GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
2 GraphicsDevice.RenderState.AlphaBlendEnable = false;
3 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
4 // XNA 4.0
5 // 恢复混合模式
1 GraphicsDevice.BlendState = BlendState.Opaque;
2 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4 // XNA 3.1
5 // 设置alpha混合,无深度测试和深度写
1 GraphicsDevice.RenderState.DepthBufferEnable = false;
2 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
3 GraphicsDevice.RenderState.AlphaBlendEnable = true;
4 GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
5 GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
6 // XNA 4.0
7 // 设置alpha混合,无深度测试和深度写
1 GraphicsDevice.DepthStencilState = DepthStencilState.None;
2 GraphicsDevice.BlendState = BlendState.AlphaBlend;
3
4 // XNA 3.1
5 // 绘制3D模型时设置合适渲染模式
1 GraphicsDevice.RenderState.AlphaBlendEnable = false;
2 GraphicsDevice.RenderState.AlphaTestEnable = false;
3 GraphicsDevice.RenderState.DepthBufferEnable = true;
4 // XNA 4.0
5 // 绘制3D模型时设置合适渲染模式
1 GraphicsDevice.BlendState = BlendState.Opaque;
2 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
3
4 // XNA 3.1
5 // 加性混合
1 GraphicsDevice.RenderState.AlphaBlendEnable = true;
2 GraphicsDevice.RenderState.SourceBlend = Blend.One;
3 GraphicsDevice.RenderState.DestinationBlend = Blend.One;
4 // XNA 4.0
5 // 加性混合
1 GraphicsDevice.BlendState = BlendState.Additive;
2
3 // XNA 3.1
4 // 设置加性混合
1 GraphicsDevice.RenderState.DestinationBlend = Blend.One;
2 // XNA 4.0
3 // 设置加性混合
1 GraphicsDevice.BlendState = BlendState.Additive;
2
3 // XNA 3.1
4 // 设置alpha混合
1 GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
2 // XNA 4.0
3 // 设置alpha混合
1 GraphicsDevice.BlendState = BlendState.AlphaBlend;
2
3 // XNA 3.1
4 GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;
5 // XNA 4.0
6 GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
7
8 // XNA 3.1
9 // 设置渲染状态
01 GraphicsDevice.RenderState.DepthBufferEnable = false;
02 GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
03 GraphicsDevice.RenderState.AlphaBlendEnable = true;
04 GraphicsDevice.RenderState.SourceBlend = Blend.One;
05 GraphicsDevice.RenderState.DestinationBlend = Blend.One;
06 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
07 GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
08 GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.Zero;
09 GraphicsDevice.RenderState.AlphaSourceBlend = Blend.Zero;
10
11       // drawing code here..
12
13 // 恢复状态
1 GraphicsDevice.RenderState.DepthBufferEnable = true;
2 GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
3 GraphicsDevice.RenderState.AlphaBlendEnable = false;
4 GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
5 // XNA 4.0
6 //存储状态
1 DepthStencilState ds = GraphicsDevice.DepthStencilState;
2 BlendState bs = GraphicsDevice.BlendState;
3
4 //设置渲染状态
1 GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
2 GraphicsDevice.BlendState = BlendState.AlphaBlend;
3
4        // drawing code here..
5
6 // 恢复状态
1 GraphicsDevice.DepthStencilState = ds;
2 GraphicsDevice.BlendState = bs;

Effect, EffectPass, Begin(), End(), CommitChanges(), Clone()

01 // 应用效果 XNA 3.1
02 blurEffect.CommitChanges();
03 blurEffect.Begin(SaveStateMode.SaveState);
04 blurEffect.CurrentTechnique.Passes[0].Begin();
05 GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
06 blurEffect.CurrentTechnique.Passes[0].End();
07 blurEffect.End();
08 // 应用效果 XNA 4.0
09 blurEffect.CurrentTechnique.Passes[0].Apply();
10 GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
11
12 // XNA 3.1
13 // 提交效果改变
1 effect.CommitChanges();
2 // XNA 4.0
3 //  当任何效果属性改变需要调用EffectPass.Apply()
1 // 否则就删除它
1 // XNA 3.1
2 // 开始一个效果
1 effect.Begin(SaveStateMode.SaveState);
2 effect.CurrentTechnique.Passes[0].Begin();
3 // XNA 4.0
4 // 开始一个效果
1 effect.CurrentTechnique.Passes[0].Apply();
2
3 // XNA 3.1
4 // 结束一个效果
1 effect.CurrentTechnique.Passes[0].End();
2 effect.End();
3 // XNA 4.0
4 // 如果不需要可直接删除
1 // XNA 3.1
2 // 产生一个效果的克隆体
1 Effect newEffect = replacementEffect.Clone(replacementEffect.GraphicsDevice);
2 // XNA 4.0
3 // 产生一个效果的克隆体
1 Effect newEffect = replacementEffect.Clone();
2
3 // XNA 3.1
4 // 启用效果中的tech
01 postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];    
02
03 // 用预处理效果画一个全屏的精灵.
04 spriteBatch.Begin(SpriteBlendMode.None,SpriteSortMode.Immediate, SaveStateMode.None);
05
06 postprocessEffect.Begin();
07 postprocessEffect.CurrentTechnique.Passes[0].Begin();
08
09 spriteBatch.Draw(sceneRenderTarget.GetTexture(), Vector2.Zero, Color.White);
10 spriteBatch.End();
11
12 postprocessEffect.CurrentTechnique.Passes[0].End();
13 postprocessEffect.End();
14 // XNA 4.0
15 // 启用效果中的tech
1 postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];
2
3 // 用预处理效果画一个全屏的精灵.
1 spriteBatch.Begin(0, BlendState.Opaque, null, null, null, postprocessEffect);
2 spriteBatch.Draw(sceneRenderTarget, Vector2.Zero, Color.White);
3 spriteBatch.End();

ShaderProfile, TotalRealTime, TransparentBlack

1 // XNA 3.1
2 graphics.MinimumPixelShaderProfile = ShaderProfile.PS_3_0; //any PS number...
3 graphics.MinimumVertexShaderProfile = ShaderProfile.VS_3_0;//any VS number...
4 // XNA 4.0
5 // 不再需要该语句
1 // XNA 3.1
2 float myTime = (float)gameTime.TotalRealTime.TotalSeconds * 0.2f;
3 // XNA 4.0
4 float myTime = (float)gameTime.TotalGameTime.TotalSeconds * 0.2f;
5
6 // XNA 3.1
7 GraphicsDevice.Clear(Color.TransparentBlack);
8 // XNA 4.0
9 GraphicsDevice.Clear(Color.Transparent);

ResolveTexture2D, ResolveBackBuffer, RenderTarget2D, GetTexture, DepthStencilBuffer, PresentationParameters, MultiSampleType, MultiSampleQuality, SetRenderTarget

01 // XNA 3.1
02 ResolveTexture2D sceneMap;
03 // XNA 4.0
04 RenderTarget2D sceneMap;
05
06 // XNA 3.1
07 // 查询主缓冲的分辨率和格式.
08 PresentationParameters pp = GraphicsDevice.PresentationParameters;
09
10 // 从缓冲读取一个材质数据.
11 sceneMap = new ResolveTexture2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, pp.BackBufferFormat);
12 // XNA 4.0
13 // 查询主缓冲的分辨率和格式.
14 PresentationParameters pp = GraphicsDevice.PresentationParameters;
15
16 // 从缓冲读取一个材质数据.
17 sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat,
18                                 pp.DepthStencilFormat);
19 //or
20
21 sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat,
22                                 pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
23
24 // XNA 3.1
25 GraphicsDevice.ResolveBackBuffer(sceneMap);
26 // XNA 4.0
27 GraphicsDevice.SetRenderTarget(sceneMap);
28
29 // XNA 3.1
30 int width = GraphicsDevice.Viewport.Width;
31 int height = GraphicsDevice.Viewport.Height;
32
33 // 创建渲染对象
1 myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, 1, SurfaceFormat.Color);
2 // XNA 4.0
3 int width = GraphicsDevice.Viewport.Width;
4 int height = GraphicsDevice.Viewport.Height;
5
6 // 创建渲染对象
1 myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, true, SurfaceFormat.Color, DepthFormat.Depth24);
2
3 // XNA 3.1
4 PresentationParameters pp = GraphicsDevice.PresentationParameters;
5
6 // 创建自动以渲染对象
1 sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
2                                    pp.BackBufferFormat, pp.MultiSampleType, pp.MultiSampleQuality);
3 // XNA 4.0
4 PresentationParameters pp = GraphicsDevice.PresentationParameters;
5
6 // 创建自动以渲染对象
1 sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false,
2                                    pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount,
3                                    RenderTargetUsage.DiscardContents);
4
5 // XNA 3.1
6 PresentationParameters pp = GraphicsDevice.PresentationParameters;
7
8 // 配置一个深度缓冲
1 drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
2                                 SurfaceFormat.Color, pp.MultiSampleType, pp.MultiSampleQuality);
3
4 drawDepthBuffer = new DepthStencilBuffer(GraphicsDevice, pp.AutoDepthStencilFormat,
5                                             pp.MultiSampleType, pp.MultiSampleQuality);
6 // XNA 4.0
7 PresentationParameters pp = GraphicsDevice.PresentationParameters;
8
9 // 配置一个深度缓冲
1 drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, true,
2                                 SurfaceFormat.Color,DepthFormat.Depth24Stencil8,
3                                 pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
4 //NOTE:  DepthStencilBuffer 类不再存在
1 // XNA 3.1
2 spriteBatch.Draw(myRenderTarget.GetTexture(), Vector2.Zero, Color.White);
3 // XNA 4.0
4 spriteBatch.Draw(myRenderTarget, Vector2.Zero, Color.White); // NOTE: ".GetTexure()"  不再需要
01 // XNA 3.1
02 Texture2D myTexture = myRenderTarget.GetTexture();
03 // XNA 4.0
04 Texture2D myTexture = myRenderTarget; // NOTE: ".GetTexure()"  No longer needed
05
06 // XNA 3.1
07 GraphicsDevice.SetRenderTarget(0, myRenderTarget);
08 // XNA 4.0
09 GraphicsDevice.SetRenderTarget(myRenderTarget);
10
11 // XNA 3.1
12 // 设置两个渲染目标
1 GraphicsDevice.SetRenderTarget(0, colorRT);
2 GraphicsDevice.SetRenderTarget(1, depthRT);
3 // XNA 4.0
4 // 设置两个渲染目标
1 GraphicsDevice.SetRenderTargets(colorRT, depthRT);
2
3 // XNA 3.1
4 GraphicsDevice.SetRenderTarget(0, null);
5 // XNA 4.0
6 GraphicsDevice.SetRenderTarget(null);
7
8 // XNA 3.1
9 // 将深度缓冲解析为深度图
1 GraphicsDevice.ResolveBackBuffer(depthMap);
2
3 // 绘制场景图, 用深度图模糊它
1 GraphicsDevice.Textures[1] = depthMap;
2 Viewport viewport = GraphicsDevice.Viewport;
3 dofEffect.CurrentTechnique = depthBlurTechnique;
4 DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);
5 // XNA 4.0
6 // 将深度缓冲解析为深度图
1 GraphicsDevice.SetRenderTarget(null);
2
3 // 绘制场景图, 用深度图模糊它
01 GraphicsDevice.Textures[1] = depthMap;
02 GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp;
03 Viewport viewport = GraphicsDevice.Viewport;
04 dofEffect.CurrentTechnique = depthBlurTechnique;
05 DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);
06
07 // XNA 3.1
08 ResolveTexture2D resolveTarget;
09 RenderTarget2D renderTarget1;
10 RenderTarget2D renderTarget2;
11
12 // 查找主缓冲的分辨率和格式.
13 PresentationParameters pp = GraphicsDevice.PresentationParameters;
14
15 int width = pp.BackBufferWidth;
16 int height = pp.BackBufferHeight;
17 SurfaceFormat format = pp.BackBufferFormat;
18
19 // 创建一个材质读取缓冲中的内容.
20 resolveTarget = new ResolveTexture2D(GraphicsDevice, width, height, 1, format);
21
22 // Create two rendertargets half size for the bloom processing.
23 width /= 2;
24 height /= 2;
25
26 renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
27 renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
28
29 // ... In the Draw Method...
30 GraphicsDevice.ResolveBackBuffer(resolveTarget);
31 // ...apply effect and draw pass 1...
32 // XNA 4.0
33 RenderTarget2D sceneRenderTarget;
34 RenderTarget2D renderTarget1;
35 RenderTarget2D renderTarget2;
36
37 // 查找主缓冲的分辨率和格式. .
38 PresentationParameters pp = GraphicsDevice.PresentationParameters;
39
40 int width = pp.BackBufferWidth;
41 int height = pp.BackBufferHeight;
42 SurfaceFormat format = pp.BackBufferFormat;
43
44 // Create a texture for rendering the main scene, prior to applying bloom.
45 sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false,
46                                        format, pp.DepthStencilFormat, pp.MultiSampleCount,
47                                        RenderTargetUsage.DiscardContents);
48
49 // Create two rendertargets half size for the bloom processing.
50 width /= 2;
51 height /= 2;
52
53 renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
54 renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, DepthFormat.None);
55
56 // ...In the Draw Method...
57 GraphicsDevice.SetRenderTarget(sceneRenderTarget);
58 GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
59 // ...apply effect and draw pass 1....

VertexDeclaration, Vertices, VertexElements, SizeInBytes

01 // XNA 3.1
02 // Vertex declaration for rendering our 3D model.
03 GraphicsDevice.VertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexElements);
04 // XNA 4.0
05 // Delete it. No longer needed.
06
07 // XNA 3.1
08 // set vertex buffer and declaration
09 GraphicsDevice.VertexDeclaration = vertexDeclaration;
10 GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionTexture.SizeInBytes);
11 // XNA 4.0
12 // set vertex buffer and declaration
13 GraphicsDevice.SetVertexBuffer(vertexBuffer);
14
15 // XNA 3.1
16 // create vertex declaration
17 vertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionTexture.VertexElements);
18 // XNA 4.0
19 // create vertex declaration
20 vertexDeclaration = new VertexDeclaration(VertexPositionTexture.VertexDeclaration.GetVertexElements());
21
22 // XNA 3.1
23 // reset vertex buffer declaration
24 GraphicsDevice.VertexDeclaration = null;
25 GraphicsDevice.Vertices[0].SetSource(null, 0, 0);
26 // XNA 4.0
27 // reset vertex buffer declaration
28 GraphicsDevice.SetVertexBuffer(null);
29
30 // XNA 3.1
31 // the vertices array
32 VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
33
34 // set new particles to vertex buffer
35 vertexBuffer.SetData<VertexPositionNormalTexture>(VertexPositionNormalTexture.SizeInBytes * vertexCount,
36                     vertices,vertexCount,count,VertexPositionNormalTexture.SizeInBytes);
37 // XNA 4.0
38 // the vertices array
39 VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
40
41 // set new particles to vertex buffer
42 vertexBuffer.SetData<VertexPositionNormalTexture>(vertices);
1 VertexBuffer, StreamOffset, VertexStride, IndexBuffer, BaseVertex
01 // XNA 3.1
02 // for each mesh part
03 foreach (ModelMeshPart meshPart in mesh.MeshParts)
04 {
05     // if primitives to render
06     if (meshPart.PrimitiveCount > 0)
07     {
08         // setup vertices and indices
09         GraphicsDevice.VertexDeclaration = meshPart.VertexDeclaration;
10         GraphicsDevice.Vertices[0].SetSource(mesh.VertexBuffer, meshPart.StreamOffset, meshPart.VertexStride);
11         GraphicsDevice.Indices = mesh.IndexBuffer;
12         ...
13 // XNA 4.0
14 GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; // may be needed in some cases...
15
16 // for each mesh part
17 foreach (ModelMeshPart meshPart in mesh.MeshParts)
18 {
19     // if primitives to render
20     if (meshPart.PrimitiveCount > 0)
21     {
22         // setup vertices and indices
23         GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer);
24         GraphicsDevice.Indices = meshPart.IndexBuffer;
25         ...
26
27 // XNA 3.1
28 // draw primitives
29 GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
30     meshPart.BaseVertex, 0, meshPart.NumVertices,
31     meshPart.StartIndex, meshPart.PrimitiveCount);
32 // XNA 4.0
33 // draw primitives
34 GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
35     meshPart.VertexOffset, 0, meshPart.NumVertices,
36     meshPart.StartIndex, meshPart.PrimitiveCount);

Points, PointSpriteEnable, PointSizeMax, PointList

01 // XNA 3.1
02 // create the vertex buffer
03 vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
04                                 250, BufferUsage.WriteOnly | BufferUsage.Points);
05 // XNA 4.0
06 // create the vertex buffer
07 vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
08                                 250, BufferUsage.WriteOnly | BufferUsage.None);
09
10 // XNA 3.1
11 // enable point sprite 3.1
12 GraphicsDevice.RenderState.PointSpriteEnable = true;
13 GraphicsDevice.RenderState.PointSizeMax = 128;
14 // XNA 4.0
15 // Delete it. No longer available.
16
17 // XNA 3.1
18 // draw the point sprites
19 GraphicsDevice.DrawPrimitives(PrimitiveType.PointList, vertexPosition, numberVertices);
20 // XNA 4.0
21 // draw the point sprites
22 GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, vertexPosition, numberVertices);

OpenContainer, BeginShowStorageDeviceSelector, EndShowStorageDeviceSelector, Path, TitleLocation, FileStream

001 // XNA 3.1
002 // open the container
003 StorageContainer storageContainer = storageDevice.OpenContainer("YourGameName");
004 // XNA 4.0
005 //To make life easier simply create a method to replace the storageDevice.OpenContainer...
006
007 /// <summary>
008 /// Synchronously opens storage container
009 /// </summary>
010 private static StorageContainer OpenContainer(StorageDevice storageDevice, string saveGameName)
011 {
012     IAsyncResult result = storageDevice.BeginOpenContainer(saveGameName, null, null);
013
014     // Wait for the WaitHandle to become signaled.
015     result.AsyncWaitHandle.WaitOne();
016
017     StorageContainer container = storageDevice.EndOpenContainer(result);
018
019     // Close the wait handle.
020     result.AsyncWaitHandle.Close();
021
022     return container;
023 }
024
025 // open the container
026 StorageContainer storageContainer = OpenContainer(storageDevice, "YourGameName");
027
028 // XNA 3.1
029 // retrieve the storage device
030 Guide.BeginShowStorageDeviceSelector(GetStorageDeviceResult, retrievalDelegate);
031 // XNA 4.0
032 // retrieve the storage device
033 if (!Guide.IsVisible)
034 {
035     StorageDevice.BeginShowSelector(GetStorageDeviceResult, retrievalDelegate);
036 }
037
038 // XNA 3.1
039 // retrieve and store the storage device
040 storageDevice = Guide.EndShowStorageDeviceSelector(result);
041 // XNA 4.0
042 // retrieve and store the storage device
043 storageDevice = StorageDevice.EndShowSelector(result);
044
045 // XNA 3.1
046 // get the level setup files
047 string[] filenames = Directory.GetFiles(storageContainer.Path, "LevelSetup*.xml");
048 // XNA 4.0
049 // get the level setup files
050 string[] filenames = storageContainer.GetFileNames("LevelSetup*.xml"");
051
052 // XNA 3.1
053 // save game level data
054 using (FileStream stream = new FileStream(Path.Combine(storageContainer.Path, levelFilename), FileMode.Create))
055 {
056     new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData);
057 }
058 // XNA 4.0
059 // save game level data
060 using (Stream stream = storageContainer.OpenFile(levelFilename, FileMode.Create))
061 {
062     new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData);
063 }
064
065 // XNA 3.1
066 // Delete the saved game level data.
067 using (StorageContainer storageContainer = storageDevice.OpenContainer("saveGameName"))
068 {
069     File.Delete(Path.Combine(storageContainer.Path, saveGameLevel.FileName));
070
071     File.Delete(Path.Combine(storageContainer.Path, "SaveGameLevel" +
072         Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) +".xml"));
073 }
074 // XNA 4.0
075 // Delete the saved game level data. NOTE: using OpenContainer method created in previous example
076 using (StorageContainer storageContainer = OpenContainer(storageDevice, "saveGameName"))
077 {
078     storageContainer.DeleteFile(saveGameLevel.FileName);
079
080     storageContainer.DeleteFile("SaveGameLevel" +
081         Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) + ".xml");
082 }
083
084 // XNA 3.1
085 //Load the Next Level...
086
087 // Find the path of the next level.
088 string levelPath;
089
090 // Loop here so we can try again when we can't find a level.
091 while (true)
092 {
093     // Try to find the next level. They are sequentially numbered txt files.
094     levelPath = String.Format("Levels/{0}.txt", ++levelIndex);
095     levelPath = Path.Combine(StorageContainer.TitleLocation, "Content/" + levelPath);
096     if (File.Exists(levelPath))
097         break;
098
099     // If there isn't even a level 0, something has gone wrong.
100     if (levelIndex == 0)
101         throw new Exception("No levels found.");
102
103     // Whenever we can't find a level, start over again at 0.
104     levelIndex = -1;
105 }
106
107 // Unloads the content for the current level before loading the next one.
108 if (level != null)
109     level.Dispose();
110
111 // Load the level.
112 level = new Level(Services, levelPath);
113 // XNA 4.0
114 // Load the Next Level...
115
116 // move to the next level
117 levelIndex = (levelIndex + 1) % numberOfLevels;
118
119 // Unloads the content for the current level before loading the next one.
120 if (level != null)
121     level.Dispose();
122
123 // Load the level.
124 string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex);
125 using (Stream fileStream = TitleContainer.OpenStream(levelPath))
126     level = new Level(Services, fileStream, levelIndex);
127
128
129 // XNA 3.1
130 //Save the current state of the session, with the given storage device.
131
132 // check the parameter
133 if ((storageDevice == null) || !storageDevice.IsConnected)
134 {
135     return;
136 }
137
138 // open the container
139 using (StorageContainer storageContainer = storageDevice.OpenContainer(Session.SaveGameContainerName))
140 {
141     string filename;
142     string descriptionFilename;
143
144     // get the filenames
145     if (overwriteDescription == null)
146     {
147         int saveGameIndex = 0;
148         string testFilename;
149         do
150         {
151             saveGameIndex++;
152             testFilename = Path.Combine(storageContainer.Path, "SaveGame" + saveGameIndex.ToString() + ".xml");
153         }
154         while (File.Exists(testFilename));
155         filename = testFilename;
156         descriptionFilename = "SaveGameDescription" + saveGameIndex.ToString() + ".xml";
157     }
158     else
159     {
160         filename = Path.Combine(storageContainer.Path, overwriteDescription.FileName);
161         descriptionFilename = "SaveGameDescription" +
162             Path.GetFileNameWithoutExtension(overwriteDescription.FileName).Substring(8) + ".xml";
163     }
164
165     using (FileStream stream = new FileStream(filename, FileMode.Create))
166     {
167         using (XmlWriter xmlWriter = XmlWriter.Create(stream))
168         {
169             //create and write xml data...
170         }
171     }
172
173    // create the save game description
174     SaveGameDescription description = new SaveGameDescription();
175     description.FileName = Path.GetFileName(filename);
176     description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
177     description.Description = DateTime.Now.ToString();
178
179     using (FileStream stream = new FileStream(Path.Combine(storageContainer.Path, descriptionFilename), FileMode.Create))
180     {
181         new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
182     }
183 }
184 // XNA 4.0
185 //Save the current state of the session, with the given storage device.
186
187 // check the parameter
188 if ((storageDevice == null) || !storageDevice.IsConnected)
189 {
190     return;
191 }
192
193 // open the container Note: using OpenContainer method from previous examples
194 using (StorageContainer storageContainer = OpenContainer(storageDevice, Session.SaveGameContainerName))
195 {
196     string filename;
197     string descriptionFilename;
198     // get the filenames
199     if (overwriteDescription == null)
200     {
201         int saveGameIndex = 0;
202         string testFilename;
203         do
204         {
205             saveGameIndex++;
206             testFilename = "SaveGame" + saveGameIndex.ToString() + ".xml";
207         }
208         while (storageContainer.FileExists(testFilename));
209         filename = testFilename;
210         descriptionFilename = "SaveGameDescription" + saveGameIndex.ToString() + ".xml";
211     }
212     else
213     {
214         filename = overwriteDescription.FileName;
215         descriptionFilename = "SaveGameDescription" +
216             Path.GetFileNameWithoutExtension(overwriteDescription.FileName).Substring(8) + ".xml";
217     }
218
219     // Note: using Stream instead of FileStream...
220     using (Stream stream = storageContainer.OpenFile(filename, FileMode.Create))
221     {
222         using (XmlWriter xmlWriter = XmlWriter.Create(stream))
223         {
224             //create and write xml data...
225         }
226     }
227
228     // create the save game description
229     SaveGameDescription description = new SaveGameDescription();
230     description.FileName = Path.GetFileName(filename);
231     description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
232     description.Description = DateTime.Now.ToString();
233
234     // Note: using Stream instead of FileStream...
235     using (Stream stream = storageContainer.OpenFile(descriptionFilename, FileMode.Create))
236     {
237         new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
238     }
239 }
1 VertexShader, PixelShader, ps_1_x
01 // XNA 3.1
02 VertexShaderOutput VertexShader(...)
03 {
04     //some code
05 }
06 float4 PixelShader(...)
07 {
08    // some code
09 }
10 // XNA 4.0
11 // VertexShader can not be used
12 VertexShaderOutput  VertexShaderFunction(...)
13 {
14    // some code
15 }
16 // PixelShader can not be used
17 float4 PixelShaderFunction(...)
18 {
19    // some code
20 }
21
22 // XNA 3.1
23 technique
24 {
25     pass
26     {
27         VertexShader = compile vs_1_1 VertexShader();
28         PixelShader  = compile ps_1_1 PixelShader();
29     }
30 }
31 // XNA 4.0
32 technique
33 {
34     pass
35     {
36         VertexShader = compile vs_2_0 VertexShaderFunction(); //VertexShader can not be used & set vs higher than 1_1
37         PixelShader  = compile ps_2_0 PixelShaderFunction(); //PixelShader can not be used & set ps higher than 1_1
38     }
39 }

XNA Model drawn inside out, slightly transparent, missing parts or just looks wrong

1 // Set suitable renderstates for drawing a 3D model
2 GraphicsDevice.BlendState = BlendState.Opaque;
3 GraphicsDevice.DepthStencilState = DepthStencilState.Default;
4
5 // your model draw code starts here...

相关文章: