//---------------------------------------------------------------------------


#pragma hdrstop

#include "vmx_p32.h"
#pragma package(smart_init)

__fastcall T32BitBMP::T32BitBMP (void)
{
  Picture = new Graphics::TBitmap;
  Alpha = new Graphics::TBitmap;
}
//---------------------------------------------------------------------------

__fastcall T32BitBMP::~T32BitBMP (void)
{
  delete Picture;
  delete Alpha;
}

void __fastcall T32BitBMP::LoadFromFile (AnsiString File)
{
  TFileStream *fs = new TFileStream (File,fmOpenRead);
  int w, h;
  fs->Read(&w,4);
  fs->Read(&h,4);
  Picture->Width=w;
  Picture->Height=h;
  Picture->PixelFormat=pf24bit;
  Alpha->Width=w;
  Alpha->Height=h;
  Alpha->PixelFormat=pf24bit;
  BYTE r,g,b,a;
  for (int i = 0; i < h; i++)
    for (int j = 0; j < w; j++)
    {
      fs->Read(&r,1);
      fs->Read(&g,1);
      fs->Read(&b,1);
      fs->Read(&a,1);
      Picture->Canvas->Pixels[j][i]=RGB(r,g,b);
      Alpha->Canvas->Pixels[j][i]=RGB(a,a,a);
    }
  delete fs;
}

void __fastcall T32BitBMP::SaveToFile (AnsiString File)
{
  TFileStream *fs = new TFileStream (File,fmCreate|fmOpenWrite);
  fs->Position=0;
  int w = Picture->Width;
  int h = Picture->Height;
  fs->Write(&w,4);
  fs->Write(&h,4);
  BYTE R,G,B,a;
  Byte *Lp,*Ap;
  for (int i = 0; i < h; i++)
  {
    Lp = (Byte*)Picture->ScanLine[i];
    Ap = (Byte*)Alpha->ScanLine[i];
    for (int j = 0; j < w; j++)
    {
      R = Lp[j*3+2];
      G = Lp[j*3+1];
      B = Lp[j*3];
      a = Ap[j*3+2];
      fs->Write(&R,1);
      fs->Write(&G,1);
      fs->Write(&B,1);
      fs->Write(&a,1);
    }
  }
  delete fs;
}

void __fastcall T32BitBMP::Draw (TCanvas *Canvas, int X, int Y)
{
  Byte *Lp, *Ap, *Op;
  Byte R, G, B, or, og, ob;
  Graphics::TBitmap *O = new Graphics::TBitmap;
  O->Width=Picture->Width;
  O->Height=Picture->Height;
  O->Canvas->CopyRect(TRect(0,0,O->Width,O->Height),Canvas,TRect(X,Y,X+O->Width,Y+O->Height));
  float k = 0;
  for (int i = 0; i < Picture->Height; i++)
  {
    Lp = (Byte*)Picture->ScanLine[i];
    Ap = (Byte*)Alpha->ScanLine[i];
    Op = (Byte*)O->ScanLine[i];
    for (int j = 0; j < Picture->Width; j++)
    {
      R = Lp[j*3+2];
      G = Lp[j*3+1];
      B = Lp[j*3];
      or = Op[j*4+2];
      og = Op[j*4+1];
      ob = Op[j*4];
      k = (float)(Ap[j*3+2])/255.0;
      Canvas->Pixels[j+X][i+Y]=RGB(R*k+or*(1-k),G*k+og*(1-k),B*k+ob*(1-k));
    }
  }
  delete O;
}

