XNA3到4的转换

282 篇文章 5 订阅
239 篇文章 13 订阅

XNA3.0到4.0的转换

http://blog.sina.com.cn/s/articlelist_1747721953_0_1.html


XNA4.0可以说是一个变化很大的版本了,许多类都被重构或者删除,转换的相关重点描述文章中,比较好的


是下面的URL地址:
http://www.nelxon.com/blog/xna-3-1-to-xna-4-0-cheatsheet/
 
不过这篇文章有些细节还是漏掉了一部分,如在XNA3.0中下面的代码显示选择存储设备的界面.
public static StorageDevice XnaUserDevice
  {
   get
   {
    // Create if not created yet.
    if (xnaUserDevice == null)
     xnaUserDevice =
                        StorageDevice.ShowStorageDeviceGuide(PlayerIndex.One);
    return xnaUserDevice;
   } // get
  } // XnaUserDevice
 
但是上面的代码在4.0下会提示StorageDevice没有BeginShowSelector函数,那么,如何改写这段代码呢?


看下面的代码.
public static StorageDevice XnaUserDevice
  {
   get
   {
     if (xnaUserDevice == null)
     result =
                        StorageDevice.BeginShowSelector(PlayerIndex.One, null,null);
                if (result.IsCompleted)
                    xnaUserDevice = StorageDevice.EndShowSelector(result);
    return xnaUserDevice;
   } // get
  } // XnaUserDevice
 在XNA4.0中,Game类的LoadGraphicsContent方法被LoadContent替代.
 3.0 中GameTime属性ElapsedRealTime已被4.0的ElapsedGameTime取代
========

XNA 3.1 转换到 XNA4.0 的备忘录

http://blog.csdn.net/kenkao/article/details/11111623
http://www.cnblogs.com/Baesky/archive/2011/02/01/1948789.html
 
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


// XNA 3.1
sprite.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Deferred, SaveStateMode.SaveState);
// XNA 4.0
sprite.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
  
// XNA 3.1
// 通过深度排列场景对象


spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.BackToFront, 


SaveStateMode.None);
// XNA 4.0
// 通过深度排列场景对象


spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
  
// XNA 3.1
sprite.Begin(SpriteBlendMode.None, SpriteSortMode.Immediate, SaveStateMode.SaveState);
// XNA 4.0
sprite.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
  
// XNA 3.1
// 画背景图


spriteBatch.Begin(SpriteBlendMode.None);
Viewport viewport = GraphicsDevice.Viewport;
spriteBatch.Draw(background, new Rectangle(0, 0, viewport.Width, viewport.Height), 


Color.White);
spriteBatch.End();
// XNA 4.0
// 画背景图


spriteBatch.Begin(0, BlendState.Opaque);
spriteBatch.Draw(background, GraphicsDevice.Viewport.Bounds, Color.White);
spriteBatch.End();
 
RenderState


// XNA 3.1
// 启用alpha混合和深度写


GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
GraphicsDevice.RenderState.AlphaSourceBlend = Blend.One;
GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.One;
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
// XNA 4.0
// 启用alpha混合和深度写


GraphicsDevice.BlendState = BlendState.AlphaBlend;
GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
  
// XNA 3.1
// 重置混合和深度写


GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
// XNA 4.0
// 重置混合和深度写


GraphicsDevice.BlendState = BlendState.Additive;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  
// XNA 3.1
// 启用深度缓冲


GraphicsDevice.RenderState.DepthBufferEnable = true;
// XNA 4.0
// 启用深度缓冲


GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  
// XNA 3.1
// 禁用深度缓冲


GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
GraphicsDevice.RenderState.DepthBufferEnable = false;
// XNA 4.0
// 禁用深度缓冲


GraphicsDevice.DepthStencilState = DepthStencilState.None;
  
// XNA 3.1
// 累加混合(zero on alpha)
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.One;
GraphicsDevice.RenderState.DestinationBlend = Blend.One;
// XNA 4.0
// 累加混合(zero on alpha)
GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
GraphicsDevice.BlendState = BlendState.AlphaBlend;
  
// XNA 3.1
// 恢复混合模式


GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
// XNA 4.0
// 恢复混合模式


GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  
// XNA 3.1
// 设置alpha混合,无深度测试和深度写
?
1
2
3
4
5
6
7
GraphicsDevice.RenderState.DepthBufferEnable = false;
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
// XNA 4.0
// 设置alpha混合,无深度测试和深度写


