24 Feb

Google Chart API is pretty cool

I just stumbled upon the Google Chart API and I couldn’t resist playing with it (statistics being a fetish of mine). A few moments later, I came up with some PHP code that uses my stats plugin for WordPress to fetch page views and generates an URL for the Google API (see below for the attached source code).

The main idea behind Google Chart is that the chart is an image and all data for the chart is in the URL. That includes the chart title, size and the data sets. Personally, I think this is a brilliant idea. You can embed the charts anywhere you can use images and best of all, you don’t need to have data anywhere else but in the URL (you don’t even need to duplicate the generated image in your own webspace).
You can also pretty much generate charts by hand if needed.

On the other hand, when using dynamic data fetched from a database, it is a relatively small task to encode the data into the format Google Chart uses. They even provide a Javascript snippet for that (obviously, you might want to do that server-side – see below). Or, you can simply use floating point numbers if you don’t mind long URLs (and I’m not even sure you can always use very long URLs).

For example, below there’s a graph generated from daily visits to this site:

And here is the URL used to get that graph (lines split for convenience):

http://chart.apis.google.com/chart?
chs=400x150&chd=s:NQGHJ&cht=lc&chdl=Page+views
&chxt=x,y&chxl=0:|Mon|Tue|Wed|Thu|Fri|1:|200|500

The above URL has quite Google-like short parameter names but that’s obviously because of technical limitations. The chd parameter is where the data set for the graph is: s:NQGHJsimple encoding : encoded data.

One interesting aspect arises because of the encoding: you need to fit your data set to use the granularity the encoding has. E.g. when using simple encoding and encoding a data set of 0, 4.7 and 244, you have to normalize and remap the data so the data goes from 0 (character A) to 61 (character 9), not from 0 to 244. That may sound horribly inaccurate but remember, nobody measures the charts with a ruler – they look at the numbers for accurate data. And there are more accurate encodings.

I like how the charts look slick. A lot of existing libraries and APIs for similar stuff tend to have less aesthetic appeal. Anti-aliasing does not better stats make but it certainly looks more professional. The API also has nice features such as adding arrows and red X’es on a graph (think an arrow with the caption “stock market crash” – after which the graph plummets), the always useful Venn diagrams (see right) and other usual stuff you’d need.

Anyway, my original point was that Chart is a cool API, is probably easier to use and faster to install than gnuplot or other chart drawing software, is compatible with any browser able to display images and it’s free for everyone to use (the limit is something like 50 thousand views per user per day – and I guess their policy says nothing against caching the charts on your own site). Check it out.

P.S. This is quite obvious but… I predict that in the future, Google will use the accumulated charts for some kind of statistics search. The charts contain text (label, title) so a Google search result might include relevantly labeled graphs. Which is an interesting scenario, considering the Internet is full of lies, kooks and gullible users.

22 Feb

Generating game content

Part 2 of this series »

If you can’t draw graphics or create sounds for your games, here are a few interesting tools I came across recently that can help you.

sfxr

sfxr generates random sound effects such as explosions, sounds for jumping and so on. The sounds are nice and crisp and you can easily tweak a randomly generated sound to suit your needs better. A nice feature is that you can click on sound types to generate a sound for common actions in games.

Pixel Robots & Invader Fractal

Pixel Robots generates random sprites that resemble robots (well, duh). It’s a Java applet (made with Processing) so you can (or, have to) run it in your web browser. Hence, it is not too convenient to use for pure sprite generation purposes – but it is quite nice eye candy.

The author mentions the Invader Fractal as his inspiration. It is a quite similar thing, in that it generates a sheet of tiny sprites and runs in browser (it’s a Flash applet).

Both generators are quite nice in that their authors give good insight how the programs generate the sprites.

Richard’s Evolving Sprite Tool

I saved the best for last. Richard’s Evolving Sprite Tool, as the name implies, evolves sprites. The main idea is that the program generates a grid of mutated sprites and you can choose the one that looks good. The selected sprite then spawns mutated offspring. This continues until you decide the sprite is good enough. On the left, there’s an example of an evolved and hand-colored sprite (grabbed from the Retro Remakes forum thread).

