Skip to content

Instantly share code, notes, and snippets.

@Arnklit
Created March 16, 2022 06:56
Show Gist options
  • Save Arnklit/faf33e768c9c08223f08c3afefaab8c0 to your computer and use it in GitHub Desktop.
Save Arnklit/faf33e768c9c08223f08c3afefaab8c0 to your computer and use it in GitHub Desktop.
Subdivided Plane Set as Lod Levels in Godot 4.0
@tool
extends MeshInstance3D
@export var generate := false:
set(v):
gen_mesh()
@export_range(0, 10) var subdivisions := 5
@export var size := 8.0
func gen_mesh():
print("gen mesh")
var new_mesh := ArrayMesh.new()
var verts := PackedVector3Array()
var indices := []
var index_counter := 0
var lod := subdivisions
while lod >= 0:
var subs = pow(2.0, float(lod))
var sub_indices := PackedInt32Array()
for y in subs:
for x in subs:
var current_pos := Vector3()
verts.append(Vector3(float(x) / subs * size, 0.0, float(y) / subs * size))
verts.append(Vector3(float(x) / subs * size + float(size) / subs, 0.0, float(y) / subs * size))
verts.append(Vector3(float(x) / subs * size, 0.0, float(y) / subs * size + float(size) / subs))
verts.append(Vector3(float(x) / subs * size, 0.0, float(y) / subs * size + float(size) / subs))
verts.append(Vector3(float(x) / subs * size + float(size) / subs, 0.0, float(y) / subs * size))
verts.append(Vector3(float(x) / subs * size + float(size) / subs, 0.0, float(y) / subs * size + float(size) / subs))
sub_indices.append(index_counter)
sub_indices.append(index_counter + 1)
sub_indices.append(index_counter + 2)
sub_indices.append(index_counter + 3)
sub_indices.append(index_counter + 4)
sub_indices.append(index_counter + 5)
index_counter += 6;
indices.append(sub_indices)
lod -= 1
var vertices := PackedVector3Array(verts)
var arrays = []
arrays.resize(Mesh.ARRAY_MAX)
arrays[Mesh.ARRAY_VERTEX] = verts
arrays[Mesh.ARRAY_INDEX] = indices[0]
var blend_shapes = []
var lods = {}
for i in subdivisions:
lods[(float(i) + 1.0)] = indices[i + 1]
new_mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays, blend_shapes, lods)
mesh = new_mesh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment