using Cryville.Common.Pdt; using UnityEngine; namespace Cryville.Crtr.Components { public abstract class SpriteBase : MeshBase { public SpriteBase() { SubmitProperty("bound", new op_set_bound(this)); SubmitProperty("pivot", new PropOp.Vector2(v => Pivot = v)); SubmitProperty("scale", new PropOp.Vector2(v => Scale = v)); SubmitProperty("ui", new PropOp.Boolean(v => UI = v)); } #pragma warning disable IDE1006 class op_set_bound : PdtOperator { readonly SpriteBase _self; public op_set_bound(SpriteBase self) : base(2) { _self = self; } protected override void Execute() { _self.SetBound( GetOperand(0).As(), GetOperand(1).As() ); } } #pragma warning restore IDE1006 Vector2 _scale = Vector2.one; public Vector2 Scale { get { return _scale; } set { _scale = value; UpdateScale(); } } protected virtual void UpdateScale() { if (!mesh.Initialized) return; var s = BaseScale; var ss = new Vector3(_scale.x, 1, _scale.y); s.Scale(ss); mesh.MeshTransform.localScale = s; OnPivotUpdate(); } protected abstract Vector3 BaseScale { get; } protected virtual Vector3 BaseSize { get { return Vector3.one; } } Vector2 _pivot; public Vector2 Pivot { get { return _pivot; } set { _pivot = value; OnPivotUpdate(); } } protected void OnPivotUpdate() { if (!mesh.Initialized) return; var r = new Vector3(_pivot.x - BasePivot.x, 0, _pivot.y - BasePivot.y); r.Scale(mesh.MeshTransform.localScale); r.Scale(BaseSize); mesh.MeshTransform.localPosition = -r; } protected virtual Vector2 BasePivot { get { return Vector2.zero; } } public void SetBound(Vector2 piv, Vector3 pos) { var r = Quaternion.Inverse(transform.rotation); var da = piv - Pivot; var dp = r * (pos - transform.localPosition); if (da.x != 0) _scale.x = dp.x / da.x; if (da.y != 0) _scale.y = dp.z / da.y; } static readonly Quaternion uirot = Quaternion.Euler(new Vector3(-90, 0, 0)); bool _ui; public bool UI { get { return _ui; } set { _ui = value; if (_ui) transform.localRotation = uirot; } } protected void InternalInit(string meshName = "quad") { mesh.Init(transform); mesh.Renderer.sharedMaterials = materials = new Material[] { MeshWrapper.NewMaterial() }; mesh.Mesh = Mesh.Instantiate(GenericResources.Meshes[meshName]); UpdateColor(); UpdateScale(); UpdateZIndex(); } } }