Sign in to follow this  
Black Knight

[.net] XNA questions

Recommended Posts

Is it possible to use XNA assemblies with visual studio 2005 professional. I cant find a download for it on MS site so I think I should download XNA game studio express and use its XNA assemblies in VS2005. And is there any cons of not using GSE other than the lack of content pipeline?

Share this post


Link to post
Share on other sites
You can simply add the assemblies as references to your project, like you would Windows Forms for example. You'll have to create your Game subclass and/or graphics device manually, but it does work.

If you''re not using GSE , XBox deployment should be pretty much out the window and getting the bitmap fonts to work might also prove to be a pain. Now I wasn't too happy being forced to use GSE either, but I haven't found anything significant yet that really makes me want to go back to VS2005, while not using GSE comes with some definite cons, not the least of which is indeed the lack of the content pipeline. It may not be perfect, but it beats writing importers manually [smile]

Exactly what are you trying to do for which you really need VS2005?

Share this post


Link to post
Share on other sites
To be honest I havent tried GSE yet and dont know how it looks like.Mainly I dont want to learn a new IDE all over again though probably it looks muck like VS.
Another thing I read is that vs2005 has shader debugging and GSE doesnt have it.
Up until now I was using c++ and opengl/d3d but I want to make a switch to c# to ease the pain of writing lots of stuff which are already provided within .net
Im mainly doing windows programming so I thinking of dropping opengl but am confused on either using MDX which is no longer updated AFAIK.So this only leaves me with XNA which forces me to GSE :|

PS. I also read that D3DX is not available in vs2005+xna.Not sure on this though.

So what should I prefer if im up for windows 3d game programming with d3d?
a)c++ d3d on vs2005
b)c# xna(on managed d3d) on GSE(vc#express)

I wanna go b because i think it will cut the development time by a huge amount.
Any comment?

Share this post


Link to post
Share on other sites
Quote:
Original post by Black Knight
To be honest I havent tried GSE yet and dont know how it looks like.Mainly I dont want to learn a new IDE all over again though probably it looks muck like VS.


What? GSE is just a plugin for Visual C# Express Edition. If you have VS Pro, Visual C# Express is near identical minus a few extras (Such as full plugin support, and the ability to use multiple programming languages under 1 IDE for instance). You wont have to learn a new IDE again :-)

The only downside to using the Express Edition is that the Team Explorer plugin does not work with it. Therefore, when I'm working on my codeplex project I have to open bothe Visual Studio 2005 and Visual C# Express.

You can install Visual C# Express w/ GSE on the same machine as Visual Studio 2005 Standard, Pro & Team Edition. Whats to loose?

MS is known to be working on plugins for the retail versions of VS. When it it'll be out, only they know ;-)

- Bill

Share this post


Link to post
Share on other sites
If you want to do Windows games with C# I'd have to say start digging into XNA. The Racing Game Starter Kit was just released. Download it and take a look at what you can do with XNA.

Share this post


Link to post
Share on other sites
I have downloaded and installed both vc#express and xna everything seems to be working good for now :)
Creating a d3d window is a piece of cake considered to a c++ win32 d3d window.
I wonder if I can create my own window and use another form inside it for rendering just like MDI child windows.
I did this with c# mdx so I think its possible with XNA too.
But XNA directly inherits from Microsoft.Xna.Framework.Game so it doesnt let you create a d3d window directly.
I guess i need to go the old way and inherit from Windows.Form and create the d3d device myself.
I want to do this because I want to use XNA for a world editor so I dont want the whole window to be a d3d viewport.

Share this post


Link to post
Share on other sites
Does any1 managed to handle the xna game window sizing?
It always crashes when the I size the height to 0.Here is my code.


#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion

namespace deneme
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
ContentManager content;
GraphicsDevice m_Device;

Effect effect;

VertexPositionColor[] vertices;

private VertexBuffer vb;
private IndexBuffer ib;

private float angle = 0.0f;

public Game1()
{
graphics = new GraphicsDeviceManager(this);
content = new ContentManager(Services);

Window.AllowUserResizing = true;
Window.ClientSizeChanged += new System.EventHandler(Window_ClientSizeChanged);


}

