#!/usr/bin/perl -w

# afm2txf.pl 0.2
#
# Generates .txf font textures from Type 1 fonts
# Requirements: Ghostscript, ImageMagick
#
# Usage:
#       afm2txf.pl whatever.afm
#
# Changelog:
#       0.2 (06/28/2002): Generate fonts with proper padding
#       0.1 (06/28/2002): Initial version
#
# Copyright (C) 2002 Andrew James Ross
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

use strict;

my $METRICS = shift or die; # AFM file

# Texture size
my $TEXSIZ = 256;

# Padding around each character, for mipmap separation
my $PADDING = 4;

# Antialiasing multiplier.  Should be 16 for production work.  As low
# as 4 works well for testing.
my $DOWNSAMPLE = 16;

# The printable ISO-8859-1 characters (and space and hard space) and their
# postscript glyph names.  We use names because not all postscript
# fonts are encoded using ASCII.  AFM metrics generated by ttf2afm, in
# fact, don't have any numerical character IDs at all.  In principle,
# this mechanism will work for any 8 bit font encoding, you just have
# to do the legwork of figuring out the name to ID mapping.
my %CHARS = ('space'=>32, 'exclam'=>33, 'quotedbl'=>34,
	     'numbersign'=>35, 'dollar'=>36, 'percent'=>37,
	     'ampersand'=>38, 'quotesingle'=>39, 'parenleft'=>40,
	     'parenright'=>41, 'asterisk'=>42, 'plus'=>43,
	     'comma'=>44, 'hyphen'=>45, 'period'=>46, 'slash'=>47,
	     'zero'=>48, 'one'=>49, 'two'=>50, 'three'=>51,
	     'four'=>52, 'five'=>53, 'six'=>54, 'seven'=>55,
	     'eight'=>56, 'nine'=>57, 'colon'=>58, 'semicolon'=>59,
	     'less'=>60, 'equal'=>61, 'greater'=>62, 'question'=>63,
	     'at'=>64, 'A'=>65, 'B'=>66, 'C'=>67, 'D'=>68, 'E'=>69,
	     'F'=>70, 'G'=>71, 'H'=>72, 'I'=>73, 'J'=>74, 'K'=>75,
	     'L'=>76, 'M'=>77, 'N'=>78, 'O'=>79, 'P'=>80, 'Q'=>81,
	     'R'=>82, 'S'=>83, 'T'=>84, 'U'=>85, 'V'=>86, 'W'=>87,
	     'X'=>88, 'Y'=>89, 'Z'=>90, 'bracketleft'=>91,
	     'backslash'=>92, 'bracketright'=>93, 'asciicircum'=>94,
	     'underscore'=>95, 'quoteleft'=>96, 'a'=>97, 'b'=>98, 'c'=>99,
	     'd'=>100, 'e'=>101, 'f'=>102, 'g'=>103, 'h'=>104,
	     'i'=>105, 'j'=>106, 'k'=>107, 'l'=>108, 'm'=>109,
	     'n'=>110, 'o'=>111, 'p'=>112, 'q'=>113, 'r'=>114,
	     's'=>115, 't'=>116, 'u'=>117, 'v'=>118, 'w'=>119,
	     'x'=>120, 'y'=>121, 'z'=>122, 'braceleft'=>123,
	     'bar'=>124, 'braceright'=>125, 'asciitilde'=>126,
	     'space'=>160, 'exclamdown'=>161, 'cent'=>162, 'sterling'=>163,
	     'currency'=>164, 'yen'=>165, 'brokenbar'=>166, 'section'=>167,
	     'dieresis'=>168, 'copyright'=>169, 'ordfeminine'=>170, 'guillemotleft'=>171,
	     'logicalnot'=>172, 'hyphen'=>173, 'registered'=>174, 'macron'=>175,
	     'degree'=>176, 'plusminus'=>177, 'twosuperior'=>178, 'threesuperior'=>179,
	     'acute'=>180, 'mu'=>181, 'paragraph'=>182, 'bullet'=>183,
	     'cedilla'=>184, 'onesuperior'=>185, 'ordmasculine'=>186, 'guillemotright'=>187,
	     'onequarter'=>188, 'onehalf'=>189, 'threequarters'=>190, 'questiondown'=>191,
	     'Agrave'=>192, 'Aacute'=>193, 'Acircumflex'=>194, 'Atilde'=>195,
	     'Adieresis'=>196, 'Aring'=>197, 'AE'=>198, 'Ccedilla'=>199,
	     'Egrave'=>200, 'Eacute'=>201, 'Ecircumflex'=>202, 'Edieresis'=>203,
	     'Igrave'=>204, 'Iacute'=>205, 'Icircumflex'=>206, 'Idieresis'=>207,
	     'Eth'=>208, 'Ntilde'=>209, 'Ograve'=>210, 'Oacute'=>211,
	     'Ocircumflex'=>212, 'Otilde'=>213, 'Odieresis'=>214, 'multiply'=>215,
	     'Oslash'=>216, 'Ugrave'=>217, 'Uacute'=>218, 'Ucircumflex'=>219,
	     'Udieresis'=>220, 'Yacute'=>221, 'Thorn'=>222, 'germandbls'=>223,
	     'agrave'=>224, 'aacute'=>225, 'acircumflex'=>226, 'atilde'=>227,
	     'adieresis'=>228, 'aring'=>229, 'ae'=>230, 'ccedilla'=>231,
	     'egrave'=>232, 'eacute'=>233, 'ecircumflex'=>234, 'edieresis'=>235,
	     'igrave'=>236, 'iacute'=>237, 'icircumflex'=>238, 'idieresis'=>239,
	     'eth'=>240, 'ntilde'=>241, 'ograve'=>242, 'oacute'=>243,
	     'ocircumflex'=>244, 'otilde'=>245, 'odieresis'=>246, 'divide'=>247,
	     'oslash'=>248, 'ugrave'=>249, 'uacute'=>250, 'ucircumflex'=>251,
	     'udieresis'=>252, 'yacute'=>253, 'thorn'=>254, 'ydieresis'=>255
	     );

