Search code examples
c#modelxnaterraingenerated

How to Create Model from Scratch


I am working to generate terrain for our project, something that will be contained in the Model class that I can draw, but I new class would be alright since I may need to look inside for specific data often, and then I would just need the basic function to work with the Game class. Anyway, I have a fair amount of knowledge of the XNA framework, but because of how convoluted it handles anything. So my problem is I can't just make a Model, I can't instantiate that class or anything. I have what I believe the proper data to form a model's geometry, which is all I need right now, and later possibly have it textured. I don't know where to go from here.

XNA you usually use Content.Load, to have their content pipeline read in a file and parse it specifically, but I want to avoid that because I want my terrain generated. I can compute an array of Vertex data and indices for the triangles I want to make-up a mesh, but so far my efforts have tried to instantiate any object like Model or those it contains, have failed. If there is some factory class I can use to build it, I have no idea what that is, so if someone else can point me in the right direction there and give me a rough outline on how to build a model, that would help. If that's not the answer, maybe I need to do something completely different, either centered on using Content.Load or not, but basically I don't want my terrain sitting in a file, consistent between executions, I want to control the mesh data on load and randomize it, etc.

So how can I get a model generated completely programmatically, to show up on the screen, and still have its data exposed?


Solution

  • Model and its associated classes (eg: ModelMesh), are convenience classes. They are not the only way to draw models. It is expected that sometimes, particularly when doing something "special", you will have to re-implement them entirely, using the same low-level methods that Model uses.

    Here's the quick version of what you should do:

    First of all, at load time, create a VertexBuffer and an IndexBuffer and use SetData on each to fill each with the appropriate data.

    Then, at draw time, do this:

    GraphicsDevice.SetVertexBuffer(myVertexBuffer);
    GraphicsDevice.Indices = myIndexBuffer;
    
    // Set up your effect. Use a BasicEffect here, if you don't have something else.
    myEffect.CurrentTechnique.Passes[0].Apply();
    
    GraphicsDevice.Textures[0] = myTexture; // From Content.Load<Texture2D>("...")
    
    GraphicsDevice.DrawIndexedPrimitives(...);