/*****************************************************************************
* Module to handle viewing of objects in the ViewWindow.		     *
*									     *
* Written by:  Gershon Elber		    Unix - X11 Ver 0.1, Mar. 1990    *
*****************************************************************************/

#ifndef __MSDOS__

#include <stdio.h>
#include <string.h>
#include <setjmp.h>
#include <math.h>
#include "program.h"
#include "postscrp.h"
#include "viewobjl.h"
#include "viewobjg.h"
#include "graphgng.h"

#include "xgraphic.h"

/* Save the current displayed object information in local variables. */
static FileDescription **LocalFD;
static int LocalNumOfObjects;
static char **LocalObjects;

static jmp_buf LongJumpBuffer;			        /* Used in breaking. */

/*****************************************************************************
*  Routine to interactively display geometric object(s) PObjList on the View *
* window enable rotating/translating/scaling it using the Input Device.      *
*****************************************************************************/
void InteractGeomObject(FileDescription **FD, int NumOfObjects,	char **Objects)
{
    /* Get data from input device, interpret it, and display interactively:  */
    InteractHandleInput(FD, NumOfObjects, Objects);
}

/*****************************************************************************
*  Routine to handle data from the input device (keyboard, mouse etc.) -     *
* clip it against the sub windows of the interactive menu and perform the    *
* required transfomation, by updating the global view matrix object VIEW_MAT *
*  The input data in the Rotation/Translation/Scaling sub windows is used    *
* (horizontal distance from sub window center) to set amount of change.	     *
*****************************************************************************/
static void InteractHandleInput(FileDescription **FD, int NumOfObj,
							char **Objects)
{
    int i, UpdateView, QuitView = FALSE;
    char *ToggleStr;
    RealType x, y, ChangeFactor;
    MatrixType Mat, OrigViewMat, OrigPerspMat;

    /* Save copy of original matrix, so we can recover if reset is required. */
    GEN_COPY(OrigViewMat,  GlblViewMat,  sizeof(MatrixType));
    GEN_COPY(OrigPerspMat, GlblPerspMat, sizeof(MatrixType));

    switch (GlblViewMode) {			 /* Update the current view. */
	case VIEW_ORTHOGRAPHIC:
	    GEN_COPY(CrntViewMat, GlblViewMat, sizeof(MatrixType));
	    break;
	case VIEW_PERSPECTIVE:
	    MultTwo4by4(CrntViewMat, GlblViewMat, GlblPerspMat);
	    break;
    }

    LocalFD = FD;
    LocalNumOfObjects = NumOfObj;
    LocalObjects = Objects;

    GGMySetLineStyle(FULL_LINE_STYLE);

    GGClearAllScreen();				  /* Clear the view window. */
    ViewGeomObjectList(FD, NumOfObj, Objects);/* Display it for first time. */

    while (TRUE) {
	QuitView = FALSE;

	UpdateView = TRUE;
	GenUnitMat(Mat);		    /* No transformation by default! */

	switch (GetGraphicEvent(&ChangeFactor, &ToggleStr)) {
	    case EVENT_SCR_OBJ_TGL:    /* Its Coordinate system - toggle it. */
		GlblTransformMode = *ToggleStr == 'S' ?
				    TRANS_SCREEN :
				    TRANS_OBJECT;
		UpdateView = FALSE;
		break;
	    case EVENT_PERS_ORTHO_TGL:	       /* Its View mode - toggle it. */
		GlblViewMode = *ToggleStr == 'P' ?
		               VIEW_PERSPECTIVE :
			       VIEW_ORTHOGRAPHIC;
		break;
	    case EVENT_PERS_ORTHO_Z: /* Its Perspective Z focal point modif. */
		if (GlblViewMode != VIEW_PERSPECTIVE) {
		    GGTone(1000, 100);			   /* Do some noise! */
		    UpdateView = FALSE;
		    break;
		}
		/* Make it between 0.5 and 1.5: */
		ChangeFactor = ChangeFactor / 2.0 + 1.0;
		GlblPerspMat[2][2] *= ChangeFactor;
		GlblPerspMat[2][3] *= ChangeFactor;
		GlblPerspMat[3][2] *= ChangeFactor;
		break;
	    case EVENT_ROTATE_X:	   /* Its rotation along the X axis. */
		GenMatRotX1(DEG2RAD(ChangeFactor * MAX_ROTATE_ANGLE), Mat);
		break;
	    case EVENT_ROTATE_Y:	   /* Its rotation along the Y axis. */
		GenMatRotY1(DEG2RAD(ChangeFactor * MAX_ROTATE_ANGLE), Mat);
		break;
	    case EVENT_ROTATE_Z:	   /* Its rotation along the Z axis. */
		GenMatRotZ1(DEG2RAD(ChangeFactor * MAX_ROTATE_ANGLE), Mat);
		break;
	    case EVENT_TRANSLATE_X:	/* Its translation along the X axis. */
		GenMatTrans(ChangeFactor * MAX_TRANSLATE_FACTOR, 0.0, 0.0,
									Mat);
		break;
	    case EVENT_TRANSLATE_Y:	/* Its translation along the Y axis. */
		GenMatTrans(0.0, ChangeFactor * MAX_TRANSLATE_FACTOR, 0.0,
									Mat);
		break;
	    case EVENT_TRANSLATE_Z:	/* Its translation along the Z axis. */
		GenMatTrans(0.0, 0.0, ChangeFactor * MAX_TRANSLATE_FACTOR,
									Mat);
		break;
	    case EVENT_SCALE:		      /* Its scaling along all axes. */
		if (ChangeFactor > 0.0)		      /* Make it around 1... */
		     ChangeFactor = ChangeFactor * MAX_SCALE_FACTOR + 1.0;
		else ChangeFactor = 1.0 /
			(-ChangeFactor * MAX_SCALE_FACTOR + 1.0);
		GenMatScale(ChangeFactor, ChangeFactor, ChangeFactor, Mat);
		break;
	    case EVENT_DEPTH_CUE:
		GlblDepthCue = *ToggleStr == 'D';
		if (!GlblDepthCue) GGMySetLineStyle(FULL_LINE_STYLE);
		break;
	    case EVENT_SAVE_PS:
		SavePostScript(FD, NumOfObj, Objects);
		UpdateView = FALSE;
		break;
	    case EVENT_SAVE_MATRIX:
		SaveCurrentMat();
		UpdateView = FALSE;
		break;
	    case EVENT_RESET_MATRIX:
		GEN_COPY(GlblViewMat,  OrigViewMat,  sizeof(MatrixType));
		GEN_COPY(GlblPerspMat, OrigPerspMat, sizeof(MatrixType));
		break;
	    case EVENT_QUIT:
		LocalFD = NULL;
		LocalNumOfObjects = 0;
		LocalObjects = NULL;
		return;						/* Its Quit. */
	    default:
		GGTone(1000, 100);			   /* Do some noise! */
		UpdateView = FALSE;
	}
	if (UpdateView) {
	    GGClearAllScreen();			   /* Clear the view window. */

	    switch (GlblTransformMode) {/* Udpate the global viewing matrix. */
		case TRANS_SCREEN:
		    MultTwo4by4(GlblViewMat, GlblViewMat, Mat);
		    break;
		case TRANS_OBJECT:
		    MultTwo4by4(GlblViewMat, Mat, GlblViewMat);
		    break;
	    }

	    switch (GlblViewMode) {		 /* Update the current view. */
		case VIEW_ORTHOGRAPHIC:
		    GEN_COPY(CrntViewMat, GlblViewMat, sizeof(MatrixType));
		    break;
		case VIEW_PERSPECTIVE:
		    MultTwo4by4(CrntViewMat, GlblViewMat, GlblPerspMat);
		    break;
	    }

	    ViewGeomObjectList(FD, NumOfObj, Objects);	/* And display it... */
	}
    }
}