my %metrics = ();
my %positions = ();

#
# Parse the font metrics.  This is a 5 element array.  All numbers are
# expressed as a fraction of the line spacing.
# 0:    nominal width (distance to the next character)
# 1, 2: Coordinates of the lower left corner of the bounding box,
#       relative to the nominal position.
# 3, 4: Size of the bounding box
#
print STDERR "Reading font metrics...\n";
my $FONT;
my @lines = `cat $METRICS`
    or die "Couldn't read metrics";
foreach my $m (grep {/^(C|FontName) /} @lines) {
    chomp $m;
    if($m =~ /^FontName ([^\s]*)/) { $FONT = $1; next; }

    die "No name: $m" if $m !~ /N\s+([^\s]+)\s+;/;
    my $name = $1;

    die "No box: $m"
	if $m !~ /B\s+([-0-9]+)\s+([-0-9]+)\s+([-0-9]+)\s+([-0-9]+)\s+;/;
    my ($left, $bottom, $right, $top) = ($1/1000, $2/1000, $3/1000, $4/1000);

    die "No width: $m" if $m !~ /WX\s+([-0-9]+)/;
    my $nomwid = $1/1000; # nominal, not physical width!

    # The coordinates of the corner relative to the character
    # "position"
    my ($x, $y) = (-$left, -$bottom);
    my ($w, $h) = ($right-$left, $top-$bottom);

    $metrics{$name} = [$nomwid, $x, $y, $w, $h];
}

die "No FontName found in metrics" if not defined $FONT;

#
# Find the height of the tallest character, and print some warnings
#
my $maxhgt = 0;
foreach my $c (keys %CHARS) {
    if(!defined $metrics{$c}) {
	print STDERR "% WARNING: no metrics for char $c.  Skipping.\n";
	next;
    }
    if($metrics{$c}->[4] > $maxhgt) { $maxhgt = $metrics{$c}->[4]; }
}
if($maxhgt == 0) {
    print STDERR "No usable characters found.  Bailing out.\n";
    exit 1;
}

#
# Do the layout.  Keep increasing the row count until the characters
# just fit.  This isn't terribly elegant, but it's simple.
#
print STDERR "Laying out";
my $rows = 1;
my $PS;
my $LINEHGT;
while(!defined ($PS = genPostscript($rows))) { $rows++; }
print STDERR " ($rows rows)\n";

#
# Call ghostscript to render
#
print STDERR "Rendering Postscript...\n";
my $res = $TEXSIZ * $DOWNSAMPLE;
my $pid = open PS, "|gs -r$res -g${res}x${res} -sDEVICE=ppm -sOutputFile=\Q$FONT\E.ppm > /dev/null";
die "Couldn't spawn ghostscript interpreter" if !defined $pid;
print PS join("\n", @$PS), "\n";
close PS;
waitpid($pid, 0);

#
# Downsample with ImageMagick
#
print STDERR "Antialiasing image...\n";
system("mogrify -geometry ${TEXSIZ}x${TEXSIZ} \Q$FONT\E.ppm") == 0
    or die "Couldn't rescale $FONT.ppm";

#
# Generate the .txf file
#
print STDERR "Generating textured font file...\n";

# Prune undefined glyphs
foreach my $c (keys %metrics) {
    delete $metrics{$c} if !defined $CHARS{$c};
}

