#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;

our $VERSION = '0.1.1';

use Getopt::Long qw(:config no_ignore_case bundling);

sub usage_message {
	print STDERR << "EOH";
usage: dizzy [options]

   Graphics settings:
     -w num           set window width
     -h num           set window height
     -f               run in fullscreen mode
     -r num           set texture resolution (power of two)
     -s num           set texture display scale

   Auto mode:
     -a num           set a new texture every num seconds

   Texture switching options:
     -t switcher      choose the texture switcher
     -T opt=val       pass options to the texture switcher

   Keyboard commands:
     cursor left      select previous texture
     cursor right     select next texture
     escape           exit dizzy
EOH
}

my %options = (
	help                   => sub { usage_message(); exit(0); },

	width                  => 0,
	height                 => 0,
	fullscreen             => 0,
	texture_resolution     => 64,
	texture_scale          => 50,

	automode               => 0,

	texswitcher            => 'Simple',
	texswitcher_options    => {},
);

GetOptions(\%options,
	'help|?',

	'width|w=i',
	'height|h=i',
	'fullscreen|f+',
	'texture_resolution|texture-resolution|r=i',
	'texture_scale|texture-scale|s=f',

	'automode|a=f',

	'texswitcher|t=s',
	'texswitcher_options|texswitcher-options|T=s',

	'debug_show_planes|debug-show-planes+',
	'debug_show_messages|debug-show-messages+',
) or (usage_message(), exit(1));

########
use lib 'lib';
use OpenGL qw(:all);
use Math::Trig;
use Time::HiRes qw(sleep time);
use Dizzy::TextureManager;
use Dizzy::TextureSwitcher;
use Dizzy::Textures;
use Dizzy::Render;
use Dizzy::GLUT;
use Dizzy::Handlers;

Dizzy::GLUT::init(title => "Dizzy", width => $options{width}, height => $options{height}, fullscreen => $options{fullscreen});
Dizzy::Render::init_view(texture_scale => $options{texture_scale});

Dizzy::TextureManager::init(
	texture_resolution => $options{texture_resolution},
);

# read textures
foreach my $texture (Dizzy::Textures::textures()) {
	Dizzy::TextureManager::add(%{$texture});
}

Dizzy::TextureSwitcher::init($options{texswitcher}, %{$options{texswitcher_options}});

# text rendering
my ($text_start, $text_text) = (0, "");
if ($options{debug_show_messages}) {
	Dizzy::Handlers::register_last(
		render => sub {
			if (defined $text_text and time() - $text_start <= 1.5 + length($text_text) / 13) {
				# disable blending and texturing, otherwise the text would look funny.
				glDisable(GL_BLEND);
				glDisable(GL_TEXTURE_2D);

				# draw the text shadow
				glColor3f(0, 0, 0);
				glRasterPos2f(-3.0, 2.2);
				foreach (split(//, $text_text)) {
					glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord $_);
				}

				# draw the text itself
				glColor3f(1, 1, 1);
				glRasterPos2f(-3.01, 2.19);
				foreach (split(//, $text_text)) {
					glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord $_);
				}

				# reenable texturing and blending
				glEnable(GL_BLEND);
				glEnable(GL_TEXTURE_2D);

				# update display
				glFlush();
			}
			Dizzy::Handlers::GO_ON;
		},
	);
}