/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();

SetupXNADevice();

SetupVertices();

SetUpIndices();

SetUpCamera();

}
private void SetupXNADevice()
{
m_Device = graphics.GraphicsDevice;

CompiledEffect compiledEffect = Effect.CompileEffectFromFile("@/../../../../effects.fx", null, null, CompilerOptions.None, TargetPlatform.Windows);
effect = new Effect(graphics.GraphicsDevice, compiledEffect.GetEffectCode(), CompilerOptions.None, null);

graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 600;
graphics.IsFullScreen = false;
graphics.ApplyChanges();
Window.Title = "My First XNA Game :)";

//Disable back face culling
m_Device.RenderState.CullMode = CullMode.None;


}
private void SetupVertices()
{
vertices = new VertexPositionColor[5];

vertices[0].Position = new Vector3(0f, 0f, 0f);
vertices[0].Color = Color.White;
vertices[1].Position = new Vector3(5f, 0f, 0f);
vertices[1].Color = Color.White;
vertices[2].Position = new Vector3(10f, 0f, 0f);
vertices[2].Color = Color.White;
vertices[3].Position = new Vector3(5f, 5f, 0f);
vertices[3].Color = Color.White;
vertices[4].Position = new Vector3(10f, 5f, 0f);
vertices[4].Color = Color.White;

vb = new VertexBuffer(m_Device, sizeof(float) * 4 * 5, ResourceUsage.WriteOnly, ResourceManagementMode.Automatic);
vb.SetData(vertices);

}
private void SetUpIndices()
{
short[] indices = new short[6];

indices[0] = 3;
indices[1] = 1;
indices[2] = 0;
indices[3] = 4;
indices[4] = 2;
indices[5] = 1;

ib = new IndexBuffer(m_Device, typeof(short), 6, ResourceUsage.WriteOnly, ResourceManagementMode.Automatic);
ib.SetData(indices);
}

private void SetUpCamera()
{
Matrix viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 40), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
Matrix projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.Window.ClientBounds.Width / this.Window.ClientBounds.Height, 1.0f, 50.0f);


}

protected void Window_ClientSizeChanged(object sender, System.EventArgs e)
{

graphics.PreferredBackBufferWidth = Window.ClientBounds.Width;
graphics.PreferredBackBufferHeight = Window.ClientBounds.Height;



}

/// <summary>
/// Load your graphics content. If loadAllContent is true, you should
/// load content from both ResourceManagementMode pools. Otherwise, just
/// load ResourceManagementMode.Manual content.
/// </summary>
/// <param name="loadAllContent">Which type of content to load.</param>
protected override void LoadGraphicsContent(bool loadAllContent)
{
if (loadAllContent)
{
// TODO: Load any ResourceManagementMode.Automatic content
}

CompiledEffect compiledEffect = Effect.CompileEffectFromFile("@/../../../../effects.fx", null, null, CompilerOptions.None, TargetPlatform.Windows);
effect = new Effect(graphics.GraphicsDevice, compiledEffect.GetEffectCode(), CompilerOptions.None, null);


if(this.Window.ClientBounds.Height>0){
Matrix viewMatrix = Matrix.CreateLookAt(new Vector3(0, 0, 40), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
Matrix projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, this.Window.ClientBounds.Width / this.Window.ClientBounds.Height, 1.0f, 50.0f);
effect.Parameters["xView"].SetValue(viewMatrix);
effect.Parameters["xProjection"].SetValue(projectionMatrix);
effect.Parameters["xWorld"].SetValue(Matrix.Identity);
}


// TODO: Load any ResourceManagementMode.Manual content
}


/// <summary>
/// Unload your graphics content. If unloadAllContent is true, you should
/// unload content from both ResourceManagementMode pools. Otherwise, just
/// unload ResourceManagementMode.Manual content. Manual content will get
/// Disposed by the GraphicsDevice during a Reset.
/// </summary>
/// <param name="unloadAllContent">Which type of content to unload.</param>
protected override void UnloadGraphicsContent(bool unloadAllContent)
{
if (unloadAllContent)
{
// TODO: Unload any ResourceManagementMode.Automatic content
content.Unload();
}
effect.Dispose();

// TODO: Unload any ResourceManagementMode.Manual content
}


