New Year, new tools – OpenScad Tetrahedron

Screen Shot 2016-01-02 at 8.16.57 AM

I fired up OpenScad, and created a new tetrahedron model using it.  I’ve done tons with platonic solids in OpenScad in the past.  This time around though, I figured I’d create the simplest tetrahedron I know.  Here’s the OpenScad code for the same:




    translate([0, 100, 100])
    translate([100, 0, 100])

The trick here is in the fact of the special relationship between a tetrahedron and a cube. The cube has 8 vertices, and you can create a tetrahedron by using 4 of those vertices. You just have to pick the right ones. You can easily choose the right ones by picking a set at opposite corners of any face (cutting a diagonal across that face). Then, choose the face exactly opposite, and select the two corners that are different from the ones you picked on the first face. Now you have these 4 vertices.

OpenScad has had the ‘hull()’ module since forever, but it didn’t always work so well. In this modern OpenScad, and for this particular case, it works extremely well. Just take the 4 vertices, throw them into a hull(), and out comes a nice tetrahedron!

This is the tetrahedron for the masses. No math required, except to know the vertices of a unit cube. And of course you can scale it up to any size you please.

If you want to do anything tricky with it though, like subtract some holes and the like, you’ll have to know the math again. But, there you have it, tetrahedron solid in a few lines of OpenScad.

End of 2015 Already!

Over the past few years, I figured out that in the US, if you spend on your business, you’ll recoup more money than you’ll ever make by simply saving that money in a bank account.  So, here we are, it’s the end of the year, what to do?

Well, first up was a new laser cutter:

G. Weike LG 900N

Then came another large format powder printer

3D Systems Pro Jet 660Pro

A replacement for my original Up! automated glue gun

Afinia H800

And finally, I took a flyer on the GlowForge laser cutter

