//
/* There are walls, and Polly can't go through them */

import render.*;
import java.awt.*;

public class PollyWalls extends RenderApplet
{
   Polly polly1, polly2;

   public boolean keyUp(Event e, int k) {        // SET ACTIONS VIA KEYBOARD
      if (! super.keyUp(e, k))
         key(k);
      return true;
   }

   public void key(int k) {
      if (k >= 'A' && k <= 'Z')
         polly1.action(k - 'A');
      else if (k >= 'a' && k <= 'z')
         polly2.action(k - 'a');
   }

   double w[][] = {                                // WALL DATA
      {5,3, -4,3, -2,-3, 2,-3, 3,0, 4,0, 5,3},
      //{-1.5,1.5, -1.3,1},
      //{1,.7, .7,-.3},
   };

   public void initialize() {                      // INITIALIZE EVERYTHING

      addLight(1,1,1, 1,1,1);          // LIGHTS
      addLight(0,-1,0, 1,1,1);
      setBgColor(.2,.2,.8);            // BACKGROUND COLOR
      setFL(12);                       // CAMERA FOCAL LENGTH
      push();
         translate(-.5,0,0);
	 rotateX(Math.PI/6);
	 transform(world);             // INITIAL VIEW ANGLE
      pop();

      world.add().setMaterial(
         (new Material()).setColor(0,1,0).setTransparency(.5));
      world.child[0].mesh(10, 10).setDoubleSided(true);
      push();                          // MAKE THE TRANSPARENT FLOOR
	 scale(6,1,4);
	 rotateX(-Math.PI/2);
	 transform(world.child[0]);
      pop();

      Geometry walls = world.add().setMaterial(
         (new Material()).setColor(1,1,1).setTransparency(.5));
      walls.setDoubleSided(true);
      Polly.clearWalls();
      for (int i = 0 ; i < w.length ; i++) {
         Polly.addWall(w[i]);
         makeWall(walls, w[i]);
      }

      Polly.clearPollys();
      world.add(polly1 = new Polly().setSize(.9).setPosition(1,0).setColor(1,0,0));
      world.add(polly2 = new Polly().setSize(.6).setPosition(-1,0).setColor(1,.5,.5));
   }

   void makeWall(Geometry g, double w[]) {
      for (int j = 0 ; j < w.length/2 - 1 ; j++) {
         double ax = w[2*j  ], az = w[2*j+1],
                bx = w[2*j+2], bz = w[2*j+3];
         push();
            double dx = (bx-ax)/2, dz = (bz-az)/2;

            Geometry wall = g.add();
            wall.mesh((int)Math.sqrt(dx*dx+dz*dz)+2, 2);

            translate((ax+bx)/2, .5, (az+bz)/2);
	    rotateY(Math.atan2(-dz, dx));
	    scale(Math.sqrt(dx*dx + dz*dz), .5, 1);
            transform(wall);
         pop();
      }
   }

   public void animate(double time) {              // ANIMATE ONE FRAME
      polly1.animate(time);
      polly2.animate(time);
   }
}