Thoughts on Dart

Lately I’ve started playing around with the Dart programming language by Google. The idea behind Dart, is that writing applications in javascript is really a painful act. Sure overtime many of us have gotten used to the various pain points, and there are conventional workarounds that have essentially become part of the ‘hidden standard’ of Javascript language. But why should we have to live with them? Just because it is, doesn’t mean we should be forced to deal with it!

Let me give you an example, in Javascript how would you go about creating a class (Note: Please don’t bother me with the semantics of class vs prototypical inheritance, just go with it for the sake of argument)?
Well here’s one way:

Animal = function () {
    this.isAlive = true;
}
Animal.prototype = {
    eat: funciton(){},
    pray: function(){},
    love: function(){}
}

So far so good, no big deal here, now we can create many new Animal’s all we want.
However what if we want to subclass Animal, to a more specific type of say Dog?

Well here’s where javascript’s faults come into play, there is no one way to do this so what you have is many people reinventing the wheel and confusion for new comers especially from other languages when they attempt to implement something as simple as creating a Dog that inherrits from Animal.

Here’s one way of doing it in Javascript:

Dog = function() {
    Animal.call( this ); // Call super's constructor
}
Dog.prototype = Object.create( Animal.prototype );

Here’s a different way of tackling the problem:

function extend( subclass, superclass ) {
 
    var originalSubclassPrototype = subclass.prototype;
 
    // Store the superclass prototype in a surrogate function
    var F = function(){};
    F.prototype = superclass.prototype;
 
    subclass.prototype = new F();
    subclass.superclass = superclass.prototype;
    subclass.prototype.constructor = superclass;
 
    for(var method in originalSubclassPrototype) {
        if( originalSubclassPrototype.hasOwnProperty(method) )
            subclass.prototype[method] = originalSubclassPrototype[method];
    }
 
}

Which is correct? Well the answer is both, there’s plenty of ways to skin a classy cat in Javascript, and these are just two of them, there’s plenty more out there as well. To me having too many ways to do something as simple as creating a subclass is a A Bad Thing.

In Dart there is only one way to create a Class, and only one way to create a subclass:

    class Vec2 {
        num x;
        num y;
        Vec2( this.x, this.y );
    }

That’s it, and in case you’re wondering about that sleek looking constructor, as you should be, well that is a special type of syntatic sugar shorthand in Dart that is the equivalent of:

    class Vec2 {
        num x;
        num y;
        Vec2( num pX, num pY ) {
            x = pX;
            y = pY;
        }
    }

How many times have you had to create a constructor where the first 10 lines were just simply setting the variables of the local instance? A lot i’m sure. Instead Dart allows you to simply state that the arguments passed in should be set to the respective local variables. Also notice that I did not type the word this. In Dart the scoping is already correct, so there is no need to explicitely type ‘this’ (although you can if you like).

Creating a subclass is equally as straight forward:

/// A circle is similar to a [Vec2] except it contains an area.
class Circle extends Vec2 {
  /// Radius of the [Circle]
  num radius;
 
  /// Creates a new [Circle] with [radius]
  Circle( num pX, num pY, this.radius) : super(pX, pY);
 
  /// Returns whether a point is contained within [this] [Circle]
  bool containsPoint( Vec2 p ) => ( distanceSquared(p) <= radius*radius );
}

That’s all there is to it, no confusion about which is the correct way, the “fastest” way, etc.

A couple of other things to notice here as well.
Firstly are the comments. In Dart a comment that contains three slashes, ///, is considered a Documentation comment. It will be parsed by the built-in (!!) Dart-Doc generator. It even uses Markdown so you don’t have to write annoying HTML in your Documentation comments. Again notice the brackets around [Vec2], because Dart has full knowledge of your application, it knows to go and find the class Vec2 and link to it in the documentation.

So back to subclassing, notice our constructor:

Circle( num pX, num pY, this.radius) : super(pX, pY) {
    print("My radius is ${radius}");
}

Here we are using another two special constructs Dart provides for constructors.
The first is the ‘initializer list’, which come from C++. They allow you to set properties separated by comma’s after the constructor, but outside of the function’s body. Notice the call to super, very straightforward.

Finally the last thing to notice is the string interpolation occuring in the ‘print’ function (essentially console.log). Here we have a single string, and inside we have a special syntax ‘${}’, where inside we can place an expression ( or value ), that dart will evaluate for us. No more having to concact strings with plus signs and making typos that are hard to spot.

Overall I’m very much liking the things that Dart is bringing to the table, best of all it compiles to Javascript so it will work on any modern browser. Currently Dart’s compiled javascript, runs at 80% speed of something written in vanilla javascript, and getting it’s not even at version 1.0 yet! Also worth mentioning that DartVM is already outperforming V8 in nearly all javascript benchmarks.

In the next post I’ll dissect a few more interesting things that I like about Dart, and a few who I dislike.
In the meantime, don’t waste any time, go watch the screencast that sold me http://www.dartlang.org/docs/editor/

Calculating the gravity of the gravitational force or 0.00000000000667

Gravity is by far the best force in the universe. Despite being the weakest of the “main” four (strong nuclear force, weak nuclear force, electromagnetism, gravity). It is the one that dominates given enough time and distances. All this even though it falls of inversely to the square of the distance, meaning, if you double the separation between the two objects you quarter the force, or if you cut the separation in half you quadruple the force of attraction.

It’s also one of my favorite things when creating visualizations, because things move so beautifully when you simply let gravity take over.

