#! /usr/bin/gawk -f
# Last edited on 2006-04-08 14:17:43 by stolfi

BEGIN {
  PROG_NAME = "make-sphere-normal-map";
  PROG_DESC = "create the normal map of a sphere";
  PROG_VERS = "1.0";

  # Copyright  2006 by the State University of Campinas (UNICAMP).
  # See the copyright, authorship, and warranty notice at end of file.
  # Last edited on 2006-04-08 14:10:38 by stolfi

  PROG_HELP = \
    PROG_NAME " \\\n" \
    "    -v radius={RAD} \\\n" \
    "    > {NORMALMAP}.fni";

  PROG_INFO = \
    "NAME\n" \
    "  " PROG_NAME " - " PROG_DESC ".\n" \
    "\n" \
    "SYNOPSIS\n" \
    "  " PROG_HELP "\n" \
    "\n" \
    "DESCRIPTION\n" \
    "  Writes to {stdout} a three-channel float-valued image of the\n" \
    " speficied dimensions, where the value of each pixel is the unit\n" \
    " normal vector of a sphere.\n" \
    "\n" \
    "  The sphere is assumed to be viewed in parallel orthogonal projection,\n" \
    " from the +Z axis.  The output image has {2*RAD+1} columns and\n" \
    " rows.  The sphere's projetion is centered and has radius {RAD}\n" \
    " in pixels.\n" \
    "\n" \
    "  The output file is in the FNI format. See\n" \
    " {float_image.h} for details.\n" \
    "\n" \
    "AUTHOR\n" \
    "  Created 2006-04-07 by Jorge Stolfi, Unicamp" ;

  abort = -1;
  if (radius == "") { arg_error("must define \"radius\""); }
  size = 2*radius + 1;
  printf "begin float_image_t (format of 2006-03-25)\n";
  printf "NC = 3\n";
  printf "NX = %d\n", size;
  printf "NY = %d\n", size;
  for (y = 0; y < size; y++)
    { if (y > 0) printf "\n"
      for (x = 0; x < size; x++)
        { printf "%5d %5d ", x, y;
          xx = x - radius;
          yy = y - radius;
          xf = xx + (xx < 0 ? -0.5 : +0.5 );
          yf = yy + (yy < 0 ? -0.5 : +0.5 );
          if (xf*xf + yf*yf <= radius*radius) 
            { nx = xx/radius;
              ny = yy/radius;
              nz = sqrt(1.000001 - nx*nx - ny*ny);
            }
          else
            { nx = 0; ny = 0; nz = 0; }
          printf " %9.6f %9.6f %9.6f\n", nx, ny, nz;
        }
    }
  printf "end float_image_t\n"; 
}

(abort >= 0) { exit abort; }

function arg_error(msg)
{
  printf "%s: ** %s\n", PROG_NAME, msg > "/dev/stderr";
  printf "usage: %s\n", PROG_HELP > "/dev/stderr"
  abort = 1; exit abort; 
}

function data_error(msg)
{
  printf "%s:%d: %s: ** %s\n", FILENAME, FNR, PROG_NAME, msg > "/dev/stderr";
  abort = 1; exit abort; 
}