/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();


KeyboardState kState = Keyboard.GetState();
if(kState.IsKeyDown(Keys.F)) {
graphics.ToggleFullScreen();
}

// TODO: Add your update logic here

angle += 0.05f;



base.Update(gameTime);
}

/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
m_Device.Clear(Color.BurlyWood);

effect.CurrentTechnique = effect.Techniques["Colored"];

Vector3 rotAxis = new Vector3(3*angle, angle, 2*angle);
rotAxis.Normalize();

Matrix worldMatrix = Matrix.CreateTranslation(-5, -10 * 1 / 3, 0) * Matrix.CreateFromAxisAngle(rotAxis, angle);
worldMatrix = Matrix.Identity;
effect.Parameters["xWorld"].SetValue(worldMatrix);

m_Device.RenderState.FillMode = FillMode.WireFrame;

effect.Begin();

foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
pass.Begin();

m_Device.Vertices[0].SetSource(vb, 0, VertexPositionColor.SizeInBytes);
m_Device.Indices = ib;
m_Device.VertexDeclaration = new VertexDeclaration(m_Device, VertexPositionColor.VertexElements);
m_Device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 5, 0, 2);

pass.End();
}
effect.End();


base.Draw(gameTime);
}
}
}




It usually crashes on m_Device.Clear because m_Device is disposed.I tried to recreate it but then it crashes on draw saying memory is corrupt.

Share this post


Link to post
Share on other sites
Just a note on creating editors, you can add a winform to an XNA project, I'm just using a seperated winform window to handle my buttons and menus etc (just like a floating tools box)

ie

Just add a winform to the project and use the designer to add your buttons and menues etc.

Say you call the winform ControlForm then you add it as a variable to the in the main "game file"


ControlForm form;



Then in the Initialize section add.


form = new ControlForm();
form.Show();



I communicate from the winform to the xna project by using accesors in the winform
for a colour variable or to set the text in a text box.


Color backColour = Color.PaleTurquoise;
public Color GetBackColor { get { return backColour; } }

//Access the textbox
public String CameraTarget { set { CamTextBox.Text = value; } }



I read and write these in the update section of the XNA code.
To use dialog boxes I found you have to chenge the threading model to


System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA);



and add [STAThread] before the Main delcaration in the Program file. (Program.cs) I assume this threading change is not great for games but for tools it sholud be fine.

I haven't invesigated using messages to communicate with the winform and the xna prog I tend just to use boolean and int flags.

Share this post


Link to post
Share on other sites
Quote:
Original post by Black Knight
Does any1 managed to handle the xna game window sizing?
It always crashes when the I size the height to 0.

Don't let the window be resized to 0. [wink]

Share this post


Link to post
Share on other sites
Here is what I got finally.
A XNA application using MDI forms.
I created an XNA game project and delete the game class completely then I added an MDI parent form.
I create a RenderForm in another project which is a game library.
The render form is derived from Form and IServiceProvider.
IServiceProvider is used to get the GraphicsDeviceManager which in turn gives the graphics device.I also implemented IGraphicsDeviceService and IGraphicsDeviceManager.These can be found on the net.

Then i added this render form by code to the MDI application and created the device and rendering.The render form also has a content manager so loading of sprite fonts and other contents will be done like that.

Here is a screen shot.

Share this post


Link to post
Share on other sites
Kal_jez, one thing you can do is just add event handlers to the control form that are found in the game form. For example, add Button_Click() function to the Game class, and then set frmContro.button1.click += new Eventhandler(Button_Click);

One question though, is where you are setting the threading model? You said in Main, but for me it always fails to change the threading, and it seems to work without it.

Thanks!

Share this post


Link to post
Share on other sites
Note that xna does not depend on the game framework. If you're solely targeting Windows and find the Game class too inflexible, choosing to not use it is a very reasonable thing to do. The game class doesn't do anything magical that you can't do yourself. And as an MS developer admitted to me, the Game class isn't designed to be very flexible. It's just there so new users can jump straight in.

