unit _PNG;

interface

uses
  OpenGL,
  Frost.GL,
  SysUtils,
  pngimage;

type
  PRGB = record        {тип для работы с цветом в битмапе}
   r,g,b:byte;
  end;
  TSline = array[0..1] of PRGB;   {линия пикселей}
  TAline = array[0..1] of byte;

function LoadPNGTexture(FileName: String): Cardinal;

implementation

function LoadPNGTexture(FileName: String): Cardinal;   
const
  CB = 4; //Color bits
var
  i, j,
  TexWidth, TexHeight: Word;
  PNG: TPNGObject;
  TransparentMode: TPNGTransparencyMode;
  PPixel: ^TSline;
  PLine: pByteArray;
  TextureBit: array of Byte;
  PTextureBit: Pointer;
//  F: TextFile;
//  A: Byte;
begin                                     
  PLine:= nil;
  PNG:= TPNGObject.Create;
  PNG.LoadFromFile(FileName);
  TexWidth:=  PNG.Width;
  TexHeight:= PNG.Height;
  SetLength( TextureBit, TexWidth * TexHeight * CB);
  TransparentMode:=  PNG.TransparencyMode;
  for j:=0 to TexHeight - 1 do
  begin
    PPixel:=PNG.ScanLine[j];
    if not (TransparentMode = ptmNone) then
      PLine:= PNG.AlphaScanline[j];
    for i:=0 to TexWidth - 1 do
    begin
      TextureBit[i * CB + (TexHeight - 1 - j) * TexWidth * CB + 0]:= PPixel[i].b;
      TextureBit[i * CB + (TexHeight - 1 - j) * TexWidth * CB + 1]:= PPixel[i].g;
      TextureBit[i * CB + (TexHeight - 1 - j) * TexWidth * CB + 2]:= PPixel[i].r;
      if not (TransparentMode = ptmNone) then
        TextureBit[i * CB + (TexHeight - 1 - j) * TexWidth * CB + 3]:= PLine[i]
      else
        TextureBit[i * CB + (TexHeight - 1 - j) * TexWidth * CB + 3]:= 255;
    end;
  end;
//  Create File With bytemask of font texture
//  AssignFile(F, 'file.txt');
//  ReWrite(F);
//  for i := 0 to 128 - 1 do
//  begin
//    for j := 0 to 128 - 1 do
//    begin
//      if TextureBit[i * CB * TexWidth + (j) * CB + 0] > 0 then
//        A := (A shl 1) or 1
//      else
//        A := (A shl 1);
//      if (j mod 8 = 7) then
//      begin
//        Write(F, 'ff' + IntToStr(1000 + A) + ',');  
//        A := 0;
//      end;
//    end;
//    Write(F, chr(13));
//  end;
//  CloseFile(F);

  PTextureBit:=TextureBit;
//  Result:= GenerateMipTexture(PTextureBit,TexWidth,TexHeight, GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_LINEAR);
  Result:= GenerateTexture(PTextureBit,TexWidth,TexHeight);
  PNG.Free;
end;

end.
