Unity: Un-even progress bar

Posted in Programming on April 15th, 2011 by Jacob

One afternoon at the DADIU production, I was assigned the task of creating an un-even progress bar for the game (Branch) [branchgame.com].

Having searched the documentation and forum, I didn’t see an easy way to do this posted anywhere.. thus this post.

The idea is having image A as a background to image B, which is the fill. Then, calculating the percentage of image B which needs to be filled and using Unity’s ScaleMode.ScaleToFit when drawing image B on top of A, the desired effect can easily be achieved. An example can be seen in the image below.

Example of un-even progress bar

Example of un-even progress bar

The code for the GUI can be seen below, and a unitypackage with the example can be found here [jbmadsen.com].


using UnityEngine;
using System.Collections;

public class GUIMask : MonoBehaviour
{
    public Texture2D tex = null;
    public Texture2D texOver = null;
    private Rect texRect;
    private Rect texOverRect;
    private int texWidth = 200;
    private int texHeight = 200;

    private int counter = 0;

    public void Start()
    {
        texRect = new Rect(Screen.width - texWidth - 10, 10, 
                           texWidth, texHeight);
        StartCoroutine(Counter());
    }

    private IEnumerator Counter()
    {
        while (counter < 100)
        {
            counter++;
            yield return new WaitForSeconds(0.2f);
        }
    }

    public void OnGUI()
    {
        if (tex == null || texOver == null) return;

        GUI.DrawTexture(texRect, tex);
        if (counter >= 1)
        {
            int tempTexHeight = (int)Mathf.Min(counter * texHeight / 100, 
                                               texHeight);
            texOverRect = new Rect(
                                   Screen.width - texWidth - 10,
                                   10 + texHeight - tempTexHeight,
                                   texWidth,
                                   tempTexHeight
                              );
            GUI.BeginGroup(texOverRect);
            GUI.DrawTexture(new Rect(
                                     0, 
                                     -(texHeight - tempTexHeight), 
                                     texWidth, 
                                     texHeight), 
                                     texOver, 
                                     ScaleMode.ScaleToFit
                                    );
            GUI.EndGroup();
        }
    }
}


Second and final DADIU production

Posted in Medialogy, Miscellaneous on April 4th, 2011 by Jacob

So, I’m finally home again, after finishing my second and final DADIU [dadiu.dk] production! And what better time to be back than the beginning of spring!

Just as last time, I acted as a programmer, and was part of creation of the game Branch [branchgame.com].
The game requires the Unity webplugin.

A short teaser video of the game story can be seeen here:

Another day, another Python script

Posted in Miscellaneous, Programming on January 3rd, 2011 by Jacob

So, I had a couple of hours today to play around.. and what did I do in that time? I decided to clean up my media server.

I store most of my movies ripped on a media server, as I’m waaay to lazy to find a DVD when I want to watch a movie. I am also too lazy to scan the cover and place it with the movie rip. So, every once in a while I stumble upon an old movie, and can’t really remember what it’s about.

So, I created a very simple script that look up the movie based on the folder name, as I keep a very clean “Name [Year]” structure on my folders. So, it was easy to create a simple script to look up the movie on IMDB [imdb.com] and create a url link in the folder.

The code can be seen below:


import sys, os
import urllib, urllib2

# Global variables
name = 'Watch movie details on IMDB'
_list = ['[InternetShortcut]', '']

def writeToFile(fulldir, name, _list):
    # Creates a file and saves it to .url,
    # creating an url shortcut to the webpage in _list
    f = open(fulldir + '\\' + name + '.url', 'w')
    for item in _list:
        f.write(item + '\n')
    f.close

def getURL(search):
    # Does a search using google feeling lucky, and returns the url of the hit
    query = 'http://www.google.com/search?btnI=745&q='
    # Header to spoof an old mozilla browser
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = { 'User-Agent' : user_agent }
    # Create the actual url and request to homepage from google
    url = query + search
    req = urllib2.Request(url, None, headers)
    response = urllib2.urlopen(req)
    the_page = response.read()
    if '.imdb.com' in the_page:
        #the_header = response.info()
        if '<link rel="canonical" href="' in the_page:
            result = the_page[the_page.find('<link rel="canonical" href="')+28:\
                              the_page.find('<link rel="canonical" href="')+80]
            result = result[:result.rfind('\"')]
            return result
        else:
            print 'IMDB site found, but could\'nt track URL'
    else:
        print 'The site returned was not IMDB.',
        print 'The link will not be saved for:', search
    #return result

def main():
    # Current Working Directory (sys.path[0] also works)
    #folder = os.getcwd() # Change this to do it in another folder
    folder = '\\\\DISKSTATION\\video'
    # Runs through all subfolders of current and prints their subfolders
    for curdir, direntries, fileentries in os.walk(folder):
        # Strips to only the folder name
        fulldir = curdir[:]
        curdir = curdir[curdir.rfind('\\')+1:]
        curdir = curdir.replace(' ', '%20')
        url = getURL(curdir)
        try:
            _list[1] = 'URL=' + url
            writeToFile(fulldir, name, _list)
            print "Success:", curdir.replace('%20', ' '), "(", _list[1], ")"
        except TypeError, e:
            print "Error concatenating list:", e
    print "Done!"

if __name__ == "__main__":
    main()

So, when I stumble upon an old movie I forgot I had, it’s easy to look it up :)
And, it is low-tech enough for me…

Annoyance of .gif in Windows 7

Posted in Miscellaneous, Programming on December 29th, 2010 by Jacob

