First Commit
This commit is contained in:
commit
eed6b79efc
2836 files changed
+948481
No files matched your search
@@ -0,0 +1,342 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public struct CarDefectsSummary
|
||||
{
|
||||
public int rustedPartsCount;
|
||||
public int missingBodyPartsCount;
|
||||
public int flatTiresCount;
|
||||
public int missingWheelsCount;
|
||||
public int lowFluidsCount;
|
||||
public int engineIssuesCount;
|
||||
public int hiddenRepaintCount;
|
||||
public float dirtAmount;
|
||||
public bool startProblems;
|
||||
public bool oilProblems;
|
||||
public bool overheatProblems;
|
||||
public bool brakeProblems;
|
||||
public List<string> missingPartNames;
|
||||
public float totalPricePenalty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Детерминированная генерация состояния подержанного авто по Seed: грязь, ржавчина, скрытый перекрас,
|
||||
/// отсутствующие навесные детали, спущенные/отсутствующие колеса, износ подкапотных агрегатов и жидкостей.
|
||||
/// Один и тот же seed дает 100% одинаковую машину и на фото объявления, и на месте встречи.
|
||||
/// </summary>
|
||||
public class CarConditionGenerator : MonoBehaviour
|
||||
{
|
||||
[Header("Настройки ржавчины")]
|
||||
[Range(0f, 1f)] [SerializeField] private float rustProbability = 0.65f;
|
||||
[SerializeField] private float minRustAmount = 0.25f;
|
||||
[SerializeField] private float maxRustAmount = 0.80f;
|
||||
|
||||
[Header("Шанс отсутствия навесных деталей (бамперы, фары, крылья)")]
|
||||
[Range(0f, 0.5f)] [SerializeField] private float missingBodyPartChance = 0.15f;
|
||||
[SerializeField] private int maxMissingBodyParts = 3;
|
||||
|
||||
[Header("Проблемы с колесами")]
|
||||
[Range(0f, 1f)] [SerializeField] private float flatTireChance = 0.25f;
|
||||
[Range(0f, 1f)] [SerializeField] private float missingWheelChance = 0.12f;
|
||||
|
||||
[Header("Грязь и скрытый перекрас")]
|
||||
[SerializeField] private Vector2 dirtRange = new Vector2(0.35f, 0.95f);
|
||||
[Range(0f, 1f)] [SerializeField] private float hiddenRepaintChance = 0.18f;
|
||||
|
||||
[Header("Цвет кузова")]
|
||||
[SerializeField] private bool overrideMaterialColor = false;
|
||||
[SerializeField] private Color baseCarColor = Color.blue;
|
||||
|
||||
private bool configuredExternally = false;
|
||||
|
||||
public CarDefectsSummary LastSummary { get; private set; }
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// Если машина уже настроена через CarMarketManager (по Seed) — не перезаписываем её!
|
||||
if (!configuredExternally)
|
||||
{
|
||||
GenerateCondition();
|
||||
}
|
||||
}
|
||||
|
||||
public void MarkConfigured() => configuredExternally = true;
|
||||
|
||||
[ContextMenu("Сгенерировать случайное состояние")]
|
||||
public void GenerateCondition()
|
||||
{
|
||||
int randomSeed = Random.Range(1, 999999);
|
||||
Color col = overrideMaterialColor ? baseCarColor : GetCurrentBodyColor();
|
||||
ApplyConditionBySeed(randomSeed, col, false, out _);
|
||||
}
|
||||
|
||||
public Color GetCurrentBodyColor()
|
||||
{
|
||||
int rustProp = Shader.PropertyToID("_RustAmount");
|
||||
int colorProp = Shader.PropertyToID("_BaseColor");
|
||||
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
foreach (Material m in r.sharedMaterials)
|
||||
{
|
||||
if (m != null && m.HasProperty(rustProp) && m.HasProperty(colorProp))
|
||||
return m.GetColor(colorProp);
|
||||
}
|
||||
}
|
||||
return baseCarColor;
|
||||
}
|
||||
|
||||
private static bool IsWheel(CarPart part) => part.GetComponent<CarWheelCondition>() != null || part.TotalBoltsCount > 0 || part.LinkedWheelCollider != null;
|
||||
|
||||
/// <summary>
|
||||
/// Генерирует 100% одинаковое состояние машины для одного и того же seed (и в фотобоксе, и на карте).
|
||||
/// </summary>
|
||||
public void ApplyConditionBySeed(int seed, Color carColor, bool isPhotoStudio, out CarDefectsSummary summary)
|
||||
{
|
||||
configuredExternally = true;
|
||||
|
||||
EngineBayManager bay = GetComponent<EngineBayManager>();
|
||||
if (bay != null) bay.EnsureBuilt();
|
||||
|
||||
Random.State oldState = Random.state;
|
||||
Random.InitState(seed);
|
||||
|
||||
summary = new CarDefectsSummary
|
||||
{
|
||||
missingPartNames = new List<string>()
|
||||
};
|
||||
|
||||
float carDirt = Random.Range(dirtRange.x, dirtRange.y);
|
||||
summary.dirtAmount = carDirt;
|
||||
summary.totalPricePenalty += carDirt * 40f;
|
||||
|
||||
CarPart[] allParts = GetComponentsInChildren<CarPart>(true);
|
||||
|
||||
// 1. Кузовные и навесные детали (кроме колес и подкапотных агрегатов)
|
||||
foreach (CarPart part in allParts)
|
||||
{
|
||||
if (IsWheel(part) || part.GetComponent<EnginePart>() != null)
|
||||
continue;
|
||||
|
||||
CarPartVisuals visuals = part.GetComponent<CarPartVisuals>();
|
||||
if (visuals == null) visuals = part.gameObject.AddComponent<CarPartVisuals>();
|
||||
|
||||
visuals.SetPaintColor(carColor);
|
||||
float partDirt = Mathf.Clamp01(carDirt + Random.Range(-0.1f, 0.1f));
|
||||
|
||||
float partPrice = part.Data != null ? part.Data.basePrice : 150f;
|
||||
string partTitle = part.Data != null ? part.Data.partName : part.name;
|
||||
|
||||
// Проверяем, отсутствует ли эта навесная деталь (бампер, фара, крыло, дверь, зеркало)
|
||||
if (summary.missingBodyPartsCount < maxMissingBodyParts && Random.value < missingBodyPartChance)
|
||||
{
|
||||
summary.missingBodyPartsCount++;
|
||||
summary.missingPartNames.Add(partTitle.ToLower());
|
||||
summary.totalPricePenalty += partPrice * 1.4f;
|
||||
visuals.SetDamage(0f);
|
||||
visuals.SetDirt(0f);
|
||||
part.MakeMissingAtStart(null, false);
|
||||
continue;
|
||||
}
|
||||
|
||||
visuals.SetDirt(partDirt);
|
||||
|
||||
// Пластик не ржавеет
|
||||
if (part.Data != null && !part.Data.canRust)
|
||||
{
|
||||
visuals.SetDamage(0f);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Random.value < rustProbability)
|
||||
{
|
||||
float dmg = Random.Range(minRustAmount, maxRustAmount);
|
||||
visuals.SetDamage(dmg);
|
||||
visuals.SetHiddenRepaint(false);
|
||||
summary.rustedPartsCount++;
|
||||
summary.totalPricePenalty += partPrice * dmg;
|
||||
}
|
||||
else
|
||||
{
|
||||
visuals.SetDamage(0f);
|
||||
bool repainted = Random.value < hiddenRepaintChance;
|
||||
visuals.SetHiddenRepaint(repainted);
|
||||
if (repainted)
|
||||
{
|
||||
summary.hiddenRepaintCount++;
|
||||
summary.totalPricePenalty += partPrice * 0.35f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Основной несъемный кузов (body): ржавеют только крупные панели, не больше 3 очагов на машину
|
||||
int rustProp = Shader.PropertyToID("_RustAmount");
|
||||
List<Renderer> bodyRenderers = new List<Renderer>();
|
||||
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
if (r.GetComponentInParent<CarPart>(true) != null) continue;
|
||||
foreach (Material m in r.sharedMaterials)
|
||||
{
|
||||
if (m != null && m.HasProperty(rustProp))
|
||||
{
|
||||
bodyRenderers.Add(r);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int bodyRust = 0;
|
||||
foreach (Renderer r in bodyRenderers)
|
||||
{
|
||||
CarPartVisuals bodyVis = r.GetComponent<CarPartVisuals>();
|
||||
if (bodyVis == null) bodyVis = r.gameObject.AddComponent<CarPartVisuals>();
|
||||
bodyVis.SetPaintColor(carColor);
|
||||
bodyVis.SetDirt(Mathf.Clamp01(carDirt + Random.Range(-0.05f, 0.08f)));
|
||||
|
||||
bool large = r.bounds.size.magnitude > 1.2f;
|
||||
float roll = Random.value;
|
||||
float dmgRoll = Random.Range(minRustAmount, maxRustAmount);
|
||||
float bodyDmg = (large && bodyRust < 3 && roll < rustProbability * 0.6f) ? dmgRoll : 0f;
|
||||
bodyVis.SetDamage(bodyDmg);
|
||||
if (bodyDmg > 0.05f)
|
||||
{
|
||||
bodyRust++;
|
||||
summary.rustedPartsCount++;
|
||||
summary.totalPricePenalty += 140f * bodyDmg;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Колеса (Нормальное / Спущенное / Отсутствует)
|
||||
CarWheelCondition[] wheels = GetComponentsInChildren<CarWheelCondition>(true);
|
||||
foreach (CarWheelCondition wheel in wheels)
|
||||
{
|
||||
float roll = Random.value;
|
||||
// В одном объявлении убираем максимум 1 колесо, чтобы машина не висела вся на кирпичах
|
||||
if (roll < missingWheelChance && summary.missingWheelsCount < 1)
|
||||
{
|
||||
summary.missingWheelsCount++;
|
||||
summary.totalPricePenalty += 220f;
|
||||
CarPart wp = wheel.GetComponent<CarPart>();
|
||||
if (wp != null) wp.MakeMissingAtStart(null, !isPhotoStudio);
|
||||
}
|
||||
else if (roll < missingWheelChance + flatTireChance)
|
||||
{
|
||||
summary.flatTiresCount++;
|
||||
summary.totalPricePenalty += 100f;
|
||||
wheel.ApplyState(CarWheelCondition.TireState.Flat);
|
||||
}
|
||||
else
|
||||
{
|
||||
wheel.ApplyState(CarWheelCondition.TireState.Normal);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Подкапотные агрегаты (АКБ, свечи, фильтры, радиатор, генератор)
|
||||
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(true))
|
||||
{
|
||||
float r1 = Random.value;
|
||||
float r2 = Random.value;
|
||||
float r3 = Random.value;
|
||||
ep.charge = 100f;
|
||||
|
||||
switch (ep.partType)
|
||||
{
|
||||
case EnginePartType.Battery:
|
||||
ep.condition = Mathf.Lerp(40f, 100f, r2);
|
||||
if (r1 < 0.30f)
|
||||
{
|
||||
ep.charge = Mathf.Lerp(4f, 18f, r3);
|
||||
summary.startProblems = true;
|
||||
summary.engineIssuesCount++;
|
||||
summary.totalPricePenalty += 60f;
|
||||
}
|
||||
else ep.charge = Mathf.Lerp(45f, 100f, r3);
|
||||
|
||||
if (r1 > 0.94f && ep.Part != null && ep.Part.State == PartState.Installed)
|
||||
{
|
||||
summary.startProblems = true;
|
||||
summary.engineIssuesCount++;
|
||||
summary.missingPartNames.Add("аккумулятор");
|
||||
summary.totalPricePenalty += 110f;
|
||||
ep.Part.MakeMissingAtStart(null, false);
|
||||
}
|
||||
break;
|
||||
|
||||
case EnginePartType.SparkPlugs:
|
||||
ep.condition = r1 < 0.35f ? Mathf.Lerp(5f, 28f, r2) : Mathf.Lerp(50f, 100f, r2);
|
||||
if (ep.condition < 30f) { summary.startProblems = true; summary.engineIssuesCount++; summary.totalPricePenalty += 45f; }
|
||||
break;
|
||||
|
||||
case EnginePartType.AirFilter:
|
||||
ep.condition = r1 < 0.40f ? Mathf.Lerp(5f, 28f, r2) : Mathf.Lerp(40f, 100f, r2);
|
||||
if (ep.condition < 30f) { summary.engineIssuesCount++; summary.totalPricePenalty += 20f; }
|
||||
break;
|
||||
|
||||
case EnginePartType.Radiator:
|
||||
ep.condition = r1 < 0.20f ? Mathf.Lerp(10f, 28f, r2) : Mathf.Lerp(50f, 100f, r2);
|
||||
if (ep.condition < 30f) { summary.overheatProblems = true; summary.engineIssuesCount++; summary.totalPricePenalty += 120f; }
|
||||
break;
|
||||
|
||||
case EnginePartType.Alternator:
|
||||
ep.condition = r1 < 0.15f ? Mathf.Lerp(5f, 25f, r2) : Mathf.Lerp(50f, 100f, r2);
|
||||
if (ep.condition < 30f) { summary.startProblems = true; summary.engineIssuesCount++; summary.totalPricePenalty += 130f; }
|
||||
break;
|
||||
|
||||
default:
|
||||
ep.condition = Mathf.Lerp(10f, 100f, r2);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Технические жидкости под капотом (масло, антифриз, тормозная, омывайка)
|
||||
CarFluids fluids = GetComponent<CarFluids>();
|
||||
if (fluids != null)
|
||||
{
|
||||
fluids.SetRandomLevels(0.20f, 0.70f);
|
||||
if (fluids.EngineOil.FillPercent < 0.50f || fluids.EngineOil.quality < 0.3f)
|
||||
{
|
||||
summary.lowFluidsCount++;
|
||||
summary.oilProblems = true;
|
||||
summary.totalPricePenalty += 60f;
|
||||
}
|
||||
if (fluids.Coolant.FillPercent < 0.50f)
|
||||
{
|
||||
summary.lowFluidsCount++;
|
||||
summary.overheatProblems |= fluids.Coolant.FillPercent < 0.25f;
|
||||
summary.totalPricePenalty += 50f;
|
||||
}
|
||||
if (fluids.BrakeFluid.FillPercent < 0.30f)
|
||||
{
|
||||
summary.lowFluidsCount++;
|
||||
summary.brakeProblems = true;
|
||||
summary.totalPricePenalty += 30f;
|
||||
}
|
||||
if (fluids.WasherFluid.FillPercent < 0.25f)
|
||||
{
|
||||
summary.lowFluidsCount++;
|
||||
summary.totalPricePenalty += 10f;
|
||||
}
|
||||
}
|
||||
|
||||
Random.state = oldState;
|
||||
LastSummary = summary;
|
||||
}
|
||||
|
||||
/// <summary>Идеальное состояние (используется для отладки и демонстрации).</summary>
|
||||
[ContextMenu("Сделать машину новой")]
|
||||
public void MakePristine()
|
||||
{
|
||||
configuredExternally = true;
|
||||
foreach (CarPartVisuals v in GetComponentsInChildren<CarPartVisuals>(true))
|
||||
{
|
||||
v.SetDamage(0f);
|
||||
v.SetDirt(0f);
|
||||
v.SetHiddenRepaint(false);
|
||||
}
|
||||
foreach (CarWheelCondition w in GetComponentsInChildren<CarWheelCondition>(true))
|
||||
w.ApplyState(CarWheelCondition.TireState.Normal);
|
||||
foreach (EnginePart ep in GetComponentsInChildren<EnginePart>(true))
|
||||
ep.SetAsNew();
|
||||
CarFluids f = GetComponent<CarFluids>();
|
||||
if (f != null) f.FillAllFresh();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 598fbcd97cc34477934893a1802ce999
|
||||
timeCreated: 1791330530
|
||||
@@ -0,0 +1,180 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Анализирует геометрию кузовных деталей (двери, капот, багажник, крылья)
|
||||
/// и запекает веса торцов и кромок в цвета вершин (Mesh.colors),
|
||||
/// чтобы ржавчина реалистично зарождалась на торцах и швах.
|
||||
/// </summary>
|
||||
public static class CarPartMeshEdgeAnalyzer
|
||||
{
|
||||
private static readonly Dictionary<string, Color[]> vertexColorCache = new Dictionary<string, Color[]>();
|
||||
|
||||
public static void ApplyEdgeColorsToMesh(MeshFilter filter, string partNameHint = "")
|
||||
{
|
||||
if (filter == null || filter.sharedMesh == null) return;
|
||||
|
||||
Mesh shared = filter.sharedMesh;
|
||||
int vertexCount = shared.vertexCount;
|
||||
if (vertexCount == 0) return;
|
||||
|
||||
string cacheKey = $"{shared.name}_{vertexCount}";
|
||||
|
||||
Color[] colors;
|
||||
if (!vertexColorCache.TryGetValue(cacheKey, out colors) || colors == null || colors.Length != vertexCount)
|
||||
{
|
||||
colors = CalculateEdgeColors(shared, partNameHint);
|
||||
vertexColorCache[cacheKey] = colors;
|
||||
}
|
||||
|
||||
// Если в sharedMesh еще нет цветов, или если мы в рантайме создаем экземпляр
|
||||
if (shared.colors == null || shared.colors.Length != vertexCount)
|
||||
{
|
||||
// Клонируем меш для инстанса, чтобы не портить исходный asset на диске
|
||||
Mesh instanceMesh = Object.Instantiate(shared);
|
||||
instanceMesh.name = shared.name + "_EdgeColored";
|
||||
instanceMesh.colors = colors;
|
||||
filter.sharedMesh = instanceMesh;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Если уже инстанс — просто присваиваем
|
||||
filter.sharedMesh.colors = colors;
|
||||
}
|
||||
}
|
||||
|
||||
private static Color[] CalculateEdgeColors(Mesh mesh, string partName)
|
||||
{
|
||||
Vector3[] vertices = mesh.vertices;
|
||||
Vector3[] normals = mesh.normals;
|
||||
int[] triangles = mesh.triangles;
|
||||
int vCount = vertices.Length;
|
||||
|
||||
Color[] colors = new Color[vCount];
|
||||
if (triangles == null || triangles.Length < 3)
|
||||
{
|
||||
for (int i = 0; i < vCount; i++) colors[i] = Color.black;
|
||||
return colors;
|
||||
}
|
||||
|
||||
Bounds bounds = mesh.bounds;
|
||||
Vector3 bMin = bounds.min;
|
||||
Vector3 bMax = bounds.max;
|
||||
Vector3 bSize = bounds.size;
|
||||
|
||||
// 1. Поиск граничных ребер (Boundary Edges) — ребра, принадлежащие только 1 треугольнику
|
||||
Dictionary<long, int> edgeUsage = new Dictionary<long, int>(triangles.Length);
|
||||
for (int i = 0; i < triangles.Length; i += 3)
|
||||
{
|
||||
int i0 = triangles[i];
|
||||
int i1 = triangles[i + 1];
|
||||
int i2 = triangles[i + 2];
|
||||
|
||||
AddEdge(edgeUsage, i0, i1);
|
||||
AddEdge(edgeUsage, i1, i2);
|
||||
AddEdge(edgeUsage, i2, i0);
|
||||
}
|
||||
|
||||
HashSet<int> boundaryVertices = new HashSet<int>();
|
||||
foreach (var kvp in edgeUsage)
|
||||
{
|
||||
if (kvp.Value == 1) // Ребро лежит на открытом торце / кромке металла
|
||||
{
|
||||
int v0 = (int)(kvp.Key >> 32);
|
||||
int v1 = (int)(kvp.Key & 0xFFFFFFFF);
|
||||
boundaryVertices.Add(v0);
|
||||
boundaryVertices.Add(v1);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Оптимизированный расчет расстояния от каждой вершины до ближайшего торца
|
||||
// Для деталей авто ширина зоны распространения ржавчины от торца: 8-12 см
|
||||
float maxEdgeDist = Mathf.Max(0.08f, Mathf.Min(bSize.x, Mathf.Min(bSize.y, bSize.z)) * 0.45f);
|
||||
|
||||
List<Vector3> boundaryPoints = new List<Vector3>(boundaryVertices.Count);
|
||||
foreach (int idx in boundaryVertices)
|
||||
{
|
||||
boundaryPoints.Add(vertices[idx]);
|
||||
}
|
||||
|
||||
bool hasBoundary = boundaryPoints.Count > 0;
|
||||
|
||||
string lowerName = partName.ToLowerInvariant();
|
||||
bool isDoor = lowerName.Contains("door");
|
||||
bool isFender = lowerName.Contains("fender") || lowerName.Contains("wing");
|
||||
bool isHood = lowerName.Contains("hood");
|
||||
bool isTrunk = lowerName.Contains("trunk") || lowerName.Contains("tailgate");
|
||||
|
||||
for (int i = 0; i < vCount; i++)
|
||||
{
|
||||
Vector3 p = vertices[i];
|
||||
|
||||
// Фактор расстояния до геометрического торца меша
|
||||
float edgeDist = float.MaxValue;
|
||||
if (hasBoundary)
|
||||
{
|
||||
// Ищем ближайшую точку торца
|
||||
for (int b = 0; b < boundaryPoints.Count; b++)
|
||||
{
|
||||
float sqr = (p - boundaryPoints[b]).sqrMagnitude;
|
||||
if (sqr < edgeDist) edgeDist = sqr;
|
||||
if (sqr < 0.0004f) break; // Ближе 2 см — точно торец
|
||||
}
|
||||
edgeDist = Mathf.Sqrt(edgeDist);
|
||||
}
|
||||
|
||||
float boundaryWeight = hasBoundary ? Mathf.Clamp01(1f - (edgeDist / maxEdgeDist)) : 0f;
|
||||
|
||||
// Фактор нижней кромки (пороги, низ дверей, нижние углы крыльев)
|
||||
// Вода и дорожная соль стекают вниз: нижние 10-15% высоты детали ржавеют сильнее всего
|
||||
float relY = (bSize.y > 0.001f) ? Mathf.Clamp01((p.y - bMin.y) / bSize.y) : 0f;
|
||||
float bottomWeight = Mathf.Clamp01(1f - (relY / 0.18f));
|
||||
|
||||
// Фактор периметра габаритов (для капота — передняя кромка, для багажника — задний торец)
|
||||
float perimeterWeight = 0f;
|
||||
if (isDoor)
|
||||
{
|
||||
// На дверях ржавчина сильнее всего на нижней кромке (hem flange) и переднем/заднем торцах
|
||||
perimeterWeight = bottomWeight * 0.85f + boundaryWeight * 0.75f;
|
||||
}
|
||||
else if (isFender)
|
||||
{
|
||||
// На крыльях ржавчина по кромке колесной арки и внизу у брызговика
|
||||
perimeterWeight = boundaryWeight * 0.85f + bottomWeight * 0.65f;
|
||||
}
|
||||
else if (isHood)
|
||||
{
|
||||
// На капоте сильнее всего передний торец от сколов камней
|
||||
float relZ = (bSize.z > 0.001f) ? Mathf.Clamp01((p.z - bMin.z) / bSize.z) : 0f;
|
||||
float frontLip = Mathf.Clamp01(1f - (relZ / 0.20f));
|
||||
perimeterWeight = frontLip * 0.85f + boundaryWeight * 0.65f;
|
||||
}
|
||||
else if (isTrunk)
|
||||
{
|
||||
// На багажнике — нижний и задний край
|
||||
float rearLip = bottomWeight;
|
||||
perimeterWeight = rearLip * 0.85f + boundaryWeight * 0.65f;
|
||||
}
|
||||
else
|
||||
{
|
||||
perimeterWeight = Mathf.Max(boundaryWeight, bottomWeight * 0.7f);
|
||||
}
|
||||
|
||||
// Итоговый вес: 1.0 на торцах, плавно спадает к 0 в центре детали
|
||||
float finalEdgeFactor = Mathf.Clamp01(perimeterWeight);
|
||||
|
||||
colors[i] = new Color(finalEdgeFactor, bottomWeight, boundaryWeight, 1f);
|
||||
}
|
||||
|
||||
return colors;
|
||||
}
|
||||
|
||||
private static void AddEdge(Dictionary<long, int> dict, int a, int b)
|
||||
{
|
||||
int min = Mathf.Min(a, b);
|
||||
int max = Mathf.Max(a, b);
|
||||
long key = ((long)min << 32) | (long)(uint)max;
|
||||
if (!dict.ContainsKey(key)) dict[key] = 0;
|
||||
dict[key]++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bc9438d09442eea48993b97d16b13579
|
||||
@@ -0,0 +1,331 @@
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
public enum RepairStage
|
||||
{
|
||||
Healthy, Rusted, Cleaned, Puttied, Sanded, Repaired
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Визуальное состояние кузовной детали через MaterialPropertyBlock (без дублирования материалов):
|
||||
/// родной цвет, ржавчина, шпаклевка, шлифовка, покраска и слой дорожной грязи (dirtAmount).
|
||||
/// </summary>
|
||||
[DisallowMultipleComponent]
|
||||
public class CarPartVisuals : MonoBehaviour
|
||||
{
|
||||
private static readonly int BaseColorProp = Shader.PropertyToID("_BaseColor");
|
||||
private static readonly int RustAmountProp = Shader.PropertyToID("_RustAmount");
|
||||
private static readonly int RustInitialProp = Shader.PropertyToID("_RustInitial");
|
||||
private static readonly int PuttyProp = Shader.PropertyToID("_PuttyProgress");
|
||||
private static readonly int SandProp = Shader.PropertyToID("_SandProgress");
|
||||
private static readonly int PaintProp = Shader.PropertyToID("_PaintProgress");
|
||||
private static readonly int SmoothnessProp = Shader.PropertyToID("_PaintSmoothness");
|
||||
|
||||
private const float DoneThreshold = 0.98f;
|
||||
private const float RustCleanThreshold = 0.02f;
|
||||
public const float DirtyThreshold = 0.1f;
|
||||
|
||||
private static readonly Color DirtColor = new Color(0.36f, 0.31f, 0.24f);
|
||||
|
||||
[Header("Состояние детали")]
|
||||
[Range(0f, 1f)] [SerializeField] private float rustInitial;
|
||||
[Range(0f, 1f)] [SerializeField] private float rustCurrent;
|
||||
[Range(0f, 1f)] [SerializeField] private float putty;
|
||||
[Range(0f, 1f)] [SerializeField] private float sanding;
|
||||
[Range(0f, 1f)] [SerializeField] private float paint;
|
||||
[SerializeField] private Color paintColor = Color.white;
|
||||
|
||||
[Header("Грязь и ЛКП")]
|
||||
[Range(0f, 1f)] [SerializeField] private float dirtAmount;
|
||||
[Tooltip("Деталь была перекрашена прошлым владельцем (толщиномер покажет 250–450 мкм)")]
|
||||
[SerializeField] private bool hiddenRepaint;
|
||||
|
||||
private struct Slot
|
||||
{
|
||||
public Renderer renderer;
|
||||
public int materialIndex;
|
||||
}
|
||||
|
||||
private readonly List<Slot> slots = new List<Slot>();
|
||||
private readonly List<Slot> dirtSlots = new List<Slot>();
|
||||
private MaterialPropertyBlock dirtBlock;
|
||||
private MaterialPropertyBlock block;
|
||||
private bool initialized;
|
||||
private bool colorInitialized;
|
||||
private float baseSmoothness = 0.8f;
|
||||
|
||||
public float CurrentRust => rustCurrent;
|
||||
public float InitialRust => rustInitial;
|
||||
public Color CurrentColor => paintColor;
|
||||
public float DirtAmount => dirtAmount;
|
||||
public bool IsDirty => dirtAmount > DirtyThreshold;
|
||||
public bool HiddenRepaint => hiddenRepaint;
|
||||
public bool HasPaintSlots { get { EnsureInit(); return slots.Count > 0; } }
|
||||
public bool IsMainBody => GetComponent<CarPart>() == null;
|
||||
|
||||
public RepairStage Stage
|
||||
{
|
||||
get
|
||||
{
|
||||
if (rustInitial <= 0.001f) return RepairStage.Healthy;
|
||||
if (rustCurrent > RustCleanThreshold) return RepairStage.Rusted;
|
||||
if (putty < DoneThreshold) return RepairStage.Cleaned;
|
||||
if (sanding < DoneThreshold) return RepairStage.Puttied;
|
||||
if (paint < DoneThreshold) return RepairStage.Sanded;
|
||||
return RepairStage.Repaired;
|
||||
}
|
||||
}
|
||||
|
||||
public float StageProgress
|
||||
{
|
||||
get
|
||||
{
|
||||
switch (Stage)
|
||||
{
|
||||
case RepairStage.Rusted: return 1f - rustCurrent / Mathf.Max(rustInitial, 0.001f);
|
||||
case RepairStage.Cleaned: return putty;
|
||||
case RepairStage.Puttied: return sanding;
|
||||
case RepairStage.Sanded: return paint;
|
||||
default: return 1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Толщина ЛКП в микронах для толщиномера (стабильная для конкретной детали).</summary>
|
||||
public int PaintThicknessMicrons
|
||||
{
|
||||
get
|
||||
{
|
||||
int h = Mathf.Abs(gameObject.name.GetHashCode());
|
||||
float jitter = (h % 100) / 100f;
|
||||
switch (Stage)
|
||||
{
|
||||
case RepairStage.Rusted: return Mathf.RoundToInt(Mathf.Lerp(40f, 80f, jitter));
|
||||
case RepairStage.Cleaned: return 0;
|
||||
case RepairStage.Puttied:
|
||||
case RepairStage.Sanded: return Mathf.RoundToInt(Mathf.Lerp(600f, 900f, jitter));
|
||||
case RepairStage.Repaired: return Mathf.RoundToInt(Mathf.Lerp(250f, 450f, jitter));
|
||||
default:
|
||||
return hiddenRepaint ? Mathf.RoundToInt(Mathf.Lerp(250f, 450f, jitter)) : Mathf.RoundToInt(Mathf.Lerp(95f, 120f, jitter));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureInit()
|
||||
{
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
block = new MaterialPropertyBlock();
|
||||
|
||||
CarPart owner = GetComponent<CarPart>();
|
||||
|
||||
foreach (Renderer r in GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
if (owner != null && r.GetComponentInParent<CarPart>(true) != owner) continue;
|
||||
// Основной кузов (без CarPart) не забирает рендеры съемных деталей
|
||||
if (owner == null && r.GetComponentInParent<CarPart>(true) != null) continue;
|
||||
if (owner == null && r.GetComponent<CarPartVisuals>() != null && r.gameObject != gameObject) continue;
|
||||
|
||||
Material[] mats = r.sharedMaterials;
|
||||
for (int i = 0; i < mats.Length; i++)
|
||||
{
|
||||
if (mats[i] != null && mats[i].HasProperty(RustAmountProp))
|
||||
{
|
||||
// Автоматически запоминаем родной цвет машины из материала (например, синий!)
|
||||
if (!colorInitialized && mats[i].HasProperty(BaseColorProp))
|
||||
{
|
||||
paintColor = mats[i].GetColor(BaseColorProp);
|
||||
colorInitialized = true;
|
||||
}
|
||||
if (mats[i].HasProperty(SmoothnessProp))
|
||||
baseSmoothness = mats[i].GetFloat(SmoothnessProp);
|
||||
|
||||
slots.Add(new Slot { renderer = r, materialIndex = i });
|
||||
AddDirtOverlay(r);
|
||||
|
||||
MeshFilter mf = r.GetComponent<MeshFilter>();
|
||||
if (mf != null)
|
||||
{
|
||||
CarPartMeshEdgeAnalyzer.ApplyEdgeColorsToMesh(mf, gameObject.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Слой дорожной грязи: полупрозрачная текстура поверх краски на том же меше.
|
||||
/// Её непрозрачность (= dirtAmount) задается через MaterialPropertyBlock, мойка смывает её до 0.
|
||||
/// </summary>
|
||||
private void AddDirtOverlay(Renderer r)
|
||||
{
|
||||
if (!Application.isPlaying) return;
|
||||
foreach (Slot d in dirtSlots) if (d.renderer == r) return;
|
||||
Material overlay = PartCatalog.DirtOverlayMaterial;
|
||||
if (overlay == null) return;
|
||||
|
||||
Material[] mats = r.sharedMaterials;
|
||||
foreach (Material m in mats) if (m == overlay) return;
|
||||
Material[] extended = new Material[mats.Length + 1];
|
||||
mats.CopyTo(extended, 0);
|
||||
extended[mats.Length] = overlay;
|
||||
r.sharedMaterials = extended;
|
||||
dirtSlots.Add(new Slot { renderer = r, materialIndex = mats.Length });
|
||||
}
|
||||
|
||||
private void OnValidate()
|
||||
{
|
||||
if (Application.isPlaying && initialized) Apply();
|
||||
}
|
||||
|
||||
public void SetDamage(float amount)
|
||||
{
|
||||
EnsureInit();
|
||||
amount = Mathf.Clamp01(amount);
|
||||
if (amount <= 0.001f) amount = 0f;
|
||||
|
||||
rustInitial = amount;
|
||||
rustCurrent = amount;
|
||||
putty = 0f;
|
||||
sanding = 0f;
|
||||
paint = 0f;
|
||||
Apply();
|
||||
}
|
||||
|
||||
public void SetDirt(float amount)
|
||||
{
|
||||
EnsureInit();
|
||||
dirtAmount = Mathf.Clamp01(amount);
|
||||
Apply();
|
||||
}
|
||||
|
||||
public void SetHiddenRepaint(bool value) => hiddenRepaint = value;
|
||||
|
||||
/// <summary>Мойка высокого давления: снижает слой грязи.</summary>
|
||||
public bool Wash(float amount01)
|
||||
{
|
||||
if (dirtAmount <= 0f) return false;
|
||||
dirtAmount = Mathf.Max(0f, dirtAmount - amount01);
|
||||
if (dirtAmount < 0.01f) dirtAmount = 0f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
public void SetPaintColor(Color newColor)
|
||||
{
|
||||
EnsureInit();
|
||||
paintColor = newColor;
|
||||
colorInitialized = true;
|
||||
Apply();
|
||||
}
|
||||
|
||||
public bool CleanRust(float amount01)
|
||||
{
|
||||
if (Stage != RepairStage.Rusted) return false;
|
||||
rustCurrent -= rustInitial * amount01;
|
||||
if (rustCurrent <= RustCleanThreshold) rustCurrent = 0f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool ApplyPutty(float amount01)
|
||||
{
|
||||
if (Stage != RepairStage.Cleaned) return false;
|
||||
putty = Mathf.Min(1f, putty + amount01);
|
||||
if (putty >= DoneThreshold) putty = 1f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool Sand(float amount01)
|
||||
{
|
||||
if (Stage != RepairStage.Puttied) return false;
|
||||
sanding = Mathf.Min(1f, sanding + amount01);
|
||||
if (sanding >= DoneThreshold) sanding = 1f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool PaintRepair(float amount01)
|
||||
{
|
||||
if (Stage != RepairStage.Sanded) return false;
|
||||
paint = Mathf.Min(1f, paint + amount01);
|
||||
if (paint >= DoneThreshold) paint = 1f;
|
||||
Apply();
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool Recolor(Color newColor)
|
||||
{
|
||||
RepairStage s = Stage;
|
||||
if (s != RepairStage.Healthy && s != RepairStage.Repaired) return false;
|
||||
SetPaintColor(newColor);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Apply()
|
||||
{
|
||||
EnsureInit();
|
||||
// Грязь приглушает родной цвет землисто-серым матовым налетом и снижает гладкость
|
||||
Color shown = Color.Lerp(paintColor, DirtColor, dirtAmount * (dirtSlots.Count > 0 ? 0.35f : 0.82f));
|
||||
float smooth = Mathf.Lerp(baseSmoothness, 0.05f, dirtAmount);
|
||||
|
||||
foreach (Slot s in slots)
|
||||
{
|
||||
if (s.renderer == null) continue;
|
||||
s.renderer.GetPropertyBlock(block, s.materialIndex);
|
||||
block.SetColor(BaseColorProp, shown);
|
||||
block.SetFloat(RustInitialProp, rustInitial);
|
||||
block.SetFloat(RustAmountProp, rustCurrent);
|
||||
block.SetFloat(PuttyProp, putty);
|
||||
block.SetFloat(SandProp, sanding);
|
||||
block.SetFloat(PaintProp, paint);
|
||||
block.SetFloat(SmoothnessProp, smooth);
|
||||
s.renderer.SetPropertyBlock(block, s.materialIndex);
|
||||
}
|
||||
|
||||
if (dirtSlots.Count > 0)
|
||||
{
|
||||
if (dirtBlock == null) dirtBlock = new MaterialPropertyBlock();
|
||||
foreach (Slot d in dirtSlots)
|
||||
{
|
||||
if (d.renderer == null) continue;
|
||||
d.renderer.GetPropertyBlock(dirtBlock, d.materialIndex);
|
||||
dirtBlock.SetColor(BaseColorProp, new Color(1f, 1f, 1f, Mathf.Clamp01(dirtAmount * 1.05f)));
|
||||
d.renderer.SetPropertyBlock(dirtBlock, d.materialIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Находит обрабатываемую поверхность по точке попадания луча: сначала деталь под лучом,
|
||||
/// иначе ближайший к точке рендер основного несъемного кузова этой машины.
|
||||
/// </summary>
|
||||
public static CarPartVisuals FindAt(Collider hitCollider, Vector3 hitPoint)
|
||||
{
|
||||
if (hitCollider == null) return null;
|
||||
CarPartVisuals direct = hitCollider.GetComponentInParent<CarPartVisuals>();
|
||||
CarPart directPart = hitCollider.GetComponentInParent<CarPart>();
|
||||
if (direct != null && (directPart == null || direct.GetComponent<CarPart>() == directPart))
|
||||
return direct;
|
||||
if (directPart != null) return directPart.GetComponent<CarPartVisuals>();
|
||||
|
||||
VehicleInteraction car = hitCollider.GetComponentInParent<VehicleInteraction>();
|
||||
if (car == null) return direct;
|
||||
|
||||
CarPartVisuals best = null;
|
||||
float bestDist = float.MaxValue;
|
||||
foreach (CarPartVisuals v in car.GetComponentsInChildren<CarPartVisuals>())
|
||||
{
|
||||
if (!v.IsMainBody || !v.HasPaintSlots) continue;
|
||||
Renderer r = v.GetComponent<Renderer>();
|
||||
float d = r != null ? r.bounds.SqrDistance(hitPoint) : (v.transform.position - hitPoint).sqrMagnitude;
|
||||
if (d < bestDist)
|
||||
{
|
||||
bestDist = d;
|
||||
best = v;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: de28a2301d654322a1a3aa450e964901
|
||||
timeCreated: 1791330380
|
||||
Reference in new issue
Block a user