# XRACER (C) 1999-2000 Richard W.M. Jones <rich@annexia.org> and other AUTHORS
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# $Id: BlenderImport.pm,v 1.1 2000/01/30 12:11:31 rich Exp $

package XRacer::BlenderImport;

use Exporter;

@ISA = qw( Exporter );
@EXPORT = qw(  );

use XRacer::Math;

use strict;

sub parse
  {
    my $class = shift;
    my $filename = shift || "blender.export";

    unless (open IMPORTFILE, $filename)
      {
	warn "$filename: $!";
	return undef;
      }

    my $world = { vertices => [],
		  vertexhash => {},
		  layers => [] };

    bless $world, $class;

    while ($_ = _next_line (\*IMPORTFILE))
      {
	my ($name, $layer, $has_col, $has_uvco, $has_mat)
	  = split /[ \t]+/, $_;

	# Layer is a bitmap of the actual layers in which
	# this object exists. For objects which lie in multiple
	# layers, choose the smallest layer number and print
	# a warning.
	$layer = _get_layer ($name, $layer);

	#warn "reading object: $name (layer $layer)";

	# Read the number of faces.
	unless ($_ = _next_line (\*IMPORTFILE))
	  { warn "$filename: unexpected EOF"; return undef }

	my $nr_faces = $_;
	my @faces = ();

	# Read each face in turn.
	for (my $i = 0; $i < $nr_faces; ++$i)
	  {
	    # Read the number of vertices in this face.
	    unless ($_ = _next_line (\*IMPORTFILE))
	      { warn "$filename: unexpected EOF"; return undef }

	    my $nr_vertices = $_;
	    my @face_vertices = ();

	    # Read each vertex in turn.
	    for (my $j = 0; $j < $nr_vertices; ++$j)
	      {
		# Read the vertex.
		unless ($_ = _next_line (\*IMPORTFILE))
		  { warn "$filename: unexpected EOF"; return undef }

		my ($x, $y, $z, $u, $v, $nx, $ny, $nz);

		if ($has_uvco)
		  {
		    ($x, $y, $z, $u, $v, $nx, $ny, $nz)
		      = split /[ \t]+/, $_;
		  }
		else
		  {
		    $u = $v = 0;
		    ($x, $y, $z, $nx, $ny, $nz)
		      = split /[ \t]+/, $_;
		  }

		# Store the vertex.
		push @face_vertices,
		{ coords => [ $x, $y, $z, 0 ],
		  texcoords => [ $u, $v ],
		  normal => [ $nx, $ny, $nz, 0 ],
		  colour => [ 1, 1, 1, 1 ] };
	      }

	    # Vertex colours?
	    if ($has_col)
	      {
		# Read the number of vertex colours.
		unless ($_ = _next_line (\*IMPORTFILE))
		  { warn "$filename: unexpected EOF"; return undef }

		my $nr_vertex_colours = $_;

		if ($nr_vertex_colours != $nr_vertices)
		  {
		    warn "$filename: number of vertex colours doesn't match number of vertices";
		    return undef;
		  }

		for (my $j = 0; $j < $nr_vertex_colours; ++$j)
		  {
		    # Read the vertex colour.
		    unless ($_ = _next_line (\*IMPORTFILE))
		      { warn "$filename: unexpected EOF"; return undef }

		    my ($r, $g, $b, $a) = split /[ \t]+/, $_;

		    $face_vertices[$j]->{colour} = [ $r, $g, $b, $a ];
		  }
	      }

	    push @faces, { vertices => \@face_vertices };
	  }

	# Read the transformation matrices.
	unless ($_ = _next_line (\*IMPORTFILE))
	  { warn "$filename: unexpected EOF"; return undef }

	my ($sizex, $sizey, $sizez) = split /[ \t]+/, $_;

	unless ($_ = _next_line (\*IMPORTFILE))
	  { warn "$filename: unexpected EOF"; return undef }

	my ($rotx, $roty, $rotz) = split /[ \t]+/, $_;

	unless ($_ = _next_line (\*IMPORTFILE))
	  { warn "$filename: unexpected EOF"; return undef }

	my ($locx, $locy, $locz) = split /[ \t]+/, $_;

	my ($matr, $matg, $matb) = (1, 1, 1);

	if ($has_mat)
	  {
	    # Read the material colour.
	    unless ($_ = _next_line (\*IMPORTFILE))
	      { warn "$filename: unexpected EOF"; return undef }

	    ($matr, $matg, $matb) = split /[ \t]+/, $_;
	  }

	# Transform all the vertices by the rotation matrix
	# so we have the real coordinates. Add vertices onto
	# the global list of vertices.
	my $cosx = cos ($rotx);
	my $sinx = sin ($rotx);

	my $matx = [ [ 1,     0,      0, 0 ],
		     [ 0, $cosx, -$sinx, 0 ],
		     [ 0, $sinx,  $cosx, 0 ],
		     [ 0,     0,      0, 0 ] ];

	my $cosy = cos ($roty);
	my $siny = sin ($roty);

	my $maty = [ [ $cosy,  0, $siny, 0 ],
		     [    0,   1,     0, 0 ],
		     [ -$siny, 0, $cosy, 0 ],
		     [ 0,      0,     0, 0 ] ];

	my $cosz = cos ($rotz);
	my $sinz = sin ($rotz);

	my $matz = [ [ $cosz, -$sinz, 0, 0 ],
		     [ $sinz,  $cosz, 0, 0 ],
		     [     0,      0, 1, 0 ],
		     [     0,      0, 0, 0 ] ];

	my $mat = matrix_multiply (matrix_multiply ($matz, $maty),
				   $matx);

	my $face;
	foreach $face (@faces)
	  {
	    my @face_vertices = ();

	    my $vertex;
	    foreach $vertex (@{$face->{vertices}})
	      {
		$vertex->{coords}
		  = matrix_vector_multiply ($mat, $vertex->{coords});

		$vertex->{coords}[0] *= $sizex;
		$vertex->{coords}[1] *= $sizey;
		$vertex->{coords}[2] *= $sizez;

		$vertex->{coords}[0] += $locx;
		$vertex->{coords}[1] += $locy;
		$vertex->{coords}[2] += $locz;

		$vertex->{normal}
		  = matrix_vector_multiply ($mat, $vertex->{normal});

		my $vertexindex = $world->add_vertex ($vertex);

		push @face_vertices, $vertexindex;
	      }

	    $face->{vertices} = \@face_vertices;
	  }

	# Push the mesh into the appropriate layer.
	unless (defined ($world->{layers}[$layer]))
	  {
	    $world->{layers}[$layer] = [];
	  }

	my $mesh = {
		    name => $name,
		    layer => $layer,
		    faces => \@faces,
		    material => [ $matr, $matg, $matb ],
		    has_colours => $has_col,
		    has_texcoords => $has_uvco,
		    has_material => $has_mat
		   };

	push @{$world->{layers}[$layer]}, $mesh;
      }

    close IMPORTFILE;

    return $world;
  }

