unit Game;

interface

uses
  NewtonImport,
  JEN_Header,
  JEN_Math,
  Terrain,
  Trace,
  Player,
  Enemies,
  Bonuses;

type
  TGame = class
  constructor Create;
  destructor Destroy; override;
  private
    Heals : ITexture;
    Aim : ITexture;
    HealsFull : ITexture;
  public
    TraceMng : TTraceManager;
    Terrain : TTerrain;
    Player : TPlayer;
    EnemiesMng : TEnemiesManager;
    BonusMng : TBonuseManager;
    World : PNewtonWorld;
    FAccDelta : Single;
    procedure OnUpdate(dt: LongInt);
    procedure OnRender;
    procedure Init;
  end;


implementation

uses
  Main,
  Config;

constructor TGame.Create;
begin
  World := NewtonCreate(nil, nil);

  NewtonSetPlatformArchitecture(World, 2);
  NewtonSetSolverModel(World, 0);
end;

procedure TGame.Init;
begin
  Heals := ResMan.LoadTexture('Media\Heals.dds');
  HealsFull := ResMan.LoadTexture('Media\HealsFull.dds');
  Aim := ResMan.LoadTexture('Media\Aim.dds');

  Terrain := TTerrain.Create;
  Player := TPlayer.Create;
  TraceMng := TTraceManager.Create;
  EnemiesMng := TEnemiesManager.Create;
  BonusMng := TBonuseManager.Create;

  Display.Cursor := false;
  Input.SetCapture(true);
end;

destructor TGame.Destroy;
begin
  Terrain.Free;
  Player.Free;
  TraceMng.Free;
  EnemiesMng.Free;
  BonusMng.Free;

  NewtonDestroyAllBodies(World);
  NewtonMaterialDestroyAllGroupID(World);
  NewtonDestroy(World);
end;

procedure TGame.OnUpdate(dt: LongInt);
begin
  Player.OnUpdate(dt);
  Terrain.OnUpdate(dt);
  TraceMng.OnUpdate(dt);
  EnemiesMng.OnUpdate(dt);
  BonusMng.OnUpdate(dt);

  FAccDelta := FAccDelta + dt/1000;
  while FAccDelta > (1/60) do
  begin
    NewtonUpdate(World, (1/60));
    FAccDelta := FAccDelta - (1/60);
  end;

  if Player.Heals<EPS then
    Engine.Finish;
end;

procedure TGame.OnRender;
var
  i : integer;
  P : TVec2f;
begin
  Render.CullFace := cfBack;
  Render.DepthWrite := True;
  Render.Clear(True,True,False);
  EnemiesMng.OnDraw;
  Terrain.OnDraw;
  TraceMng.OnDraw;
  BonusMng.OnDraw;

  Render.DepthTest := false;
  Render.DepthWrite := false;
  Render.BlendType := btAdd;


  for I := 0 to 8 do
  begin
    SinCos(2*pi/9*i, P.x, P.y);
    P := P * (Player.Weapon.Scattering+Player.Weapon.SpeedScatt)*9 * vec2f(1/Screen_Width, 1/Screen_Height);
    Render2d.DrawSprite(Aim, 0.5 + P.x, 0.5 + P.y, 16/Screen_Width, 8/Screen_Height, vec4f(0.33, 0.0, 1.0, 1.0),  110 -360/9*i);

  end;

  Render.BlendType := btNormal;
  Render2d.DrawSprite(Heals, 0, 1.0 - 64/Screen_Height, 512/Screen_Width, 64/Screen_Height, clWhite);

  Render.BlendType := btNone;
  Render.AlphaTest := 255-Round(Player.Heals/100*254);
  Render2d.DrawSprite(HealsFull, 0,  1.0 - 64/Screen_Height, 512/Screen_Width, 64/Screen_Height, clWhite);
  Render.AlphaTest := 0;
end;


end.
