Introducing Pwiff

Considering I’ve reached a small milestone in the project, I figured I would write a post explaining what I’ve been up to. My previous entry relates to this, as at the time I was experimenting with writing a class to encode binary data into a stream of bits. Float information was important, as the class needed to support half-precision floating point numbers, which standard PHP cannot do.

If the name of the project didn’t give it away, I am writing an SWF output (possibly input, later) library using only PHP, without the need for something like ext/ming or swflib. The name seems pretty unoriginal – SWF is pronounced swiff, so I put a P in there for PHP :-P . The last project which attempted this, FreeMovie, has not been updated in more than five years, was written in PHP4, and crammed into a few large files. This one is written using the PHP5 object model, and will hopefully be modular enough to extend upon as the SWF specification continues to grow.

Currently, there is a class for writing out the raw datatypes, and a set of classes for the current SWF records (RGB, RGBA, ARGB, LanguageCode, Matrix, Rect, CXForm, and CXFormWithAlpha). I have other issues/work occupying my time at the moment, but after I get back into this, I plan on starting a Google Code project for it once it can actually encode a full SWF file.

Until next time.

Posted in PHP | Tagged , | Leave a comment

Extracting Information from Floats

I was tinkering around with working in binary again, for a project I may or may not follow through on – still deciding. Along the way I was dealing with floating point numbers, and how to work with their individual bits in PHP. It’s definitely not as nice as in C, where you can just typecast into the raw binary representation. Unless there’s a better way I haven’t seen, you have to pack() a float, then unpack() it as an unsigned int, before you can use bitwise operators on it to pick out information.

/**
 * Takes a single-precision floating point number, and returns it as a
 * sequence of bits in the form of an unsigned integer.
 *
 * @param  float $float
 * @return int
 */
function floatToIntBits($float)
{
	$s = unpack('Vval', pack('f', $float));
	return $s['val'];
}

/**
 * Takes a sequence of bits representing a float in the form of an unsigned
 * integer, and returns an associative array of information about the float.
 *
 * The returned array has the keys:
 * - sign: 0 if positive, 1 if negative
 * - exp:  exponent, with 127 exponent bias applied
 * - mant: decoded mantissa
 *
 * Using these you can reconstruct the float with (1 - 2*sign) * mant * 2^exp
 *
 * @param  int $bits
 * @return array
 */
function floatInfo($bits)
{
	$exponent = ($bits & 0x7f800000) >> 23;
	$mantissa = $bits & 0x7fffff;

	// if the exponent is nonzero, the mantissa gets a leading bit
	if ($exponent !== 0) {
		$mantissa |= 1 << 23;
	}

	// decode the mantissa
	// bit 23 = 1.0
	// bit 22 = 0.5
	// bit 21 = 0.25
	// etc
	$decoded = 0;
	for ($i = 23; $i >= 0; $i--) {
		if (($mantissa >> $i) & 1) {
			$decoded += pow(2, $i - 23);
		}
	}

	return array(
		// sign would otherwise be -1 on 32bit systems
		'sign' => abs(($bits & 0x80000000) >> 31),
		'exp'  => $exponent - 127,
		'mant' => $decoded,
	);
}

$bits = floatToIntBits(25.0);
var_dump(floatInfo($bits));
// array(3) {
//   ["sign"]=>
//   int(0)
//   ["exp"]=>
//   int(4)
//   ["mant"]=>
//   float(1.5625)
// }
Posted in PHP | Leave a comment

Crindigan: An Introduction

This entry is meant to quickly describe what Crindigan is, and what led to its creation.

As the description on Google Code states, it is basically a web-based role playing game, played through a user’s browser using standard technologies like AJAX to enhance the experience. You create your first character, then spend artificial money to purchase new recruits, items, and equipment. You can organize the characters into multiple squads, then use those squads to explore the game world and fight enemies/other parties.

