/* Copyright (C) 2002-2003 Damir Zucic */

/*=============================================================================

				small_atoms.c

Purpose:
	Draw small atoms (small style).

Input:
	(1) Pointer to MolComplexS structure.
	(2) Number of macromolecular complexes.
	(3) Pointer to ConfigS structure, with configuration data.
	(4) Pointer to GUIS structure.
	(5) Pointer to NearestAtomS structure, with information about the
	    atom occupying the given pixel.
	(6) The number of pixels in the main window free area.
	(7) The refreshI, used to check the  NearestAtomS associated with
	    a given pixel.

Output:
	(1) Small spheres drawn to the hidden pixmap.
	(2) Return value.

Return value:
	(1) Positive always (trivial).

Notes:
	(1) Indentation is exceptionally 4 spaces.

=============================================================================*/

#include <stdio.h>

#include <math.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>

#include "defines.h"
#include "typedefs.h"

/*======function prototypes:=================================================*/

unsigned long	SpacefillColor_ (AtomS *, GUIS *, double);

/*======draw atoms as spheres, small style:==================================*/

int DrawSmall_ (MolComplexS *mol_complexSP, int mol_complexesN,
		ConfigS *configSP, GUIS *guiSP,
		NearestAtomS *nearest_atomSP, size_t pixelsN,
		unsigned int refreshI)
{
int			imageI, imagesN;
double			scale_factor, user_atomic_position;
int			left_edge[2], right_edge[2];
int			mol_complexI;
MolComplexS		*curr_mol_complexSP;
size_t			atomsN, atomI;
AtomS			*curr_atomSP;
int			screen_x0, screen_y0;
double			radius, radius_squared;
double			denominator, reciprocal_denominator;
int			screen_radius;
long			screen_radius_squared;
int			screen_x1, screen_y1, screen_x2, screen_y2;
int			screen_x, screen_y;
long			delta_x, delta_y, distance_squared;
double			z0, front_z, delta_z, z;
size_t			pixelI;
NearestAtomS		*curr_pixelSP;
double			denominator2, reciprocal_denominator2;
double			rho_squared;
VectorS			vectorS;
double			abs_value, abs_value_squared;
double			scalar_product, cos_angle;
unsigned long		colorID;
int			bondI;

/* Initialize the bond index. The negative value means that pixels */
/* filled  in this function  are not a part of  any chemical bond. */
bondI = -1;

/* Number of images: */
if (configSP->stereoF) imagesN = 2;
else imagesN = 1;

/* The auxiliary scale factor: */
scale_factor = configSP->user_screen_atomic_distance *
	       configSP->atomic_to_screen_scale_x;

/* Prepare the user position in atomic coordinates: */
user_atomic_position = configSP->user_atomic_position;

/* Left and right image edge (in stereo mode there are two images): */
left_edge[0]  = configSP->image_screen_x0[0];
right_edge[0] = configSP->image_screen_x1[0];
left_edge[1]  = configSP->image_screen_x0[1];
right_edge[1] = configSP->image_screen_x1[1];

/*------first pass - fill NearestAtomS array with planar atoms:--------------*/

/* Draw each macromolecular complex: */
for (mol_complexI = 0; mol_complexI < mol_complexesN; mol_complexI++)
    {
    /* Pointer to current macromolecular complex: */
    curr_mol_complexSP = mol_complexSP + mol_complexI;

    /* Prepare and check the number of atoms: */
    atomsN = curr_mol_complexSP->atomsN;
    if (atomsN == 0) continue;

    /* Draw atoms which have the given style: */
    for (atomI = 0; atomI < atomsN; atomI++)
	{
	/* Pointer to the current atom: */
	curr_atomSP = curr_mol_complexSP->atomSP + atomI;

	/* Check style: */
	if (curr_atomSP->raw_atomS.atom_styleI != SMALL_ATOM) continue;

	/* Check is atom hidden: */
	if (curr_atomSP->hiddenF) continue;

	/* Check is atom inside slab: */
	if (!curr_atomSP->inside_slabF) continue;

	/* Check is atom inside window: */
	if (!curr_atomSP->inside_windowF) continue;

	/* Small radius, in atomic units: */
	radius = curr_atomSP->raw_atomS.small_radius;

	/* The y coordinate of atomic center, in screen units: */
	screen_y0 = curr_atomSP->raw_atomS.screen_y;

	/* Prepare one image (mono) or two images (stereo): */
	for (imageI = 0; imageI < imagesN; imageI++)
            {
	    /* The z coordinate of atomic center, in atomic units: */
	    z0 = curr_atomSP->raw_atomS.z[imageI];

	    /* Prepare the factor required for the projection of radius: */
	    denominator = z0 - user_atomic_position;
	    if (denominator == 0.0) continue;
	    reciprocal_denominator = 1.0 / denominator;

	    /* Small radius in screen units: */
	    screen_radius = (int) (radius *
				   scale_factor *
				   reciprocal_denominator +
				   0.5);

	    /* Screen radius squared (used to improve speed): */
	    screen_radius_squared = (long) screen_radius *
				    (long) screen_radius;

	    /* The x coordinate of atomic center, in screen units: */
	    screen_x0 = curr_atomSP->raw_atomS.screen_x[imageI];

	    /* Define the bounding rectangle: */
	    screen_x1 = screen_x0 - screen_radius;
	    screen_y1 = screen_y0 - screen_radius;
	    screen_x2 = screen_x0 + screen_radius;
	    screen_y2 = screen_y0 + screen_radius;

	    /* Horizontal scan: */
	    for (screen_x = screen_x1; screen_x <= screen_x2; screen_x++)
		{
		/* Check horizontal position: */
		if (screen_x <  left_edge[imageI])  continue;
		if (screen_x >= right_edge[imageI]) continue;

		/* Vertical scan: */
		for (screen_y = screen_y1; screen_y <= screen_y2; screen_y++)
		    {
		    /* Check vertical position: */
		    if (screen_y < 0) continue;
		    if (screen_y >= (int) guiSP->main_win_free_area_height)
			{
			continue;
			}

		    /* Check distance from the circle center: */
		    delta_x = (long) (screen_x - screen_x0);
		    delta_y = (long) (screen_y - screen_y0);
		    distance_squared = delta_x * delta_x + delta_y * delta_y;
		    if (distance_squared > screen_radius_squared) continue;

		    /* Prepare index  to the array */
		    /* of NearestAtomS structures: */
		    pixelI = guiSP->main_win_free_area_width * screen_y +
			     screen_x;

		    /* Check the pixel index: */
		    if (pixelI >= pixelsN) continue;

		    /* Pointer to  NearestAtomS struct. */
		    /* assigned to current coordinates: */
		    curr_pixelSP = nearest_atomSP + pixelI;

		    /* Check was  this pixel used  already in */
		    /* this drawing step;  if it was, compare */
		    /* the z value of the current atom with z */
		    /* value previously stored to this pixel: */
		    if (refreshI == curr_pixelSP->last_refreshI)
			{
			if (z0 > curr_pixelSP->z) continue;
			}

		    /* Refresh the content of NearestAtomS */
		    /* array  associated  with this pixel: */
		    curr_pixelSP->styleI = SMALL_ATOM;
		    curr_pixelSP->last_refreshI = refreshI;
		    curr_pixelSP->mol_complexI = mol_complexI;
		    curr_pixelSP->atomI = atomI;
		    curr_pixelSP->bondI = bondI;
		    curr_pixelSP->z = z0;
		    }
		}
	
	    }	/* imageI loop */
	}	/* atomI  loop */
    }		/* mol_complexI loop */

/*------second pass - draw spherical atoms:----------------------------------*/

/* Draw each macromolecular complex: */
for (mol_complexI = 0; mol_complexI < mol_complexesN; mol_complexI++)
    {
    /* Pointer to current macromolecular complex: */
    curr_mol_complexSP = mol_complexSP + mol_complexI;

    /* Prepare and check the number of atoms: */
    atomsN = curr_mol_complexSP->atomsN;
    if (atomsN == 0) continue;

    /* Draw atoms which have the given style: */
    for (atomI = 0; atomI < atomsN; atomI++)
	{
	/* Pointer to the current atom: */
	curr_atomSP = curr_mol_complexSP->atomSP + atomI;

	/* Check style: */
	if (curr_atomSP->raw_atomS.atom_styleI != SMALL_ATOM) continue;

	/* Check is atom hidden: */
	if (curr_atomSP->hiddenF) continue;

	/* Check is atom inside slab: */
	if (!curr_atomSP->inside_slabF) continue;

	/* Check is atom inside window: */
	if (!curr_atomSP->inside_windowF) continue;

	/* Small radius, in atomic units: */
	radius = curr_atomSP->raw_atomS.small_radius;

	/* Squared small radius: */
	radius_squared = radius * radius;

	/* The y coordinate of atomic center, in screen units: */
	screen_y0 = curr_atomSP->raw_atomS.screen_y;

	/* Prepare one image (mono) or two images (stereo): */
	for (imageI = 0; imageI < imagesN; imageI++)
            {
	    /* The z coordinate of atomic center, in atomic units: */
	    z0 = curr_atomSP->raw_atomS.z[imageI];

	    /* The z coordinate of the nearest */
	    /* point of a given atom (sphere): */
	    front_z = z0 - radius;

	    /* Prepare the factor required for the projection of radius: */
	    denominator = z0 - user_atomic_position;
	    if (denominator == 0.0) continue;
	    reciprocal_denominator = 1.0 / denominator;

	    /* Small radius in screen units: */
	    screen_radius = (int) (radius *
				   scale_factor *
				   reciprocal_denominator +
				   0.5);

	    /* Square of the small radius (in screen units): */
	    screen_radius_squared = (long) screen_radius *
				    (long) screen_radius;

	    /* Reciprocal value will be used to improve performance: */
	    denominator2 = (double) screen_radius_squared;
	    if (denominator2 == 0.0) continue;
	    reciprocal_denominator2 = 1.0 / denominator2;

	    /* The x coordinate of atomic center, in screen units: */
	    screen_x0 = curr_atomSP->raw_atomS.screen_x[imageI];

	    /* Define the bounding rectangle: */
	    screen_x1 = screen_x0 - screen_radius;
	    screen_y1 = screen_y0 - screen_radius;
	    screen_x2 = screen_x0 + screen_radius;
	    screen_y2 = screen_y0 + screen_radius;

	    /* Horizontal scan: */
	    for (screen_x = screen_x1; screen_x <= screen_x2; screen_x++)
		{
		/* Check horizontal position: */
		if (screen_x < left_edge[imageI])  continue;
		if (screen_x > right_edge[imageI]) continue;

		/* Vertical scan: */
		for (screen_y = screen_y1; screen_y <= screen_y2; screen_y++)
		    {
		    /* Check vertical position: */
		    if (screen_y < 0) continue;
		    if (screen_y >= (int) guiSP->main_win_free_area_height)
			{
			continue;
			}

		    /* Check distance from the circle center: */
		    delta_x = (long) (screen_x - screen_x0);
		    delta_y = (long) (screen_y - screen_y0);
		    distance_squared = delta_x * delta_x + delta_y * delta_y;
		    if (distance_squared > screen_radius_squared) continue;

		    /* Prepare index  to the array */
		    /* of NearestAtomS structures: */
		    pixelI = guiSP->main_win_free_area_width * screen_y +
			     screen_x;

		    /* Check the pixel index: */
		    if (pixelI >= pixelsN) continue;

		    /* Pointer to  NearestAtomS struct. */
		    /* assigned to current coordinates: */
		    curr_pixelSP = nearest_atomSP + pixelI;

		    /* Check z value (this is just a quick check): */
		    if (refreshI == curr_pixelSP->last_refreshI)
			{
			if (front_z > curr_pixelSP->z) continue;
			}

		    /* Calculate the accurate z value: */
		    rho_squared = radius_squared *
				  (double) distance_squared *
				  reciprocal_denominator2;
		    delta_z = sqrt (fabs (radius_squared - rho_squared));
		    z = z0 - delta_z;

		    /* Check z value (precise check): */
		    if (refreshI == curr_pixelSP->last_refreshI)
			{
			if (z > curr_pixelSP->z) continue;
			}

		    /* The vector from sphere center to the current pixel: */
		    vectorS.x = (double) delta_x;
		    vectorS.y = (double) delta_y;
		    vectorS.z = - sqrt (fabs (screen_radius_squared -
					      vectorS.x * vectorS.x -
					      vectorS.y * vectorS.y));
		    abs_value_squared = vectorS.x * vectorS.x +
					vectorS.y * vectorS.y +
					vectorS.z * vectorS.z;
		    abs_value = sqrt (abs_value_squared);

		    /* The scalar product  between this */
		    /* vector and  light source vector: */
		    scalar_product = vectorS.x * configSP->light_vectorS.x +
				     vectorS.y * configSP->light_vectorS.y +
				     vectorS.z * configSP->light_vectorS.z;

		    /* Cosine of  the angle between  the vector to the */
		    /* current pixel and the light source unit vector: */
		    if (abs_value == 0.0) cos_angle = 0.0;
		    else cos_angle = scalar_product / abs_value;

		    /* Prepare color: */
		    colorID = SpacefillColor_ (curr_atomSP, guiSP, cos_angle);

		    XSetForeground (guiSP->displaySP,
				    guiSP->theGCA[0],
				    colorID);

		    XDrawPoint (guiSP->displaySP,
				guiSP->main_hidden_pixmapID,
				guiSP->theGCA[0],
				screen_x, screen_y);

		    /* Refresh the content of NearestAtomS */
		    /* array  associated  with this pixel: */
		    curr_pixelSP->styleI = SMALL_ATOM;
		    curr_pixelSP->last_refreshI = refreshI;
		    curr_pixelSP->mol_complexI = mol_complexI;
		    curr_pixelSP->atomI = atomI;
		    curr_pixelSP->bondI = bondI;
		    curr_pixelSP->z = z;
		    curr_pixelSP->colorID = colorID;
		    }
		}
	
	    }	/* imageI loop */
	}	/* atomI  loop */
    }		/* mol_complexI loop */

/*---------------------------------------------------------------------------*/

/* Return positive value (trivial): */
return 1;
}

/*===========================================================================*/


