The Nature of Code for Cinder

November 8, 2013

Last year, Daniel Shiffman released The Nature of Code, a book that explores and explains how to simulate systems that appear in nature using processing. In the intro of the book, he made a declaration to anyone that cared to contribute to convert all of the examples in the book into other relevant languages that might be useful to people, be it flash, javascript, openframeworks, etc. I took this as a chance to learn the principles taught in the book and convert everything to Cinder.

I’m still working on it in my spare time, but I’ve made some progress. You can check out the first 4 chapters on github. I hope to have the next chapter done in December. Enjoy.

And if you haven’t checked it out yet, take a look at The Nature of Code. Buy the ebook or print copy. Whatever. Dan does a great job breaking down the principles that are necessary to simulating these different systems in a way that’s accessible and makes you actually feel kind of smart. It’s quite great.

Flash to Cinder – Timed Event Loops

September 2, 2012

This is the first tutorial in a series designed to help Flash developers transfer their skills to the C++ creative coding framework Cinder. I’ll provide links to sample code at the end of the post. There’s a lot to learn, so lets get started.

Timing events to happen in a repeating loop is a common technique used in games and applications. It’s commonly used in games when for instance, you want a missile to attack you’re hero every 2 seconds or in an application when you want to remind the user where to click if they haven’t touched anything in a few minutes. I recently used a timed event loop for an installation that required an image transition every 30 seconds.

PathFitter Block for Cinder

May 31, 2012

PathFitter Screenshot

I created and released my first cinder block and wanted to put it out there to see if it’s useful to anyone else.
https://github.com/gregkepler/CinderPathFitter

What it does is simplifies and returns a smoothed out, simplified Path2d object based on a vector of Vec2fs that you pass to it. It uses the same algorithm that paperjs uses, but c++-ified. It’s a slightly modified version of An Algorithm for Automatically Fitting Digitized Curves from “Graphic Gems.”

There are 2 samples in there.

  • PathSimplification: Drag to draw a line on the screen. Once the line is finished, it analyzes and smooths out the line, letting you know how many lines you saved. It’s based on this paperjs example.
  • ContinuousPath: Analyzes and smooths a path as you draw it. Could be good for making a drawing application.

SWC File as Embedded Runtime Asset Library

March 20, 2012

This post is really for myself so that I have somewhere that I can look this up again. Maybe it’ll be helpful to someone else in to the future too.

When working in flash (which I find myself doing less and less now a days), one of my favorite ways to work with assets is through the use of swc files. That’s what they’re there for anyways right? Well what’s not so obvious is how to use swc files to load assets at runtime without using the import command. There are times that it’s useful to refer to an asset at runtime by name that you may or may not use, so you don’t want to explicitly go through the hassle of writing the lines to embed it. This often happens with sounds or items that are easier to loop through to use, such as when using a map of the US. It’s much easier to write a loop vs writing 51 embed statements (yes, I know that there are a million different ways of doing this without writing all of that).

When you do something like going through a loop and saying getDefinitionByName(“state_”+i) to grab a library item that resides in the swc asset file, there are no compiletime errors because Flash Builder can find that swc in the library. But once it runs, the debugger will yell at you. To fix this, you need to embed the swc file at compile time. In Flash Builder, this is done in the Actionscript Compiler settings and all you have to do is add this line (replacing it with the path to your asset swc file obviously)

-include-libraries /assets/assets.swc

Now when you run your swf, it’ll work like a charm and you’ll have those assets available without having to import them in the head of your class file. That being said, be sure to only do this when it makes sense. This embeds the swc file into your swf. So if there are assets in the library that are outdated and set to export at compile time, they’ll be included adding extra senseless bloat. As I write this, I’m using this method for a prototype where bloat doesn’t really matter, but just be mindful of that.

Setting the swf Base Directory in HTML

April 7, 2011

Have you ever completed a flash project and started testing it online only to realize that the swf is looking for assets either in a different directory than the one you specified? Or that the folder that you have all your media stored is not in a relative directory like it was when working on it locally?