It is also much more of a tool than the two previous generators, the user can edit the sprites inside the program. After the user has edited a sprite, it can be evolved further. Very nice if you’re short on inspiration.

Next thing Richard needs to do is to add a way to colorize and animate the lovely sprites.

kometbombNote: Since this tool has gone AWOL, here’s something similar: Retro Avatar generator. For example, the avatar created from my name looks like what you see on the left (cute!).

20 Feb

Let’s make a planet

For the last few days, I have been working on a planet generator. I originally got the idea from the method how you can easily tessellate sphere into triangles. This results in a spherical map instead of a cylindrical map.

The usual way of rendering a planet as a a sphere with cylindrical texture map (or height field) looks quite bad in places because the map is stretched on the equator and pinched near the poles. The method described below takes a different approach and generates a map of vertices connected by triangles.

The vertices contain the terrain information such as terrain type (sea, land, mountain) and height. More detail is introduced by subdividing the triangles into smaller triangles.

The starting shape is an octahedron. We then subdivide each side into four triangles, normalize the new vertices and apply simple physics to move all the vertices away from the others (reverse gravity) – this eventually settles the vertices quite evenly (it won’t be a perfect shape but it is good enough for most purposes). We don’t even need to start from a symmetrical shape, using a naive repulsion algorithm eventually makes the shape symmetric as long as it is possible.

The number of subdivisions can be variable and dynamic. I’m planning to make the generator subdivide triangles on demand. In a game, you would see approximate shapes from the orbit but when flying close to the surface, the shorelines etc. would have a lot more detail. You can subdivide infinitely which means there will be infinite detail.

Dragon curve

I use a very simple algorithm to decide the terrain type on each vertex, simply the first point of the triangle decides the terrain type on the new triangle. This results into the Dragon curve fractal. A more sophisticated algorithm would change the subdivision rules according to the subdivision depth. For example, the same rules shouldn’t apply when subdividing on a continental scale versus to a scale of a few kilometers.

Next, I’m going to model a very simple simulation of atmosphere including prevailing winds, cloud formation and temperature.

Links

18 Feb

A simple statistics plugin for WordPress

Here’s a very simple plugin for WordPress that keeps track of view counts of individual pages. It is not intended to be a complete statistics solution. Rather, the main purpose is to provide something for those empty spots in your site layout.

Here is a sample graph (page views for this site):

For a better example, see the site stats page.

Features

  • Keeps day-by-day based page view stats using the database
  • Outputs a clean histogram
  • Includes easy functions for those who are better at blogging than programming

Installation

Copy viewcount.php in /wp-content/plugins and enable it in WordPress options. Enter the path of the directory you want to the graph cache to be located in the options page (Options > Viewcount). The plugin will then start counting page views.

Note: the plugin taps into the_content(). Pages that do not use it will not update the stats! See below for a workaround.

Usage

To display statistics, there are a few functions.

get_view_histogram($page=-1,
  $days=60,
  $barwidth=10,
  $barheight=16,
  $barspacing=1,
  $barcolor='#000000',
  $backgroundcolor='#ffffff',
  $web20=16)

get_view_histogram() returns a URL to a PNG image.

If $page is unset or is -1, the data will be the combined page views for all pages. $web20 specifies the height of a “Web 2.0” style reflection under the bars. The rest of the parameters should be easy enough to figure out.

You can use the function like this to display the statistics for the current post (or page):

<img src="<?php echo get_view_histogram($post->ID); ?>" />

You can also display a top list of page views with get_view_count_list().

get_view_count_list($limit=10,
  $days=30,
  $before='<li>',
  $after='</li>',
  $excludeid='',
  $type='')

$excludeid is a comma-separated list of post IDs (note:the list is not escaped so do not use any values in there that come straight off $_GET or so!). $type is either “post” or “page”, empty string returns both.

You can exclude the page that is currently viewed like this (shows the top five pages from the last 30 days excluding post ID $post->ID):

get_view_count_list(5,30,'<li>','</li>',$post->ID);

