three.js custom shader material

December 31st, 2011 | Posted by cjgammon in web | webgl - (1 Comments)

This post is going to assume you have used three.js to set up a basic scene with a camera and objects. The shaders can go in a script tag within the page and then can be referenced using the id of the script elements.

 

Vertex Shader:

varying vec2 vUv; uniform float delta; uniform float scale; uniform float alpha; void main() {     vUv = uv;     vec3 p = position;     p.z += sin(2.0 * p.y + delta) * 5.0;     p.z += cos(2.0 * p.z + delta / 2.0) * 5.0;     p.z += cos(2.0 * p.x + delta) * 5.0;     p.x += sin(p.y + delta / 2.0) * 10.0;     vec4 mvPosition = modelViewMatrix * vec4(scale * p, 1.0 );     gl_Position = projectionMatrix * mvPosition; }

This is a pulsing vertex shader that will distort the geometry in a geometric wave like fashion based on the delta value.

 

Fragment Shader:

#ifdef GL_ES precision highp float; #endif uniform float delta; uniform float alpha; varying vec2 vUv;         void main(void) {     vec2 position = vUv;     float red = 1.0;     float green = 0.25 + sin(delta) * 0.25;     float blue = 0.0;     vec3 rgb = vec3(red, green, blue);     vec4 color = vec4(rgb, alpha);         gl_FragColor = color; }

This is a fragment shader that will transition from orange to red and back again based on the delta value.
We can set up our uniform values which correlate with our shader.

//these should reference their respective shaders vertShader = document.getElementById('vertShader').innerHTML; fragShader = document.getElementById('fragShader').innerHTML; attributes = {}; uniforms = {   delta: {type: 'f', value: 0.0},   scale: {type: 'f', value: 1.0},   alpha: {type: 'f', value: 1.0} }; material = new THREE.ShaderMaterial({   uniforms: uniforms,   attributes: attributes,   vertexShader: vertShader,   fragmentShader: fragShader,   transparent: true }); //create sphere geometry and apply our new material var sphere = new THREE.Mesh( new THREE.SphereGeometry(3000, 20, 20), material); //update the delta value on an interval,  //we could also alter other values like alpha or scale function update() { uniforms.delta.value += 0.1; } //set the interval setInterval(update, 100);

That should just about get you up and running with a basic vertex shader and fragment shader and an idea of how to manipulate values within them.  For more ideas on what you can do with fragment shaders and glsl, check out the glsl sandbox glsl sandbox.

Particularly in mobile safari on iOS CSS3 properties can be particularly tricky. Performance can become an issue to the point that CSS animations flicker even when using translate3d for hardware accelerated animations. Tricks have been mentioned to make -webkit-backface-visibility:none; and -webkit-perspective:1000;. However sometimes these are not enough and I’ve found resorting to javascript animation saves the day. Tweening the CSS properties within an interval completely removes this flickering, though testing should be done to ensure speeds are accurate and performance is at it’s best, since sometimes CSS animation does seem to out perform Javascript, though it seems to be a case by case basis and I’ve found elements with a great deal of content animate better via CSS. However you do it both methods should be tested and considered tools in your arsenal of animation.

So yesterday I thought it would be useful to have a tool that generates CSS classes based on defined slices of an image.  There are tools out there that do this but I wanted to be able to custom tweak it to do what i wanted and output things a certain way.  So I made one.  It’s very rough around the edges and definitely read the instructions before using as I made it in an afternoon, but check it out and feel free to add to it or change it to your liking.

CSS Sprite Map Generator

Facebook Share url Metadata Parameters

April 13th, 2011 | Posted by cjgammon in web - (2 Comments)

So in the glorious void and mess that is the facebook documentation, nowhere does it discuss the details on the share url and the optional parameters that you can pass to customize the images title and more.

http://www.facebook.com/sharer.php?s=100&p[title]=titlehere&p[url]=http://www.yoururlhere.com&p[summary]=yoursummaryhere&p[images][0]=http://www.urltoyourimage.com