/*****************************************************************************
*  Routine to update the viewing screen. On unix systems this routine may    *
* be invoked when X sends expose event to this program (see xgrphgen.c).     *
* In MSDOS this routine is static and been called from InteractHandleInput   *
* above routine only.							     *
*****************************************************************************/
void UpdateInteractHandleInput(void)
{
    GGClearAllScreen();
    if (LocalFD)
	ViewGeomObjectList(LocalFD, LocalNumOfObjects, LocalObjects);
}

/*****************************************************************************
*  Routine to display the geometric objects in PObjList, by simply calling   *
* ViewGeomObject on all of them. PObjList must be of type OBJ_LIST_OBJ.	     *
*****************************************************************************/
static void ViewGeomObjectList(FileDescription **FD, int NumOfObjects,
								char **Objects)
{
    int	i;
    ObjectStruct *PObject;

    GGMySetColor(RED);			        /* Make default color - RED. */

    if (setjmp(LongJumpBuffer) == 0)	      /* Its the setjmp itself call! */
	if (NumOfObjects > 0)	   /* There was something on command line... */
	    for (i=0; i<NumOfObjects; i++) {
		if ((PObject = SearchObject(FD, *Objects)) ==
							(ObjectStruct *) NULL)
		    fprintf(stderr,
			    "Given Object %s not found in data files\n",
			    *Objects);
		else ViewOneObject(PObject);
		Objects++;
	    }
	else {
	    /* Draw all objects not in other object by scanning object trees.*/
	    DrawAllObjects(FD);	    /* and drawing ones with Reference == 0. */
	}
}

