#nullable enable
using System;
using UnityEngine;
using UnityEngine.UIElements;
namespace UVC.UIToolkit
{
///
/// Vector4(4D 벡터) 입력 필드 컴포넌트.
/// Unity Vector4Field를 래핑하여 커스텀 스타일을 적용합니다.
/// X, Y, Z, W 네 개의 float 값을 입력받습니다.
///
///
/// Vector4란?
/// Vector4는 4개의 float 값을 저장하는 구조체입니다.
/// 주로 다음 용도로 사용됩니다:
/// - 동차 좌표(Homogeneous coordinates): 3D 변환에서 이동을 포함한 행렬 연산
/// - 색상(RGBA): Red, Green, Blue, Alpha 값 (0~1 범위)
/// - 쉐이더 파라미터: 커스텀 쉐이더에 전달하는 4개의 값
/// - 사원수(Quaternion)와 유사한 구조로 회전 데이터 저장
///
/// - Validation 함수를 통한 입력 검증 (FocusOut 시 자동 호출)
/// - 에러 상태 시 붉은 외곽선 + 에러 메시지 표시
///
///
///
/// C# 코드에서 사용:
///
/// // 기본 Vector4 필드 생성
/// var vec4Field = new UTKVector4Field();
/// vec4Field.label = "쉐이더 파라미터";
///
/// // 초기값 설정
/// vec4Field.Value = new Vector4(1, 0.5f, 0.5f, 1);
///
/// // 값 변경 이벤트 처리
/// vec4Field.OnValueChanged += (vec) => {
/// Debug.Log($"파라미터: X={vec.x}, Y={vec.y}, Z={vec.z}, W={vec.w}");
/// };
///
/// // 라벨 커스터마이징 (RGBA 색상용)
/// vec4Field.XLabel = "R";
/// vec4Field.YLabel = "G";
/// vec4Field.ZLabel = "B";
/// vec4Field.WLabel = "A";
///
/// // 비활성화
/// vec4Field.IsEnabled = false;
///
/// // 읽기 전용 (사용자가 수정할 수 없음)
/// var readOnlyField = new UTKVector4Field("고정 파라미터");
/// readOnlyField.Value = new Vector4(1, 0.5f, 0.5f, 1);
/// readOnlyField.IsReadOnly = true;
///
/// Validation (입력 검증):
///
/// // 검증 함수 설정 (Func)
/// var colorField = new UTKVector4Field("색상");
/// colorField.ErrorMessage = "알파 값은 0~1 사이여야 합니다.";
/// colorField.Validation = () => colorField.Value.w >= 0 && colorField.Value.w <= 1;
/// // → FocusOut 시 자동으로 검증
/// // → 실패 시 붉은 외곽선 + 에러 메시지 표시, 통과 시 자동 해제
///
/// // 강제 검증 호출 (예: 폼 제출 버튼 클릭 시)
/// bool isValid = colorField.Validate();
/// if (!isValid) return; // 검증 실패
///
/// // 에러 수동 해제
/// colorField.ClearError();
///
/// // 에러 메시지 직접 설정 (Validation 없이, 서버 오류 등)
/// vec4Field.ErrorMessage = "서버 오류가 발생했습니다.";
/// vec4Field.ErrorMessage = ""; // 오류 제거
///
/// UXML에서 사용:
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
/// Label Min-Width 설정:
///
/// // label이 있을 때 .unity-label의 min-width를 설정
/// var vec4Field = new UTKVector4Field("값");
/// vec4Field.LabelMinWidth = 120f; // 120px
///
/// 실제 활용 예시:
///
/// // 머티리얼 쉐이더 파라미터 설정
/// var shaderParam = new UTKVector4Field("_MainTex_ST");
/// shaderParam.XLabel = "Tile X";
/// shaderParam.YLabel = "Tile Y";
/// shaderParam.ZLabel = "Offset X";
/// shaderParam.WLabel = "Offset Y";
/// shaderParam.Value = new Vector4(1, 1, 0, 0); // 기본 타일링
/// shaderParam.OnValueChanged += (vec) => {
/// material.SetVector("_MainTex_ST", vec);
/// };
///
///
[UxmlElement]
public partial class UTKVector4Field : Vector4Field, IDisposable
{
#region Constants
private const string USS_PATH = "UIToolkit/Input/UTKVector4Field";
#endregion
#region Fields
private bool _disposed;
private bool _isEnabled = true;
private bool _isReadOnly = false;
private string _xLabel = "X";
private string _yLabel = "Y";
private string _zLabel = "Z";
private string _wLabel = "W";
private string _errorMessage = "";
private float _labelMinWidth = -1f;
private Func? _validation;
private Label? _errorLabel;
#endregion
#region Events
/// 값 변경 이벤트
public event Action? OnValueChanged;
#endregion
#region Properties
/// 활성화 상태
[UxmlAttribute("is-enabled")]
public bool IsEnabled
{
get => _isEnabled;
set
{
_isEnabled = value;
SetEnabled(value);
EnableInClassList("utk-vector4field--disabled", !value);
}
}
/// 현재 값
public Vector4 Value
{
get => value;
set => this.value = value;
}
/// X축 라벨
[UxmlAttribute("x-label")]
public string XLabel
{
get => _xLabel;
set
{
_xLabel = value;
UpdateAxisLabels();
}
}
/// Y축 라벨
[UxmlAttribute("y-label")]
public string YLabel
{
get => _yLabel;
set
{
_yLabel = value;
UpdateAxisLabels();
}
}
/// Z축 라벨
[UxmlAttribute("z-label")]
public string ZLabel
{
get => _zLabel;
set
{
_zLabel = value;
UpdateAxisLabels();
}
}
/// W축 라벨
[UxmlAttribute("w-label")]
public string WLabel
{
get => _wLabel;
set
{
_wLabel = value;
UpdateAxisLabels();
}
}
/// 읽기 전용 상태
[UxmlAttribute("is-readonly")]
public bool IsReadOnly
{
get => _isReadOnly;
set
{
_isReadOnly = value;
UpdateReadOnlyState();
EnableInClassList("utk-vector4field--readonly", value);
}
}
/// 에러 메시지. 비어있지 않으면 에러 상태로 표시
[UxmlAttribute("error-message")]
public string ErrorMessage
{
get => _errorMessage;
set
{
_errorMessage = value;
var hasError = !string.IsNullOrEmpty(value);
EnableInClassList("utk-vector4field--error", hasError);
UpdateErrorLabel(hasError ? value : null);
}
}
/// 검증 함수. FocusOut 시 호출되어 false 반환 시 ErrorMessage 표시
public Func? Validation
{
get => _validation;
set => _validation = value;
}
/// label이 있을 때 .unity-label의 min-width (px). -1이면 미설정
[UxmlAttribute("label-min-width")]
public float LabelMinWidth
{
get => _labelMinWidth;
set
{
_labelMinWidth = value;
ApplyLabelMinWidth();
}
}
#endregion
#region Constructor
public UTKVector4Field() : base()
{
UTKThemeManager.Instance.ApplyThemeToElement(this);
var uss = Resources.Load(USS_PATH);
if (uss != null)
{
styleSheets.Add(uss);
}
SetupStyles();
SetupEvents();
SubscribeToThemeChanges();
}
public UTKVector4Field(bool isReadOnly) : this()
{
_isReadOnly = isReadOnly;
UpdateReadOnlyState();
}
public UTKVector4Field(string label, bool isReadOnly = false) : this()
{
this.label = label;
_isReadOnly = isReadOnly;
UpdateReadOnlyState();
}
#endregion
#region Setup
private void SetupStyles()
{
AddToClassList("utk-vector4field");
// 초기 라벨 설정
schedule.Execute(() =>
{
UpdateAxisLabels();
ApplyLabelMinWidth();
});
}
private void SetupEvents()
{
RegisterCallback>(OnFieldValueChanged);
RegisterCallback(OnFocusOut);
}
private void SubscribeToThemeChanges()
{
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
RegisterCallback(OnAttachToPanelForTheme);
RegisterCallback(OnDetachFromPanelForTheme);
}
private void OnAttachToPanelForTheme(AttachToPanelEvent evt)
{
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
UTKThemeManager.Instance.ApplyThemeToElement(this);
}
private void OnDetachFromPanelForTheme(DetachFromPanelEvent evt)
{
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
}
private void OnThemeChanged(UTKTheme theme)
{
UTKThemeManager.Instance.ApplyThemeToElement(this);
}
private void UpdateAxisLabels()
{
// Vector4Field의 내부 FloatField들을 찾아서 라벨 변경
var floatFields = this.Query().ToList();
if (floatFields.Count >= 4)
{
floatFields[0].label = _xLabel;
floatFields[1].label = _yLabel;
floatFields[2].label = _zLabel;
floatFields[3].label = _wLabel;
}
}
private void UpdateReadOnlyState()
{
// 내부 FloatField들의 TextInput을 찾아서 읽기 전용 설정
var textInputs = this.Query>().ToList();
foreach (var textInput in textInputs)
{
textInput.isReadOnly = _isReadOnly;
}
}
private void ApplyLabelMinWidth()
{
if (string.IsNullOrEmpty(label)) return;
var labelElement = this.Q