using System.Collections.Generic; using UnityEngine; public enum RepairStage { Healthy, Rusted, Cleaned, Puttied, Sanded, Repaired } /// /// Визуальное состояние кузовной детали через MaterialPropertyBlock (без дублирования материалов): /// родной цвет, ржавчина, шпаклевка, шлифовка, покраска и слой дорожной грязи (dirtAmount). /// [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 slots = new List(); private readonly List dirtSlots = new List(); 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() == 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; } } } /// Толщина ЛКП в микронах для толщиномера (стабильная для конкретной детали). 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(); foreach (Renderer r in GetComponentsInChildren(true)) { if (owner != null && r.GetComponentInParent(true) != owner) continue; // Основной кузов (без CarPart) не забирает рендеры съемных деталей if (owner == null && r.GetComponentInParent(true) != null) continue; if (owner == null && r.GetComponent() != 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(); if (mf != null) { CarPartMeshEdgeAnalyzer.ApplyEdgeColorsToMesh(mf, gameObject.name); } } } } } /// /// Слой дорожной грязи: полупрозрачная текстура поверх краски на том же меше. /// Её непрозрачность (= dirtAmount) задается через MaterialPropertyBlock, мойка смывает её до 0. /// 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; /// Мойка высокого давления: снижает слой грязи. 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); } } } /// /// Находит обрабатываемую поверхность по точке попадания луча: сначала деталь под лучом, /// иначе ближайший к точке рендер основного несъемного кузова этой машины. /// public static CarPartVisuals FindAt(Collider hitCollider, Vector3 hitPoint) { if (hitCollider == null) return null; CarPartVisuals direct = hitCollider.GetComponentInParent(); CarPart directPart = hitCollider.GetComponentInParent(); if (direct != null && (directPart == null || direct.GetComponent() == directPart)) return direct; if (directPart != null) return directPart.GetComponent(); VehicleInteraction car = hitCollider.GetComponentInParent(); if (car == null) return direct; CarPartVisuals best = null; float bestDist = float.MaxValue; foreach (CarPartVisuals v in car.GetComponentsInChildren()) { if (!v.IsMainBody || !v.HasPaintSlots) continue; Renderer r = v.GetComponent(); float d = r != null ? r.bounds.SqrDistance(hitPoint) : (v.transform.position - hitPoint).sqrMagnitude; if (d < bestDist) { bestDist = d; best = v; } } return best; } }