Crindigan is actually my third attempt at creating a web application like this. My first attempt started in the Fall of 2005, maybe six months after starting to learn PHP. Back then, I really had no knowledge of proper application design, and so it was a sloppy jumble of code based on the “RPG Creator System” program badly ported to an object-oriented architecture. It eventually died off after a few months, as it was a pain to look at.

My second attempt started a year after the first, in Fall 2006. This one lasted for over two years, with the last change happening in December 2008. It only worked with the vBulletin forum software, and in fact had portions of its architecture based on it, such as session and input handling. The RPG started out in PHP4, and went through some small rewrites and design changes, but nothing drastic. In the end, I had a 17,000 line codebase written with PHP5 features, that also included a couple thousand lines of JavaScript for fancy battle, equipment, and skill learning screens. Why did I abandon it? It was still running on the architecture I made in 2006, with a few hacks added on top of it for things like fancy URLs. There was no clear separation between the model and the view, and new features were becoming harder and more clumsy to add. At this point, I had two choices: continue adding hacks to the existing codebase, or rewrite it from scratch. Since I now had almost four years of programming experience, I opted for the rewrite, mainly as a test to see how far I progressed and whether or not I could finally make something maintainable.

And that’s how the Crindigan project came to fruition. Of course, it didn’t really have a name until this summer. Development has been slower than I would like, but at least I’m now feeling proud about the code I’m writing. From the start, I declared that PHP 5.2 would be a requirement, and I would force myself to follow the MVC design pattern, which has really helped to keep my code clean. Most of the work I’ve done has been on the framework rather than the application itself, though things like logging in were written, along with parts of the style. My next task is to rethink how I’m handling updates and inserts through the Model, such as making it a bit smarter but without overdoing it, as I’m not particularly interested in coding a full-blown ORM. After that comes a forms library, then finally I can get to the application itself.

See you next article!

Crindigan @ Google Code
Crindigan @ Ohloh

Posted in PHP | Tagged | Leave a comment

Absence of Stability

Funny how when I run this site off the latest WordPress SVN, version 2.9 coming out of beta only means that I’m now running 3.0 alpha. :-P

In other news, I’ll be trying to post an introduction to my Crindigan project soon. I did a little bit more work on the codebase tonight, though I really need to get it in gear before it becomes pseudo-vaporware and people brush it off as another abandoned newbie project.

Posted in Miscellaneous | Tagged | Leave a comment

Mariph

Mariph is a collection of a few classes that can read a subset of Ruby’s Marshal format. I wrote it back when I worked with RPG Maker XP, and wanted to convert the marshalled data from that program into something I could read. In order to do it in Ruby, I would have had to recreate most of the module and class structure defined in RPG Maker, so I instead opted to write a reader in the language most familiar to me – PHP.

It does not support every feature built in to the marshal format, only the ones that I required at the time. This includes: nil, true, false, int, float, string, symbol, regexp (string), array, hash, object, and user. Hash types are returned as a Mariph_Hash, which is a simple representation of a hash table with arbitrary data for keys. Objects are returned as stdClass, with the property __mariphName set to the name of its Ruby counterpart class. User types look for a PHP class defined with the same name as the Ruby class, with any double colon replaced by a double underscore. It then statically calls the class’s rubyLoad() method, which should accept the raw data string as its only parameter, and return an instance of the class. See the Table class in the file for an example.

The simplest way to parse in the data is by calling the mariph_load() shortcut function, which saves you the trouble of initializing both the tokenizer and interpreter classes. Each top-level element in the marshalled string becomes an element of the returned array.

$data = mariph_load($marshalString);

The Mariph_Hash class has your standard get() and set() methods, along with a few convenience methods such as iterate(), count() (implementing Countable), each(), and reset().

$hash = new Mariph_Hash(array('initial' => 'data'));
$hash->set(1, 'one');
$hash->set(2.5, 'two point five');
$hash->set('str', 'string');
$hash->set(array(1, 2, 3), 'one two three');

