#include <vectrex.h>

/*
      Test of a silly effect.  May not be too useful in any actual games as current
    implementation is too expensive computationally.  Still, lots of room for optimisations.
 */

#define set_scale(s) do { VIA_t1_cnt_lo = s; } while (0)
int horizontal = 1;
void Move(long x, long y) {
  if (horizontal) {
    Moveto_d((int)((y*3L)>>2L), (int)((x)));
  } else {
    Moveto_d( (int)((x*7L)>>3L), (int)((y)));
  }
}

void Line(long dx, long dy) {
  if (horizontal) {
    Draw_Line_d((int)((dy*3L)>>2L), (int)(dx));
  } else {
    Draw_Line_d((int)((dx*7L)>>3L), (int)(dy));
  }
}

int draw_quad(long p0x, long p0y, long p1x, long p1y,
               long p2x, long p2y, long p3x, long p3y) {
  if (p0x < -128) return 0;
//  if (p1x >= 128) return 0;
  Reset0Ref();
  Move(p0x, p0y);
  Line((p1x-p0x), (p1y-p0y));
  Line((p3x-p1x), (p3y-p1y));
  Line((p2x-p3x), (p2y-p3y));
  Line((p0x-p2x), (p0y-p2y)/*+2*/);
  return 1;
}

int draw_building(long x, long y, long wth, long hgt, int pass) {
  int fix = 4;
  int drawn = 1;
  if (pass == 2) {
    drawn = draw_quad(((x-wth)*hgt)>>fix, ((y+wth)*hgt)>>fix, ((x+wth)*hgt)>>fix, ((y+wth)*hgt)>>fix, 
                      ((x-wth)*hgt)>>fix, ((y-wth)*hgt)>>fix, ((x+wth)*hgt)>>fix, ((y-wth)*hgt)>>fix);
  } else {
    if (x < -wth) {
      draw_quad(((x+wth)*hgt)>>fix, ((y+wth)*hgt)>>fix, x+wth, y+wth, 
                ((x+wth)*hgt)>>fix, ((y-wth)*hgt)>>fix, x+wth, y-wth);
    }
    if (y < -wth) {
      draw_quad(((x-wth)*hgt)>>fix, ((y+wth)*hgt)>>fix, ((x+wth)*hgt)>>fix, ((y+wth)*hgt)>>fix, 
                x-wth, y+wth, x+wth, y+wth);
    } else if (y > wth) {
      draw_quad(((x-wth)*hgt)>>fix, ((y-wth)*hgt)>>fix, ((x+wth)*hgt)>>fix, ((y-wth)*hgt)>>fix, 
                 x-wth, y-wth, x+wth, y-wth);
    }
    if (x > wth) {
      draw_quad(x-wth, y+wth, ((x-wth)*hgt)>>fix, ((y+wth)*hgt)>>fix, 
                x-wth, y-wth, ((x-wth)*hgt)>>fix, ((y-wth)*hgt)>>fix);
    }
  }
  return drawn;
}

int main(void)
{
  int drawn;
  int tmr = 0;
  for (;;) {
    Wait_Recal(); Reset0Ref(); Intensity_7F(); set_scale(0x80);

    drawn = draw_building(tmr,  -tmr,  20, 19,  2);
    if (drawn) draw_building(tmr,  -tmr,  20, 19,  1);

    drawn = draw_building(0,  tmr,  17, 17,  2);
    if (drawn) draw_building(0,  tmr,  17, 17,  1);

    drawn = draw_building((tmr<<2)+90,  -64,  15, 18,  2);
    if (drawn) draw_building((tmr<<2)+90,  -64,  15, 18,  1);

    tmr -= 1;
  };
  return 0;
}

// ***************************************************************************
// end of file
// ***************************************************************************