Skip to content

Instantly share code, notes, and snippets.

@Frooxius
Created September 16, 2018 14:16
Show Gist options
  • Save Frooxius/393e675200fd270bae207fb9c16eba3c to your computer and use it in GitHub Desktop.
Save Frooxius/393e675200fd270bae207fb9c16eba3c to your computer and use it in GitHub Desktop.
Quad Array Mesh
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BaseX;
namespace FrooxEngine
{
[Category("Assets/Procedural Meshes")]
public class QuadArrayMesh : ProceduralMesh
{
public readonly SyncArray<float3> Points;
public readonly SyncArray<float2> Sizes;
public readonly SyncArray<floatQ> Rotations;
public readonly SyncArray<color> Colors;
public readonly SyncArray<float4> UVs;
RangeModificationTracker invalidRange = new RangeModificationTracker();
TriangleSubmesh submesh;
Quad quad;
protected override void OnAwake()
{
base.OnAwake();
invalidRange.TrackArray(Points);
invalidRange.TrackArray(Sizes);
invalidRange.TrackArray(Rotations);
invalidRange.TrackArray(Colors);
invalidRange.TrackArray(UVs);
}
protected override IEnumerator<Context> UpdateMesh()
{
int uploadIndex = invalidRange.MinInvalidIndex;
int uploadCount = MathX.Min(invalidRange.InvalidCount, MathX.Max(0, Points.Count - uploadIndex));
if (uploadCount == 0)
yield break;
invalidRange.Reset();
var _points = Points.GetBuffer();
var _sizes = Sizes.GetBuffer();
var _rotations = Rotations.GetBuffer();
var _colors = Colors.GetBuffer();
var _uvs = UVs.GetBuffer();
yield return Context.ToBackground();
submesh = submesh ?? meshx.TryGetSubmesh<TriangleSubmesh>();
var newTrigCount = _points.count * Quad.TOTAL_TRIANGLES;
var oldTrigCount = submesh.Count;
meshx.SetVertexCount(_points.count * Quad.TOTAL_VERTICES);
submesh.SetCount(newTrigCount);
if(newTrigCount > oldTrigCount)
for(int i = oldTrigCount; i < newTrigCount; i+=2)
{
int vIndex = i << 1;
submesh.SetQuadAsTriangles(vIndex, vIndex + 1, vIndex + 2, vIndex + 3, i, i + 1);
}
quad = quad ?? new Quad(meshx.GetVertex(0));
meshx.HasColors = _colors.count > 0;
meshx.HasUV0s = true;
meshx.HasNormals = true;
meshx.HasTangents = true;
if (meshx.HasColors)
quad.Color = null;
for(int i = uploadIndex; i < uploadIndex + uploadCount; i++)
{
quad.Position = _points[i];
quad.Rotation = _rotations.GetElement(i, floatQ.Identity);
quad.Size = _sizes.GetElement(i, float2.Zero);
var uv = _uvs.GetElement(i, new float4(0f, 0f, 1f, 1f));
quad.UVOffset = uv.xy - uv.zw * 0.5f;
quad.UVScale = uv.zw;
if (_colors.count != 0)
quad.Color = _colors.GetElement(i, color.White);
quad.UpdateUnsafe(i * Quad.TOTAL_VERTICES);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment