/*
 * This file is part of Afterwarp Framework (http://afterwarp.io).
 * Copyright (c) 2015 - 2025 Dr. Yuriy Kotsarenko. All rights reserved.
 *
 * 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:
//  * Creating and filling texture from system memory in real-time to produce a plasma-looking effect.
//  * Accurate time-based movement independent of rendering frame rate.

#ifdef _WIN32
  #include "resource.h"
  #include <SDKDDKVer.h>

  #define WIN32_LEAN_AND_MEAN
  #include <windows.h>
  // Remove conflicting Windows macros.
  #undef KEY_EXECUTE
#endif

#include <stdio.h>

#include "Afterwarp.h"
#include "Afterwarp.Vectors.h"

#define AFTERWARP_VECTORS_IMPLEMENTATION
#include "Afterwarp.Vectors.h"

#include "PlasmaPalette.h"

// Global variables.

// Display characteristics.
static Point displaySize = {800, 600};
static float displayScale = 1.0f;

// Base Afterwarp interfaces.
static Application* application = NULL;
static Device* device = NULL;
static SwapChain* swapChain = NULL;
static Canvas* canvas = NULL;
static TextRenderer* textRenderer = NULL;
static Timer* timer = NULL;

// Textures for performing work.
static Texture* texturePlasma = NULL;
static Surface* surfacePlasma = NULL;
static Texture* textureScanline = NULL;

// Lookup tables.
static uint16_t lookupSin[2048];
static uint16_t lookupCos[2048];

// Animation indices.
static Point shift = {0};
static int32_t paletteIndex = 0;

// Forward declarations.

static void outputError(char const* message);

// Implementation.

LibraryBool applicationCreate(Application* application, void* user)
{
  device = DeviceCreate(application, DEVICE_TECHNOLOGY_UNKNOWN, 0);
  if (!device)
  {
    outputError("Could not create graphics device.");
    return false;
  }
  swapChain = SwapChainCreate(device, ApplicationGetWindowHandle(application), &displaySize,
    PIXEL_FORMAT_RGBA8, PIXEL_FORMAT_UNKNOWN, 0, false);
  if (!swapChain)
  {
    outputError("Could not create rendering swap-chain.");
    return false;
  }
#ifndef _WIN32
  {
    char const* fileNames[] = {"../../../../Media/afterwarp.ico"};

    if (!ApplicationSetIconsFromFiles(application, fileNames, sizeof(fileNames) / sizeof(fileNames[0])))
    {
      outputError("Could not load application icon.");
      return false;
    }
  }
#endif
  canvas = CanvasCreate(device);
  if (!canvas)
  {
    outputError("Could not create rendering canvas.");
    return false;
  }
  textRenderer = TextRendererCreate(canvas, &(Point){512, 512}, PIXEL_FORMAT_LA8, false);
  if (!textRenderer)
  {
    outputError("Could not create text rendering module.");
    return false;
  }
  timer = TimerCreate();
  if (!timer)
  {
    outputError("Could not create timer module.");
    return false;
  }

  surfacePlasma = SurfaceCreate(512, 512, PIXEL_FORMAT_RGBA8);
  if (!surfacePlasma)
  {
    outputError("Could not create plasma surface.");
    return false;
  }
  texturePlasma = TextureCreate(device, &(TextureParameters){.width = 512, .height = 512,
    .attributes = TEXTURE_ATTRIBUTE_DYNAMIC, .format = PIXEL_FORMAT_RGBA8});
  if (!texturePlasma)
  {
    outputError("Could not create plasma texture.");
    return false;
  }

  textureScanline = TextureCreate(device, &(TextureParameters){.width = 64, .height = 64,
    .format = PIXEL_FORMAT_L8});
  if (!textureScanline)
  {
    outputError("Could not create scanline texture.");
    return false;
  }
  { // Generate scanline texture content.
    uint8_t pixels[64 * 64];

    for (int32_t i = 0; i < 64 * 64; ++i)
      pixels[i] = (i / 64) % 2 == 1 ? 174 : 255;

    // Update texture contents with the aforementioned values.
    TextureUpdate(textureScanline, pixels, 0, 0, NULL, 0);
  }
  // Create lookup tables.
  for (int32_t i = 0; i < 2048; ++i)
  {
    lookupSin[i] = (int32_t)(trunc(sin(2.0 * M_PI * i / 2048.0) * 1024.0) + 1024) & 0x7FF;
    lookupCos[i] = (int32_t)(trunc(cos(2.0 * M_PI * i / 2048.0) * 1024.0) + 1024) & 0x7FF;
  }
  return true;
}

void applicationDestroy(Application* application, void* user)
{
  TextureDestroy(texturePlasma);
  SurfaceDestroy(surfacePlasma);
  TimerDestroy(timer);
  TextRendererDestroy(textRenderer);
  CanvasDestroy(canvas);
  SwapChainDestroy(swapChain);
  DeviceDestroy(device);
}

void applicationResize(Application* application, void* user)
{
  Rect clientRect = {0};
  ApplicationGetClientRect(application, &clientRect);

  displaySize = rectGetSize(clientRect);

  SwapChainResize(swapChain, &displaySize);
}

void applicationRender(Application* application, void* user)
{
  displayScale = ApplicationGetWindowScale(application);

  for (int32_t j = 0; j < 512; ++j)
  {
    Color* dest = (Color*)((char*)SurfaceGetBits(surfacePlasma) + (SurfaceGetPitch(surfacePlasma) *
      (size_t)j));

    int32_t const addX = lookupSin[((j << 2) + shift.x) & 0x7FF];
    int32_t const addC = lookupCos[((j << 2) + shift.y) & 0x7FF];

    for (int32_t i = 0; i < 512; ++i)
    {
      int32_t index = (lookupSin[((i << 2) + addX) & 0x7FF] + addC) & 0x7FF;
      if (index > 1023)
        index = 2047 - index;

//      *dest++ = MakeColorGray(127 + ((index * 255) / 0x7FF), 255);
      *dest++ = plasmaPalette[((index / 4) + paletteIndex) & 0x3FF];
    }
  }
  TextureCopyFromSurface(texturePlasma, surfacePlasma, 0, NULL, NULL, 0);

  DeviceTechnology const technology = DeviceGetTechnology(device);

  bool const flipped = technology == DEVICE_TECHNOLOGY_OPENGL || technology == DEVICE_TECHNOLOGY_OPENGL_ES;
  Quad const texCoords = flipped ? quadFlip(quadUnity) : quadUnity;

  if (SwapChainBegin(swapChain))
  {
    FloatColor const clearColor = floatColor(0xFFE1E2E6u);
    DeviceClear(device, DEVICE_CLEAR_LAYER_COLOR, &clearColor, 1.0f, 0);

    if (CanvasBegin(canvas))
    {
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_SCENE);
      CanvasSetSamplerState(canvas, &(CanvasSamplerState){TEXTURE_FILTER_NEAREST, TEXTURE_FILTER_NEAREST});

      // Draw plasma texture tiled.
      for (int32_t j = 0; j <= displaySize.y / 512; ++j)
        for (int32_t i = 0; i <= displaySize.x / 512; ++i)
        {
          Quad const quad = makeQuad(i * 512.0f, j * 512.0f, 512.0f, 512.0f);
          CanvasTexturedQuad(canvas, texturePlasma, &quad, &texCoords, &colorRectWhite,
            BLENDING_EFFECT_COPY);
        }

      // Apply scanline effect.
      for (int32_t j = 0; j <= displaySize.y / 64; ++j)
        for (int32_t i = 0; i <= displaySize.x / 64; ++i)
        {
          Quad const quad = makeQuad(i * 64.0f, j * 64.0f, 64.0f, 64.0f);
          CanvasTexturedQuad(canvas, textureScanline, &quad, &texCoords, &colorRectWhite,
            BLENDING_EFFECT_MULTIPLY);
        }

      // Prepare canvas for text output.
      CanvasSetContextState(canvas, CANVAS_CONTEXT_STATE_FLAT_TEXT);

      { // Draw technology string.
        FontParameters parameters = {
          .family = "Segoe UI", .size = 16.0f * displayScale, .weight = FONT_WEIGHT_SEMI_BOLD,
          .stretch = FONT_STRETCH_NORMAL, .slant = FONT_SLANT_NONE, .effect = fontEffectDefault};
        parameters.effect.borderType = FONT_BORDER_SEMI_HEAVY;
        parameters.effect.borderBrightness = 1.0f;
        parameters.effect.fillBrightness = 0.0f;
        parameters.effect.shadowBrightness = 0.75f;
        parameters.effect.shadowOpacity = 1.0f;
        TextRendererSetFontParameters(textRenderer, &parameters);

        char const* const textDirect3D = "Direct3D (%d.%d), features: %d.%d";
        char const* const textOpenGL = "OpenGL (%d.%d+), features: %d.%d";

        char const* const formatText = DeviceGetTechnology(device) == DEVICE_TECHNOLOGY_DIRECT3D ?
          textDirect3D : textOpenGL;

        char text[128];

        snprintf(text, sizeof(text), "Frame Rate: %1.0f", TimerGetFrameRate(timer));

        TextRendererDrawAligned(textRenderer, &(PointF){12.0f * displayScale, 4.0f * displayScale}, text,
          &COLOR_PAIR(0xB0FFFFFFu), TEXT_ALIGNMENT_START, TEXT_ALIGNMENT_START, 1.0f, true, NULL);

        snprintf(text, sizeof(text), formatText,
          DeviceGetTechVersion(device) >> 8, (DeviceGetTechVersion(device) >> 4) & 0xF,
          DeviceGetTechFeatureVersion(device) >> 8, (DeviceGetTechFeatureVersion(device) >> 4) & 0xF);

        TextRendererDrawAligned(textRenderer, &(PointF){displaySize.x - 12.0f * displayScale,
          displaySize.y - 6.0f * displayScale}, text, &COLOR_PAIR(0xB0FFFFFFu), TEXT_ALIGNMENT_END,
          TEXT_ALIGNMENT_END, 1.0f, true, NULL);
      }
      CanvasEnd(canvas);
    }
    SwapChainEnd(swapChain);
  }
  TimerUpdate(timer);

  // Extract fixed-rate processing tokens, if there are any.
  int32_t const tokens = TimerExtractTokens(timer);

  // Advance animation by a number of fixed-rate processing tokens.
  shift.x += tokens;
  shift.y -= tokens;
  paletteIndex += tokens;
}

LibraryBool applicationIdle(Application* application, void* user)
{
  ApplicationInvalidate(application);
  return false;
}

void outputError(char const* message)
{
#ifdef _WIN32
  static char const* initErrorTitle = "Initialization Error";
  MessageBoxA(NULL, message, initErrorTitle, MB_ICONERROR | MB_OK | MB_DEFAULT_DESKTOP_ONLY);
#else
  printf("%s\n", message);
#endif
}

// Main application entry.

#ifdef _WIN32

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prevInstance, _In_ LPWSTR cmdLine,
  _In_ int showCmd)
{
  UNREFERENCED_PARAMETER(prevInstance);
  UNREFERENCED_PARAMETER(cmdLine);
  UNREFERENCED_PARAMETER(showCmd);

  char const* windowClassName = "AfterwarpPlasmaDemo";

#else

int main(int argc, char **argv)
{

#endif

  ApplicationConfiguration configuration = {0};
  configuration.size = displaySize;
  configuration.position = (Point){.x = INT32_MAX, .y = INT32_MAX}; // default position
#ifdef _WIN32
  configuration.startup.win.handleInstance = instance;
  configuration.startup.win.handleIconSmall = LoadIcon(instance, MAKEINTRESOURCE(IDI_AFTERWARP));
  configuration.startup.win.handleIconBig = LoadIcon(instance, MAKEINTRESOURCE(IDI_AFTERWARP));

  strncpy(configuration.startup.win.windowClassName, windowClassName,
    sizeof(configuration.startup.win.windowClassName));
#else
  configuration.startup.nx.parameterCount = argc;
  configuration.startup.nx.parameterStrings = argv;
#endif

  application = ApplicationCreate(&configuration);
  if (!application)
  {
    outputError("Could not create Application object.");
    return -1;
  }

  ApplicationEvents events = {0};
  events.eventCreate = applicationCreate;
  events.eventDestroy = applicationDestroy;
  events.eventResize = applicationResize;
  events.eventRender = applicationRender;
  events.eventIdle = applicationIdle;
  ApplicationSetEvents(application, &events, NULL);

  displayScale = ApplicationGetWindowScale(application);
  ApplicationSetTitle(application, "Afterwarp: Plasma example");

  { // Retrieve client size back in case it has changed since startup.
    Rect clientRect = {0};
    ApplicationGetClientRect(application, &clientRect);

    displaySize = rectGetSize(clientRect);
  }

  bool const executed = ApplicationExecute(application);
  ApplicationDestroy(application);

  return executed ? 0 : -1;
}