To display a Popularity Contest style percentage (the percentage of traffic a post has compared to other posts), use get_popularity($page=-1,$days=30,$format=’percent’). if $page equals to -1, the current page ID will be used automatically. $format can be either ‘percent‘ or ‘float‘ — ‘percent‘ returns a string with the percent sign, ‘float‘ returns a floating point number between 0.0 and 1.0. The following will display a percentage of page views for the current page during the last 30 days.

<?php echo get_popularity(); ?>

To display all time statistics, you can simply do this:

<?php echo get_popularity(-1,99999); ?>

This will display all time statistics, unless your blog has been online for more than 274 years.

To get the list of most viewed pages, use the function get_top_pages($days=30,$limit=10,$type=’views’). $type is either ‘views’ or ‘popularity’.

You can request more functions!

Download

viewcount.zip

Notes

You need the GD library installed for PHP.

I created the plugin to see how that is done. Therefore, crap code ensues (see the warning about excluding posts above).

The plugin will count views for pages and single posts only. Page views from users who are logged in (e.g. you) will not be logged.

The plugin taps into the_content() to count views. You can use vc_update_counter($id) to manually update the page views (or, you can be creative and count very different stuff with it – just make sure the ID is not in use by real pages).

In case you think the graph is wrong: the bar height is normalized. This is just so there is interesting variation in the height.

15 Feb

Customizable page layouts

I recently redesigned my site running on WordPress, which gave me some ideas about a bit more convenient layouts. I hope they are of some value to anyone who is designing their own layouts.

I wanted to tackle a common problem: on a modern (1280+ pixels wide) screen resolution it is often hard to read because the text rows are simply too long.

The easiest way to limit text width layout-wise would of course be to create a fixed-width layout. However, some viewers probably would like to have as wide text as the screen allows. Using some Javascript and DHTML magic, it is easy to make the fixed-width layout resizable. The site can even keep the same width across different pages if it is stored in a cookie.

In Javascript, you can easily change an element’s properties, here is how you would change the width of an element with the ID ‘resizable‘:

document.getElementById('resizable').style.width="500px";

Values can be saved in a cookie as follows (using / as the path sets the cookie for all pages under the domain, important if you want to keep the same width across different pages, cookie expires after days days):

var expire = new Date();
expire.setTime(expire.getTime() + 1000*60*60*24*days);
document.cookie = cookieName+"="+escape(cookieValue)+
  ";expires="+expire.toGMTString()+";path=/";

It is suboptimal to resize the layout after it loads, this will result in an annoying redraw of the page after a few moments. Using some server-side scripting, you can inject the width from the cookie so the page renders at the desired width from the beginning. On my page it is done like this:

<div style="width: <?php echo $_COOKIES[page_width]; ?>">

Probably the most technical thing when implementing the resizing is handling mouse drag in Javascript. On my page, I check if a mouse click happens on an element that has a class name of “drag” and if it is, the drag begins. If the mouse button is released, the drag ends and the resized width is calculated.

var dragging=false;
var start_x=0;

function mousedown(e) {
  if (e.target.className=="drag") {
    start_x=e.clientX;
    dragging=true;
  }
}

function mouseup(e) {
  if (dragging) {
    dragging=false;
    end_x=e.clientX;
    move_x=end_x-start_x;
    // drag ends, we moved move_x pixels
  }
}

After we know how much the X position changed, we can adjust the element width. The following code extracts the number part from the width, adds the X movement to it and again adds the ‘px’ unit in the end:

d=document.getElementById('postcolumn');
m=d.style.width.match(/(\d+)px$/i);
d.style.width=move_x+Math.round(m[1])+'px';

The element width should change by the same amount the user dragged the mouse. At this point you might want to set the cookie as described above.

That’s about it! I am quite sure someone who has no experience of doing things in Javascript and CSS doesn’t get much from the above. I intented this post to be a heads-up of sorts, this is quite easy to implement and in my opinion can be quite convenient. You can try it by dragging the right edge of this post.

If you really want to have that on your site but can’t figure out it by yourself, leave a comment and I’ll help as much as I can. Also, you can look at the source code of this page to see how I did it.

Links