subpixels.com | SPXL.TVblog | contactgallery | videoflash | processingmyspace | facebook

Category / Physics

Springback 21 May, 2008 at 7:01 am

If you don’t do technical, you probably want to tune out right about now. Follow the link to play with things on springs, and press space to randomise the configuration. *boing!*

Flash Link: springpixel_02.swf

I spent some time over the weekend reacquainting myself with the spring simulation Flash project I displayed in an earlier post. I wanted to try out a new effect from the next part of the book, but ended up getting heavily bogged down in trying to work out how to make an object (a class) have it’s presentation (a MovieClip) as a member, rather than have the class itself inherit from the MovieClip class. Up to this point, all of the little balls and boxes were instantated at design time in the Flash editor, which is clearly not The Way Things Should Be, and was seriously limiting my options for creating arbitrary (randomised) configurations.

Other soon started to pop up, such as how to access configuration information for the simulation, such as the acceleration due to gravity and the friction constant. The original design allowed my spring items (things on the end of springs) and springs to ‘globally’ access that information by virtue of them being static class members, but I decided that the SpringSimulation objects should be allowed to vary these values between instances… not that I really expect to be running multiple separate simulations, but it could be interesting for “side by side” type comparisons.

One of the main reasons I wanted to see if I could get this to work without having to inherit from MovieClip is the question: how do you instantiate an object of a MovieClip subclass? MovieClip objects come to life by using the attachMovie() method, not by calling a constructor. Hang on a minute… hold the phones, Batman! Maybe the answer is to just override the attachMovie() method in the subclass! D’oh! I will have to try that later! For now, on with my solution, which was to create a new, simple subclass of MovieClip, with the single added member, handle (of type Object), which can be used to refer back to the main object for which the MovieClip derivative is the “display” of. I needed that because when I started wanting to do things like add an onClick() handler to drag items around, the handler had no way of otherwise referring back to the object it needed to update – big problem!

Here are some snips of code (note: numerous details not related to the issues discussed, such as the physics calculations, are left out):

class SpringItem
{
    public var dragging:Boolean;
    public var sim:SpringSimulation; // Parent simulation
    public var mc:SpxlMovieClip; // Visual depiction of item

    public function init(simulation:SpringSimulation, movie:SpxlMovieClip, ...)
    {
        sim = simulation;
        mc = movie;
        dragging = false;
        mc.onPress = doDrag;
        mc.onRelease = mc.onReleaseOutside = doDrop;
        mc.handle = this;
    }

    public function doDrag():Void
    {
        //NOTE: "this" is the movieclip instance, not the SpringItem object.
        var mc:SpxlMovieClip = SpxlMovieClip(this);
        mc.startDrag();
        var si:SpringItem = SpringItem(mc.handle);
        si.dragging = true;
        si.vx = 0;
        si.vy = 0;
    }

    public function doDrop():Void
    {
        //NOTE: "this" is the movieclip instance, not the SpringItem object.
        var mc:SpxlMovieClip = SpxlMovieClip(this);
        mc.stopDrag();
        var si:SpringItem = SpringItem(mc.handle);
        si.dragging = false;
        si.vx = si.sim.vxm; // The SpringSimulation object has vxm and vym members
        si.vy = si.sim.vym; // ..that are updated with "mouse velocity" for each frame
    }
}

It seems like a lot of hassle, but it works. There is probably a better way! The SpringItems don’t update themselves, the SpringSimulation object is in control – it processes all the springs in one pass (adding per-component accelerations to each involved SpringObject’s vx and vy values), then updates the positions of the items in a second pass, ‘all at once’, as it were.

The MovieClips (eg the red balls) need a reference to the parent SrpingItem object, and each SpringItem needs a reference to the SpringSimulation object for various constants, and the SpringSimulation object actively manages the SpringItems. Curiously, the Spring class has no dependency on the SpringSimulation object: for it’s calculations it needs only the the two ends (SpringItem objects, which do contain references to the SpringSimulation, but these are not used or required), the relaxed spring length and the spring constant. I guess that means I could have two separate “simulation” environments running with a spring connecting across both of them… Synchronisation will likely be an issue, but I’m sure it always is when you are affecting objects in parallel universes! ;o)

Anyhow, the new version likely behaves similarly (if not identically) to the original, so it might seem that a major refit of the plumbing was a waste… only now I can generate objects on springs from code (yay!) and easily create randomised arrangements and “chains” (springs made out of lots of little springs) which have some pretty cool play-with factors, though I think the nature of the simulation means things are far from smooth, and changing some settings (like making the masses quite small) really makes the simulation wig out with unacceptable crazy highspeed superwobbles (yeah, that’s the scientific term!). I didn’t quite get around to implementing the next effect/idea from the book, but maybe that, too, will be easier now that some things have been fixed up.

In any case, space resets, only now with a completely new set of spring connections instead of only varying the strengths, weights, item locations, etc, up and down arrow keys increase and decrease the gravitational effect, and z sets “zero-G”. :o)