Dizzy::Handlers::register(
	keyboard => sub {
		my %args = @_;

		# so we don't get warning spam
		$args{ascii} //= "";
		$args{special} //= -1;

		if ($args{ascii} eq "\e" or $args{ascii} eq "q") { # escape/q
			exit(0);
		} elsif ($args{special} == GLUT_KEY_LEFT or $args{special} == GLUT_KEY_RIGHT) {
			Dizzy::Handlers::invoke("texture_switch",
				direction => (($args{special} == GLUT_KEY_LEFT) ? -1 : +1),
			);
		}

		Dizzy::Handlers::GO_ON;
	},

	# notify user about texture switches
	texture_changed => sub {
		my %args = @_;
		print "*** selected texture \"$args{name}\"\n";

		# draw an informational message.
		$text_start = time;
		$text_text = $args{name};
		Dizzy::Handlers::GO_ON;
	},

	# auto mode. move? or leave it here?
	render => sub {
		state $last_switch = 0;

		if ($options{automode} > 0) {
			if ($last_switch + $options{automode} <= time()) {
				$last_switch = time();
				Dizzy::Handlers::invoke("texture_switch", direction => +1);
			}
		}

		Dizzy::Handlers::GO_ON;
	},

	# to be moved to: somewhere else (or keep it here? it's nice and warm)
	render => sub {
		Dizzy::Render::render_planes(
			tick => time() - $^T,
			rotator_func => sub {
				my ($tick, $plane) = @_;
				if ($options{debug_show_planes}) {
					glScalef(0.2, 0.2, 0.2);
				}
				if ($plane == 1) {
					glRotatef($tick * 5, 0, 0, 1);
					glTranslatef(sin($tick * 0.5), cos($tick * 0.75), 0);
				} elsif ($plane == 2) {
					glRotatef($tick * -2.5, 0, 0, 1);
					glTranslatef(sin($tick * 0.5), cos($tick * 0.75), 0);
				}
			},
		);

		Dizzy::Handlers::GO_ON;
	},
);

Dizzy::TextureManager::set(0);

Dizzy::GLUT::run();

__END__

=head1 NAME

B<dizzy> - a graphics demo that makes you dizzy using rotating textures

=head1 SYNOPSIS

B<dizzy> [B<-f>|B<-w> I<width> B<-h> I<height>] [B<-t> I<switch_module>] [B<-T> I<options>]

=head1 DESCRIPTION

B<dizzy> is a graphics demo that rotates planes of patterns on a colored
background to make you dizzy. Textures can be cross-faded and there is a mode
that automatically changes textures, allowing Dizzy to be run as a screensaver.

=head1 OPTIONS

=over

=item B<-w> I<width>

=item B<--width> I<width>

=item B<-h> I<height>

=item B<--height> I<height>

Sets the window width and height.

=item B<-f>

=item B<--fullscreen>

Attempts to switch into a true fullscreen mode, if possible. The window size
parameters are ignored.

=item B<-a>

=item B<--automode> I<time>

Automatically switches textures after a specified number of seconds has passed.
I<time> can be fractional and the decimal separator is always the period.

=item B<-t> I<module>

=item B<--texswitcher> I<module>

Selects the texture switching module to use. Default is B<Simple>.

See below for available texture switchers and their descriptions.

=item B<-T> I<option>=I<value>

=item B<--texswitcher-options> I<option>=I<value>

Passes an option I<option> with the value I<value> to the selected texture
switcher. The available options depend on the texture switcher used.

This option can be given multiple times to set multiple options.

=item B<-r> I<resolution>

=item B<--texture-resolution> I<resolution>

Changes the texture resolution. I<resolution> must be a power of two. The default
value is 64.

=item B<-s> I<scale>

=item B<--texture-scale> I<scale>

Changes the texture scale factor, which is 50 by default, to I<scale>. Smaller
numbers result in larger boxes drawn on-screen, larger numbers draw smaller
boxes.

=item B<--debug-show-planes>

Zooms out of the normal view so you can see how Dizzy creates the animation.

=item B<--debug-show-messages>

Display some messages not only on standard output, but also in the GL window.

=back

=head1 TEXTURE SWITCHERS

=head2 Simple

A simple texture switcher. It just sets the new texture when it is told to do
so. It takes no options.

=head2 Blend

A texture switcher that crossfades between textures to generate a smooth
transition. It takes one option:

=over

=item B<blend>=I<duration>

Sets the duration of a blend to I<duration> seconds. The value can be fractional
(the decimal separator is always a period).  The default value is 2.

Note that you have to add the time you specify here to the automode time, so if
you want the transition to take two seconds and every image to stay for five
seconds, you set the duration to 2 and automode to 7 (not 5).

=back

=head1 KEYBOARD COMMANDS

=over

=item Cursor left

Select previous available texture.

=item Cursor right

Select next available texture.

=item Escape

=item q

Exit Dizzy.

=back

=cut