Manually initialising the graphics device is actually very easy. Much easier than managed directx. Incidently, you don't need to use the Game class on the xbox 360 either: you can just pass null to the graphics device constructor for the window handle.

If you're happy with your current method, by all means stay with it. I just mention this because I prefer the greater flexibility it gives you when doing something unusual like rendering to an external window or incorporating xna into an existing engine. When I try to do this with the Game class I feel like I'm trying to cram a cube through a round hole.

Share this post


Link to post
Share on other sites
If that's the case, then does the 360 see the app any differently than the PC in terms of how the device is setup? I have not compared the default code created from choosing a 360 and PC project, but I was under the impression that everything underneath was handled differently. Now I think about it, really, that should all be handled under the abstraction layer that is DX, and not within the C# code itself. Is there by any chance another thread of these conversations we can reference?

Share this post


Link to post
Share on other sites
When setting up the device manually, the only difference between the pc and xbox is that in windows, you pass the handle to the window to the GraphicsDevice constructor, while on the xbox you simply pass null. Naturally you also need to account for different display modes between the console and pc, but you need to do that whether manually managing the device or not.

Here's a thread where I contributed a very minimalist example of using xna in a form.

For the xbox you'd pass null in place of form.Handle.

Share this post


Link to post
Share on other sites
I'm interested in what people have to say about the approach to the problem presented by The instruction limit: http://www.zaknafein.hjcrusaders.com/?p=24

It has the obvious flaw of the programmer having to copy and post all the form+designer code from the Form file to the WindowsControl file, but the first comment posted on the page is interesting in that he says that this is not really necessary, however he does not expand much. Does anyone get what he is pointing out?

Share this post


Link to post
Share on other sites
This blog entry is an example of what I was referring to: someone being too attached to the game class when doing something unusual. A ton of ugly hacks result, as seen there. Using reflection and manually duplicating the Game framework? Wow, that's ugly.

The nice thing is, you don't need the game class to implement the content pipeline. All the ContentManager class needs is an IGraphicsDeviceService to provide it with a GraphicsDevice.


class GraphicsDeviceService
: IGraphicsDeviceService, IServiceProvider
{
public GraphicsDeviceService(GraphicsDevice graphicsDevice)
{
mGraphicsDevice = graphicsDevice;
}

private GraphicsDevice mGraphicsDevice = null;

public GraphicsDevice GraphicsDevice
{
get { return mGraphicsDevice; }
}

public event EventHandler DeviceCreated;
public event EventHandler DeviceDisposing;
public event EventHandler DeviceReset;
public event EventHandler DeviceResetting;

public Object GetService(System.Type serviceType)
{
if (serviceType == typeof(IGraphicsDeviceService))
return this;
else
throw new ArgumentException();;
}
}





Then you create the graphics device manually as I showed previously. Then create the content manager as follows:

mContentManager = new ContentManager(new GraphicsDeviceService(mGraphicsDevice));

That's it, you now have a working content pipeline. I confirmed yesterday that this works on the 360 (finally broke down and bought one :P ).

Quote:
Original post by JustHeath
It has the obvious flaw of the programmer having to copy and post all the form+designer code from the Form file to the WindowsControl file, but the first comment posted on the page is interesting in that he says that this is not really necessary, however he does not expand much. Does anyone get what he is pointing out?


The commenter was right. Copying and pasting the code like that is sloppy (as is the rest of this guys code, I must say). He can just make the panel accessible through a property in the form. I don't know what the problem is with competing input focus: a control and it's parent window don't compete like that. What he describes would occur between say, a MDI child window and it's parent window, but not here. There are minor complications, such as the fact that keyboard input is received through the form, while mouse input is received through the panel, but that's perfectly manageable.

[Edited by - gharen2 on June 28, 2007 3:02:10 PM]

Share this post


Link to post
Share on other sites
What about a scenario where you have developed something integral to both the game and the editor (such as a tile engine) as a GameComponent? How do you compensate for something like that without either rewriting your code or writing a specialized version of the component for use without a Game object?

Share this post


