uses
  {$I deng_app_units.inc},
  dvector2i,
  dvector4f,
  dstreamfile,
  djson,
  dtga,
  dpng,
  dsprite;

var
  Frame: TSprite.TFrame;
  Sprite: TSprite;
  SpriteOnce: TSprite;
  SpriteFromJson: TSprite;
  Json: TJson;

procedure InitAnimatedCountdown(Eng: TEngine; Sprite: PSprite; Looped: Boolean);
var
  I, X, Y: LongInt;
begin
  Sprite.Init;
  for I := 0 to 86 do begin
    X := 64 * (I mod 16);
    Y := 64 * (I div 16);
    Sprite.AddFrame(nil, Eng, Asset('countdown.png'), 100, Vec2i(X, Y), Vec2i(64, 64));
  end;
  Sprite.State.Looped := Looped;
end;

procedure Init(Eng: TEngine);
var
  V: TJsonValue;
begin
  Frame.Init;
  Frame.Tex.Init(nil, Eng, Asset('countdown.png'));
  Frame.P := Vec2i(0, 0);
  Frame.S := Vec2i(64, 64);
  Frame.Dt := 100;
  InitAnimatedCountdown(Eng, @Sprite, True);
  InitAnimatedCountdown(Eng, @SpriteOnce, False);
  ParseJson('sprite.json', Json);
  V._Type := JSON_OBJECT;
  V.O := @Json;
  SpriteFromJson.Init;
  SpriteFromJson.LoadFromJson(nil, Eng, @V);
end;

procedure Done(Eng: TEngine);
begin
  SpriteFromJson.Done;
  SpriteOnce.Done;
  Sprite.Done;
  Frame.Done;
end;

procedure Render(Eng: TEngine);
begin
  Eng.Draw.BeginRender;
  Eng.Draw.ClearScreen(Vec4f(0, 0, 0, 1));
  Eng.Draw.Start2D;
  Frame.Draw(Eng, Vec2i(200, 200));
  Sprite.State.Animate(30);
  Sprite.State.Draw(Eng, Vec2i(400, 200));
  SpriteOnce.State.Animate(30);
  SpriteOnce.State.Draw(Eng, Vec2i(600, 200));
  SpriteFromJson.State.Animate(30);
  SpriteFromJson.State.Draw(Eng, Vec2i(200, 400));
  Eng.Draw.EndRender;
end;

procedure Update(Eng: TEngine);
begin
  if Eng.Control.Pressed(KEY_ESC) then
    Eng.StopLoop;
end;

begin
  Eng.InitDisplayMode(800, 600, 32, DENG_GL);
  Eng.InitTitle('Example for sprites');
  Eng.InitInitFunc(Init);
  Eng.InitDoneFunc(Done);
  Eng.InitRenderFunc(Render);
  Eng.InitUpdateFunc(Update, 30);
  Eng.Run;
end.
