iFactory.Godot/Artists/Scripts/Factory/PathRenderer.cs

63 lines
1.6 KiB
C#
Raw Normal View History

2023-11-02 20:58:36 +08:00
using Godot;
using System;
using System.Collections.Generic;
using BITKit;
using Newtonsoft.Json.Linq;
namespace BITFactory;
public partial class PathRenderer : EntityBehaviour
{
[Export] private DeviceValueComponent valueComponent;
[Export] private Node3D root;
private readonly List<MeshInstance3D> meshInstances=new();
public override void OnAwake()
{
base.OnAwake();
valueComponent.OnValueChanged += OnValueChanged;
}
private void OnValueChanged(string arg1, DateTime arg2)
{
foreach (var x in meshInstances)
{
x.QueueFree();
}
meshInstances.Clear();
Vector3 lastPoint = Vector3.Zero;
foreach (var pair in JArray.Parse(arg1))
{
var x = pair["X"]!.ToObject<float>()!;
var y = pair["Y"]!.ToObject<float>()!;
var currentPoint =root.Position + new Vector3(x, 0, y);
if (lastPoint != Vector3.Zero)
{
meshInstances.Add(Line(lastPoint, currentPoint,Colors.Orange));
}
lastPoint = currentPoint;
}
}
public static MeshInstance3D Line(Vector3 pos1, Vector3 pos2, Color? color = null)
{
var meshInstance = new MeshInstance3D();
var immediateMesh = new ImmediateMesh();
var material = new StandardMaterial3D();
meshInstance.Mesh = immediateMesh;
meshInstance.CastShadow = GeometryInstance3D.ShadowCastingSetting.Off;
immediateMesh.SurfaceBegin(Mesh.PrimitiveType.Lines, material);
immediateMesh.SurfaceAddVertex(pos1);
immediateMesh.SurfaceAddVertex(pos2);
immediateMesh.SurfaceEnd();
material.ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded;
material.AlbedoColor = color ?? Colors.WhiteSmoke;
(Engine.GetMainLoop() as SceneTree).Root.AddChild(meshInstance);
return meshInstance;
}
}