echo $hash->get(2.5); // "two point five"

// should work in PHP 5.3
$hash->iterate(function($value, $key) {
    echo 'Key: ';
    var_dump($key);
    echo 'Value: ';
    var_dump($value);
});

// Alternatively iterate with each()
while (list($key, $value) = $hash->each()) {
    // do whatever
}

// reset iteration position after using each()
$hash->reset();

I’m sure there’s much better ways for designing a custom hash class than what I wrote, but for me it gets the job done. Hopefully this small library can prove useful to some people. :)

Posted in PHP | Tagged , | Leave a comment

Obfuscated Cake

Almost forgot about this one. I wrote it back in June 2008 for Jeremy’s birthday since he was having a rough day. Like the heart, this is code in the shape of a birthday cake (well, as long as you use some imagination :-P ) that draws a birthday cake. A chocolate one.

The code first draws the main cake rectangle. After that, it loops three times to draw the rectangles for the candlesticks, polygons for the flames, then orange circles with an alpha channel for the light. It finishes off with a series of lines whose lengths are determined by the sine function, used for the frosting.

Here’s the output.

<?php               header             ('Content'.
'-type:'.          'image/png'         );$f = 'im'.
'agecre'.          'atetrueco'.        'lor';$im=$f
(250,250);         $g='imagef'.        'illedrect'.
'angle';$g         ($im,10,120,        240,240,(630*
10000)+ 37         *100+44);for        ($i=0;$i<3;$i
++){$x=60+         $i*60;$g($im        ,$x+2,50,$x+8,
120,0xeeeeee);$h=str_rot13('vzntrsvyyrqcbyltba');$h(
$im,array($x,50,$x+5,30,$x+10,50),3,0xc00000);$h($im,
array($x+2,50,$x+ 5,40,$x+8,50),3, 0xff8000);$h ($im,
array($x+3,50,$x+5,45,$x+7,50),3,0x0000ff);$el='ima'.
'gefilledellipse';$el($im,$x+5,40,40,40,0x48ffa000);}
$l='i'.'m'.'a'. 'g'.'e'.'l'.'in'.'e';$c=0xd0d0ff; for
($i=10;$i<=240;$i++){$y=130+3* sin(($i-10)/2);$l($im,
$i,120,$i,$y,$c);}$p=strrev('egami').'png';$d='imag';
$d.='ede';$de='str';$d.=$de;$d.='oy';$p($im);$d($im);

Unobfuscated version:

<?php

header('Content-type: image/png');
$img = imageCreateTrueColor(250, 250);
imageFilledRectangle($img, 10, 120, 240, 240, 0x603000);

// loop through the 3 candles
for ($i = 0; $i < 3; $i++) {
	$x = 60 + $i * 60;
	// candlestick, red flame, orange flame, blue flame, light
	imageFilledRectangle($img, $x + 2, 50, $x + 8, 120, 0xEEEEEE);
	imageFilledPolygon($img, array($x, 50, $x + 5, 30, $x + 10, 50), 3, 0xC00000);
	imageFilledPolygon($img, array($x + 2, 50, $x + 5, 40, $x + 8, 50), 3, 0xFF8000);
	imageFilledPolygon($img, array($x + 3, 50, $x + 5, 45, $x + 7, 50), 3, 0x0000FF);
	imageFilledEllipse($img, $x + 5, 40, 40, 40, 0x48FFA000);
}

// frosting
for ($i = 10; $i <= 240; $i++) {
	$y = 130 + 3 * sin(($i - 10) / 2);
	imageLine($img, $i, 120, $i, $y, 0xD0D0FF);
}

imagePNG($img);
imageDestroy($img);
Posted in PHP | Tagged , | 1 Comment

Voronoi Diagram

Here’s another imaging example done with PHP – a Voronoi Diagram. I don’t exactly remember when I wrote this, but it was some time this year. The code doesn’t use any fancy, ultra-efficient algorithm, so it takes several seconds to make a medium-size image on my (old) computer.