GraphicsDevice.DepthStencilState = DepthStencilState.None;
GraphicsDevice.BlendState = BlendState.AlphaBlend;
  
// XNA 3.1
// 绘制3D模型时设置合适渲染模式


GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.AlphaTestEnable = false;
GraphicsDevice.RenderState.DepthBufferEnable = true;
// XNA 4.0
// 绘制3D模型时设置合适渲染模式


GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
  
// XNA 3.1
// 加性混合


GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.One;
GraphicsDevice.RenderState.DestinationBlend = Blend.One;
// XNA 4.0
// 加性混合


GraphicsDevice.BlendState = BlendState.Additive;
  
// XNA 3.1
// 设置加性混合


GraphicsDevice.RenderState.DestinationBlend = Blend.One;
// XNA 4.0
// 设置加性混合


GraphicsDevice.BlendState = BlendState.Additive;
  
// XNA 3.1
// 设置alpha混合


GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
// XNA 4.0
// 设置alpha混合


GraphicsDevice.BlendState = BlendState.AlphaBlend;
  
// XNA 3.1
GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;
// XNA 4.0
 GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
  
// XNA 3.1
// 设置渲染状态


GraphicsDevice.RenderState.DepthBufferEnable = false;
GraphicsDevice.RenderState.DepthBufferWriteEnable = false;
GraphicsDevice.RenderState.AlphaBlendEnable = true;
GraphicsDevice.RenderState.SourceBlend = Blend.One;
GraphicsDevice.RenderState.DestinationBlend = Blend.One;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
GraphicsDevice.RenderState.AlphaBlendOperation = BlendFunction.Add;
GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.Zero;
GraphicsDevice.RenderState.AlphaSourceBlend = Blend.Zero;
   
      // drawing code here..
   
// 恢复状态


GraphicsDevice.RenderState.DepthBufferEnable = true;
GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
GraphicsDevice.RenderState.AlphaBlendEnable = false;
GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = false;
// XNA 4.0
//存储状态


DepthStencilState ds = GraphicsDevice.DepthStencilState;
BlendState bs = GraphicsDevice.BlendState;
   
//设置渲染状态


GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;
GraphicsDevice.BlendState = BlendState.AlphaBlend;
   
       // drawing code here..
   
// 恢复状态


GraphicsDevice.DepthStencilState = ds;
GraphicsDevice.BlendState = bs;
 
Effect, EffectPass, Begin(), End(), CommitChanges(), Clone()
 
// 应用效果 XNA 3.1
blurEffect.CommitChanges();
blurEffect.Begin(SaveStateMode.SaveState);
blurEffect.CurrentTechnique.Passes[0].Begin();
GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
blurEffect.CurrentTechnique.Passes[0].End();
blurEffect.End();
// 应用效果 XNA 4.0
blurEffect.CurrentTechnique.Passes[0].Apply();
GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);
  
// XNA 3.1
// 提交效果改变


effect.CommitChanges();
// XNA 4.0
//  当任何效果属性改变需要调用EffectPass.Apply()


// 否则就删除它


// XNA 3.1
// 开始一个效果


effect.Begin(SaveStateMode.SaveState);
effect.CurrentTechnique.Passes[0].Begin();
// XNA 4.0
// 开始一个效果


effect.CurrentTechnique.Passes[0].Apply();
  
// XNA 3.1
// 结束一个效果


effect.CurrentTechnique.Passes[0].End();
effect.End();
// XNA 4.0
// 如果不需要可直接删除


// XNA 3.1
// 产生一个效果的克隆体


Effect newEffect = replacementEffect.Clone(replacementEffect.GraphicsDevice);
// XNA 4.0
// 产生一个效果的克隆体


Effect newEffect = replacementEffect.Clone();
  
// XNA 3.1
// 启用效果中的tech


postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];     
   
// 用预处理效果画一个全屏的精灵.
spriteBatch.Begin(SpriteBlendMode.None,SpriteSortMode.Immediate, SaveStateMode.None);
   
postprocessEffect.Begin();
postprocessEffect.CurrentTechnique.Passes[0].Begin();
   
spriteBatch.Draw(sceneRenderTarget.GetTexture(), Vector2.Zero, Color.White);
spriteBatch.End();
   
