Author Archive

Pretty equations in HTML

November 27th, 2008 6 comments

You may have seen the nice looking equations in my last post. As part of the process of writing that post I researched MathML as a way of embedding the equations in the post. it turned out to be a complex markup language which renders very nicely but has a few big drawbacks. The first is that only Firefox supports MathML in its core so far. There is a plugin for Internet Explorer which supports it but I doubt it’s widely installed. The second problem is that you can’t just put MathML in your web page and have Firefox interpret it. It turns out you need a bit of Javascript to make it pick up and render the MathML. This is great and makes equations render very well in Firefox but writing the MathML is a pain.

Enter ASCIIMathML, a JavaScript library which converts a simple ASCII format to MathML for rendering in MathML compliant browsers. The syntax is pretty much what you would expect with a few tricks up its sleeve. A simple equation, such as `y=x^2` is written as y=x^2. A more complicated example from my last post such as:
is written as:


Another example with a square root:


Now, those if you viewing these posts in a non-Firefox browser are probably wondering why you are also seeing pretty equations here. The short answer is that you’re seeing images imstead of MathML rendered by your browser. The long answer involves a four part toolchain. The first piece is ASCIIMathML, slightly altered to insert an image tag instead of MathML. The images are generated by a PHP script which first runs the ASCII through ASCHIIMathPHP, a version of ASCIIMathML.js to PHP. The resulting MathML has the times symbol replace by one which the later tools understand (replace ⋅ with ·). The resulting MathML is then passed to svgmath, a python script which converts MathML to SVG. SVG would be great but Internet Explorer still doesn’t support it without a plugin. Because of this the SVG is then passed through inkscape via command-line to render out a png which is what you see in your browser.
Here’s some sample PHP to run these commands:

