I am new to jMonkeyEngine and I am creating a game where the user can dynamically alter the map. For this I am using custom objects derived from the Mesh class where I set everything to generate the shapes of the parts of my map.
So if a user blows a hole into a part of my map the corresponding custom Mesh gets recreated with the blown off parts missing to give an example. What I am currently doing and what works is: when a Mesh is altered I detach the old one, create the new altered one and attach it to the scene in place of the old Mesh. This works as expected.
Is there also a way to modify the old Mesh in place? Can I just set new vertex buffers for it and tell it to rerender itself? I tried this out already but when I do this then the Mesh isn’t correctly rendered anymore and sometimes it even disappears completely.
Do I have to call certain methods after resetting the vertex buffers?
Which of the two approaches is the better one regarding performance?
It depends. Does your mesh when modified contain the same amount of vertices? Will the indices still work with the changes? If yes, then just modify the mesh, else you will have to re-calculate/re-built it all anyway.
When you build or modify a mesh you must execute mesh.updateBounds() to update the bounds.
There are a few very helpful static methods in BufferUtils that aid you with meshes.
And just to add, In my experience, i just create or rebuild the meshes in some form of threadpool. I first add the new mesh and then remove the old one. It stops objects disappearing momentarily.
It does not contain the same amount of vertices when modified. I am rebuilding the buffers every time. So I guess creating a new Mesh, attaching it and then detaching the old one is the way to go?
Those static methods are pretty useful.
You can see how to update meshes by looking at many of the existing Mesh subclasses like Quad, Box, etc. that all let you resize/rebuild them at runtime. After that, you just need to make sure the model bound is updated.
But if you ever plan to offload the mesh modifications to another thread then there is no alternative but to rebuild and replace… because you absolutely 100000% cannot touch a mesh in the scene from another thread.
Edit: but note that if you are changing the size of the buffers… you can reuse the mesh but you will be replacing the buffers anyway. And the mesh wrapper is the small part. Might as well just replace it all.