Alter a plane mesh programmatically with Godot 3.0.2

As I’m playing around with Godot and meshes (programmatically generated meshes to be precise).
I’ve found something that I believe is worth sharing.

I have to mention that I haven’t found a real life use of this technique, say to generate a heightmap. Yet I believe it may exist a way to do it.

How to use SurfaceTool and MeshDataTool

I’ve created a simple script that should allow to understand it just by reading the code, it’s quite simple once you know how to use those tools.

You have to place the script in a scene with the following elements (same names, or change the code accordingly):

Spatial (attach script here)
|- DirectionalLight
|- MeshInstance

The script should be attached to the root node, and actually, the directional light is needed just to see the correct creation of the normals.

Once done you should see the new property “size”, when you set it the code will generate a “heightmap”, the size you have established.

Please note that depending on your machine it may take a while as you go further than 256 (on my slow ION pc it takes in seconds per size: 0.5 x 64, 2 x 128, 13 x 256).

The role of SurfaceTool

So, to go deeper, st (the surface tool), can create an array mesh starting from a previously generated mesh (it can be any type, in this case i have used the plane mesh), this way:

The Mesh Data Tool

Once converted into an ArrayMesh, it can be used by the MeshDataTool, as the other one, the PlaneTool, cannot modify meshes, just create them.

Now that the MeshDataTool can place its hands on the plane we can work this way to alter some vertex (the y axis in this case)

Generating normals and place the mesh in the nodetree

Good, almos done, now the next part consists in removing the previous meshes (if any), and generate the normals for our modified plane.

How do you create the normals, well, godot have this nice feature that allow us to avoid using vector math, ad does it all for us, but you have to move the mesh back to the SurfaceTool (yeah, I wonder why it’s not all in the same object, instead of having 2, but well) generate_normals() does it all.

Then, finally, we take our newly created mesh and we want to put it somewhere, so that anyone can see it, as we are proud parents (commit() returns the final mesh):

 

Posted in 3D, Game Development and tagged , , , , .

2 Comments

    • Hahaha… LOL, not really applicable, at least not for me, when I realized that it’s quite hard to forsee where a vertex is positioned in the plane mesh given the index only..
      Anyhow I’ll try to find the time to better understand the usage of the Mesh Data Tool.. hopefully by the time the official documentation will be improved (last version I checked was much better than a year ago).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.