//>>> _using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX;
using SharpDX.Direct3D11;
using SharpDX.Windows;
//<<< _using
using Framefield.Core.OperatorPartTraits;
using Framefield.Core.Rendering;
using Buffer = SharpDX.Direct3D11.Buffer;
using SharpDX.Direct3D;

namespace Framefield.Core.ID25323be5_3502_49b7_9fcf_55381996d152
{
    public class Class_Bend2 : FXSourceCodeFunction, IFXSceneSourceCode, IMeshSupplier
    {
        //>>> _inputids
        private enum InputId
        {
            Code = 0,
            Scene = 1,
            CenterX = 2,
            CenterY = 3,
            CenterZ = 4,
            AxisX = 5,
            AxisY = 6,
            AxisZ = 7,
            AngleStart = 8,
            AngleEnd = 9,
            OrientationX = 10,
            OrientationY = 11,
            OrientationZ = 12,
            SpiralOffset = 13,
            Radius = 14,
            RotateDirection = 15,
            RotateTilt = 16
        }
        //<<< _inputids

        public Class_Bend2()
        {
            _meshCollector = new MeshCollector(this);
        }

        public override void Dispose() 
        {
            Utilities.DisposeObj(ref _mesh);
            base.Dispose();
        }

        public void AddMeshesTo(ICollection<Mesh> meshes)
        {
            UpdateMesh(new OperatorPartContext(), OperatorPart.Connections);
            if (_mesh != null)
                meshes.Add(_mesh);
        }

        public override OperatorPartContext Eval(OperatorPartContext context, List<OperatorPart> inputs, int outputIdx)
        {
            try
            {
                UpdateMesh(context, inputs);

                if (_mesh.Vertices != null)
                {
                    // render stream output to screen or whatever target is set
                    context.Renderer.SetupEffect(context);
                    context.Renderer.Render(_mesh, context);
                }
            }
            catch (Exception exception)
            {
                Logger.Error(this, "Load Effect error: {0}", exception.Message);
            }

            return context;
        }

        bool _firstEval = true;
        private void UpdateMesh(OperatorPartContext context, List<OperatorPart> inputs)
        {
            if (_firstEval)
            {
                for (int i = 0; i < NumCodes(); ++i)
                    Compile(i);
                _firstEval = false;
                Changed = true;
            }

            if (!Changed && _mesh.Vertices != null)
                return;

            //>>> _params
            var Code = inputs[(int)InputId.Code].Eval(context).Text;
            var Scene = inputs[(int)InputId.Scene];
            var CenterX = inputs[(int)InputId.CenterX].Eval(context).Value;
            var CenterY = inputs[(int)InputId.CenterY].Eval(context).Value;
            var CenterZ = inputs[(int)InputId.CenterZ].Eval(context).Value;
            var Center = new Vector3(CenterX, CenterY, CenterZ);
            var AxisX = inputs[(int)InputId.AxisX].Eval(context).Value;
            var AxisY = inputs[(int)InputId.AxisY].Eval(context).Value;
            var AxisZ = inputs[(int)InputId.AxisZ].Eval(context).Value;
            var Axis = new Vector3(AxisX, AxisY, AxisZ);
            var AngleStart = inputs[(int)InputId.AngleStart].Eval(context).Value;
            var AngleEnd = inputs[(int)InputId.AngleEnd].Eval(context).Value;
            var OrientationX = inputs[(int)InputId.OrientationX].Eval(context).Value;
            var OrientationY = inputs[(int)InputId.OrientationY].Eval(context).Value;
            var OrientationZ = inputs[(int)InputId.OrientationZ].Eval(context).Value;
            var Orientation = new Vector3(OrientationX, OrientationY, OrientationZ);
            var SpiralOffset = inputs[(int)InputId.SpiralOffset].Eval(context).Value;
            var Radius = inputs[(int)InputId.Radius].Eval(context).Value;
            var RotateDirection = inputs[(int)InputId.RotateDirection].Eval(context).Value;
            var RotateTilt = inputs[(int)InputId.RotateTilt].Eval(context).Value;
            var Rotate = new Vector2(RotateDirection, RotateTilt);
            //<<< _params

            if (Scene.Func.Changed || _mesh.Vertices == null)
            {
                //Logger.Info(this, "collect meshes");
                _meshCollector.Collect(Scene);
                Scene.Func.Changed = false;
            }

            var inputMesh = _meshCollector.FirstMeshOrDefault;
            if (inputMesh == null)
                return;

            _mesh.AttributesSize = inputMesh.AttributesSize;
            _mesh.NumTriangles = inputMesh.NumTriangles;
            _mesh.InputElements = inputMesh.InputElements;
            if (_mesh.Vertices == null || _mesh.Vertices.Description.SizeInBytes != inputMesh.Vertices.Description.SizeInBytes)
            {
                if (_mesh.Vertices != null)
                    _mesh.Vertices.Dispose();

                _mesh.Vertices = new Buffer(D3DDevice.Device, new BufferDescription()
                                                                    {
                                                                        BindFlags = BindFlags.StreamOutput | BindFlags.VertexBuffer,
                                                                        CpuAccessFlags = CpuAccessFlags.None,
                                                                        OptionFlags = ResourceOptionFlags.None,
                                                                        SizeInBytes = _mesh.NumTriangles*inputMesh.AttributesSize*3,
                                                                        Usage = ResourceUsage.Default
                                                                    });
            }
            
            var up = new Vector3(0,1,0);
            var m =  Matrix.Identity;
            Matrix.RotationAxis( ref up, RotateDirection / 180f*3.141578f, out m);
            
            var rotatedOrientation  = Vector3.Transform( Orientation, m);
            var rotatedAxis = Vector3.Transform( Axis, m);
            
            SetScalar("AngleStart", AngleStart / 180f * 3.141578f);
            SetScalar("AngleEnd",   AngleEnd / 180f * 3.141578f);
            SetScalar("SpiralOffset", SpiralOffset);
            SetScalar("Radius",     Radius);
            SetVector("Center",     Center);
            SetVector("Orientation", Vector3.Normalize( new Vector3( rotatedOrientation.X , rotatedOrientation.Y, rotatedOrientation.Z)));
            SetVector("Axis",       Vector3.Normalize( new Vector3( rotatedAxis.X, rotatedAxis.Y, rotatedAxis.Z)));

            context.D3DDevice.ImmediateContext.StreamOutput.SetTargets(new [] { new StreamOutputBufferBinding(_mesh.Vertices, 0) });
            context.D3DDevice.ImmediateContext.OutputMerger.DepthStencilState = new DepthStencilState(context.D3DDevice,
                                                                                                        new DepthStencilStateDescription()
                                                                                                            {
                                                                                                                IsDepthEnabled = false,
                                                                                                                IsStencilEnabled = false
                                                                                                            });
            context.D3DDevice.ImmediateContext.InputAssembler.InputLayout = context.InputLayout;
            context.D3DDevice.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList;
            context.D3DDevice.ImmediateContext.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(inputMesh.Vertices, inputMesh.AttributesSize, 0));
            var technique = _effect.GetTechniqueByIndex(0);
            technique.GetPassByIndex(0).Apply(context.D3DDevice.ImmediateContext);
            context.D3DDevice.ImmediateContext.Draw(_mesh.NumTriangles*3, 0);
            context.D3DDevice.ImmediateContext.StreamOutput.SetTargets(new [] { new StreamOutputBufferBinding(null, 0) });

            Changed = false;
        }

        private Mesh _mesh = new Mesh();
        private MeshCollector _meshCollector;
    }
}


