<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>More of a programming nerd than is strictly healthy. See also {nevyn.nu, thirdcog.eu, twitter}</description><title>Overooped</title><generator>Tumblr (3.0; @nevyn)</generator><link>http://overooped.com/</link><item><title>VoidStar game engine with the game VoidBomb. First year project...</title><description>&lt;img src="http://28.media.tumblr.com/MLhBbCcsblqm0momthXjENmgo1_500.png"/&gt;&lt;br/&gt;&lt;br/&gt;&lt;p&gt;VoidStar game engine with the game VoidBomb. First year project in Game Programming at BTH by me, voxar, sterd and mangeh. Conversation with Per brought it up, and I just had to make it compile again :)&lt;/p&gt;

&lt;p&gt;The objective of the game is to drop bombs to blow up the ground (modifiable heightmap!) to find the flag.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://nevyn.nu/files/VoidStar.zip"&gt;Download for Mac&lt;/a&gt;, &lt;a href="svn://nevyn.nu/school/trunk/stervymangxar"&gt;Source code repository&lt;/a&gt;&lt;/p&gt;

&lt;p&gt; What’s interesting about this project is that it’s the origin for my favorite game engine design, and the same designed used in Deathtroid. There is only one Entity class, so instead of using inheritance to create different kinds of entities, one builds an Entity from Elements, one for each sub-engine. For example, to create the avatar in Deathtroid, we initialize an Entity with a ForceBasedPhysics element for the physics slot, an AvatarBehavior bound to the correct Player for the logics slot, and StateAnimatedSprite for the view slot.&lt;/p&gt;

&lt;em&gt;Update: Forgot to bundle dependencies. Try it again if it failed for you before.&lt;/em&gt;</description><link>http://overooped.com/post/91662612</link><guid>http://overooped.com/post/91662612</guid><pubDate>Tue, 31 Mar 2009 22:52:00 +0200</pubDate><category>coding</category><category>gamedev</category><category>engine-design</category><category>voidstar</category></item><item><title>Mutable Adventure, Pedro and Erlang Text Processing</title><description>&lt;p&gt;As some of you might know, I’m currently writing a game called Mutable Adventure, a 2D sidescrolling platformer MMOG with the editability of Second Life.
&lt;/p&gt;
&lt;p&gt;The thing about Mutable that interests me the most, however, is the networking. I’m using a library/protocol called &lt;a href="http://www.itee.uq.edu.au/~pjr/HomePages/PedroHome.html" title="Pedro Home"&gt;Pedro&lt;/a&gt;, by &lt;a href="http://www.itee.uq.edu.au/~pjr/" title="Peter Robinson"&gt;Peter Robinson&lt;/a&gt;, which I found when &lt;a href="http://en.wikipedia.org/wiki/Keith_Clark" title="Keith Clark - Wikipedia, the free encyclopedia"&gt;Keith Clark&lt;/a&gt; presented it at &lt;a href="http://bth.se/" title="Blekinge Tekniska Högskola, BTH"&gt;work&lt;/a&gt;. Before I go on, I need to explain why this protocol is so goddamned cool.
&lt;/p&gt;
&lt;h3&gt;Pedro and software agents&lt;/h3&gt;
&lt;p&gt;It’s based on Prolog, more specifically, his own implementation of QuProlog. It’s sort of a blackboard system, with a central messaging server that everyone connects to. It’s string-based, and what you send over the network are prolog fact-style messages, called a notification, for example:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;
  playerWasHit(152, 12388)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is then broadcasted to everyone to subscribe to this message. A subscription might look like this:
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;
  playerWasHit(PlayerID, ObjectID), PlayerID = 152
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that the expression contains Prolog variables, and a guard expression. This means that several clients may subscribe to the same notification, but with a guard expression that says they only want player info about their own player.
&lt;/p&gt;