will display the following info:
Title: titlehere
Summary: yoursummaryhere
URL: http://www.yoururlhere.com
Image: http://www.urltoyourimage.com

Although Apple claims to be a major proponent of HTML5 by dismissing flash, the truth is they are really just trying to keep the web from being as rich as native applications where they have the greatest stronghold in the mobile market. You can do quite a bit with HTML5, with canvas, video, webGL, and other new features it contains a lot of the abilities that made flash so cool. A lot of these are popping up in rich games and websites and while they still aren’t to the ability that flash has, there is no where they seem more limited than on apple’s own device. For example canvas itself runs much slower on the iPhone than if you simply animate div’s with hardware acceleration using webkit’s translate3d transformation. Video is completely crippled, particularly on the iPhone where they disable the ability to play inline video, instead launching it full screen. They also don’t allow more than one video playing on both iPhone and iPad, as well as removing the ability to auto play video on both devices. The argument for this autoplay functionality is that people are typically charged for data usage on these devices, but this argument becomes null when you consider the iPad is typically using wi-fi. These hindrances handicap the mobile space on these platforms and the ability for web developers to creatively utilize video beyond simple video playback. It’s interesting because it seems the natural progression of the web is to emulate native applications, however on these devices popular for using the web Apple seems to be blocking it.

HTML5 getting started with canvas

March 19th, 2011 | Posted by cjgammon in web - (0 Comments)

HTML5 and javascript are supposedly the next wave of the web to do rich content without flash or any other plug ins like unity. A big part of this is the canvas element which allows you to draw and manipulate content in 2D and in some browsers 3D with webGL. The canvas tag looks like the following:

<canvas id="myCanvas">your browser does not support canvas</canvas>

Pretty basic right?
So to actually make things appear we need to reference this with javascript and then draw whatever we want.

var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d");

Now we have the canvas and the context which is where we’ll actually do the rendering, notice we specified 2d, if we’re doing 3d drawing we would specify a different context to draw in. So now we can draw.

ctx.fillRect(10, 10, 100, 50);

If you are familiar with Flash’s Drawing API this will look familiar. The properties look like this fillRect(x, y, width, height). You can reference the full canvas API here. You can also draw any HTML element like images or videos with the below method.

var myImageElement = new Image(); myImageElement.src = "images/image.png"; ctx.drawImage(myImageElement, 10, 10);

What we’re doing is creating an image element in javascript and then drawing it onto the canvas. Once you can do this we can start to unravel the true potential of canvas by animating it.

var newX = 10; setInterval("loop()", 100); function loop(){ newX++; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(myImageElement, newX, 10); }

So now that we have animation we can do all sorts of magic! Using javascript you can capture events to change behavior for rich interactive experiences.

Flixel Animated TileMap

March 13th, 2011 | Posted by cjgammon in actionscript | games - (2 Comments)

So I was putting together a game where I wanted an animated tilemap in flixel, it did not seem to have this functionality natively, so I created a class for it and thought I’d share. It would be pretty simple to extend this to add animation features for randomly animating tilemaps or specify tile sequences for different positions.

/////////////////////////////////////////////////// //      FlxAnimTilemap.as //      CREATED: Wed Mar 12 21:19:36 EDT 2008 //      BY: cjgammon - cj.gammon@gmail.com // //      CLASS RESPONSIBILITES: //     tilemap of sprites that animate in a synchronized fashion // ////////////////////////////////////////////////// package org.flixel { import org.flixel.FlxAnimTilemap; public class FlxAnimTilemap extends FlxTilemap { private var _animating:Boolean = true; private var _animSpeedState:uint = 0; private var _animState:uint = 1;                //the first sprite of the animation sequence private var spriteTotalTiles:uint = 5;         //the last sprite of the animation private var animIntervals:uint = 5;            //speed of animation //      CONSTRUCTOR public function FlxAnimTilemap($spriteTotalTiles:uint = 5, $animInterval:uint = 10):void { spriteTotalTiles = $spriteTotalTiles; animIntervals = $animInterval; super(); } //      PUBLIC METHODS override public function update():void { if (_animating) { _animSpeedState++ if (_animSpeedState%animIntervals==0) { animate(); } } } public function play():void { _animating = true; } public function stop():void { _animating = false; } public function animate():void { _animState++; for (var i:int = 0; i &lt; totalTiles; i++) { var tile:uint = getTileByIndex(i); if (tile!=0) { setTileByIndex(i, _animState); } } if (_animState==spriteTotalTiles) { _animState=1; } }     } }

