Wednesday, September 18, 2013

Unboxing iOS7, no WebGL

Well, my iPad2 has finished the download, and is into the updating process. I figured I should fire up a blog post and do this sucka real-time.

My first and pretty much only need in this release is for Apple to enable WebGL in Safari. WebRTC is pretty high on the list as well. These are core HTML5 technologies, and years ago Apple kicked Adobe Flash off their devices because, they said, they had a commitment to web standards over proprietary formats.

Granted, a lot of us read between the lines of Apple's statement as only applying to other people's proprietary formats, but we're a cynical bunch.

And in truth, the web is probably stronger now that HTML5 Canvas is out there. Apple did do us a slight favor with the "dragging kicking and screaming", but a lot of people were left with slightly assaulted feeling.

My update has finished the download, but is still preparing.

Oh, by the way, you need have 3Gb of free space before doing the update. For me, that meant deleting my biggest eBooks and my entire music collection. I doubt anyone who's had their iDevice longer than six months would have that much free space. I really hope I get that space back at the end, since I rather enjoyed using my device for more than merely running iOS.

Still preparing...

The problem is, the advancing HTML5 spec is doing to apple the same thing that Apple did to Adobe. Special feature that only iOS Apps had (like using the camera, compass, and local storage) are now core parts of HTML5. Why use an App when a web page can do it all?

Apple controls the App Store, and it has shown a propensity to attack any program, individuals, or technologies which try to end-run around their tollbooth. It makes perfect business sense, but has been rubbing people the wrong way.

Apple championed open standards when it was a way to leverage their device into the market, let's see if they keep the faith. But cynical me remembers Steve Jobs changing position from "Great artists steal!" to "we must defend our intellectual property!" as soon as it was profitable.

Prep finished, I pressed the install button (before it self-pressed) it verified, and now I've got the reboot screen. Waiting....

WebGL means that 3D games and systems can be written in the browser, not as an App. We know apple has ported the technology, because you can do HTML5 WebGL in iAds. Frankly, that's a little galling. Advertisers have access to better technology (in the in-app banner adds) than web developers do in their premier browser. Some people are beginning to release special browser apps that enable this one feature. (Not available in the app store, of course. You have to download and compile it on your OSX developer box. Oh, you don't have one? Too bad.)

The install bar is over a third of the way through. This is going to take longer than I thought.

Mmmm. Coffee. Over half done now.

So, here's the test. Will Apple enable a technology that creates a better cross-browser experience for everyone, if it means reducing the value of the App Store?

Oh, it's saying "Hello" now. It's user friendly, my dear chum.

First impressions:

  1. The keyboard feels 'sloppy' now. Like, an extra 50ms or so before the press is registered. I built a HTML keyboard that felt more responsive than this, clearly worse than the old keyboard. 
  2. They Skeumorphisms are gone, just like they promised. At least there's that.
And now for the big test.

FAIL. No WebGL. No UserMedia extensions.

Cranberries.



Well, thank you Apple, for not helping. You've just managed to derail a major part of my project with one self-interested decision. I was hoping to use your hardware platform to do some interesting things, like map the entire of cis-lunar space using a network of internet connected telescopes, but I guess I'll have to use Android for that instead. Frankly, I don't have time to rebuild my apps for your gated cul-de-sac. It would have been nice to include your users too.

At least it works in iAds, eh? Now we know who you care about the most.

Saturday, September 14, 2013

Fire Map Updates - South Australia Feed Interruption

