/**
  WIP raycasting demo for Pokitto.

  author: Miloslav "drummyfish" Ciz
  license: CC0
 */

#define POK_SIM

#include <stdio.h>
#include "raycastlib.h"
#include "Pokitto.h"
#include <stdlib.h>

class Level
{
public:
  int16_t getHeight(int16_t x, int16_t y)
  {
    if (x > 12 || y > 12)
      return x * y;

    return (x < 0 || y < 0 || x > 9 || y > 9) ? 1 : 0;
  }
};

class Character
{
public:
  Camera mCamera;

  Character()
  {
    mCamera.position.x = 400;
    mCamera.position.y = 6811;
    mCamera.direction = 660;
    mCamera.fovAngle = UNITS_PER_SQUARE / 4;
    mCamera.height = UNITS_PER_SQUARE / 2;
    mCamera.resolution.x = 55;
    mCamera.resolution.y = 88;
  } 
};

Pokitto::Core p;
Character player;
Level level;

int16_t heightFunc(int16_t x, int16_t y)
{
  return level.getHeight(x,y);
}

void pixelFunc(PixelInfo pixel)
{
  p.display.color = pixel.hit.direction + 4;
  p.display.drawPixel(pixel.position.x * 2,pixel.position.y);
  p.display.drawPixel(pixel.position.x * 2 + 1,pixel.position.y);
}

void draw()
{
  RayConstraints c;

  c.maxHits = 1;
  c.maxSteps = 32;

  render(player.mCamera,heightFunc,pixelFunc,c);
}

int main()
{
  p.begin();
  p.setFrameRate(60);

  p.display.setFont(fontTiny);

  while (p.isRunning())
  {
    if (p.update())
    {
      draw();

      const int16_t step = 50;
      const int16_t step2 = 10;

      Vector2D d = angleToDirection(player.mCamera.direction);

      d.x = (d.x * step) / UNITS_PER_SQUARE;
      d.y = (d.y * step) / UNITS_PER_SQUARE;

      if (p.upBtn())
      {
        player.mCamera.position.x += d.x;
        player.mCamera.position.y += d.y;
      }
      else if (p.downBtn())
      {
        player.mCamera.position.x -= d.x;
        player.mCamera.position.y -= d.y;
      }

      if (p.rightBtn())
        player.mCamera.direction += step2;
      else if (p.leftBtn())
        player.mCamera.direction -= step2;

      player.mCamera.position.x = clamp(player.mCamera.position.x,UNITS_PER_SQUARE / 2,10 * UNITS_PER_SQUARE - UNITS_PER_SQUARE / 2);
      player.mCamera.position.y = clamp(player.mCamera.position.y,UNITS_PER_SQUARE / 2,10 * UNITS_PER_SQUARE - UNITS_PER_SQUARE / 2);
    }
  }

  return 0;
}