{$MODE OBJFPC}
{$MODESWITCH AUTODEREF}
unit dpng;

interface

uses
  BeRoPNG,
  dtypes,
  dstrnum,
  dcolors,
  dstream,
  dstream_op,
  dtexture2d;

type
TTexture2dFormatPng = object(TTexture2dFormat)
  function CheckFormat(Stream: PStream): Boolean; virtual;
  function Load(Stream: PStream; var Texture: TTexture2dRgba): Boolean; virtual;
  function Name: AnsiString; virtual;
end;

implementation

function TTexture2dFormatPng.CheckFormat(Stream: PStream): Boolean;
var
  M: array[0..7] of AnsiChar;
begin
  Stream.Read(@M[0], SizeOf(M));
  Result := (M[0] = #$89) and (M[1] = #$50) and (M[2] = #$4e) and (M[3] = #$47)
        and (M[4] = #$0d) and (M[5] = #$0a) and (M[6] = #$1a) and (M[7] = #$0a);
end;

function TTexture2dFormatPng.Load(Stream: PStream; var Texture: TTexture2dRgba): Boolean;
var
  DataPointer: Pointer;
  DataSize: SizeUInt;
  ImageData: Pointer;
  ImageWidth, ImageHeight: LongInt;
begin
  Stream^.ReadToMemory(DataPointer, DataSize);
  Result := LoadPNG(DataPointer, DataSize, ImageData, ImageWidth, ImageHeight, False);
  FreeMem(DataPointer);
  if Result then
    Texture.InitOwnership(ImageWidth, ImageHeight, ImageData);
end;

function TTexture2dFormatPng.Name: AnsiString;
begin
  Exit('png');
end;


var
  Format: TTexture2dFormatPng;
initialization
  Format.Init;
  RegistTexture2dFormat(@Format);
end.
