Archived
* 将组件加入到菜单中。
* 添加一个任意形状编辑器
This commit is contained in:
@@ -0,0 +1,800 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace XericLibrary.Runtime.Renderer
|
||||
{
|
||||
/// <summary>
|
||||
/// 任意图案渲染器
|
||||
/// </summary>
|
||||
[AddComponentMenu("Xeric Library/UI/UIAnyPatternRenderer", 15)]
|
||||
public class UIAnyPatternRenderer : XericRendererComponent
|
||||
{
|
||||
public enum DistanceFieldMode
|
||||
{
|
||||
/// <summary>
|
||||
/// 简单模式:仅使用中心点(适用于凸多边形)
|
||||
/// </summary>
|
||||
SimpleCenter,
|
||||
|
||||
/// <summary>
|
||||
/// 高级模式:使用中轴变换(适用于任意多边形)
|
||||
/// </summary>
|
||||
MedialAxis,
|
||||
|
||||
/// <summary>
|
||||
/// 网格采样模式:在网格上采样距离(最精确但最慢)
|
||||
/// </summary>
|
||||
GridSampling
|
||||
}
|
||||
|
||||
[System.Serializable]
|
||||
public class PatternGroup
|
||||
{
|
||||
[Tooltip("该组包含的顶点索引")]
|
||||
public List<int> vertexIndices = new List<int>();
|
||||
|
||||
[Tooltip("该组的填充颜色")]
|
||||
public Color32 fillColor = Color.white;
|
||||
|
||||
[Tooltip("该组的描边颜色")]
|
||||
public Color32 strokeColor = Color.black;
|
||||
|
||||
[Tooltip("描边宽度(像素)")]
|
||||
[Range(0f, 20f)]
|
||||
public float strokeWidth = 2f;
|
||||
|
||||
[Tooltip("是否填充该组")]
|
||||
public bool fillEnabled = true;
|
||||
|
||||
[Tooltip("是否显示描边")]
|
||||
public bool strokeEnabled = true;
|
||||
|
||||
[Header("距离场设置")]
|
||||
[Tooltip("距离场生成模式")]
|
||||
public DistanceFieldMode distanceFieldMode = DistanceFieldMode.SimpleCenter;
|
||||
|
||||
[Tooltip("距离场分辨率(仅GridSampling模式使用)")]
|
||||
[Range(16, 256)]
|
||||
public int distanceFieldResolution = 64;
|
||||
|
||||
[Tooltip("是否在着色器中使用距离场(需要自定义着色器)")]
|
||||
public bool useDistanceFieldInShader = false;
|
||||
|
||||
[Tooltip("距离场衰减系数")]
|
||||
[Range(0.1f, 10f)]
|
||||
public float distanceFalloff = 1f;
|
||||
|
||||
[HideInInspector]
|
||||
public List<Vector2> cachedMedialAxisPoints = new List<Vector2>();
|
||||
[HideInInspector]
|
||||
public List<float> cachedDistances = new List<float>();
|
||||
[HideInInspector]
|
||||
public Texture2D distanceFieldTexture;
|
||||
}
|
||||
|
||||
[Header("顶点设置")]
|
||||
[Tooltip("所有顶点的列表(局部坐标)")]
|
||||
public List<Vector2> vertices = new List<Vector2>();
|
||||
|
||||
[Header("图形分组")]
|
||||
[Tooltip("定义哪些顶点构成一个图形")]
|
||||
public List<PatternGroup> patternGroups = new List<PatternGroup>();
|
||||
|
||||
[Header("全局设置")]
|
||||
[Tooltip("是否显示所有顶点的辅助标记")]
|
||||
public bool showVertexMarkers = false;
|
||||
|
||||
[Tooltip("顶点标记大小")]
|
||||
[Range(1f, 20f)]
|
||||
public float vertexMarkerSize = 5f;
|
||||
|
||||
[Tooltip("顶点标记颜色")]
|
||||
public Color vertexMarkerColor = Color.red;
|
||||
|
||||
[Header("调试设置")]
|
||||
[Tooltip("显示中轴线")]
|
||||
public bool showMedialAxis = false;
|
||||
|
||||
[Tooltip("中轴线颜色")]
|
||||
public Color medialAxisColor = Color.yellow;
|
||||
|
||||
[Tooltip("显示距离场可视化")]
|
||||
public bool visualizeDistanceField = false;
|
||||
|
||||
// 三角剖分和距离场缓存
|
||||
private Dictionary<int, List<int>> triangulationCache = new Dictionary<int, List<int>>();
|
||||
private Dictionary<int, Vector2[]> uvCache = new Dictionary<int, Vector2[]>();
|
||||
private bool isDirty = true;
|
||||
|
||||
protected override void OnPopulateMesh(VertexHelper vh)
|
||||
{
|
||||
vh.Clear();
|
||||
|
||||
if (vertices == null || vertices.Count == 0 || patternGroups == null || patternGroups.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 为每个图形分组生成网格
|
||||
foreach (var group in patternGroups)
|
||||
{
|
||||
if (group.vertexIndices == null || group.vertexIndices.Count < 3)
|
||||
continue;
|
||||
|
||||
// 获取该组的顶点
|
||||
List<Vector2> groupVertices = new List<Vector2>();
|
||||
foreach (int index in group.vertexIndices)
|
||||
{
|
||||
if (index >= 0 && index < vertices.Count)
|
||||
{
|
||||
groupVertices.Add(vertices[index]);
|
||||
}
|
||||
}
|
||||
|
||||
if (groupVertices.Count < 3)
|
||||
continue;
|
||||
|
||||
// 三角剖分
|
||||
List<int> triangles;
|
||||
int cacheKey = GetCacheKey(group.vertexIndices);
|
||||
|
||||
if (!triangulationCache.TryGetValue(cacheKey, out triangles) || isDirty)
|
||||
{
|
||||
triangles = TriangulatePolygon(groupVertices);
|
||||
triangulationCache[cacheKey] = triangles;
|
||||
}
|
||||
|
||||
// 生成UV(距离场)
|
||||
Vector2[] uvs;
|
||||
if (!uvCache.TryGetValue(cacheKey, out uvs) || isDirty)
|
||||
{
|
||||
uvs = GenerateDistanceFieldUVs(group, groupVertices, triangles);
|
||||
uvCache[cacheKey] = uvs;
|
||||
}
|
||||
|
||||
// 添加填充
|
||||
if (group.fillEnabled && triangles != null && triangles.Count > 0)
|
||||
{
|
||||
AddFilledPolygon(vh, groupVertices, triangles, uvs, group.fillColor);
|
||||
}
|
||||
|
||||
// 添加描边
|
||||
if (group.strokeEnabled && group.strokeWidth > 0)
|
||||
{
|
||||
AddStroke(vh, groupVertices, group.strokeWidth, group.strokeColor);
|
||||
}
|
||||
|
||||
// 显示中轴线
|
||||
if (showMedialAxis && group.cachedMedialAxisPoints.Count > 0)
|
||||
{
|
||||
AddMedialAxis(vh, group.cachedMedialAxisPoints, medialAxisColor);
|
||||
}
|
||||
}
|
||||
|
||||
// 添加顶点标记
|
||||
if (showVertexMarkers)
|
||||
{
|
||||
AddVertexMarkers(vh);
|
||||
}
|
||||
|
||||
isDirty = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成距离场UV坐标
|
||||
/// </summary>
|
||||
private Vector2[] GenerateDistanceFieldUVs(PatternGroup group, List<Vector2> vertices, List<int> triangles)
|
||||
{
|
||||
Vector2[] uvs = new Vector2[vertices.Count];
|
||||
|
||||
switch (group.distanceFieldMode)
|
||||
{
|
||||
case DistanceFieldMode.SimpleCenter:
|
||||
uvs = GenerateSimpleCenterUVs(vertices);
|
||||
break;
|
||||
|
||||
case DistanceFieldMode.MedialAxis:
|
||||
uvs = GenerateMedialAxisUVs(group, vertices, triangles);
|
||||
break;
|
||||
|
||||
case DistanceFieldMode.GridSampling:
|
||||
uvs = GenerateGridSamplingUVs(group, vertices, triangles);
|
||||
break;
|
||||
}
|
||||
|
||||
return uvs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 简单中心模式:计算质心并生成线性距离
|
||||
/// </summary>
|
||||
private Vector2[] GenerateSimpleCenterUVs(List<Vector2> vertices)
|
||||
{
|
||||
Vector2[] uvs = new Vector2[vertices.Count];
|
||||
|
||||
// 计算质心
|
||||
Vector2 centroid = CalculateCentroid(vertices);
|
||||
|
||||
// 计算最大距离(归一化用)
|
||||
float maxDistance = 0;
|
||||
foreach (var vertex in vertices)
|
||||
{
|
||||
float dist = Vector2.Distance(vertex, centroid);
|
||||
if (dist > maxDistance) maxDistance = dist;
|
||||
}
|
||||
|
||||
if (maxDistance < 0.001f) maxDistance = 1f;
|
||||
|
||||
// 生成UV:质心处为(0.5, 0.5),边界处根据距离变化
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
{
|
||||
float dist = Vector2.Distance(vertices[i], centroid);
|
||||
float normalizedDist = dist / maxDistance;
|
||||
|
||||
// UV的x分量表示距离(0-1),y分量可以用于其他用途
|
||||
uvs[i] = new Vector2(normalizedDist, 0.5f);
|
||||
}
|
||||
|
||||
return uvs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 中轴变换模式:计算多边形的中轴线
|
||||
/// </summary>
|
||||
private Vector2[] GenerateMedialAxisUVs(PatternGroup group, List<Vector2> vertices, List<int> triangles)
|
||||
{
|
||||
Vector2[] uvs = new Vector2[vertices.Count];
|
||||
|
||||
// 清空缓存
|
||||
group.cachedMedialAxisPoints.Clear();
|
||||
group.cachedDistances.Clear();
|
||||
|
||||
// 计算中轴线
|
||||
List<Vector2> medialAxis = ComputeMedialAxis(vertices);
|
||||
group.cachedMedialAxisPoints = medialAxis;
|
||||
|
||||
if (medialAxis.Count == 0)
|
||||
{
|
||||
// 如果中轴线计算失败,回退到简单中心模式
|
||||
return GenerateSimpleCenterUVs(vertices);
|
||||
}
|
||||
|
||||
// 计算每个顶点到最近的中轴线点的距离
|
||||
float maxDistance = 0;
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
{
|
||||
float minDist = float.MaxValue;
|
||||
|
||||
foreach (var axisPoint in medialAxis)
|
||||
{
|
||||
float dist = Vector2.Distance(vertices[i], axisPoint);
|
||||
if (dist < minDist) minDist = dist;
|
||||
}
|
||||
|
||||
group.cachedDistances.Add(minDist);
|
||||
if (minDist > maxDistance) maxDistance = minDist;
|
||||
}
|
||||
|
||||
if (maxDistance < 0.001f) maxDistance = 1f;
|
||||
|
||||
// 生成UV
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
{
|
||||
float normalizedDist = group.cachedDistances[i] / maxDistance;
|
||||
uvs[i] = new Vector2(normalizedDist, 0.5f);
|
||||
}
|
||||
|
||||
return uvs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算多边形的中轴线(简化版)
|
||||
/// 实际应用中可以使用更复杂的算法如Voronoi图或直线骨架算法
|
||||
/// </summary>
|
||||
private List<Vector2> ComputeMedialAxis(List<Vector2> vertices)
|
||||
{
|
||||
List<Vector2> medialAxis = new List<Vector2>();
|
||||
|
||||
// 方法1:使用Voronoi图的简化版本
|
||||
// 对于每条边,计算其法线方向上的点
|
||||
|
||||
int n = vertices.Count;
|
||||
|
||||
// 添加质心作为起点
|
||||
Vector2 centroid = CalculateCentroid(vertices);
|
||||
medialAxis.Add(centroid);
|
||||
|
||||
// 对于每条边,计算中垂线与相邻边中垂线的交点
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int prev = (i - 1 + n) % n;
|
||||
int curr = i;
|
||||
int next = (i + 1) % n;
|
||||
|
||||
// 计算三条边的中垂线
|
||||
Vector2 edge1Mid = (vertices[prev] + vertices[curr]) * 0.5f;
|
||||
Vector2 edge1Dir = vertices[curr] - vertices[prev];
|
||||
Vector2 edge1Normal = new Vector2(-edge1Dir.y, edge1Dir.x).normalized;
|
||||
|
||||
Vector2 edge2Mid = (vertices[curr] + vertices[next]) * 0.5f;
|
||||
Vector2 edge2Dir = vertices[next] - vertices[curr];
|
||||
Vector2 edge2Normal = new Vector2(-edge2Dir.y, edge2Dir.x).normalized;
|
||||
|
||||
// 计算两条中垂线的交点
|
||||
Vector2 intersection;
|
||||
if (LineLineIntersection(edge1Mid, edge1Normal, edge2Mid, edge2Normal, out intersection))
|
||||
{
|
||||
// 检查交点是否在多边形内部
|
||||
if (PointInPolygon(intersection, vertices))
|
||||
{
|
||||
medialAxis.Add(intersection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 去重
|
||||
medialAxis = RemoveDuplicatePoints(medialAxis, 0.1f);
|
||||
|
||||
return medialAxis;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 网格采样模式:在网格上采样距离场(最精确)
|
||||
/// </summary>
|
||||
private Vector2[] GenerateGridSamplingUVs(PatternGroup group, List<Vector2> vertices, List<int> triangles)
|
||||
{
|
||||
Vector2[] uvs = new Vector2[vertices.Count];
|
||||
|
||||
// 计算包围盒
|
||||
Vector2 min = vertices[0];
|
||||
Vector2 max = vertices[0];
|
||||
foreach (var v in vertices)
|
||||
{
|
||||
min = Vector2.Min(min, v);
|
||||
max = Vector2.Max(max, v);
|
||||
}
|
||||
|
||||
float width = max.x - min.x;
|
||||
float height = max.y - min.y;
|
||||
|
||||
// 创建距离场纹理
|
||||
if (group.distanceFieldTexture == null ||
|
||||
group.distanceFieldTexture.width != group.distanceFieldResolution)
|
||||
{
|
||||
group.distanceFieldTexture = new Texture2D(
|
||||
group.distanceFieldResolution,
|
||||
group.distanceFieldResolution,
|
||||
TextureFormat.R8, false);
|
||||
group.distanceFieldTexture.filterMode = FilterMode.Bilinear;
|
||||
}
|
||||
|
||||
Color32[] pixels = new Color32[group.distanceFieldResolution * group.distanceFieldResolution];
|
||||
|
||||
// 对每个像素采样
|
||||
for (int y = 0; y < group.distanceFieldResolution; y++)
|
||||
{
|
||||
for (int x = 0; x < group.distanceFieldResolution; x++)
|
||||
{
|
||||
// 计算世界坐标
|
||||
float worldX = min.x + (x / (float)(group.distanceFieldResolution - 1)) * width;
|
||||
float worldY = min.y + (y / (float)(group.distanceFieldResolution - 1)) * height;
|
||||
Vector2 worldPos = new Vector2(worldX, worldY);
|
||||
|
||||
// 计算到边界的最小距离
|
||||
float minDistance = float.MaxValue;
|
||||
|
||||
// 检查是否在多边形内部
|
||||
bool inside = PointInPolygon(worldPos, vertices);
|
||||
|
||||
// 计算到每条边的距离
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
{
|
||||
int next = (i + 1) % vertices.Count;
|
||||
float dist = DistancePointToSegment(worldPos, vertices[i], vertices[next]);
|
||||
|
||||
if (dist < minDistance)
|
||||
minDistance = dist;
|
||||
}
|
||||
|
||||
// 归一化距离
|
||||
float normalizedDist = Mathf.Clamp01(minDistance / Mathf.Max(width, height));
|
||||
|
||||
// 如果在外部,距离为负
|
||||
if (!inside)
|
||||
normalizedDist = -normalizedDist;
|
||||
|
||||
// 存储到纹理
|
||||
int pixelIndex = y * group.distanceFieldResolution + x;
|
||||
byte distByte = (byte)(Mathf.Clamp01(Mathf.Abs(normalizedDist)) * 255);
|
||||
pixels[pixelIndex] = new Color32(distByte, distByte, distByte, 255);
|
||||
|
||||
// 为顶点生成UV
|
||||
if (visualizeDistanceField)
|
||||
{
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
{
|
||||
if (Vector2.Distance(vertices[i], worldPos) < 1f)
|
||||
{
|
||||
uvs[i] = new Vector2(x / (float)group.distanceFieldResolution,
|
||||
y / (float)group.distanceFieldResolution);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
group.distanceFieldTexture.SetPixels32(pixels);
|
||||
group.distanceFieldTexture.Apply();
|
||||
|
||||
// 如果不显示可视化,使用简单模式的UV
|
||||
if (!visualizeDistanceField)
|
||||
{
|
||||
return GenerateSimpleCenterUVs(vertices);
|
||||
}
|
||||
|
||||
return uvs;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算多边形的质心
|
||||
/// </summary>
|
||||
private Vector2 CalculateCentroid(List<Vector2> vertices)
|
||||
{
|
||||
float signedArea = 0;
|
||||
float centerX = 0;
|
||||
float centerY = 0;
|
||||
|
||||
int n = vertices.Count;
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
int next = (i + 1) % n;
|
||||
float temp = vertices[i].x * vertices[next].y - vertices[next].x * vertices[i].y;
|
||||
signedArea += temp;
|
||||
centerX += (vertices[i].x + vertices[next].x) * temp;
|
||||
centerY += (vertices[i].y + vertices[next].y) * temp;
|
||||
}
|
||||
|
||||
signedArea *= 0.5f;
|
||||
|
||||
if (Mathf.Abs(signedArea) < 0.001f)
|
||||
return vertices.Count > 0 ? vertices[0] : Vector2.zero;
|
||||
|
||||
centerX /= (6 * signedArea);
|
||||
centerY /= (6 * signedArea);
|
||||
|
||||
return new Vector2(centerX, centerY);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 检查点是否在多边形内部
|
||||
/// </summary>
|
||||
private bool PointInPolygon(Vector2 point, List<Vector2> vertices)
|
||||
{
|
||||
int n = vertices.Count;
|
||||
bool inside = false;
|
||||
|
||||
for (int i = 0, j = n - 1; i < n; j = i++)
|
||||
{
|
||||
if (((vertices[i].y > point.y) != (vertices[j].y > point.y)) &&
|
||||
(point.x < (vertices[j].x - vertices[i].x) * (point.y - vertices[i].y) /
|
||||
(vertices[j].y - vertices[i].y) + vertices[i].x))
|
||||
{
|
||||
inside = !inside;
|
||||
}
|
||||
}
|
||||
|
||||
return inside;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算点到线段的最短距离
|
||||
/// </summary>
|
||||
private float DistancePointToSegment(Vector2 point, Vector2 a, Vector2 b)
|
||||
{
|
||||
Vector2 ab = b - a;
|
||||
Vector2 ap = point - a;
|
||||
|
||||
float dot = Vector2.Dot(ap, ab);
|
||||
float lenSq = ab.sqrMagnitude;
|
||||
|
||||
float t = dot / lenSq;
|
||||
t = Mathf.Clamp01(t);
|
||||
|
||||
Vector2 projection = a + t * ab;
|
||||
return Vector2.Distance(point, projection);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算两条直线的交点
|
||||
/// </summary>
|
||||
private bool LineLineIntersection(Vector2 p1, Vector2 d1, Vector2 p2, Vector2 d2, out Vector2 intersection)
|
||||
{
|
||||
intersection = Vector2.zero;
|
||||
|
||||
float det = d1.x * d2.y - d1.y * d2.x;
|
||||
if (Mathf.Abs(det) < 0.001f)
|
||||
return false;
|
||||
|
||||
Vector2 diff = p2 - p1;
|
||||
float t = (diff.x * d2.y - diff.y * d2.x) / det;
|
||||
|
||||
intersection = p1 + t * d1;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 去除重复点
|
||||
/// </summary>
|
||||
private List<Vector2> RemoveDuplicatePoints(List<Vector2> points, float threshold)
|
||||
{
|
||||
List<Vector2> result = new List<Vector2>();
|
||||
|
||||
foreach (var p in points)
|
||||
{
|
||||
bool isDuplicate = false;
|
||||
|
||||
foreach (var r in result)
|
||||
{
|
||||
if (Vector2.Distance(p, r) < threshold)
|
||||
{
|
||||
isDuplicate = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isDuplicate)
|
||||
result.Add(p);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ========== 以下是原有代码的简化版本 ==========
|
||||
|
||||
/// <summary>
|
||||
/// 生成缓存键(基于顶点索引列表)
|
||||
/// </summary>
|
||||
private int GetCacheKey(List<int> indices)
|
||||
{
|
||||
int hash = 17;
|
||||
foreach (int index in indices)
|
||||
{
|
||||
hash = hash * 31 + index;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 耳切法三角剖分(简化版)
|
||||
/// </summary>
|
||||
private List<int> TriangulatePolygon(List<Vector2> polygonVertices)
|
||||
{
|
||||
// 这里使用简化版本,实际应用中可以使用更复杂的三角剖分算法
|
||||
List<int> triangles = new List<int>();
|
||||
|
||||
if (polygonVertices.Count < 3)
|
||||
return triangles;
|
||||
|
||||
// 简单的扇形三角剖分(仅适用于凸多边形)
|
||||
for (int i = 1; i < polygonVertices.Count - 1; i++)
|
||||
{
|
||||
triangles.Add(0);
|
||||
triangles.Add(i);
|
||||
triangles.Add(i + 1);
|
||||
}
|
||||
|
||||
return triangles;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加填充多边形
|
||||
/// </summary>
|
||||
private void AddFilledPolygon(VertexHelper vh, List<Vector2> vertices, List<int> triangles, Vector2[] uvs, Color32 color)
|
||||
{
|
||||
int vertexStartIndex = vh.currentVertCount;
|
||||
|
||||
// 添加顶点
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
{
|
||||
Vector2 uv = uvs != null && i < uvs.Length ? uvs[i] : Vector2.zero;
|
||||
vh.AddVert(vertices[i], color, uv);
|
||||
}
|
||||
|
||||
// 添加三角形索引
|
||||
for (int i = 0; i < triangles.Count; i += 3)
|
||||
{
|
||||
vh.AddTriangle(
|
||||
vertexStartIndex + triangles[i],
|
||||
vertexStartIndex + triangles[i + 1],
|
||||
vertexStartIndex + triangles[i + 2]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加描边
|
||||
/// </summary>
|
||||
private void AddStroke(VertexHelper vh, List<Vector2> vertices, float width, Color32 color)
|
||||
{
|
||||
if (vertices.Count < 2)
|
||||
return;
|
||||
|
||||
float halfWidth = width * 0.5f;
|
||||
|
||||
// 为每条边生成两个三角形(形成矩形)
|
||||
for (int i = 0; i < vertices.Count; i++)
|
||||
{
|
||||
int next = (i + 1) % vertices.Count;
|
||||
|
||||
Vector2 p1 = vertices[i];
|
||||
Vector2 p2 = vertices[next];
|
||||
|
||||
// 计算边的法线
|
||||
Vector2 edge = p2 - p1;
|
||||
Vector2 normal = new Vector2(-edge.y, edge.x).normalized;
|
||||
|
||||
// 生成四个顶点(矩形)
|
||||
Vector2 v1 = p1 + normal * halfWidth;
|
||||
Vector2 v2 = p1 - normal * halfWidth;
|
||||
Vector2 v3 = p2 - normal * halfWidth;
|
||||
Vector2 v4 = p2 + normal * halfWidth;
|
||||
|
||||
int startIndex = vh.currentVertCount;
|
||||
|
||||
vh.AddVert(v1, color, Vector2.zero);
|
||||
vh.AddVert(v2, color, Vector2.zero);
|
||||
vh.AddVert(v3, color, Vector2.zero);
|
||||
vh.AddVert(v4, color, Vector2.zero);
|
||||
|
||||
// 两个三角形
|
||||
vh.AddTriangle(startIndex, startIndex + 1, startIndex + 2);
|
||||
vh.AddTriangle(startIndex, startIndex + 2, startIndex + 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加中轴线可视化
|
||||
/// </summary>
|
||||
private void AddMedialAxis(VertexHelper vh, List<Vector2> points, Color32 color)
|
||||
{
|
||||
if (points.Count < 2)
|
||||
return;
|
||||
|
||||
// 绘制线段
|
||||
for (int i = 0; i < points.Count - 1; i++)
|
||||
{
|
||||
Vector2 p1 = points[i];
|
||||
Vector2 p2 = points[i + 1];
|
||||
|
||||
float lineWidth = 3f;
|
||||
Vector2 edge = p2 - p1;
|
||||
Vector2 normal = new Vector2(-edge.y, edge.x).normalized;
|
||||
|
||||
Vector2 v1 = p1 + normal * lineWidth * 0.5f;
|
||||
Vector2 v2 = p1 - normal * lineWidth * 0.5f;
|
||||
Vector2 v3 = p2 - normal * lineWidth * 0.5f;
|
||||
Vector2 v4 = p2 + normal * lineWidth * 0.5f;
|
||||
|
||||
int startIndex = vh.currentVertCount;
|
||||
|
||||
vh.AddVert(v1, color, Vector2.zero);
|
||||
vh.AddVert(v2, color, Vector2.zero);
|
||||
vh.AddVert(v3, color, Vector2.zero);
|
||||
vh.AddVert(v4, color, Vector2.zero);
|
||||
|
||||
vh.AddTriangle(startIndex, startIndex + 1, startIndex + 2);
|
||||
vh.AddTriangle(startIndex, startIndex + 2, startIndex + 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加顶点标记(小圆圈)
|
||||
/// </summary>
|
||||
private void AddVertexMarkers(VertexHelper vh)
|
||||
{
|
||||
int segments = 8;
|
||||
|
||||
foreach (var vertex in vertices)
|
||||
{
|
||||
List<Vector2> circleVertices = new List<Vector2>();
|
||||
List<int> circleTriangles = new List<int>();
|
||||
|
||||
circleVertices.Add(vertex);
|
||||
|
||||
for (int i = 0; i <= segments; i++)
|
||||
{
|
||||
float angle = (i / (float)segments) * 2 * Mathf.PI;
|
||||
Vector2 point = vertex + new Vector2(
|
||||
Mathf.Cos(angle) * vertexMarkerSize,
|
||||
Mathf.Sin(angle) * vertexMarkerSize
|
||||
);
|
||||
circleVertices.Add(point);
|
||||
}
|
||||
|
||||
for (int i = 1; i <= segments; i++)
|
||||
{
|
||||
circleTriangles.Add(0);
|
||||
circleTriangles.Add(i);
|
||||
circleTriangles.Add(i + 1);
|
||||
}
|
||||
|
||||
int startIndex = vh.currentVertCount;
|
||||
foreach (var v in circleVertices)
|
||||
{
|
||||
vh.AddVert(v, vertexMarkerColor, Vector2.zero);
|
||||
}
|
||||
|
||||
for (int i = 0; i < circleTriangles.Count; i += 3)
|
||||
{
|
||||
vh.AddTriangle(
|
||||
startIndex + circleTriangles[i],
|
||||
startIndex + circleTriangles[i + 1],
|
||||
startIndex + circleTriangles[i + 2]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 标记为需要重新生成网格
|
||||
/// </summary>
|
||||
public void SetVerticesDirty()
|
||||
{
|
||||
isDirty = true;
|
||||
SetAllDirty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置顶点列表
|
||||
/// </summary>
|
||||
public void SetVertices(List<Vector2> newVertices)
|
||||
{
|
||||
vertices = newVertices ?? new List<Vector2>();
|
||||
SetVerticesDirty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置图形分组
|
||||
/// </summary>
|
||||
public void SetPatternGroups(List<PatternGroup> newGroups)
|
||||
{
|
||||
patternGroups = newGroups ?? new List<PatternGroup>();
|
||||
SetVerticesDirty();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加一个新的图形分组
|
||||
/// </summary>
|
||||
public void AddPatternGroup(List<int> vertexIndices, Color fillColor, Color strokeColor, float strokeWidth = 2f)
|
||||
{
|
||||
PatternGroup group = new PatternGroup
|
||||
{
|
||||
vertexIndices = vertexIndices,
|
||||
fillColor = fillColor,
|
||||
strokeColor = strokeColor,
|
||||
strokeWidth = strokeWidth,
|
||||
fillEnabled = true,
|
||||
strokeEnabled = true,
|
||||
distanceFieldMode = DistanceFieldMode.SimpleCenter
|
||||
};
|
||||
|
||||
if (patternGroups == null)
|
||||
patternGroups = new List<PatternGroup>();
|
||||
|
||||
patternGroups.Add(group);
|
||||
SetVerticesDirty();
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
protected override void OnValidate()
|
||||
{
|
||||
base.OnValidate();
|
||||
isDirty = true;
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e0096bca1b7b40bf90e0aa7ebbda48f0
|
||||
timeCreated: 1775548842
|
||||
@@ -3,15 +3,17 @@ using UnityEngine;
|
||||
using UnityEngine.Serialization;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace XericLibrary
|
||||
namespace XericLibrary.Runtime.Renderer
|
||||
{
|
||||
/// <summary>
|
||||
/// UI上线条绘制组件
|
||||
/// 支持设置线条厚度、居中显示,并为线段之间添加斜角边缘
|
||||
/// 继承自 MaskableGraphic,可与 UI 遮罩系统配合使用
|
||||
/// </summary>
|
||||
[AddComponentMenu("Xeric Library/UI/UILineRenderer", 15)]
|
||||
public class UILineRenderer : XericRendererComponent
|
||||
{
|
||||
// todo 根据优弧劣弧绘制线段,这么说可能不太准确,但我需要在90度以内绘制漂亮的转角,大于90度则用中心圆代替
|
||||
#region 字段属性
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -10,21 +10,24 @@ using XericLibrary.Runtime.MacroLibrary;
|
||||
#if ODIN_INSPECTOR
|
||||
using Sirenix.OdinInspector;
|
||||
#endif
|
||||
namespace XericLibrary
|
||||
namespace XericLibrary.Runtime.Renderer
|
||||
{
|
||||
/// <summary>
|
||||
/// UI多边形图形图案渲染组件(三角形,菱形,五边形...三十二边形)
|
||||
/// 支持倒角
|
||||
/// </summary>
|
||||
[AddComponentMenu("Xeric Library/UI/UIPatternRenderer", 15)]
|
||||
public class UIPatternRenderer : XericRendererComponent
|
||||
{
|
||||
#region 字段属性
|
||||
|
||||
public override string ShaderName => "XericLibrary/UILine/UIPattern";
|
||||
|
||||
[Header("多边形设置"), Range(3, 32)] public int sides = 6;
|
||||
|
||||
[SerializeField, Tooltip("多边形的大小 (相对于矩形区域的比例 0-1)")]
|
||||
#if ODIN_INSPECTOR
|
||||
[ProgressBar("Scalemin", "GetMaxScale")]
|
||||
[PropertyRange("ScaleMin", "GetMaxScale")]
|
||||
#else
|
||||
[Range(0f, 1f)]
|
||||
#endif
|
||||
@@ -42,13 +45,14 @@ namespace XericLibrary
|
||||
private float borderThickness = .1f;
|
||||
|
||||
[SerializeField, Tooltip("边框颜色")] private Color borderColor = Color.white;
|
||||
[SerializeField, Tooltip("边框颜色渐变")] private Color borderColor2 = Color.white;
|
||||
[SerializeField, Tooltip("填充颜色")] private Color fillColor = Color.gray;
|
||||
|
||||
/// <summary>
|
||||
/// 获取最大缩放(一个参考值)
|
||||
/// </summary>
|
||||
public float GetMaxScale => 1 / Mathf.Cos(GetSideRadius);
|
||||
private float Scalemin => 0.01f;
|
||||
private float ScaleMin => 0.01f;
|
||||
/// <summary>
|
||||
/// 获取多边形的旋转弧度
|
||||
/// </summary>
|
||||
@@ -62,6 +66,7 @@ namespace XericLibrary
|
||||
};
|
||||
|
||||
private static readonly int BorderColor1 = Shader.PropertyToID("_BorderColor");
|
||||
private static readonly int BorderColor2 = Shader.PropertyToID("_BorderColor2");
|
||||
private static readonly int FillColor1 = Shader.PropertyToID("_FillColor");
|
||||
private static readonly int Thinkness = Shader.PropertyToID("_Thinkness");
|
||||
|
||||
@@ -90,6 +95,18 @@ namespace XericLibrary
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 边框颜色渐变
|
||||
/// </summary>
|
||||
public Color BorderColorLinear
|
||||
{
|
||||
get => borderColor2;
|
||||
set
|
||||
{
|
||||
borderColor2 = value;
|
||||
m_Material.SetColor(BorderColor2, borderColor2);
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 填充颜色
|
||||
/// </summary>
|
||||
public Color FillColor
|
||||
@@ -101,6 +118,7 @@ namespace XericLibrary
|
||||
m_Material.SetColor(FillColor1, fillColor);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置缩放
|
||||
/// </summary>
|
||||
@@ -110,17 +128,20 @@ namespace XericLibrary
|
||||
// 缓存顶点列表以避免每帧分配内存
|
||||
private readonly List<Vector3> verticesCache = new List<Vector3>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region 类内类型
|
||||
|
||||
public enum AngleSelectMode
|
||||
{
|
||||
Angle,
|
||||
Multiples,
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected override void OnPopulateMesh(VertexHelper vh)
|
||||
protected override void OnPopulatePrefabricateVertex(List<UIVertex> vertexList, List<int> indexList)
|
||||
{
|
||||
if (vh == null) return;
|
||||
vh.Clear();
|
||||
|
||||
// 获取绘图区域的中心点和尺寸
|
||||
Rect rect = GetPixelAdjustedRect();
|
||||
Vector2 center = rect.center;
|
||||
@@ -154,12 +175,13 @@ namespace XericLibrary
|
||||
// 此渲染组件的颜色和中心uv
|
||||
Color32 color32 = this.color;
|
||||
Vector2 uvCenter = new Vector4(0.5f, 0.5f, 0, 0);
|
||||
|
||||
// 没有倒角,使用常规流程
|
||||
if (currentRounding <= 0f)
|
||||
{
|
||||
verticesCache.AddRange(OriginPatternVectorPoints(sides, radius, sideAngle, center));
|
||||
// 添加中心点
|
||||
vh.AddVert(center, color32, uvCenter, uvCenter, uvCenter, Vector4.zero);
|
||||
vertexList.AddVert(center, uvCenter, color32);
|
||||
|
||||
float angleStep = 360f / sides;
|
||||
// 添加外围点
|
||||
@@ -170,24 +192,23 @@ namespace XericLibrary
|
||||
XericRendererUtils.GetUVAtRect(verticesCache[i], rect, out var u, out var v);
|
||||
GetNormalizedAngleByPos(angleStep, i, out var normalizedAngle);
|
||||
var uv = new Vector4(u, v, 1, normalizedAngle);
|
||||
vh.AddVert(verticesCache[i], color32, uv, uv, uv, Vector4.zero);
|
||||
vertexList.AddVert(verticesCache[i], uv, color32);
|
||||
}
|
||||
|
||||
// 三角形顺序:中心点, 当前外点, 下一个外点
|
||||
for (int i = 1; i < sides; i++)
|
||||
vh.AddTriangle(0, i, i + 1);
|
||||
indexList.AddTriangle(0, i, i + 1);
|
||||
// 连接最后一个点和第一个点以闭合形状
|
||||
vh.AddTriangle(0, sides, 1);
|
||||
indexList.AddTriangle(0, sides, 1);
|
||||
}
|
||||
// 启用倒角
|
||||
else
|
||||
{
|
||||
verticesCache.AddRange(OriginPatternVectorPoints(sides, radius, sideAngle, center));
|
||||
// 添加中心点
|
||||
vh.AddVert(center, color32, uvCenter, uvCenter, uvCenter, Vector4.zero);
|
||||
vertexList.AddVert(center, uvCenter, color32);
|
||||
var maxVpCount = sides * roundingTime + 1;
|
||||
var l = 2 * radius * Mathf.Sin(Mathf.PI / sides);
|
||||
var lastPos = center;
|
||||
for (var i = 0; i < sides; i++)
|
||||
{
|
||||
Vector2 pCurr = verticesCache[i];
|
||||
@@ -226,19 +247,18 @@ namespace XericLibrary
|
||||
MacroCurve.BezierCurve3(p0, p1, p2, p3, jTime, out var pos);
|
||||
pos.GetUVAtRect(rect, out var u, out var v);
|
||||
var uv = new Vector4(u, v, 1, 1);
|
||||
vh.AddVert(pos, this.color, uv, uv, uv, Vector4.zero);
|
||||
vertexList.AddVert(pos, uv, this.color);
|
||||
var index = roundingTime * i + j + 1;
|
||||
var next = index + 1;
|
||||
if (next >= maxVpCount)
|
||||
next = (next % maxVpCount) + 1;
|
||||
vh.AddTriangle(0, index, next);
|
||||
Debug.Log($"{jTime}|{pos}");
|
||||
lastPos = pos;
|
||||
indexList.AddTriangle(0, index, next);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 图元基础外围图形顶点
|
||||
/// </summary>
|
||||
@@ -286,9 +306,9 @@ namespace XericLibrary
|
||||
if (sides < 3) sides = 3;
|
||||
if (scale <= float.Epsilon) scale = float.Epsilon;
|
||||
SetVerticesDirty();
|
||||
|
||||
BorderThickness = borderThickness;
|
||||
BorderColor = borderColor;
|
||||
BorderColorLinear = borderColor2;
|
||||
FillColor = fillColor;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,7 +4,7 @@ using UnityEngine;
|
||||
using UnityEngine.Pool;
|
||||
using UnityEngine.UI;
|
||||
|
||||
namespace XericLibrary
|
||||
namespace XericLibrary.Runtime.Renderer
|
||||
{
|
||||
/// <summary>
|
||||
/// 自定义渲染组件
|
||||
@@ -20,13 +20,13 @@ namespace XericLibrary
|
||||
private readonly List<UIVertex> _vertexList = new List<UIVertex>();
|
||||
private readonly List<int> _indexList = new List<int>();
|
||||
// 阵列原点
|
||||
private readonly List<Vector4> _arrayTransformList = new List<Vector4>();
|
||||
private List<Vector4> _arrayTransformList = new List<Vector4>();
|
||||
// 中间数据
|
||||
private List<UIVertex> _temp_vertexList = new List<UIVertex>();
|
||||
private List<int> _temp_indexList = new List<int>();
|
||||
|
||||
private bool _dirty;
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#if UNITY_EDITOR
|
||||
@@ -54,6 +54,8 @@ namespace XericLibrary
|
||||
/// <param name="vh"></param>
|
||||
protected override void OnPopulateMesh(VertexHelper vh)
|
||||
{
|
||||
if (vh == null) return;
|
||||
vh.Clear();
|
||||
ClearCache();
|
||||
// 填充图元
|
||||
OnPopulatePrefabricateVertex(_vertexList, _indexList);
|
||||
@@ -80,7 +82,6 @@ namespace XericLibrary
|
||||
{
|
||||
_vertexList.Clear();
|
||||
_indexList.Clear();
|
||||
_arrayTransformList.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -88,9 +89,30 @@ namespace XericLibrary
|
||||
/// </summary>
|
||||
/// <param name="offset">偏移</param>
|
||||
/// <param name="angle">角度</param>
|
||||
protected void AddArrayModifier(Vector3 offset, float angle)
|
||||
public int AddArrayModifier(Vector3 offset, float angle)
|
||||
{
|
||||
var index = _arrayTransformList.Count;
|
||||
_arrayTransformList.Add(new Vector4(offset.x, offset.y, offset.z, angle));
|
||||
Refresh();
|
||||
return index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清空阵列节点
|
||||
/// </summary>
|
||||
public void ClearArrayModifier()
|
||||
{
|
||||
_arrayTransformList.Clear();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public bool ModifyArrayModifier(int index, Vector3 offset, float angle)
|
||||
{
|
||||
if (index < 0 || index >= _arrayTransformList.Count)
|
||||
return false;
|
||||
_arrayTransformList[index] = new Vector4(offset.x, offset.y, offset.z, angle);
|
||||
Refresh();
|
||||
return true;
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -104,27 +126,31 @@ namespace XericLibrary
|
||||
/// <param name="trans"></param>
|
||||
protected void ArrayVertexList(List<Vector4> trans)
|
||||
{
|
||||
_temp_vertexList.Clear();
|
||||
_temp_indexList.Clear();
|
||||
|
||||
if (trans == null || trans.Count == 0)
|
||||
{
|
||||
Copy();
|
||||
return;
|
||||
}
|
||||
foreach (var t in trans)
|
||||
Copy2(t);
|
||||
|
||||
for (int i = 0; i < trans.Count; i++)
|
||||
Copy2(i, trans[i]);
|
||||
|
||||
void Copy()
|
||||
{
|
||||
_temp_vertexList = _vertexList.GetRange(0, _vertexList.Count);
|
||||
_temp_indexList = _indexList.GetRange(0, _indexList.Count);
|
||||
_temp_vertexList.AddRange(_vertexList.GetRange(0, _vertexList.Count));
|
||||
_temp_indexList.AddRange(_indexList.GetRange(0, _indexList.Count));
|
||||
}
|
||||
void Copy2(Vector4 transform)
|
||||
void Copy2(int index, Vector4 transform)
|
||||
{
|
||||
_temp_vertexList = _vertexList.Select(a =>
|
||||
_temp_vertexList.AddRange(_vertexList.Select(a =>
|
||||
{
|
||||
var newPos = new Vector3(a.position.x, a.position.y, a.position.z);
|
||||
if (a.position.z != 0)
|
||||
var newPos = a.position;
|
||||
if (transform.w != 0)
|
||||
{
|
||||
var rot = Quaternion.Euler(0, 0, a.position.z);
|
||||
var rot = Quaternion.Euler(0, 0, transform.w);
|
||||
newPos = rot * newPos;
|
||||
}
|
||||
newPos += (Vector3)transform;
|
||||
@@ -139,8 +165,8 @@ namespace XericLibrary
|
||||
uv2 = a.uv2,
|
||||
uv3 = a.uv3,
|
||||
};
|
||||
}).ToList();
|
||||
_temp_indexList = _indexList.GetRange(0, _indexList.Count);
|
||||
}));
|
||||
_temp_indexList.AddRange(_indexList.Select(a => index * _vertexList.Count + a));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,518 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using MathNet.Numerics.Distributions;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Pool;
|
||||
using UnityEngine.UI;
|
||||
using XericLibrary.Runtime.MacroLibrary;
|
||||
|
||||
namespace XericLibrary
|
||||
{
|
||||
/// <summary>
|
||||
/// UILineRenderer 的工具类,提供静态方法用于线条渲染相关的操作
|
||||
/// </summary>
|
||||
internal static class XericRendererUtils
|
||||
{
|
||||
/// <summary>
|
||||
/// 计算线路的总长度
|
||||
/// </summary>
|
||||
/// <param name="points">线路的顶点数组</param>
|
||||
/// <param name="cycleLoop">线路是循环</param>
|
||||
/// <returns>线路的总长度</returns>
|
||||
public static float CalculateTotalLength(this Vector2[] points, bool cycleLoop = false)
|
||||
{
|
||||
if (points.Length < 2)
|
||||
return 0f;
|
||||
|
||||
var totalLength = 0f;
|
||||
for (int i = 0; i < points.Length - 1; i++)
|
||||
totalLength += Vector2.Distance(points[i], points[i + 1]);
|
||||
|
||||
if (cycleLoop)
|
||||
totalLength += Vector2.Distance(points[0], points[^1]);
|
||||
|
||||
return totalLength;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算一个点指向另一个点的角度(以度为单位)
|
||||
/// </summary>
|
||||
/// <param name="vertex">起始点</param>
|
||||
/// <param name="target">目标点</param>
|
||||
/// <returns>旋转角度,范围为 -180 到 180 度</returns>
|
||||
public static float RotatePointTowards(Vector2 vertex, Vector2 target)
|
||||
{
|
||||
// 使用反正切函数计算两点之间的角度
|
||||
// 将弧度转换为角度返回
|
||||
return (Mathf.Atan2(target.y - vertex.y, target.x - vertex.x) * Mathf.Rad2Deg);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 如果需要居中显示,则偏移到组件中心
|
||||
/// </summary>
|
||||
/// <param name="center">是否要居中显示</param>
|
||||
/// <param name="rectSize">整个绘制矩形范围的尺寸</param>
|
||||
/// <returns></returns>
|
||||
public static Vector2 SwitchCenterOffset(bool center, Vector2 rectSize) => center ? Vector2.zero : -(rectSize / 2);
|
||||
|
||||
/// <summary>
|
||||
/// 获取两个点之间的法线,副法线
|
||||
/// </summary>
|
||||
/// <param name="startPoint">起点</param>
|
||||
/// <param name="endPoint">终点</param>
|
||||
/// <param name="vector">起点到终点的矢量</param>
|
||||
/// <param name="distance">两点间距离</param>
|
||||
/// <param name="normal">起点到终点的法线</param>
|
||||
/// <param name="subTangent">垂直与起点到终点的法线(法线左转90)</param>
|
||||
/// <returns></returns>
|
||||
private static bool GetNormalizedVector(Vector2 startPoint, Vector2 endPoint,
|
||||
out Vector2 vector, out float distance, out Vector2 normal, out Vector2 subTangent)
|
||||
{
|
||||
vector = endPoint - startPoint;
|
||||
distance = vector.magnitude;
|
||||
normal = Vector2.zero;
|
||||
subTangent = Vector2.zero;
|
||||
|
||||
// 距离过小时不绘制
|
||||
if (distance <= float.Epsilon)
|
||||
return false;
|
||||
|
||||
// 线段的法线和副法线
|
||||
normal = vector / distance;
|
||||
subTangent = Vector2.Perpendicular(normal);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算起点和终点的UV坐标Y值
|
||||
/// </summary>
|
||||
/// <param name="startLength">这段线段的起始线路长度</param>
|
||||
/// <param name="currentLength">这段线段的长度</param>
|
||||
/// <param name="totalLength">总线路的长度</param>
|
||||
/// <param name="startUVY">起点处的uv y</param>
|
||||
/// <param name="endUVY">终点处的uv y</param>
|
||||
private static void GetCurrentLengthUVY(float startLength, float currentLength, float totalLength, out float startUVY, out float endUVY)
|
||||
{
|
||||
startUVY = totalLength > 0 ? startLength / totalLength : 0f;
|
||||
endUVY = totalLength > 0 ? (startLength + currentLength) / totalLength : 0f;
|
||||
}
|
||||
|
||||
#region 简易线路绘制
|
||||
|
||||
// 在点与点之间绘制给定宽度(thickness)的方片,转角处用两个三角形链接
|
||||
// 这样会造成一根线会出现5个顶点,所以叫做 DSL5 (直接简单的5点直线 directly simple line 5)
|
||||
|
||||
/// <summary>
|
||||
/// 创建线段的顶点数据
|
||||
/// 每个线段由 5 个顶点组成:
|
||||
/// - 起点的左右两个顶点
|
||||
/// - 终点的左右两个顶点
|
||||
/// - 终点的中心点(用于线段连接)
|
||||
/// </summary>
|
||||
/// <param name="vertices">顶点容器</param>
|
||||
/// <param name="startPoint">线段的起点</param>
|
||||
/// <param name="distance">线段的距离</param>
|
||||
/// <param name="endPoint">线段的终点</param>
|
||||
/// <param name="thickness">线条的厚度</param>
|
||||
/// <param name="color">线条的颜色</param>
|
||||
/// <param name="startLength">当前线段起点在线路中的累积长度</param>
|
||||
/// <param name="totalLength">线路的总长度</param>
|
||||
public static List<UIVertex> GetSingleLineSegmentVerts_DSL5(List<UIVertex> vertices, Vector2 startPoint, Vector2 endPoint,
|
||||
float thickness, Color color, float startLength, out float distance, float totalLength, Vector3 offset)
|
||||
{
|
||||
if (vertices == null)
|
||||
throw new Exception("没有指定线段片段顶点容器列表");
|
||||
vertices.Clear();
|
||||
// 创建顶点模板,设置颜色为组件的当前颜色
|
||||
UIVertex vertex = UIVertex.simpleVert;
|
||||
vertex.color = color;
|
||||
|
||||
if (!GetNormalizedVector(startPoint, endPoint,
|
||||
out var vector, out distance, out var normal, out var subTangent))
|
||||
return vertices;
|
||||
|
||||
// 线段单侧宽度
|
||||
var width = thickness / 2;
|
||||
|
||||
GetCurrentLengthUVY(startLength, distance, totalLength, out var startUVY, out var endUVY);
|
||||
|
||||
vertex.position = (startPoint +
|
||||
subTangent * width);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(0f, startUVY); // 左侧顶点的UV
|
||||
vertices.Add(vertex);
|
||||
|
||||
vertex.position = (startPoint +
|
||||
subTangent * -width);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(1f, startUVY); // 右侧顶点的UV
|
||||
vertices.Add(vertex);
|
||||
|
||||
vertex.position = (endPoint +
|
||||
subTangent * width);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(0f, endUVY); // 左侧顶点的UV
|
||||
vertices.Add(vertex);
|
||||
|
||||
vertex.position = (endPoint +
|
||||
subTangent * -width);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(1f, endUVY); // 右侧顶点的UV
|
||||
vertices.Add(vertex);
|
||||
|
||||
// 添加终点的中心点,用于连接后续线段
|
||||
vertex.position = endPoint;
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(0.5f, endUVY); // 中心点的UV
|
||||
vertices.Add(vertex);
|
||||
return vertices;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在网格构建对象上添加这个直线片段
|
||||
/// </summary>
|
||||
/// <param name="vh">构建网格对象</param>
|
||||
/// <param name="segmentPartIndex">该线路片段索引(比如第一段线应该是0)</param>
|
||||
/// <param name="verts">该片段顶点</param>
|
||||
public static void AddSingleLineSegmentVertsAndTriangle_DSL5(this VertexHelper vh, int segmentPartIndex, IEnumerable<UIVertex> verts)
|
||||
{
|
||||
foreach (var vert in verts)
|
||||
vh.AddVert(vert);
|
||||
int index = segmentPartIndex * 5;
|
||||
|
||||
// 添加线段的两个三角形(构成矩形线段)
|
||||
vh.AddTriangle(index, index+1, index+3);
|
||||
vh.AddTriangle(index+3, index+2, index);
|
||||
|
||||
// 为线段之间添加斜角边缘
|
||||
// 使用上一个线段的终点和当前线段的起点创建过渡三角形
|
||||
if (segmentPartIndex != 0)
|
||||
{
|
||||
vh.AddTriangle(index, index-1, index-3);
|
||||
vh.AddTriangle(index+1, index-1, index-2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推送顶点绘制线路
|
||||
/// </summary>
|
||||
/// <param name="vh"></param>
|
||||
/// <param name="points"></param>
|
||||
/// <param name="thickness"></param>
|
||||
/// <param name="cycleLoop"></param>
|
||||
/// <param name="color"></param>
|
||||
/// <param name="offset"></param>
|
||||
public static void PopulateLineByPointsArray_DSL5(this VertexHelper vh, Vector2[] points, float thickness, bool cycleLoop, Color color, Vector3 offset)
|
||||
{
|
||||
// 至少需要 2 个点才能绘制线条
|
||||
if (points.Length < 2)
|
||||
return;
|
||||
|
||||
// 计算线路总长度
|
||||
var totalLength = points.CalculateTotalLength(cycleLoop);
|
||||
var currentLength = 0f;
|
||||
var vertices = ListPool<UIVertex>.Get();
|
||||
for (int i = 0; i < points.Length - (cycleLoop ? 0 : 1); i++)
|
||||
{
|
||||
vh.AddSingleLineSegmentVertsAndTriangle_DSL5(i,
|
||||
GetSingleLineSegmentVerts_DSL5(vertices, points[i], points[(i + 1) % points.Length], thickness, color, currentLength, out var distance, totalLength, offset));
|
||||
currentLength += distance;
|
||||
}
|
||||
ListPool<UIVertex>.Release(vertices);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 圆弧过度的线路绘制
|
||||
|
||||
// 在简易线路绘制的基础上,修改了转角处的处理
|
||||
// 线的顶点还是5,但是转角圆弧处理会更细节,叫它 CFAL (中心对齐的圆弧转角直线,center fanshaped arc Line)
|
||||
|
||||
/// <summary>
|
||||
/// 在网格构建对象上添加这个直线片段
|
||||
/// </summary>
|
||||
/// <param name="vh">构建网格对象</param>
|
||||
/// <param name="segmentPartIndex">该线路片段索引(比如第一段线应该是0)</param>
|
||||
/// <param name="verts">该片段顶点</param>
|
||||
public static void AddSingleLineSegmentVertsAndTriangle_CFAL(this VertexHelper vh, int segmentPartIndex, IEnumerable<UIVertex> verts)
|
||||
{
|
||||
foreach (var vert in verts)
|
||||
vh.AddVert(vert);
|
||||
int index = segmentPartIndex * 5;
|
||||
|
||||
// 添加线段的两个三角形(构成矩形线段)
|
||||
vh.AddTriangle(index, index+1, index+3);
|
||||
vh.AddTriangle(index+3, index+2, index);
|
||||
|
||||
// 为线段之间添加斜角边缘
|
||||
// 使用上一个线段的终点和当前线段的起点创建过渡三角形
|
||||
if (segmentPartIndex != 0)
|
||||
{
|
||||
vh.AddTriangle(index, index-1, index-3);
|
||||
vh.AddTriangle(index+1, index-1, index-2);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建带有倒角的线段顶点数据
|
||||
/// 支持设置圆弧细分数量和内圆弧半径
|
||||
/// </summary>
|
||||
/// <param name="vertices">顶点容器</param>
|
||||
/// <param name="startPoint">线段的起点</param>
|
||||
/// <param name="endPoint">线段的终点</param>
|
||||
/// <param name="nextPoint">下一个线段的终点(用于计算夹角)</param>
|
||||
/// <param name="prevPoint">上一个线段的起点(用于计算夹角)</param>
|
||||
/// <param name="thickness">线条的厚度</param>
|
||||
/// <param name="color">线条的颜色</param>
|
||||
/// <param name="startLength">当前线段起点在线路中的累积长度</param>
|
||||
/// <param name="totalLength">线路的总长度</param>
|
||||
/// <param name="offset">偏移量</param>
|
||||
/// <param name="chamferSegments">倒角细分数量</param>
|
||||
/// <param name="innerRadius">内圆弧半径</param>
|
||||
/// <param name="distance">返回线段的距离</param>
|
||||
/// <returns>包含线段顶点的列表</returns>
|
||||
public static List<UIVertex> GetSingleLineSegmentVerts_CFAL(List<UIVertex> vertices, Vector2 startPoint, Vector2 endPoint, Vector2 nextPoint, Vector2 prevPoint,
|
||||
float thickness, Color color, float startLength, out float distance, float totalLength, Vector3 offset,
|
||||
int chamferSegments = 0, float innerRadius = 0f)
|
||||
{
|
||||
if (vertices == null)
|
||||
throw new Exception("没有指定线段片段顶点容器列表");
|
||||
vertices.Clear();
|
||||
|
||||
// 创建顶点模板,设置颜色为组件的当前颜色
|
||||
UIVertex vertex = UIVertex.simpleVert;
|
||||
vertex.color = color;
|
||||
|
||||
if (!GetNormalizedVector(startPoint, endPoint,
|
||||
out var vector, out distance, out var normal, out var subTangent))
|
||||
return vertices;
|
||||
|
||||
// 线段单侧宽度
|
||||
var width = thickness / 2;
|
||||
|
||||
GetCurrentLengthUVY(startLength, distance, totalLength, out var startUVY, out var endUVY);
|
||||
|
||||
// 计算起点和终点的夹角
|
||||
float startAngle = 0f;
|
||||
float endAngle = 0f;
|
||||
|
||||
if (prevPoint != startPoint)
|
||||
{
|
||||
var prevVector = startPoint - prevPoint;
|
||||
var prevNormal = prevVector.normalized;
|
||||
startAngle = Vector2.Angle(normal, -prevNormal);
|
||||
}
|
||||
|
||||
if (nextPoint != endPoint)
|
||||
{
|
||||
var nextVector = nextPoint - endPoint;
|
||||
var nextNormal = nextVector.normalized;
|
||||
endAngle = Vector2.Angle(-normal, nextNormal);
|
||||
}
|
||||
|
||||
// 计算顶点偏移量
|
||||
float startOffset = 0f;
|
||||
float endOffset = 0f;
|
||||
|
||||
if (Mathf.Abs(startAngle) > 0.1f)
|
||||
{
|
||||
if (innerRadius > 0f)
|
||||
{
|
||||
startOffset = (width + innerRadius) / Mathf.Sin(startAngle * Mathf.Deg2Rad / 2) - innerRadius;
|
||||
}
|
||||
else
|
||||
{
|
||||
startOffset = width / Mathf.Sin(startAngle * Mathf.Deg2Rad / 2);
|
||||
}
|
||||
}
|
||||
|
||||
if (Mathf.Abs(endAngle) > 0.1f)
|
||||
{
|
||||
if (innerRadius > 0f)
|
||||
{
|
||||
endOffset = (width + innerRadius) / Mathf.Sin(endAngle * Mathf.Deg2Rad / 2) - innerRadius;
|
||||
}
|
||||
else
|
||||
{
|
||||
endOffset = width / Mathf.Sin(endAngle * Mathf.Deg2Rad / 2);
|
||||
}
|
||||
}
|
||||
|
||||
// 添加起点的左侧顶点
|
||||
vertex.position = (startPoint +
|
||||
subTangent * width +
|
||||
normal * startOffset);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(0f, startUVY);
|
||||
vertices.Add(vertex);
|
||||
|
||||
// 添加起点的右侧顶点
|
||||
vertex.position = (startPoint +
|
||||
subTangent * -width +
|
||||
normal * startOffset);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(1f, startUVY);
|
||||
vertices.Add(vertex);
|
||||
|
||||
// 添加终点的左侧顶点
|
||||
vertex.position = (endPoint +
|
||||
subTangent * width +
|
||||
normal * -endOffset);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(0f, endUVY);
|
||||
vertices.Add(vertex);
|
||||
|
||||
// 添加终点的右侧顶点
|
||||
vertex.position = (endPoint +
|
||||
subTangent * -width +
|
||||
normal * -endOffset);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(1f, endUVY);
|
||||
vertices.Add(vertex);
|
||||
|
||||
// 添加终点的中心点
|
||||
vertex.position = (endPoint +
|
||||
normal * -endOffset);
|
||||
vertex.position += offset;
|
||||
vertex.uv0 = new Vector2(0.5f, endUVY);
|
||||
vertices.Add(vertex);
|
||||
|
||||
return vertices;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 推送顶点绘制带有倒角的线路
|
||||
/// </summary>
|
||||
/// <param name="vh">网格构建对象</param>
|
||||
/// <param name="points">线路顶点数组</param>
|
||||
/// <param name="thickness">线条厚度</param>
|
||||
/// <param name="cycleLoop">是否循环</param>
|
||||
/// <param name="color">线条颜色</param>
|
||||
/// <param name="offset">偏移量</param>
|
||||
/// <param name="chamferSegments">倒角细分数量</param>
|
||||
/// <param name="innerRadius">内圆弧半径</param>
|
||||
public static void PopulateLineByPointsArray_CFAL(this VertexHelper vh, Vector2[] points, float thickness, bool cycleLoop, Color color, Vector3 offset,
|
||||
int chamferSegments = 0, float innerRadius = 0f)
|
||||
{
|
||||
// 至少需要 2 个点才能绘制线条
|
||||
if (points.Length < 2)
|
||||
return;
|
||||
|
||||
// 计算线路总长度
|
||||
var totalLength = points.CalculateTotalLength(cycleLoop);
|
||||
var currentLength = 0f;
|
||||
var vertices = ListPool<UIVertex>.Get();
|
||||
|
||||
for (int i = 0; i < points.Length - (cycleLoop ? 0 : 1); i++)
|
||||
{
|
||||
var startPoint = points[i];
|
||||
var endPoint = points[(i + 1) % points.Length];
|
||||
var prevPoint = i > 0 ? points[i - 1] : cycleLoop ? points[^1] : startPoint;
|
||||
var nextPoint = points[(i + 2) % points.Length];
|
||||
|
||||
vh.AddSingleLineSegmentVertsAndTriangle_CFAL(i,
|
||||
GetSingleLineSegmentVerts_CFAL(vertices, startPoint, endPoint, nextPoint, prevPoint,
|
||||
thickness, color, currentLength, out var distance, totalLength, offset,
|
||||
chamferSegments, innerRadius));
|
||||
currentLength += distance;
|
||||
}
|
||||
|
||||
ListPool<UIVertex>.Release(vertices);
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#region 带有顶合并的线路绘制方法
|
||||
|
||||
/// <summary>
|
||||
/// 创建线段的顶点数据
|
||||
/// 每个线段由 5 个顶点组成:
|
||||
/// - 起点的左右两个顶点
|
||||
/// - 终点的左右两个顶点
|
||||
/// - 终点的中心点(用于线段连接)
|
||||
/// </summary>
|
||||
/// <param name="startPoint">线段的起点</param>
|
||||
/// <param name="endPoint">线段的终点</param>
|
||||
/// <param name="angle0">起点到终点与终点到下一点</param>
|
||||
/// <param name="angle3">起点到终点与终点到下一点</param>
|
||||
/// <param name="thickness">线条的厚度</param>
|
||||
/// <param name="center">是否居中显示</param>
|
||||
/// <param name="rectSize">矩形变换的尺寸</param>
|
||||
/// <param name="color">线条的颜色</param>
|
||||
/// <param name="vh">用于添加顶点的 VertexHelper 对象</param>
|
||||
/// <param name="startLength">当前线段起点在线路中的累积长度</param>
|
||||
/// <param name="totalLength">线路的总长度</param>
|
||||
public static void CreateLineSegment_CFAL(this VertexHelper vh, Vector2 startPoint, Vector2 endPoint, float angle0, float angle3, float thickness, bool center, Vector2 rectSize, Color color, float startLength, float totalLength)
|
||||
{
|
||||
// 计算偏移量:如果需要居中显示,则偏移到组件中心
|
||||
Vector2 offset = center ? (rectSize / 2) : Vector2.zero;
|
||||
|
||||
// 创建顶点模板,设置颜色为组件的当前颜色
|
||||
UIVertex vertex = UIVertex.simpleVert;
|
||||
vertex.color = color;
|
||||
|
||||
if (!GetNormalizedVector(startPoint, endPoint,
|
||||
out var vector, out var distance, out var normal, out var subTangent))
|
||||
return;
|
||||
|
||||
// 线段单侧宽度
|
||||
var width = thickness / 2;
|
||||
//顶点偏移量,根据夹角计算内侧交点相对坐标点应该退后的距离
|
||||
var pointOffset1 = Mathf.Abs(angle0) <= 0.1f ? 0 : width / Mathf.Sin(angle0 * Mathf.Deg2Rad) + (angle0 > 90 ? width : 0);
|
||||
var pointOffset2 = Mathf.Abs(angle3) <= 0.1f ? 0 : width / Mathf.Sin(angle3 * Mathf.Deg2Rad) + (angle3 > 90 ? width : 0);
|
||||
Debug.Log($"{angle0} = {Mathf.Sin(angle0 * Mathf.Deg2Rad)} , {angle3} = {Mathf.Sin(angle3 * Mathf.Deg2Rad)}");
|
||||
// 计算起点和终点的UV坐标Y值
|
||||
float startUVY = totalLength > 0 ? startLength / totalLength : 0f;
|
||||
float endUVY = totalLength > 0 ? (startLength + distance) / totalLength : 0f;
|
||||
|
||||
vertex.position = (Vector3)(startPoint +
|
||||
subTangent * width +
|
||||
normal * pointOffset1) - (Vector3)offset;
|
||||
vertex.uv0 = new Vector2(0f, startUVY); // 左侧顶点的UV
|
||||
vh.AddVert(vertex);
|
||||
|
||||
vertex.position = (Vector3)(startPoint +
|
||||
subTangent * -width +
|
||||
normal * pointOffset1) - (Vector3)offset;
|
||||
vertex.uv0 = new Vector2(1f, startUVY); // 右侧顶点的UV
|
||||
vh.AddVert(vertex);
|
||||
|
||||
vertex.position = (Vector3)(endPoint +
|
||||
subTangent * width +
|
||||
normal * -pointOffset2) - (Vector3)offset;
|
||||
vertex.uv0 = new Vector2(0f, endUVY); // 左侧顶点的UV
|
||||
vh.AddVert(vertex);
|
||||
|
||||
vertex.position = (Vector3)(endPoint +
|
||||
subTangent * -width +
|
||||
normal * -pointOffset2) - (Vector3)offset;
|
||||
vertex.uv0 = new Vector2(1f, endUVY); // 右侧顶点的UV
|
||||
vh.AddVert(vertex);
|
||||
|
||||
// 添加终点的中心点,用于连接后续线段
|
||||
vertex.position = (Vector3)(endPoint +
|
||||
normal * -pointOffset2) - (Vector3)offset;
|
||||
vertex.uv0 = new Vector2(0.5f, endUVY); // 中心点的UV
|
||||
vh.AddVert(vertex);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 顶点工具集
|
||||
|
||||
public static void GetUVAtRect(this Vector2 pos, Rect rect, out float u, out float v)
|
||||
{
|
||||
u = (pos.x - rect.xMin) / rect.width;
|
||||
v = (pos.y - rect.yMin) / rect.height;
|
||||
}
|
||||
|
||||
public static void Get(this IList<UIVertex> vertexList, Vector4 uv2)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 117633a298088ab4fb9fa0edac2bd141
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user