using ComponentFramework;
using ComponentFramework.Modules;
using MTV3D65;
using System;

namespace OctreeRendering
{
    class Sample : Core
    {
        protected override void Initialize()
        {
            Engine.SetSearchDirectory("Content");
#if !DEBUG
            Engine.SetDebugMode(false);
#endif
            InputEngine.Initialize(true, true);
        }

        int screenshotNumber;
        protected override void Update()
        {
            if (KeyboardState.GetKeyState(CONST_TV_KEY.TV_KEY_ESCAPE) == KeyState.Pressed)
                SampleState.ShowConsole = !SampleState.ShowConsole;

            if (KeyboardState.GetKeyState(CONST_TV_KEY.TV_KEY_1) == KeyState.Pressed)
            {
                SampleState.OctreeCullingMode = SampleState.OctreeCullingMode.Value + 1;
                if (SampleState.OctreeCullingMode > CullingMode.FurstumAndOcclusion)
                    SampleState.OctreeCullingMode = CullingMode.None;
            }

            var octreeDepth = (int)Math.Log(WorldState.Octree.Size, 2);
            var minCoarseness = SampleState.OctreeCullingMode == CullingMode.FrustumBoxIntersection ? 0 : 0;

            if (KeyboardState.GetKeyState(CONST_TV_KEY.TV_KEY_F2) == KeyState.Pressed)
                SampleState.OctreeTraversalCoarseness = Math.Min(SampleState.OctreeTraversalCoarseness + 1, octreeDepth);
            if (KeyboardState.GetKeyState(CONST_TV_KEY.TV_KEY_2) == KeyState.Pressed)
                SampleState.OctreeTraversalCoarseness = Math.Max(SampleState.OctreeTraversalCoarseness - 1, minCoarseness);

            if (KeyboardState.GetKeyState(CONST_TV_KEY.TV_KEY_F3) == KeyState.Pressed)
                SampleState.OcclusionSurfaceFactor = SampleState.OcclusionSurfaceFactor + 1;
            if (KeyboardState.GetKeyState(CONST_TV_KEY.TV_KEY_3) == KeyState.Pressed)
                SampleState.OcclusionSurfaceFactor = Math.Max(SampleState.OcclusionSurfaceFactor - 1, 1);

            if (KeyboardState.GetKeyState(CONST_TV_KEY.TV_KEY_4) == KeyState.Pressed)
                SampleState.UseSynchronousQueries = !SampleState.UseSynchronousQueries;

            if (KeyboardState.GetKeyState(CONST_TV_KEY.TV_KEY_0) == KeyState.Pressed)
                Engine.Screenshot("C:\\" + screenshotNumber++ + ".png", CONST_TV_IMAGEFORMAT.TV_IMAGE_PNG);
        }

        [ServiceDependency]
        public IKeyboardState KeyboardState { private get; set; }
        [ServiceDependency]
        public ISampleState SampleState { private get; set; }
        [ServiceDependency]
        public IWorldState WorldState { private get; set; }
    }
}