Temperatures have been ticking up again, so I thought I should review the Fire Map. Good thing I did, because South Australia changed their KML namespace from "http://earth.google.com/kml/2.2" to "http://schemas.opengis.net/kml/2.2.0" which meant all their dots had disappeared from the map. (No bells went off because technically there was still a valid XML document being retrieved - it just seemed to be empty from the old namespace's point of view, something which is often the case in the off-season.)

Doh.

Sorry about that. Fixed now. I rather wish there was an RSS feed for people who depend on the RSS feeds so we could be informed about changes to the feed before they occur. Just saying.

I also would have liked to fill in the final missing square - the Northern Territory - but they still don't have any kind of public incidents feed. At least the MODIS satellites provide hotspots. Shame; It looks like there's a lot on fire up there at the moment.

And I really need to check in again with Queensland Parks and Wildlife, (well, whoever is left) and try to get at their incidents data again, since they essentially cover half the state. (The half where QFRS don't go.)

Alas I haven't been privy to the long-term forecasts for this year, so I'm not sure whether it's expected to be a wild fire season like last time. Let's hope not, but still make plans for if it does.


Thursday, September 12, 2013

Beatmatching the Internet

The primary skill of a DJ is 'beatmatching'; playing two songs together so their beats perfectly overlap and it sounds like one song. (Do it wrong, and the whole room groans from the cacophony.)

The next issue that I have to solve is how to keep a network of thousands of browsers running my peer-to-peer app synchronized with a single network clock. If they don't share common time, then peers can't swap physics state, because positions, velocities, and accelerations are all time-related quantities.

So the paper I've been implementing this week is:
Gossip Based Clock Synchronization for Large Decentralized Systems

The basic principle is stolen from Fireflies. They blink in synchrony with each other in swarms of thousands, or even millions of the little bugs. They clearly don't have a central network-accessible timeserver, so how do they do it? Well, it's also the same way a crowd 'locks on' to synchronized clapping at basketball games. We all have our own 'clapping rate' and we adjust that rate to bring it into perceived synchrony with what we can hear - which is your neighborly 'subset' of people within audio range.



When that principle is in operation (defined as "taking the alpha-trimmed mean of all known peers". "alpha-trimming" is just ranking the list, and throwing away the top and bottom quarters, or some other fixed percentage. In essence, "going with the majority".) crowds that started with pure chaos have order spontaneously emerge, and within seconds the entire ensemble is in perfect lock-step.

Now that's all well and good, but I have also learned the secret pain of all true timekeepers: General Relativity.

Special relativity is enough trouble on it's own, but the concept of speed-of-light delays is entirely tractable and is built into the internet at a fundamental level. Instantaneous communication would really help the problem of keeping remote clocks synchronized, but isn't strictly necessary. So long as the flight-time to and fro are equal, we can cancel them out with some math.

General Relativity explains that there is no such thing as a single reference timeframe. And frankly, we've tended to ignore that as not relevant to our daily lives, but it's no longer the case. If you like having a GPS that gives better than 30 metres of accuracy, then you're invoking full General Relativity, because they have to 'slow down' the clock ticks that the GPS satellites send out because they are higher in the gravity well than us, and therefore time passes slightly faster for the satellites than us.

If you remember your Popular Science, this is the Twins Paradox. We have a situation where the atomic clocks in orbit seem to go faster because, literally, time is faster up there. Send two clocks along different spacetime paths with different time dilations, and they will perfectly record the time they individually experienced getting there, and will legitimately disagree. So we can't do the classical trick of starting a clock in Greenwich and then moving it to Mars, because the path we take will change the result.

If they did not account for that effect, your GPS system would not be accurate to the city block.

But then how does this affect the concept of internet timekeeping? Well, the internet is expanding out into the solar system, catching a ride with the various probes we send. All our protocols are based on an Earth-Greenwich-centric concept of universal linear time, which is fundamentally not true. That's an issue for the JPL planners right now.

And as our clocks get better, we'll begin to notice the same effect across the surface of the globe. If you live on a tall mountain, or in one of those gravitational anomalies, then clocks in your area are going at a different rate. At some point we'll have to add corrections to our internet routers to account for the warp, or packet times will be wrong. Your mobile phone will need know the local rate of time in order to get sub-millimetre GPS accuracy.

As for our Legal System? I'm waiting for someone to divorce an astronaut, and for the lawyers to explain whether the change in marital status propagates at light-speed, or faster. (Is it like a neutrino?) Or more importantly, what 'before' and 'after' actually mean for high-frequency nanosecond trades in the global financial system.

At least for me, at the moment, the accuracy of browser timers isn't sufficient to really show up this problem. Thermal noise will have a bigger effect, so I can get away with purely classical ideas of time. At least, in this version. Call it an open problem.

But now I know why internet timekeepers have such a crazy look in their eyes. For them, the wibbly-wobbly nature of time is a physical presence who comes into their labs and beats up their fragile human conceptions of one-thing-happening-after-another. On a daily basis.

Be kind to them.

Oh, and I got a message from PayPal explaining the new way in which they are being stupid from next month (upgrading from HTTP 1.0 to 1.1 on your servers shouldn't require the entire internet to upgrade their software simultaneously.) in ways which I expect will seriously damage the credibility of the company when thousands of small internet stores suddenly break on Oct 9, and then have to dig through their spam archives to figure out why. But frankly I'm bored of that entire kettle of stupid. My forehead can't take the face-palming anymore.

Wednesday, September 4, 2013

Cosmic Update

I've been busy with Delaunay triangulations, since they're vital to a couple of things I have going on. And then this evening I saw this:
Oh my.

It's like Carl Sagan regenerated and came back as Neil deGrasse Tyson. Parts of my head exploded.

I am so very, very tempted to wrap a vertical fin around my existing virtual astronomy dome in fanboy appreciation, but since I already planned to have one version of the Starship Imagination 'docked' for use as a presentation theater, I can simply make a place for another.

We are all clearly inspired by the same background material, and the shared feeling that it's again time for some Real Science. (Try it!) So I await in eager anticipation. No, better than that... I'll race you. 2014 it is. Let's show the world how incredible the universe really can be.


Saturday, August 31, 2013

Peer to Peer MMO


In the last few days, I've built a browser based peer-to-peer message passing system. It was easier than I thought.

I've also been building control panels, now that all the tech is working. I solved the texture curvature problem with a little trig math and storing polar texture coordinates instead of linear spatial. They look nicer.

Incidentally, I tweaked a few things, and the entire interface is now running in-browser (chrome on desktop) at 60fps, which means that technically I am redrawing the consoles (and entire 3D environment) at a faster framerate than ST:TNG was actually broadcast at. Welcome to the future.


Thanks to PeerJS, I now have a functioning peer-to-peer network between the clients using WebRTC. So far it's just carrying 'chat' messages, but it's a very short step to fully encrypted video streams.


Well, I say 'peer-to-peer network', but currently it's the worst kind - a "complete N-way mesh" where every client connects to every other client and sends everything to everyone. To say this is an area of active research is an understatement, but you have to start somewhere.

Given my fairly low needs, that will probably be good for up to a hundred clients, which technically exceeds the number of concurrent PeerJS connections I can have on their free developer account, but the software is open-source, so I can scale up to my own server when needed.

I'm still using Pusher here and there, (just another ODN Conduit type, from inside the code) but it's clear that solution has a different niche. It's more a 'fallback' for highly constrained mobile devices that can't do all the latest WebRTC networking. (Or even WebSockets) Pusher sometimes takes a second or two to get messages across the network, but it's reliable.

When you have two systems with different strengths and weaknesses, the right answer is often to choose both. In fact, if more peer-to-peer style IM services become available, I'll do my best to fold them in too. Heterogeny is good for networks.

Once again, I'm impressed by the quality of work the W3C demonstrated in building the spec, and the talented people at Mozilla and Google who implemented the hard parts while the ink was still barely dry. You might not realize it yet, but your browser has been granted all kinds of new superpowers.

My only gripe is with the quality of the tutorials; too many of the 'official' demos/tutorials are simply incomprehensible. They look more like test cases. Confusing (repetitive and overly long) variable names, poor documentation, no comments, and one-line functions that call other one-line functions instead of inlining for readability.

That's probably why no-one knows about this stuff - the awful tutorials. A similar situation exists for WebGL. I don't blame the W3C or the devs for this: The W3C specs. aren't really meant to be normal-human readable. They have to use a very precise language where terms like "must", "should" and "may" determine what your IF statements need to do. (Although I'd like to find the person who thinks "candidate" is a noun, and give them a piece of my vocabulary.) And the devs are too busy implementing the code and asking for clarifications as needed.

The poor tutorials are really our fault. Mine too, for not writing better expositions of the tech. 'Newcomers' have to document their journey, and discover the common pitfalls and misconceptions that the developers are not longer capable of making, or realizing that we might make. That hasn't happened yet, so being an early adopter means confusion and headaches. WebGL at least has the HeNe tutorials originally written for pure OpenGL and 'ported' across. The best part was their 'lesson structure', not the code. There'a difference between documenting a standard and teaching a class.

While I don't have the time to write a comprehensive tutorial, I can at least say that WebRTC seems to be worth it. Browsers can't go fully peer to peer yet - some 'signalling' by a server is required to set up the connection between consenting browsers, which specifically prevents the general 'try random peers until we get a connection' algorithms - which could potentially turn your computer into a botnet slave if it has a single insecure listener running in a web page. It's a balance, really.

But even this mediated peer-to-peer ability is going to change the web in ways I can't entirely contemplate. The platform is now ready. Let's see what we build upon it.


Sunday, August 25, 2013

Creator of Worlds, Master of Hyperbola

It's been going so well I've barely had time to update. Here's a more recent screenshot:


So, there's a lot to explain in that image, and it's only the second floor. I've moved the old signal processing consoles down into the 'basement', and the upper floor is left for the planetarium/system map.

The earth and moon should be obvious. Both datasets are from NASA. Earth is the 2013 bathyspheric "blue marble" image, and the moon is albedo corrected. The Sun is textured with the 2012 STEREO image (the first simultaneous full-sun image map) And far off to the left is a pair of Plank Microwave Anisotropy datasets: Background radiation in red, and matter density in blue.

Oh yeah, and there's a skybox too, but it's fake. Looks nice though. There'll be an option to turn it off.

The spheres are not actually spheres - in model space they're cubes. I suppose technically they are 'voxels'. Each sphere is raytraced within the cube with correct perspective, but without creating z-buffer geometry, so "hologram" might also be a good word. The spheres look geometrically perfect, but won't intersect correctly.

Why go to the trouble, compared with simply creating a triangular tesselation mesh for the sphere? Well, each "sphere" voxel is eight vertexes, with no normal or surface buffers. I can have thousand of spheres, millions, so long as they are stacked in non-overlapping minecraft rows.

I'm essentially ready to tackle the next major algorithm, the one which should elevate astromech to a whole new level: Ray Bundle Adjustment.

Long story short: Ray Bundle Adjustment is a tomography technique, think of it as the advanced successor to the 'backprojection' algorithm used to reconstruct CAT scans. Here's a good paper: http://luthuli.cs.uiuc.edu/~daf/courses/Optimization/Papers/bundleadjust.pdf

What the application? Given data coming from multiple viewpoints (such as a ring of solar observatory satellites like SOHO, SDO, or STEREO-A and B) one should be able to reconstruct the 3D structure of the volume.

Near-real-time 3D maps of the Sun and it's near volume (flares, mass ejections) sounds like a neat thing. I expect to have something working within the month.

Another load off my mind is that I found an excellent solution for one of my other problems: sensible rendering of cluster data containing thousands or millions of points. This is some beautiful work, based on the brilliant idea of leaving a step out. Expect to see something very similar in Astromech, soon as I get to it.


Lastly, I'm investigating going nearly fully peer-to-peer for the networking layer using WebRTC. In terms of spec and capabilities for moving video and data streams around, I would be an idiot not too. I'm putting together a small signalling server, and thinking about adaptive mesh "gossip" networks.

Google gave an excellent talk on what WebRTC is all about which I recommend you see, given how much impact that particular spec is going to have on the peer-to-peer internet. Without this technology, I would need some heavy central servers to videoconference a dozen telescopes. Now it can go point-to-point.

That changes many things. Assuming it all works. And it's already in your browser, most likely. There are still Chrome/Moz compatibility issues, but only because the spec is still moving.

So, progress is good. Problems are falling one after another, and the roadmap to release stretches ahead.

Saturday, August 10, 2013

"Aim it at... The Moon!"

So I thought, "keplerian elements are pretty straightforward once you get past the jargon", but there's different jargon for comets as asteroids, so that's still a work in progress. And I assumed that plotting the position of the moon would be a similar exercise.

Oh boy. Utterly not.

Let's just say that the best and easiest way is probably to ping NASA and just ask their big ephemeris computer, called HORIZON.

I did it the masochistic way, which is to port the ELP/MPP002 code out of GAL (the 'General Astrodynamics Library') and into Javascript. The amazing thing is that it seems to have worked.




See how all the lines are off from each other? Like it's a couple of rounds of a strange attractor? Well, that's actually correct. The "orbit of the moon" is chaotic. Not a neat hoop. Practically everything in the solar system perturbs it. The size of the ocean (and hence tide) it's currently over affects it. It's orbit shrinks when the Earth is farther from the sun, and expands again when we're closest.

And since Earth is the Moon's dancing partner, anything it does, we do to, but considerably less so. Plotting Earth's true position (compared to the stable "earth-moon barycenter" which is what most programs approximate down to) means adding a suitably scaled opposing vector.

The equation which computes this orbit is literally the largest I have ever dealt with. It is a polynomial with upwards of 20,000 terms. The code which runs is barely 50 lines long, but the 'coefficients' file it accesses is 10Mb of data.

This 'Lunar Equation' is not a physical computation of any kind. The coefficients represent a 'best fit' curve to the JPL ephemeris computations. (which are physically based) The JPL supercomputer crunched the numbers to find the position over time (ignore that part) and then the ELP computer "compressed" that path down to a best-fit curve. The code then "uncompresses" the coordinates for a given point in time.

Even that 10Mb of data is not the true 'best fit' curve: but, they discovered that adding any more terms actually degrades the computation through rounding errors more than the accuracy gained. That's how big it is.

Once again, I'm surprised at the numerical stability I'm getting out of Javascript's native floats. It's agreeing with the test cases down to the meter, over hundreds of years. Again, it would be good to re-implement the native math with a BigDecimal class, but the performance hit will be intense. Applying those 20,000 trig coefficients means I can only compute about 250 points-per-second on a beefy modern machine. That year's worth of orbit took about four seconds to calculate.

So, I can compute moon positions client-side in the browser now. At the cost of downloading 10Mb of javascript code and intense processing. That's a tradeoff that only makes sense in some circumstances. A pre-computed table of a year's moon positions, three times a day, would only take 3,000 numbers, and would be instant-lookup.

Then again, the GAL table contains _two_ lunar models. It might be possible to split those out. 5Mb (on demand) starts being a very manageable quantity. And the code can surely be optimized.

Friday, August 9, 2013

On being an Orbital Mechanic

I spent yesterday implementing a digital orrey in my WebGL environment. (New furniture is nice) Just the major planetary barycenters, so far. All the numbers and equations come from this JPL document, and frankly I think I spent more time typing and rechecking all the numbers than actually coding the algorithm.



(Yes, I tried copying and pasting the table at the end, in various PDF readers, and invariably got a screen full of Zapf Dingbats.)

Then there was a good half-hour of staring at random messy lines, while I figured out that all the equations assumes angles in degrees rather than radians. Then I noticed that I had the whole solar system upside-down.

You know why Orbital Mechanics has a reputation for being hard? Because it's deliberately made so. Even professional astronomers can't remember the terms or actually do the math. They just use the on-line calculators like HORIZON, and have to look up what "argument of perihelion" means, just like everyone else.

There's a philosophical question hidden in there: when a Jargon becomes so dense and archaic that modern experts in the field don't understand it, what use does it have?

The other reason is the complete lack of a sensible reference frame. Orbital mechanics specified in "Heliocentric" co-ordinates don't actually have the Sun at the origin. (There are side-tables of where the sun is actually located) "Equatorial" co-ordinates are based on the Earth's position, (literally extending the plane of the equator out into space) which sounds easy, until you hear the word "precession", let alone "nutation", or "three body problem".

Earth is probably the worst place to define as a reference point, because it's locked in a three-way chaotic dance with the moon and sun. Yet pretty much all intra-solar-system co-ordinates are based on the "longitude of vernal eqinox" and the "ecliptic plane" from Earth. Both of which are constantly shifting.

OK, it makes the math simple and convenient for Earth-based astronomy. If you're doing it with pencil and paper. Which no-one does anymore. You can tell because all the math is presented as trigonometry, not vector/matrix forms. What's the difference? Quadrants. Inverse trig functions lead to quadrant ambiguity. Which a human must sanity-check along the way with their pencil.

Now I'm on to the task of plotting comets and asteroids, which is fun because their orbits are specified in a different format. Yup, different classes of objects get different co-ordinate formats. Why? No good reason.

Perhaps my biggest surprise in all of this is that Javascript seems quite capable of handing the precision required to crunch the numbers. I was all set to use the 'big.js" arbitrary precision library, (and still should implement that in parallel as a numerical check) but I'm not seeing any numeric instability yet. Granted, if the precision of the keplerian elements goes up another few decimal places then Javascript clearly won't have the mantissa to encode it, but for the moment it matches or exceeds the precision of the data.

Since I like to post code, here's my table of keplerian orbital elements. I've double-checked it, but a triple-check probably wouldn't go astray before you plan a space mission. And they'll slightly improve the numbers in a year or so, so they're always provisional.


var planets_ESAA2006_6K = {
source: 'http://iau-comm4.jpl.nasa.gov/keplerformulae/kepform.pdf',
mercury:{ 
a:['0.38709843','0.000000'], e:['0.20563661','0.00002123'], I:['7.00559432','-0.00590158'], 
L:['252.25166724','149472.67486623'], w:['77.45771895','0.15940013'], O:['48.33961819','-0.12214182'] },
venus:  { 
a:['0.72332102','-0.00000026'], e:['0.00676399','-0.00005107'], I:['3.39777545','0.0043494'], 
L:['181.97970850','58517.81560260'], w:['131.76755713','0.05679648'], O:['76.67261496','-0.27274174'] },
earthmoon:  { 
a:['1.00000018','-0.00000003'], e:['0.01673163','-0.00003661'], I:['-0.00054346','-0.01337178'], 
L:['100.46691572','35999.37306329'], w:['102.93005885','0.31795260'], O:['-5.11260389','-0.24123856'] },
mars:   { 
a:['1.52371243','0.00000097'], e:['0.09336511','0.00009149'], I:['1.85181869','-0.00724757'], 
L:['-4.56813164','19140.29934243'], w:['-23.91744784','0.45223625'], O:['49.71320984','-0.26852431'] },
jupiter:{ 
a:['5.20248019','0.00002864'], e:['0.04853590','0.00018026'], I:['1.29861416','-0.00322699'], 
L:['34.22479152','3034.90371757'], w:['14.27495244','0.18199196'], O:['100.29282654','0.13024619'],
b:'-0.00012452', c:'0.06064060', s:'-0.35635438', f:'38.35125000' },
saturn: { 
a:['9.54149883','-0.00003065'], e:['0.05550825','-0.00032044'], I:['2.49424102','0.00451969'], 
L:['50.07571329','1222.11494724'], w:['92.86136063','0.54179478'], O:['113.63998702','-0.25015002'],
b:'0.00025899', c:'-0.13434469', s:'0.87320147', f:'38.35125000' },
uranus: { 
a:['19.18797948','-0.00020455'], e:['0.04685740','-0.0001550'], I:['0.77298127','-0.000180155'], 
L:['314.20276625','428.49512595'], w:['172.43404441','0.09266985'], O:['73.96250215','0.05739699'],
b:'0.00058331', c:'-0.97731848', s:'0.17689245', f:'7.67025000' },
neptune:{ 
a:['30.06952752','0.00006447'], e:['0.00895439','0.00000818'], I:['1.77005520','0.00022400'], 
L:['304.22289287','218.46515314'], w:['46.68158724','0.01009938'], O:['131.78635853','-0.00606302'],
b:'-0.0041348', c:'0.68346318', s:'-0.10162547', f:'7.67025000' },
pluto:  { 
a:['39.48686035','0.00449751'], e:['0.24885238','0.00006106'], I:['17.14104260','0.00000501'], 
L:['238.96535011','145.18042903'], w:['224.09702598','-0.00968827'], O:['110.30167986','-0.00809981'],
b:'-0.01262724', c:'0', s:'0', f:'0' },
};


Friday, June 21, 2013

...requires extraordinary proof.

I talked a lot of big talk in my last post about the powers of WebGL, so here's my first stable proof-of-concept for a lot of things I've been working on:

http://www.unorthodox.com.au/astromech/jarvis.01/

A friend of mine called it my "JARVIS Interface", and she has a point.

WASD to move Doom-wise. Arrow keys and mouse drag to spin. Scroll wheel to change field-of-view. You'll get the hang of it.

It's pretty indecipherable, but old hands will recognize real-time 2D fourier transforms, velocity (convolution) maps, and some primitive image stacking. The right-hand bunch of panels is a first, failing, attempt to use convolution to seek out the target image (saturn) in the video feed.

That part isn't working. Yet. It's basically a spectacular fail. It's just a snapshot of fail #103, which failed a little less hard than #102, in Iron Man progressive montage style.

In fact, if you don't have the right combination of browser and 3D card drivers to make it all go, it will silently error and break and you'll get some very uninteresting "flatline" displays. Check the console log.

So, there you have it. Real-time 30fps 512x512 2D fast-fourier transforms and convolutions, even though the math is wrong. (i'm normalizing my crosspower wrongly. Working on it now.)

Alas I'll be busy for a few days more, but it was time to update the internet, and see if anyone is interested in where I'm going.

Thursday, June 13, 2013

And the winner is... GL!

For nearly my entire career, Microsoft has been trying to kill OpenGL and replace it with DirectX. I've never been entirely sure why. They used to support it, (the first-gen Windows NT drivers were pretty good) but then they got struck by the DirectX thunderbolt, and decided they weren't going to use an open standard already implemented by the.biggest names in graphics, they were going to make their own.

There was even a period  in the early 2000's where it looked like DirectX might win, because it really did perform better on that generation of hardware. Perhaps because of the high degree of involvement Microsoft had with those vendors. Features were enabled for DirectX that took months or years to appear as OpenGL extensions, for no obvious reason. It was a symbiotic relationship that sold a lot of 'certified' graphics cards and copies of Windows. If it hadn't been for Quake III Arena, OpenGL probably would have died on windows entirely. (All hail the great John Carmack.)

But then, oh then, there was the great Silverlight debacle. I don't think there's any concise way to explain that big ball of disappointment. Perhaps there are internal corporate projects that have real-time media streams and 3D models zooming all over, but on the web it was a near-complete fail. A lot of people put their trust in Microsoft that it would be cross-platform enough to replace Flash. A lot of code got written for that theoretical future, and then it only properly worked on IE.

Here's the secret about web standards, and HTML5 in particular... they lie dormant until some critical 'ubiquity' percentage is passed, and then they explode and are everywhere. Good web developers want their site to work on all browsers, but they also want to use the coolest stuff. Therefore they use the coolest stuff which is supported by all browsers.

Of course, "All Browsers" is a stupidly wide range, so really a metric like "95-98% of all our visitors" is what gets used. So once a technology is available in 95% of people browsers, that's the tipping point.

Silverlight didn't make it, because it didn't properly work on Linux or Mac. Or even most other Windows browsers. Flash used to enjoy this ubiquity, but Apple stopped that when it hired bouncers to keep Adobe out of iOS.

But the pressure kept building for access to the 3D card from inside a browser window. 3D CSS transforms meant the browser itself was positioning DIV elements in 3D space (and using the 3D card for compositing) and this deepened the ties between the browser and the GPU. Microsoft had already put all it's eggs in the Silverlight basket, but everyone else wanted an open standard that could be incorporated quickly into HTML without  too much trouble. There really wasn't any choice.

In a couple of hours, a delivery person should be dropping off a shiny new Google Nexus smartphone. If you run a special debug command, WebGL gets activated. On iOS, the WebKit component will do WebGL in certain modes (ads) but not in the actual browser. The hardware is already there (3D chips drive the display of many smartphones) it's just a matter of APIs.

WebGL's "Ubiquity" number is already higher than any equivalent 3D API. The open-ness of the standard guaranteed that. And as GPUs get more powerful, they look more and more like the Silicon Graphics Renderstations that OpenGL was written on, and less like the 16-bit Voodoo cards that DirectX was optimized for. OpenGL has been accused of being "too abstract", but that feature is now an advantage because of the range of hardware it runs on.

Lastly, WebGL is OpenGL-ES. That suffix makes a lot of difference. The 'ES' standard is something of a novelty in the world of standards... it's a reduction of the previous API set. Any method that performed an action that was a subset of another method was removed. So all the 'simple' calls went away, and left only the 'complex' versions. This might sound odd, but it's a stroke of genius. Code duplication is removed. There are less API calls to test and debug. And you _know_ the complex methods work consistently (aren't just an afterthought) because they're the only way to get everything done.

Rebuilding a 'simple' API of your own on top of the 'complex' underlying WebGL API is obviously the first thing everyone does. That's fine. There's a dozen approaches for how to do that.

In short, WebGL is like opening a box of 'Original' LEGO, when you just had four kinds of brick in as many colours. You can make anything with enough of those bricks. Anything in your imagination. Sure, the modern LEGO has pre-made spaceship parts that just snap together, but where's the creativity? "Easy" is not the same as "Better".

There will quickly come the WebGL equivalent of JQuery. Now that the channel to the hardware is open, we can pretty up the Javascript end with nice libraries. (Mine is coming along, although optimized in the 'GPU math' direction which treats textures as large variables in equation) There are efforts like "three.js" which make WebGL just one renderer type (although the best) under a generic 3D API that also works cross-platform on VRML and Canvas. (Although you have less features, to maintain compatibility)

The point is, while the WebGL API is a bit of a headspin (and contains some severe rocket science in the form of homogeneous co-ordinates and projective matrix transforms) you almost certainly won't have to use it directly. The ink on the standard is barely dry, and there are at least five independant projects to create complete modeler/game engines. Very shortly we will be 'drawing" 3D web pages and pressing the publish button. The protypes are already done, and they work.

Wednesday, June 5, 2013

The Astrometrics Project


Below is a screenshot of a major success from the other night. It's a proof-of-concept of a very big idea, and will need some explaining, not only because prototypes are notoriously unfriendly and obscure.

It's a web-page, that's clear enough. You have to use your imagination somewhat and realize that the individual box over on the right was a live camera feed from the small astronomical telescope I now have set up in the back yard. It's a webcam video box.

That input image from the webcam is then being thrown into the computational coffee grinder, in the form of Fast Fourier Transforms being implemented in the core of my 3D card's Texture Engine. You can see the original image in the top-left of the 'wall', and it's FFT frequency-analysis directly below it.


The bar graphs are center slices across the 'landscape' of the frequency image above them, because in the frequency domain we're dealing with complex numbers and negative values, which render badly into pixel intensities when debugging.

Doing a 2D FFT in real-time is pretty neat, but that's not all. The FFT from the current frame is compared against the previous frame (shown next to it, although without animation it's hard to see the difference) through a convolution, which basically means multiplying the frames together in a special way, and taking the inverse fourier transform of what you get.

The result of that process is the small dot in the upper right-hand quadrant box. That dot is a measurement of the relative motion of the star from frame to frame. It's a 'targeting lock'. Actually, it's several useful metrics in one:

  1. It's the 'correspondence map' of how similar both images are when one is shifted by the co-ordinates of the output pixel. So the center pixel is an indication of how they line up exactly, the pixel to the left is an indication of how well if the second image is shifted one pixel to the left, and so on.
  2. For frames which are entirely shifted by some amount, the 'lock' pixel will shift by the same amount. It becomes a 'frame velocity measurement'.
  3. If multiple things in the scene are moving, a 'lock' will appear for the velocity of each object, proportional to it's size in the image. 
  4. If the image is blurred by linear motion, the 'lock' pixel is blurred by the same amount. (The "Point Spread Function" of the blur)
  5. Images which are entirely featureless do not generate a clear lock.
  6. Images which contain repeating copies of the same thing will have a 'lock' pixel at the location of each repetition.
This is what happens when you 'convolve' two images in the frequency domain. Special tricks are possible which just can't be done per-pixel in the image. You get 'global phase' information about all the pixels, assuming you can think in those terms about images.

Of course you're wondering, "Sure, but what's the framerate on that thing? It's in a web browser." Well, as I type this, it's running in the window behind at 50fps. Full video rate. My CPU is at 14%.

So now you're thinking, "what kind of monster machine do you have that can perform multiple 256-point 2D Fourier transforms and image convolution in real-time, in a browser?" Well, I have an ATI Radeon 7750 graphics card. 

Yup, the little one. The low-power version. Doesn't even have a secondary power connector. Gamers would probably laugh at it.

So the next question is, what crazy special pieces of prototype software am I running to do this? None. It's standard Google Chrome under Windows. I did have to make sure my 3D card drivers were completely up to date, if that makes you feel better. Also, three thousand lines of my code.

Most of this stuff probably wouldn't have worked 3-6 months ago... although WebGL is part of the HTML5 spec, it's one of the last pieces to get properly implemented.

In fact, just two days ago Chrome added a shiny new feature which makes life much easier for people with multiple webcams / video sources. (ie; me!) You can just click on the little camera to switch inputs, rather than digging three levels deep in the config menu. So it's trivial to have different windows attached to different cameras now. Thanks, Google!

The HTML5 spec is still lacking when it comes to multiple camera access, but that's less important now. (And probably "by design", since choosing among cameras might not be something you leave to random web pages...)

So, why?

Astromech, Version 0

This is where I should wax lyrical about the majesty of the night sky, the sweeping arc of our galaxy and it's shrouded core. All we need to do is look up, and hard enough, and infinite wonder is arrayed in every direction, to the limits of our sight.

Those limitations can be pretty severe, though. Diffraction effects, Fresnel Limits, the limits of the human eye, CCD thermal noise, analog losses, and transmission errors. Not to mention clouds, wind, dew, and pigeons.

Professional astronomers spend all their days tuning and maintaining their telescopes. But weather is the great leveler which means that a lucky amateur standing in the right field can have a better night than the pros. In fact, the combined capability of the Amateur Astronomy community is known to be greater, in terms of collecting raw photons, than the relatively few major observatories.

Modern-day amateurs have some incredible hardware, such as high-resolution DSLR digital cameras that can can directly trace their ancestry to the first-gen CCDs developed for astronomical use. And the current generation of folded-optics telescopes are also a shock to those used to meter-long refractors.

Everyone is starting to hit the same limits - the atmosphere itself. Astronomy, and Astrophotography are becoming a matter of digital signal processing. 

The real challenge is this: how do we take the combined data coming from all the amateur telescopes and 'synthesize' it into a single high-resolution sky map?  Why, we would need some kind of web-based software which could access the local video feed and perform some advanced signal processing on it before sending it on through the internet.... ah.

Perhaps now you can see where I'm going with this.

Imagine Google Sky (the other mode of Google Earth) but where you can _see_ the real-time sky being fed from thousands of automated amateur observatories. (plus your contribution) Imagine the internet, crunching its way through that data to discover dots that weren't there before, or that have moved because they're actually comets, or just exploded as supernovae. 

My ideas on how to accomplish this are moving fast, as I catch up the latest AI research, but before the synthesis comes data acquisition. 

Perhaps one fuzzy star and one fuzzy targeting lock isn't much, but it's a start. I've made a measurement on a star. Astrometrics has occurred.

The Moon, captured with a CCD security camera
 through a 105mm Maksutov Cassegrain Telescope
Hopefully before my next shot at clear skies (it was cloudy last night, and today isn't looking any better) I can start pulling some useful metrics out of the convolution. The 'targeting dot' can be analysed to obtain not only the 'frame drift' needed to 'stack' all the frames together (to create high-resolution views of the target) but also to estimate the 'point spread function' needed for deblurring. With a known and accurate PSF, you can reverse the effects of blurring in software.

Yes, there is software that already does this. (RegiStax, Deep Sky Stacket, etc) but they all work in 'off-line' mode which means you have no idea how good your imagery really is until the next day. That's no help when you're in a cold field, looking at a dim battery-saving laptop screen through a car window, trying to figure out if you're still in focus.

So, a good first job for "Astromech" is to give me some hard numbers on how blurry it thinks the image is.. that's probably today's challenge, although real life beckons with it's paperwork and hassles.

It's fun to be writing software in this kind of 'experimental, explorative' mode, where you're literally not sure if something is possible until you actually try it. I've found myself pulling down a lot of my old Comp Sci. Textbooks with names like "Advanced Image Processing", skipping quickly through to the last chapter, and then being disappointed they end there. In barely a month, I've managed to push myself right up to the leading edge of this topic. I've built software that's almost ready for mass release that's only existed before in research labs. There's every chance it will run on next-gen mobile phones.

This is gonna work.

Monday, May 27, 2013

Transform and Roll Out

I've spent most of the last week deep in the Fast Fourier Transform and WebGL Shaders, two things I have not had that much experience with before. Oh sure, I knew the theory, but there's a big difference between that and being able to write actual code.


This paper was extremely useful. My implementation really only added one line.


It didn't help that I set myself a pretty hard challenge on this one. Implement a famously brain-bending algorithm that I didn't entirely understand in a language/environment that I'd never used before. And I have to admit, this time yesterday morning I was staring at frustration at corrupted transforms with no idea how to fix them.

But, when in doubt, work it out by hand. I knew I was close. Exactly half a pixel off, in fact. That's pretty close.

Turns out the gl_FragCoord  coordinates passed to the Fragment Shader are not integers. They are half-integers, which align with the pixel's center. So they run [0.5, 1.5, 2.5...]. (It seems DirectX, which the original paper targeted, doesn't do this.)

Because I like to show the code, here's the WebGl fragment shader which performs a radix-2 Stockham FFT pass on a texture.


<script id="fft-rows" type="x-fragment-shader">
precision mediump int;
precision highp float;
precision highp sampler2D;

uniform sampler2D image; // source texture
uniform float N; // FFT Size (eg. 256)
uniform float Ns; // FFT Pass Size (eg. 128)

// perform a dual-fft (operate on the texture XY as one complex number, and ZW independantly)
// pass for a muti-pass transform of a size declared in the uniforms
vec4 dualfft_rows(vec2 p) {
p.x = floor(p.x);
float base = floor(p.x / Ns) * (Ns/2.0);
float offset = mod(p.x, Ns/2.0);
float iy  = p.y / N;
float ix0 = (base + offset) / N;
float ix1 = ix0 + 0.5;
vec4 v0 = texture2D(image, vec2(ix0, iy) );
vec4 v1 = texture2D(image, vec2(ix1, iy) );
float angle = radians(-360.0*p.x/Ns);
vec2 t = vec2( cos(angle), sin(angle) );
// transform two complex number planes at once
return v0 + vec4(t.x*v1.x - t.y*v1.y,
t.y*v1.x + t.x*v1.y,
t.x*v1.z - t.y*v1.w,
t.y*v1.z + t.x*v1.w);
}

void main() {
gl_FragColor = dualfft_rows( gl_FragCoord.xy );
}
</script>

It computes the twiddle factors explicitly instead of looking them up in a texture (as other variants do, since modern cards probably perform trig faster than texture accesses) and performs two independent FFTs on the xy and zw pairs per pass. Floating Point textures are essential for this.

Of course there's another 1500 lines of code wrapped around this little fragment shader, but a lot of that is 'test' scaffolding that can come down now. However there seems to be a good 700 lines of code that I've packaged into a 'GPU' class that acts as a friendly wrapper around WebGL, and lets me 'compute' with textures like I'm doing simple algebra.

The main point is this: two weeks ago, I had favorable initial impressions of WebGL. There were some pretty demos. It worked great as a toy. But I had some reservations about how far I could take it. Since then, I've implemented one of the most important and powerful scientific analysis tools there is - the Fourier transform. And it flies.

Today's challenge will be to combine the working FFT code with some other experimental code, and jump from images to transforming video. I've already got the code to access the webcam from inside the browser. HTML5 makes all this integration not only possible, but almost trivial.

Lastly, this is a huge load off my mind. I'd been proceeding on the assumption this was possible, (that I can actually write a working FFT in GLSL) so I'm gratified that has proved correct. I spend last weekend standing in a very, very cold paddock capturing astronomical imagery on that assumption. Now I can process that data.

Beyond that, I've now got new tools in my bag of tricks. And a new respect for browsers.

Sunday, May 12, 2013

WebGL Initial Impressions

You know how you put things off, and then when you finally make yourself do it you discover it's actually great fun, and you wonder why you ever waited? I had a week like that with WebGL and the FFT.

WebGL is another of the HTML5 technologies which is poised to make an enormous impact on how we use the internet, and how browser code can accesses our hardware. It is essentially a binding of the OpenGL ES 2.0 spec within Javascript.

Web pages that can do OpenGL. Think about that for a minute.

Then consider that WebGL isn't some wonderful future standard, it's already in most major browsers. (IE people have to wait until 11.) If you have Chrome or Mozilla and a 3D Card, you already have it. Really. Mobile devices also support it (that's really important.) depending on their hardware. (Most new phones have a 3D chip, if only for fast 2D compositing.)

So yes, MineCraft and Quake could be written in Javascript now, and run in the browser on Android. That's great. Lots of people are writing new games, as you would expect.

There's also a second reason why you want to access the GPU from Javascript - it's an enormous chunk of optimized processing power that we can use to do cool stuff. On many machines, it's actually more powerful than the core CPU.

Texture Shaders, in particular, are special programs that are downloaded to the GPU and run per-pixel, in parallel, on perhaps hundreds of 'texture units'. They can perform massive parallel computations that are fast on a lot of useful algorithms besides drawing animation, like Fourier transforms.

The first texture shader I wrote in WebGL computed mandelbrot sets. In a 1024x1024 canvas element, I was generating 1024 iteration mandelbrots at real-time framerates over 10fps. At say 8 math operations per iteration, that calculation consumed 80GFlops, easily. And I wasn't pushing it.

80GFLOPS. Eighty Billion Floating-point operations per second. The original Cray Supercomputers weren't that fast.

And another thing... I've written OpenGL code before, and WebGL is just better. First, there's no mucking around with video capabilities or window handles or bit planes. You put a canvas element on a HTML page. Then you ask for it's OpenGL context. The browser does all the rest. Compared to how it used to be done, getting a GL context is sheer ease.

Then it all gets confusing again when you can't find how to render simple triangles, until you realize the big normalization they did in the OpenGL 'ES' specs is to take away all the 'simplified' methods, and leave only the 'useful' methods, whenever there was a duplication of functionality. You can't draw single triangles anymore. Only triangle strips. (of which the simplest strip is a single triangle, so you can still get the same outcome, just with the 'more useful' method)

Odd enough, this is also a joy to use, once you get your head around it. It makes writing the equivalent of 'hello world' a little harder, but once you've coded minimal vertex and fragment shaders just to get a single quad on the screen, you're already most of the way towards your end goal. Since you're always using the 'hard shader language' and not 'easy shader language', you don't have to stop and re-code once your program exceeds the capabilities of the simple primitives.

All shaders - simple and complex - fit the same basic pattern and become more interchangeable, while shortening the full spec. In the normally expanding world of standards, (to the point they can't be implemented in a single human lifetime anymore) this is an amazing and refreshing achievement.

It does, however, come at the cost of a bigger initial learning curve. GPUs compute in a different way. (That's kind of the point) And it's not necessarily obvious why they function the way they do... GPU card are more a collection of "hacks that worked" than any coherent plan to create a platform. I know a lot about the history of how they evolved to this point, and I've done a lot of parallel programming on SIMD machines too, so most of the shader concepts are already familiar to me.

WebGL is getting a 'Dark Arts' reputation because of this, and not without good reason. We leave the comforting worlds of Paragraps and CSS for matrix math and rendering pipelines.

What I'm discovering is this; it's a Dark Art that's well worth learning. You can perform some very powerful juju.

Assuming your browser can take it, look at some of these: http://glsl.heroku.com/

Saturday, March 2, 2013

Busy, busy. Went to Sydney and came back to Brisbane. There was a flood in one of those places, and the other was trying very hard also.

The fire map has been quite 'successful', in the sense that most of Christmas was spent keeping it going, tweaking it for the sometimes odd conditions under which it was used. For example, Fairfax local media sites  started embedding it, but their restricted column width was squishing some of the controls over each other.

There needs to be times where you - as the developer - should try to understand your user's dilemmas: they can't hack their CMS in one day to do special things just for my map to look better, those limitations are pretty hard set in their systems.

But I could change my code. Faster. It took the entire day, by the next smoky morning I had polished the app so it fit their iframe. It even detected that it had been 'framed' and offered a new menu option to link out to the fullscreen map.

The result - thousands of random people got a slightly better user experience. That's much more useful than a grumpy developer mumbling "but you're using it wrong!"

Fire season has mostly given way to flood season, and traffic has waned to almost nothing. I'll need to revisit it come next fire season, but for now its easy to keep it running. I expect a few feeds will break over the coming months as the agencies mess with their data in the 'off' season.

First Preview of New LOGO Language


Argh. So many half-written updates that I still haven't finished. For the moment, here's a sample of something pretty that I've been working on that just came alive today:

The above is not a mock-up, but a result of running the following chunk of Javascript:


lisp(
["meta",
{ en: "First LOGO Program" },
["do",
["import","logo"],
["to","square",["fn", ["length"], 
["pendown"],
["repeat",4, ["fn",[],
["forward",["length"]],
["right",90]
]],
["penup"]
]],
["canvas","drawing"],
["setpen",2,"red"],
["square",50],
["right",45],
["setpen",3,"black"],
["square",30]

]]
);

What you're seeing is:

  • A LISP-like language encoded in JSON
  • LOGO-like expression library which draws SVG content
  • An interpreter (written in Javascript but designed to be portable) which runs the code, generating the coloured squares.
  • An IDE 'editor' which pretty-formats the code for display, intended for use on a touch screen.
  • Everything running in the browser, client-side, in a sandbox.
Why? Long story. "Parametric content" is about the pithiest explanation I can give. (eg: animation!) And perhaps a little pining for the 80's thrown in. These are old ideas. But they were also considered "too far ahead of their time". I think it might be time.


Monday, January 7, 2013

Now we're cooking

Man, I hate doing that. Hacking up a last-minute feature and pushing it out to the live site with nowhere near enough testing. There needs to be a damn good reason to do that.

Sometime in the last week or so the NSW Rural Fire Service added a new field to their data feed. It's a field called "Instruction" that contains rather useful text like "There is a heightened level of threat. Conditions are changing and you need to start taking action now to protect you and your family."

I swear that field wasn't there before. Looks like I'm not the only one still coding hard and fast for fire season.

It's useful and important information. My framework is built to be adaptive in the face of changing data. It's taken longer to blog about than implement the code. But I still hate pushing features out that fast. It's way too easy to find yourself in a bugfix spiral or take down the site entirely.

I think I made the right decision.

Now if only the Vic fire service would add a similar field... Or the NT Fire service would provide a feed at all.

Thursday, December 20, 2012

Just a regular expression

It's taken me a little time to really get my head around the Javascript regular expressions. You have to be pretty on the ball when you're writing a parser.

In fact I managed to double the decoder speed with a couple of deft new functions, by thinking a little more carefully about the Javascript RegEx objects and their peculiars.

At first, Javascript's RegEx object seem particularly bad for the task of generalized parsing, because parsing generally requires checking the next token and the Javascript function calls seem to do either first or global searches, but not from a given index.

Then they seem like a great idea when you discover the 'sticky' option in the MDN documentation which distinctly allows you to do just this. Then they seem like a terrible idea again when you discover that only Firefox implements them.

Most people get disheartened here and go back to parsing the string themselves character by character. But regular expressions execute as compiled, highly optimized code. You're never going to beat that with 'case' statements.

So, back to the code mines we go, and some more digging turns up the "lastIndex" property on the RegEx objects, which is one of the more badly named javascript methods. (and there are a lot, trust me) It has some quite unexpected behavior, and it's got at least two purposes, but this property in combination with the standard .exec() call, turns out to be exactly what we need.

exec() seems inappropriate (or at least very inefficient), because a LALR parser wants to check if the next chunk of string is the token it wants, and standard exec() with a global option can't be stopped from zooming away into the string, looking for it anywhere. Right to the end if need be.

But that's OK, because if we let it, and then remember where (or if ) it found a match, then we don't have to ask again until we get past that point. It's still very inefficient at the point we first call it, but it gives us enough information to not have to call it again for a while.

It's obvious when you think about the situation when you get near the end of the file. By then, many of the match expressions will have worked out they never appear again. They can just hang up their coats and say 'nope' if they're asked if there's anything left to do. It's called having a functional memory.

Yes yes, standard RegEx optimization tricks. Nothing new. That's not the point.

Once I put the optimization in the code doubled in speed. (whoo!) But only on Safari (iOS) and FireFox (windows). Chrome (windows) and IE (windows) continued running at exactly the same speed as before.

Now that's interesting.

What it suggests is that the Javascript engines in Chrome and IE had already implemented the identical optimization, but at a language interpreter level. I assume they detect the exact same RegEx object being applied to the exact same string object and they just re-start the matching from internally stored state.

But Safari and Firefox clearly haven't implemented this "same regex, same string" optimization, so when I explicitly do it myself it saves an enormous amount of time.

Here's the relevant bit of code. Don't worry about the lambdas.


function decode_rex(type, empty, rex) {
rex_registry.push(rex);
return function(s,i) {
var r = {ok:empty?true:false, pos:i, len:0, type:type};
// are we past the point where we need to look for a new match?
if(rex.lastIndex<=i) {
// match the expression from here
rex.lastIndex = i;
var m = rex.exec(s);
if(m instanceof Array) {
// found it
rex.matchIndex = m.index; 
rex.matchLength = m[0].length;
rex.lastIndex = rex.matchIndex + 1; // safe consumer
} else {
// no more
rex.lastIndex = s.length;
rex.matchIndex = -1;
rex.matchLength = 0;
}
}
// is the next match supposed to be now?
if(rex.matchIndex===i) {
// consume the match
r.ok = true; r.len = rex.matchLength;
}
return r;
}
}



Finite Loop

I was going to post more details about JSON-U yesterday, but right about then the entire concept was in pieces around my feet after discovering a few things about how the colon and semicolon are handled in reality. Don't ask.

But that's OK, because I reworked the grammar and managed to remove both special characters, two more, and added new capabilities besides. To the point of making URL's nearly Turing-complete. Ignore that for the moment.

There are a few last things I'm trying to figure out. I've got my encoding to reliably survive most kinds of common mangling, and it really takes some determined effort to make the parser fail, but there's always the lure of handling one more case now so you never have to worry about it again.

Oddly, by being so free to rip things out of the parser, I'm discovering was of putting them back but using only the things remaining. For example, I had an array constructor syntax, and a function call syntax. Then I removed arrays as an explicit data, which is unhead of, but I kept the named function space (now called 'locallizers") and defined the "unnamed function" to "return an array consisting of the parameters passed to the function".

Boom, explicit arrays are gone. Replaced with a "pseudo-call" to a function that creates them. So functions are more primal than arrays, in a data coding. And since the functions use the round brackets, we save two characters from ever being used.

I've gone round and round, pulling things out and replacing them again. (quoted strings are back, but only to read in user-hacked values, never as output.) and it's like an infinite Rubik's cube where a couple more twists leaves a scrambled mess, but then a few more moves and everything is harmonious and better matched than ever.

I'm down to the point where I have a test page that generates hundreds of random data structures, encodes them all, checks they go backwards again properly, and offers up a list for clicking. I can type random crap into the parse-as-you-type text boxes, and JSON-U tends to cope with this better (spends more time in a 'parsed' state that correctly represents the data) than JSON does.

Along the road I've made some funny choices. But they hopefully combine their powers in a good way. For example, here's one consequence:

If you repetitively 'unescape' canonical JSON-U, you get the same string.
if you encodeURI() canonical JSON-U, you get the same string.

That's actually a major ability, and can't be said for any encoding that has a backslash, percent sign, or space in it. Ever.

("Canonical" just means "the one true blessed way, not the way we do it when we're in a rush.")

The single remaining annoying issue turns up when someone uses encodeURIComponent() on something that ends up in the hash fragment. From what I can tell of the standard, the fragment requires only the equivalent of encodeURI() and all possible component characters, including the hash, are allowed from that point on.

Therefore, doing a blanket encodeURIComponent() or escape() on anything destined for the hash fragment is de facto wrong. But that won't stop people from doing it, because who really knows the standards that well? How far do I go to accept the incorrect behavior? I think the answer is actually "not at all". But then, it might be easy to make it work with just a few more twists of the cube.

At the moment my encoding survives most mangling, Can I make it survive all? Perhaps.

Why do I care so much? Because shortly I'll be handing out URLs in the new format that I'll be expected my server to honor for months. Years even. While the code goes through development cycles, and I'm sure I'll want to change the parameters every few damn months. I need something like JSON-U up and running before I even  hand out my first (versioned, metadata enhanced, expiry timed) links.

I have to be able to accurately predict all possible futures for the data I'll want to transmit and consume. As they say, prediction is very hard, especially about the future.

Fortunately, I am a computer scientist. And predictions of those kinds are one of my superpowers.

Sunday, December 16, 2012

A digression to the heart of the matter

I "invented" a new micro-language over the weekend. I put the word in air quotes, because I was actually trying very hard not to do any such thing, but was forced by dreadful necessity to do some inventing anyway.

Why the odd programmer self-loathing? Because there are already too many microformats in use, and I'm not sure that adding "yet another unifying standard" to the mix will help. But I need it.

Here's the problem: URLs. That's it in a nutshell. Bloody URLs.

There is a spec for them, but hardly anyone reads it. Even when they have, they usually just chop URL strings up with Regular Expressions intended to get the bit they want, and fail utterly if given anything that doesn't start with http:// or https://. So it's a minefield.

The latest crazy thing to do is to make extensive use of what they call the 'hash fragment'; everything that comes after the '#' sign in the URL, which is a special fragment for two reasons:

  • It is never sent to the server during page requests, it's only available to the client browser and scripts.
  • Clicking on a page link that differs only in it's hash fragment from the current page does not reload the page, and in fact does nothing at all (except notify your scripts) if the fragment id doesn't match up with a real element id.

Remember, making the browser focus on an element half-way down the page was the original intention of the hash fragment, so all browsers support it and are 'tolerant' of this abuse. (ie: they don't throw errors or 'correct' the URL because a weird fragment ID doesn't actually exist in the page) We are just extending that metaphor, which just happens to work consistently on almost every browser ever made.

A classic modern use of the hash fragment is to put database article identifiers in it that correspond to AJAX calls to obtain that 'page fragment'. When your script detects the user has clicked on a new 'fragment link', the corresponding article is loaded. Sites like Twitter and Facebook have reached the point where there is only one 'page' for the entire site, and everything you see is dynamically loaded into that container.

A consequence has been such AJAX-driven sites were difficult for search engines (ie: Google) to index properly as none of the 'content' was on any real pages anymore. So they came up with a scheme: When the search engine (which acts like a big automatic browser) sees URLs with hash fragments, why not call a 'special' url with that fragment as a normal server GET parameter (basically, juggle the URL around a bit to put the client part in the server part) and then the site can tell the search engine all about the text and paragraphs that the 'hash fragment' corresponds to.

The search engine can even publish those links, and since they still contain the article id, your site will load up that content and the user will see what they expect!

So long as everyone does their jobs right.

Just to be sure that they don't accidentally index sites which can't cope with this behavior  Google (and therefore all search engines) use the presence of the "!" symbol at the start of the fragment to indicate "this is an indexable hash link"  Since the 'bang' character must be the first one following the 'hash', it is informally referred to as a "hashbang". (For the sound made by primitive parsers mangling your parameter strings just before they crash)

Why does this matter? Well, let's say I have a map application (hey I do!) and I want to record the co-ordinates of their window location into the URL in such a way that if they copy the link and sent it to someone, or just bookmark it, then going back to that link reloads the map to that same geographic location.

These cannot be ordinary server GET parameters, because we can't change the browsers URL to that without causing a page reload. It has to stay in the hash fragment, which means the client has to do all the work decoding it's own parameters.

In fact, wouldn't it be nice if we could just append an entire serialized Javascript object up there in the URL? And then deserialize it again with the same ease as JSON? Hey, why don't you just turn Javascript objects into JSON strings, then URLEncode them? Well:
  • The standard javascript encode/escape routines don't quite do all the edge-case characters right.
  • JSON transforms really badly when URLEncoded. As in, every bracket and apostrophe turning into three or six characters bad.
  • Let's not even get into the unicode/utf8 conversion issues.
  • The result is usually an unreadable mess.
  • A lot of people do exactly that anyway.
Well, if the standard JSON format encodes badly because of its syntax character choices, why not just make some different choices that are URL-friendly? And then deal with the other character encoding issues?

...oh, and it would be nice if the data didn't change format when in the hash fragment compared to when it gets used as a server parameter, since different characters are allowed...
... and it would be nice if we could save some bytes by leaving out some of the JSON 'syntactic sugar' (like quoted identifiers) that aren't totally necessary...
... and if there were a more efficient way of encoding binary strings than 'percent' escaping, that would be good....
... and it would be nice if the user (ie, the developer) could still hand-edit some parameters, but then hide them away without affecting anything else...

That's pretty much what I have done. I'm calling the result JSON-U.


So, that's the why. Next time, the how.