GlowForge (link to save $100:

Now, what business does any sane person have putting all this stuff into their garage?  Well, first of all, the Pro Jet isn’t actually in my garage, it’s actually being put into production in California.  That does leave me with the Weike and Afinia (ignore the GlowForge).  The Weike is an interesting tool in that it’s big enough to cut large enough pieces to incorporate into real furniture.  The way I see it is, I can cut 1/8″ or 1/16″ slices and create my own “plywood”.  That can result in a lot of possibilities.  And of course there’s always the paper/cardboard cutting for kids crafts, ‘living hinge’ jewelry boxes, and the like.  The Afinia, whenever it shows up, can serve for in house ‘print/cut’, rather than being the heavy duty garage bound tool.  It will go in my office.

The Afinia is just an evolution of a fairly good ‘just print’ printer.  I purchased one of the earliest Up! printers a few years back, after first spending quite a few frustrating months with the original MakerBot Cupcake.  I’ve loved my Up! ever since, but it’s getting long in the tooth, so it’s time for an upgrade.  The H800 has a larger print area, and probably more importantly it has an enclosed volume with a HEPA filter.  This makes it a candidate for living inside the house if I make space for it.  The larger print volume will make it feasible to print fun parts for construction, and not just little trinkets.  I’m looking forward to having an enclosed build volume, it will likely make for better temperature control, and thus less warping of ABS.

I recently had one of my ancient designs printed on the powder printer, just to see what it would look like.  I have plans to have it made using injection molding process, meanwhile, using the Afinia will help me make some small runs of the same, in true rapid prototyping fashion.

Speaking of designs, I recently installed the 2015 version of OpenScad.  It renders my old designs nicely enough, and it has some new features which will make some work I had done previously even better.  So, what better time to dust off some of those old designs and update them with the modern OpenScad.  We’ll see how hard it is to get back into the mindset of that programming environment.

And how can the year end purchases ignore electronics!

Raspberry Pi Zero (from Adafruit)

Raspberry Pi Microsoft iOT package

At $5 (for basic board), how could any self respecting tinkerer pass this up.  Yes, if you really add things up, it’s much more than this, but I already have enough power supplies, keyboards and wifi dongles in stock that these are not additional costs, and the incremental cost to me is truly $5.  At the very least, I can see using these as a learning tool to teach Linux.  A Raspberry Pi 0, with LuaJIT installed, and tons of “Lua Tools For Linux”, and you’re all set.

So, finishing the year with a wallet busting blowout, taking back some tax dollars in the process, and generally setting up to have some great fun in the new year.

Happy New Year!

Spelunking Linux – procfs, and a bag of chips

Recently, as a way to further understand all things Linux, I’ve been delving into procfs.  This is one of those virtual file systems on linux, meaning, the ‘files’ and ‘directories’ are not located on some real media anywhere, they are conjured up in realtime from within the kernel.  If you take a look at the ‘/proc’ directory on any linux machine, you’ll find a couple of things.  First, there are a bunch of directories with numeric values as their names.


1	     10			100	      1003	     1004
10075	     101		10276	      10683	     10695
10699	     1071		10746	      10756	     10757
1081	     11			11927	      12	     1236
12527	     12549		12563	      1296	     13

Yes, true to the unix philosophy, all the things are but files/directories. Each one of these numbers represents a process that is running on the system at the moment. Each one of these directories contains additional directories, and files. The files contain interesting data, and the directories lead into even more places where you can find more interesting things about the process.

Here are the contents of the directory ‘1’, which is the first process running on the system:

attr/	    autogroup	     auxv	 cgroup     clear_refs	cmdline
comm	    coredump_filter  cpuset	 cwd@	    environ	exe@
fd/	    fdinfo/	     gid_map	 io	    limits	loginuid
map_files/  maps	     mem	 mountinfo  mounts	mountstats
net/	    ns/		     numa_maps	 oom_adj    oom_score	oom_score_adj
pagemap     personality      projid_map  root@	    sched	schedstat
sessionid   setgroups	     smaps	 stack	    stat	statm
status	    syscall	     task/	 timers     uid_map	wchan

Some actual files, some more directories, some symbolic links. To find out the details of what each of these contains, and their general meaning, you need to consult the procfs man page, as well as the source code of the linux kernel, or various utilities that use them.

Backing up a bit, the /proc directory itself contains some very interesting files as well:

acpi/	      asound/		 buddyinfo     bus/	      cgroups
cmdline       consoles		 cpuinfo       crypto	      devices
diskstats     dma		 driver/       execdomains    fb
filesystems   fs/		 interrupts    iomem	      ioports
irq/	      kallsyms		 kcore	       keys	      key-users
kmsg	      kpagecount	 kpageflags    loadavg	      locks
mdstat	      meminfo		 misc	       modules	      mounts@
mtrr	      net@		 pagetypeinfo  partitions     sched_debug
schedstat     scsi/		 self@	       slabinfo       softirqs
stat	      swaps		 sys/	       sysrq-trigger  sysvipc/
thread-self@  timer_list	 timer_stats   tty/	      uptime
version       version_signature  vmallocinfo   vmstat	      zoneinfo

Again, the meanings of each of these is buried in the various documentation and source code files that surround them, but let’s take a look at a couple of examples. How about that uptime file?

8099.41 31698.74

OK. Two numbers. What do they mean? The first one is how many seconds the system has been running. The second one is the number of seconds all cpus on the system have been idle since the system came up. Yes, on a multi-proc system, the second number can be greater than the first. And thus begins the actual journey into spelunking procfs. If you’re like me, you occasionally need to know this information. Of course, if you want to know it from the command line, you just run the ‘uptime’ command, and you get…

 06:38:22 up  2:18,  2 users,  load average: 0.17, 0.25, 0.17

Well, hmmm, I get the ‘up’ part, but what’s all that other stuff, and what happened to the idle time thing? As it turns out, the uptime command does show the up time, but it also shows the logged in users, and the load average numbers, which actually come from different files.

It’s like this. Whatever you want to know about the system is probably available, but you have to know where to look for it, and how to interpret the data from the files. Often times there’s either a libc function you can call, or a command line utility, if you can discover and remember them.

What about a different way? Since I’m spelunking, I want to discover things in a more random fashion, and of course I want easy lua programmatic access to what I find. In steps the lj2procfs project.

In lj2procfs, I try to provide a more manageable interface to the files in /proc.  Most often, the information is presented as lua tables.  If the information is too simple (like /proc/version), then it is presented as a simple string.  Here is a look at that uptime example, done using lj2procfs:


return {
    ['uptime'] = {
        seconds = 19129.39,
        idle = 74786.86,

You can see that the simple two numbers in the uptime file are converted to meaningful fields within the table. In this case, I use a simple utility program to turn any of the files into simple lua value output, suitable for reparsing, or transmitting. First, what does the ‘parsing’ look like?

	seconds idle 

	The first value is the number of seconds the system has been up.
	The second number is the accumulated number of seconds all processors
	have spent idle.  The second number can be greater than the first
	in a multi-processor system.
local function decoder(path)
	path = path or "/proc/uptime"
	local f =
	local str = f:read("*a")

	local seconds, idle = str:match("(%d*%.?%d+)%s+(%d*%.?%d+)")
	return {
		seconds = tonumber(seconds);
		idle = tonumber(idle);

return {
	decoder = decoder;

In most cases, the output of the /proc files are meant to be human readable. At least with Linux. Other platforms might prefer these files to be more easily machine readable (binary). As such, they are readily parseable mostly by simple string patterns.

So, this decoder is one of many. There is one for each of the file types in the /proc directory, or at least the list is growing.

They are in turn accessed using the Decoders class.

local Decoders = {}
local function findDecoder(self, key)
	local path = "lj2procfs.codecs."..key;

	-- try to load the intended codec file
	local success, codec = pcall(function() return require(path) end)
	if success and codec.decoder then
		return codec.decoder;

	-- if we didn't find a decoder, use the generic raw file loading
	-- decoder.
	-- Caution: some of those files can be very large!
	return getRawFile;
setmetatable(Decoders, {
	__index = findDecoder;


This is a fairly simple forwarding mechanism. You could use this in your code by doing the following:

procfs = require("Decoders")
local uptime = procfs.uptime


When you try to access the procfs.uptime field of the Decoders class, it will go; “Hmmm, I don’t have a field in my table with that name, I’ll defer to whatever was set as my __index value, which so happens to be a function, so I’m going to call that function and see what it comes up with”. The findDecoder function will in turn look in the codecs directory for something with that name. It will find the code in uptime.lua, and execute it, handing it the path specified. The uptime function will read the file, parse the values, and return a table.

And thus magic is practiced!

It’s actually pretty nice because having things as lua tables and lua values such as numbers and strings, makes it really easy to do programmatic things from there.

Here’s meminfo.lua

local function meminfo(path)
	path = path or "/proc/meminfo"
	local tbl = {}
	local pattern = "(%g+):%s+(%d+)%s+(%g+)"

	for str in io.lines(path) do
		local name, size, units = str:match(pattern)
		if name then
			tbl[name] = {
				size = tonumber(size), 
				units = units;

	return tbl

return {
	decoder = meminfo;

The raw ‘/proc/meminfo’ file output looks something like this:

MemTotal:        2045244 kB
MemFree:          273464 kB
MemAvailable:     862664 kB
Buffers:           72188 kB
Cached:           629268 kB
SwapCached:            0 kB

And the parsed output might be something like this:

    ['meminfo'] = {
        ['Active'] = {
            size = 1432756,
            units = [[kB]],
        ['DirectMap2M'] = {
            size = 1992704,
            units = [[kB]],
        ['MemFree'] = {
            size = 284604,
            units = [[kB]],
        ['MemTotal'] = {
            size = 2045244,
            units = [[kB]],

Very handy.

In some cases, the output can be a bit tricky, since it’s trying to be human readable, there might be some trickery, like header lines, and variable number of columns. This can get tricky, but you have the full power of lua to do the parsing, including using something like lpeg if you so choose. Here’s the parser for the ‘/proc/interrupts’ file, for example:

local strutil = require("lj2procfs.string-util")

local namepatt = "(%g+):(.*)"
local numberspatt = "[%s*(%d+)]+"
local descpatt = "[%s*(%d+)]+(.*)"

local function numbers(value)
	num, other = string.match(value, numpatt)
	return num;

local function interrupts(path)
	path = path or "/proc/interrupts"

	local tbl = {}
	for str in io.lines(path) do
		local name, remainder = str:match(namepatt)
		if name then
			local numbers = remainder:match(numberspatt)
			local desc = remainder:match(descpatt)

			local cpu = 0;
			local valueTbl = {}
			for number in numbers:gmatch("%s*(%d+)") do
				--print("NUMBER: ", number)
				valueTbl["cpu"..cpu] = tonumber(number);
				cpu = cpu + 1;
			valueTbl.description = desc
			tbl[name] = valueTbl


	return tbl

return {
	decoder = interrupts;

And it deals with raw file data that looks like this:

          CPU0       CPU1       CPU2       CPU3       
  0:         38          0          0          0   IO-APIC-edge      timer
  1:      25395          0          0          0   IO-APIC-edge      i8042
  8:          1          0          0          0   IO-APIC-edge      rtc0
  9:      70202          0          0          0   IO-APIC-fasteoi   acpi

In this case, I’m running on a VM which was configured with 4 cpus. I had run previously with a VM with only 3 CPUs, and there were only 3 CPU columns. So, in this case, the patterns first isolate the interrupt number from the remainder of the line, then the numeric columns are isolated from the interrupt description field, then the numbers themselves are matched off using an iterator (gmatch). The table generated looks something like this:

    ['interrupts'] = {
        ['SPU'] = {
            cpu2 = 0,
            cpu3 = 0,
            cpu1 = 0,
            cpu0 = 0,
            description = [[Spurious interrupts]],
        ['22'] = {
            cpu2 = 0,
            cpu3 = 0,
            cpu1 = 0,
            cpu0 = 0,
            description = [[IO-APIC  22-fasteoi   virtio1]],
        ['NMI'] = {
            cpu2 = 0,
            cpu3 = 0,
            cpu1 = 0,
            cpu0 = 0,
            description = [[Non-maskable interrupts]],


To make spelunking easier, I’ve created a simple script which just calls the procfs thing, given a command line argument of the name of the file you’re interested in looking at.

#!/usr/bin/env luajit


	This is a general purpose /proc/<file> interpreter.
		$ sudo ./procfile filename

	Here, 'filname' is any one of the files listed in the 
	/proc directory.

	In the cases where a decoder is implemented in Decoders.lua
	the file will be parsed, and an appropriate value will be
	returned and printed in a lua form appropriate for reparsing.

	When there is no decoder implemented, the value returned is

		$ sudo ./procfile cpuinfo
		$ sudo ./procfile partitions


package.path = "../?.lua;"..package.path;

local procfs = require("lj2procfs.procfs")
local putil = require("lj2procfs.print-util")

if not arg[1] then
	print ([[

	$ sudo ./procfile <filename>

where <filename> is the name of a file in the /proc

	$ sudo ./pocfile cpuinfo


local filename = arg[1]

print("return {")
putil.printValue(procfs[filename], "    ", filename)

Once you have these basic tools in hand, you can begin to look at the various utilities that are used within linux, and try to emulate them. For example, the ‘free’ command will show you roughly how memory currently sits on your system, in terms of how much is physically available, how much is used, and the like. It’s typical output, without any parameters, might look like:

             total       used       free     shared    buffers     cached
Mem:       2045244    1760472     284772      28376      73276     635064
-/+ buffers/cache:    1052132     993112
Swap:      1046524          0    1046524

Here’s the code to generate something similar, using lj2procfs

#!/usr/bin/env luajit

	This lua script acts similar to the 'free' command, which will
	display some interesting information about how much memory is being
	used in the system.
package.path = "../?.lua;"..package.path;

local procfs = require("lj2procfs.procfs")

local meminfo = procfs.meminfo;

local memtotal = meminfo.MemTotal.size
local memfree = meminfo.MemFree.size
local memused = memtotal - memfree
local memshared = meminfo.Shmem.size
local membuffers = meminfo.Buffers.size
local memcached = meminfo.Cached.size

local swaptotal = meminfo.SwapTotal.size
local swapfree = meminfo.SwapFree.size
local swapused = swaptotal - swapfree

print(string.format("%18s %10s %10s %10s %10s %10s",'total', 'used', 'free', 'shared', 'buffers', 'cached'))
print(string.format("Mem: %13d %10d %10d %10d %10d %10d", memtotal, memused, memfree, memshared, membuffers, memcached))
--print(string.format("-/+ buffers/cache: %10d %10d", 1, 2))
print(string.format("Swap: %12d %10d %10d", swaptotal, swapused, swapfree))

The working end of this is simply ‘local meminfo = procfs.meminfo’

The code generates the following output.

             total       used       free     shared    buffers     cached
Mem:       2045244    1768692     276552      28376      73304     635100
Swap:      1046524          0    1046524

I couldn’t quite figure out where the -/+ buffers/cache: values come from yet. I’ll have to look at the actual code for the ‘free’ program to figure it out. But, the results are otherwise the same.

Some of these files can be quite large, like kallsyms, which might argue for an iterator interface instead of a table interface. But, some of the files have meta information, as well as a list of fields. Since the number of large files is fairly small, it made more sense to cover the broader cases instead, and tables do that fine. kallsyms being fairly large, it will still nicely fit into a table.

So, what can you do with that?

package.path = "../?.lua;"..package.path;

local sym = arg[1]
assert(sym, "must specify a symbol")

local putil = require("lj2procfs.print-util")
local sutil = require("lj2procfs.string-util")
local fun = require("")
local procfs = require("lj2procfs.procfs")

local kallsyms = procfs.kallsyms

local function isDesiredSymbol(name, tbl)
    return sutil.startswith(name, sym)

local function printSymbol(name, value)

fun.each(printSymbol, fun.filter(isDesiredSymbol, kallsyms))

In this case, a little utility which will traverse through the symbols, looking for something that starts with whatever the user specified on the command line. So, I can use it like this:

luajit findsym.lua mmap

And get the following output:

    location = [[0000000000000000]],
    name = [[mmap_init]],
    kind = [[T]],
    location = [[0000000000000000]],
    name = [[mmap_rnd]],
    kind = [[t]],
    location = [[0000000000000000]],
    name = [[mmap_zero]],
    kind = [[t]],
    location = [[0000000000000000]],
    name = [[mmap_min_addr_handler]],
    kind = [[T]],
    location = [[0000000000000000]],
    name = [[mmap_vmcore_fault]],
    kind = [[t]],
    location = [[0000000000000000]],
    name = [[mmap_region]],
    kind = [[T]],
    location = [[0000000000000000]],
    name = [[mmap_vmcore]],
    kind = [[t]],
    location = [[0000000000000000]],
    name = [[mmap_kset.19656]],
    kind = [[b]],
    location = [[0000000000000000]],
    name = [[mmap_min_addr]],
    kind = [[B]],
    location = [[0000000000000000]],
    name = [[mmap_mem_ops]],
    kind = [[r]],
    location = [[0000000000000000]],
    name = [[mmap_mem]],
    kind = [[t]],

Of course, you’re not limited to simply printing to stdout. In fact, that’s the least valuable thing you could be doing. What you really have is programmatic access to all these values. If you had run this command as root, you would get the actual addresses of these routines.

And so it goes. lj2procfs gives you easy programmatic access to all the great information that is hidden in the procfs file system on linux machines. These routines make it relatively easy to gain access to the information, and utilize tools such as luafun to manage it. Once again, the linux system is nothing more than a very large database. Using a tool such a lua makes it relatively easy to access all the information in that database.

So far, lj2procfs just covers reading the values. In this article I did not cover the fact that you can also get information on individual processes as well. Aside from this, procfs actually allows you to set some values as well. This is why I structured the code as ‘codecs’. You can encode, and decode. So, in future, setting a value will be as simple as ‘procfs.something.somevalue = newvalue’. This will eliminate the guess work out of doing command line ‘echo …’ commands for esoteric values, which are seldom used. It also makes easy to achieve great things programmatically through script, without even relying on various libraries that are meant to do the same.

And there you have it. procfs wrapped up in lua goodness.

Burner Computers – and the meek shall inherit the electrons

I wanted to write these words a week ago, because the thought occurred to me then.  But, today I read the news of the latest 5$ Raspberry Pi Zero.  Of course, the world of computing has been on pause much of this past year waiting for the $9 Computer by Next Thing Co.  Of course, the Spark Photon has been making hay over the past year, and has the added benefit of integrated wifi.  Speaking of which, the ESP8266 really got things moving over the past year, because $3!  But, that’s for a fairly tiny micro controller, main benefit being integrated wifi.

So, how does this relate to burner computers?  Well, you know, in the movies, and more so on television crime serials, people are always picking up burner phones.  You know, the kind where you walk into a local convenience store, and seemingly pick a phone off the rack for about $30, make a few clandestine calls, and then throw it in the trash, or crush it convincingly under foot, or throw it deceivingly out the moving car window, or drop it into the pocket of a passerby to throw the trackers off your scent…  You know “burner phones”.  They are so appealing because they’re so cheap, and they provide such anonymous activity.

I feel computers are reaching the same level of ubiquity and cost structure.  As an example, last week I took possession of a laser cutter.  With the cutter there were two things.  A DVD, which contained software drivers, and a USB stick which contained who knows what.  Now, in days of old, I would have stuck that DVD into my Windows machine, seen what was on it, and probably unknowingly installed some sort of root kit.  Same with the USB thing.  Especially after reading about the USB Driveby, I realize there is no way to safely stick anything into your computer without coming away with some sort of disease.  Even worse if you connect anything to the internet, but what ja gonna do?

Well, with a fully functional computer at $5, you can simply plug that foreign media in, browse around, use some forensic tools on it, and when you’re done, or you’ve perhaps done this a few times, throw the computer away!  Yep, that’s right.  It’s served its purpose, that of being a prophylactic against diseases which might otherwise infect various other of your more important computing systems around the home and office.

So, at $5, or $9, or $3, or whatever the very low price is for ‘robust enough’ computing, the Compaticles have arrived!  They will become ubiquitous, low power consumer, all encompassing, and they will inherit the computing landscape.

Now, all they all need is a Lua core, and we’re all set.

graphicc – Scalable Fonts

The initial text support in graphicc was based on some fixed sized bitmap fonts.  That’s a good starting point, and good enough for a lot of UI work, and perhaps even some simple graphs.  But it’s a less satisfying answer when you really want to get into the nitty gritty of things.


Here’s the segoeui.ttf font being displayed in the current graphicc .  Why display in such an unreadable way?  To emphasize that it looks pretty smooth if you don’t look too close…

When it comes to truetype font rendering, the most common goto source is probably the freetype library.  It does a great job, has existed forever, and is used by everyone who doesn’t want to roll their own.  It does great rendering, using the hinting found in the truetype font files and all that.  All that greatness comes at a cost though.  The freetype library is a bit largish for such a small library as graphicc.  So, I went with a different approach.

Here I’m leveraging the stb_trutype.h file found in the public domain stb codes.  The library is good enough to render what you see here, using any of the truetype fonts found on your system.  It won’t do all the fancy things that freetype will, but it at least gives you access to the bulk of the font information, so you can do simple things like kerning.

Whats more, you get access to all the vertex information, so if you want to, you can actually render polygon outlines and the like, and not just take the pre-rendered bitmaps that it offers up.  In fact, one of the strongest parts of these routines is the polygon rendering code.  It makes sense to lift this code up and make it the general polygon rendering code for the entirety of graphicc.  At the moment, there are two or three polygon renderers in the codebase (including samples).  Having one routine which is compact, and capable of dealing with text, and anything else less complex than that, would be a big win for a tiny library such as this.  It will take some work to refactor in such a way that this can become a reality, but it’s probably well worth the effort.

Another benefit of that separation will be the fact that I’ll be able to apply a transform to the vertices for a glyph, and do the cheesy rotated text tricks.
Curious about the code? It’s roughly this

struct ttfset fontset;
struct stbtt_fontinfo finfo;

void setup()
	size(1024, 768);

	//char *filename = "c:/windows/fonts/arial.ttf";
	char *filename = "c:/windows/fonts/segoeui.ttf";

	if (!ttfset_open(fontset, filename)) {
		return ;

	finfo = ttfset_font_from_index(fontset, 0);

void drawText()
	int i, j;
	int ascent, descent, lineGap, baseline;
	float scale, xpos = 2; // leave a little padding in case the character extends left
	float ypos = 2;

	char *text = "Hella Werld!";
	unsigned char *bitmap;

	stbtt_GetFontVMetrics(&finfo, &ascent, &descent, &lineGap);

	for (int pixfactor = 3; pixfactor < 9; pixfactor++) {

		int pixsize = pow((float)2, pixfactor);
		scale = stbtt_ScaleForPixelHeight(&finfo, pixsize);
		baseline = (int)(ascent*scale);

		int idx = 0;
		while (text[idx]) {
			int advance, lsb, x0, y0, x1, y1;
			float x_shift = xpos - (float)floor(xpos);
			stbtt_GetCodepointHMetrics(&finfo, text[idx], &advance, &lsb);
			stbtt_GetCodepointBitmapBoxSubpixel(&finfo, text[idx], scale, scale, x_shift, 0, &x0, &y0, &x1, &y1);

			int w, h;
			bitmap = stbtt_GetCodepointBitmap(&finfo, 0, scale, text[idx], &w, &h, 0, 0);

			raster_rgba_blend_alphamap(gpb, xpos, ypos + baseline + y0, bitmap, w, h, pYellow);

			//printf("%d %d %d", baseline, y0, y1);
			xpos += (advance * scale);
			if (text[idx + 1])
				xpos += scale*stbtt_GetCodepointKernAdvance(&finfo, text[idx], text[idx + 1]);

			stbtt_FreeBitmap(bitmap, NULL);
		xpos = 2;
		ypos += pixsize-(scale*descent);

It’s a bit wasteful in that a new glyph bitmap is created for every single character, even if they repeat, so there’s no caching of those bitmaps going on. If this were a real app, I’d be caching those bitmaps whenever I created them for a particular size.

The primary addition to the graphicc core is the rgba_blend_alphamap() function. It takes the 256 value alpha image generated for a glyph, and copies it to the destination, using the specified color, and the bitmap as the alpha value of the color as it does it. This makes for some nice anti-aliasing, which helps make the thing look smooth.

Well, there you have it. The font support is improving, without dragging in the kitchen sink. It may be possible that graphicc is able to stick to a very slender memory footprint and offer serious enough features.

Render Text like a Boss

And it looks like this:


One of the most rewarding parts of bringing up a graphics system is when you’re able to draw some text.  I have finally reached that point with the graphicc library.  There are many twists and turns along the way, some of which are interesting, but I’ll just share a bit of the journey here.

First of all, the code that generates this image looks like this:

#include "test_common.h"
#include "animwin32.h"

struct font_entry {
	char *name;
	const uint8_t *data;

struct font_entry fontlist[] = {
	{"gse4x6", gse4x6 },
	{ "gse4x8", gse4x8 },
	{ "gse5x7", gse5x7 },
	{ "gse5x9", gse5x9 },
	{ "gse6x12", gse6x12 },
	{ "gse6x9", gse6x9 },
	{ "gse7x11", gse7x11 },
	{ "gse7x11_bold", gse7x11_bold },
	{ "gse7x15", gse7x15 },
	{ "gse7x15_bold", gse7x15_bold },
	{ "gse8x16", gse8x16 },
	{ "gse8x16_bold", gse8x16_bold },
	{ "mcs11_prop", mcs11_prop },
	{ "mcs11_prop_condensed", mcs11_prop_condensed },
	{ "mcs12_prop", mcs12_prop },
	{ "mcs13_prop", mcs13_prop },
	{ "mcs5x10_mono", mcs5x10_mono },
	{ "mcs5x11_mono", mcs5x11_mono },
	{ "mcs6x10_mono", mcs6x10_mono },
	{ "mcs6x11_mono", mcs6x11_mono },
	{ "mcs7x12_mono_high", mcs7x12_mono_high },
	{ "mcs7x12_mono_low", mcs7x12_mono_low },
	{ "verdana12", verdana12 },
	{ "verdana12_bold", verdana12_bold },
	{ "verdana13", verdana13 },
	{ "verdana13_bold", verdana13_bold },
	{ "verdana14", verdana14 },
	{ "verdana14_bold", verdana14_bold },
	{ "verdana16", verdana16 },
	{ "verdana16_bold", verdana16_bold },
	{ "verdana17", verdana17 },
	{ "verdana17_bold", verdana17_bold },
	{ "verdana18", verdana18 },
	{ "verdana18_bold", verdana18_bold }

static const int numfonts = sizeof(fontlist) / sizeof(fontlist[0]);
static int fontidx = 0;

LRESULT CALLBACK keyReleased(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
	switch (wParam)
		case VK_UP:
			if (fontidx < 0) {
				fontidx = numfonts - 1;

		case VK_DOWN:
			if (fontidx >= numfonts){
				fontidx = 0;

		case VK_SPACE:
			write_PPM("test_agg_raster_fonts.ppm", gpb);

	return 0;

void setup()
	size(640, 480);


static char LOWS[] = "abcdefghijklmnopqrstuvwxyz";
static char NUMS[] = "1234567890";
static char SYMS[] = "!@#$%^&*()_+-={}|[]\\:\"; '<>?,./~`";
static char SOME[] = "The quick brown fox jumped over the lazy dog.";

void draw()

	text(fontlist[fontidx].name, 0, 0);
	text(CAPS, 0, gfont.height * 1);

	text(LOWS, 0, gfont.height * 2);

	text(NUMS, 0, gfont.height * 3);

	text(SYMS, 0, gfont.height * 4);

	text(SOME, 0, gfont.height * 5);

Many of the test programs in graphicc have this similar layout. If you’ve every done any programming using Processing you might be familiar with the ‘setup()’ and ‘draw()’ methods. The animwin32 file is responsible for this little construction. Basically, it provides a “Processing like” environment, which makes it really easy to play with various graphics routines. It also does mouse/keyboard handling, so you can setup to deal with key presses and mouse actions. In this case, I use the key up/down actions to change the font from a list of font data. Pressing ‘SPACE’ will take a dump of the screen.

That font data was borrowed from the Anti-Grain Geometry library, because it’s a nice compact bitmap representations of a few fonts.  Just a brief on the AGG library.  This is a fairly well written graphics library written by Maxim Shemanarev, who died way too young I think.  The library is an inspiration and source of knowledge to anyone doing 2D graphics.

The text() function will render the string using whatever is the currently selected font, fill color, and specified location. The location specified the upper left of the font box. There are various text rendering attributes which can be employed, such as alignment, a draw box, whether to use the upper left corner, or the baseline, etc. All in due time.

The guts of the text() routine look like this:

// Text Processing
void text(const char *str, const int x, const int y)
	scan_str(gpb, &gfont, x, y, str, fillColor);

void setFont(const uint8_t *fontdata)
	font_t_init(&gfont, fontdata);

Very simple yes?

And deeper into the rabbit hole…

int scan_str(pb_rgba *pb, font_t *font, const int x, const int y, const char *chars, const int color)
	glyph_t ginfo;

	int idx = 0;
	int dx = x;
	int dy = y;

	while (chars[idx])
		glyph_t_init(font, &ginfo, chars[idx]);
		scan_glyph(pb, font, &ginfo, dx, dy, color);
		dx += ginfo.width;

	return dx;

Basically, get the glyph information for each character, and scan that glyph into the pixel buffer. The scan_glyph() in turn takes the packed bitmap information, unpacks it into individual ‘cover spans’, then turns that into pixels to be placed into the pixel buffer.

Lots can be done to optimize this activity. For example, all the glyphs can be rendered into a bitmap, and then just do a blit to the pixel buffer when needed. This would essentially be a tradeoff between space and time. That’s a choice easily made at a higher level than the lowest graphics routines, so the low level graphic routines don’t make that assumption, they only deal with the packed form of the data. I find this kind of design choice to be most interesting and useful in terms of what kind of profile the overall system has, and what constraints it will adhere to in terms of what type of system it will run on.

So, there you have it.  At this point, the graphicc library can do primitives from single pixels to bezier curves, and text.  With the help of the animwin32 routines, you can do simple UI programming as if you were using the 2D portion of Processing.  I find this to be a good plateau in the development of the library.  At this point, it makes sense to reconsider the various design choices made, cleanup the API, throw in some ‘const’ here and there, consider error checking, and the like.  The next step after that is to consider higher level libraries, which might be purpose built.  I’ll want to incorporate 3D at some point, and there are hints of that already in the routines, but I don’t want to get bogged down in that just yet.  Good image scaling and rotation is probably a first priority before lighting models and 3D rendering.

I would love to be able to create graphic systems profiles, such as, can I mimic GDI, or the HTML Canvas routines.  I can already do Processing to a certain extent.  My first test of the library though is something much simpler.  I want to be able to render the state of a network of machines performing some tasks.  First pass will likely be simple 2D graphs of some sort, so time to get on it.

More Drone Nonsense

Just having a tool/toy in hand makes you thought wander of the possibilities.  After flying the iris+, taking some video in my local neighborhood, and watching other videos people are taking, I believe this whole flying sensor platform thing is going to be quite transformative.  Here are some more thoughts on what might likely come;

Surveillance – of course, but since these things are so cheap and easy, it’s not just going to be the state watching the citizenry.  In fact, the state may lag behind due to various restrictions, such as budget, laws, and the like.  Just imagine that everything will be filmed and listended to by someone.

Everyting else is a form of surveillanace in one form or another.

Animal tracking – As a child I watched Mutual of Omaha’s Wild Kindom.  Marklin Perkins set things up, and Jim Fowler jumped out of the truck to tag the wild rhino.  Well, with a drone, you could just sneak up on the animals from a distance, blow a tracking dart into them, and be done with it.  Not so sexy for the insurance salesmen, but easier for the animal trackers.

Agriculture – another no brainer.  You want to survey the fields.  Fly a pattern, send pictures back to something that can make sense of them.  Dispatch robot machinery to fix problems.  I’m no aggie, but it must be pretty difficult to inspect what’s going on in a field that covers hundreds our thousands of acres.  With a drone, or a few, you could do cameras, take simple soil samples, and the like, send data to some processor, and do your analysis.

Mapping – Another no brainer.  Google has spent years trying to perfect the whole mapping thing.  Multi-camera rigs worn by intrepid mappers, cars with roof mounted thingies, and the like.  But, technology stands still for no technological dream.  Take you van equipped with 20 drones, park it in the center of town, and within an hour, you no doubt can do the job that a self driving car would have done in a few days.  The drones can no only do the street view, but they can do the view up to 100ft as well, pretty easily.  They can track the wifi hot spots, and all the other fun things google has gotten into trouble for.  It doesn’t take a large company, or a monsterous outlay of cash to implement this one either.  I could easily imagine local companies getting in on the act, promoting the intricacy of their maps, or the timeliness.

Sports – When I was in college, I met this guy who with his father, invented that camera system that zips around sports stadiums.  That has provided quite a nice view on the playing field from above.  With drones, you could assign a drone per player, and have them zipping around constantly, filming from interesting angles.  I, as a viewer, could setup my tv viewing to watch the 2 or 3 camera views that I prefer.  Always watch the quarterback, wide receiver, safety, the ball, or the hot dog vendor…  Of course there would have to be automated air traffic control so the drones don’t knock into each other, but that’s a sure bit of software that must be developed anyway.  Ad hoc localized air traffic management for drones.

Some things are autonomous, some things require interaction.  The possibilities are fairly limitless at this point.


Get every new post delivered to your Inbox.

Join 56 other followers