postprocessEffect.CurrentTechnique.Passes[0].End();
postprocessEffect.End();
// XNA 4.0
// 启用效果中的tech


postprocessEffect.CurrentTechnique = postprocessEffect.Techniques[effectTechniqueName];
   
// 用预处理效果画一个全屏的精灵.


spriteBatch.Begin(0, BlendState.Opaque, null, null, null, postprocessEffect);
spriteBatch.Draw(sceneRenderTarget, Vector2.Zero, Color.White);
spriteBatch.End();
 
ShaderProfile, TotalRealTime, TransparentBlack


// XNA 3.1
graphics.MinimumPixelShaderProfile = ShaderProfile.PS_3_0; //any PS number...
graphics.MinimumVertexShaderProfile = ShaderProfile.VS_3_0;//any VS number...
// XNA 4.0
// 不再需要该语句


// XNA 3.1
float myTime = (float)gameTime.TotalRealTime.TotalSeconds * 0.2f;
// XNA 4.0
float myTime = (float)gameTime.TotalGameTime.TotalSeconds * 0.2f;
  
// XNA 3.1
GraphicsDevice.Clear(Color.TransparentBlack);
// XNA 4.0
GraphicsDevice.Clear(Color.Transparent);
 
ResolveTexture2D, ResolveBackBuffer, RenderTarget2D, GetTexture, DepthStencilBuffer, 


PresentationParameters, MultiSampleType, MultiSampleQuality, SetRenderTarget


// XNA 3.1
ResolveTexture2D sceneMap;
// XNA 4.0
RenderTarget2D sceneMap;
  
// XNA 3.1
// 查询主缓冲的分辨率和格式.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
   
// 从缓冲读取一个材质数据.
sceneMap = new ResolveTexture2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1, 


pp.BackBufferFormat);
// XNA 4.0
// 查询主缓冲的分辨率和格式.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
   
// 从缓冲读取一个材质数据.
sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 


false, pp.BackBufferFormat,
                                pp.DepthStencilFormat);
//or 
   
sceneMap = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 


false, pp.BackBufferFormat,
                                pp.DepthStencilFormat, pp.MultiSampleCount, 


RenderTargetUsage.DiscardContents);
  
// XNA 3.1
GraphicsDevice.ResolveBackBuffer(sceneMap);
// XNA 4.0
GraphicsDevice.SetRenderTarget(sceneMap);
  
// XNA 3.1
int width = GraphicsDevice.Viewport.Width;
int height = GraphicsDevice.Viewport.Height;
   
// 创建渲染对象


myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, 1, SurfaceFormat.Color);
// XNA 4.0
int width = GraphicsDevice.Viewport.Width;
int height = GraphicsDevice.Viewport.Height;
   
// 创建渲染对象


myRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, true, 


SurfaceFormat.Color, DepthFormat.Depth24);
  
// XNA 3.1
PresentationParameters pp = GraphicsDevice.PresentationParameters;
   
// 创建自动以渲染对象


sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, 


pp.BackBufferHeight, 1,
                                   pp.BackBufferFormat, pp.MultiSampleType, 


pp.MultiSampleQuality);
// XNA 4.0
PresentationParameters pp = GraphicsDevice.PresentationParameters;
   
// 创建自动以渲染对象


sceneRenderTarget = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, 


pp.BackBufferHeight, false,
                                   pp.BackBufferFormat, pp.DepthStencilFormat, 


pp.MultiSampleCount,
                                   RenderTargetUsage.DiscardContents);
  
// XNA 3.1
PresentationParameters pp = GraphicsDevice.PresentationParameters;
   
// 配置一个深度缓冲


drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 1,
                                SurfaceFormat.Color, pp.MultiSampleType, 


pp.MultiSampleQuality);
   
drawDepthBuffer = new DepthStencilBuffer(GraphicsDevice, pp.AutoDepthStencilFormat,
                                            pp.MultiSampleType, pp.MultiSampleQuality);
// XNA 4.0
PresentationParameters pp = GraphicsDevice.PresentationParameters;
   
// 配置一个深度缓冲