/*****************************************************************************
* Routine to save the current view trans. GlblViewMat to a generic mat file  *
*****************************************************************************/
static void SaveCurrentMat(void)
{
    int	i, j;
    FILE *f;
    char *p, FileName[FILE_NAME_LEN];
    static char FileCount = '0';

    strcpy(FileName, GENERIC_MAT_FILE);
    if ((p = strchr(FileName, '#')) != NULL) {
	*p = FileCount;
	if (FileCount++ == '9') FileCount = '0';
    }
    if ((f = fopen(FileName, "wt")) == NULL) {
	GGTone(700, 200);
	return;
    }

    for	(i=0; i<4; i++)	{
	for (j=0; j<4; j++) fprintf(f, "%12lf ", GlblViewMat[i][j]);
	fprintf(f, "\n");
    }

    if (GlblViewMode == VIEW_PERSPECTIVE) {
	fprintf(f, "\n");
	for (i=0; i<4; i++) {
	    for (j=0; j<4; j++) fprintf(f, "%12lf ", GlblPerspMat[i][j]);
	    fprintf(f, "\n");
	}
    }

    fclose(f);
}

/*****************************************************************************
* Routine to search for	an object in the File descriptions FD. Note that if  *
* an object exists more	than once only the first will be returned. If none   *
* is found then	NULL is	returned, else a pointer to that object	struct.	     *
*****************************************************************************/
static ObjectStruct *SearchObject(FileDescription **FD, char *Object)
{
     BinTree *PBinTree;

     while (*FD) {
	  if ((PBinTree	= GetBinTree(Object, (*FD++) -> ObjectPointer)) !=
						 (BinTree *) NULL)
	  return PBinTree -> Data.PObject;
     }
     return (ObjectStruct *) NULL;
}

/*****************************************************************************
* Routine to draw all the objects not in other objects...		     *
* by scanning all the object trees and drawing the objects with	Reference==0 *
* meaning nobody referred to them yet...				     *
*****************************************************************************/
static void DrawAllObjects(FileDescription **FD)
{
    while (*FD)	VisitObjectTree((*FD++) -> ObjectPointer);
}