Link to post
Share on other sites
I can say what I'd do: not use the GameComponent class in either situation. I really don't like that part of xna, as it binds you too tightly to an api, and makes your code harder to port (which is the same reason I gave for disliking the Game class).

The GameComponent class is very simple anyways. It's essentially just a container that the game automatically updates each frame. There's nothing keeping you from creating your own class and calling it's update function yourself each frame. You can supply any information it needs through that function, such as elapsed time.

edit:

For giggles I decided to put together a simple game framework of my own, since I already have all the necessary parts lying around and some people may find it useful. Plus I've been looking for a nice little side project. Looking at the horrible hacks in that blog inspired me. This framework should be usable without Game Studio Express, you'll just have to load content manually rather than through the content pipeline.

I've applied for a sourceforge project for it, and once it's approved I'll make the source available. I've called it the Minimalist Game Framework for Xna (MGFX) and it's designed to be both minimal and flexible. Features it shares with Xna's game class are the content pipeline and simplified device management. But it's designed be cleanly usable in a Control as well, and gives you direct control over the rendering loop. A lot of fluff such as GraphicsDeviceManager have been cut out. Classes also aren't as tightly coupled (for example, in Xna, the GameWindow and Game classes are interdependent. In my framework, the Window class has no knowledge of the Game class).

Here's a project template as it stands right now. It's been tested in windows, the 360, and inside a WinForm control.


using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;

using MGFX;

namespace MGFXWindowsGame
{
public class Game1
: MGFX.Game
{
/// <summary>
/// Perform any initialisations needed before the game runs. This method is called
/// before the first frame is rendered. The GraphicsDevice has yet to be created, so
/// only non-graphical resources should be created or altered here. The one exception
/// is that you may alter the PresentationParameter property however you like.
/// </summary>
/// <returns>An instance of an IWindow implementation.</returns>
protected override IWindow Initialise()
{
// TODO: Add your initialization logic here.

// At this point PresentationParameter has been set to default values, but may
// be altered as you choose.

// Create and return an IWindow implementation.
IWindow window = new Window(PresentationParameters.BackBufferWidth, PresentationParameters.BackBufferHeight);
window.Text = "MGFX Windows Game";
return window;
}

/// <summary>
/// Load GraphicsDevice dependent resources.
/// </summary>
/// <param name="loadAllResources">If true, load resources with either
/// ResourceManagementModes. If false, only load resources with
/// ResourceManagementMode.Manual.</param>
protected override void LoadGraphicsResources(bool loadAllResources)
{
if (loadAllResources)
{
// TODO: Load any ResourceManagementMode.Automatic resources.
}

// TODO: Load any ResourceManagementMode.Manual resources.
}

/// <summary>
/// Dispose GraphicsDevice dependent resources.
/// </summary>
/// <param name="disposeAllResources">If true, dispose resources with either
/// ResourceManagementModes. If false, only dispose resources with
/// ResourceManagementMode.Manual.</param>
protected override void DisposeGraphicsResources(bool disposeAllResources)
{
if (disposeAllResources)
{
// TODO: Dispose any ResourceManagementMode.Automatic resources.
ContentManager.Unload();
}

// TODO: Dispose any ResourceManagementMode.Manual resources.
}

/// <summary>
/// Perform per-frame logic not related to rendering. This includes
/// physics, audio, and input.
/// </summary>
/// <param name="timeSpan">The duration of the previous frame.</param>
protected override void Update(TimeSpan timeSpan)
{
// Exit the game if the gamepad's back button or the escape button is hit.
if ((GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) ||
Keyboard.GetState().IsKeyDown(Keys.Escape))
{
Dispose();
return;
}

// TODO: Add your update logic here.
}

/// <summary>
/// Render a frame.
/// </summary>
protected override void Render()
{
GraphicsDevice.Clear(Color.CornflowerBlue);

// TODO: Add your rendering code here.

GraphicsDevice.Present();
}
}
}







edit 2:

Sourceforge project

I'm not going to release a package until it's more complete. For example, at the moment there's zero error handling, and plenty of features missing like the ability to hide the cursor. But the source is there to look at.

[Edited by - gharen2 on June 29, 2007 12:39:05 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this