Parse XML for iPhone NSXMLParser

December 13th, 2010 | Posted by cjgammon in iphone - (0 Comments)

so here’s how you parse an xml file in objective c, you include the xml in you resources folder in xcode and then we’ll create a class file which acts as an NXMLParserDelegate to parse the file and call specific methods we’ll need to get the xml attributes.

So if our xml looks something like this:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE addresses SYSTEM "addresses.dtd"> <levels>     <level number = "1">         <birds>                 <bird color="red" />         </birds>     </level> </levels>

We have to make a class that acts as an NXMLParserDelegate so the .h file would look something like this:

@interface myXMLParser : NSObject <NSXMLParserDelegate> {       } - (void)parseXMLFile:(NSString *)pathToFile; @end

Then in the .m file we’ll have the parseXMLFile method which takes a path to the xml file:

- (void)parseXMLFile:(NSString *)pathToFile {     BOOL success;         NSXMLParser *addressParser;     NSURL *xmlURL = [NSURL fileURLWithPath:pathToFile];     if (addressParser) // addressParser is an NSXMLParser instance variable         [addressParser release];     addressParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];     [addressParser setDelegate:self];     [addressParser setShouldResolveExternalEntities:YES];     success = [addressParser parse]; // return value not used         // if not successful, delegate is informed of error } // Start of element - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName   namespaceURI:(NSString *)namespaceURI  qualifiedName:(NSString *)qName         attributes:(NSDictionary *)attributeDict {     if ( [elementName isEqualToString:@"level"] ) {         //currentPerson = [[NSObject alloc] init];         return;     }         if ( [elementName isEqualToString:@"bird"] ) {                 NSString *color = [attributeDict objectForKey:@"color"];                 NSLog(@"bird %@", color);         return;     } }

So what we were doing is going through the elements and searching for the ones that match what we are looking for, then we can add them to objects or do whatever logic we need.

To implement this class we just need to allocate it and pass it the path to the file

BirdXML *birdXML = [BirdXML alloc]; [birdXML parseXMLFile:[[NSBundle mainBundle] pathForResource:@"myxmlfilename" ofType:@"xml"]];

That’s pretty much the gist of it!

applescript to hide/reveal hidden files

September 14th, 2010 | Posted by cjgammon in workflow - (1 Comments)

There are certain things I find I do now and again which would be nice to automate. One of them is revealing hidden files, on a mac that means the file name begins with a period, like a .htaccess file. Typically I would go into terminal, write a little shell command and then I’d have a messy desktop and file browsing until I got around to hiding hidden files again. So I wrote the below shell script which will do this switch for me. I’ve even set it up as a trigger in Quicksilver so I can toggle it on and off with a keyboard shortcut. Pretty simple!

on run set hiddenState to (do shell script "/usr/bin/defaults read com.apple.Finder AppleShowAllFiles") try tell application "Finder" to quit if (hiddenState is "ON") then do shell script "defaults write com.apple.finder AppleShowAllFiles OFF" delay 3 else if (hiddenState is "OFF") then do shell script "defaults write com.apple.finder AppleShowAllFiles ON" delay 3 end if on error myError display dialog "problem:" & myError end try FinderCheck() end run on FinderCheck() tell application "System Events" if (name of every process) does not contain "Finder" then tell application "Finder" to launch end if end tell end FinderCheck

orbity now available

September 13th, 2010 | Posted by cjgammon in games | iphone - (0 Comments)

Check out my new iphone game orbity. Don’t forget to comment any feedback.

orbity