drawBuffer = new RenderTarget2D(GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, 


true,
                                SurfaceFormat.Color,DepthFormat.Depth24Stencil8,
                                pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
//NOTE:  DepthStencilBuffer 类不再存在


// XNA 3.1
spriteBatch.Draw(myRenderTarget.GetTexture(), Vector2.Zero, Color.White);
// XNA 4.0
spriteBatch.Draw(myRenderTarget, Vector2.Zero, Color.White); // NOTE: ".GetTexure()"  不再


需要


// XNA 3.1
Texture2D myTexture = myRenderTarget.GetTexture();
// XNA 4.0
Texture2D myTexture = myRenderTarget; // NOTE: ".GetTexure()"  No longer needed
  
// XNA 3.1
GraphicsDevice.SetRenderTarget(0, myRenderTarget);
// XNA 4.0
GraphicsDevice.SetRenderTarget(myRenderTarget);
  
// XNA 3.1
// 设置两个渲染目标


GraphicsDevice.SetRenderTarget(0, colorRT);
GraphicsDevice.SetRenderTarget(1, depthRT);
// XNA 4.0
// 设置两个渲染目标


GraphicsDevice.SetRenderTargets(colorRT, depthRT);
  
// XNA 3.1
GraphicsDevice.SetRenderTarget(0, null);
// XNA 4.0
GraphicsDevice.SetRenderTarget(null);
  
// XNA 3.1
// 将深度缓冲解析为深度图


GraphicsDevice.ResolveBackBuffer(depthMap);
   
// 绘制场景图, 用深度图模糊它


GraphicsDevice.Textures[1] = depthMap;
Viewport viewport = GraphicsDevice.Viewport;
dofEffect.CurrentTechnique = depthBlurTechnique;
DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);
// XNA 4.0
// 将深度缓冲解析为深度图


GraphicsDevice.SetRenderTarget(null);
   
// 绘制场景图, 用深度图模糊它


GraphicsDevice.Textures[1] = depthMap;
GraphicsDevice.SamplerStates[1] = SamplerState.PointClamp;
Viewport viewport = GraphicsDevice.Viewport;
dofEffect.CurrentTechnique = depthBlurTechnique;
DrawFullscreenQuad(sceneMap, viewport.Width, viewport.Height, dofEffect);
  
// XNA 3.1
ResolveTexture2D resolveTarget;
RenderTarget2D renderTarget1;
RenderTarget2D renderTarget2;
   
// 查找主缓冲的分辨率和格式.
PresentationParameters pp = GraphicsDevice.PresentationParameters;
   
int width = pp.BackBufferWidth;
int height = pp.BackBufferHeight;
SurfaceFormat format = pp.BackBufferFormat;
   
// 创建一个材质读取缓冲中的内容.
resolveTarget = new ResolveTexture2D(GraphicsDevice, width, height, 1, format);
   
// Create two rendertargets half size for the bloom processing.
width /= 2;
height /= 2;
   
renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, 1,format);
   
// ... In the Draw Method...
 GraphicsDevice.ResolveBackBuffer(resolveTarget);
 // ...apply effect and draw pass 1...
// XNA 4.0
RenderTarget2D sceneRenderTarget;
RenderTarget2D renderTarget1;
RenderTarget2D renderTarget2;
   
// 查找主缓冲的分辨率和格式. .
PresentationParameters pp = GraphicsDevice.PresentationParameters;
   
int width = pp.BackBufferWidth;
int height = pp.BackBufferHeight;
SurfaceFormat format = pp.BackBufferFormat;
   
// Create a texture for rendering the main scene, prior to applying bloom.
sceneRenderTarget = new RenderTarget2D(GraphicsDevice, width, height, false,
                                       format, pp.DepthStencilFormat, pp.MultiSampleCount,
                                       RenderTargetUsage.DiscardContents);
   
// Create two rendertargets half size for the bloom processing.
width /= 2;
height /= 2;
   
renderTarget1 = new RenderTarget2D(GraphicsDevice, width, height, false, format, 


DepthFormat.None);
renderTarget2 = new RenderTarget2D(GraphicsDevice, width, height, false, format, 


DepthFormat.None);
   
// ...In the Draw Method...
GraphicsDevice.SetRenderTarget(sceneRenderTarget);
GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;
// ...apply effect and draw pass 1....
 
VertexDeclaration, Vertices, VertexElements, SizeInBytes


// XNA 3.1
// Vertex declaration for rendering our 3D model.
 GraphicsDevice.VertexDeclaration = new VertexDeclaration


(VertexPositionTexture.VertexElements);
// XNA 4.0
// Delete it. No longer needed.
  