The solution that I mustered up in the past was to create a flashvar called something like “mediafolder” and put that in the embed code. From there, I would go back into my actionscript code and make sure all external media had the passed “mediafolder” variable appended to the beginning of the url for each external asset and then republish my swf.

This always worked well, so I usually plan for this, but my latest project didn’t have that built in. When it came to testing and we realized that the media folder was going to be in a different location than the base swf file and it was supposed to launch soon, it was time to see if there was another alternative to the usual solution. That’s when I discovered the “base” attribute in the swf object embed code.

The “base” attribute is actually an href attribute that specifies a base URL for all relative URLs on a page. Traditionally, you should be able to put it in the head of an html page and have all links on a page link relative to the string specified in the base attribute. For this it’s just specified for the swf, which picks it up when passed as a param and picks up any external asset from that folder by default instead of the folder that the actual swf is in.

Here’s a sample of the swfobject embed code:

<script type="text/javascript"> 
	var flashvars = {};
	var params = {"base": "../project/subfolder/"};
	var attributes = {id: "Main", name: "Main"};
	swfobject.embedSWF("MainLoader.swf", "myAlternativeContent", "920", "550", "10.0.0", "expressInstall.swf", flashvars, params, attributes);
</script>

With the example above, any asset that the main swf is trying to load relative to itself can now be placed in “../project/subfolder” without having to change any actionscript and republishing your swf. This is a tip that has saved me hours of work and would have saved me even more time had I discovered it in the past.

Loading External Across Domains in Flash

September 27, 2010

I feel like I’ve run into this issue so many times and either fixed it by accident or came up with some other solution in order to do the same thing. This time I cam to a conclusion that I understand and hopefully other people can use.

The Problem:

You create an flash app for the web which loads in data from a variety of other external sites, such as thumbnails from an aggregated feed using a 3rd party API and it works swimmingly while you’re testing locally. As soon as you put it on a remote server, you get a Flash Player security error, perhaps something like:

SecurityError: Error #2122: Security sandbox violation: LoaderInfo.content:http://staging.site.com/project/Main.swf cannot access http://www.website.com/image.jpg. A policy file is required, but the checkPolicyFile flag was not set when this media was loaded.
    at flash.display::LoaderInfo/get content()
    at com.gregkepler.testProject.imageloader::ImageLoader/onImageLoad()

Depending on if you’re ready for this error or not, you may not get a popup and can fail silently.

Why This Happens:

This is happening because you don’t have your policy files set up on your server and your swf is “illegally” trying to access data from another domain. This is actually a good thing since it stops potentially dangerous files from doing bad shit to your project/server/network/computer. But you want to ALLOW access to these different domains since that’s a big part of your project, right? The solutions are actually very easy to implement, just sometimes a pain in the ass to figure out.

The Solution(s):

Depending on the project and how wide-spread and prominent it will be on your website and if other projects will need the same sort of access on your server, you may want to allow the entire domain access to the external domains or just one individual project.

For an entire domain

All you have to do is place a crossdomain.xml file is the root of the server where the project will reside. The crossdomain file will look similar to this:

<cross-domain-policy>  
<allow-access-from domain="*" />
</cross-domain-policy>

Replace the * with a specific domain if you don’t want to allow access to all sites. This works because the flash player automatically looks for a crossdomain.xml file when it is asked to load any file in a different domain. It checks to see if it should allow the file based on which domains are specified in the file. If it doesn’t see this file or a domain isn’t listed, or * isn’t specified, it will throw an error and won’t allow the file to be loaded into your app.

For a sub-domain

Sometimes the above solution isn’t appropriate, especially for a website that can potentially house many different projects that have different rules about what is can and should allow. This solution involves a few extra steps, but is still pretty easy.


Step 1:
You still need to add a crossdomain.xml file to the root of your server, but instead of allowing all domains to be accessed, you want to tell it that it should allow crossdomain policy files to be set elsewhere on the server. This is what the crossdomain.xml file would look like instead:

<cross-domain-policy>
<site-control permitted-cross-domain-policies="all" />
</cross-domain-policy>