$ascii = 'y=(+-r_2*sqrt(4*r_1^2-r_2^2))/(2*r_1)';
$pngFile = md5($ascii).'.png';
if (!file_exists($pngFile)) {
    require 'ASCIIMathPHP-2.0.cfg.php';
    require 'ASCIIMathPHP-2.0.class.php';
    $ascii_math = new ASCIIMathPHP($symbol_arr);
    $mathml = $ascii_math->getMathML();
    $mathml = str_replace('⋅', '·', $mathml);
    $mathmlFile = tempnam(sys_get_temp_dir(), 'mathml');
    $td = fopen($mathmlFile, 'w');
    fwrite($td, $mathml);
    $svgFile = tempnam(sys_get_temp_dir(), 'svg');
    system("/usr/bin/env python -s $mathmlFile > $svgFile");
    system("inkscape -f $svgFile -e $pngFile");
header('Content-Type: image/png');

All of this is also wrapped up in a WordPress plugin which includes the JS file in the header. Unfortunately, I don’t have an easy way to package this up as it requires python and inkscape but if you would like to get more info just let me know and I’ll send you more information.

UPDATE: I finally did update the plugin to be useful for others and posted it.

Fitting circles within a larger circle

November 24th, 2008 No comments

I have been working on an internal graphical tool at work and had an interesting problem arise. How can I know how many smaller circles I can fit within a larger circle? The best way to lay them out that I came up with was to put the smaller circles in an arc inside of the larger circle, just one smaller circle’s radius in from the edge of the large circle. This looks something like this:

Circles within a circle

Circles within a circle

When the first arc is filled up you then move to an arc which is the diameter of the small circles further within the large circle. The problem, however, is how to know how many circles can fit along that arc. I started originally with a simplistic realization that the arc length would be similar to the diameter of the small circles. This works out ok but ends up creating problems especially when you get close to the center of the larger circle (i.e. when the radius of the arc is close to the radius of the small circles). The correct solution is to calculate the exact angle along the arc that the circle takes up. After a few false starts with incorrect assumptions regarding tangent lines and their lengths I came up with the following.

Geometric definition

Geometric definition

  • The large circle is centered at the origin
  • `r_1` is the radius of the large circle
  • `C` is the center of the small circle
  • `r_2` is the radius of the large circle
  • `I` are the interseciton points between the circles
  • `theta` is the angle between the x axis and the line from the origin to `I`
  • `arc` is the length of the arc between the two interseciton points (`I`)



Circle Equations


Solve for `y^2`


Set equal and solve for `x`


`theta` is then:


You could then use `theta` directly but this will leave you with a remainder of space that’s empty in the arc. To make the circles equally spaced you need the arc length.

Replace values for a full `arc` formula


You can then divide the large circle’s circumfrence by the arc length to get the actual number of circles that will fit. You then divide the circle into that many pieces and voila, you get equally spaced circles like the first image above.

`y` is not needed for the solution, but comes out to be:


Categories: html, JavaScript, math Tags: ,

Falling Away

October 28th, 2008 No comments

I had a new idea last night on my way home for a simple use of Flash 10′s 3D to do a simple visualization. Imagine that you are looking down at the ground from high up. Suddenly the screen falls away and starts falling to the ground. Then the ground you were looking at falls away and you rezlize that it was only a screen. Repeat.

This screenshot shows the app running with a flickr satellite photo feed displaying on each falling plane. Unfortunately, since my code uses BitmapData.draw(), this won’t work from the web as I don’t want to run a flickr proxy. The linked version simply colors the planes, but you can get the idea from it. Right click the movie to view its code. If you run it locally with USE_FLICKR = true you can see the full effect.

Categories: Flash Tags: , , ,

Flash 10 Camp, 3D, Sound Creation, and IK

October 12th, 2008 No comments

I’ve just come home from Flash(10)Camp and am winding down. I had a lot of fun, saw some coll stuff, and even won Best Audio (with my team) with our app Flash Tones.

I was actually very surprised, there were a lot of well done apps, including others that generated sound but I guess we just had the app polished well enough. Thanks to Rod for that, he gave us the last few bits that really made it look nice. You’ll need Flash Player 10 and a web cam if you want to try it out.

All of the features I saw in Flash Player 10 were ones I’d seen before, except for the sound generation. Things were more in depth and better put together this time, though. The sound generation is nice, but complicated and hard to make it do what you’re expecting. Of course, I’m assuming you know almost nothing about the specifics of sound, like I do.

IK is fun, but I I focused on the other 2 as I didn’t have any IK idea that seemed particularly interesting.

The 3D is very nice, being able to move and rotate objects in all three dimensions opens up a lot of new possibilities. I had a lot of fun creating some simple squares and rotating them, then applying various blend modes and filters. Here are 2 of my favorites:

Those were fun but then someone mentioned webcams. I successfully connected up webcam video to my project and then spent several hours getting the video mapped to each of the rotating squares then getting it all matched up with the video behind it. I then added edge detection (thanks to Luke Walsh’s post), added some more blending and filters and voila!

I was quite proud of that and still think it looks cool. I wish I’d shown it earlier at the Hackathon but then again we won an award so I guess I’m just being greedy.

As an added bonus, here’s an earlier version of Flash Tones which warbled in an interesting way. Try putting your hand up at the very right edge of the screen.

Categories: Flash Tags: , , , ,

Flex Bug: Icon shadows in a TabNavigator’s Tabs

May 27th, 2008 No comments

This is likely a generic problem with anything that uses a Button but I have found this issue with Tabs in a TabNavigator specifically. When you have a TabNavigator with multiple complicated children that take a while to load, clicking one tab then clicking another quickly can lead to a “shadow” icon at the top-left of the tabs. See the bug for more: SDK-15656

Categories: Flex Tags: , ,

Running JavaScript when the page finishes loading

May 23rd, 2008 1 comment

I know what you’re thinking. window.onload and <body onload> already let you run javascript when the page loads. Why do I need something more? The answer is that the standard onload only runs when the entire page and its dependencies are finished loading. This means that if you have multiple images (such as tracking tags) or scripts or a large swf, the onloaded code will only run once all of those pieces load. The point of the following is to run some JavaScript once the page itself has loaded and been parsed. This allows you to do things like set the background color, add additional elements, or start loading other dependencies while the rest of the page’s depdencies are loading. This is particularly useful if you need to do something on a page while a large swf is loading.

The following is a combination of several posts on Dean Edwards’ blog as well as an onload handler for those browsers that don’t support this kind of solution that I found elsewhere. This may not work in Opera, I am not sure. According to the second post Opera supports DOMContentLoaded but I don’t know if this code will catch Opera properly.

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;
  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;
// for Mozilla browsers
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
} else
// for Safari
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
  }, 10);
} else
//for those other poor souls
  function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
      window.onload = func;
    } else {
      window.onload = function() {
// for Internet Explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id='__ie_onload' src='javascript:void(0)'></script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
  if (this.readyState == "complete") {
    init(); // call the onload handler
/*@end @*/

UPDATE: fixed the code above. WordPress was screwing up the last bit due to its insistence on changing the preformatted HTML in the code.

Categories: JavaScript Tags: ,

Easy ID3 Tag Editing in OSX

May 1st, 2008 No comments

This is another quick informational post about a program that I find very useful. Musorg. When I was on Windows I used Mp3/Tag Studio to edit the ID3 tags in my MP3s. While this program is very useful and free (ad supported) it’s a pain to have to fire it up in Parallels to edit my tags now. Musorg is a free and simple OSX program that just lets you edit your ID3 tags.

Categories: Music Tags: , , , ,

Pitch Detection for Mac OS X

March 19th, 2008 No comments

I just had to put up a quick blurb about QPitch. It’s the only free software I could find which would do pitch detection for Mac OS X and it works very well (and is fun to play with). Thanks, William Spinelli.

Categories: Music Tags: ,

Inverted Mask in Flex

March 17th, 2008 4 comments

Today I took on the challenge of changing a component I built last year to fit into a new style our creative department just finished for a new website. The previous component had a drawn background and some text laid over it which was a different color. The new style called for the same thing with a different background color and the text cut out of the shape. The different background color was easy, I simply added a few styles (one for rollover too) and had it changing color. The harder part was cutting the text out of the background. I knew that this was possible in graphics programs by inverting the mask used or subtracting the shape from another shape and using that as the mask. I couldn’t find any options in Flex for inverting a mask and a google search provided nothing on inverting a mask. I did, however run into a graphics tricks article on InsideRIA. This reminded me of the blend modes that I’d played with in the San Francisco Papervision3D course.

Curious, I went looking and sure enough there was a BlendMode.INVERT. This didn’t, however, do what I wanted of course. This inverted the color values, not the mask. Looking further I found BlendMode.ERASE. This sounded promising but several iterations had it doing nothing, then showing as normal text, then “erasing” everything underneath it. I didn’t want my text to erase everything, just the shape behind it. After some more playing I found the key. cacheAsBitmap. Of course, cacheAsBitmap on one of the pieces didn’t work. Normal masking, for that matter, required cacheAsBitmap on both the mask and the maskee. The trick to make an inverse mask is to set cacheAsBitmap to true for the container of the things that are being masked.

I’m not sure what the performance implications of this are but the effect sure is nice. :-)

Example (click to invert, view source enabled):

The red horizontal lines are on the bottom level. The text and the green vertical lines are within containingCanvas on top of the red lines. The green lines are beneath the text and masked by the text by default. Click to have it mask the green lines in inverse.

Categories: Flex Tags: , ,

Travian Resource Reallocator

February 28th, 2008 6 comments

Last but not least in this deluge of posts is a little utility I created to allow people to reallocate their resources efficiently in Travian. There is a feature in this game, for those who pay a little money, that allows you to change any type of resource (lumber, clay, iron, crop) into any other type. This is very useful for situations where you are producing way more of one resource than another or simply want to speed up your development but if you reallocate for one thing then want to use the remaining resources for another thing you would need to either calculate the amounts manually or reallocate multiple times (thus costing more “gold”). The resulting app allows you to reallocate your resources for any troop type in the game, allows for configuration of the # of them you wish to train, and lets you add any number of subsequent reallocations with the remaining resources.

Travian Tool

Categories: Flex, Games, Travian Tags: , ,