/*****************************************************************************
* Routine to draw all the objects not in other objects...		     *
* by scanning all the object in	tree PBinTree and drawing the objects with   *
* Reference==0,	meaning	nobody referred	to them	yet...			     *
*****************************************************************************/
static void VisitObjectTree(BinTree *PBinTree)
{
    if (PBinTree == (BinTree *)	NULL) return;

    VisitObjectTree(PBinTree -> right);

    if (MoreFlag == 1)
	printf("Drawing object %s\n", PBinTree -> Name);
    ViewOneObject(PBinTree -> Data.PObject);

    VisitObjectTree(PBinTree -> left);
}

/*****************************************************************************
* Routine to draw one object Object, using the Matrix transform	Mat.	     *
*****************************************************************************/
static void ViewOneObject(ObjectStruct *PObject)
{
    PolygonStruct *PList = PObject -> PPolygon;

    SetDrawColor(PObject -> Color);	       /* Default color for object. */

    while (PList) {
	ViewOnePolygon(PList);
	PList =	PList -> Pnext;
    }
}

/*****************************************************************************
* Routine to draw one polygon, using the Matrix	transform Mat.		     *
* Note this is the routine that	makes the real drawing...		     *
*****************************************************************************/
static void ViewOnePolygon(PolygonStruct *PPolygon)
{
    int	i, Count, DrawNextEdge, NumOfVertices;
    float MappedNormal[3], PolyNormal[3];
    VertexStruct *PList = PPolygon -> PVertex;

    TestQuitView();

    Count = NumEdges;

    if (PList == NULL) return;

    switch (PPolygon -> PolyType) {
	case POINTLIST:
	    while (PList) {
		MyMoveTo(PList -> Coord);
		MyDrawTo(PList -> Coord);
		PList = PList -> Pnext;
	    }
	    break;
	case POLYLINE:
	    MyMoveTo(PList -> Coord);
	    DrawNextEdge = !PList -> Internal;
	    PList = PList -> Pnext;

	    while (PList) {
		MyDrawTo(PList -> Coord);

		PList = PList -> Pnext;
	    }
	    break;
	case POLYGON:
	    if (DrawPNormalsFlag && PPolygon->HasPlane)
	    {
		for (i=0; i<3; i++) PolyNormal[i] = PList -> Coord[i];
		NumOfVertices = 1;
	    }

	    MyMoveTo(PList -> Coord);
	    DrawNextEdge = !PList -> Internal;
	    PList = PList -> Pnext;

	    while (PList) {
		if (DrawNextEdge || InterFlag)
		    MyDrawTo(PList -> Coord);
		else MyMoveTo(PList -> Coord);

		if (DrawVNormalsFlag && PList -> HasNormal) {
		    for (i=0; i<3; i++) MappedNormal[i] =
					PList -> Coord[i] + PList -> Normal[i];
		    i = ClosedObject;
		    ClosedObject = FALSE;
		    MyDrawTo(MappedNormal);
		    MyMoveTo(PList -> Coord);
		    ClosedObject = i;
		}

		if (DrawPNormalsFlag && PPolygon->HasPlane)
		{
		    for (i=0; i<3; i++) PolyNormal[i] += PList -> Coord[i];
		    NumOfVertices++;
		}
		/* If -e option specified #Edges to draw. */
		if (!(--Count)) return;
		DrawNextEdge = !PList -> Internal;
		PList = PList -> Pnext;
	    }

	    /* Close polygon by drawing a line to first vertex. */
	    if (DrawNextEdge || InterFlag)
		MyDrawTo(PPolygon -> PVertex -> Coord);

	    if (DrawPNormalsFlag && PPolygon->HasPlane)
	    {
		for (i=0; i<3; i++) PolyNormal[i] /= NumOfVertices;
		MyMoveTo(PolyNormal);
		for (i=0; i<3; i++) PolyNormal[i] += PPolygon->Plane[i];
		i = ClosedObject;
		ClosedObject = FALSE;
		MyDrawTo(PolyNormal);
		ClosedObject = i;
	    }
	    break;
    }
}

