// Copyright (c) 2021 homuler // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. using UnityEngine; namespace Mediapipe.Unity { public interface IHierachicalAnnotation { IHierachicalAnnotation root { get; } Transform transform { get; } RectTransform GetAnnotationLayer(); UnityEngine.Rect GetScreenRect(); } public abstract class HierarchicalAnnotation : MonoBehaviour, IHierachicalAnnotation { private IHierachicalAnnotation _root; public IHierachicalAnnotation root { get { if (_root == null) { var parentObj = transform.parent == null ? null : transform.parent.gameObject; _root = (parentObj != null && parentObj.TryGetComponent(out var parent)) ? parent.root : this; } return _root; } protected set => _root = value; } public RectTransform GetAnnotationLayer() { return root.transform.parent.gameObject.GetComponent(); } public UnityEngine.Rect GetScreenRect() { return GetAnnotationLayer().rect; } public bool isActive => gameObject.activeSelf; public bool isActiveInHierarchy => gameObject.activeInHierarchy; public void SetActive(bool isActive) { if (this.isActive != isActive) { gameObject.SetActive(isActive); } } /// /// Prepare to annotate . /// If is not null, it activates itself. /// /// /// If it is activated and can be drawn. /// In effect, it returns if is null or not. /// /// Data to be annotated protected bool ActivateFor(T target) { if (target == null) { SetActive(false); return false; } SetActive(true); return true; } public virtual bool isMirrored { get; set; } public virtual RotationAngle rotationAngle { get; set; } = RotationAngle.Rotation0; protected TAnnotation InstantiateChild(GameObject prefab) where TAnnotation : HierarchicalAnnotation { var annotation = Instantiate(prefab, transform).GetComponent(); annotation.isMirrored = isMirrored; annotation.rotationAngle = rotationAngle; return annotation; } protected TAnnotation InstantiateChild(string name = "Game Object") where TAnnotation : HierarchicalAnnotation { var gameObject = new GameObject(name); gameObject.transform.SetParent(transform); return gameObject.AddComponent(); } } }