using GarmentButton.Culling;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Rendering;
using Unity.Transforms;
using UnityEngine;
using Vector3 = UnityEngine.Vector3;
namespace GarmentButton.VerletIntegration.Render
{
[UpdateInGroup(typeof(VerletIntegrationGroupSystems))]
public partial struct EditPointsToRender : ISystem
{
public void OnCreate(ref SystemState state)
{
var query = SystemAPI.QueryBuilder().WithAll<Point, RenderMeshArray, MaterialMeshInfo>().Build();
state.RequireForUpdate(query);
}
public void OnUpdate(ref SystemState state)
{
foreach (var (points, renderMeshArray, renderInfo, transform) in SystemAPI
.Query<DynamicBuffer<Point>, RenderMeshArray, MaterialMeshInfo, RefRO<LocalToWorld>>()
.WithAll<VisibleTag>())
{
var mesh = renderMeshArray.GetMesh(renderInfo);
var pointsNative = points.AsNativeArray().AsReadOnly();
NativeArray<float3> positions = new NativeArray<float3>(points.Length, Allocator.TempJob);
var job = new EditPoints
{
VertexPoints = positions,
Points = pointsNative,
EntityPosition = transform.ValueRO.Position,
EntityRotation = transform.ValueRO.Rotation,
}.ScheduleParallel(pointsNative.Length, 16, new JobHandle());
job.Complete();
var v3 = positions.Reinterpret<Vector3>();
mesh.SetVertices(v3);
positions.Dispose();
}
}
[BurstCompile]
public partial struct EditPoints : IJobFor
{
[NativeDisableParallelForRestriction] public NativeArray<float3> VertexPoints;
[ReadOnly] public NativeArray<Point>.ReadOnly Points;
[ReadOnly] public float3 EntityPosition;
[ReadOnly] public quaternion EntityRotation;
public void Execute(int index)
{
float3 worldOffset = Points[index].Position - EntityPosition;
VertexPoints[index] = math.rotate(math.inverse(EntityRotation), worldOffset);
}
}
public static NativeArray<float3> GetVertices(Mesh.MeshData meshData)
{
int vertexCount = meshData.vertexCount;
var vertices = new NativeArray<float3>(vertexCount, Allocator.TempJob);
meshData.GetVertices(vertices.Reinterpret<Vector3>());
return vertices;
}
}
}