static double LastCoord[3];    /* Used to store last point we moved/draw to. */

/*****************************************************************************
* Routine to mave to 3D	point given as Coord[3], using Mat transform.	     *
*****************************************************************************/
static void MyMoveTo(float Coord[3])
{
    MultVecby4by4(LastCoord, Coord, CrntViewMat);   /* Set last point coord. */
}

/*****************************************************************************
* Routine to draw to 3D	point given as Coord[3], using Mat transform, from   *
* the last point we moved to.						     *
*****************************************************************************/
static void MyDrawTo(float Coord[3])
{
    double NewCoord[3], MiddleCoord[3], t;

    MultVecby4by4(NewCoord, Coord, CrntViewMat);    /* Set last point coord. */
    if (ClosedObject && NewCoord[2] < LastCoord[2]) {
	GEN_COPY(LastCoord, NewCoord, 3 * sizeof(double));
	return;
    }

    /* Implementation of simple depth cue - if line is >Z or <Z ... */
    if (LastCoord[2] <= 0.0 && NewCoord[2] <= 0.0) {
	if (GlblDepthCue) GGMySetLineStyle(DOTTED_LINE_STYLE);
	GGMyMove(LastCoord[0], LastCoord[1]);
	GGMyDraw(NewCoord[0], NewCoord[1]);			    /* DRAW! */
    }
    else
    if (LastCoord[2] >= 0.0 && NewCoord[2] >= 0.0 ||
	ABS(LastCoord[2] - NewCoord[2]) < EPSILON) {
	if (GlblDepthCue) GGMySetLineStyle(FULL_LINE_STYLE);
	GGMyMove(LastCoord[0], LastCoord[1]);
	GGMyDraw(NewCoord[0], NewCoord[1]);			    /* DRAW! */
    }
    else {				      /* Line intersect Z = 0 plane. */
	t = LastCoord[2] / (LastCoord[2] - NewCoord[2]);
	MiddleCoord[0] = LastCoord[0] * (1.0 - t) + NewCoord[0] * t;
	MiddleCoord[1] = LastCoord[1] * (1.0 - t) + NewCoord[1] * t;
	if (GlblDepthCue) GGMySetLineStyle(FULL_LINE_STYLE);
	if (LastCoord[2] > 0.0) {
	    GGMyMove(LastCoord[0], LastCoord[1]);
	    GGMyDraw(MiddleCoord[0], MiddleCoord[1]);		    /* DRAW! */
	}
	else {
	    GGMyMove(MiddleCoord[0], MiddleCoord[1]);
	    GGMyDraw(NewCoord[0], NewCoord[1]);			    /* DRAW! */
	}
	if (GlblDepthCue) GGMySetLineStyle(DOTTED_LINE_STYLE);
	if (LastCoord[2] < 0.0) {
	    GGMyMove(LastCoord[0], LastCoord[1]);
	    GGMyDraw(MiddleCoord[0], MiddleCoord[1]);		    /* DRAW! */
	}
	else {
	    GGMyMove(MiddleCoord[0], MiddleCoord[1]);
	    GGMyDraw(NewCoord[0], NewCoord[1]);			    /* DRAW! */
	}
    }

    GEN_COPY(LastCoord, NewCoord, 3 * sizeof(double)); /* Set current point. */
}

/*****************************************************************************
* Routine to set current drawing color to given	RGB values:		     *
* Currently only 8 colors are supported:				     *
*****************************************************************************/
static void SetDrawColor(int Color)
{
    GGMySetColor(Color);
}

/*****************************************************************************
*  Routine to test if quit display event - occured - SPACE was hit on	     *
* keyboard or right button was clicked on mouse.			     *
*****************************************************************************/
static void TestQuitView(void)
{
    if (IsAbortKeyPressed()) longjmp(LongJumpBuffer, 1);       /* Jump to... */
}

#endif /* __MSDOS__ */