sub _next_line
  {
    my $fh = shift;

    while (<$fh>)
      {
	# Remove trailing CR, LF.
	s/[\n\r]+$//;

	# Ignore blank lines, comments.
	next if m/^[ \t]*#/;
	next if m/^[ \t]*$/;

	return $_;
      }

    return undef;
  }

sub _get_layer
  {
    my $name = shift;
    my $layer_in = shift;
    my $layer_out = 0;

    while (($layer_in & 1) == 0)
      {
	$layer_in >>= 1;
	$layer_out ++;
      }

    if ($layer_in != 1)
      {
	warn "object $name is in multiple layers: using layer $layer_out";
      }

    return $layer_out;
  }

sub add_vertex
  {
    my $world = shift;
    my $v = shift;

    my $index;

    my $hashkey = join ",",
                  (
		   $v->{coords}[0],
		   $v->{coords}[1],
		   $v->{coords}[2],
		   $v->{coords}[3],
		   $v->{texcoords}[0],
		   $v->{texcoords}[1],
		   $v->{normal}[0],
		   $v->{normal}[1],
		   $v->{normal}[2],
		   $v->{normal}[3],
		   $v->{colour}[0],
		   $v->{colour}[1],
		   $v->{colour}[2],
		   $v->{colour}[3]
		  );

    if (exists ($world->{vertexhash}{$hashkey}))
      {
	return $world->{vertexhash}{$hashkey};
      }
    else
      {
	push @{$world->{vertices}}, $v;
	$index = @{$world->{vertices}} - 1;
	$world->{vertexhash}{$hashkey} = $index;

	return $index;
      }
  }

sub get_vertices
  {
    my $world = shift;

    return $world->{vertices};
  }