Enjoy!

New version: springpixel_02.swf

Original: springpixel_01.swf

-G.

Blackle holes? 24 April, 2008 at 7:13 am

I’ve been reading about black holes recently, you know, those things that Hawking eats for breakfast, but Blackle is something else: a rebadged Google search, painted black “to save energy”, because the white background of the usual Google search pages uses too much power.

What the?.. Sounds like the kind of pseudo-scientific slight of hand or turn of phrase that might make the writings of the Saturday-morning-doorknocking witnesses on evolution (or lack thereof) seem plausible.

An LCD panel uses less power than an equivalent CRT (well, let’s say most of the time – there may be some extreme examples where this is not the case, but not that I know about). LCD = good. LCD screens work with a backlight – a white light behind the (sub-)pixels, which produce the coloured display we see by blocking some of the white light: if you block the red and the green, you’re left with blue. As a side note, now that I think of it, it’s ironic that this ‘emissive’ colour mixing property we typically associate with screens is, in a sense, actually an absorptive colour mixing technology! Perhaps it is better to think of it as transmissive, as opposed to reflective colour mixing (eg CMYK printing). Actually, though, the LCD’s white backlight is separated into red, green, and blue subpixels before the ‘liquid crystal’ part, so each LC cell only deals with one of red, green, or blue light, and it is our eyes that do the actual mixing (this is called optical mixing), such as is with pointillism or divisionism (chromoluminarism) of the impressionists in the art world.

An LED display (think big, like an outdoor display) has red, green and blue lights (maybe white as well), so is an RGB(W) display, for which one might expect having less lights on (ie more black and dark colours) to require less power. A LCD screen (such as in most laptops and most flat-panel displays) is, in a sense, a minus-RGB, or anti-RGB device, but does blocking the light take more or less power than letting it through? That I wasn’t so sure of, so I had a quick read of the technology behind LCD displays before keying the following message to Blackle via their contact page:

On LCD technology…

“The optical effect of a twisted nematic device in the voltage-on state is far less dependent on variations in the device thickness than that in the voltage-off state. Because of this, these devices are usually operated between crossed polarizers such that they appear bright with no voltage (the eye is much more sensitive to variations in the dark state than the bright state).”

Given that most (if not all) LCD screens are probably twisted nematic devices, and producing black on such a device requires application of a voltage (, then surely displaying black instead of white uses MORE power, not less.

I’m sure you are already well aware of this, so am wondering why you don’t just drop the pretending that black screens use less power.

Do you really just not give a shit and it is about making money from the advertising?

Excuse my French (and, to the French, excuse my English; I’m aware that swearing in French is so much more expressive) – a liberty taken as this Blackle caper is apparently Aussie (based in Sydney), and it only seemed proper to show some local concern.

With a little more reading I got to the part about ‘vertical alignment’ LCD’s, which are black in the natural (no voltage applied) state. At this moment I don’t know if that is common, as compared to the opposite voltage requirement suggested earlier as being the most common. It is doubtful that I’m the first person to have such musings (maybe if I now go and do a search… just to, you know, save some energy). I’m supposing it is similarly doubtful that I will receive a particularly meaningful reply. If you ask me, using a bunch of computers (Blackle’s) to process and re-serve search results that have already been provided by a bunch of other computers (Google’s) sounds like using more power than any perceived, perhaps even imagined, display wattage saving.

Meanwhile, on the subject of black holes, I’m currently confused by the notion that a black hole is something that exhibits extremely high entropy. Evidently I wasn’t paying enough attention at some point… If an ice cube has lower entropy than the ice cube when it is melted (water), how can something even more dense, more localised (the probability of a particle being found far off in the universe), less able to change its arrangement with respect to the particles around it (er… this is a pretty vague assumption, given that things are supposed to be ‘weird’ in a black hole!), have higher entropy? Sneaking a peek just now on Wikipedia, I read,

Jacob Bekenstein and Stephen Hawking have shown that black holes have the maximum possible entropy of any object of equal size. This makes them likely end points of all entropy-increasing processes, if they are totally effective matter and energy traps. Hawking has, however, recently changed his stance on this aspect.

Hmm… I don’t know/understand Hawking’s original stance, nor his new one, but it’s nice to know I’m not the only one that isn’t so sure! :o)

-subpixel (subtractive-RGB!)

The spring is sprung 17 April, 2008 at 7:21 am

More Flash fun, this time with balls on springs chained together. The example code in the book I’m reading suggested using trigonometric functions to calculate the ‘spring target’, but I thought I could do it with similar triangles.

Physics-ish based flash animationImagine two items (A and B) connected by a spring of a certain relaxed length (not stretched or compressed). It will help to think of item B as a fixed point and item A as the ‘free’ end of the spring. The item A will tend towards a point that is the relaxed length from B, in a straight line between A and B; it will be drawn towards B if pulled far away, and pushed away from B if it is too close. I’m assuming, of course, a massless spring and a whole bunch of other things – this is only a simple approximation of the very complex real world!