Step 2:
Create a crossdomain file somewhere else on the server that makes sense, such as where your project exists. This will look a lot more like the original file. In fact it’s exactly the same, unless you want to change the domains that you want to allow for this specific project.

<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

Make note as to where you are putting this file, since you will be specifying this actual xml file as the one to look at for cross domain access (ie: http://staging.site.com/project/crossdomain.xml).


Step 3:
The next 2 steps involve actually adding some as3 code and republishing.
Specify the policy file that should be loaded instead of the one in the root. This should be done before trying to actually load anything. I normally place in the document class as one of the first things that should be done.

Security.loadPolicyFile('http://staging.site.com/project/crossdomain.xml');

Don’t forget to import flash.system.Security.


Step 4:
Go to where you are trying to load the external data and create a LoaderContext instance.

var context: LoaderContext = new LoaderContext();
context.checkPolicyFile = true;

As noted from adobe’s website, what checkPolicyFile does is specifies whether a cross-domain policy file should be loaded from the loaded object’s server before beginning to load the object itself.

Then you will pass that context as an argument when you go to actually load the file, as seen below.

imgLoader = new Loader();
iimgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoad, false, 0, true);
imgLoader.load(new URLRequest(thumbUrl), context);


This article got me on the right foot: http://stunnedgrowth.livejournal.com/4540.html
More about LoaderContext: LoaderContext

Thoughts on Pure MVC

December 29, 2009

Recently, I used the Pure MVC framework for the first time on a project and it opened my mind to the right ways, wrong ways, and new ways to structure a project in Flash. Before I get into the pros and cons, I want want to first warn any of you that are new to using frameworks in general that there is some studying involved in order to fully wrap your mind around how this thing works. But it’s totally worth it.

Before you jump in, it’ll help if you are familiar with OOP programming basics and have an understanding of what the MVC design pattern is. When I started, I was already quite familiar with MVC pattern and decided that having a framework that laid out some rules for my programming may help in keeping the project consistent. In order for me to completely grasp this new way of thinking, I first took a look at the conceptual diagram and quickly decided that it made absolutely no sense to me. Then I read through the Framework Overview and the Best Practices PDFs multiple times and it started to finally click. The guys who put together this framework did a really good job of providing lots of examples and documentation to help you though this difficult time, so search through and give it a good honest go around before throwing you hands in the air.

After using it for a few months, here’s a summary of the advantages and disadvantages.

Pros

  • Provides structure and “rules” for programming your project
  • Used among multiples languages, so your one leg up if you want to use it in C#, Java, or PHP
  • Gives you a better understanding of OOP concepts in general and why they’re so useful
  • Makes it easy to separate your project into multiples pieces which may help if there are multiple people working on a project
  • Makes it easy to remove or turn off features

Cons

  • Forces you make a lot of classes
  • Adds to the compile time, so it’s probably not a good idea to use with small projects
  • When adding new functionality, it may take a little more time to implement if it’s going through the entire framework, though it’s more likely that it will be less buggy

Summary

Pure MVC was great to learn and helped me more concretely understand some OOP concepts that I was a little spotty on. I’m sure that I will use it again, but only for larger projects where I need a  shell that ties everything together and has a lot of different “modes”. For a smaller project, I’m going to try out Robotlegs, which seems to have some of the same core concepts in a tighter package. Either way, I know that all of my future projects will have some solid structure and some of my own rules for developing it.

Check back soon to see how this Pure MVC-based project turned out.

Getting stop() to stop

July 7, 2009

In as3, the introduction to of the display list has made the stop() method a little less straightforward. Traditionally, when you used stop() on the timeline of a movieclip, it would do just that, stop the playhead from playing past where that script is. To be fare, this does still work, but only if you place the movieclip on the timeline manually (not via code).

Now to get a movieclip to stop on the first frame when added to the display list via the addChild() method, you must be sure to add stop() once it’s added. Also, note that you cannot call any other timeline based methods such as gotoAndPlay() and gotoAndStop() to a dynamically added movieclip unless it’s on the display list either.

This is specifically useful when you are using a movieclip that has a timeline based rollover and rollout animation as a button.