&lt;p&gt;Each subscription is accompanied by a number, so that you on the client side can redirect the incoming notification to the right place. In Python I’ve implemented this so that individual objects may subscribe, and that individual objects may receive notifications. For example, say a ball is spawned in the game world. At the instance it’s instansiated, it may subscribe to information &lt;em&gt;pertaining to this specific instance&lt;/em&gt;, by giving the subscription a guard expression with its own ID number. Boom, automatic network message propagation within your game client or server. As an example, in the client, the Tilemap class is appended with a category/mixin with the following code (notice the third argument, the guard):
&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;
  gClient.net.subscribe(self, "tilemap(TilemapName, NameOfTilesetTilemapUses, ScrollX, ScrollY, AutoScrollX, AutoScrollY)", 
                              "TilemapName = \"%s\""%self.name)
  gClient.net.subscribe(self, "tileInMap(TilemapName, TileX, TileY, TileIndexInRoomTileset)",
                              "TilemapName = \"%s\""%self.name)
  gClient.net.subscribe(self, "tilesInMap(TilemapName, FromIndex, ToIndex, TileIndexArray)",
                              "TilemapName = \"%s\""%self.name)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(&lt;a href="http://blog.voxar.net/" title="Voxar"&gt;Voxar&lt;/a&gt; has &lt;a href="http://dl.getdropbox.com/u/47446/pedronet.py" title=""&gt;significantly improved the syntax in the Pedro python wrapper&lt;/a&gt; since then)
&lt;/p&gt;

&lt;p&gt;Suddenly, your objects aren’t mere objects; because they can communicate on their own with the outside world, and respond on their own, they’re now &lt;a href="http://en.wikipedia.org/wiki/Software_agent" title="Software agent - Wikipedia, the free encyclopedia"&gt;software agents&lt;/a&gt;. Also, because the messaging medium is now separate from the server instance, your game server may now be freely split as you see fit into several processes, both for load balancing and for division of labor into discrete entities, with higher cohesion and lower coupling.
&lt;/p&gt;
&lt;h3&gt;The downside&lt;/h3&gt;
&lt;p&gt;Peter Robinson’s implementation of this concept isn’t perfect, however. First off, it’s written in plain c, &lt;em&gt;and&lt;/em&gt; it depends on glib2. GObjects. I can’t stand GObjects. I can’t stand manual memory management. And it’s 5000 lines of code for a relatively simple concept.
&lt;/p&gt;
&lt;p&gt;Secondly, you just traded yourself simplicity for the price of a single bottleneck. A buggy, unstable, memory leaking single bottleneck with no means of load balancing or distribution. Written in C with a single maintainer, based on glib2 which is pretty hard to get running under Windows, if you would want to.
&lt;/p&gt;
&lt;p&gt;(I attended a 24 hour game development challenge a while back, where I wrote a networked 3D racer. Because I couldn’t get pedro running under Windows, I had to run it on my own server at home, while the judges tested the game from the other side of the country. &gt;1sec lag and no lag compensation or similar whatsoever in the code = I certainly didn’t win that competition :( )
&lt;/p&gt;

&lt;h3&gt;Erlang, The Savior&lt;/h3&gt;
&lt;p&gt;After reading &lt;a href="http://armstrongonsoftware.blogspot.com/" title="armstrong on software"&gt;Joe Armstrong&lt;/a&gt;’s &lt;a href="http://amazon.com/dp/193435600X" title="Amazon.com: Programming Erlang: Software for a Concurrent World: Joe Armstrong: Books"&gt;book on Erlang&lt;/a&gt;, I was itching to write something. I tried writing a Twitter clone, thinking that Erlang’s highly distributed nature would come to great use there, but every line took a minute to write (because I’m so new to Erlang), and Twitter just felt too big and too difficult to write as a first project, so that got abandoned.
&lt;/p&gt;
&lt;p&gt;So, the next thing I’m trying is to write a Pedro clone in Erlang. It’s a good match, since the hardest part of of Pedro is the pattern matching, and Erlang got that as a part of being a functional programming language. I’ve set out to get it to work in 100 lines or less. So far I’m up to 60 lines, and I think I have a chance of making it.
&lt;/p&gt;
&lt;p&gt;In Erlang, processes are cheap and abundant. You spawn a lot of processes and then do all communication through erlang messaging. A common pattern is the middle man pattern. While cleaning the dishes I remembered this pattern, from its usage in an IRC client built in the book, and tried to apply it to Erdro (Erlang Pedro :P) conceptually in my head (Sorry, the following is a bit hazy as 1) I haven’t implemented it yet 2) it contains a lot of erlang terms). One problem with Erdro is that in its current implementation, even if you have a supervisor process watching the server and respawning if it does, restoring all the stack state, the process would be dead and the sockets meaningless, and all clients would have been lost and restring state would be pointless. However, if each client is abstracted away with a middle man process (meaning all socket communication goes to and from a separate process, and communication with the server is handled through erlang messages), you could store all the state including process pointers to these middle men  in a mnesia database or similar, and if the server dies, respawn the server and its state and everything you’d have lost was a single message (the one that made the server crash); all socket connections would be alive and all clients just continue communicating.
&lt;/p&gt;
&lt;p&gt;Put the middle men on a cluster of machines away from the messaging server, each with its own IP and bandwidth, and you’ve distributed your network load. The machine containing the messaging server could self-immolate, still only a single message would be lost (given that there is another computer that could act as messaging server).
&lt;/p&gt;
&lt;p&gt;Process load balancing of the server, however, is left as an exercise for the reader.
&lt;/p&gt;
&lt;h3&gt;The nitty gritty details of text processing in Erlang&lt;/h3&gt;
&lt;p&gt;There’s a slight mismatch between Erlang and Prolog, given that they’re completely different languages (one is functional, the other is logical). In the context of Pedro, however, I could only think of a single difference that mattered, and had to be changed.
&lt;/p&gt;
&lt;p&gt;In Prolog, the term “myFunctor(atom, anotherAtom)” defines a fact. In Erlang, it’s a function call. So, for this to work, I’d have to convert that term to something equivalent that could be used in Erlang pattern matching: a tuple, like so, “{myFunctor, atom, anotherAtom}”. Since Pedro doesn’t have tuples, the transformation is reversible and fully equivalent (I hope! It’s not like I’ve tested my code yet…). How would &lt;em&gt;you&lt;/em&gt; do this? The first thing on my mind, being a ruby coder, was regular expressions. My first realization was the erlang’s regexp support is really, really, really horrible. Not only is it slow, its syntax support is so basic you might as well do without. My second realization was that regular expressions were a really bad match for the task at hand anyway. So my first real piece of Erlang code was a text search-and-replace implementation with pattern matching specific to my task:
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
functor_to_struct(PrologString) -&gt;
  [First|Rest] = PrologString,
  fts("", [First], Rest, false, 0).

