/*************************************************************************
	File:	pcld_out.c

	FormZ unstructured translator sample.  Imports and exports point cloud data.

	COPYRIGHT (C) 2001.  All Rights Reserved.
	auto*des*sys, Inc., Columbus, Ohio, USA.
*************************************************************************/

#include "pcld_prvt.h"



/*************************************************************************
	Opens and writes a point cloud file.
	All objects in the file will be written as one big point cloud.
	The density is set by the first object found with a density attribute.
		If no object has a density attribute, a default value of 0.1 is used.
*************************************************************************/
fzrt_error_td pcld_write(fzrt_int windex, fzrt_floc_ptr floc)
{
	fzrt_error_td	err = FZRT_NOERR;
	fz_objt_ptr		obj;
	double			density = 0.1, dens;
	fzrt_boolean	has_dens, found = FALSE;
	fzrt_int			pnt_cnt = 0, pcnt, i;
	fz_xyz_td		pnt;
	FILE			*fp;
	char			fname[256];
	char			tmp_name[256];
	
	/* Iterate over all objects to accumulate a total point count. */
	err = _model_funcs.fz_objt_get_next(windex, NULL, &obj);
	while(obj != NULL && err == FZRT_NOERR)
	{
		/* Use first density found and compute a point count */
		_model_attr_funcs.fz_objt_attr_get_objt_sdns(windex, obj, &has_dens, &dens);
		if(has_dens && !found)
		{
			found = TRUE;
			density = dens;
		}
		/* Get the location of the vertex and add it to the point count. */
		_model_funcs.fz_objt_get_point_count(windex, obj, FZ_OBJT_MODEL_TYPE_FACT, &pcnt);
		if(pcnt > 0)	pnt_cnt += pcnt;
	
		err = _model_funcs.fz_objt_get_next(windex, obj, &obj);
	}
	
	/* Get the file name and open the file. */
	err = _fzrt_file_funcs.fzrt_file_floc_get_name(floc, fname, 256);
	_fzrt_file_funcs.fzrt_file_cnvt_name(fname, tmp_name, 256);
	fp = fopen(tmp_name, "w");
	if(fp != NULL && err == FZRT_NOERR)
	{
		/* Write the total point count and density. */
		fprintf(fp, "%d %f\n", pnt_cnt, density*_export_scale);
	
		/* Iterate over all objects and write the objects' points. */
		err = _model_funcs.fz_objt_get_next(windex, NULL, &obj);
		while(obj != NULL && err == FZRT_NOERR)
		{
			/* Get the number of vertices in the object. */
			_model_funcs.fz_objt_get_point_count(windex, obj, FZ_OBJT_MODEL_TYPE_FACT, &pcnt);
			for(i = 0; i < pcnt; i++)
			{
				/* Get the location of the vertex. */
				_model_funcs.fz_objt_point_get_xyz(windex, obj, i, FZ_OBJT_MODEL_TYPE_FACT, &pnt);
				pnt.x *= _export_scale;
				pnt.y *= _export_scale;
				pnt.z *= _export_scale;
				fprintf(fp, "%f %f %f\n", pnt.x, pnt.y, pnt.z);
			}
	
			err = _model_funcs.fz_objt_get_next(windex, obj, &obj);
		}
		
		/* Close the file. */
		fclose(fp);
	}

	return(err);
}
