/* plotfunc.c */

#include <math.h>
#include <stdio.h>

static float f(float x, float y)
{
  return sin(x) * cos(y);
}

int main(int argc, char **argv)
{
  int xDimension, zDimension, i, j;
  float xSpacing, zSpacing, minx, maxx, minz, maxz, miny, maxy;

  fprintf(stderr, "xDimension?\n");
  scanf("%d", &xDimension);
  fprintf(stderr, "zDimension?\n");
  scanf("%d", &zDimension);
  fprintf(stderr, "minx maxx?\n");
  scanf("%f %f", &minx, &maxx);
  fprintf(stderr, "minz maxz?\n");
  scanf("%f %f", &minz, &maxz);

  xSpacing = (maxx - minx) / (float)(xDimension-1);
  zSpacing = (maxz - minz) / (float)(zDimension-1);

  printf("#VRML V2.0 utf8\n");
  printf("\n");
  printf("Transform {\n");
  printf("	translation %g %g 0\n", minx, minz);
  printf("	rotation 1 1 1 %g\n", M_PI*2./3.);
  printf("	children Shape {\n");
  printf("		appearance Appearance { material Material {\n");
  printf("			specularColor 0.8 0.8 0.8\n");
  printf("			shininess 10\n");
  printf("		} }\n");
  printf("		geometry ElevationGrid {\n");
  printf("			xDimension %d\n", xDimension);
  printf("			zDimension %d\n", zDimension);
  printf("			xSpacing %g\n", xSpacing);
  printf("			zSpacing %g\n", zSpacing);
  printf("			creaseAngle %g\n", M_PI/2.);
  printf("			height [ \n");
  miny = HUGE; maxy = -HUGE;
  for (j=0; j<zDimension; j++) {
    for (i=0; i<xDimension; i++) {
      float y = f(minx + i*xSpacing, minz + j*zSpacing);
      printf("%g ", y);
      if (y < miny) miny = y;
      if (y > maxy) maxy = y;
    }
    printf("\n");
  }
  printf(" ]\n");
  printf("			colorPerVertex FALSE\n");
  printf("			color Color { color [ \n");
  for (j=0; j<zDimension-1; j++) {
    for (i=0; i<xDimension-1; i++) {
      float y = f(minx + ((float)i+0.5)*xSpacing, minz + (float)(j+0.5)*zSpacing);
      y = (y - miny) / (maxy - miny);
      if (y < 0.5) {
	y *= 2.;
	printf("%g %g %g, ", 0., y, 1-y);
      } else {
	y = 1. - (y-0.5) * 2.;
	printf("%g %g %g, ", 1-y, y, 0.);
      }
    }
    printf("\n");
  }
  printf(" ] }\n");
  printf("		}\n");
  printf("	}\n");
  printf("}\n");
  printf("\n");

  return 0;
}