fts(BeforeFunctor, Functor, [], _, _) -&gt;
    BeforeFunctor++Functor;
fts(BeforeFunctor, Functor, Rest, InStringEscapeMode, Prev) -&gt;
  [Next|Rest2] = Rest,
  case Next of
    34 when (Prev == $\\) and InStringEscapeMode -&gt; % \"
      fts(BeforeFunctor++[34], "", Rest2, true, Next);
    34 -&gt; % "
        fts(BeforeFunctor++[34], "", Rest2, not InStringEscapeMode, Next);
    Char when InStringEscapeMode -&gt;
      fts(BeforeFunctor++[Char], "", Rest2, true, Next);

    $( -&gt;
      fts(BeforeFunctor++"{++Functor++", " , "", Rest2, false, Next);
    $) -&gt;
      fts(BeforeFunctor++Functor++"}", "", Rest2, false, Next);
    Char when ((Char &gt;= $a) and (Char == $A) and (Char == $0) and (Char =
      fts(BeforeFunctor, Functor++[Char], Rest2, false, Next);
    Char -&gt;
      fts(BeforeFunctor++Functor++[Char], "", Rest2, false, Next)
  end.
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Half-way through the code, it felt so horrible, I felt like I was writing the worst code in the universe. Now that it’s done, though, I find it pretty nice. It’s relatively short for what it accomplishes (replaces function calls with tuples, being careful not to interpret parens inside a quoted string) imo. However, after a good night’s sleep, I realized that this was a really stupid way of doing it. Why? Because Erlang has a code parser in its standard library.
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  {ok, Scanned, _} = erl_scan:string("foo(bar)."),
  {ok, Parsed} = erl_parse:parse_exprs(Scanned)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;yields &lt;code&gt;[{call,1,{atom,1,foo},[{atom,1,bar}]}]&lt;/code&gt;, a perfectly fine nested Erlang data structure that can be traversed and parsed. So that’s what I did!
&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;
  transform_calls_to_tuples(ParseTree) -&gt;
    tctt(ParseTree, []).

  tctt([], Collected) -&gt;
    lists:reverse(Collected);
  tctt([Token|Rest], Collected) when element(1, Token) == call -&gt;
    {call, 1, FunctorNameAtom, ArgumentList} = Token,
    tctt(Rest, [{tuple, 1, [FunctorNameAtom | tctt(ArgumentList, [])]} | Collected]);
  tctt([Token|Rest], Collected) -&gt;
    tctt(Rest, [Token|Collected]).
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;… which yields the same result, but in a parse tree (which you can turn into a string again with erl_pp, the pretty printer).
&lt;/p&gt;
&lt;p&gt;That’s it! I’ll get back to you when Erdro is done.
&lt;/p&gt;</description><link>http://overooped.com/post/44978605</link><guid>http://overooped.com/post/44978605</guid><pubDate>Wed, 06 Aug 2008 22:02:00 +0200</pubDate><category>faves</category><category>gamedev</category><category>coding</category></item><item><title>Properly bundling .frameworks in your application package</title><description>&lt;p&gt;&lt;b&gt;Update&lt;/b&gt;: &lt;a href="http://overooped.com/post/87887322/use-rpath-instead-of-loader-path-or-executable-path"&gt;My blog post on @rpath&lt;/a&gt; supersedes/complements this post (it’s not finished yet, though).&lt;/p&gt;
&lt;br/&gt;&lt;br/&gt;&lt;p&gt;I’m sure you’ve run into it. You build your app and it works fine, but when you distribute it, your users get:&lt;/p&gt;
&lt;code&gt;&lt;pre&gt;
Library not loaded: /Users/Richard/Library/Frameworks/libmng.framework/Versions/A/libmng
  Referenced from: /Users/nevyn/Downloads/Sphere-Mac RC3/SphereEngine.app/Contents/MacOS/SphereEngine
  Reason: image not found
&lt;/pre&gt;&lt;/code&gt;

&lt;p&gt;One more time. This subject seems to pop up quite often, but I think I’ve finally gotten it nailed. Before I used to fetch the sources of all the libraries I was using, set up an .xcodeproj and set install_name to “@executable_path/../Frameworks/” (&lt;a href="http://thirdcog.eu/apps/frameworks"&gt;and that I did here&lt;/a&gt;). That’s not really necessary, and not possible for non-open source frameworks. So, no matter what framework or library you have, this is how you bundle it anyway, no matter what the install_name is.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Add an extra Copy Files target action in your XCode project (and rename it Copy Frameworks)&lt;/li&gt;
&lt;li&gt;Get info on the new terget action, and set its destination to Frameworks.&lt;/li&gt;
&lt;li&gt;Then, drag all custom frameworks to this target action, and they will be automatically bundled with the application when you build.&lt;/li&gt;
&lt;li&gt;You will now need to gather some information. Run `otool -L on YourApp.app/Contents/MacOS/YourApp` and note its output for each of the lines corresponding to a framework you just bundled.&lt;/li&gt;
&lt;li&gt;Next, add a Shell Script target action. This target action will call the install_name_tool to rewrite the linking information in the built binary to reference the bundled frameworks instead, even if the frameworks haven’t been built with an install_name of @executable_path/../Frameworks. Copy and modify as appropriate:
&lt;/li&gt;
&lt;/ol&gt;
&lt;code&gt;&lt;pre&gt;
function relocateLibraryInCurrentApp() {
  install_name_tool -change $1$2 @executable_path/../Frameworks/$2 $CONFIGURATION_BUILD_DIR/$EXECUTABLE_PATH
}

relocateLibraryInCurrentApp /usr/local/lib/ libfmodex.dylib #note the space
relocateLibraryInCurrentApp /Library/Frameworks/ Foobar.framework/Versions/A/Foobar #note the space
&lt;/pre&gt;&lt;/code&gt;

Note the two different styles for a loose dylib and for a .framework. Just add one relocateLibraryInCurrentApp for each library or framework you’re bundling. Good luck!


&lt;p&gt;&lt;br/&gt;&lt;b&gt;Addendum&lt;/b&gt;: I realized that making a post that just describes how to do something, not why, is kind of lame.&lt;/p&gt;

&lt;p&gt;In Mac OS, each binary contains a list of paths to binaries which it was linked to and which need to be loaded for all code to be available. When you launch an app, the runtime will thus load the app’s code, and for each library it needs to find will try to load it from the path set in the app’s binary. (For frameworks it’ll also look in /System/Library/Frameworks and /Library/Frameworks). What install_name_tool does is simply to rewrite that path inside the binary given as the fourth argument, searching exactly for the string argument #2, and change it to argument #3.&lt;/p&gt;

&lt;p&gt;Additional resources:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://qin.laya.com/tech_coding_help/dylib_linking.html"&gt;&lt;a href="http://qin.laya.com/tech_coding_help/dylib_linking.html"&gt;http://qin.laya.com/tech_coding_help/dylib_linking.html&lt;/a&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://balanceinmotion.net/blog/2007/12/26/free-love-frustration/"&gt;&lt;a href="http://balanceinmotion.net/blog/2007/12/26/free-love-frustration/"&gt;http://balanceinmotion.net/blog/2007/12/26/free-love-frustration/&lt;/a&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</description><link>http://overooped.com/post/42240519</link><guid>http://overooped.com/post/42240519</guid><pubDate>Mon, 14 Jul 2008 21:54:00 +0200</pubDate><category>frameworks</category><category>cocoa</category><category>coding</category></item><item><title>Lazy Man's Logging</title><description>&lt;p&gt;file_put_contents(…, FILE_APPEND) to log is a bad idea and you know it, but it’s sometimes good enough, or you just don’t get paid enough to make something serious. I just let you make it a tiny bit more serious, a whole lot more dependable, and still just change a single line of code.

&lt;pre name="code" class="php"&gt;
  /// Creates a table called $table as (id, when, message) if none such exists, and inserts a row with $message in it.
  /// If no connection details are given, it uses the current database connection. Same goes for $database and $when.
  ///
  /// @returns TRUE on success or FALSE on failure.
  ///
  /// @example mysql_put_contents("orders", "I CAN HAZ CHEEZBURGER?", "mysite", NULL, "127.0.0.1:3306", "mysite_user", "secret") or die(mysql_error());
  /// @example mysql_put_contents("guestbook", "Longcat says: I'm loooooooooooong") or die("Errorz!");
  function mysql_put_contents($table, $message, $database = NULL, $when = NULL, $host = NULL, $user = NULL, $pass = NULL) {
    if($host)
	    mysql_connect($host, $user, $pass);
	  if($database)
	    mysql_select_db($database);
	
	  $qry = "CREATE TABLE IF NOT EXISTS `$table` (
             `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
             `when` TIMESTAMP DEFAULT NOW(),
             `message` TEXT NOT NULL
           );";
    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;
      
    $qry = "INSERT INTO `$table` VALUES(NULL, ".($when ? $when : 'NULL').", '".mysql_real_escape_string($message)."');";

    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;
      
    return TRUE;
  }
	
&lt;/pre&gt;&lt;/p&gt;</description><link>http://overooped.com/post/35063696</link><guid>http://overooped.com/post/35063696</guid><pubDate>Fri, 16 May 2008 23:40:00 +0200</pubDate><category>coding</category><category>php</category><category>faves</category></item><item><title>PHP: Timeout on file_get_contents</title><description>&lt;p&gt;Since there doesn’t seem to be a single piece of documentation or example on the use of the context option for file_get_contents, and everyone’s actually setting the PHP app’s ini value for timeout (euugh) instead of doing it right, I thought I’d feed this to google:&lt;/p&gt;
&lt;div style="text-align:left;color:#000000; background-color:#ffffff; border:solid black 1px; padding:0.5em 1em 0.5em 1em; overflow:auto;font-size:small; font-family:monospace; "&gt;
&lt;span style="color:#825900;"&gt;$ctx&lt;/span&gt; = &lt;span style="color:#661aa9;"&gt;stream_context_create&lt;/span&gt;(&lt;span style="color:#881350;"&gt;array&lt;/span&gt;(&lt;br/&gt;
    &lt;span style="color:#eb7300;"&gt;‘http’&lt;/span&gt; =&gt; &lt;span style="color:#881350;"&gt;array&lt;/span&gt;(&lt;br/&gt;
        &lt;span style="color:#eb7300;"&gt;‘timeout’&lt;/span&gt; =&gt; &lt;span style="color:#0000ff;"&gt;1&lt;/span&gt;&lt;br/&gt;
        )&lt;br/&gt;
    )&lt;br/&gt;
);&lt;br/&gt;&lt;span style="color:#003369;"&gt;file_get_contents&lt;/span&gt;(&lt;span style="color:#eb7300;"&gt;“http://google.com/”&lt;/span&gt;, &lt;span style="color:#0000ff;"&gt;0&lt;/span&gt;, &lt;span style="color:#825900;"&gt;$ctx&lt;/span&gt;);&lt;/div&gt;

&lt;p&gt;The unit on the timeout argument is seconds as a float; that is, it is possible to use fractions (e g set timeout to 0.1).&lt;/p&gt;</description><link>http://overooped.com/post/31812358</link><guid>http://overooped.com/post/31812358</guid><pubDate>Tue, 15 Apr 2008 11:30:00 +0200</pubDate><category>php</category><category>coding</category><category>webdev</category></item><item><title>The truth, it hurts, it hurts! (Default parameters in Python seem to be evaluated once)</title><description>&lt;p&gt;&lt;div style="text-align:left;color:#000000; background-color:#ffffff; border:solid black 1px; padding:0.5em 1em 0.5em 1em; overflow:auto;font-size:small; font-family:monospace; "&gt;
&lt;span style="color:#881350;"&gt;class&lt;/span&gt; Bar(&lt;span style="color:#440088;"&gt;object&lt;/span&gt;):&lt;br/&gt;
  &lt;span style="color:#881350;"&gt;pass&lt;/span&gt;&lt;br/&gt;
 &lt;br/&gt;&lt;span style="color:#881350;"&gt;class&lt;/span&gt; Foo(&lt;span style="color:#440088;"&gt;object&lt;/span&gt;):&lt;br/&gt;
  &lt;span style="color:#881350;"&gt;def&lt;/span&gt; &lt;span style="color:#ff0000;"&gt;__init__&lt;/span&gt;(&lt;span style="color:#881350;"&gt;self&lt;/span&gt;, a = Bar()):&lt;br/&gt;
    &lt;span style="color:#440088;"&gt;super&lt;/span&gt;(Foo, &lt;span style="color:#881350;"&gt;self&lt;/span&gt;).&lt;span style="color:#ff0000;"&gt;__init__&lt;/span&gt;()&lt;br/&gt;
    &lt;span style="color:#881350;"&gt;self&lt;/span&gt;.a = a&lt;br/&gt;
 &lt;br/&gt;
foo1 = Foo()&lt;br/&gt;
foo2 = Foo()&lt;br/&gt;
 &lt;br/&gt;&lt;span style="color:#881350;"&gt;print&lt;/span&gt; &lt;span style="color:#440088;"&gt;repr&lt;/span&gt;(foo1) + &lt;span style="color:#440088;"&gt;repr&lt;/span&gt;(foo2)&lt;br/&gt;&lt;span style="color:#881350;"&gt;print&lt;/span&gt; &lt;span style="color:#440088;"&gt;repr&lt;/span&gt;(foo1.a) + &lt;span style="color:#440088;"&gt;repr&lt;/span&gt;(foo2.a)&lt;br/&gt;&lt;span style="color:#236e25;"&gt;# foo1.a and foo2.a is the same instance&lt;/span&gt;
&lt;/div&gt;&lt;/p&gt;</description><link>http://overooped.com/post/29651361</link><guid>http://overooped.com/post/29651361</guid><pubDate>Sun, 23 Mar 2008 22:39:00 +0100</pubDate><category>python</category><category>coding</category></item><item><title>Nevyn's First Rule of Singleton Evilness</title><description>&lt;p&gt;I finally figured out a litmus test for whether being a singleton is okay or evil for a particular class:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If a class is thread-safe and has no state that can be changed, it may be a singleton.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html"&gt;NSFileManager&lt;/a&gt;: OK. &lt;a href="http://www.friendlystapler.se/wiki/Sound"&gt;RMS::Sound::Gateway&lt;/a&gt;: Not so much.&lt;/p&gt;

&lt;p&gt;I suppose there are ways to circumvent this rule; e g most of Apple’s singletons may be created either through the+[defaultManager] method, or instantiated on-the-spot, e g if you want several separate &lt;a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#"&gt;NSNotificationCenter&lt;/a&gt; inside the same application.&lt;/p&gt;

&lt;p&gt;This discussion came up during the creation of the &lt;a href="http://www.friendlystapler.se"&gt;RMS game engine&lt;/a&gt;, among many other times. Now that I’m ripping out parts of the engine for re-use, I realize that it was a very bad design decision to use singletons the way we did. For example, my &lt;a href="http://nevyn.tumblr.com/post/25051276"&gt;2D modeler prototype&lt;/a&gt; for my &lt;a href="http://nevyn.nu/realtime_acoustics/"&gt;candidate thesis&lt;/a&gt; is document-based, thus it needs an RMS::Sound::Gateway for each window. This is no-can-do until I fix the code, because for example the Voice class has the delegated play method, and the way it works is that it gets the global gateway and adds itself to the gateway’s list of playing voices.&lt;/p&gt;

&lt;p&gt;“State that can be changed”? Oh, right. +[NSColor redColor] has state, but it can still be a singleton since that state can’t be changed by my code. Same for NSEvent’s singleton methods, and so on.&lt;/p&gt;</description><link>http://overooped.com/post/26541196</link><guid>http://overooped.com/post/26541196</guid><pubDate>Sun, 17 Feb 2008 10:14:00 +0100</pubDate><category>coding</category><category>faves</category></item><item><title>Not sure why Core Audio isn't an Objective C API</title><description>&lt;p&gt;It’s for performance, right? It’s the only good reason I can think of. And, you know, it sounds sensible. I mean, ultra-low latency and all that, you probably don’t want that objc dispatch overhead.&lt;/p&gt;

&lt;p&gt;I just did an experiment, however. I dislike working with C APIs, so I’m writing Cocoa wrappers for Core Audio, just exposing those pesky Component properties that take five lines to set or get, with simple methods. Suddenly I thought, “Wait, what if I try to use an objc method as a render callback? Those require very low latency and are called often. So I should be seeing some of that objc overhead.”.&lt;/p&gt;

&lt;p&gt;Very unscientific comparison, comparing a simple sine renderer in c and objc, on an MBP 1.83x2 (source available on request):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;CPU usage in app using C callback: 3.0%&lt;/li&gt;
 &lt;li&gt;CPU usage in app using ObjC callback: 3.1%&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This isn’t, by far, any compelling evidence that Core Audio should be Objective C; I’m just saying it seems more feasible than I originally thought it’d be. Also, actually thinking about the problem, I realize that the callback’s only called 44100/512 ≈ 86 times a second and has about 10 ms to complete (astronomically long in computer terms).&lt;/p&gt;

&lt;p&gt;But NeXT did it that way, didn’t they? I want to remember that NeXT had basically /everything/ in objc, including drivers and audio and such things. So, why not Mac OS X? NeXT was hardly known for being a slow OS. Tell me what I’m missing in the comments.&lt;/p&gt;</description><link>http://overooped.com/post/26051076</link><guid>http://overooped.com/post/26051076</guid><pubDate>Mon, 11 Feb 2008 12:59:00 +0100</pubDate><category>cocoa</category><category>coding</category><category>faves</category></item><item><title>Three Points On Error Handling</title><description>&lt;p&gt;I’ve been ranting on Twitter lately about how to do error checking &lt;em&gt;the wrong way&lt;/em&gt;. Coincidentally, the &lt;a href="http://www.macdevnet.com/index.php/podcasts/mdr/38-mdr/138-mdr003" title="MDR003: Exceptional Errors"&gt;latest topic on Mac Developer Roundtable&lt;/a&gt; was about just that, error handling.
&lt;/p&gt;

&lt;p&gt;I don’t think this episode of MDR was very interesting. It was essentially an overview of the three common error handling strategies (exceptions, enum returns, pass-by-ref error object), and some general C++/Java likeage from Uli (which is not a compliment :P). However, it got me writing a real blog entry, which is a good thing :)
&lt;/p&gt;

&lt;p&gt;So: Three things kept repeating in my head while I listened to MDR#3, hoping that someone’d mention it so that we can rid the world of more bad code.
&lt;/p&gt;

&lt;br/&gt;&lt;p&gt;&lt;strong&gt;First off&lt;/strong&gt;, stay far far away from nested ifs. I don’t remember which Mac dev blog I read it on, maybe &lt;a href="http://www.wilshipley.com/blog/" title="Call Me Fishmeal."&gt;Wil Shipley&lt;/a&gt;’s or &lt;a href="http://ridiculousfish.com/blog/" title="ridiculous_fish"&gt;ridiculous_fish&lt;/a&gt;, but whoever it was recommended to always try to keep the code as far to the left as possible. Use the outermost block for the common, correct case, and use inner blocks for error cases. What I mean by this is, check for the error condition and treat it in-place, don’t check for the not-error case and treat the error in an else far far away. An example is in order…
&lt;/p&gt;

&lt;pre&gt;&lt;code class="cpp"&gt;
// Don't:
void collectPhazon() {
  PhazonDetector *detector = findNearestPhazonDetector();
  if(detector) {
    Phazon *nearestPhazon = detector-&gt;scanForPhazon();
    if(nearestPhazon) {
      sendPhazonCollectorDrone(nearestPhazon-&gt;position());
    } else {
      beep(kNoPhazonFoundBeep);
    }
  } else {
    beep(kMajorlyCatastrophicErrorBeep);
  }
}

// Do:
void collectPhazon() {
  PhazonDetector *detector = findNearestPhazonDetector();
  if(!detector) { beep(kMajorlyCatastrophicErrorBeep); return; }
  
  Phazon *nearestPhazon = detector-&gt;scanForPhazon();
  if(!nearestPhazon) { beep(kNoPhazonFoundBeep); return; }
  
  sendPhazonCollectorDrone(nearestPhazon-&gt;position());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This also applies to smaller scopes, such as for and while loops. Instead of having a big &lt;em&gt;if&lt;/em&gt; block inside the loop, say &lt;em&gt;if(error_condition) continue;&lt;/em&gt;. Feel free to use gotos as well, eg:
&lt;/p&gt;
&lt;pre&gt;&lt;code class="cpp"&gt;
  Baz *a() {
    ...
    if(error) goto a_cleanup;

    return myBaz;
  a_cleanup:
    free(myBaz);
    fclose(bazHandle);
    return NULL;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The same effect can be achieved with try-catch-finally, so use whichever makes your code the easiest to understand.
&lt;/p&gt;

&lt;br/&gt;&lt;p&gt;&lt;strong&gt;Secondly&lt;/strong&gt;, never use just a boolean NO or a nil return value as an error return for a method or function that can fail in more than one way. If you do, the user of your library (or yourself, if it’s in your app!) can’t know what actually went wrong.
&lt;/p&gt;

&lt;p&gt;This leads to error dialogs such as “Couldn’t connect to iPod” — why not? Because one isn’t connected? Because it’s the wrong model? Because I hit it with a hammer? The sentence is lacking a ‘because’ because the reason is hidden behind bad abstractions.
&lt;/p&gt;

&lt;p&gt;This is where NSError is your friend, and I think that this is the answer to Scotty’s burning question: ‘When should I use NSError’? The answer is simple: whenver there’s more than one way to fail; whenver a NO/nil can mean more than one kind of failure.
&lt;/p&gt;

&lt;br/&gt;&lt;p&gt;&lt;strong&gt;Third&lt;/strong&gt;, and this was actually mentioned, if you’re checking for errors, make sure you understand /why/ you’re checking for that error, and what the logical response is.
&lt;/p&gt;

&lt;p&gt;This snippet from Apple’s sample “ComplexPlayThru” is a perfect example of how not to do it (ComplexPlayThru.cpp, line 353-354):&lt;/p&gt;
&lt;pre&gt;&lt;code class="cpp"&gt;
  comp = FindNextComponent(NULL, &amp;desc);
  if (comp == NULL) exit (-1);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nice! My app suddenly disappeared with no explanation whatsoever! And I’m sure no other part of the app uses the error code ‘-1’! Awesome. Also, the component that they’re looking for is an Apple default, must-be-there-or-any-sound-app-will-crash component. It’s safe to assume that it will always be there, and just skip the error check.
&lt;/p&gt;
&lt;p&gt;This also goes against Gus’ advice: please &lt;em&gt;don’t&lt;/em&gt; just copy any sample code you find, even if it’s from Apple.
&lt;/p&gt;</description><link>http://overooped.com/post/24237783</link><guid>http://overooped.com/post/24237783</guid><pubDate>Sun, 20 Jan 2008 23:09:00 +0100</pubDate><category>cocoa</category><category>coding</category><category>faves</category></item><item><title>NSURLConnection, rails, apache, spaces in URLs and "Your browser sent a request that this server could not understand"</title><description>&lt;p&gt;My Rails application uses redirect_to at one point in my code where it redirects to a pdf document on an apache server. The URL that it redirects to contains spaces. URLs may not contain spaces. redirect_to does not escape these spaces, but issues a ‘302 Found’ redirect response with the unescaped URL.&lt;/p&gt;

&lt;p&gt;When my Cocoa application receives this redirect request through the currently running NSURLConnection, it follows the new url. In 10.4, it escaped the URL before sending the GET request. In 10.5, this is no longer the case, and apache (correctly) barfs on the request with
&lt;/p&gt;
&lt;blockquote&gt;
&lt;b&gt;Bad Request&lt;/b&gt;
&lt;p&gt;Your browser sent a request that this server could not understand.&lt;/p&gt;
&lt;p&gt;The request line contained invalid characters following the protocol string.&lt;/p&gt;
&lt;/blockquote&gt;

The solution is simple: URI::escape the URL before redirecting to it. The big question however, is: &lt;b&gt;Is this a bug in my code, in Rails, or in Cocoa?&lt;/b&gt;

&lt;p&gt;I’m guessing first or second; I’m supposing there’s a very good reason why Apple chose to change the behaviour of NSURLConnection. Also, the Rails documentation &lt;i&gt;does&lt;/i&gt; say, &lt;q&gt;String starting with protocol:// (like http://): Is passed straight through as the target for redirection&lt;/q&gt;, which would put the responsibility square on me. However, Rails &lt;em&gt;is&lt;/em&gt; generating an invalid response, so I’ll go with blaming rails.&lt;/p&gt;</description><link>http://overooped.com/post/24108621</link><guid>http://overooped.com/post/24108621</guid><pubDate>Fri, 18 Jan 2008 22:10:00 +0100</pubDate><category>cocoa</category><category>coding</category></item></channel></rss>