// XNA 3.1
// set vertex buffer and declaration
GraphicsDevice.VertexDeclaration = vertexDeclaration;
GraphicsDevice.Vertices[0].SetSource(vertexBuffer, 0, VertexPositionTexture.SizeInBytes);
// XNA 4.0
// set vertex buffer and declaration
GraphicsDevice.SetVertexBuffer(vertexBuffer);
  
// XNA 3.1
// create vertex declaration
vertexDeclaration = new VertexDeclaration(GraphicsDevice, 


VertexPositionTexture.VertexElements);
// XNA 4.0
// create vertex declaration
vertexDeclaration = new VertexDeclaration


(VertexPositionTexture.VertexDeclaration.GetVertexElements());
  
// XNA 3.1
// reset vertex buffer declaration
GraphicsDevice.VertexDeclaration = null;
GraphicsDevice.Vertices[0].SetSource(null, 0, 0);
// XNA 4.0
// reset vertex buffer declaration
GraphicsDevice.SetVertexBuffer(null);
  
// XNA 3.1
// the vertices array
VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
   
 // set new particles to vertex buffer
vertexBuffer.SetData<VertexPositionNormalTexture>(VertexPositionNormalTexture.SizeInBytes * 


vertexCount,
                    vertices,vertexCount,count,VertexPositionNormalTexture.SizeInBytes);
// XNA 4.0
// the vertices array
VertexPositionNormalTexture[] vertices = new VertexPositionNormalTexture[100];
   
// set new particles to vertex buffer
vertexBuffer.SetData<VertexPositionNormalTexture>(vertices);


VertexBuffer, StreamOffset, VertexStride, IndexBuffer, BaseVertex


// XNA 3.1
// for each mesh part
foreach (ModelMeshPart meshPart in mesh.MeshParts)
{
    // if primitives to render
    if (meshPart.PrimitiveCount > 0)
    {
        // setup vertices and indices
        GraphicsDevice.VertexDeclaration = meshPart.VertexDeclaration;
        GraphicsDevice.Vertices[0].SetSource(mesh.VertexBuffer, meshPart.StreamOffset, 


meshPart.VertexStride);
        GraphicsDevice.Indices = mesh.IndexBuffer;
        ...
// XNA 4.0
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap; // may be needed in some 


cases...
   
// for each mesh part
foreach (ModelMeshPart meshPart in mesh.MeshParts)
{
    // if primitives to render
    if (meshPart.PrimitiveCount > 0)
    {
        // setup vertices and indices
        GraphicsDevice.SetVertexBuffer(meshPart.VertexBuffer);
        GraphicsDevice.Indices = meshPart.IndexBuffer;
        ...
  
// XNA 3.1
// draw primitives
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
    meshPart.BaseVertex, 0, meshPart.NumVertices,
    meshPart.StartIndex, meshPart.PrimitiveCount);
// XNA 4.0
// draw primitives
GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList,
    meshPart.VertexOffset, 0, meshPart.NumVertices,
    meshPart.StartIndex, meshPart.PrimitiveCount);
 
Points, PointSpriteEnable, PointSizeMax, PointList


// XNA 3.1
 // create the vertex buffer
vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
                                250, BufferUsage.WriteOnly | BufferUsage.Points);
// XNA 4.0
// create the vertex buffer
vertexBuffer = new VertexBuffer(GraphicsDevice, typeof(VertexPositionNormalTexture),
                                250, BufferUsage.WriteOnly | BufferUsage.None);
  
// XNA 3.1
// enable point sprite 3.1
GraphicsDevice.RenderState.PointSpriteEnable = true;
GraphicsDevice.RenderState.PointSizeMax = 128;
// XNA 4.0
// Delete it. No longer available.
  
// XNA 3.1
// draw the point sprites
GraphicsDevice.DrawPrimitives(PrimitiveType.PointList, vertexPosition, numberVertices);
// XNA 4.0
// draw the point sprites
GraphicsDevice.DrawPrimitives(PrimitiveType.LineList, vertexPosition, numberVertices);
 
OpenContainer, BeginShowStorageDeviceSelector, EndShowStorageDeviceSelector, Path, 


TitleLocation, FileStream


// XNA 3.1
// open the container
StorageContainer storageContainer = storageDevice.OpenContainer("YourGameName");
// XNA 4.0
//To make life easier simply create a method to replace the storageDevice.OpenContainer... 
   
/// <summary>
/// Synchronously opens storage container
/// </summary>
private static StorageContainer OpenContainer(StorageDevice storageDevice, string 


saveGameName)
{
    IAsyncResult result = storageDevice.BeginOpenContainer(saveGameName, null, null);
   
    // Wait for the WaitHandle to become signaled.
    result.AsyncWaitHandle.WaitOne();
   
    StorageContainer container = storageDevice.EndOpenContainer(result);
   
    // Close the wait handle.
    result.AsyncWaitHandle.Close();
   
    return container;
}
   
// open the container
StorageContainer storageContainer = OpenContainer(storageDevice, "YourGameName");
  
// XNA 3.1
// retrieve the storage device
Guide.BeginShowStorageDeviceSelector(GetStorageDeviceResult, retrievalDelegate);
// XNA 4.0
// retrieve the storage device
if (!Guide.IsVisible)
{
    StorageDevice.BeginShowSelector(GetStorageDeviceResult, retrievalDelegate);
}
  
// XNA 3.1
 // retrieve and store the storage device
 storageDevice = Guide.EndShowStorageDeviceSelector(result);
// XNA 4.0
// retrieve and store the storage device
 storageDevice = StorageDevice.EndShowSelector(result);
  
// XNA 3.1
// get the level setup files
 string[] filenames = Directory.GetFiles(storageContainer.Path, "LevelSetup*.xml");
// XNA 4.0
// get the level setup files
string[] filenames = storageContainer.GetFileNames("LevelSetup*.xml"");
  
// XNA 3.1
// save game level data
using (FileStream stream = new FileStream(Path.Combine(storageContainer.Path, 


levelFilename), FileMode.Create))
{
    new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData);
}
// XNA 4.0
// save game level data
using (Stream stream = storageContainer.OpenFile(levelFilename, FileMode.Create))
{
    new XmlSerializer(typeof(SaveGameLevel)).Serialize(stream, levelData);
}
  
// XNA 3.1
// Delete the saved game level data.
using (StorageContainer storageContainer = storageDevice.OpenContainer("saveGameName"))
{
    File.Delete(Path.Combine(storageContainer.Path, saveGameLevel.FileName));
   
    File.Delete(Path.Combine(storageContainer.Path, "SaveGameLevel" +
        Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) +".xml"));
}
// XNA 4.0
// Delete the saved game level data. NOTE: using OpenContainer method created in previous 