So, I’ve been using Windows 7 for quite some time now, and are generally happy with it. But, for some reason Microsoft has redone their Photo Viewer, and it is no longer possible to view .gif files in it. I don’t know if this was an issue in Windows Vista, as I never used it.

So, instead of finding an alternative photo/image viewer, I wrote a small Python script that converts most image files into .jpg files, as I’m happy enough with Photo Viewer to want to be bothered by finding an alternative :)

Here’s the code for the script:


import Image, sys, os

def convert(infile):
    name, filetype = os.path.splitext(infile)
    outfile = name + ".jpg"
    try:
        im = Image.open(infile)
        if im.mode != "RGB":
            im = im.convert("RGB")
        im.save(outfile, "JPEG")
        print "Succesfully converted", infile, "to", outfile
    except IOError, e:
        print "Cannot convert", infile
        print "Error:", e

if __name__ == "__main__":
    for item in sys.argv[1:]:
        convert(item)
    sys.exit()

DADIU production took all my time!

Posted in Medialogy, Miscellaneous on June 1st, 2010 by Jacob

So, I guess it’s been a while since I posted anything here.

In the last week I’ve managed to hand in my semester project for this semester as well as finishing up the game I was part of the the DADIU [dadiu.dk] production. Yay! Almost time for a little vacation.. and enjoying the nice weather.

I was programmer on Team 1, and created the game Anton og Katastrofen (Anton and the Catastrophe) [antonogkatastrofen.dk].The game requires the Unity webplugin.

A short teaser video of the game can be seeen here:

The conditions for the game before production start was for it to be aimed at 3-7 year old kids, and only left mouse button was allowed as input to the game.

Getting started with Unity3D

Posted in Medialogy, Miscellaneous on March 16th, 2010 by Jacob

So, for this semester we are doing simulation, and doing a small game in Unity3D [unity3d.com]. So, we have begun digging around in Unity, and within a short time, we have created some mechanics that hopefully will develop into a small game :)

I must say I’m impressed with the ease of using Unity once you’re “used” to it. I won’t say I’ve gotten that much into it yet, but it is nice and easy to do a lot of stuff in there. And with the link to Visual Studio 2010 RC, it’s really easy to just throw away the IDE Unity comes with and code in Visual Studio (as long as the RC lasts anyway).

So, enough with me rambling on, and time to show a few pictures :)

First person view of the "game"

First person view of the "game"

The image shows the first person view of the “game”, with two planets and a bullet fired from a cannon. Both of the planets have gravity to draw the bullet to them, which is visualized from the trajectory of the bullet (in orange/red) as well as by the particle system.

Overview of the "game"

Overview of the "game"

The second image is an overview of the game. Don’t mind the aim texture, it’s currently in all cameras :). The particle system spawns on a large sphere and is dragged towards the planets to show their forces.

In a month or so, the game should be finished. For the time being, you can download the files if you want to play with it yourself. Link here.

Real-Time Shadows in Augmented Reality

Posted in Medialogy on March 3rd, 2010 by Jacob

This is the title on the semester project I did last semester (7th) as a Medialogy student.

The idea behind the semester project was to look into generating shadows for Augmented Reality, as we hadn’t seen shadows implemented in many frameworks for Augmented Reality.

We looked into creating projection shadows, shadow maps and shadow volumes for ARToolkit.

Simple example of shadows for Augmented Reality

Simple example of shadows for Augmented Reality

As the project evolved, we became more and more interested in updating the positions for the shadows in real time, so the shadows aren’t static. As the shadows themselves were not important for this, we implemented projected shadows (as they were the fastest to implement), and focussed on a way for finding light in the environment and create shadows based on this.

Based on prior research, we created a reflective sphere to collect light in the environment and used math to calculate an environment map of the scene.

Environment map created from the reflective sphere (painted black)

Environment map created from the reflective sphere (painted black)

From this, we used median cut [gl.ict.usc.edu] (which is usually used for HDR environment maps), and created light sources and direction based on this. From there it was just using OpenGL lights and our created projected shadows.

Image showing the light directions computed from the reflective sphere

Image showing the light directions computed from the reflective sphere

Image of the final implementation:

Final implementation. Showing a bed with multiple=

Final implementation. Showing a bed with multiple shadows.

The paper is available for download here [jbmadsen.com].

A video of the implementation has been uploaded to youtube and can be seen here [youtube.com].

Workshop: Environmental Response

Posted in Medialogy, Miscellaneous on March 1st, 2010 by Jacob

In the days from January 24th to 30th, I participated in a small workshop called “Environmental Response 2010″. The idea behind the project was to create installation art that could act on sensory input from the environment. It was a workshop for students of Medialogy and Architecture & Design.

The Environmental Response workshop, 2010

During the workshop my group created an installation that used sensory data to control multiple servos, created like a delta robot (link [Youtube.com]) using an Arduino as microcontroller (link [Arduino.cc]). On the Arduino a small state machine was written to control the behaviors of the system.

Diagram of the elements in the installation

The use of servos to control the system

Testing the light and material

A complete element, controlled by 3 servos

Getting the last wiring done.. getting ready to test :)

And some more wiring...

Link to the source code for the Arduino.

To see what the other groups created, visit the projects homepage [Wordpress.com].

Hello world!

Posted in Miscellaneous on March 1st, 2010 by Jacob

Yet another blog on the internet! Yay, and welcome!

This is a personal blog of hobbies and interests of mine. I’m a MSc. student at Aalborg University, studying Medialogy. This will a place to collect my thoughts and share them with everyone who might find that interesting. :)

Happy reading…