﻿/*
MIT License

Copyright(c) 2019 Mitchel Thompson
www.angryarugula.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor;

namespace Arugula
{
    [RequireComponent(typeof(MeshFilter))]
    public class MeshSlicer : MonoBehaviour
    {
        /// <summary>
        /// Slice defines where to cut a mesh and how to stretch it
        /// </summary>
        [System.Serializable]
        public class Slice
        {
            public string name;
            public float offset;
            public Vector3 normal;
            public float shift;
            public Plane plane;

            public Slice(string name, Vector3 normal, float offset)
            {
                this.name = name;
                this.normal = normal;
                this.offset = offset;
                UpdatePlane();
            }

            public void UpdatePlane()
            {
                plane.SetNormalAndPosition(normal, normal * offset);
            }

            //TODO: optionally cache vertex indices for continuous slicing optimization
            [HideInInspector]
            internal int[] indices;
        }

        private Mesh meshInstance;
        private MeshFilter meshFilter;

        /// <summary>
        /// The base mesh to slice.
        /// </summary>
        public Mesh baseMesh;

        /// <summary>
        /// Slices array defining where to cut a mesh and how far to stretch it
        /// </summary>
        public List<Slice> slices = new List<Slice>();

        [HideInInspector]
        public bool drawBaseMesh;

        bool initialized = false;

        /// <summary>
        /// Creates slices on standard axes. WARNING: Clears all existing slices.
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="z"></param>
        public void CreateSlices(bool x, bool y, bool z)
        {
            if (baseMesh == null)
                throw new System.Exception("baseMesh must not be null!");

            slices.Clear();
            Vector3 extents = baseMesh.bounds.extents * 0.75f;
            if (x)
            {
                slices.Add(new Slice("X-", Vector3.left, extents.x));
                slices.Add(new Slice("X+", Vector3.right, extents.x));
            }

            if (y)
            {
                slices.Add(new Slice("Y-", Vector3.down, extents.y));
                slices.Add(new Slice("Y+", Vector3.up, extents.y));
            }

            if (z)
            {
                slices.Add(new Slice("Z-", Vector3.back, extents.z));
                slices.Add(new Slice("Z+", Vector3.forward, extents.z));
            }

            Init(true);
            UpdateMesh();
        }



        private void Start()
        {
            Init(true);
        }

        private void OnEnable()
        {

            if (meshInstance == null)
            {
                if (baseMesh != null)
                {
                    meshInstance = Instantiate(baseMesh);
                    meshFilter.sharedMesh = meshInstance;
                }
            }
        }

        private int[] GetVertexIndices(Plane p)
        {
            List<int> indices = new List<int>();

            Vector3[] vertices = baseMesh.vertices;

            for (int i = 0; i < vertices.Length; i++)
            {
                if (p.GetSide(vertices[i]))
                    indices.Add(i);
            }

            return indices.ToArray();
        }

        private void OnDrawGizmosSelected()
        {

            if (baseMesh != null && drawBaseMesh)
            {
                Gizmos.color = new Color(1, 1, 1, 0.2f);
                Gizmos.DrawWireMesh(baseMesh, 0, transform.position, transform.rotation, transform.lossyScale);
            }
        }

        /// <summary>
        /// Initializes references
        /// </summary>
        /// <param name="force"></param>
        public void Init(bool force = false)
        {
            if (initialized && !force)
                return;

            meshFilter = GetComponent<MeshFilter>();
            if (force)
            {
                if (meshInstance != null)
                {
                    UpdateMesh();
                }
            }
        }

        /// <summary>
        /// Force an update to the resulting mesh
        /// </summary>
        public void UpdateMesh()
        {
            if (baseMesh == null)
                return;

            if (meshFilter == null)
                meshFilter = GetComponent<MeshFilter>();
            if (meshInstance == null || meshFilter.sharedMesh == baseMesh)
            {
                meshInstance = Instantiate(baseMesh);
                meshFilter.sharedMesh = meshInstance;
            }

            Vector3[] verts = baseMesh.vertices;
            //TODO: optionally cache vertex indices for continuous slicing optimization
            foreach (var s in slices)
            {
                s.UpdatePlane();
                s.indices = GetVertexIndices(s.plane);

                foreach (var i in s.indices)
                {
                    verts[i] += s.normal * s.shift;
                }
            }

            meshInstance.vertices = verts;
            meshInstance.RecalculateBounds();
        }
    }
}