example
using (StorageContainer storageContainer = OpenContainer(storageDevice, "saveGameName"))
{
    storageContainer.DeleteFile(saveGameLevel.FileName);
   
    storageContainer.DeleteFile("SaveGameLevel" +
        Path.GetFileNameWithoutExtension(saveGameLevel.FileName).Substring(8) + ".xml");
}
  
// XNA 3.1
//Load the Next Level...
   
// Find the path of the next level.
string levelPath;
   
// Loop here so we can try again when we can't find a level.
while (true)
{
    // Try to find the next level. They are sequentially numbered txt files.
    levelPath = String.Format("Levels/{0}.txt", ++levelIndex);
    levelPath = Path.Combine(StorageContainer.TitleLocation, "Content/" + levelPath);
    if (File.Exists(levelPath))
        break;
   
    // If there isn't even a level 0, something has gone wrong.
    if (levelIndex == 0)
        throw new Exception("No levels found.");
   
    // Whenever we can't find a level, start over again at 0.
    levelIndex = -1;
}
   
// Unloads the content for the current level before loading the next one.
if (level != null)
    level.Dispose();
   
// Load the level.
level = new Level(Services, levelPath);
// XNA 4.0
// Load the Next Level...
   
// move to the next level
levelIndex = (levelIndex + 1) % numberOfLevels;
   
// Unloads the content for the current level before loading the next one.
if (level != null)
    level.Dispose();
   
// Load the level.
string levelPath = string.Format("Content/Levels/{0}.txt", levelIndex);
using (Stream fileStream = TitleContainer.OpenStream(levelPath))
    level = new Level(Services, fileStream, levelIndex);
  
  
// XNA 3.1
//Save the current state of the session, with the given storage device. 
   
// check the parameter
if ((storageDevice == null) || !storageDevice.IsConnected)
{
    return;
}
   
