GodotSectors/Scripts/Space/SpaceRegion.gd

82 lines
2.2 KiB
GDScript

extends SpaceEntity
class_name SpaceRegion
@export var elevation: float = 0.0
@export var height: float = 100.0
@export var wall_texture: Texture2D
@export var floor_texture: Texture2D
func generate_geometry(space: Space) -> Node3D:
return _generate_geometry(space, true)
func _generate_geometry(space: Space, looked_from_inside: bool) -> Node3D:
var geometry := MeshInstance3D.new()
geometry.name = name
var polygon = self.polygon
var polygon_pairs = Array()
for i in range(-1, polygon.size() - 1):
polygon_pairs.append([polygon[i], polygon[i+1]])
var vertices = PackedVector3Array()
var uvs = PackedVector2Array()
for line in polygon_pairs:
_push_line(space, line, vertices, uvs, looked_from_inside)
var arrays := Array()
arrays.resize(Mesh.ARRAY_MAX)
arrays[Mesh.ARRAY_VERTEX] = vertices
arrays[Mesh.ARRAY_TEX_UV] = uvs
var mesh := ArrayMesh.new()
mesh.add_surface_from_arrays(Mesh.PRIMITIVE_TRIANGLES, arrays)
var new_material := preload("res://Scenes/RegionMaterial.tres")
new_material.albedo_texture = wall_texture
mesh.surface_set_material(0, new_material)
geometry.mesh = mesh
for child in get_children():
if child is SpaceRegion:
geometry.add_child(child._generate_geometry(space, not looked_from_inside))
return geometry
func _push_line(space: Space,
line: Array,
vertices: PackedVector3Array,
uvs: PackedVector2Array,
looked_from_inside: bool
):
var v0 := Vector3(
line[0][0] * space.unit_scale, elevation * space.unit_scale,
line[0][1] * space.unit_scale)
var v1 := Vector3(
line[1][0] * space.unit_scale, (elevation + height) * space.unit_scale,
line[1][1] * space.unit_scale)
var v2 := Vector3(
line[1][0] * space.unit_scale, elevation * space.unit_scale,
line[1][1] * space.unit_scale)
var v3 := Vector3(
line[0][0] * space.unit_scale, (elevation + height) * space.unit_scale,
line[0][1] * space.unit_scale)
if looked_from_inside:
vertices.append_array([v0, v1, v2, v1, v0, v3])
else:
vertices.append_array([v0, v2, v1, v1, v3, v0])
uvs.append(Vector2(0, 1))
uvs.append(Vector2(1, 0))
uvs.append(Vector2(1, 1))
uvs.append(Vector2(1, 0))
uvs.append(Vector2(0, 1))
uvs.append(Vector2(0, 0))