Layers of Detail with Blitting in SDL

Continuing with my efforts to learn SDL, I’ve drawn kind of a silly set of bitmaps that will be sewn together to form a landscape.

To the left you see a composite of 11 distinct images.  Each image falls into one of 4 layers, Foreground, Middleground, Background, Clouds, and Horizon.

The point of having multiple layers is to simulate depth in a simple side-scroller.  The “closer” the layer is to the user, the faster it’ll slide across the screen.  In the case of the “Clouds” layer, it has a slow but constant motion of its own.  In my simple tileset, I imagine the player to be somewhere in between the “Foreground” represented by the green/orange things stuck to the bottom of the screen and the “Middleground” which are the bent looking rectangular structures in the middle of the image.

For the programming part of this exercise, I’ve been simply following this SDL Tutorial.  That tutorial basically gets you a class that manages the lifecycle of your game along with the main() method.  I had a little bit of trouble getting this to work in OSX, but it turned out that I simply needed to RTFM.  If you’re trying this on a Mac, be sure to copy SDLMain.h and SDLMain.m from the “Extras” folder in the .dmg.

The lion’s share of the work in this SDL_BlitSurface(). This method is well described in the second SDL TutorialBlitting is really just the act of drawing one bitmap on top of another.

To implement layers as described above, I’ll create a class called an ImageLayer which takes an array of SDL_Surface objects (images) and an array of coordinates representing the upper left corner of each instance of the image sorted by X coordinates.  As the layer gets scrolled left or right, it’s a simple matter of keeping track of which image instances represent the extreme edges of what’s visible. All images in between these extremes get rendered.

With multiple ImageLayers populated with images and where they are, you render each layer from furthest to nearest.

Controlling 6 LEDs with only 3 pins

The Arduino Uno has something like 13 digital I/O pins and 5 analog I/O pins which can be re-tasked to act like digital pins bringing the grand total of 18 possible Digital I/O pins to work with… so what happens when you need to work with more than 18 different devices?  For example… what if you wanted to independently strobe 19 LEDs?

Here, I've connected 3 LEDs directly to the Arduino UNO's digital I/O pins 2,3 and 4. In this configuration, I could control at most 18 LEDs independently.

I’ve come up with a project which faces just such a problem… I want to be able to independently light up and update 32+ little 20×2 LCDs with a single Arduino.  To give a little context, each LCD has 16 pins, 8 of which are data pins.   This means that 8 of the 18 digital out pins from the Arduino must be used for sending data to the LCD.  That hardly seems like more than one could possibly be driven by a single Arduino!  Clearly, if my plan is to be realized, I need to come up with a scheme that doesn’t involve directly driving all the LCDs from the Digital I/O pins.

Remembering back to my Structural Computer Organization class, I realized the answer: Demultiplexing.

Here, I'm controlling 6 LEDs with only 3 pins through a 3-8 multiplexer. Chaining multiplexers together, I could control 2^N LEDs with N pins.

A Demultiplexer or Decoder is a component made up of logic gates that takes a combination of inputs and chooses a corresponding output.  Generally, for you can choose from 2^N outputs with N inputs.  Learning about them in class is one thing.. but actually sticking them on a breadboard is another.  I chose this Demultiplexer: the HD74LS138P.  It’s a 3-input 8-output multiplexer. It turns out, though that it works counter to how I expected it to.. instead of the selected output being high, the selected output was low and the other outputs were high.  When I hooked it up to my LEDs… all of the LEDs were on except for the one currently being selected!

Using a hex inverter, I was able to invert the outputs of the Decoder and make the selected output be on while having the other outputs stay off.

Ok… well, If I want the unselected outputs to be low while the selected is high, I need to invert the output of the multiplexer.  It turns out that there are little chips that have a bunch of inverters built into them.  The popular form factor seems to be the “Hex Inverter” which is simply 6 inverters crammed into a 14-pin package.  I ended up using a MC54F04 to do it. It seems like every semiconductor makes identical hex inverters, so Jameco‘s catalog just says “popular manufacturer”.  Anyhow, you can see from the photo to the left, using the inverters, we now have selected output being on and unselected outputs being off.

If you’re curious about the code that I used for this setup? Here it is.. It’s pretty simple:

int count = 0;
int values[8][3] = {
   { LOW, LOW, LOW },  
   { LOW, LOW, HIGH },  
   { LOW, HIGH, LOW },  
   { LOW, HIGH, HIGH },  
   { HIGH, LOW, LOW },  
   { HIGH, LOW, HIGH },  
   { HIGH, HIGH, LOW },  
   { HIGH, HIGH, HIGH },
};

void setup() {                
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);     
  pinMode(4, OUTPUT);       
}

void loop() {
  count = (count + 1) % 8;
  digitalWrite(2, values[count][0]);
  digitalWrite(3, values[count][1]);
  digitalWrite(4, values[count][2]);
  delay(1000);
}