Here is the code:

var dx:Number = itemA._x - itemB._x;
var dy:Number = itemA._y - itemB._y;

if (dx || dy)
{
  var d:Number = Math.sqrt(dx*dx + dy*dy);
  var r:Number = springLength / d;

  var targetX:Number = itemB._x + r * dx;
  var targetY:Number = itemB._y + r * dy;

  // ... other fun bits about the same
}

A diagram would probably help! :o)

Basically I’m using the fact that we have similar right-triangles, and am using a ratio of the relaxed length of the spring to the length of the hypotenuse instead of using atan2() to find an angle then sin() and cos() to extrapolate a position. I don’t have any sort of performance metrics on it (hey, Flash is generally pretty slow for anything), but I’m supposing it could help a bit.

The hardest parts of this little project have been trying to figure out how to get Flash to actually do something… or at least tell me why it isn’t doing something, and moving code into some custom classes proved quite painful. The result is quite nice, though, and I’ll build on the techniques developed here in later projects.

I noticed an increase in size with almost exactly the same functionality when I started moving code in to classes, which I was a little surprised by given that the classes allowed me to reduce code repetition. I’m supposing that using classes (accessing object methods, etc) impinges on performance, but even with only a few balls on springs things were starting to get ‘messy’. The new code breaks things down a lot better and will hopefully allow for integrating new ideas as I make my way to the next chapter…

The Flash movie is roughly five and a half kilobytes. You can grab the boxy handles, and ‘throw’ the balls around. Use the UP, DOWN, 0 (zero) and Z keys to change the gravitational constant used (a little anti-gravity can be fun!), and hit SPACE to assign random masses and positions to the balls, as well as random spring lengths and stiffnesses to the springs. You can’t change the connections just yet – maybe next time!

Flash link: springpixel_01.swf

-G.

Leaves of Grass [1856] 22 February, 2008 at 5:08 am

On Valentines day last week I went to buy an alarm clock (how exciting…), and on my way towards home passed through Borders. I asked, as I have asked at numerous bookshops in the past six months or so, if they had a copy of The Holographic Universe in stock. To my surprise, the answer was ‘yes’. Two copies, in fact, “in the astronomy section.” Astronomy?.. Er, okay, sure, that makes sense.

The book had been recommended quite some time ago by a friend, to follow The Alchemist, The Celestine Prophecy and Way of the Peaceful Warrior – in that order. At the time I’d already read Paulo Coelho’s The Alchemist (perhaps not so surprising as it is apparently one of the best selling books in history!) generously lent by another friend. Between then and now I read the other two books, both of which I enjoyed thoroughly. (Side note: in grabbing links for the books just now, I discovered that films were released of both The Celestine Prophecy and Way of the Peaceful Warrior in 2006! I’ll have to check these out. Something has also been brewing for The Alchemist since 2003.)

In any case, it is a fascinating book, and whilst reading it I was struck by the familiarity of the title of chapter 4: I Sing the Body Holographic.
The chord struck was with the title of an album by Icarus: I Tweet the Birdy Electric. Why does this name seem even otherwise familiar? What is it a quote from, or reference to? After a little searching I come across references to “I sing the body electric”. That’s probably it! From a poem in Leaves of Grass, first (self-)published by American poet Walt Whitman in 1855, though initially without that line, which was introduced in the second edition in the following year.

It turns out that there is a site – The Walt Whitman Archive – which makes the texts available online, so I went to check it out. The archive has not only transcriptions of the text, but photographs of actual book pages… flipping through the second edition, I arrive at the first poem, Poem of Walt Whitman, an American:

I CELEBRATE myself,
And what I assume you shall assume,
For every atom belonging to me, as good belongs to you.

That sounds familiar! It is certainly in keeping with some of the ideas in The Holographic Universe such as things not really being separate, so I flick back through the book and what do I find? The quote at the beginning of the chapter in Talbot’s book:

You will hardly know who I am or what I mean,
But I shall be good health to you nevertheless….

—Walt Whitman, “Song of Myself”

A-ha! Perhaps not what I was looking for, but certainly that’s where the link is. Song of Myself, by the way, being the original title for Poem of Walt Whitman, an American. Mystery solved! The “every atom” quote is probably in Talbot’s book as well. Or perhaps I’ve just imagined it. :o)

Another strange coincidence, or synchronicity, here is that I Tweet the Birdy Electric was released on a label called ‘Leaf’ (Leaf/Inertia).

In all, so far The Holographic Universe, especially Part I, has been a good read. Find out some more about the idea at Crystalinks. I noted there, in the first paragraph, “Michael Talbot (1953-1992)”, and suddenly realised he probably didn’t get to see much of the reaction from his book, published 1991… sadly Michael Talbot died in 1992 from leukemia at the age of 39. Rest in millions of self-referential, universe-encompassing pieces Mr Talbot.

-G.