
uses screen, memory, crt, dos;

const
VGA=$a000;

procedure setonecolor(c,r,g,b:byte);assembler;
asm
  mov dx,3c8h
  mov al,c
  out dx,al
  inc dx
  mov al,r
  out dx,al
  mov al,g
  out dx,al
  mov al,b
  out dx,al
end;


var palitra, palitra2:array[0..767] of byte;

Procedure LoadTga(TgaName : String; size, where:word);
Var
  InF   : File of byte; Loop : Word;
  Dummy : Array[1..18] of Byte;
  Pal   : Array[1..768] of Byte;
  n:word;
  tmp,r,g,b:byte;
Begin
  Assign(Inf,TgaName);
  Reset(Inf);
  for n:=0 to 17 do read(inf,tmp);
  for n:=1 to 768 do read(inf,pal[n]);
  for n:=0 to size do read(inf, mem[where:n]);
  Close(Inf);
{  Port[$3C8]:=0;}
  Loop:=1;
  n:=0;
  While Loop<768 Do
    Begin
      r:=Pal[Loop+2] Div 4;
      g:=Pal[Loop+1] Div 4;
      b:=Pal[Loop] Div 4;
      palitra[n]:=r;
      palitra[n+1]:=g;
      palitra[n+2]:=b;

{      Port[$3C9]:=r;
      Port[$3C9]:=g;
      Port[$3C9]:=b;}
      n:=n+3;
      Inc(Loop,3);
    End;
End;


var
fw1,fw2:file;

c, i, x,y,n,m:word;
fr:file;
b:byte;
size:word;

begin
SetUpVirtual(scr,vaddr);
SetUpVirtual(scr2, vaddr2);
SetUpVirtual(scr3, vaddr3);

asm
mov ax, 13h
int 10h
end;

LoadTga('test2_t2.tga', 65535, vaddr);

for y:=0 to 199 do for x:=0 to 319 do mem[vga:y*320+x]:=mem[vaddr:y*256+x];
for n:=0 to 255 do setonecolor(n, palitra[n*3], palitra[n*3+1], palitra[n*3+2]);{}


readkey;

{Optimize texture and palette for fasted draw}
{Делаем палитры 0..127 - 128..255 чередующимися,
чтобы избавится от "SHL 7" в цикле отрисовки}
for i:=0 to 65535 do mem[vaddr:i]:=mem[vaddr:i]*2;{}

for i:=0 to 127 do for n:=0 to 2 do {дублируем палитру 0..127 в 128..255}
     palitra[(i*3)+n+(128*3)]:=palitra[(i*3)+n];




for i:=0 to 127 do
  for n:=0 to 2 do begin
     palitra2[(i*3)*2+n]:=palitra[(i*3)+n];
     palitra2[(i*3)*2+n+3]:=palitra[(i*3)+n+(128*3)];
  end;

{-----------------------------------------}

  Assign(fw1, 'test2_t2.bin');
  Rewrite(fw1,1);
  Reset(fw1, 1);
  for i:=0 to 65535 do BlockWrite(fw1, mem[vaddr:i], 1);
  Close(fw1);

  Assign(fw1, 'test2_p2.pal');
  Rewrite(fw1,1);
  Reset(fw1, 1);
  for i:=0 to 767 do BlockWrite(fw1, palitra2[i], 1);
  Close(fw1);

for y:=0 to 199 do for x:=0 to 319 do mem[vga:y*320+x]:=mem[vaddr:y*256+x];
for n:=0 to 255 do setonecolor(n, palitra2[n*3], palitra2[n*3+1], palitra2[n*3+2]);

readkey;

for y:=0 to 199 do for x:=0 to 319 do mem[vga:y*320+x]:=mem[vaddr:y*256+x]+1;

for x:=0 to 63999 do mem[vga:x]:=0;

for x:=0 to 127 do for y:=10 to 90 do mem[vga:x+y*320]:=x*2;

for x:=0 to 127 do for y:=110 to 190 do mem[vga:x+y*320]:=x*2+1;

repeat
{Clear(64000, vaddr);}





WaitVR;{}
{FlipScreen(vaddr,vga);{}
until port[$60]=1;

asm
mov ax, 3h
int 10h
end;
{readkey;
repeat until keypressed;}

end.