In the setup method, we say that pins 2, 3, and 4 are assigned output roles.  In the loop, we increment our count variable and if the count exceeds 7, it gets set back to 0.  We then set our pins HIGH or LOW depending on the count’s offset in our table of values.   We also put a 1 second delay between loop executions so that the loop doesn’t happen too quickly to see.

One kind of annoying problem that I ran into while stringing up my Decoder was, it has 3 pins called G1, G2a and G2b which are effectively enable pins.  G1 must be HIGH and BOTH G2a and G2b must be ACTIVELY LOW in order for the demultiplexer to work.  I didn’t realize it and only connected G2a to ground… so naturally nothing worked because G2b was not actively being set to LOW (not directly connected to ground).  It wasn’t until I grounded both pins, that the decoder started decoding.

screw this noise, libsdl to the rescue!

I’d spent the last week beating my head trying to learn the dark arts of programming for the OS X.  I had basically gotten a window to open up… but that was it.  Did i really want to learn this? or was this simply a means to an end?  I’m guessing it’s the latter… there has to be a better solution than this. Turns out there is… libsdl.

It had all but skipped my mind… the Simple Directmedia Layer.  It’s basically a platform abstraction library that lets you write media-rich native apps without worrying about what the underlying architecture is.

I first tried using it about 5 years ago and was fairly impressed.  It’s easy to use and has a whole mess of language bindings.   I think I’ll be doing more of my n-body stuff using this lib as the front end instead of trying to learn all of the cocoa specifics.

Hopefully, this time next week I’ll have something that’s downloadable, runnable, and interactive!

Objective C, C++ and OpenGL

I started working on converting my N-Body simulation code over to C/C++ and realized that I had no idea how I’d actually display the results.  So… it was time to learn a little about displaying stuff in OS X.

One thing that struck me as ungainly was having to use XCode when really all I wanted to do was get myself a window and draw to it. This lead me to this awesome blog post showing a very minimalist Cocoa app.

With that start, I thought that I’d try to do most of my work in C++ instead of Objective C… so how does one do THAT in OS X?? There seems to be a bunch of literature about how to make C++ calls from Objective C… but not the other way around, which is really what I want to do… I want my C++ code to be the driver of the application and use Objective C to pass events and display results… It was stackoverflow to the rescue with this article: http://stackoverflow.com/questions/1061005/calling-objective-c-method-from-c-method

Essentially, you write yourself a C header with some forward declarations for methods that are later declared in a .mm file.  Assuming that you’re coding in C++ instead of C, compile with g++ or you’ll get a lot of strange missing symbols at link-time if you use plain old gcc.

Once I have things going smoothly, I’ll post the skeleton code up on github!

The Lady of Thorn Keep, Part 3

Good friend and co-conspirator, Stephanie Stone has completed the third part of our on-going collaboration!

You can see from the image to the right, we’ve finally hit some action. As always, Steph does an awesome rendering; in this case, of Sorcha facing off against the Warlock, Fenris Wolfborne.

I’ve updated the story page to include the third part of our adventure! As always, comments and discussion are always welcome.

You can contact Stephanie and see more of her art at her Deviant Art account!

Wrapping N-Body Simulation

Continuing with my previous efforts, I updated my N-Body simulation code to not require the edges of the simulation to be boundaries.  Instead, the edges now wrap.

That might seem like a pretty simple change, but the code involved gets a bit complex…

For example, say you’re calculating the force between particle A and some other particle B and particle B’s force is wrapped around the screen, you need to basically translate B to the other side of A and do your calculation…

If you’re in a corner… say the upper right, you’d have to do this with all particles above and all particles to the right of you, so you’d need to do two sets of transformations.

The process is slow enough with 100,000 points that I need to think about moving from Java, which is what the simulation is currently written in, to something speedier, like C.

16×2 LCD Display Contrast

A few weeks ago, I put in an order to Jameco for some parts that’ll help me complete some of the projects in Michael McRoberts‘s book Beginning Arduino.

One of the more interesting components was this KST1602B 16×2 LCD Display.  I dunno about you all, but ever since I saw one on a digital calculator, I’ve wanted to bend one of these bad boys to my will… and now I have! … well, sorta.

The first time I wired this up, I got a totally blank screen. I had assumed that I did *something* wrong and went through and re-verified that things were connected right.  Finally, I eyed the resistor that I had been using on the “Contrast” pin on the LCD.  (V0 in the case of this one).  I had chosen a resistor close to that described in the book, but meh… so I pulled out the potentiometer from my last project and hooked that up to pin V0.  It turns out that the resistance needs to be a lot more than what I had expected!

To the left you can see an image with three contrast settings on the potentiometer.  The top one is max (about 10k ohms) the middle one was maybe 8k ohms and the last one represents anything less than say, 7k ohms.

When you look at the data sheet PDF, the section called “Adjusting Display Contrast” seems to suggest that you can put a resistance of between 20 and 50k ohms… that’s a HUGE range considering that what you can go from visible to NO contrast in less than 2k ohms.  I feel like the contrast range should be a little more linear… but that’s just me.

 