sub get_layer_info
  {
    my $world = shift;
    my @layers = @{$world->{layers}};
    my %info = ();

    for (my $i = 0; $i < @layers; ++$i)
      {
	if (defined ($layers[$i]) && @{$layers[$i]} > 0)
	  {
	    $info{$i} = @{$layers[$i]};
	  }
      }

    return %info;
  }

sub get_meshes_in_layer
  {
    my $world = shift;
    my $layer = shift;

    return @{$world->{layers}[$layer]};
  }

1;
__END__

=head1 NAME

XRacer::BlenderImport - Import files exported by xracer-blenderexport.py

=head1 SYNOPSIS

  use XRacer::BlenderImport;

  $world = parse XRacer::BlenderImport [ $filename ];

  $index = $world->add_vertex ($vertex);
  $verticesref = $world->get_vertices;
  %layerinfo = $world->get_layer_info;

  @objects = $world->get_meshes_in_layer ($layer);

=head1 DESCRIPTION

The C<XRacer::BlenderImport> module contains functions for
importing special XRacer-specific Blender files into Perl scripts.
These Blender files have been previously exported by the
C<xracer-blenderexport.py> Python script for Blender.

The C<XRacer::BlenderImport> module parses the "blender.export"
file, cleans it up (removing multiple vertices, for example)
and presents an internal I<world> representation. The world
is divided into layers (corresponding to the layers in the
original Blender image), and in each of these layers is a
set of meshes.

=head2 FUNDAMENTAL TYPES

Vertices are stored in a global list, so that common vertices
are only stored once. A vertex structure looks like this:

  $vertex = { coords => [ $x, $y, $z, 0 ],
              texcoords => [ $u, $v ],
              normal => [ $nx, $ny, $nz, 0 ],
              colour => [ $r, $g, $b, $a ] };

The fields are (in order): the coordinates of the vertex, the
texture coordinates, the normal vector at this point and the
colour of the vertex.

Faces are stored simply as a list of vertex indices (relative
to the global list of vertices). A face looks like this:

  $face = { vertices => [ $index0, $index1, $index2, ... ] }

Faces have at least three vertices, and maybe more.

A mesh is a list of faces and additional information, such as
the name of the mesh (object). A mesh structure looks like this:

  $mesh = { name => $name,
            layer => $layer,
            faces => \@faces,
            material => [ $red, $green, $blue ],
            has_colours => $has_colours,
            has_texcoords => $has_texcoords,
            has_material => $has_material };

The fields are: the name of the mesh (or object), the layer
on which the object exists, the list of faces, the material
and then three flags which are passed to us from Blender:
did the user supply vertex colours? did the user supply
texture coordinates? and did the user supply a material?

=head1 CLASS METHODS

=over 4

=item $world = parse XRacer::BlenderImport [ $filename ];

Parse the import file C<$filename> (or "blender.export" if
no filename is given) and generate a I<world> representation.
If the file could not be parsed, then this function will print
an error message and return C<undef>.

=back

=head1 OBJECT METHODS

=over 4

=item $index = $world->add_vertex ($vertex)

This function adds a single vertex to the world object (vertices
are stored in a large shared list so that common vertices are
folded into one). It returns the vertex index of the new vertex.
If another vertex with the same position, texture coordinates,
normal and colour existed, then this function would return the
index of the other vertex, rather than creating a fresh vertex
object.

=item $verticesref = $world->get_vertices

This returns a reference to the global list of vertices. You
B<must not> update or change this list. Use the C<add_vertex> method
instead.

=item %layerinfo = $world->get_layer_info

This method returns a hash. The I<keys> of the hash are layers which
contain at least one object. The I<values> of the hash are the number
of objects in that layer.

For example, if the world contained 3 objects on layer 1, 1 object
on layer 2 and 4 objects on layer 5, then the hash returned would
be equivalent to:

  %layerinfo = ( 1 => 3, 2 => 1, 5 => 4 );

=item @objects = $world->get_meshes_in_layer ($layer)

Get a list of the objects (i.e. meshes) found in layer C<$layer>.
See the DESCRIPTION section above for a description of the
mesh structure.

=back

=head1 AUTHOR

  Richard W.M. Jones, <rich@annexia.org>

=head1 COPYRIGHT

XRacer is copyright (C) 1999-2000 Richard W.M. Jones (rich@annexia.org)
and other contributors listed in the AUTHORS file.

=head1 SEE ALSO

L<perl(1)>, L<xracer(6)>.

=cut
