LWJGL 2D Breakout Tutorial – Environment Setup

Update: Just trying to get set up? Check out the streamlined setup tutorial LWJGL 2D Breakout Tutorial – Setup Summary.

So, I’ve been looking around for a good game engine that allows me to develop in Linux and ship to all sorts of platforms. I’ve finally settled on LWJGL, but there’s a lack of information out there for how to do, well, everything. So I figure I may as well take notes while I’m attempting to do stuff.

So, I’m starting right now. I’ve got gedit open, and I’m running in Ubuntu 12.04 x64 LTS. I am very familiar with development in eclipse, and I like Maven for the dependency management it supplies, so I’m going to use Eclipse with Maven[1].

First, we need java and maven.

sudo apt-get install openjdk-6-jdk openjdk-6-jre maven

download and install Eclipse Juno

http://www.eclipse.org/downloads/packages/eclipse-standard-43/keplerr

Now install the maven plugin for Eclipse m2e

maven_for_eclipse

Now we need to create a new maven project for breakout. For me, I put my projects into /home/midas/git/ and the new maven project will add the directories breakout-lwjgl/breakout. This whole path will be referred to as PROJECT_PATH (/home/midas/git/breakout-lwjgl/breakout) from here on, because it will probably be different for everyone.

new_maven_project

pick_maven_type

save_project_location

Ok, now open Eclipse so we can edit the pom.xml to set up our lwjgl dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>breakout-lwjgl</groupId>
  <artifactId>breakout</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>breakout</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <natives.version>0.0.6</natives.version>
    <lwjgl.version>2.8.4</lwjgl.version>
    <slick.version>274</slick.version>
    <junit.version>4.10</junit.version>
  </properties>

  <repositories>
    <repository>
      <id>mavenNatives</id>
      <name>Maven Natives Repository</name>
      <url>http://mavennatives.googlecode.com/svn/repo</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
    <repository>
      <id>slick</id>
      <name>slick</name>
      <url>http://slick.cokeandcode.com/mavenrepo</url>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.lwjgl.lwjgl</groupId>
      <artifactId>lwjgl</artifactId>
      <version>${lwjgl.version}</version>
    </dependency>
    <dependency>
      <groupId>slick</groupId>
      <artifactId>slick</artifactId>
      <version>${slick.version}</version>
    </dependency>
    <dependency>
      <groupId>java3d</groupId>
      <artifactId>vecmath</artifactId>
      <version>1.3.1</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <configuration>
            <source>1.6</source>
            <target>1.6</target>
          </configuration>
        </plugin>
        <plugin>
          <groupId>com.googlecode.mavennatives</groupId>
          <artifactId>maven-nativedependencies-plugin</artifactId>
          <version>${natives.version}</version>
          <executions>
            <execution>
              <id>unpacknatives</id>
              <phase>generate-resources</phase>
              <goals>
              <!--suppress MavenModelInspection (this line is for IDEA) -->
                <goal>copy</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

This caused Eclipse to yell at me for the slick dependency, since that maven repo no longer exists. Awesome! Ok, so I’ll just git clone the slick2d repo from github and then copy the jar over. Hey, look! Someone made a slick2d-maven project!

cd /home/midas/git/
git clone https://github.com/nguillaumin/slick2d-maven.git
cd slick2d-maven
mvn clean install

Aww damn it. Apparently I’m missing a dependency for javaws.jar which only comes from Oracle. Ok, ok. I got this. Looks like WebUpd8 has a nice easy solution.[2]

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java6-installer

Awesome! Now let’s try recompiling the slick2d-maven project using our new java version.

JAVA_HOME='/usr/lib/jvm/java-6-oracle/';mvn clean install