Using Background Images in Blender

While I was building the iPhone4 model, I began to realize that my proportions were off.  The Home Button seemed out of place. The front camera and speaker were not quite the right shape.  The buttons and breaks in the seems were a bit off from where they needed to be… the list went on and on.

It turns out that blender has a feature for exactly this problem, background images.  This lets you set an image as the background to your modeling space, thus allowing you to match up your mesh boundaries to features of the image!  Obviously, care has to be chosen when choosing these kinds of images, but assuming you can find fairly orthogonal shots of the front, back, left, right, top and bottom, you can model very precisely from actual photographs.

Ok. How can you set background images?  Go to your view menu and click properties. That should pop up a properties pane.  Near the bottom of the properties pane, you’ll see the widget for background images.  Check the check box and click “Add Image”.  Select which view you’d like this image to show up in (front, left, right, back, etc) and expand the “Not Set” arrow. That should give you a little dialog box that’ll give you a file picker.

You can add an image for every orthogonal view, so when you hit a perspective key on the number pad, the appropriate background image is displayed.

After digging around the web for a while, I finally found a set of images that could help me re-tune my iPhone mesh… here’s the mesh with the “front” background image

Smooth Analog Input Class for Arduino

In the above photo, you see my Arduino Uno with a mini-breadboard ProtoShield.

Here, I wired it up to accept data from a potentiometer on analog input A0.  I also have a standard servo connected to digital pin 7.  The point of this is, you turn the potentiometer, it produces a corresponding motion in the servo.

Here’s the initial code that I used for making this happen:

#include 

Servo servo;
int last;
void setup() {
    servo.attach(7);
    Serial.begin(9600);
    last = -1;
}

void loop() {
  int current = analogRead(A0);
  int scaled = map(current, 0, 1024, 0, 180);
  if (scaled != last) {
    last = scaled;
    Serial.println(scaled);
    servo.write(scaled);
  }
}

Pretty simple stuff.  You see I attach he Servo object to pin 7 and within the loop() section, read from A0, scale the value, then write it to the servo! It works!

One kind of annoying thing that I noticed was… the input from the potentiometer wasn’t terribly stable.  Even when it was just sitting there, it would output values that were up to plus/minus 5.  Because of this, my servo was constantly twitching.  Not only is that probably not good for the servo, you could constantly hear it too… so it was annoying.

It turns out that in one of the Arduino Tutorials, they talk about analog input smoothing.  Essentially, you take 10 readings and average them.  That’ll give you a more stable value.  The problem with using the code from the tutorial is, it’s ungainly.  It would be nice if we could create an object, attach it to A0 and have it automatically smooth incoming values for us… well, that’s what I wrote!

You can grab the actual code from here: http://github.com/rl337/incubator/tree/master/main/arduino/libraries/SmoothAnalogInput

The prototype for the object looks like this:

#define SMOOTH_ANALOG_INPUT_SIZE 32

class SmoothAnalogInput {
    public:
        SmoothAnalogInput();
        void attach(int pin);
        void scale(int min, int max);
        int read();
        int raw();

};

The object smooths data over 32 samples. You attach() the object to whatever pin you want it to smooth input for, in our case, A0. the raw() method takes a reading and returns the raw value from the analog input. the read() method returns the smoothed result which can be automatically scaled between a min/max value if you call the scale() method. Here’s the program reworked to use the SmoothAnalogInput object

#include 
#include 

Servo servo;
SmoothAnalogInput ai;
int last;
void setup() {
  Serial.begin(9600);
  servo.attach(7);
  ai.attach(A0);
  last = -1;
}

void loop() {
  int sensorReading = ai.read();

  int scaled = map(sensorReading, 0, 1024, 0, 180);
  if (scaled != last) {
    last = scaled;
    Serial.println(scaled);
    servo.write(scaled);
  }
}

Looking at the Serial Monitor, there are still a few cases where the servo fidgets, but by and large, the values become stable quickly after you stop moving the potentiometer.

iPhone4 Blender Model – Still incomplete, but oh well..

Continuing my efforts to fill in all the models needed to render the first Little Robots Script, I started on modeling a phone… in this case, my iPhone4.

I thought incorrectly that the simple shape of the phone would make the modeling go by pretty quickly… but it turns out that there is some trickyness involved with how you get the little buttons and indentations into the body itself.  There’s also texturing complications.  You want the screen to be a single rectangular texture so that when you animate, you don’t have to worry about strange artifacts involving the screen content being stretched or otherwise transformed.

On this model, I still need to add the speaker holes and interface jack at the bottom as well as the buttons on the side.  I need to revisit the front surface though. I’d like to actually put a transparent layer over it just like the real thing… I’ll be able to easy texture that with smudges and blemishes.

Here’s what  I have rendered in-scene…

The metal texturing still isn’t quite right.  For some reason I’m getting strange textured reflections from the surface of the phone. You can see it toward the home button in the render.  It looks like it’s reflecting the wall, but the stucco pattern is way too emphasized.