5

Lets say you make a game engine, and you have several GameObjects and every GameObject have a list of components that you can add or remove.

Lets say there is a MeshComponent who has vertices, normals etc. If several GameObjects have the same MeshComponent, there will be a lot of memory waste. Of course there are many ways to implements this but I want some good advice how to solve this? How do components share data that is not going to be modified?

Tetrad
  • 30,124
  • 12
  • 94
  • 143
Merni
  • 247
  • 1
  • 5

2 Answers2

3

You need to make the distinction between "component" and "asset".

Basically, you would have some kind of renderer component attached to your game object that references a mesh (by a handle or by pointer or whatever) and uses that. It's just like how you reference textures by ID instead of having everything that needs a texture have all the pixel data.

Tetrad
  • 30,124
  • 12
  • 94
  • 143
  • 1
    I was thinking of having a mesh_manager, and then you ask the manager, mesh_manager->get("Speher"); and the manager handles all the meshes. Which way do you prefer? Maybe your way is better, because then you can easily change mesh by just doing, mesh_component(set Mesh) or something – Merni May 22 '11 at 08:50
3

I would assume you want a different structure for a MeshComponent than, say, a HealthComponent.

Consider some kind of AssetManager or ResourceManager that holds the resources - be it a mesh, a map, or a texture (probably different managers) - and your MeshComponent holds a reference or a pointer. All the meshes will share the same actual mesh.

You may have some system like this: (since there is no language given, this is C# - C++ or other non managed languages would need pointers somewhere)

ResourceCache<Mesh> meshManager = new ResourceCache<Mesh>();
meshManager.Load("sphere");
Entity e = Entity.Create(); //Factory
e.AddComponent("Mesh", new MeshComponent(meshManager.GetReferenceTo("sphere"));

The only problem arises if you want any kind of mesh deformation. You'll probably either want to store a list of changed vertex data OR a whole new set of mesh data. Probably the former.

PrettyPrincessKitty FS
  • 10,315
  • 8
  • 43
  • 68
  • Another mesh deformation solution might be to make mesh data lazily copied when accessed. Normally it just draws, but if you access the mesh data it makes a copy so you can do whatever you want with it without affecting other instances of it. – Tetrad May 22 '11 at 17:06