So I thought I would give it it’s own tiny blog post, in honor of its value 0.00000000000667

    // Compute the net force acting between the invoking body a and b, and
    // add to the net force acting on the invoking Body
    public void addForce(Body b) {
        Body a = this;
        double G = 0.00000000000667;
        double EPS = 0.0001;      // softening parameter
        double dx = b.rx - a.rx;
        double dy = b.ry - a.ry;
        double dist = Math.sqrt(dx*dx + dy*dy);
        double F = (G * a.mass * b.mass) / (dist*dist + EPS*EPS);
        a.fx += F * dx / dist;
        a.fy += F * dy / dist;
    }

Eclipse template project with cocos2dx

I have created an eclipse project template, which contains an SDK project, with a NDK C++ bindings ( done via ‘javah’ build step ), combined with Cocos2dx helloworld project.
I have used it as the base for 2 projects, and figured I would share.

https://github.com/onedayitwillmake/EclipseAndroid_NDK_SDK/tree/cocos2dx

 

Using EclipseLovesCinder template

About a year ago, I created a template to use the Cinder framework within Eclipse. I still use it all the time, as I still find Eclipse a better C++ editor (although xcode is slowly catching up if you use the compile and use the latest LLVM). I recently decided to revisit it and update it to better fit the workflow I prefer, and fix issues I’ve over time found work arounds for.

With that I decided that it was time to give some new instructions so here they are. I’ll revisit this post with more details, but if pictures are a 1000 words this is a pretty big post.

Continue reading Using EclipseLovesCinder template

Better Eclipse Icon for Android Development

Every time I setup eclipse for a new computer, new OS install, or decide to use it for a different language/platform I find myself recreating the icon for it. This usually occurs at the VERY beginning of the affair with a new whatever, so I have plenty of energy and really want to get off on the right foot. It’s kind of part of the fun.

Continue reading Better Eclipse Icon for Android Development

C++11 in Eclipse CDT Part 1 – Getting and Installing GCC4.7

This is the second part of a three part series on using C++0x11 on OSX via Eclipse. If you need a little bit more nudging, you might want to look at Part0 of this series, where I make the case that the Langauge is moving in this direction and as such does not make sense for us to use older outdated tools.

In this post I’ll discuss the process of getting and installing the GCC4.7 compiler. First we need to arm our computer with the right tools.

We’ll be configuring and installing the following tools:

  • Macports: A tool for configuring / building / installing  tools, binaries, etc from terminal on OSX similar to ports or apt-get
  • Xcode 4.2+ : Required for above
  • Xcode 4.2+ Command Line Support: Required to build macports
  • Eclipse CDT: Our editor

Continue reading C++11 in Eclipse CDT Part 1 – Getting and Installing GCC4.7

C++0x11 + OSX + Eclipse: Part 0 – The Why

I use Eclipse CDT as my C++ editor of choice on my Mac at work and at Home.
It’s really a very good editor for C++. Xcode, is a decent editor. When doing iphone / mac OSX projects with Objective-C its an amazing editor. However it is very bad at C++, in my opinion Xcode 4 is much worse than Xcode 3 at C++ code editing.

Is it a conspiracy to nudge developers towards developing using (basically) Apple’s own Objective-C programming language? Maybe I’m not sure, however I do love Objective-C, it’s my second and sometimes first favorite programing language, behind only C++.

To be honest it’s probably not, since they support the Clang+LLVM project which supports C++11, in fact it supports more features than GCC4.7 and is a faster compiler.

C++ has matured so much in the last few years, and a large part of that is due to the Boost libraries. In fact Boost, is sort of used as a testing ground for C++ – and many parts of C++0x11 started off as Boost Libraries ( for-each, any containers, lambdas, smart pointers, thread ).

As an OSX affectionato, I have to admit that I was upset that my latest version of OSX ( Lion at the time of writing ) was using GCC 4.2… GCC 4.2.1 is from July 2007!. The compiler and accompanying library is over 5 years old! In computer years, from what I sophisticatedly computed, thats 1 zillion years ago. That doesn’t seem right… Apple is defineintly making amzing strides with LLVM+Clang compiler, it’s actually better and faster than the latest GCC (4.7 at time of writing), however Xcode is such aTERRIBLE C++ editor, often not providing auto-complete, and not being able to find references until upto a minute after click. One minute? That’s crazy.

Hearing all this talk about how great C++0x11 was, I wanted to use it. To be honest, a lot of the stuff can be faked using the amazing Boost libraries – some of which are now standard. However I felt ripped off, these are officially part of C++ I should be able to use them now right!? Well not on OSX you can’t – well at least not without a little bit of work.

Continue reading C++0x11 + OSX + Eclipse: Part 0 – The Why

BulletML running on iOS

BulletML is an XML like markup language created to describe bullet barrages seen in shooters. It allows you to describe complex bullet patterns in simple XML files, then parse them and let it run. Very easy to create nice boss patterns

In this video is my first working attempt at getting it to run on the iPhone. Currently bullets can not spawn other bullets, but once I get that i’ll share the source

It runs at 60FPS, but the screen recorder drops some frames.

Project:
https://github.com/onedayitwillmake/BulletHaven

I’ve managed to get BulletML and cocos2d to work together.
Most of the bulletml files work, except for when bullets need to spawn other bullets.

Does anyone have any experience with this, perhaps it’s a callback function that needs to be inside of bullet?

Video of 2.5D Javascript/WebGL PortalGun

I’m in the middle of adding a Portal gun to chuclone – There are still a few kinks in it, namely related to determining the side of the object the Portal gun hits, and converting the 3D position of your shot into 2D cordinates so that it shoots exactly where you aimed. However I have it far along enough to show a video of it in action!

Here you can see me messing around with the gun, as well as trying out a couple of simple level ideas that come with it.
Mostly the momentum based puzzles, as those were my favorite in Portal. However I kind of wonder if i should add switches as well – that might be kind of cool.