24 entries in 2008

Comment Headings

Enable easy navigation of code using GIANT comments made up of block characters

Friday, November 14th, 2008

When navigating through large classes, it can be a real pain to find certain bits of code if you don't have a good IDE. As I often work in Flash IDE and DreamWeaver IDE, I have to rely on comment blocks here and there, with lots of - - - - - - - - - - delimiters, etc. which is an OK start.

However, I saw the PaperVision 3D classes had moved on a step from this, and had rather nice blocks at the top of each script with their logo, made out of characters. Why not extend this idea and actually build a small Flash application to let me build dirty-great big words that I can use in my scripts for navigation purposes?

Comment Headings

Edit the text in the left-hand text box to update the text in the right, then click Copy Text to copy the headings directly to the clipboard so you can paste to your IDE.

Note:Comment Headings works only with mono-spaced fonts! Mac users - you might have to experiment to find the best one.

Firefox 3 users: due to FF3's mono-spaced font tracking, the characters below may not display correctly, but rest-assured that in the final downloadable utility, and your IDE, the headings will appear just fine.

Demonstration

To demonstrate the differences between a comment-headered file and a normal file, compare the following two files, and see how much easier it is to skim through the one with larger comment headings.

Options

The following options are available to customize your headings:

  • Font - Choose from 12 available fonts of varying sizes and styles
  • Block - Various characters to create the block comments themselves
  • Comment - Various leading-comment styles to suit different languages
  • Delimiter - Various delimiter characters for the

Presets

If you change programming languages / tasks regularly, you can save time by storing oft-used combinations as presets. For example:

  • Input presets - Your most common heading text combinations
  • Output presets - Your most common settings for each language / editor / etc

Presets can be quickly called up by selecting them from the dropdown lists, which automatically updates related dropdowns as well as the output text.

Both Input Templates and Output Settings are stored in an editable text file, presets.xml, which is well-commented, allowing you to add or delete settings to suit your workflow.

To have the utility start with your chosen presets, for example having the MaxScript headings always open, just ensure its entry is first in the input list.

Customization