// open the container
using (StorageContainer storageContainer = storageDevice.OpenContainer


(Session.SaveGameContainerName))
{
    string filename;
    string descriptionFilename;
   
    // get the filenames
    if (overwriteDescription == null)
    {
        int saveGameIndex = 0;
        string testFilename;
        do
        {
            saveGameIndex++;
            testFilename = Path.Combine(storageContainer.Path, "SaveGame" + 


saveGameIndex.ToString() + ".xml");
        }
        while (File.Exists(testFilename));
        filename = testFilename;
        descriptionFilename = "SaveGameDescription" + saveGameIndex.ToString() + ".xml";
    }
    else
    {
        filename = Path.Combine(storageContainer.Path, overwriteDescription.FileName);
        descriptionFilename = "SaveGameDescription" +
            Path.GetFileNameWithoutExtension(overwriteDescription.FileName).Substring(8) + 


".xml";
    }
   
    using (FileStream stream = new FileStream(filename, FileMode.Create))
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stream))
        {
            //create and write xml data...
        }
    }
   
   // create the save game description
    SaveGameDescription description = new SaveGameDescription();
    description.FileName = Path.GetFileName(filename);
    description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
    description.Description = DateTime.Now.ToString();
   
    using (FileStream stream = new FileStream(Path.Combine(storageContainer.Path, 


descriptionFilename), FileMode.Create))
    {
        new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
    }
}
// XNA 4.0
//Save the current state of the session, with the given storage device. 
   
// check the parameter
if ((storageDevice == null) || !storageDevice.IsConnected)
{
    return;
}
   
// open the container Note: using OpenContainer method from previous examples
using (StorageContainer storageContainer = OpenContainer(storageDevice, 


Session.SaveGameContainerName))
{
    string filename;
    string descriptionFilename;
    // get the filenames
    if (overwriteDescription == null)
    {
        int saveGameIndex = 0;
        string testFilename;
        do
        {
            saveGameIndex++;
            testFilename = "SaveGame" + saveGameIndex.ToString() + ".xml";
        }
        while (storageContainer.FileExists(testFilename));
        filename = testFilename;
        descriptionFilename = "SaveGameDescription" + saveGameIndex.ToString() + ".xml";
    }
    else
    {
        filename = overwriteDescription.FileName;
        descriptionFilename = "SaveGameDescription" +
            Path.GetFileNameWithoutExtension(overwriteDescription.FileName).Substring(8) + 


".xml";
    }
   
    // Note: using Stream instead of FileStream...
    using (Stream stream = storageContainer.OpenFile(filename, FileMode.Create))
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(stream))
        {
            //create and write xml data...
        }
    }
   
    // create the save game description
    SaveGameDescription description = new SaveGameDescription();
    description.FileName = Path.GetFileName(filename);
    description.ChapterName = IsQuestLineComplete ? "Quest Line Complete" : Quest.Name;
    description.Description = DateTime.Now.ToString();
   
    // Note: using Stream instead of FileStream...
    using (Stream stream = storageContainer.OpenFile(descriptionFilename, FileMode.Create))
    {
        new XmlSerializer(typeof(SaveGameDescription)).Serialize(stream, description);
    }
}


VertexShader, PixelShader, ps_1_x


// XNA 3.1
VertexShaderOutput VertexShader(...)
{
    //some code
}
float4 PixelShader(...)
{
   // some code
}
// XNA 4.0
// VertexShader can not be used
VertexShaderOutput  VertexShaderFunction(...)
{
   // some code
}
// PixelShader can not be used
float4 PixelShaderFunction(...)
{
   // some code
}
  
// XNA 3.1
technique
{
    pass
    {
        VertexShader = compile vs_1_1 VertexShader();
        PixelShader  = compile ps_1_1 PixelShader();
    }
}
// XNA 4.0
technique
{
    pass
    {
        VertexShader = compile vs_2_0 VertexShaderFunction(); //VertexShader can not be 


used & set vs higher than 1_1
        PixelShader  = compile ps_2_0 PixelShaderFunction(); //PixelShader can not be used 


& set ps higher than 1_1
    }
}
 
XNA Model drawn inside out, slightly transparent, missing parts or just looks wrong


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

XNA3.1 - 4.0对应表

http://www.codeweblog.com/%E8%BD%AC-xna3-1-4-0%E5%AF%B9%E5%BA%94%E8%A1%A8/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值