Friday, January 27, 2012

bounding rectangles 101

I'm very psyched to be doing the Global Game Jam for the fourth time-- all around the world people form small teams in order to make interesting games, all over one-48-hour weekend.

Something that comes up often in game programming is the question "did this thing hit this other thing?" Often, the easiest way of figuring that out is using "bounding rectangles", changing the question to the simpler-to-code "does the box corresponding to this thing's outline overlap the box corresponding to this other thing's outline?" (Even if you need to do a finer-grained collision detection, it's often more efficient to start with this question.)

But even with this simplification, it's not a trivial thing to code. If you code like I do, you'll be having two objects, each with an x,y coordinate for their top corner, and a width and a height (referred to now from w and h).  My class in (processing/processing.js) to represent that is something like this:

class boxish{
    float w,h,x,y;
    color c;
    
    boxish(float px,float py,float pw,float ph,color pc){
            x = px;
            y = py;
            w = pw;
            h = ph;
            c = pc;
    }
    
    void draw(){
        fill(c);
        rect(x,y,w,h);        
    }    
}

that lets me create a box, give it a color, and then ask it do draw itself.

So now what?

The first simplification of "do these boxes overlap?" can be "do these boxes overlap horizontally AND vertically"? Because two boxes could be around the same x-coordinate, but if one is way higher than the other one, they won't overlap-- and vice versa for the y-coordinate. By breaking down the problem this way, we're turning our 2 dimensional issue into a 2 1 dimensional ones... much easier!

The trivial code for this is

boolean overlapBox(boxish b1, boxish b2){
    if(overlapHoriz(b1,b2) && overlapVert(b1,b2)){
        return true;
    } else {
        return false;    
    }
}


Ok. Lets start with the Horizontal 1D problem. We have 2 line segments, and we need to know if they touch each other. There are 6 possibilities, outline here in this crude diagram:

I don't know about you, but my takeaway was this: there are more ways for two lines to overlap than for them not to... therefore, we're going to just test for the two cases where they don't - namely where both of line1's points are to the left of line 2's left or both the points are to the right of line 2's right.

So my code was:
boolean overlapHoriz(boxish b1, boxish b2){
    float b1left = b1.x;
    float b1right = b1.x+b1.w;
    float b2left = b2.x;
    float b2right = b2.x+b2.w;
    if(b1left < b2left && b1right < b2left) return false;
    if(b1left > b2right && b1right > b2right) return false;
    return true;
}


overlapVert() should be pretty obvious from that.

So that's it. I put together the following little test program that changes color when the moving box overlaps one of the static ones:


You can see the full psj sourcecode here.

Wednesday, January 18, 2012

a simple jquery slot machine effect

Update! This is now a proper github project with a lot of details filled in... More Information Here!


For work they wanted a "juicy" (I've been promoting use of that term for pleasingly physical or generally pleasant animations) way of showing a randomly generated amount of virtual currency assigned to the user. I suggested a slot machine-effect, and it came out really nicely, a widget with a very high "coolness to code complexity" ratio.

Here's another version of what I quickly came up with, click to spin!


The final product for work was a bit different, a single little rotating slot with graphical icons and more polish,  (including a nice fade in behind once the final amount was displayed). But for messing about purposes, I simplified the display, threw in a few extra windows, and made the results A B C D or F.

You can see the html, js, and css here.

There's very little too it, really: each slot consists of an outer class "slots" that provides the border and has a hidden overflow. Inside each slot is a (very tall) "wrapper", and then the js code adds a bunch of divs of class "slot", each as wide as the wrapper and each containing a random letter.  When it's time to let things "spin", we just animate the wrapper's margin-top property to a multiple (7) of the negative height of a single slot. Some of the secret sauce is the easing, "easeOutElastic" from the jQuery easing module... I wrote about that easing stuff earlier.

If the user clicks again, we repeat the process, adding in extra divs of class slot, and moving an increased seven times the height from where it was before. There are some little tricks going on here: we add more divs than we actually need because the elastic animation overshoots a bit (and of course, it's not really circular like a real slot machine would be), it took a while to realize that you should just move a small # of slots, and I added some randomness to the length of time of the animation, so it didn't all move in lockstep. It would be easy to tweak the timing so slots 2 and 3 started after 1, for a kind of 1....2...3! effect. (Another thing I added for this demo was the use of the "stop()" command... otherwise repeated spin clicks would have to wait until the earlier spins were fully settled. stop() has some arguments I missed when I first learned about it, they didn't come in handy here, but let you control if the element/animation queue finishes the pending animation(s) or just stops cold to start the new one. (Actually it turns out I needed to stop() the animation, including the parameter to jump to the final position, before reading the old position to set the new goal.)

Stuff like this is a great argument for jQuery/CSS UI engineers to err on the side of building things from scratch rather than relying on gluing together pre-existing bits. If I had only used other people's slideshow modules, rather than realizing it was a simple matter of wrapper divs, overflow:hidden, and animating margins, I wouldn't know enough to put this together... but it's really quite simple when you treat jQuery and CSS as the empowering technologies that they are.

BONUS PROTIP: This animation read the old margin-top in order to set the new one
jqo.css("margin-top"); //jqo is the jQuery object
That returns a value like "100px". To get rid of the "px" and treat that as an integer, parseInt works very well, it's designed to read numbers at the start of a string and then stop when it encounters non-digits:
var marginTop = parseInt(jqo.css("margin-top"), 10);
(The 10 after makes sure that we keep things in base 10, if the number string started with, say, a "0", strange  things might result.)
Of course after you've done your math you need to append the "px" again, but you know that already, right?

Thursday, January 12, 2012

on smaller frameworks

(This is a response to Gordon L Hempton's blogpost Javascript Frameworks Are Too Small)

Interesting article link you posted. Why don't we have as many layer of abstractions for web development? One answer might be, each of levels Queru describes is built on a REALLY reliable and well-engineered level beneath it, and there isn't that kind of solidity under JS/HTML5. But I think the other answer is: it's not necessary, at least for a certain kind of developer.

I can't even tell you how foreign I find your proclamation given the choice between two frameworks with equally well-written code, I would probably opt for the larger framework

There's a valid outlook that's the opposite of this: it says, I want to learn as little new as possible to get the job done, to minimize the mental load my tools are causing me. Toolkits with lots of abstraction often don't have good power/weight ratios; they're not much more expressive than more basic toolkits, but there's a lot more you new unique knowledge you have to keep in your head to use them properly (lest you become one of those Microsoft-y types, who can do decent stuff but have NO idea what's going on under the hood, or how to fix it when it goes wrong in a deep way.)

I think more abstract toolkits tend to program in nouns... "configure me correctly/learn which of my calls will do your bidding, and I'll do all the "tough work" and you can keep commanding on high rather than dirtying your hands in the trenches". But the cost of that comes in debugging, where suddenly the result of your bug is more likely to be farther away -- "physically" in the files, mentally in the abstraction -- than if you kept your toolbox nice and light and focused on the solving the problems that are actually a pain in the butt to keep resolving. (jQuery being one of the shining examples of awesomeness for the latter.)

I agree that "a larger amount of energy goes towards dealing with the frameworks involved, rather than the problem being solved" but not in the sense you mean: finding people who know the intricacies of a new stack, or training up people to get that knowledge, is the expense...

Friday, January 6, 2012

jquery animating background positions (and colors)

Short but sweet: "background-position" tends to be a compound kind of setting, with a separate value for x and y, but the single key. This means jQuery's default animation function can't smooth animate it, like it can't animate color transitions. But just like how there's a plugin to let you animate colors there's one for backgroundPosition as well. There's not much to it besides what the page says. I stuck copies of both on my "just in case the links go away" jquery file archive at https://kirk.is/m/files/.

Thursday, January 5, 2012

juicy in 2012: bouncy topicgrid

This is a work in progress for my day job, but I'm digging it so far: squares that jiggle on hover, then expand to twice the size when you "hold".


(Live demo from https://kirk.is/m/files/kirkdev/topicgrid/) These are all divs positioned absolutely with a containing div. The "shove the small blocks out of the way" routine our UX guy Marco was looking for was hard to wrap my head around at first. Say we're growing 0-0, doubling its height and width so it takes 4 spaces instead of 1, a net change of 3 spaces. We start by shoving the columns topped by 0-1 and 1-1 straight down, freeing 2 of the squares. We then shove 1-0 to the right, freeing up the final square. And to make room for 1-0, the column topped by 2-0 has to be pushed down. (But if the block we're growing is on the right side of the layout we change its position so that it grows to the left, and that changes which side our single column down is on.) It seems pretty simple (to me, now) when I write it out (3 groups of blocks to move: the 2 cols. underneath, the singleton off to the side, the single col. down to make room for the singleton) but I kind of had to sleep on it to get the general case.

(The other UI guy Ben pointed out the cool flexible zooming grid at  the Adidas homepage -- that looks like it was an even cooler challenge.)

The other fun and educational part was the "jiggle" when you hover the mouse over a block-- this creates a small juicy "toy" as you sweep your mouse across the whole area. My first idea was trying to use one of the bounce-y easings, but keep the block the same size. This did precisely nothing... I think the easings generally depend on multiples of the difference between two values like width/height or position so you can't "ease in place". I then tried the JQuery UI effect "bounce", but it assumes you have something that can be positioned "relative" on the page, and left the div stuck to the top left when it was done. So I rolled my own, using a series of animations (using the built-in linear easing instead of the default swing)- it animates to random x and y offsets, then animates to half the opposite of those values, then settles back to where it was.

This isn't perfected yet, but it's pretty good. I had to look into different techniques for restoring the squares...  I thought always stop()ing the animation would help, but that just got blocks stuck. So now it just adds the move onto the animation queues, but it works out, in part because things are pretty briskly paced.

Thursday, December 29, 2011

osx vs windows redux

Ranting on obscure blogs is a bit like tossing nickels into the Grand Canyon, but... hey, a nickel!

I sometimes jump the gun in criticizing Apple and OSX. Too often that comes from inexperience with OSX. In many cases, a serious criticism of "you can't do this on a Mac" (for example, easily copying the path information from an open Finder window into a "Save As" dialog) runs head on into a "Mac just does it a different way, you Windows-muddled fool" (you can drag the little folder icon on top of the Finder window!) and gets diluted into vaguer criticisms about "UI emphasis" and "potential confusion" (the way that drag and dropping that icon feels too much like a file system manipulation... and darn it, using string-based paths is sensible, if a bit nerdy.)

So once more into the breach...

One thing holding me back from switching to OSX for my work machine is a feeling that the keyboard support isn't up to snuff... specifically on Windows, nearly every text editor I use maps ctrl-left arrow and ctrl-right arrow to jumping words. Now there is some inconsistency to it: some editors think an underscore is a word break, others don't, some jump to the start of the next word immediately, others jump to the end of the current word first. But at least the standard is there, and I don't have to interrupt my typing flow with mouse movements, or play "press and hold the arrow key 'til the cursor finally gets there".

I thought this problem sprung from Apple's pro-mouse, anti-keyboard stance. The original Mac keyboard didn't even have arrow keys! See for yourself:

But of course, I was wrong. I was expecting that all the keys I was looking for would be mapped to cmd-, which is (roughly) the Mac equivalent of "ctrl". On OSX however, the cmd-arrow keys jump either to the beginning/end of the line (left and right) or of the whole document (up and down). However, The "option" key WAS mapped to what I wanted, with the left and right jumping of words.

Arguably, Mac's use of these keys is more efficient and logical than the PC standards. There's an intuitive hook to how cmd-left/right goes to line endings, and cmd-up/down means the whole document. These keys can then play the role of home/end on PCs: home/end = line, ctrl-home,/ctrl-end=whole document. Furthermore home/end are two of the most wandering keys on laptop and compact PC keyboards, there has been no definitive consensus on where they should go, and sometimes they are mapped to special, laptop only "fn-" keys. So points to Apple for battening down the hatches on that.

So I was wrong. Mostly. But can I say Mac has too many of the wrong kind of keys? Look at this:

 "fn" "control" "option" and "command"! 4 different keys that mean roughly the same thing, "make the other key I'm pressing do something else". To make things worse, the little used key "fn" gets the most prime real estate-- the place where Fitt's Law implies the most important key should go. (To be fair, IBM/Lenovo Thinkpads make the same mistake, and it's even worse because a PC's ctrl key is much more important than the Mac's.)

Here's the same image from a typical Windows keyboard:

It's the same number of keys, but I think handled much more gracefully, with better differentiation. "ctrl" and "alt" are far away from each other. Plus in Windows, there's a stronger convention for when which is used: ctrl- combinations tend to be "do something now": copy, paste, save, new, etc. Alt- combinations are mostly used to pull down menus. (Windows used to have greater discoverability of that feature by underlining the accelerator letter on the menubar, e.g. File and Edit, but now (by default) those underlines are hidden until the user holds the alt key.)

The windows-key is special, in most sense of the word: usually it means a quick hop to the start menu (and I love the way they put the cursor in a search box there... windows-key,"program name fragment", return is a very quick way to start a program that is not frequently used enough to merit a pin on the task bar.) The Windows key also has a few obscure key combos that are all OS-wide, like win-m or win-d for hiding all windows and showing the desktop. (Though weirdly, win-d is reversible by hitting again, and the older win-m is not.)

(And it still seems odd to me that Microsoft managed to get their logo on all that hardware by all those manufacturers...)

So wrapping up my arrow key rant, Mac feels a bit klutzy to me, and it's awkward to use and annoying to remember the distinction between "command" and "option" when going back and highlighting and copy words that I just typed. To make the whole scene worse, why isn't the Option (formerly Closed Apple Key) labeled with its icon,  ?(And what kind of symbol is that anyway? To be fair I guess the Option Key has its uses, like for typing letters with accents and the like, but still there are aspects to it that seem half-baked.

Rant over! I'm still on the fence about making the "switch" (and in part because I worry about Apple being such a dominant monoculture of computing) but thinking about the UI/interface it provides makes the potential transition easier for me.

Thursday, December 22, 2011

bonus: fireworks cheatsheet notes

So the designers at my work use a lot of Adobe Fireworks. It's a cool program. Its raw format is .png, but a cranked up .png that holds lots of stuff like layers, alpha transparency, and even vector information. For enginerds like me who tend to think in terms of pixels only (and maybe diving into crazy complexities like "layers") it's a lot to wrap our heads around... and watching a skilled artisan use it, and its ability to treat text and lines and pieces part as objects, even when they're not explicitly set on a different layer... it's eye-opening.

So, as notes to my future self, I thought I'd write out just what I had to go through to make up the basic white-rectangle-with-drop-shadow images... in particular, how to use Fireworks to slice it into the top,middle, and bottom the final example used.

Here are those notes:


  • make a new image: ctrl-n, 500x500...
  • On toolbar stroke would be null (red line X, fill to white...), fill would be white
  • on the toolbar under vector, make the shape tool do rectangles not ellipse tool
  • draw the shape then handfix the W and H under Properties at the bottom (mostly the width)
  • Under Properties|Filters, Shadow and Glow | Drop Shadow
  • This pulls up some Filter properties. (By default the dropshadow is to the Southeast)
    • so Filters is a list of effects added to this selection, you have to be careful not to make extra ones...
    • the arrows is distance, how far away the center of the shadow is from the center of the item... I want this at zero, centered, not off to one side
      • (which means I can ignore the angle for which direction it should go)
    • I set the fuzziness bigger than 4, like 10 or so
    • you don't see changes applied 'til you close the filter mini-properties box
  • Make sure the canvas itself has the null background selected (indicated with the red line) and you can see the gray and white boxes
  • Here I could select the rectangle with the selection tool, ctrl-c copy, ctrl-n (which autodefaults to the size of the thing in the clipboard), paste, then save. But of course I wanted my 3 slices...
  • now we need to use the slicing tool. You draw bounding boxes (including the dropshadow) and rely on the AI thing to find the right edges for you... I draw one for the top, bottom, and middle. At my first attempt I tried to close-crop the top and bottom without interior padding, but that messed up the shading of the corners, and I had to redo it.
  • Then I go to Export... the settings are QUITE a bit fiddly, what the helpful designer helped me figure out I wanted was "Export:Images Only" "HTML: [None]" "Slices:Export Slices" "Pages:Curent Pages" and "Include Areas without Slices" left unchecked
And that was it!

Sometimes I dispair of ever deeply learning Adobe stuff. It seems like such a different, non-engineery, don't-try-to-understand-everything-we're-doing / intuitive system... or maybe the designers are just more used to. (GIMP. in contrast, is pure-Engineer, we-don't-give-you-any-convenient-defaults, no matter how logical it might be.)