Once tinkering in the presets file, the following elements are configurable:

  • Comments - Choose the leading comments (//, --, etc) according to programming language
  • Blocks - Choose which characters you want to physically build the words from
  • Delimiters - Choose which characters you want to use to delineate each comment block
  • Fonts - Choose from any of 12 fonts to be available

3dsmax users

In order to display the full-block style of comments, you will need to set up the SCiTE editor to use the extended Unicode character set. To do so, you will need to add the following lines to your User Preferences file:

code.page = 65001
character.set = 204

Obviously this is only applicable if you are using 3dsmax 2008 or above.

Download

Kohana: Default controller for serving static pages

Save development time by routing un-routable content to default views

Thursday, September 11th, 2008

A brief overview of the problem

A framework such as Kohana is really useful when serving lots of dynamic pages, as it allows you organise both your thoughts and your code into folders, creating order from what could potentially be chaos, at the expense of having to adhere to a structured way of working, in this case setting up controllers and methods that are correctly mapped from URLs (routes).

Whilst this is necessary for dynamic pages that need access to models, helpers and such like, for static pages that literally just need to be output to the browser, it's quite a lot of overhead, and your controllers can very quickly end up bloated with itty-bitty "view this page" methods.

What would be great would be some magic method to automatically handle static pages, without having to set up an actual controller and method, that way all you really need to create is the view file, and you leave your controllers folder nice and lean.

Note: this tutorial is for Kohana 2.2. I haven't investigated how it will work with 2.3 and the routing yet. Please comment if you have something to add!

The Fallback controller

The solution is using a default or "fallback" controller that takes care of serving views from routes that don't map to an existing controller and method.

Essentially, this new controller kicks in just after the routing has drawn a blank, locates the appropriate view file, then serves it - instead of serving a 404 page.

Step-by-step

Let's a take a look at how this works in a step-by-step approach from Kohana's perspective. Don't worry - it's actually pretty simple, I've just mapped it out specifically so you can see what's happening every step of the way.

Let's start with a route

  • The user navigates to a route, lets say /about/company/history
  • Kohana looks for
    • an about controller, with
    • a company method, and intends to supply it with
    • a history argument

Here's the thing though, because we did't want the hassle of setting up ALL our controllers with methods just to load views, our about controller doesn't have a company method! So what is Kohana to do?

Let's load the Fallback Controller!
Well, normally, a 404 page would be served, but using the magic of hooks, we're going to give Kohana one last chance to do something before serving that horrid 404 page.

So:

  • The system.post_routing hook kicks in, and due to the way we've set up the hook file
  • It loads our Fallback controller, which is designed to do something useful with the route before bombing out.

Let's have the Fallback Controller do it's stuff and find the view!
In this case, we want it to attempt to find a view, so:

  • The Fallback controller builds a path from the arguments /about that will (hopefully) map to a view, in this case views/main/about.php, then
  • Attempts to find this view using Kohana::find_file, and
    • if found - loads the view!
    • if not found - serves the 404 page

Summary

Pretty useful, huh? Basically all that happened is

  • Kohana couldn't find a controller, so loaded a Fallback controller
  • The fallback controller took the route and found a view
  • Kohana loads the view (or the 404 page if the view didn't exist)

OK, perhaps it's time to look at some code

Code

You will need to create or edit code in 3 separate places:

  1. Enable hooks in your application's configuration file
  2. Create a hook file which tells Kohana what to do in the system.post_routing event
  3. Create the actual Fallback Controller that will do the finding and loading of your view files

.

application/config/config.php - Enable hooks in the main config file...

$config['enable_hooks'] = TRUE;

.

application/hooks/fallback_page.php - Add a hook file to the hooks directory...

Event::add('system.post_routing' ,'call_fallback_page');

function call_fallback_page()
{
    if (Router::$controller === NULL)
    {
        Router::$controller = 'fallback_page';
        Router::$arguments = Router::$segments;
        Router::$controller_path = APPPATH.'controllers/fallback_page.php';
    }
}

.

application/controllers/fallback_page.php - Set up a controller to do the business

class Fallback_Page_Controller extends Page_Controller // page controller is my standard page template
{

    public function __construct()
    {

    // the constructor can be omitted if you're not doing anything special,
    // as the parent constructor it is called automatically
        parent::__construct();
    }

    public function __call($function, $arguments)
    {

    // search for a view, and load it if it exists
    // it's up to you how you handle the mapping of arguments to folders here!
        $route =  implode('/', $arguments);
        if(Kohana::find_file('views/main', $route))
        {
            $this->template->content = new View('main/'.$route);
        }

    // display alternative content if not found
        else
        {
            $view = new View('common/404');
            $view->info = array($function, $arguments);
            $this->template->content = $view;
        }
    }

}

Conculsion

So now you should be able to set up a bunch of views, but needn't worry about building controllers for them if nothing exciting is happening.

The fallback controller will run, will attempt to find a matching view, and if found, will echo it the page. The main thing is - it keeps your controllers folder and classes nice and lean, and you only need to build controllers that actually DO any controlling!

Nice.

Kohana ‘filesystem’ Helper

A robust helper to handle everything file and folder-related within Kohana

Wednesday, August 20th, 2008

Kohana is just an excellent framework to work with, but one of my beefs is that the structure of its bundled libraries and helpers is a little haphazard, missing basic functions you'd expect to find in the core (so you can rely on them when writing modules) omitted!

For this reason, here's my attempt at a more integrated helper class. It's somewhat of a Frankenstein's monster with bits borrowed from Code Igniter, and my own code thrown in as well. Apart from this, it:

  • Adds a few new methods
  • Improves on some existing methods
  • Combines the 'download' helper functionality
  • Tidies up various method calls

The methods are:

  • map()
  • get_folders()
  • get_files()
  • delete_files()
  • read_file()
  • write_file()
  • make_path()
  • download()

Download filesystem.php here.

(more...)

I love CodeIgniter!

A brief introduction to the wonderful PHP CodeIgniter framework

Monday, June 30th, 2008

I don't normally write a post unless I'm specifically publishing code, but I wanted to write a brief post about Code Igniter as it's the best damn thing I've discovered since jQuery!

Overview

If you haven't heard of it already, CodeIgniter is a rapid application-development framework for PHP that uses the Model-View-Controller pattern to separate the presentation, logic and data from each other whilst building your web application.

What this means in practice is that instead of building one large linear PHP file that...

  1. Contains swathes of PHP in the head to filter user input (logic), then
  2. Gets results from a database (data) and does something meaningful with them, then finally
  3. Outputs the HTML (presentation) and continues to escape in and out of PHP during the process

...you end up working on many different smaller files that do one task only, with which the framework pieces together for you to deliver finished web pages.

However, before I delve into MVC, I want to touch upon CodeIgniters excellent class library.

A excellent and fully-integrated set of Library classes

The primary reason I started using CodeIgniter in the first place, is that it provides an incredibly robust and integrated set of classes to handle everything web-app related, from database classes, to session classes, to file uploading and email.

Had it not been for the fact that you have to use them within the overall CodeIgniter structure, I may well have gone off and carried on the way I was going, with logic at the top of my pages, and presentation at the bottom.

However, in order to actually use them, you have to accept you'll start coding within the CodeIgniter framework, and things will never be the same again...

An intelligent and modular approach to building web applications

The vast majority of what you do within CodeIgniter will be written within class files, that will fall under one of the three MVC areas:

  1. Controllers - classes responsible for making overall decisions, such as deciding what task is being undertaken in response to user-input, as well as loading supporting classes and logic to get the job done. Controllers are the first step in processing a task, and outputting a web page.

    It helps to think of controllers and their methods as the "folder" and "page" structure of a site. For example a "Home Controller" might have an "index" function would handle loading the home page, whilst a "Messaging Controller" and might have a "List" and "Compose" methods would handle listing messages, composing new messages, etc.

    Both these methods would take high-level decisions about the task in hand, offloading the drudgery of the tasks to other elements, such as...

  2. Models - classes responsible for everything "data" related, such as read and writing from databases, storing representations of said data, configuration, etc.

    In practice, what this means is that a Controller would never read or write data directly, it would hand all responsibility for that to a Model, and would just make calls such as "get the last 10 unread messages". The model would do the grunt-work, leaving the Controller to get on with more important things.

  3. Views - static or dynamic files that are read by CodeIgniter, populated with data, and are output to the user. Views are analogous with the final page output you'd see in procedural PHP programming.

    A view file need not be an entire web page, it could just be a segment, such as a sidebar, a form, a graph, a header, or a footer. By combining views, you have a lot of power with regards to the output of the final page, as well as a really flexible way to store individual representations of data.

    For example, depending on user input, you could load either a Table View or a Graph View that would be populated by the Model data. Inside the view you'd have written code that would receive Model data and would know what to do with it.

The benefit of this approach is that it's much easier and quicker to build and maintain your site, as everything's modular, and can be loaded and swapped out according to the task at hand (and no more huge sprawling pages).

There aren't really that many downsides to this approach, but it can be a little tricky sometimes, as due to the way CodeIgniter works behind teh scenes, you don't work with a traditional one-to-one file / page structure, but once you're used to it, you'll never want to go back.

“List” struct

Easily create associative array-like structures in 3dsmax

Friday, June 6th, 2008

As 3dsmax doesn't allow for either associative arrays or dynamically-set object properties, it can be difficult to store unstructured, arbitrary variables.

Sometimes you just want to store lists of name/value pairs, to keep track of a few settings throughout your script, without relying on a host of variables, resorting to .ini files, or custom attributes.

Therefore, I set about writing a basic Dictionary, or List struct, similar to VB and other languages.

Example code

Here's a really basic example of storing 5 named variables within a List:

names = #("five", "four", "three", "two", "one")
values = #(5,4,3,2,1)
lst = List()

for i = 1 to 5 do lst.addItem names[i] values[i]

So let's get some data back out:

lst.getValue "two"
-- 2

lst.getIndex "two"
-- 4

lst.getValues()
-- #(5, 4, 3, 2, 1)

Or print the whole lot:

lst.print() -- unsorted

five:	5
four:	4
three:	3
two:	2
one:	1

How about some sorting:

lst.sort() -- by name, alphabetically

five:	5
four:	4
one:	1
three:	3
two:	2

lst.sort field:#value -- by value

one:	1
two:	2
three:	3
four:	4
five:	5

As you can see, it's pretty straightforward stuff!

Properties and Methods

Properties

  • <array> items <name> <value> - the key/value pairs.
    • Names can be a #name, "string", or even an index
    • Values can be any MaxWrapper value (i.e. anything)

Setters

  • <ListItem> addItem <name> <value> - adds an item to the List, and if it already exists
  • <ListItem> setItem <name> <value> - synonym for the above

Getters

  • <value> getValue <name> - returns the value of the named item
  • <index> getIndex <name> - returns the index of the named item
  • <name> getName <value> - returns the name of the first item that matches the supplied value
  • <ListItem> getItem <name> - returns the List item corresponding to the supplied name (typically, you wouldn't use this, as you know the name component already, it's just included for completeness)
  • <array> getItems() - returns all items as an array of ListItem structs
  • <array> getNames() - returns all names as an array
  • <array> getValues() - returns all values as an array

Clear or delete

  • <array> clear() - clears the lit of all items, and returns the empty ListItems array
  • <boolean> deleteItem <name> - deletes the named item from the list, and returns it
  • <boolean> deleteIndex <index> - deletes the item at the index, and returns it

Utilities

  • <array> sort field:<name> order:<name> func:<function> - sorts the list in a variety of ways, even supply a comparison function (see the max help on qsort)
  • <string> print() - prints the List items to the Listener

Next version

Possible improvements in the next version might be:

  • .ini file integration, with save() and load() methods
  • Support for hierarchical Lists, perhaps getValue #(#parent, #child, #grandchild, ...)

Download

Download List.struct.ms here.

Time Stamper - Meshops.attach() Case Study

Monday, May 26th, 2008

Overview

In response to a post on CG Talk, Optimization ideas needed, a few other developers and I us pitched in to help out with ideas to solve a puzzling problem.

The issue was that a loop to attach 7500 objects was taking up to 8 minutes to complete. Where did the problem lie? Was it in the transformation code, the attachment code, or somewhere else?

Well as luck would have it, today's Bank Holiday has been totally washed out with rain, so I had nothing better to than to do some testing and find the cause, and in the process road test my recently-developed TimeStamper struct.

Approach

After turning undo and redraw off, as well as optimizing the transformation code within the script, which cut a 1000-object test scene's processing time in half, surprisingly the 7500-object scene was still taking around 8 minutes.

I suspected that the problem may well be in the fact that as mesh gets larger, perhaps it becomes computationally more expensive to add new meshes, seeing as the entire array of points and faces needs to be evaluated every time a new mesh is added. Cumulatively, this could really add up.

I though that perhaps the right approach would be to split the attaching up into phases, using a 2D loop, and I suspected that perhaps the square-root of the total attaches might yield the optimal performance, ie for 10000 attaches I'd perform a 100 x 100 loop, creating 100 intermediate meshes, then attaching them all at the end.

Results

These are the results for various variations of 2D loops, limiting the amount of objects attached per loop. The results are impressive!

  • For 1000 objects, the optimum loop combination was 31 loops of 32, a speed increase of 12 times over a single loop
  • For 3000 objects, the optimum loop combination was 55 loops of 54, a speed increase of 22 times over a single loop
  • For 5000 objects, the optimum loop combination was 50 loops of 100, a speed increase of 28 times over a single loop
  • For 7500 objects, the optimum loop combination was 87 loops of 86, a speed increase of 30 times over a single loop

And yes, the square root approach was most successful 3 out of 4 times.

Here are the results in table format, with the optimum loop highlighted:

1D / 2D loop comparison

Compared to the 1D loop, the 2D loop was 30 times faster on 7500 attachments.

In minutes and seconds, that means a decrease from 6 minutes and 29 seconds to just 12 seconds!

In graph-form that looks like this:

Conclusion

It seems pretty safe to say that in this case, building up intermediate meshes and attaching at the end is the best way to go. It looks likely that adding to already-huge arrays carries with it an overhead that can have an extremely negative effect in a lengthy loop situation.

I've no doubt that this approach most likely extends to other mesh / array / hash based computations as well, so splitting up large cumulatively-expensive calculations into smaller chunks could well be a great time-saver in other tasks as well.

So - a shame about the rain, but perhaps a bonus in disguise!

Resources

Transform Presets

Save and restore transformations as presets to objects such as cameras, IK handles, etc.

Saturday, May 17th, 2008

Transform Presets is a pretty simple plugin - it allows you to store multiple transformations of an object (and it's target, if there is one) in a list, to call up when you like.

You apply it to any object, and it adds a custom rollout to the base object, with a small interface that you can use when the object is selected.

I built it for fun in response to a thread on CGTalk.

Screenshots

Here it is working on a target camera. Note both the camera and target are transformed.

And here it is working with an IK handle. Note the swivel angle is updated as well as the transform.

Download and installation

Download TransformPresets.mzp and then drag the .mzp file onto one of your 3dsmax viewports, which will install the script in the correct directory. Then you can add the script to a toolbar / quad by going to:

  • Customize > Customize User Interface…
  • Then look under the Animation Tools category for Transform Presets

Towards an optimal method of quoting - Dom’s response

Thursday, May 15th, 2008

Hi DJ

Well done to you for tackling this one, is the hardest part of this design lark for sure

After reading everyones comments here I am glad I choose to avoid print and web design. Animation is easier as you dont have to quantify exact details to your client, you dont usually have to work with complicated file structures as you would with someone’s company branding/website.

To be quick, I just spend as much time as possible in a one to one basis trying to uncover the clients aspirations for the product, I then give them some reality of costs using other projects they will know as case studies. After this they usually understand cost vs 'quality'. If they understand these factors its easy to manage the project from then in.

I think having T&C’s are important in quotes but mainly to protect you from a muppet client. If you have 'managed' the client well you shouldn't need T&C’s too much.

I am trying to build a business that services clients' long term needs, that way I avoid pissing matches with details/arguments as we build a relationship of trust with clients who then get out of the loop THUS saving eveyone money.. i hope

Dom

Towards an optimal method of quoting - Matt’s response

Thursday, May 15th, 2008

Hi Dave.

Loads of thoughts on this subject.

Will write them up for you when I have a sec.

Good instigation.

In the meantime, we generally find that no matter how hard we try http://en.wikipedia.org/wiki/Hofstadter's_Law is always right...

Cheers.

M

Towards an optimal method of quoting - Zac’s response

Thursday, May 15th, 2008

Hi Dave,

Ok i'm afraid i've gone down the road of quoting for the perfect job.

Recently I quoted for a charity rebrand where I estimated the time for the logo to be x amount - this was 4 concepts and 1 concept to be carried across into the final design. All was well until they kept changing their mind (as clients do). When they were satisified with the logo they said "now we just need to show it to the board'!!

As you can tell the amount of extra time I have had to put into the project is ridiculous. Once they showed the board they chose one of the designs and they got back to me the next day saying the design was too similar to another charity logo!

So i'm still re-working the logo and the client is getting more and more frustrated. But i've stated that anything that goes over the given timescale is chargeable x per hour. If they had told me upfront that the design had to go through the board then I would have factored more time in....it's probably my fault for not asking!

 

Here is a list of things that I have learnt from larger design projects:

  • Create a document with given timescales and an initial fixed value. Break the project up into smaller chunks. i.e. Concept Stage, Implementation and Programming
  • Charge the client 50% upfront and 50% on completion of the project OR into 3 stages and everything has to be signed off and invoiced at each stage
  • Create a T&Cs document for both parties to sign this includes cancellation and termination of project.
  • Regularly update the client with how much extra work you're carrying out and cost so they don't get a shock at the end of the project

I've also said to clients that within the quote x amount of days for changes. The 'rounds of changes' has never really worked for me, my clients find this too restricting.

 

I have a client who is spot on with organising everything from the start. Word documents, images in alphabetical order etc etc. so I quote her less because the project is quicker to finish. With some clients you just know that the project is going to take longer because they are wishy washy, they faff about and they keep changing their mind.

The worst one for me is text changes and typos. I get so frustrated with really small changes which end up taking forever. It's really difficult to know exactly how much time to factor within the quote for these kind of things because these small changes end up being time consuming.

Unforseen - extra meetings. Sometimes I put in the quote 'meetings not included' within the quote so they are charged separately, I add travel on to this as well.

I think that's all for now,

Zac