That seemed to work! Now we’ve got a slick2d jar we can use in our repo. We’ll have to change the pom.xml file in the breakout repo a bit…

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>breakout-lwjgl</groupId>
	<artifactId>breakout</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>breakout</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<natives.version>0.0.6</natives.version>
		<lwjgl.version>2.8.4</lwjgl.version>
		<slick.version>2013.08-SNAPSHOT</slick.version>
		<junit.version>4.10</junit.version>
	</properties>

	<repositories>
		<repository>
			<id>mavenNatives</id>
			<name>Maven Natives Repository</name>
			<url>http://mavennatives.googlecode.com/svn/repo</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>

		<repository>
			<id>slick</id>
			<name>Slick2D</name>
			<url>file:${project.basedir}/repo</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.lwjgl.lwjgl</groupId>
			<artifactId>lwjgl</artifactId>
			<version>${lwjgl.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slick2d</groupId>
			<artifactId>slick2d-basic-game-archetype</artifactId>
			<version>${slick.version}</version>
		</dependency>
		<dependency>
			<groupId>java3d</groupId>
			<artifactId>vecmath</artifactId>
			<version>1.3.1</version>
		</dependency>
	</dependencies>

	<build>
		<pluginManagement>
			<plugins>
				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<configuration>
						<source>1.6</source>
						<target>1.6</target>
					</configuration>
				</plugin>

				<plugin>
					<groupId>com.googlecode.mavennatives</groupId>
					<artifactId>maven-nativedependencies-plugin</artifactId>
					<version>${natives.version}</version>
					<executions>
						<execution>
							<id>unpacknatives</id>
							<phase>generate-resources</phase>
							<goals>
								<!--suppress MavenModelInspection (this line is for IDEA) -->
								<goal>copy</goal>
							</goals>
						</execution>
					</executions>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

Now create a “repo” folder inside our maven project and copy the .jar file from the maven cache.

cd PROJECT_PATH
mkdir repo
cd repo
cp ~/.m2/repository/org/slick2d/slick2d-basic-game-archetype/slick2d-basic-game-archetype-2013.08-SNAPSHOT.jar .

Sweet! At this point, in Eclipse you should be able to run maven clean and maven install on your project and have everything come up as success. Awesome! Our environment looks like it’s set up. Let’s run a Maven clean and then run the hello world app that Eclipse has generated for us.

maven_clean

run_causes_error

Ahh, whoops! Since we’re using Maven, we need to tell Maven to install (and compile) our .jar before we can run it. Just run Maven install, and then you should be good to go.

maven_install

Look! Running it makes the console say “Hello world!”

environment_success

Check out the next post in this series: LWJGL 2D Breakout Tutorial – OpenGL drawing and keyboard input

[1] http://www.lwjgl.org/wiki/index.php?title=Setting_Up_LWJGL_with_Maven
[2] http://www.webupd8.org/2012/01/install-oracle-java-jdk-7-in-ubuntu-via.html

Advertisements

After PopCap

I used to think I was awesome. I was a programmer with a plethora of ideas, and the programming know-how to accomplish all of it. But I suffered from a curse; as my projects got larger and more complex, they started to get unwieldy, and I would abandon them. “I solved the interesting parts, you see” I would say, mostly trying to convince myself. I would hack together all sorts of neat tools and cool prototypes, but the ability to make a full app or even just finish one was always just out of reach. I knew that I was an excellent programmer, but I just didn’t have the attention span to finish what I started.

I was a terrible programmer. I was one of the worst, actually. I didn’t understand how to program with objects correctly, I didn’t use frameworks in the right way, and I was constantly terrified of changes I would make to my code. I remember I would tell my boss “I can’t do that” or “it’s impossible without a complete rewrite.” I was single-handedly responsible for many months of essentially “lost” productivity while we “started from scratch” to “do it right this time.”

I claim ignorance. As confident and skilled as I thought I was, my first few months at PopCap were equally humbling. I knew next to nothing, and the things I did know were so completely backwards and wrong that I would have been better off not knowing them. Honestly, I don’t know how I even managed to pass the interview process. Obviously someone saw a glimmer of hope in my inexperience and decided to change my life for the better.

Even now I won’t claim to know everything; I’ve learned better over the last two years. As a programmer I was completely broken down, and rebuilt from the ground up. The things I know now are actually useful knowledge, and I can see how they are good, strong building blocks for evolving further as a developer.

I would like to keep the knowledge I have gained. It’s been only a few months since I stopped working in a team that did this, but already I am beginning to forget, and I never want to lose what I learned. I’ve moved all of my old posts into another category, and I will begin anew here by posting the principles and practices I have learned, along with any examples I might have of actual experience. This is strictly a selfish project, but hopefully others can benefit from the experience I have had, and at least glimpse what my team and I used to call Programmer’s Utopia.

AJAX chat using jQuery

Time to get technical. The main point of this blog was to document the advancements I make in developing the Eye Of Midas, and contribute back to the web what I’ve gotten for free for so long. I’m sure there’s tons of resources for what I’m about to explain, but I enjoy doing things from scratch. So, here’s how to build a simple chat program using AJAX and jQuery, in Code Igniter.

First, you’ll need a place to store large amounts of data that you have quick access to. Check it out, MySQL Server does just that!

Create a database and put a table in it called messaging. (You can call it whatever you want, just make sure to change the appropriate fields in the code, later.

CREATE TABLE IF NOT EXISTS `messaging` (
 `message_id` int(11) NOT NULL auto_increment,
 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
 `channel` varchar(64) NOT NULL,
 `sender` varchar(64) NOT NULL,
 `target` varchar(64) NOT NULL,
 `message` varchar(255) NOT NULL,
 PRIMARY KEY  (`message_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

This builds out a simple table for what we’re going to implement in code.

Code Upkeep. HA!

So I’m not the most diligent blogger. Doesn’t mean I haven’t been doing stuff, on the contrary; I actually have a neat little hack to brag about. So something like this has been on my mind for a while now, but the actual implementation isn’t purely original.

Let me preface this by saying that my girlfriend plays a LOT of Bejeweled Blitz. You know, that Facebook flash game that gives you 1 minute on a Bejeweled board to try and get the highest score possible? Well, she averages in the 200k range, and I can muster a solid 10k on a really good run. It’s upsetting to say the least; here is this very simple game, and I just can’t think fast enough to match up some stupid colors! I mean, it’s so simple I could probably program an AI to do it for me! … wait a second…

Pulling from resources like http://mikevallotton.wordpress.com/2009/08/19/i-cheat-at-bejeweled-blitz/ and http://www.charlesrcook.com/archive/2010/09/05/creating-a-bejeweled-blitz-bot-in-c.aspx I was able to formulate a basic idea. Coders are notoriously bad at explaining things, and these documents weren’t any different. Snippets of code with references to functions that aren’t defined elsewhere in the post, lack of an organizational structure… It got out some good ideas, but definitely not a copy-and-paste dealy.

So I cracked out the C# VS Express (’cause it’s free) and started hacking together my own. As of last night, I have it solving simple patterns, but the code is still pretty ugly. So I won’t post any code yet! I can, however, detail what I’ve done at a high level, and what problems I’ve faced.

Step 1: Where the #*)@% is the game board?

So the first step was to try and find the actual flash window on the screen. I’m sure there are some fancy ways to find it automatically, but for now I’m just using manually-entered coordinate fields on the form. Type in some numbers, click Preview… almost aligned… change numbers again, click Preview… got it!

Turns our Charles Cook found a way to detect the game board on the screen, but used a compiled bit of Matlab (which I don’t have) to do the image processing. Maybe I can find something similar in C#?

Step 2: Duh, what color is red?

This part gave me a good bit of trouble, and I definitely had to come back several times to this part to make it more accurate. The solution I’ve decided on is relatively simple, but much more complex than I thought it had to be. Turns out that if you pick a single centered pixel of each piece on the board, there’s a slight chance that the pixel that’s chosen is on an edge of the gem, or in a shadow. As a result, I needed to pull in a selection of pixels, determine their color and then average them. Guess what?! That doesn’t work either. Or rather, it works, but if the shape of the gem is too small, it will get a lot of the background and throw the bias of color into purple.

The best means I found was to pick a small square inside the piece (10×10 centered) and randomly pick a few pixels out of that. It eliminates the issue with the background, as well as averages out the gem edges and highlights. Plus, since there’s an element of randomness, even if the board reads it incorrectly one time, it might read it correctly the next.

PS3 Update and Hulu workarounds

UPDATE: So it turns out this fix was blocked by Sony pretty soon afterwards, meaning there was not a single way to get on PSN without that update. Which means Sony officially sucks. On the flip side, Anthony Ventura of California has decided to bring a lawsuit against Sony for disabling a paid-for feature in their consoles.

http://ps3.ign.com/articles/108/1086720p1.html

So I’m not a big fan of Sony’s decision to remove the Other OS functionality on the PS3 with the 3.21 patch. Sure, I’ve never used it, but I like the idea of one day putting linux on the box and running a super webserver off of it.

But that’s besides the point. Here I am with a Playstation that can no longer connect to the internet because I refuse to update the firmware. It’s within my rights to be able to use a device I bought the way I want as long as it’s not for criminal activity, right? Anyway, since I have to do a bit of work setting up a proxy for this fix, I figured I might as well enable Hulu on the console as well.

Behold! The steps needed to not only get your out-of-date PS3 back online, but also view Hulu without it being blocked!

First and foremost, I have no concern for Windows or Mac users. If I want to do something cool, it’s going to be in Linux. My webserver uses Debian, so I’ve got this part easier than most.

Make sure you’re doing this on a webserver. I have Apache installed on my box, but it doesn’t really matter what program it is, as long as your localhost can serve up files.

Install Squid proxy.

sudo apt-get install squid

Once you’ve got squid installed, we need to put in a perl rewrite script. I put mine in/usr/local/lib/ps3_update.pl

#!/usr/bin/perl
$|=1;
while(<>) {
s@.*/ps3-updatelist.txt@http://localhost/ps3-updatelist.txt@;
print;
}

Ok, now we have to edit the squid configuration file and put in all of the magic. Edit the squid config file at /etc/squid/squid.conf and add the line:

url_rewrite_program /usr/local/lib/ps3_update.pl

This tells the squid proxy to call the perl script file you made. It matches any server that ends with the ps3-updatelist.txt and replaces it with a link to your local webserver, where you’ll be saving a modified update file. Then you have to find the ACL section and add (or uncomment) both the references to Hulu and your internal network.

acl localnet src 192.168.0.0/16
acl hulu url_regex -i ^http://.*.hulu.com/.*

Make sure that 192.168.0.0/16 is your internal network subnet (this is default, so it should work, but I have mine set to 192.168.1.0/24). Then you’ll need to find the line:

http_access deny all

And immediately above it (in the default configuration for squid, at least), make sure both of these lines are uncommented.

http_access allow localhost
http_access allow localnet

And now add the user agent rewrite for Hulu by adding the following lines:

header_access User-Agent deny hulu
header_replace User-Agent Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)

Sweet! Now you just need to restart squid to have those changes take effect.

sudo /etc/init.d/squid restart

Go to the root directory of your webserver (I think the default is /var/www/html for Apache) and pull down the PS3 update file.

wget http://fuse01.ps3.update.playstation.net/update/ps3/list/us/ps3-updatelist.txt

Then you’ll need to change the line in that file from:

Dest=84;CompatibleSystemSoftwareVersion=3.3000-;

to

Dest=84;CompatibleSystemSoftwareVersion=3.1500-;

and save the file.

That’s it for the server configuration! Now you just need to tell your Playstation 3 to connect to the internet through the squid proxy. Go to the network settings section on your console, and under manual configuration point to the ip address of your proxy server, on port 3128.

That should pretty much cover all of the PS3 network fixes you might want to do. So if you’ll excuse me, I’ll get back to watching Hulu on my 3.15 firmware Playstation. Oh, and feel free to post any comments if you have any questions.

PHP framework

So I’ve been developing website functionality for a long time; HTML and frames in middle school, to the more structured table-based layouts of high school, and eventually moving on to the now-accepted divs+css.

Discovering that the mystical internet was merely a collection of rendered static tags hosted by a computer somewhere completely changed my opinion of it all. What a freakin’ hack! I used to dabble in PHP back then, and all of my sites were on the unfinished/hacked-together level. But I was just a kid! Obviously I was doing something inexperienced that would be grossly overshadowed by the magnificent glory of real web development.

Oops, surprise. The most powerful tools of the internet are the unfinished, hacked-together works (although significantly larger in scale) than my youthful escapades into web dev.

And I’ve come to terms with this. The closest to elegance we can get when writing any internet-code is to wrap the ugly bits into pretty little packages that can be called with the minimum number of lines and parameters.

Which brings me to the best PHP framework ever, CodeIgniter. Some of you may say CakePHP or Symfony, but I disagree. CodeIgniter is the only framework I’ve come across that didn’t get in the way of my programming. I’ve spent years learning actual PHP code, so finding a framework that doesn’t interfere with my most basic of knowledge is a luxury. CI gives me the organisation and structure of the MVC, a readily accessible and informative documentation, and enough community support to really make it worthwhile.

When initially switching from my rudimentary PHP objects into CodeIgniter, I was able to port 90% of what I had written directly in, copy-and-paste. Everything worked, nothing had to be done automagically for me. As I learned more about CI’s abilities, I slowly cleaned up my code; abstracting away all those ugly mysql_connect() and mysql_fetch_assoc() calls into the awesome simplicity of CodeIgniter’s $this->db->query().

While more on the virtue of the Model-View-Controller scheme, I love that now I’m able to completely separate my generated HTML code and CSS layout into entirely independent files; I can now radically change the appearance of my site without ever touching the underlying code that gets it’s hands dirty in the database.

I’ve come a long way from the little kid who wrote his first website in frames on an angelfire page, and I think that finally I’ve reached the elegance of my initial assumptions.

A quick rant

I know it’s a little early in my blog-posting career to rage over something, but this inconvenience has cost me an entire day of work. I am speaking of the wonderful OS X Snow Leopard. I was chosen a few months ago as one of the lucky few in my office who got to install 10.6.1 (or rather, the only IT guy who could cope with the update and patches.)

The update from Leopard to Snow Leopard wantonly destroyed my system fonts and trashed any semblance of networking I once had. Luckily, between my boss’s Apple wizardry and myself, we were able to cobble together enough working hacks to turn this appalling mess into something resembling useful.

I even wrote a simple cron job to cope with exactly this.

Well, on Friday evening of last week, I unwisely shut down my computer and accepted to install the security updates suggested to me by the Software Update program. Monday morning comes around and my network connection is dropping and reconnecting so much I actually managed to kill the chat server for the office. I quickly remove as many hacks as I can remember, but nothing keeps the network stable enough to even google for help.

My hand being forced, I chose to reformat my poor Mac Mini and begin the arduous install of plain-old Leopard. Even got to go home early and work from there. (Linux FTW!) I’m almost entirely caught up in the hours I lost, and my completely clean install is finally shaping back into a familiar environment.

I know that people’s decisions of operating systems is more like a religious choice than anything else, but having spent so much time with Windows, Mac and Linux, I believe I can make an expert assessment and say that OS X sucks. Sorry Apple, nothing personal; your stand-alone devices are still the most usable and adored in the market, but when it comes to computers you guys are far below the competition.

I’ve never had as many problems with Windows as I’ve had with either Macs or on any flavor of Linux, but at least Linux has a good community and is open and customizable enough for me to get under the hood and fix my problems. OS X just combines the sucky parts of both Windows and Linux, and then applies a beautiful user interface over top of it so you don’t notice.

I see through your fancy veneer of glossy buttons and reflective docks, Apple. OS X is merely a graphical hack on an unfinished FreeBSD distro. If I wasn’t stuck using Macs at work, I’d abandon this feeble attempt for an operating system until I discover evidence that there is some significant improvement in the realm of Macintosh.

… so there. 😛

The beginning

To keep me more dedicated with projects and to keep track of any neat hacks/fixes/exploits I find, I’ve started a WordPress blog in the hopes that if I make regular posts, I’ll also make regular software updates. This first post is merely a placeholder until I get into the swing of posting.

The current projects I am working on are pretty varied but tend to relate immediately to web development. My main personal project is to design and develop a browser-based multiplayer RPG game. No, not like Mafia Wars; I’m aiming at more of a Runescape-esque style of browser-play. No flash, just HTML5 <canvas> and javascript.

More details as I invent stuff.