Project_WL/Assets/WL/Combat/Weapon/WLWeaponTipGlow.cs

143 lines
8.3 KiB
C#

// ─────────────────────────────────────────────────────────────────────
// WLWeaponTipGlow.cs — 무기 끝 은은한 빛 (#948 · 2026-10-20)
//
// PD 원문: 「마법검의 지팡이 끝은 은은하게 빛나도록 해줘. (마법 무기라는 느낌이 들도록)」
// ■ 붙는 자리 = WLWeaponFitter 손 맞춤 뒤 훅 1줄(WLOrbFloat 과 같은 자리 · 소켓 아래 무기 인스턴스마다 1회)
// ■ 무기 끝 = 소켓에서 가장 먼 렌더러 경계 모서리(WLStaffEarth.Tip 과 같은 생각 · 세로가 아닌 어떤 방향이든) → 무기 로컬 좌표로 기억해 따라간다
// ■ 빛 = 카메라를 보는 가산 사각형(기존 WL_Mat_ChargeHalo 사본 · 색·크기 JSON) + 선택 점광원(range · intensity JSON · 모바일 예산 고려해 1개 · 끌 수 있음) · 사인 맥동
// ■ 값 = Resources/WL/WLWeaponTipGlow.json (C45) · enabled 0 = 아무것도 안 함 · 원본 수정 0줄(훅은 WL 파일 WLWeaponFitter)
// 🔴 Debug.LogError 금지(원본 ErrorLogHook 팝업) — 예외는 LastLog 로만
// ─────────────────────────────────────────────────────────────────────
using UnityEngine;
namespace WL.Combat.Weapon
{
[System.Serializable]
public class WLWeaponTipGlowRule
{
public int[] classIds = new int[0]; // 이 직업의 무기에 붙인다(PCActor.Get_ID)
public string[] weaponNames = new string[0]; // 또는 무기 인스턴스 이름 앞부분
public float[] color = { 1f, 0.8f, 0.45f, 1f };
public float haloScale = 0.18f; // 사각형 한 변(m)
public float pulse = 0.25f; // 맥동 진폭(크기·밝기 ±비율)
public float pulseSeconds = 1.6f; // 맥동 주기(초)
public int light = 1; // 1 = 점광원도
public float lightRange = 1.4f;
public float lightIntensity = 1.0f;
public float tipUp = 0f; // 끝에서 더 올릴 높이(m)
public string material = "WL/Fx/WL_Mat_ChargeHalo"; // Resources 경로
}
[System.Serializable]
public class WLWeaponTipGlowJson { public int enabled = 1; public WLWeaponTipGlowRule[] rules = new WLWeaponTipGlowRule[0]; public string note = ""; }
public sealed class WLWeaponTipGlow : MonoBehaviour
{
public const string ResourcesPath = "WL/WLWeaponTipGlow";
public static int Attached; public static string LastLog = "";
static WLWeaponTipGlowJson s_cfg; static bool s_loaded;
static WLWeaponTipGlowJson Cfg
{
get
{
if (!s_loaded)
{
s_loaded = true;
var ta = Resources.Load<TextAsset>(ResourcesPath);
try { s_cfg = ta != null ? JsonUtility.FromJson<WLWeaponTipGlowJson>(ta.text) : null; } catch (System.Exception ex) { LastLog = "설정 파싱 실패 — " + ex.Message; }
}
return s_cfg;
}
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStatics() { s_loaded = false; s_cfg = null; } // 도메인 리로드 끔 대비(JSON 재읽기)
Transform _weapon, _socket, _halo; Light _light; Material _mat; WLWeaponTipGlowRule _r; float _t0; Vector3 _localTip; Color _col;
public static bool TryAttach(Transform weapon)
{
try
{
var c = Cfg; if (c == null || c.enabled == 0 || weapon == null || c.rules == null) return false;
if (weapon.GetComponent<WLWeaponTipGlow>() != null) return true;
var pc = weapon.GetComponentInParent<PCActor>(); int cls = pc != null ? pc.Get_ID() : 0;
WLWeaponTipGlowRule rule = null;
foreach (var r in c.rules)
{
if (r == null) continue;
bool byClass = r.classIds != null && System.Array.IndexOf(r.classIds, cls) >= 0;
bool byName = false;
if (r.weaponNames != null) foreach (var n in r.weaponNames) if (!string.IsNullOrEmpty(n) && weapon.name.StartsWith(n)) { byName = true; break; }
if (byClass || byName) { rule = r; break; }
}
if (rule == null) return false;
var g = weapon.gameObject.AddComponent<WLWeaponTipGlow>();
g._weapon = weapon; g._socket = weapon.parent != null ? weapon.parent : weapon; g._r = rule; g._t0 = Time.time;
g.Build();
Attached++; LastLog = "무기 끝 빛 " + weapon.name + " 직업 " + cls + " 끝(로컬) " + g._localTip.ToString("F2");
return true;
}
catch (System.Exception ex) { LastLog = "무기 끝 빛 실패 — " + ex.Message; return false; }
}
void Build()
{
var r = _r;
// 무기 끝 = 소켓에서 가장 먼 렌더러 경계 모서리
Vector3 tip = _weapon.position; float best = -1f;
foreach (var rd in _weapon.GetComponentsInChildren<Renderer>(false))
{
if (rd is ParticleSystemRenderer || !rd.enabled) continue;
var b = rd.bounds;
for (int i = 0; i < 8; i++)
{
var corner = new Vector3((i & 1) == 0 ? b.min.x : b.max.x, (i & 2) == 0 ? b.min.y : b.max.y, (i & 4) == 0 ? b.min.z : b.max.z);
float d = (corner - _socket.position).sqrMagnitude; if (d > best) { best = d; tip = corner; }
}
}
_localTip = _weapon.InverseTransformPoint(tip + Vector3.up * r.tipUp);
_col = r.color != null && r.color.Length >= 4 ? new Color(r.color[0], r.color[1], r.color[2], r.color[3]) : new Color(1f, 0.8f, 0.45f, 1f);
var q = GameObject.CreatePrimitive(PrimitiveType.Quad); q.name = "~WL_TipGlow";
var col = q.GetComponent<Collider>(); if (col != null) Destroy(col);
q.transform.SetParent(_weapon, false); q.transform.localScale = Vector3.one * r.haloScale;
var src = Resources.Load<Material>(r.material);
var mr = q.GetComponent<MeshRenderer>();
if (src != null) { _mat = new Material(src); mr.sharedMaterial = _mat; SetColor(_col); }
mr.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; mr.receiveShadows = false;
_halo = q.transform;
if (r.light != 0)
{
var lg = new GameObject("~WL_TipLight"); lg.transform.SetParent(_halo, false);
_light = lg.AddComponent<Light>(); _light.type = LightType.Point; _light.range = r.lightRange; _light.intensity = r.lightIntensity; _light.color = _col; _light.shadows = LightShadows.None;
}
}
void SetColor(Color c)
{
if (_mat == null) return;
if (_mat.HasProperty("_TintColor")) _mat.SetColor("_TintColor", c);
if (_mat.HasProperty("_BaseColor")) _mat.SetColor("_BaseColor", c);
if (_mat.HasProperty("_Color")) _mat.SetColor("_Color", c);
if (_mat.HasProperty("_EmissionColor")) _mat.SetColor("_EmissionColor", c);
}
void LateUpdate()
{
if (_halo == null || _weapon == null) return;
float k = 1f + (_r.pulse > 0f && _r.pulseSeconds > 0f ? _r.pulse * Mathf.Sin((Time.time - _t0) / _r.pulseSeconds * Mathf.PI * 2f) : 0f);
var pos = _weapon.TransformPoint(_localTip);
var cam = Camera.main;
_halo.position = pos;
if (cam != null) _halo.rotation = Quaternion.LookRotation(pos - cam.transform.position); // 쿼드 앞면이 카메라를 보게
_halo.localScale = Vector3.one * (_r.haloScale * k / Mathf.Max(0.0001f, _weapon.lossyScale.x)) ;
if (_mat != null) SetColor(new Color(_col.r, _col.g, _col.b, _col.a * Mathf.Clamp01(0.6f + 0.4f * k)));
if (_light != null) _light.intensity = _r.lightIntensity * k;
}
void OnDestroy() { if (_mat != null) Destroy(_mat); }
}
}