The algorithm used is very simple: Iterate through each pixel of the image, and find which reference point it is closest to. Then, set the color of the pixel to the color of the reference point.

Here’s the code.

Voronoi Diagram

Voronoi Diagram with 50 Colors

Posted in PHP | Tagged | Leave a comment

Random Line Generator

Another repost, though a bit more fresh – it was originally posted in September 2007.

JS Random Line Generator

The random line generator uses the HTML5 canvas element to draw a series of connected lines, with a large variety of options. You can choose where to start drawing, the initial angle, the line lengths, how far the lines can turn left or right, the number of lines, the line colors, the line width, and the background color. In addition, if you are using a modern browser that supports canvas’s toDataURL() method, you can save the image to your computer (otherwise you’ll likely have to Print Screen it).

One nifty thing you can do with the line colors is cycle through a gradient. By using a color fade generator and selecting “show HTML codes” then the color sequence, you can copy and paste the list into the line colors box. Additionally, it accepts code in HTML (font/color, and span/style), so if somebody has a nice gradient on a website, chances are you can copy/paste the source and use it.

Here’s an example image that I created:

Random Line Example

Random line with black-white gradient

For people with older browsers, there is a PHP version with slightly reduced functionality. It has a max color limit of 30, and no line width setting. It does allow you to turn anti-aliasing on and off, though. The source for the PHP version can be found here.

Posted in JavaScript | Tagged , | Leave a comment

Obfuscated Heart

I originally wrote this in July 2006 for PHP image generation practice, but decided to repost it. Basically, it’s code written in the shape of a heart, that draws a heart.

Going more in-depth, the code uses polar coordinates to draw a cardioid-like figure, which are converted into cartesian coordinates via the cfp_x() and cfp_y() functions. The new coordinates are then used in PHP’s imageFilledPolygon() function to draw the shape.

The formula to create the heart is simply done by setting the radius equal to the angle, rotated 90 degrees so that the shape is right-side up. So, at 0, the coordinates are at the origin – the sharp valley of the heart. At 180, the coordinates are at the bottom point of the heart.

View the output here.

           function                cfp_x($ox,
     $a,$d) {return ($ox+    round((cos (deg2rad($a
   ))*$d)));}function cfp_y($oy, $a, $d){return ($oy+
  round((sin(deg2rad($a)) * $d)));} $crd=array();$ct=0;
 $im=imageCreateTrueColor(250,250);$c=imageColorAllocate
 ($im,255,0,0);header("Content-type: image/png");for($i
  =-180;$i<180;$i++){$crd[]=cfp_x(125,$i -90,abs($i));
    $crd[] = cfp_y(50, $i - 90, abs($i) ); $ct++;}
        imageFilledPolygon($im, $crd,$ct,$c);
            imagePNG($im);imageDestroy
                      (($im));
                         ?>

Unobfuscated version:

function cfp_x($origin_x, $angle, $radius) {
    return $origin_x + round(cos(deg2rad($angle)) * $radius);
}
function cfp_y($origin_y, $angle, $radius) {
    return $origin_y + round(sin(deg2rad($angle)) * $radius);
}

$coords = array();
$num_pts = 0;
$img = imageCreateTrueColor(250, 250);

for ($i = -180; $i < 180; $i++) {
    $coords[] = cfp_x(125, $i - 90, abs($i));
    $coords[] = cfp_y(50, $i - 90, abs($i));
    $num_pts++;
}

imageFilledPolygon($img, $coords, $num_pts, 0xFF0000);
header('Content-type: image/png');
imagePNG($img);
imageDestroy($img);
Posted in PHP | Tagged , | Leave a comment

New Blog

My old blog was scarcely updated, using outdated software, and had a mixed bag of unorganized content. As a result, I decided to start over, and create a blog solely devoted to technical subjects and my programming projects.

Posted in Miscellaneous | Leave a comment