gmtk24/scripts/BuildingBlockCreator.cs

66 lines
3.0 KiB
C#
Raw Normal View History

2024-08-17 20:52:00 +02:00
using System.Collections.Generic;
using Godot;
using Godot.Collections;
namespace Gmtk24 {
public partial class BuildingBlockCreator : Node3D {
[Export]
2024-08-17 21:05:30 +02:00
public Node3D TrenchbroomMap;
2024-08-17 20:52:00 +02:00
[Export]
2024-08-17 21:05:30 +02:00
public PackedScene BuildingBlockPrefab;
[Export]
public ShaderMaterial BuildingBlockMaterial;
2024-08-17 20:52:00 +02:00
public override void _Ready() {
var scale = 0.05f;
2024-08-17 21:05:30 +02:00
var children = TrenchbroomMap.FindChildren("*_buildingblock");
2024-08-17 20:52:00 +02:00
foreach (var buildingBlockStaticBody in children) {
2024-08-17 21:05:30 +02:00
var buildingBlock = BuildingBlockPrefab.Instantiate();
2024-08-17 20:52:00 +02:00
var smallMesh = new MeshInstance3D {
Mesh = buildingBlockStaticBody.GetChild<MeshInstance3D>(0).Mesh,
Scale = Vector3.One * scale,
};
for (int i = 0; i < smallMesh.GetSurfaceOverrideMaterialCount(); i++) {
var replacedMaterial = smallMesh.Mesh.SurfaceGetMaterial(i);
var transparency = replacedMaterial.Get("transparency");
if (((int)transparency) != 0) {
// Make a new material, using the partly-transparent albedo as an alpha mask
var blockMaterialWithAlphaMask = new ShaderMaterial {
2024-08-17 21:05:30 +02:00
Shader = BuildingBlockMaterial.Shader,
2024-08-17 20:52:00 +02:00
};
2024-08-17 21:05:30 +02:00
foreach (var uniform in BuildingBlockMaterial.Shader.GetShaderUniformList()) {
2024-08-17 20:52:00 +02:00
var uniformName = (StringName)((Dictionary)uniform).GetValueOrDefault("name");
2024-08-17 21:05:30 +02:00
blockMaterialWithAlphaMask.SetShaderParameter(uniformName, BuildingBlockMaterial.GetShaderParameter(uniformName));
2024-08-17 20:52:00 +02:00
}
blockMaterialWithAlphaMask.SetShaderParameter("texture_albedo_for_alpha", replacedMaterial.Get("albedo_texture"));
smallMesh.SetSurfaceOverrideMaterial(i, blockMaterialWithAlphaMask);
} else {
2024-08-17 21:05:30 +02:00
smallMesh.SetSurfaceOverrideMaterial(i, BuildingBlockMaterial);
2024-08-17 20:52:00 +02:00
}
}
2024-08-17 21:05:30 +02:00
buildingBlock.AddChild(smallMesh);
2024-08-17 20:52:00 +02:00
var collisionShapes = buildingBlockStaticBody.FindChildren("*_collision_shape");
foreach (var shape in collisionShapes) {
var bigPoints = ((ConvexPolygonShape3D)((CollisionShape3D)shape).Shape).Points;
var points = new Vector3[bigPoints.Length];
for (int i = 0; i < bigPoints.Length; i++) {
points[i] = bigPoints[i] * scale;
}
2024-08-17 21:05:30 +02:00
buildingBlock.AddChild(new CollisionShape3D {
2024-08-17 20:52:00 +02:00
Shape = new ConvexPolygonShape3D {
Points = points,
},
});
}
2024-08-17 21:05:30 +02:00
AddChild(buildingBlock);
2024-08-17 20:52:00 +02:00
}
}
public override void _Process(double delta) {
}
}
}