using System.Collections.Generic;
using UnityEngine;
///
/// Стадии ремонта кузовной детали. Вычисляются из значений прогресса, отдельно хранить не нужно.
///
public enum RepairStage
{
Healthy, // деталь целая, ржавчины нет
Rusted, // есть ржавчина - нужна зачистка
Cleaned, // ржавчина счищена, голый металл - нужна шпаклёвка
Puttied, // зашпаклёвано - нужна шлифовка
Sanded, // отшлифовано - нужна покраска
Repaired // покрашено, ремонт завершён
}
///
/// Состояние внешнего вида детали и стадии ремонта. Значения передаются в шейдер CarPaint_Rust
/// через MaterialPropertyBlock, только в те слоты материалов, где этот шейдер есть
/// (стёкла, фары и т.п. на той же детали не затрагиваются).
///
[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");
// Порог, после которого стадия считается завершённой (и значение "защёлкивается" до 100%)
private const float DoneThreshold = 0.98f;
private const float RustCleanThreshold = 0.02f;
[Header("Состояние (можно крутить в инспекторе во время Play)")]
[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;
private struct Slot
{
public Renderer renderer;
public int materialIndex;
}
private readonly List slots = new List();
private MaterialPropertyBlock block;
private bool initialized;
public float CurrentRust => rustCurrent;
public float InitialRust => rustInitial;
public Color CurrentColor => paintColor;
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;
}
}
/// Прогресс текущей стадии 0..1 (для подсказок и UI).
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;
}
}
}
// ---------- Инициализация ----------
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;
Material[] mats = r.sharedMaterials;
for (int i = 0; i < mats.Length; i++)
{
if (mats[i] != null && mats[i].HasProperty(RustAmountProp))
slots.Add(new Slot { renderer = r, materialIndex = i });
}
}
if (slots.Count == 0)
{
Debug.LogWarning($"[{name}] Нет материалов с шейдером CarPaint_Rust (свойство _RustAmount). " +
"Ржавчина и ремонт на этой детали не будут видны.", this);
}
}
private void OnValidate()
{
// Позволяет двигать слайдеры в инспекторе и сразу видеть результат
if (Application.isPlaying && initialized) Apply();
}
// ---------- Установка состояния ----------
/// Задать начальное повреждение детали (0 = целая). Сбрасывает все стадии ремонта.
public void SetDamage(float amount)
{
amount = Mathf.Clamp01(amount);
if (amount <= 0.001f) amount = 0f;
rustInitial = amount;
rustCurrent = amount;
putty = 0f;
sanding = 0f;
paint = 0f;
Apply();
}
/// Задать цвет краски без проверок (для генератора состояния).
public void SetPaintColor(Color newColor)
{
paintColor = newColor;
Apply();
}
// ---------- Действия инструментов ----------
// amount01 - доля полной работы за этот кадр (deltaTime / время полной обработки).
// Возвращают false, если инструмент сейчас не подходит этой стадии.
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;
paintColor = newColor;
Apply();
return true;
}
// ---------- Передача в шейдер ----------
private void Apply()
{
EnsureInit();
foreach (Slot s in slots)
{
if (s.renderer == null) continue;
s.renderer.GetPropertyBlock(block, s.materialIndex);
block.SetColor(BaseColorProp, paintColor);
block.SetFloat(RustInitialProp, rustInitial);
block.SetFloat(RustAmountProp, rustCurrent);
block.SetFloat(PuttyProp, putty);
block.SetFloat(SandProp, sanding);
block.SetFloat(PaintProp, paint);
s.renderer.SetPropertyBlock(block, s.materialIndex);
}
}
}