sub round { sprintf "%.0f", $_[0] }
open TXF, ">$FONT.txf" or die;
print TXF pack "V", 0x667874ff;
print TXF pack "V", 0x12345678;
print TXF pack "V", 0;
print TXF pack "V", $TEXSIZ;
print TXF pack "V", $TEXSIZ;
print TXF pack "V", round($TEXSIZ * $LINEHGT);
print TXF pack "V", 0;
print TXF pack "V", scalar(keys(%metrics));
my @chars = sort { $CHARS{$a} <=> $CHARS{$b} } (keys %metrics);
foreach my $c (@chars) {
    my $m = $metrics{$c};
    my $p = $positions{$c};
    my $step = round($m->[0] * $LINEHGT * $TEXSIZ);

    # Pad the bounding box, to handle areas that outside.  This can
    # happen due to thick lines in the font path, or be an artifact of
    # the downsampling.
    my $w = round($m->[3] * $LINEHGT * $TEXSIZ + 2*$PADDING);
    my $h = round($m->[4] * $LINEHGT * $TEXSIZ + 2*$PADDING);
    my $xoff = -round($m->[1] * $LINEHGT * $TEXSIZ - $PADDING);
    my $yoff = -round($m->[2] * $LINEHGT * $TEXSIZ - $PADDING);
    my $x = round($p->[0] * $TEXSIZ - $PADDING);
    my $y = round($p->[1] * $TEXSIZ - $PADDING);

    print TXF pack "v", $CHARS{$c};
    print TXF pack "C", $w;
    print TXF pack "C", $h;
    print TXF pack "c", $xoff;
    print TXF pack "c", $yoff;
    print TXF pack "C", $step;
    print TXF pack "C", 0;
    print TXF pack "v", $x;
    print TXF pack "v", $y;
}

# Read in the .ppm file, dump the duplicate color values (ghostscript
# won't generate pgm's) and write to the end of the .txf.  Remember to
# swap the order of the rows; OpenGL textures are bottom-up.
open PPM, "$FONT.ppm" or die;
seek PPM, -3*$TEXSIZ*$TEXSIZ, 2 or die;
my @rows = ();
my $pixel;
for(my $r=0; $r<$TEXSIZ; $r++) {
    my @row = ();
    for(my $c=0; $c<$TEXSIZ; $c++) {
	read PPM, $pixel, 3 or die;
	push @row, substr($pixel, 0, 1);
    }
    push @rows, \@row;
}
close PPM;
for(my $r=(@rows - 1); $r>=0; $r--) {
    print TXF join('', @{$rows[$r]});
}
close TXF;

# Clean up
#system("rm $FONT.ppm");

########################################################################
########################################################################
########################################################################

sub genPostscript {
    my $rows = shift;
    my $rowhgt = 1/$rows;

    my @PS = ();

    # The canonical "point size" number, in texture space
    $LINEHGT = ($rowhgt - 2*$PADDING/$TEXSIZ) / $maxhgt;

    # Get to where we want.  Draw the whole thing in a 1 inch square at
    # the bottom left of the "page".
    push @PS, "72 72 scale";

    # Fill the square with black
    push @PS, "0 setgray";
    push @PS, "-1 -1 moveto";
    push @PS, "-1 1 lineto 1 1 lineto 1 -1 lineto";
    push @PS, "closepath";
    push @PS, "fill";

    # Draw in white
    push @PS, "1 setgray";

    # Generate our PUSH @PS, font
    push @PS, "/$FONT findfont $LINEHGT scalefont setfont";

    my $x = $PADDING/$TEXSIZ;
    my $y = 1 - $rowhgt + $PADDING/$TEXSIZ;
    my @chars = sort { $CHARS{$a} <=> $CHARS{$b} } (keys %CHARS);
    foreach my $c (@chars) {
	my $m = $metrics{$c};
	next if !defined $m;

	my $id = sprintf "%2.2x", $CHARS{$c};

	# No space?
	my $w = $m->[3]*$LINEHGT;
	if($x + $w + $PADDING/$TEXSIZ > 1) {
	    $x = $PADDING/$TEXSIZ;
	    $y -= $rowhgt;
	    return undef if $y < 0;
	}

	# Record where in the texture the box ended up
	$positions{$c} = [$x, $y];

	my $vx = $x + $m->[1]*$LINEHGT;
	my $vy = $y + $m->[2]*$LINEHGT;

	push @PS, "$vx $vy moveto";
	push @PS, "<$id> show";

	# Next box...
	$x += $w + 2*$PADDING/$TEXSIZ;
    }

    push @PS, "showpage";

    return \@PS;
}
