/*
 * This file is part of Afterwarp Framework (http://afterwarp.io).
 * Copyright (c) 2015 - 2025 Dr. Yuriy Kotsarenko. All rights reserved.
 *
 * This example source code is licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

// This example illustrates the following features:
//  * Drawing a simple 3D cube with ambient occlusion (not really visible as the cube is a very flat and
//    simple) and a bloom effect, with a depth pre-pass. Optionally, the cube can also be rendered with
//    a texture. This illustrates how the rendering pipeline generally works.

namespace Cube
{
  using System.Numerics;
  using Afterwarp;
  using TextRenderer = Afterwarp.TextRenderer;
  using Application = System.Windows.Forms.Application;

  public partial class MainForm : Form
  {
    private Device device;
    private SwapChain swapChain;
    private Canvas canvas;
    private TextRenderer textRenderer;
    private Timer timer;

    private SceneLights lights;
    private TextureCabinet textureCabinet;
    private Scene sceneDepthNormals;
    private Scene sceneModeling;
    private MeshModel modelCube;
    private Texture textureCube;

    private Matrix4x4 world;
    private Matrix4x4 view;
    private Matrix4x4 projection;
    private int ticks;
    private bool textured;

    private Vector2 displaySize;
    private float displayScale = 1.0f;

    private static readonly VertexElement[] vertexElements = [
      new VertexElement("vertexPosition", ElementFormat.Float, 3),
      new VertexElement("vertexNormal", ElementFormat.Float, 3),
      new VertexElement("vertexTexCoord", ElementFormat.Float, 2)
    ];

    public MainForm()
    {
      InitializeComponent();
      Application.Idle += Application_Idle;
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
      displaySize = new Vector2(ClientSize.Width, ClientSize.Height);
      try
      {
        device = new Device(DeviceTechnology.Direct3D);
        swapChain = new SwapChain(device, Handle);
        canvas = new Canvas(device);
        textRenderer = new TextRenderer(canvas, new Point(512, 512));
        timer = new Timer();

        lights = new SceneLights(device);
        textureCabinet = new TextureCabinet(device, new Point(ClientSize.Width, ClientSize.Height),
          TextureFidelity.High, 8, PixelFormat.D32F)
        {
          Attributes =
            TextureCabinet.Attribute.BloomCubic |
            TextureCabinet.Attribute.Bloom
        };

        sceneDepthNormals = Scene.CreateDepthNormals(device);
        sceneDepthNormals.SetVertexElements(0, vertexElements);

        sceneModeling = Scene.CreateModeling(device);
        sceneModeling.SetVertexElements(0, vertexElements);

        lights.Add(new SceneLight(
          new FloatColorRGB(0x00FFFFFFu),
          new FloatColorRGB(0x00FFFFFFu),
          new FloatColorRGB(0x00FFFFFFu),
          new Vector3(300.0f, 800.0f, -300.0f),
          default));

        // Create cube mesh model
        using (MeshBuffer buffer = new())
        {
          buffer.Cube(1, 1, 1, default, new Vector3(100.0f, 0.0f, 0.0f), new Vector3(0.0f, 100.0f, 0.0f),
            new Vector3(0.0f, 0.0f, 100.0f));

          // Replace above statement with the following to create a 3D sphere instead.
          // buffer.SuperEllipse(32, 32, default, new Vector3(75.0f), 0.0f, MathF.PI * 2.0f, 1.0f,
          //  MathF.PI * -0.5f, MathF.PI * 0.5f, 1.0f);

          modelCube = buffer.Model(device, vertexElements);
        }
        textureCube = new Texture(device, "../../../../Media/ForkLift.png", PixelFormat.RGBA8,
          Texture.Attribute.MipMapping);
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message, "Initialization failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
        Application.Exit();
        return;
      }
      timer.Speed = 60.0;
      view = Utility.MatrixLookAt4x4(new Vector3(0.0f, 50.0f, -300.0f), default, Vector3.UnitY);

      SetStyle(ControlStyles.Opaque, true);
      SetStyle(ControlStyles.UserPaint, true);
      SetStyle(ControlStyles.AllPaintingInWmPaint, true);
      SetStyle(ControlStyles.DoubleBuffer, false);
    }

    private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
    {
      textureCube?.Dispose();
      modelCube?.Dispose();
      sceneModeling?.Dispose();
      sceneDepthNormals?.Dispose();
      textureCabinet?.Dispose();
      lights?.Dispose();

      timer?.Dispose();
      textRenderer?.Dispose();
      canvas?.Dispose();
      swapChain?.Dispose();
      device?.Dispose();
    }

    private void MainForm_Resize(object sender, EventArgs e)
    {
      if (WindowState != FormWindowState.Minimized && device is not null)
      {
        displaySize = new Vector2(ClientSize.Width, ClientSize.Height);
        swapChain.Resize(new Point(displaySize));
        textureCabinet.Size = new Point(displaySize);
      }
    }

    private void MainForm_Paint(object sender, PaintEventArgs e)
    {
      displayScale = DeviceDpi / 96.0f;

      world = Matrix4x4.CreateRotationY(ticks * 0.022f) * Matrix4x4.CreateRotationX(ticks * 0.0371f);
      projection = Utility.MatrixPerspective4x4(MathF.PI * 0.25f, displaySize.X / displaySize.Y,
        10.0f, 2000.0f);

      // Perform light assignment for 3D scene.
      lights.Size = new Point(displaySize);

      // Only one light is used for the entire scene, so only minimal light culling is required.
      lights.CullingMode = ClustersCullingMode.Performance;
      lights.ClusterSize = 512;
      lights.DepthSlices = 1;

      lights.Execute(view, projection);

      // Prepare scene's attributes.
      const uint sceneAttributes = Scene.Attribute.Normals;

      // Depth pre-pass.
      textureCabinet.Clear(TextureCabinetPass.Depth);
      textureCabinet.Begin(TextureCabinetPass.Depth);
      try
      {
        sceneDepthNormals.Attributes = sceneAttributes;
        sceneDepthNormals.View = view;
        sceneDepthNormals.Projection = projection;

        sceneDepthNormals.Begin();
        try
        {
          RenderCube(sceneDepthNormals);
        }
        finally
        {
          sceneDepthNormals.End();
        }
      }
      finally
      {
        textureCabinet.End();
      }
      textureCabinet.Filter(TextureCabinetFilterType.Occlusion, projection);

      // Render main scene.
      textureCabinet.Clear(TextureCabinetPass.Color, new FloatColor(0.25f, 0.25f, 0.25f, 1.0f));
      textureCabinet.Begin(TextureCabinetPass.Color);
      try
      {
        sceneModeling.Lights = lights;
        sceneModeling.TextureCabinet = textureCabinet;
        sceneModeling.SetTexture(SceneTextureType.Albedo, textured ? textureCube : null);

        sceneModeling.Attributes = sceneAttributes;
        sceneModeling.View = view;
        sceneModeling.Projection = projection;

        sceneModeling.Prepare();
        sceneModeling.Begin();
        try
        {
          RenderCube(sceneModeling);
        }
        finally
        {
          sceneModeling.End();
        }
      }
      finally
      {
        textureCabinet.End();
      }
      textureCabinet.Filter(TextureCabinetFilterType.Bloom);

      swapChain.Begin();
      try
      {
        // Clear the device to discard previous swap-chain contents, which may improve performance.
        device.Clear(DeviceClear.Color, new FloatColor(0xFF404040u));

        // Present 3D scene on the screen.
        textureCabinet.Present();

        // Draw 2D text on top of 3D scene.
        canvas.Begin();
        try
        {
          canvas.ContextState = CanvasContextState.FlatText;
          canvas.SamplerState = CanvasSamplerState.Default;

          FontParameters parameters = new("Segoe UI", 14.0f * displayScale, FontWeight.SemiBold);
          parameters.Effect.BorderType = FontBorder.SemiHeavy;
          parameters.Effect.BorderBrightness = 1.0f;
          parameters.Effect.FillBrightness = 0.0f;
          parameters.Effect.ShadowBrightness = 0.75f;
          parameters.Effect.ShadowOpacity = 1.0f;
          textRenderer.Parameters = parameters;

          textRenderer.Draw(new Vector2(8.0f * displayScale, 4.0f * displayScale),
            string.Format("Direct3D ({0}.{1}), features: {2}.{3}",
            device.TechVersion >> 8, (device.TechVersion >> 4) & 0xF,
            device.TechFeatureVersion >> 8, (device.TechFeatureVersion >> 4) & 0xF),
            new ColorPair(0xFF40E0FFu, 0xFF2020FFu), 1.0f);

          textRenderer.DrawAligned(new Vector2(4.0f * displayScale, displaySize.Y - 4.0f * displayScale),
            "Press Space to switch between colored and textured cube.",
            new ColorPair(0xA0FFFFFFu), TextAlignment.Start, TextAlignment.End);

          textRenderer.DrawAligned(new Vector2(
            displaySize.X - 8.0f * displayScale, displaySize.Y - 6.0f * displayScale),
            $"Frame Rate: {(int)MathF.Round(timer.FrameRate)}", new ColorPair(0xFF40E0FFu, 0xFF2020FFu),
            TextAlignment.End, TextAlignment.End);
        }
        finally
        {
          canvas.End();
        }
      }
      finally
      {
        swapChain.End();
      }
      timer.Update();
      ticks += timer.ExtractTokens;
    }

    private void RenderCube(Scene scene)
    {
      if (scene.Equals(sceneModeling))
      {
        ObjectMaterial material = ObjectMaterial.Default;
        if (textured)
        {
          material.AmbientColor = new FloatColorRGB(0x00404040u);
          material.AlbedoColor = new FloatColor(0xFFFFFFFFu);
        }
        else
        {
          material.AmbientColor = new FloatColorRGB(0x00004000u);
          material.AlbedoColor = new FloatColor(0xA000FF00u);
        }
        material.SpecularExponent = 4.0f;
        material.SpecularColor = new FloatColorRGB(0x00FFFFFFu);
        scene.Material = material;
      }
      scene.World = world;
      modelCube.Draw(scene.Program);
    }

    private void Application_Idle(object sender, EventArgs e)
    {
      Invalidate(); // Continuously repaint the form.
    }

    private void MainForm_KeyDown(object sender, KeyEventArgs e)
    {
      if (e.KeyCode == Keys.Space)
        textured = !textured;
      else if (e.KeyCode == Keys.Escape)
        Close();
    }
  }
}