Flash_and_Flex_06_2009

Document Sample

Shared by: Pedro Varela
Stats
views:
1029
posted:
12/8/2009
language:
English
pages:
108
Editor’s Note

Solving the problems with OSMF.

Another issue is landing on your plate! I hope you like the online idea for this Magazine – we hope that the step we have made was the right one. If you are a new reader, welcome to our FFD community magazine; if you are one of our regular readers, thanks for staying with us! Since September the FF community had a lot to talk about, especially after Adobe Max in October. We decided to show you more about Open Source Media Framework – together with our authors and Adobe itself. Probably you know something about that, maybe still not enough? What great problem are we solving with OSMF? What is it? What are the benefits? What are the key features? So let us show you how Adobe is changing the landscape with OSMF. Customers already look to the Adobe Flash Platform to create and distribute content, and now with OSMF as part of the Flash Platform, it will be much easier for customers to tie together technology in Flash Player, Flash Media Server, Flash Access, and from the larger Flash ecosystem to create engaging and profitable playback experiences. Take a look at our Special Report on p.8 and also on our OSMF section on p. 22. If you would like to write a small multiplayer Flex TicTacToe game for two clients you should definitely take a look at our FMS section p. 30, where Maxym Golovanchuk demonstrates how to do it. On page 40, Elad Elrom presents how to create video player using Flash Lite and Flash Player 10. If you are not familiar with Flash Player 10 – take a look at p.12 where Louis DiCarro reveals all the FP10 features. Of course, it wouldn’t be much of a developer’s magazine if there weren’t any code in it. The ActionScript section is full of the greatest articles available; Louis DiCarro demonstrates how to make a custom flv player in AS3, Dennis Ippel presents the first open source 3D engine for Flash 10, Elad Elrom in his article on p.60 – helps to understand a designer-developer workflow and build and Air Twitter application... just to name a few of the programming articles in store for you. To balance things off, we take a look at some tools, software, services and book reviews. In other words, there is sure to be something in this issue that will be of interest to everyone. As usual, our deepest thanks go out to all our beta-testers and authors for their hard work and contributions. You truly make this magazine what it is today. Enjoy.



ewa.samulska@ffdmag.com



Ewa Samulska



Editor in Chief: Ewa Samulska ewa.samulska@ffdmag.com DTP Team: Ireneusz Pogroszewski ireneusz.pogroszewski@software.com.pl Przemysław Banasiewicz przemyslaw.banasiewicz@software.com.pl Art Director: Ireneusz Pogroszewski ireneusz.pogroszewski@software.com.pl Senior Consultant/Publisher: Paweł Marciniak Proofreaders: Patrick French, Lee Graham, Ed Werzyn, Russell TangChoon Publisher: Software Press Sp. z o.o. SK ul. Bokserska 1 02-682 Warszawa Poland Worldwide Publishing Software Press Sp. z o.o. SK is looking for partners from all over the World. If you are interested in cooperating with us, please contact us by e-mail: cooperation@software.com.pl

Whilst every effort has been made to ensure the high quality of the magazine, the editors make no warranty, express or implied, concerning the results of content usage. All trade marks presented in the magazine were used only for informative purposes. All rights to trade marks presented in the magazine are reserved by the companies which own them.



Thanks to the most active and helping beta testers:



Russell TangChoon, Lee Graham, Jassa Amir Lang, Ed Werzyn, Yann Smith-Kielland, Justus, Csomák Gábor, Kevin Martin, Charles Wong, Ali Raza, Almog Koren, Izcoatl Armando Estanol Fuentes, Lionel Low, Michael J. Iriarte, Paula R. Mould, Rosarin Adulseranee, Sidney de Koning



To create graphs and diagrams we used company.



program by



The editors use automatic DTP system Mathematical formulas created by Design Science MathType™



Distributing current or past issues of this magazine – without permission of the publisher – is harmful activity and will result in judicial liability.



ATTENTION!



The techniques described in our articles may only be used in private, local networks. The editors hold no responsibility for misuse of the presented techniques or consequent data loss.



DISCLAIMER!



4



06/2009 (8)



CONTENTS

SPECIAL REPORT

08 OSMF art

SUMNER PAINE



InBrief

10 News

GÁBOR CSOMÁK



Tools

12 Flash Player 10 Features

LOUIS DICARRO JACK DOYLE



14 Smarter ActionScript Animation 18 Pivot Table & Charts

FLEXMONSTER



08



20 The Risks of iPhone User Interface Design

BEN GEORGE, NA WONG



Open Media Source Framework

22 Getting started with Adobe Open Source Media Framework

MAXYM GOLOVANCHUK LOUIS DICARRO



26 Adobe’s Open Source Media Format



Flash Media Server

30 Learning Flash Media Server’s Remote Procedure Calls:Tic-Tac-Toe multiplayer minigame

MAXYM GOLOVANCHUK



22



36 A Journey into Adobe Flex Charting Components [Part2]

ALI RAZA



Flash on Devices

40 Building video players for mobile devices

ELAD ELROM



ActionScript Development

50 Creating a Custom ActionScript 3 Video Player

LOUIS DICARRO DENNIS IPPEL



30



56 Harnessing FP10 Power with Away3D Lite 60 Designer-Developer workflow Using Flash Catalyst

ELAD ELROM



80 Migrating from AS2 to AS3

GÁBOR CSOMÁK



84 Unconditional Patterns – The State and Strategy Design Patterns: Part II

BILL SANDERS



60

06/2009 (8)



6



ActionScript Development

90 Know your Language you must! The QUIZ

POWERFLASHER GMBH



Video

92 7 tips for encoding to flash video

CHAIM SAJNOVSKY



Interview

96 Interview with Jameson Hsu: Why Microtransactions will be a game changer for flash game developers



Trainings

98 Academy Class



90



Reviews

100 Shu Player for Adobe AIR 101 Web Analytics Review: Web-Stat 102 Viperdome Xplosive VX 104 Books Review



Profile

106 Portfolio – Danny Kopping

The issue 6/2009 sponsored by Advertisers:

Influxis www.influxis.com...................................................................2-3 Mediaparts Interactive S.A www.page-flip.com...................................................................5 Flexappsstore.com www.flexappsstore.com ..........................................................17 CoffeeCup Software, Inc. www.coffeecup.com.................................................................21 FlashComponents.net www.flashcomponents.net ....................................................29 Wowza Media Systems www.wowzamedia.com .........................................................35 Flash and Math www.flashandmath.com ........................................................43



106

Yogurt3D Game Engine www.yogurt3d.com..................................................................83 Sorenson Media www.sorensonmedia.com .............................................. 94-95 Flex{er} www.flexer.info ..........................................................................99 Flexchallenge Event www.flexchallenge.pl ............................................................103 Digicrafts www.digicrafts.com.hk..........................................................107 Kindisoft www.kindisoft.com.................................................................108



Infosoft Global (P) Ltd. www.infosoftglobal.com.........................................................49 Powerflasher GmbH www.fdt.powerflasher.com ....................................................55 CartoonSmart.com www.cartoonsmart.com ........................................................63 ActionScriptJobs.com http://actionscriptjobs.com/ .................................................69 Flexcommunity.net www.flexcommunity.net ........................................................73 Web Tracking Services, LLC www.web-stat.com ..................................................................77 Electricrain www.erain.com ........................................................................79



Tip of the issue

What are some of the advantages of importing PSDs (Photoshop Files) into Flash?

Jeremy Mayes, Director of Game Production for Arkadium

Importing PSDs directly into Flash has some huge advantages. Each layer of the PSD can be easily designated as a layer or a keyframe in a movieclip’s timeline. Photoshop layer effects, like drop shadows and bevels, automatically get converted into Flash filters. In addition, Flash can automatically crop each layer to its individual contents while retaining its relative position to the other layers. This is incredibly handy if you have a lot of frames of animation and want to optimize them for performance and file size by cropping them as tightly as possible.



06/2009 (8)



7



Special Report



The Open Source Media Framework



A new tool from Adobe for media player development

by Sumner Paine

Adobe’s new Open Source Media Framework is a standard, open framework that dramatically simplifies media player development.



I



n this article, Sumner Paine, the OSMF product manager, will review the key features that save time for both the initial creation and the ongoing maintenance of a media player. These features include: • Creation of the components for a user interface • Integration of still images, audio and video • Control of video quality from various sources • Open and extensible plug-in architecture for: • Content Delivery Networks • Advertising delivery partners • Publishing partners • Analytics partners • Social Media partners • Developer created custom plug-ins With Flash 6, it became possible to incorporate media directly within a website; this paved the way for rich websites to incorporate a variety of media. Some of these sites even specialized in presenting high quality media like premium TV and film content. Developers have been able to build websites focused on media distribution thanks to the Flash runtime’s inherent flexibility which enables additional features and functionality around media playback. Where the original video players outside the browser specialized in playing back a single piece of media, Flash makes it possible to incorporate advertising and tracking around that content and to present it in a customized user experience. In other words, Flash lets you meet the business requirements tied to internet video. However, modern feature-rich media players take a lot of work behind the scenes,



and for content publishers, it’s a huge effort to put the pieces together for the first time. There’s also a big gap between the quality of players developed by big content publishers and those available to the rest of us. It’s almost like a world where TV broadcasters have to build a television before viewers can see their content, and where advertising providers have to get their ads working in each different TV model. At its heart, the fundamental problem is the lack of a standard media player as part of the Adobe Flash platform. The Flash runtime creates endless possibilities, essential in such a fast-evolving space, but by itself doesn’t make it easy to meet those business requirements. In order to build a media player that delivers on that promise, you have to master a set of challenges: in addition to designing a great UI, you must also write the media playback code that performs basic functionality like pause, rewind, multi-bitrate switching, and error handling, and the code to integrate third party services like advertising and analytics. The Open Source Media Framework (OSMF) was created to solve this problem and to make everyone’s life a little easier. OSMF is a framework for building media players on the Flash platform. It’s free code that you can use to build media players, and out of the box it takes care of media playback and integration with services. Does your player need to do multi-bitrate streaming, HTTP streaming, simple progressive download, or content protection? OSMF has code that enables all the latest media features on the Flash platform. Does your player need to talk to an ad server or an ad network, and then report tracking data to a handful of analytics back ends? The OSMF plug-in API means the framework takes care of the



integration with these third party services without any custom coding. The higher level goal of the OSMF project is to accelerate development of media players by providing free and open source code that incorporates the industry’s best practices and takes care of the functionality that should be standard across all players. Content providers can now focus on the user experience of their players, rather than on player plumbing, and service providers can reduce their time spent supporting player integration. It is about making video profitable and making it easy to meet business requirements. Developers can take as much or as little of the OSMF codebase as they need for a player. We’re building OSMF with the guiding principle that the core of a media framework needs to be supportive of any and all media types, and flexible in how it can integrate backend server calls that enable and complement the media experience. The



8



06/2009 (8)



Open Source Media Framework



Figure 1. OSMF Architecture



word experience here is key, because OSMF includes a layout API that enables the player to include multiple media regions in and outside of the media player itself, and a composition API that allows you to present any type of media – video, audio, images, SWFs – in any of these regions. It’s this flexible framework architecture that enables a range of use cases from basic video players that incorporate linear and nonlinear advertising, to complex multimedia experiences incorporated seamlessly into websites. Media playback is just the beginning with OSMF. Your player also needs to talk to other back ends in order to satisfy all the requirements expected of online video today. Getting the video bits from the CDN to the player is just the beginning. The player also needs to get ads, report tracking data, provide recommendations for other content, and integrate with social networks. To enable all this within the player, OSMF supports plug-ins, and we’re working with a variety of partners across these verticals to deliver plug-ins at launch. Also, you can write your own plug-ins to augment the OSMF code base with additional logic to meet your needs.



Today, some use cases call for players to include multiple plug-ins of each type. Even in complex configurations, player performance is a top priority: it needs to load fast and orchestrate the video experience smoothly. But flexibility is also important. Options for third party services are always changing, and content publishers need the ability to change providers as the business requirements change. With both performance and flexibility in mind, OSMF supports plug-ins in two ways: compile them in for performance, or load them dynamically at runtime. OSMF empowers you to build media players tailored to your business needs. By focusing on the two areas of media playback and service integrations, OSMF is



a solution for monetized media playback on the web. Production-ready code that enables the latest and greatest media features on the Flash Platform makes it easier to stay on the leading edge of online video. Standard third party service integrations eliminate the pain of lock-in and allow you the flexibility to change providers at will. One other important aspect of the Open Source Media Framework project is that it is, as the name indicates, open source. The source code is available for free under the Mozilla Public License. In addition, Adobe is leading this open source project and working closely with customers to develop OSMF code. Developing a standard media player framework really lends itself to the open source approach for several reasons. First, the online video space is evolving quickly as technology improves and user behavior adapts, and this inherently necessitates fast-paced development. Second, the nature of the problem – simplifying the complexity of integrating code from multiple parties – means the various parties, technology providers, service providers, and player developers, need to align on how their pieces fit together. And third, different customers have very different needs for the kind and the amount of player logic they want from such a project, and providing the source code lets customers decide which pieces they want to use. Adobe is changing the landscape with OSMF. Customers already look to the Adobe Flash Platform to create and distribute content, and now with OSMF as part of the Flash Platform, it will be much easier for customers to tie together technology in Flash Player, Flash Media Server, Flash Access, and from the larger Flash ecosystem to create engaging and profitable playback experiences. A terrific set of resources is available to get you up and running quickly with OSMF.



The toolkit and documentation is available for download at:

www.OpenSourceMediaFramework.com



Join other industry leading developers in discussions on the developer forums:

http://forums.adobe.com/community/opensource/osmf/developers http://www.adobe.com/devnet/flash/articles/video_osmf.html http://groups.adobe.com/groups/7af970e6e4/summary



Check out the great set of introductory tutorials by R Blank at: And join the brand new OSMF User Group at:



06/2009 (7)



9



In brief

Adobe TV Relaunch



The Adobe TV team recently relaunched the Adobe TV website adding in tons of new features and capabilities. Most importantly, you can access and view your favorite Adobe TV videos faster and more efficiently. In addition, you can customize your own Adobe TV homepage with your favorite shows or series, add in your own comments on shows and episodes, and quickly embed, share or view videos. Be sure to check it out at http://tv.adobe.com/ Source: http://www.adobe.dougwinnie.com/



Exhaustive List of Everything That's New in AIR 2.0



B



elow is an exhaustive list of everything that Adobe is planning to include in AIR 2.0 by Christian Cantrell. The use of the word planning is because even at this relatively late stage, things can change. Consider yourself warned. • Multi-touch: Touch events are similar to mouse events, but on multi-touch enabled devices, you can track multiple touch points simultaneously. • Multi-touch support: Windows 7 and beyond. • Gestures: Applications can listen for multi-touch events, or gesture events (not both at the same time). Gestures are the synthesis of multi-touch events into a single event. • Gesture support: Windows 7 and beyond, Macs running 10.6 and beyond with multi-touch trackpads. • Type of gestures we support: GESTURE _ TWO _ FINGER _ TAP, GESTURE _ PRESS _ AND _ TAP (holding one finger down, then tapping with another -- convention on some Windows devices for bringing up context menus), GESTURE _ PAN, GESTURE _ ROTATE, GESTURE _ SWIPE, GESTURE _ ZOOM , Open Files With Default Application: The new File. openWithDefaultApplication API lets you open a file instance with whatever application it happens to be associated with. This is a good cross-platform way to integrate with other applications since you don't have to know what applications are installed, or where. • OS Download Security Dialog: The new File.downloaded property lets you indicate that a file was downloaded from the network and the OS should prompt the user with a confirmation dialog before opening it. • Supported platforms: Windows XP SP2 and later, Mac OS 10.5 (Leopard) and later No Linux support because Linux doesn't have this concept. • Storage Volume Detection: The new storage volume APIs let you listen for the mounting and unmounting of storage volumes, list accessible volumes, and get information on storage volumes







New 'get flash player' site for iPhone at adobe.com



Apple restricts use of technologies











required by products like Flash Player.... This means, you still wont have a chance to browse the Internet on Iphone with Flash Player. However, CS5 lets you develop for the Apple store. Source: http://flashmobileblog.com/







Adobe MAX



A lot of interesting sessions, and workshops. If you weren't there, you can watch them online at http: //2009.max.adobe.com. The next MAX will be held in Los Angeles, October 24 – 27, 2010. Source: http://max.adobe.com/







• • •



Cynergy Systems Demos Adobe AIR 2 Multi-touch Support



Andrew Trice of Cynergy Systems recently wrote a blog post summarizing his experiences building multi-touch applications using Adobe Flex and an early version of Adobe AIR 2. In his post, he shares a number of excellent video demonstrations, code samples and design considerations that developers thinking about multi-touch development may find valuable. In addition, Dave Wolf, also of Cynergy Systems, wrote a blog post discussing the development of an application for the Adobe MAX keynote. At MAX, Dave recorded a video demonstration of that application from the event floor. Lastly, if you are interested in learning







such as the file system type, whether it's removable, whether it's writable, the drive letter, and the drive label. Native Processes: Launch and communicate with native "out-of-band" processes. Bundle your own native executables, or call executables that you know are already on the machine. This feature requires that your application be installed with a native installer rather than though a .AIR file (we provide tools for building native installers). Types of installers: OS X: DMG, Windows: EXE, Linux: Debian and Red Hat: Package Manager File Promises: File promises let users drag and drop files that either don't exist yet (because you want to generate them on-demand), or that exist on a remote server. We provide an implementation that will automatically download remote files for you and save them to the drop location, and we provide an interface for you to implement if you want to generate files on-demand. Server Sockets: The new ServerSocket API let you listen on a socket so that you can implement inter-application communication, P2P applications, advanced network protocols like FTP, etc. Datagram Sockets: In addition to TCP sockets, AIR 2.0 will now support UDP sockets. Encrypted Sockets: Sockets can now be encrypted using TLS/SSL. IPv6 Support. Access to Low-Level Network Information: The NetworkInfo object lets you enumerate network interfaces on the machine and get access to properties such as whether they are active, their IP address, and their display name. Bind Sockets to Specific Network Interfaces: The new Socket.bind function can be used to bind to a specific network interface (discovered through the NetworkInfo API) rather than always binding to the default. This can allow you to pick the best network connection for your particular application. • DNS Resolution: Use DNSResolver to look up the following types of resource records:



10



06/2009 (8)



In brief

more about multi-touch, please be sure to watch Andrew's talk titled Multi-touch Development with Adobe Flex that he presented at Adobe MAX earlier this month. Source: http://blogs.adobe.com/



• ARecord (IPv4 address for a host) • AAAARecord (IPv6 address for a host) • MXRecord: mail exchange record for a host • PTRRecord: host name for an IP address • SRVRecord: service record for a service • Configurable HTTP Idle Timeout. URLRequest.idleTimeout and UR LRequestDefaults.idleTimeout let you specify the amount of time (in milliseconds) that a connection will remain open before it receives any data. This is useful for things like long polling. • Local Audio Encoding: Access audio data directly from the microphone. You used to have to send the data to a server and access it from there, but now you can do it entirely on the client. • Global Error Handling: Global error handling lets you handle all uncaught errors (both synchronous errors and asynchronous error events) in one place in your code. (More information on Global Error Handling.) • Accessibility: AIR 2.0 will have the same level of support for screen readers as











• •











Flash. (More information on accessibility in AIR 2.0.) NativeWindow and Bitmap Size Increases: The maximum size of a NativeWindow and Bitmap instance used to be 2880x2880. In AIR 2.0, it will be 4094x4094. Improved Printing. Vector printing on Mac (already in FP 10) and Complex transparency support. Nested Transactions. SQLite will now support nested transactions. Exiting Event on Shutdown. In AIR 2.0, you will be able to handle the Event.EXITING event when the computer is shutting down so you will have an opportunity to save any unsaved work or data. WebKit Upgrades: Nitro JavaScript Engine (SquirrelFish Extreme), CSS3 Module support (2D transformations, transitions, animations, etc.), scrollbar styling, break up text across columns, latest Canvas enhancements. General Optimizations: Lower CPU utilization when idle, lower memory consumption.



Flash CS5



The next major release of Adobe Flash Professional was unveiled at Adobe MAX 2009. The beta download will be available before the end of the year at labs.adobe.com. Some of the new features include: • Applications for iPhone – Publish ActionScript 3 projects in Adobe Flash Professional to run as applications for iPhone. New text capabilities via the Text Layout Framework (TLF) – Advanced styling and layout, including right to left text, columns, and threaded text blocks, let you work with text in Flash like never before. XML based FLA files Code Snippets panel Flash Builder™ integration Improved ActionScript editor







• • • •



Source: http://labs.adobe.com/



3D Page Turn Plug-ins for Lightroom



Source: http://blogs.adobe.com/cantrell



Flash Player 10.1: The web had it coming



PageTurn 3D Gallery is a plug-in for Adobe Lightroom, which use to make instant flash gallery. Now photographers can make their own 3D Page Turn flash gallery without using Flash. Extremely easy-to-use interface let you create gallery with only a few clicks.



Highlighted features



A



t MAX, Adobe announced the new Flash Player (10.1) features. The most interesting are:



• Diverse platform support: Adobe Flash player 10.1 will work on almost all smartphones, with support for Microsoft Windows Mobile, Android, Palm webOS, and Symbian S60. (Still no iPhone support) • Hardware acceleration on mobiles: Mobiles with their limited memory and slow CPU have perhaps the most to gain from GPU accelerated content. • Multi-touch support: Multi-touch is the way of the future, and Flash Player 10.1 (as well as AIR2.0) will expose new APIs which allow better support for multitouch input and gestures. • Video hardware decoding: More smoother playback of full screen HD video on Flash Player. With new HTTP streaming



and content protection features with Adobe Flash Access, premium audio and video content can be securely delivered within the browser. • Global error handling: the new global error handler enables developers to write a single handler to process all runtime errors that weren’t part of a try/ catch statement. Improve application reliability and user experience by catching and handling unexpected runtime errors and present custom error messages. Of course it'll be faster, better, and will use less battery. Interested? Head to labs.adobe.com! Source: http://labs.adobe.com



CSS Style Sheet Support? User can customize the gallery for background color, styles, navigation menu, and site title by css. Live Preview? All changes can be preview in the WYSIWYG Live Preview Panel in Lightroom. Book navigation bar – Gallery included an easy to use navigation bar. For more info, you can visit our website. h t t p : / / w w w. d i g i c ra f t s. co m . h k / components/LightroomPageTurn3DGal lery For more flash, flex and dreamweaver products. You can visit Digicrafts website. h t t p : / / w w w. d i g i c ra f t s. co m . h k / components/



News selected by Gábor Csomák



06/2009 (8)



11



Tools



Flash Player 10 Features

by Louis DiCarro

ActionScript Developers and Flash Animators connection to the end user is the Flash Player. With the release of version 10 of the player, Adobe has added many new features that we will review here.



Level of difficulty



W



What you will learn…

• The new features of Flash Player 10



What you should know…

• You should be familiar with the Flash Player



hen Macromedia acquired the FutureSplash Animator in 1995, it got itself a technology for bringing vector based to the web using Netscape's then new plug-in technology. Prior to the release of FutureSplash and Flash, the only way to get animation on the web was to use Java. At the time, the plug-in only had support for vector based animations – there wasn't even sound support. Through the years, Macromedia then Adobe continued to make improvements to the technology adding support for audio, bitmaps and scripting in the early years and getting more advanced as time progressed. Earlier this year, Adobe has released the latest version of the player – setting it at version 10. With this release, a lot of new features have been packed in that bring the plug-in to a new level. Some of the highlights include 3D to correspond with the release of Flash CS4, custom filters and effects, advanced text support and expanded support for new ActionScript classes. We are going to take a look at some of the new features and get some detail of what is involved with them.



and z planes, rotation and resizing of the objects. The transformations can also be applied to 2D objects to gain perspective in 3D space.



Drawing API

In addition to the 3D capabilities, a number of features have been added to the Graphics API. The added z and scaleZ properties, as mentioned earlier, give developers more control over display objects in 3D space. Objects can also have textured meshes applied to them in 3D space which will improve upon the 3D effect in animations. Classes have been added to the graphics classes that expand upon the 3D capabilities but also drawing from code. The GraphicsTrianglePath class stores the geometry of a 3D polygon that includes the mapping data. The GraphicsBitmapFill and GraphicsEndFill both help create shaders for display objects, discussed further in the next section. Bitmaps handling has been improved to accept larger sized images of over 16 million pixels. This translates to an image that is about 4096 x 4096 pixels. There have been an improvements with the use of graphics cards to render SWFs, which will also improve the ability of bitmap and movie rendering. Using graphics card will speed up the calculations that it takes to render not only bitmaps, but filters, blends and video overlays applied to the elements.



3D Effects

The release of Flash CS4 brought new tools to the authoring environment with the addition of 3D Rotation and 3D Translation tools. The plug-in now supports transformation of graphics in 3D space. In the past, developers and animators had to fake 3D with some tricky ActionScript or using timeline based animations. In addition to the tools added to CS4, an easy to use API (Application Programming Interface) has been added to AS3. The most important and easy features added to AS3 is the z and scaleZ properties to the display containers. These two properties allow developers to easily manipulate objects in 3D space without any special setup. Any 2D display object can now have their depth properties manipulated. There are other AS3 3D libraries available as open source that will take advantage of the Flash Player engine in the future. Also included is the Matrix3D that is part of the flash.geometry package. Matrix3D provides methods for transforming the position and orientation of a 3D object. Transformations included positions on the x, y,



Custom Filters and Effects

A new filter and effect engine has been added using Adobe's Pixel Bender Just in Time (JIT) compiler. Adobe's AfterEffects uses the same Pixel Bender technology in some of its filters and effects. This means that the same advanced and complex effects can be applied to SWFs. The Pixel Bender technology was originally released in Adobe Labs for developers to try out while the technology was being developed. It is based on a markup language called OpenGL Shading Language (GLSL) that has a C-like syntax used to create complex filter algorithms applied to images, videos and other media. While the filters are often attributed to the visible media such as images and video, Pixel Bender can also be applied to sounds and math functions. These functions,



12



06/2009 (8)



Flash Player 10 Freatures



which could slow a SWF down to a crawl, greatly improve their processing speed by using hardware acceleration. This gives developers very powerful data manipulation without the restraints that ActionScript can pose with additional speed of hardware access. The filters are created externally from Flash or Flex using the Pixel Bender Toolkit that can be downloaded from Adobe at http: //labs.adobe.com/downloads/pixelbender.html. The filter is created and compiled through the toolkit and imported into AS3 project using the Shader class and URLLoader. Once the filter has been assigned to the Shader object, it can be used as any other object in your project.



among multiple field and multiple columns allows the text to re-flow as the movie is resized at run-time as it does on a traditional HTML page.



Sound Capabilities

The Flash Player now works with sounds on a lower level than in the past. This capability allows code to extract audio data from a MP3 directly from the bytes of the audio file. Doing so allows the developer to manipulate the data to apply filters and mix audio in real time. The developer now has finer control of the audio that is played through the movie. Filters can be applied to the audio using the Pixel Bender technology releasing developers to create their own effects. Enhanced sound applications have started to appear on the web that apply this technology. Most notably is HobNox Audio Tool (http://www.hobnox.com/ audiotool) which simulates electronic music creation with synths, drum machines and effects. The player now also supports the generation of sound through the Sound class allowing the synths to create their own waveforms and not rely on pre-recorded sounds. Several sound features that were talked about in the past did not make it into the player just yet. One is the sound extraction of data from the microphone, which would allow the program to manipulate sound without needing to save it first. It is possible to receive sound through the microphone, but you can not process the sound as it is streamed in.



In additional to the data checking, typed vectors speed the performance of the array because it knows what kind of data it is expecting and can reserve the proper amount of memory for the variables. The vectors length can also be set and stay unchanged to allow the memory to stay at a set size and the program not have to worry about allocating extra memory to the function.



File Handling

Web based applications now have the ability to upload and download files directly through the application. This allows the movie can now process the data of the file without having to pass all the data to the server first. The classes give the plug-in direct access to the binary data to manipulate the stream but is still safe for the end user. This improvement gives a long-awaited capability to remove the reliance on backend technology to manipulate files. The web app will also have access to the system clipboard data that is sandboxed to keep it from being used maliciously. Routines can be added by the developer to handle custom copy and paste methods. Adding this capability allow the end user to experience web apps that are closer to desktop applications.



Advanced Text Support

Adobe first gained popularity as a company by creating the PostScript page description language. This technology relied heavily on the proper display of text and fonts on screen as well as in print. This experience is one benefit many designers and developers have been waiting for to be added to Flash for a long time. Text has traditionally been difficult to deal with in Flash. The final display did not always match what was set in the authoring environment and the layout of text has not been able to follow traditional type setting. While this may not be much of a problem to data-driven applications, for most developers working with clients to produce RIAs, it is a huge issue. The new version uses the Saffron Engine 3.1 which displays high-quality and scalable type on multiple outputs. The type engine improves clarity because it was built for both CRT and LCD displays with sub-pixel rendering. It handles most font formats for both Latin and Glyph based languages. The engine also keeps its clarity despite filters and other transformations applied to the text. Because it can handle Latin and Glyph based languages, it is now possible to build multilingual applications without having to build multiple versions of the same app. The improved layout engine will be able to handle the different languages because it can handle not only Left-to-Right reading languages but Right-to-Left and Top-to-Bottom. This means you should be able to use the same text field in your application for all of these languages. Traditional type setting features are now supported or improved from earlier versions. These include ligatures (two or more characters combined because of their shape), multiple columns, text wrapping around images, vertical text and flowing text across multiple fields. The text flow



Color Correction

Movies can now use the monitor's native ICC profile to display animations. Truer color and less change to how objects are displayed on different platforms give the developers more predictable results when publishing movies. The SWFs can be converted to standard RGB when displayed on the user's computer using the profile. An additional AS3 function has been added, hasColorCorrection, to test for the feature of the system.



Speex Audio Codec

A new open source voice codec has been added to improve the handling of audio data that is voice based. The codec supports data passed into the movie based from the microphone and supports new formats such as ADPCM and HE-ACC as well as MP3. Several new classes have been added including sound.extract and sampleCallbackData.



Conclusion

With the release of Flash Player 10, Adobe has added features to push the platform in new directions. Many of the features break the movie out of the browser/computer model and make Flash apps able to accept data as well as display it. As new devices and platforms are released, the Flash Platform becomes an acceptable format for delivery of content and applications. Features will continue to be added and improved as Adobe expands the Flash Platform and new delivery devices become available. The current round of improvements not only additional features, but also work to make development time quicker and more stable.



Vector Data Types

Vectors are typed arrays as you would type any other variable. By setting a variable type to an array, it is forced to only receive that kind of data. For example, if a vector is set to type int, you could pass in a simple number such as 1, 70, or 3568 but not a string such as string or a sprite. Passing in a piece of data that the vector is not set for will cause an error in your code. This will save the developer from having to write their own handlers to check the data before it is stored in the array.



On The 'Net

• • • Flash Player – http://www.adobe.com/products/flashplayer/ Pixel Bender Toolkint – http://labs.adobe.com/downloads/pixelbender.html HobNox Audio Tool – http://www.hobnox.com/audiotool



LOUIS DICARRO

Louis DiCarro is a consultant based in NYC and has been working with Flash since the first version. He has taught web development at the college level and has worked for numerous large clients. He can be reached at louis.dicarro.ffd@gmail.com



06/2009 (8)



13



Tools



Smarter ActionScript Animation

by Jack Doyle

One of the reasons we all love Flash so much is because it offers an incredible amount of power in terms of animation. The thought of a swf with no motion is, well, just weird. But what’s the best way to create animation? Sure, the Flash IDE offers timeline tweens but what if the values must be dynamic or you use a different development tool or you don’t want the animation to be dependent on the frame rate? Adobe’s Tween class to the rescue, right? Think again.



A



dobe’s tween-related classes are woefully underpowered, slow, and cumbersome. While they can technically accomplish almost any tweening task with enough supporting code, it’s like trying to cut down an Oak tree with a butter knife – why would you do such a thing when there are professional tools available that chew through the task in no time and offer significantly more capabilities? Under identical stress levels, the Adobe Tween class slowed a swf’s frame rate to 2fps whereas TweenLite cranked along at 40fps. The real-world performance improvement can be staggering when you put a solid tweening engine to use. Then factor in all the added features, ease of use, and streamlined workflow that a 3rd party tweening platform like GreenSock’s offers and it becomes clear why most professional developers steer clear of Adobe’s built-in solutions. With the recent release of version 11 of the GreenSock Tweening Platform, ActionScript animation has been taken to an entirely new level. Before I explain all the exciting advances, let me step back and identify the main characters and what they do: •

TweenLite



– a lightweight tweening class that serves as the foundation of the platform. A TweenLite instance can tween ANY numeric property of ANY object and is often the only tool you need. It has all the essentials packed into about 4.7k. You can easi-



ly add capabilities by activating plugins which are completely ActionScriptbased. • TweenMax – extends TweenLite, adding useful (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, timeScale, and more. TweenMax automatically activates 19 commonly-used plugins and the AUTO overwriting mode, prioritizing a rich feature set and convenience over small file size. • TimelineLite – tuck TweenLite and/ or TweenMax instances into a TimelineLite to organize them over the course of time, just like a MovieClip timeline. Then you can pause(), resume() , reverse(), play(), or restart() the entire sequence anytime. Tweens can overlap or there can be gaps between them. You have complete control over the placement of every tween. Even nest timelines within timelines! Add labels and gotoAndPlay() or gotoAndStop(). Set the currentTime property to skip to any point immediately, or tween it to fastforward/rewind. There’s also a timeScale property for slowing down or speeding up a timeline. All this for about 2.5k. • TimelineMax – extends TimelineLite to add useful (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo, currentLa-



getLabelAfter() , and more. TimelineMax is the ultimate sequencing tool. • TweenNano – a ridiculously small (1.6k) basic tweening engine for projects that cannot afford even TweenLite. getLabelBefore() ,



bel,



tweenTo() ,



The Basics

There’s a detailed getting started article at the GreenSock.com web site, so I won’t spend much time here on the basics. A simple tween would look like this:

TweenLite.to(mc, 1.5, {alpha:0.5, x:100});



This tweens mc’s alpha and x properties from whatever they are at the time the tween begins to 0.5 and 100 respectively over the course of 1.5 seconds. Nothing special here aside from improved performance and the fact that you can tween as many properties as you want with one line of code. But we’re just getting warmed up.



Kicking it up a Notch

What if you want to tween filters, hex colors, volume, tint, frames, saturation, contrast, hue, colorization, brightness, skewX, skewY, or do bezier tweening, orient an object’s rotation in the direction of the bezier, round values before they’re applied, automatically rotate in the shortest direction, scale/rotate as though the object has a cus-



14



06/2009 (8)



Smarter ActionScript Animation



tom registration point, apply width/height tweens with setSize(), automatically toggle the visible property to false when alpha hits 0, and more? What if you want to schedule the tween’s start time, update its destination values smoothly anytime, or reverse it, all while ensuring that the tweens are perfectly synchronized and protected from premature garbage collection? No problem; one line of code can accomplish any of this. Ever had multiple tweens that conflicted with each other? For example, what if a button has a 0.3-second rollover tween that fades an object up and a 0.6-second rollout tween that fades it back down? What if the user rolls over/out/over/out quickly? See the problem? A basic tween class won’t suffice – you need a smart, integrated platform that can handle these issues elegantly, efficiently, and automatically, giving you advanced controls when you need them. That’s precisely the goal of the GreenSock Tweening Platform.







polymorphism



Version 11: A Whole New Level of Tweenable Goodness

There just isn’t enough room in this article to explain all the new capabilities and advancements in version 11. Visit greensock.com to get the details. I’ll mention a few of the highlights here: •

motionBlur* – a new plugin that applies



resume() , and restart() are all part of a common TweenCore class. This means you can create a class variable, for example, and type it as a TweenCore and populate it with a TweenLite, TweenMax, TimelineLite, or TimelineMax and use common controls. reverse() play() , ,







pause() ,



Unique Workflow Possibilities

Some of the new plugins have developers salivating, but I think the most significant advancement has to do with the new TimelineLite and TimelineMax classes. They may change your entire animation workflow because you no longer need to think of animation on a tween-by-tween basis. Imagine, for example, a developer creating classes with common animateIn() and animateOut() methods that each return a TimelineLite instance. A designer/animator could then focus his attention on only those methods, crafting slick animations in the form of TimelineLites that get spit back to the developer to do what he wants with. They could get tucked into a parent TimelineLite/Max instance or just play on their own.



















a realistic directional blur that varies its strength dynamically based on the velocity and angle of a DisplayObject’s x/ y movement. That’s right – the blur angles in any direction, not just horizontal or vertical. physics2D* – another new plugin that delivers simple physics functionality for tweening a DisplayObject’s x and y coordinates based on a combination of velocity, angle, gravity, acceleration, accelerationAngle, and/or friction. dynamicProps* – allows you to associate a function with a property so that every time the tween is updated, it calls that function to get the end value for the associated property. You could, for example, tween an object’s x/y coordinates to wherever the mouse is using functions that return mouseX and mouseY. Advanced sequencing – TimelineLite and TimelineMax will change the way you think about animation. More on that later. useFrames feature – allows you to base the timing of your tween on frames instead of seconds. This means an ActionScript tween can be synchronized with a MovieClip’s timeline animation.



There are interactive examples of virtually all of the plugins in the Plugin Explorer which is on the web site and in all the downloads. It not only visually demonstrates each plugin, but also writes the associated code down below so that you can get familiar with the syntax. It’s a great way to learn. *A few non-essential plugins are membership benefits of Club GreenSock



06/2009 (8)



15



Tools



Listing 1. Example code

//import classes and activate any necessary plugins here (omitted for space) public class PresentationSlide {



function animateIn():TimelineLite {



var timeline:TimelineLite = new TimelineLite();



timeline.append( new TweenMax(this, 0.5, {autoAlpha:1}) );



timeline.append( new TweenLite(mc1, 1, {y:100, motionBlur:true}) ); timeline.append( new TweenMax(mc2, 1, {tint:0xFF0000, x:60}), 0.5); } return timeline;



function animateOut():TimelineLite {



var timeline:TimelineLite = new TimelineLite();



timeline.insert( new TweenLite(mc1, 0.5, {y:0, motionBlur:true}), 0); timeline.append( new TweenMax(this, 0.5, {autoAlpha:0}) ); } return timeline; timeline.insert( new TweenMax(mc2, 1, {tint:0x0000FF, x:300}), 0);



}



//then in the Main class, build the presentation by progressively appending the timelines, nesting //them in a parent "_presentation" TimelineLite that can be easily controlled. public class Main { private var _presentation:TimelineLite; function buildPresentation():void { _presentation = new TimelineLite({onComplete:onFinishPresentation}); _presentation.append( slide1.animateIn(), 0); _presentation.append( slide1.animateOut(), 8); _presentation.append( slide2.animateOut(), 6);



_presentation.append( slide2.animateIn(), -0.5); }



public function togglePause(event:MouseEvent):void { } _presentation.paused = !_presentation.paused;



public function seek(time:Number):void { } _presentation.gotoAndPlay(time);



public function onFinishPresentation():void { } trace("presentation finished");



}



The append() and appendMultiple() methods make it easy to progressively build animations, so if one of the earlier tweens/ timelines gets lengthened or shortened, the ones that are appended after it get adjusted accordingly. Here is some example code: see (Listing 1). Another common scenario involves button rollovers/rollouts that affect a sequenced animation. With TimelineLite/Max, you can create the sequence once, and then simply



play() on rollover, and reverse() on rollout



for a smooth effect.



Conclusion

If you haven’t tried the GreenSock Tweening Platform yet, do yourself a favor and audition it for your next project. I think you’ll find it to be surprisingly intuitive and it may open up a world of possibilities while at the same time boosting performance. I hear all the time from developers who were shocked by



how the platform revolutionized the way they worked. There is a reason it has quickly become a standard in the industry. If you’ve been a loyal TweenLite or TweenMax user for a while but haven’t seen version 11 yet, there has never been a more exciting update. Fire up your web browser and head over to GreenSock.com. It’s a free download and there are plenty of learning resources available. Happy tweening!



16



06/2009 (8)



Tools



Flexmonster Pivot Table & Charts:

powerful reporting component for Flex and Web applications Flexmonster Pivot Table & Charts component provides standard Flex with additional powerful reporting and visualization capabilities. Developers get ready-to-use interactive Pivot Tables and Charts exposing business data in any desired representation. Written in pure ActionScript 3.0 it renders millions cells immediately.



S



ee live demo and download at http://www.flexmonster.com/pivot. Web applications for business are becoming more usable with Flex and Flash. Adobe Flex enabled rich and really convenient user interfaces for business users. But there is one big pain. There are NO components in Flex able to work with huge data storage which every company already accumulated. Tons of statistics in the companies are being stored in spreadsheets and Excel files, databases, OLAP cubes. Data itself is terribly expensive to collect and store but almost useless without smart tools for visualization and analysis. Old-fashioned reports and charts are just very limited and inadequate in the modern every day changing world. Decision-makers dream to have the tool for selecting the part of data they need, consolidate it, and analyze in a customizable personalized view thus improving the decision-making speed and quality. Business users demand the data analyzed and visualized immediately, with convenient interactive features to drilldown to the smallest fact and quickly get back to the bird-view reports. More and more companies are looking for web based data analysis tools, because, the amount of data which these organizations have to analyze, preferably online with shared access, constantly increases. People need fast, simple, but powerful tools for this. Flex provides the initial layer and infrastructure for this. Standard components like AdvancedDataGrid and OLAPDataGrid from Flex 3 meet the very initial basic developer needs to load and expose the data to the users. These standard components are suitable only for small data portions, and becomes absolutely slow and useless for traditionally big data amount. Unfortunately developers don't have cheap ways to optimize the features and behavior of these components.



Flexmonster Pivot Table & Charts component provides standard Flex with additional powerful reporting and visualization capabilities. Developers get ready-to-use interactive Pivot tables and charts exposing business data in any desired representation. This component is written in pure ActionScript 3.0, lightweight, but has many features which we, Flex developers, were looking for so long. It can be used for multidimensional data visualization, advanced reporting, interactive drill-down and data analysis. Furthermore, the component can be easily integrated into any Flex application to replace AdvancedDataGrid or OLAPDataGrid. With this component developers get interactive Pivot Charts and tools for advanced data manipulation like filtering, sorting, grouping, aggregations, etc. Also, the component can be used in any web based data analysis system, as powerful standalone reporting tool. Normally developers save up to 80% of effort when using the component to add reporting and visualizations into the business applications.



tion. The comparison of OLAPDataGrid with Flexmonster Pivot Table & Charts is provided in Table 1. Flexmonster Pivot Table & Charts: Features and Advantages • Different Data Sources. The component supports different data sources, such as: • OLAP Cube via XMLA protocol (MS Analysis Services); • CSV files (for example, exported from Excel); • XML from custom web services; • OLAP data via XMLA protocol from Mondrian; • OLAP data via XMLA protocol from SAP. • Works Fast with Huge Amounts of Data. The component works fast with huge



Standard OLAPDataGrid VS Flexmonster Pivot Component

Many developers have been waiting for Flex 3 OLAPDataGrid as the completely functional on-hands solution for visualization of multidimensional OLAP data. But many of us were disappointed with it. Currently its limitations and bugs are known and widely discussed. OLAPDataGrid in Flex 3 is not full-featured Pivot Table. Flexmonster Pivot Table & Charts component has many critical features which are just absent in the OLAPDataGrid. If your Flex application works with complex data and is used OLAPDataGrid or AdvancedDataGrid to visualize them, you can easily switch to Pivot Table and Charts component and bring its advantages to your web applica-



Figure 1. Pivot Table and Pivot Charts



18



06/2009 (8)



Flexmonster Pivot Table & Charts



Table 1. Comparison of standard Flex OLAPDataGrid and Flexmonster Pivot Table Features Collapse & expand (drill-down) Large volumes of data (millions of facts) Standard OLAPDataGrid Only rows (columns can not be collapsed or expanded) With 3000 records – rendering and scrolling are very slow Needs additional non-trivial data preparation within complex data structures • collapse/expand rows • sorting Flexmonster Pivot Table & Charts Both rows and columns (see Figure 2) With 1 million records works fine – both rendering, filtering, scrolling are acceptable for users Accepts comma separated values file (CSV) or data URL. Can take data directly from OLAP server – only connection string required. • collapse/expand rows • collapse/expand columns • drag fields to rows and columns on-the-fly to configure view • switch fields to rows and columns • filtering • sorting • change aggregation type The same data is simultaneously available in both table view and chart view.



Data source



Ability to configure reports on-the-fly



Charts



Does not incorporate Pivot Chart visualization of data (3rd party components are required)



amounts of data. It is optimized to work with millions of facts. • works well with big data sources • shows millions of facts at once • There is a sample on www.flexmonster.com which shows how Pivot Table grid renders 10 millions of cells. • Advanced Manipulation with Data. Excel-like features provide users with interface they got used to. Users can filter, sort and group every row or column (see Figure 4) in the report in most friendly way. The component has powerful tools for manipulating data, such as: • drill-down, • filtering,



























Figure 2. Pivot Table collapse & expand on columns



• sorting, • grouping, etc. Pivot Charts. Pivot Charts is the alternative to table way of the data visualization. They are interactive. You can drill down from the summary data to details on charts. Predefined Reports, Saving Reports. It is possible to create a predefined report via configuration; define columns, rows, values, and filters to get exact data you need immediately after the Pivot Table is opened. Also, the functionality of saving reports is enabled via API. Customizable Skins, Styling by CSS. Developers can customize the look of the grid and all interface elements using standard CSS. Configurable UI. You can easily configure UI, define which UI elements are needed and which ones should be turned off. XML/FlashVars Configuration. Pivot Table component can be configured via XML or Flash vars. Easy to Integrate. The component can easily be embedded into HTML page. It can be integrated with Flex application (Pivot Table & Charts component is available as SWC). It also can be effectively integrated as front-end part of BI solutions with any back-end programming languages or frameworks (C#, PHP, Ruby on Rails, ASP, JSP, etc.).



The component is ideal to use in the following scenarios

Web Interface for OLAP Data If you already have configured OLAP server on your beck-end, you can visualize with Flex OLAPDataGrid (and spend several weeks for development, data preparation and optimization). Or you can just put connection string to Flexmonster Pivot Grid & Charts component to see it working! No need of long integration, complex data structures, big application size or bad performance. It will start working within minutes. Database-driven Reports (no need of OLAP server) Popular OLAP servers are often very expensive, open source solutions don't cover your requirements. If you don't want to waste your time on configuration of own multidimensional cube we propose to use this component. Flexmonster Pivot Table & Charts component can work with plain text data or XML and compose complete multidimensional reports on-the-fly. Just insert component into your web site and immediately get powerful reports and charts online. Simple reports Your customers don't know what multidimensional data is but want to see information in most friendly way. You can predefine desired report and Pivot Table & Charts will show them simple grid or charts. It's really easy. Flexmonster Flexmonster provides custom Flash & Flex development, BI solutions, unique OLAP and database-driven Pivot Tables & Charts and Salesforce Rich UI components.



Figure 3. Pivot Charts drill down



Figure 4. Filtering and Sorting



06/2009 (7)



19



Tools



The Risks of iPhone User Interface Design

by Ben George, Na Wong

Benjamin George and Na Wong from Sourcebits’ design team are sharing their thoughts about risky areas of iPhone user interface design.



E



verything is designed, few things are designed well. – Brian Reed. For the past two years, the iPhone has housed some of the most poorly designed applications you could imagine. The hype surrounding iPhone has prompted many designers across the globe to try their skills with the new mobile medium. The result are literally thousands of various applications which are hardly usable and counter-intuitive. However, some developers invest a lot of time and effort in creating usable and original user interfaces. The iPhone is one big constraint – no physical keyboard, small screen estate, touch screen control only, a few buttons – so designing applications for the iPhone is an exercise in building smart, simple software. Apple does provide basic guidelines along with their default applications to show us how to use the native UI best, using these elements provided we can overcome many of the devices’ limitations. Smart design is always a balance of expressive trends, classical layout aesthetics, detailed research and user motivations.



• Less time spent on design and development. • The risk of user disliking your app’s looks is smaller because they are already accustomed to native iPhone UI and they most probably love it. Cons: • It is more difficult to distinguish application’s uniqueness at a first glance. • Limited functionality with regards to the interface. • It is not possible to implement particular, unique features. Custom UI: Human creativity is always trying to push things to the limits, trying various methods to innovate, Hence customizing the iPhone UI can only be natural. Many of them have colorful, vibrant, sleek interfaces with cool animations, using real-life objects and environment to interact. This might initially be a fairly new ground to the average user, but depending on it’s design, it could end up being an exquisite user experience. Pros: • Stands out from the other apps. • Less limitations in the process of UI components creation. • Easier for branding, like a custom logo or a branding color in use. • Visual element with the help of textures can help users be more comfortable on the app, for example using a radio like interface for a radio app. Cons: • Longer development time on coding these custom UI elements.



• The challenge of providing minimal and elegant solutions is much greater than with native UI elements. • May have a longer learning curve. • Runs the risk of overdone UI which inturn is badly designed UI. • Bigger application file sizes.



Finishing Note

Using the default Apple UIKit elements, in fact most of the applications in the App Store and those coming from Apple get along fine with the built-in interface elements. Apple's built a solid framework to use when creating applications, but some app developers aren't fully satisfied so they take visual and interaction designs into their own hands. This can be a showcase of some beautiful interface design decisions but one has to be careful as it's easy to go overboard and mess things up. One has to choose wisely if the application needs to have the default iPhone UI or have a custom UI since this decision can make or break an app. The lowest denominator is always the same: the user. You can have the most beautiful and smoothly animated interface but if the visuals overburden functionality, disguise workflow paths and distract the user – you can throw your carefully crafted interface to the trash.



Design Decision: Native iPhone UI vs Custom UI

Native UI: Users want to get their work done. Getting stuff done quick means that the designer has to understand and get into the flow of the OS and create an application which requires zero explanation for the end user to operate, for which using native iPhone layout and elements is the natural solution, saving both time and energy. Pros: • Native UI elements which provide user a familiar environment.



20



06/2009 (8)



Web Form Builder

by John Shaffstall



Create Web Forms With Ease. No Scripts, No HTML, No Coding!



G



etting data from a viewer can be like pulling teeth. Web Form Builder from Coffeecup is a tool for the job. On the internet, there is a lot of pushing going on. But not a whole lot of pulling. And there are reasons for that. But needless to say, getting information to a website is not something one tends to do much of. We like to see what a website has to push at us. Pulling information from a user into a website can be considered by some to be a luxury. It’s not easy setting this up. However, more and more websites want to know more and more about their viewers. This demands input from the viewer. This demands websites contain forms for capturing information that the viewer has to provide. As easy as this may sound, it’s not. There is much that needs configuring first and Web Form Builder will help do this. It is designed to fill this specific niche of work by automating the processes and keeping the developer working on the form design. Forms are a websites means of acquiring data and this tool provides the means to create the forms.



My Trial Experience

I surfed the Coffeecup website a bit then downloaded the Web Form Builder 8.0 trial version. All went well. The installation automatically started the app and I was immediately presented with a Theme dialog for choosing a base Form to start with. Only ten of these templates are provided and you can easily add your own. I choose the Sherbert theme from the Contacts Form dropdown list and clicked Open. A Quick Tips dialog popped up with some handy advice, I clicked Close and am now looking at the application. Small yet tailored to its needs, it is quick to interpret. I wasn’t that impressed at first but quickly realized that until you receive emails with viewer data or create a file with viewer data or fill a database with viewer data, this whole Web Form Builder thing isn’t worth a hill of beans.



I think Coffeecup thought so too. Provided by the app is a Settings dialog that allows you to setup the Email Response, Text File Saving and MySQL Database Entry as easily as possible. There are things one needs to know that a normal person may not, but help from their internet provider can solve any issues encountered. You can even allow the viewer to upload a file of their choosing to be sent to your website. Nice functionality. The actual building of the Form had a few unpleasant moments and there are some shortfalls with it but this is not it’s strong point nor should it be. Remember, getting the data is the main intent here, not a beautiful Form. A nice looking and working form yes, but it will not some over-the-top eye-popper. A word of advice: set the Subdivisions value in the Grid dialog to 10. Things will line up better with the ruler. Also, don’t use a background image right off the bat. It will hide the grid which you will want when placing controls into the form. For $39, this is one tool I’ll be adding to my workbench. www.coffeecup.com



You can also use the coupon FLEX for 15% off any order



Discount coupon



Open Source Media Framework



Getting started with Adobe Open Source Media Framework

by Maxym Golovanchuk

Open Source Media Framework (OSMF) is an open developer’s framework, which is currently in public prerelease, for building rich and robust players and media applications bases on the Adobe Flash Platform.

Level of difficulty



O



SMF is a set of pluggable component allowing to avoid the complexity of player development and focus on providing better user experience. In this article we will learn the basic of OSMF and build a small player, using OSMF and Flash Builder, that can be embedded into an html page.



Installing OSMF

What you will learn…

• Installing and setting up OSMF sdk • Writing simple component to play video in flex with osmf • Using OSMF traits



What you should know…

• He basis of flex development



We are not going to talk a lot about the theory of video and OSMF (there are a lot of resources out there in the Internet on these issues). Instead, we will start by developing our first OSMF player, discussing principles along with practice. The first step will be installing OSMF. As it is seen from the title, OSMF is an open source project and can be downloaded and used free of charge. To download the source, go to http://opensource.adobe.com/wiki/ display/osmf/Downloads (or enter osmf in your search engine and it should give you a few links to the original source). From there download the latest Source ZIP file



(version 0.6 at the moment of writing this article). Unzip the content to the suitable folder and we are ready to create and code our project. This article is aimed for Flash Builder, so, to start we need to create a new project with Web Application type, Flex 4.0 SDK and None Server technology. Name your project as you like; it this article we use OSMFPlayer as a Project name. Before we begin writing the actual code, we should add OSMF to a Library path. Go to Project -> Properties menu, select Flex Build Path in the left list and Library path tab on the right. Press Add SWF... and browse for MediaFramework.swc inside recently unzipped OSMF source. Select Merged into code option for Framework linkage. Accept the new properties and press Ok. There is one more thing we need to do, before we start. Right click (default package) in the Package Explorer and select ActionScript File. Name it PlayerWrapper.as and press Finish. Everything is ready for the coding.



Figure 1. Final look of the player



22



06/2009 (8)



Open Source Media Framework



Creating custom display class

We are going to write very simple player that will play only progressive video using Flash Builder and Flex SDK 4 (this is to avoid the implementation playing and viewing all kinds of media possible with OSMF, like audio, images, SWFs etc). The player will be playing files from the urls, passed from the wrapping html with flashvars. First of all, we need to create UIComponent, that will contain a display object for playing media. (Listing 1) shows PlayerWrapper.as file. This file contains custom class that extends UIComponent and implements OSMF. The core class of OSMF that controls any interaction (like playing, pausing, seeking etc) with media is MediaPlayer. This is the main objects you will be dealing with during developing of any media applications. But we are not going to create an instance of MediaPlayer directly, instead we will use MediaPlayerSprite, that already includes MediaPlayer class as it’s property. MediaPlayerSprite is a ready solution for placing on a stage of any other Flash or Flex container. Check (Listing 1) and see, that there is only 1 private variable inside the class and it’s initialization. We also use getter/setter function of Flash Builder to make playerSprite public access and follow good object-oriented programming.



Listing 1. PlayerWrapper.as file

package { import mx.core.UIComponent;



import org.openvideoplayer.display.MediaPlayerSprite; public class PlayerWrapper extends UIComponent { private var _playerSprite:MediaPlayerSprite; public function PlayerWrapper() { super(); playerSprite = new MediaPlayerSprite(); playerSprite.width = 640; addChild(playerSprite); playerSprite.height = 352; }



public function get playerSprite():MediaPlayerSprite { } return _playerSprite;



public function set playerSprite(v:MediaPlayerSprite):void { } _playerSprite = v;



}



}



Coding main application

(Listing 2) shows the main file of our application that defines design and implements logics of our project. (Figure 1) demonstrates the final look of the player. Firstly, we declare some UI element with mxml. These elements are: • playerWrapper – an instance of the class we have previously created; • 2 buttons – play and pause; • seek bar – will display current playhead position and to seek through the video.

������������� ��������������� ������������������������� ������������� ��������������� ���������������� ����� ������������������� ���������������� �������������



Media traits

As OSMF allows to build a universal player that can play any type of media and show its content, when possible, in a single display, it is very important to see what properties the current media has to provide proper interaction with the user. Lets say we are building media player that plays video files. Later, we need to add an option to play audio, that does not have visual component. Or we would like to view images with our player, but these objects can not be paused or seek though the timeline.

����������� ������������������� ����������� ���������������



����������� ������������������ ��������������� ��������������������� ����������



������������� ���������������������� ������������



Figure 2. Traits and their connection with media types



06/2009 (8)



23



Open Source Media Framework



Listing 2. OSMFPlayer.mxml file







VideoElement(new NetLoader(), new URLResource(new URL(urlSource)));



backgroundColor="#00 creationComplete="ini }



updateControls();



private function updateControls():void { er.playable;











buttonPlay.visible = player.playerSprite.mediaPlay buttonPause.visible = player.playerSprite.mediaPla seekBar.visible = player.playerSprite.mediaPlayer .temporal; yer.pausable;







click="play(event)"/>



if (player.playerSprite.mediaPlayer.temporal) { er.duration;



seekBar.maximum = player.playerSprite.mediaPlay







change="onSeek(event)"/>



}



}



private function play(event:MouseEvent):void { } player.playerSprite.mediaPlayer.play();







player.playerSprite.mediaPlayer.addEventListener(Med CHANGE, onCapabilityChange);



}



}



iaPlayerCapabilityChangeEvent.TEMPORAL_











24



06/2009 (8)



Open Source Media Framework



Listing 3. Index.template.html snippet





var xiSwfUrlStr = "${expressInstallSwf}"; var flashvars = {}; var params = {};



var swfVersionStr = "${version_major}.${version_minor}.${version_revision}";



params.quality = "high";



params.bgcolor = "${bgcolor}";



params.allowscriptaccess = "sameDomain"; params.allowfullscreen = "true"; short.flv"; params.flashvars = "urlSource=http://mediapm.edgesuite.net/strobe/content/test/AFaerysTale_sylviaApostol_640_500_ var attributes = {};



attributes.id = "${application}"; attributes.align = "middle"; swfobject.embedSWF(



attributes.name = "${application}";



"${swf}.swf", "flashContent", "${width}", "${height}",



swfVersionStr, xiSwfUrlStr,



flashvars, params, attributes);



swfobject.createCSS("#flashContent", "display:block;text-align:left;");



This is where traits enter the stage. These objects define different capabilities of independently media element implementation. As you remember, the core object of any OSMF application is MediaPlayer. If you explore this class you will find a lot of properties (mostly there are boolean type) that describe media’s characteristics, like playable, seekable, audible etc. These are OSMF traits. (Figure 2) shows three common traits and how they relate to different type of media. Once our application is created we register a number of traits change events. When we load any new media to MediaPlayer it analyzes the type of media and refreshes its traits list with new data. CompatibilityChange events help to track any traits change to reflect them in the user’s interface. For example, we load an image to our player. Previously we had a video file playing there. It is obvious that an image is a still object and has not got any duration and position



and can not be seek (TemporalTrait). That is why we catch any temporal trait change and hide seek bar if the media does not support seeking. Also, we add 2 more events that will track Playhead position change and Duration change. This will set the maximum number and current position of the seek bar and will reflect the progress of media playing. updateControls function is called every time media trait is change and updates (hides or shows) appropriate UI controls. Finally, to play media, we provide a value to a source property of MediaPlayer. This property can be various types: VideoElement, AudioElement, TextElement etc.



just change the html template in our Flash Builder project. Right click html-template -> index.template.html in the Package Explorer and select Open With -> Text Editor. Now, find the part of the script, that is in (Listing 3) and add the string that is in bold. This will add source flashvar with video’s url (this is a test video file from OSMF example application). Compile and build your application and it’s ready for use in on the web – just change the source flashvar in your html and you have a ready OSMF video player!



Embedding the Player

As we have mentioned we use flashvar to pass video’s url to the application. There are different ways to embed the swf into the html page and define flashvar depending on the browser and other things, so we



MAXYM GOLOVANCHUK

Maxym Golovanchuk is a Photoshop Certified Expert and TV producer, and he is using Adobe's software for implementing entertainment solutions, including video delivery with Flash Media Server. mexxik@gmail.com



06/2009 (8)



25



Open Source Media Framework



by Louis DiCarro



Adobe's Open Source Media Format

With developer's talents expanded and clients discovering more uses for the web, clients are beginning to request media delivery sites that work like YouTube. Adobe's Open Source Media Format (OSMF) hopes to bridge the technology gap and improve the speed in which these projects can be delivered.



Level of difficulty



I



What you will learn…

• You will discover the theory of OSMF and how to get started



What you should know…

• You should be familiar with Adobe Flash CS4 or Adobe Flex 3 and ActionScript 3



n early 2005, YouTube was launched on the internet and the world found a new outlet from this new form of media delivery. Being based on Adobe's Flash format, the end user no longer had to mess with incompatible plug-ins but was still able to watch large format, high quality video. Despite various road-blocks and the purchase by Google, YouTube has gained more and more success by making media accessible both as a consumer of media and a content provider. YouTube has inspired many other sites who have taken the original concept and either melded into their own concept or improved on the basic technology. As more sites mimic YouTube's basic concept, more clients will want this type of format for their own site. You, as a developer, are expected to provide these results – usually with little time and low budget. Adobe's OSMF hopes to bridge the gap and allow for the low development time that is needed. OSMF was originally called by its code name Strobe and is meant to be a framework for building custom streaming media players on the Flash platform. It is part of Adobe's Open Source initiative and tied into the Open Video Player Initiative. Making the project open source means that Adobe will release not only the framework but the source code to the community. This allows the community to add to and improve upon the framework and submit the code back to Adobe. Adobe then integrates the approved changes into the base code and releases it as an update. It also means that the framework will be free to use in your projects. In addition to the simplified video streaming capabilities, the framework provides methods to integrate richer media experiences. This includes ad integration, image overlay and other features to enhance the experience to the end user. These will allow for shorter develop time for larger scale projects, whether the team is large and corporate or individual and independent. At the time of this writing, the framework is in public pre-release (version 0.5), so the final frame-



work is expected to change and grow as time progresses. It is expected to work with both Flash CS4 and Flex 3 and integrated into ActionScript 3. It can be downloaded from Adobe's open source site (http://opensource.adobe.com) and integrated into your projects. While in pre-release, it is not recommended to use it for final production of any project as features may change be removed from the final release. There are existing alternatives to using Adobe's framework that are currently available. These frameworks cover both commercial and open source which have a wide range of features. Adobe's philosophy is that OSMF will be integrated into the basis of the ActionScript classes and become a standard. In addition, the framework supports plugins that are in development from various media providers. Ad delivery systems such as PointRoll, EyeBlaster, and EyeWonder have planned plugins in development. Publishing partners such as



Figure 1. Flash ActionScript dialog



26



06/2009 (8)



Adobe's Open Source Media Format



Brightcove and Multicast have been listed as well as analytics systems such as Omniture and the Nielsen Company. Finally, content delivery networks listed include Akami, CDNetworks, Level 3 Communications, and Limelight Networks. Support from the above mentioned companies are important to the success of the framework because it will allow the developer to integrate outside vendor technologies into their projects without a lot of trouble. Often, a client will have an existing relationship with vendors with the need to integrate their existing media into a planned project. Also, by using a content delivery network, the client server's traffic can be lowered thus lowering requirements to deliver the media. The framework's simple API is based on three components – IMediaTrait, MediaElement, and the Composite Element. IMediaTrait is meant to be an ambiguous component that will play a piece of media without needing to be a specific media type. This means the IMediaTrait will work for not only video, but also work with audio or images based what individual component being used. The MediaElement is the representation of the IMediaTrait that can range from a simple video through a complex experience. Lastly, the Composite Element is made up of multiple MediaElements. The Composite Elements can play sequentially in a particular order or at the same time to make a composite. The framework will be able to stream from a variety of sources including HTTP and streaming via Flash Media Server using RTMP and Dynamic Streaming. As mentioned before, the media can be streamed from content partners via plugins – so you app does not need to be tied into the Flash Media Server. Streamed media can not only include video, but also images, audio and SWFs.



have arisen. It will also go over how to use the framework for both Flash CS4 and Flex Builder 3. In most cases, it is as simple as importing the included MediaFramework.swc component into your project whether you are using Flash or Flex. In Flash, open the publish settings of the project and click the Flash tab. In the panel that shows up, click the Settings button next to the Script drop down menu see (Figure 1). Click the Library path tab in the window that opens and click the SWC icon in the lower half of the window see (Figure 2). It is the one that looks like a red folder with a Flash logo on it. Click the plus button and navigate to where you saved the unarchived directory and select MediaFramework.swc. Click OK until you are back to the main view of Flash. Flex is just as easy to add the framework and works in a similar fashion. Select Properties from either the Project menu or by right clicking on the project folder itself under the projects tab. In the Properties window, select Flex Build Path in the left pane



see (Figure 3) and then select the Library path in the right pane of the window. Click the Add SWC... button on the righ hand side of the window see (Figure 4) and browse to where the unarchived directory is. Select the MediaFramework.swc and click the Open button. You can then click the OK button until you are back in the main view. Note that in both of these instances, if you move the directory that contains the MediaFramework.swc, you will have to relink to the file using the above process. Usually, it is easier to keep a copy of the needed files within the project directory which makes the files move with the project as they move to other locations. There are other workflows that also keep the files in specified locations, so it is best to check with your team to see which practice works best. The downloaded archive includes sample projects that work in both Flash and Flex under apps/samples. Here you can find a sampling of most of the major features that are built into the framework. Most samples have



Figure 2. Adding the SWC



Installation

The framework is easy to install into Flash CS4 or Flex Builder 3. First, you need to download the archive from Adobe's Open Source site. Go to http://opensource.adobe.com/ wiki/display/osmf/Downloads and click on the Source.zip link. Save the file to a convenient place on your computer. Please note that while this product is still in beta, the link may change for final release. Check Adobe's Open Source site (http://opensource.adobe.com) should there be any changes to the pages or placement. Once the file has downloaded, unarchive the files and enter the directory. There will be a ReadMe file that you should read first to get updated instructions on usage and installation as well any known issues that



Figure 3. Flex Project Properties



06/2009 (8)



27



Open Source Media Framework



a ReadMe included that will give instructions on how to use the sample. API documentation can be found on Adobe's Open Source site and can be viewed either online or downloaded to your local computer. The documentation is set up the same as other AS3 classes and frameworks. In the documentation, the classes that are



attached to the OSMF have the class path of org.openvideoplayer.*.



Your First Project

We will start off with a very simple Flash project to get a feel how the framework operates. There are many features in the framework but, being that the project is in



On The 'Net

• • • • Adobe Open Source site – http://opensource.adobe.com OSMF Download – http://opensource.adobe.com/wiki/display/osmf/Downloads OSMF API Online Documentation – http://help.adobe.com/en_US/OSMF/1.0/AS3LR/ Open Source Media Framework site – http://www.opensourcemediaframework.com/ index.html



Listing 1. OSMFSample.as

package { import flash.display.Sprite; import org.openvideoplayer.display.MediaPlayerSprite; import org.openvideoplayer.media.URLResource; import org.openvideoplayer.net.NetLoader; import org.openvideoplayer.utils.URL;



import org.openvideoplayer.video.VideoElement;



pre-release at the time of this writing, many of the features may change in the future. Start a Flash AS3 based project using the default settings. In this example, we are going to import the classes into the main class of the project. Create a new ActionScript file, save it in the same directory as the fla that was created earlier and add the code as in (Listing 1). If you publish the project at this point, it will not do anything. In order for the project to work, you must have the media streamed from a web server and not a local directory as you could with other media elements that are components in Flash. This could mean a locally run web server, which I am using in the example. Create a flv and place it on the web server and change the link in the last line to point to your server. Now test the project in Flash and you should see your movie playing. As you see, other than the imports, the only new line that is needed is the last line in the constructor function. Each of these functions condense down to one line what used to take several functions to create the same basic video player element.



Conclusion

As you can see, the Adobe Open Source Media Framework makes creating streaming media simple and quick. The developers will be able to spend more time creating feature rich experiences using media instead of dealing with the details to stream a piece of media. High end sites such as YouTube, Mtv, Hulu and others are now within reach to a smaller development team. Features built into the framework will continue to grow as new ones will be added. An open plug-in architecture allows the framework to add new sources of media as they become available without having to revamp the entire project. Being an open source project, the community is encouraged to download and contribute to the source code. Adobe has several open source initiatives available on their site with information on how to take part in the development process. Anyone can download the latest revision of the projects and look through the code, with the option of making changes to be submitted back to Adobe.



public class OSMFSample extends Sprite {



public function OSMFSample() { var video:MediaPlayerSprite = new MediaPlayerSprite(); addChild(video); video.element = new VideoElement(new NetLoader, new URLResource(new } URL("http://yourWebServer/yourFLVsample.flv")));



}



}



LOUIS DICARRO

Louis DiCarro is a consultant based in NYC and has been working with Flash since the first version. He has taught web development at the college level and has worked for numerous large clients. He can be reached at louis.dicarro.ffd@gmail.com



Figure 4. Adding the SWC



28



06/2009 (8)



Flash Media Server



Learning Flash Media Server’s Remote Procedure Calls: Tic-Tac-Toe multiplayer mini-game

by Maxym Golovanchuk

In this article we will learn some of the basics of Flash Media Server’s (FMS) Remote Procedure Calls (RPC) and write a small multiplayer Flex Tic-Tac-Toe game for two clients. We will be using Flash Builder and Flex SKD 4 for implementing the client side and familiarize ourselves with new Flex 4 features like FXG and States syntax.

Level of difficulty Introduction

The best way to learn any technology is to use it in a real world example, even if it is plain simple. Our goal is to learn the basics of RPC, notably declaring and implementing functions server and client side to call them remotely and pass parameters via them. When talking about server-side we mean FMS Server-Side ActionScript (SSAS), and we will use Flex or Flash as tools for implementing the client’s side. To make this tutorial more interesting and fun we will use Flex SDK 4 and the new Flash Builder to explore new features like FXG for rendering X’s and O’s inside the cells (Figure 2) as well as the new Flex’s States syntax to switch between game screens (Start New Game and Game). folder of your FMS installation directory. Create TicTacToe.asc file inside TicTacToe directory – this will be our application’s script. Now, to create a new project in Flash Builder go to File>New>Flex Project menu and use the following settings for the new project: • give the Project Name as TicTacToe (or whatever you like); • select the proper Project Location or Use default location if you are not sure about workspaces; • Application type should be Web; • select Flex 4.0 SDK as a SDK version; • and None as a Server technology. Click Finish to create a project. In the Package Explore view locate a (default package) folder inside src folder and right click on it. In the context menu select New>ActionScript File and this will bring a dialog window. Enter TicTacToe.as as a File name – this is the file where we will write the script, so to keep our code clean and separate MXML and ActionScript apart.



What you will learn…

• creating and setting up a new project in Flash Builder • implementing server-to-user RPC in FMS • implementing user-to-server RPC in FMS • • using new state syntax in flex sdk 4 using FXG in flex



Setting up the Project and the Environment

We presume that you have already installed Flesh Builder (it is still in Beta at the time of writing of the article) and Flash Media Interactive Server or it’s free Developer’s edition. To create a server application we need to create a new directory named TicTacToe inside applications



What you should know…

• the basic of FMS server-side programming • the basis of flex development



Figure 1. The final structure of the Project



Figure 2. Game interface rendered with FXG



30



06/2009 (8)



Tic-Tac-Toe multiplayer mini-game



We need to create a Component that will render all the necessary graphics. Right click on (default package) folder and select New>MXML Component from a popup menu. In the New MXML Component dialog fill the following properties: • • • • • Filename: Cell Based on: spark.components.Group Width: 100 Height: 100 leave Layout as spark.layouts.BasicLayout



Listing 1. TicTacToe.asc

var playerX; var playerO; var cells;



function reset() {



playerX = null; playerO = null;



}



application.onAppStart = function() { } reset();



Click Finish. This component extends Group class will be a container that will draw X’s and O’s depending on the player’s actions. (Figure 1) shows the final structure of the project.



application.onConnect = function(client) { if (playerX == null)



application.acceptConnection(client); playerX = client; playerO = client;



else if (playerO == null)



Implementing Server-Side logic

Open TicTacToe.asc in any ActionScript or text editing software. Even though it is a good practice to keep SSAS code clean and move any non-application related code into different file, we will leave everything in one file to make our code more convenient to read. (Listing 1) shows complete TicTacToe.asc. First of all we declare variables that will hold the information about players connected and cells (an array that contains data of player’s moves on the field). We also declare and implement reset function that will prepare variables for a new game. This function is called inside application.onAppStart when application starts. application.onConnect event is triggered when a client connects to the application. In our tutorial we do not implement any authorization so we accept this connection immediately. We assume that the first client connected will be playing X’s and will have first turn and assign the first client to connect to playerX variable. Accordingly, playerO will hold the second player. As soon as two players are connected we reset cells array and call startGame function of each client. This is where we use RPC. Each instance of client object has a call function that calls remote procedure implemented on the client’s side (we will talk about that later). The first parameter is a string for the name of remote function to call. The second parameter is the result object that contains any response from the client, in our case we do not expect any, so it will be null. Finally, the third boolean parameter indicates the priority of the player (whether he is X or O – true for X and false for O).



if (playerX != null && playerO != null) { cells = new Array(9);



playerX.call("startGame", null, true); playerX.opponent = playerO; } playerO.opponent = playerX;



playerO.call("startGame", null, false);



}



application.onDisconnect = function() { } reset();



Client.prototype.hit = function(cell, isX) { cells[cell] = isX; this.opponent.call("passTurn", null, cell); var winner = null; if (cells[0] == cells[1] && cells[0] == cells[2]) if (cells[3] == cells[4] && cells[3] == cells[5]) if (cells[6] == cells[7] && cells[6] == cells[8]) if (cells[0] == cells[3] && cells[0] == cells[6]) if (cells[1] == cells[4] && cells[1] == cells[7]) if (cells[2] == cells[5] && cells[2] == cells[8]) if (cells[0] == cells[4] && cells[0] == cells[8]) if (cells[2] == cells[4] && cells[2] == cells[6]) if (winner winner = cells[2]; != null) { winner = cells[0]; winner = cells[2]; winner = cells[1]; winner = cells[0]; winner = cells[6]; winner = cells[3]; winner = cells[0];



playerX.call("gameOver", null, winner); playerO.call("gameOver", null, winner); reset();



}



}



06/2009 (8)



31



Flash Media Server



We also assign arbitrary property opponent to each client, so it will be easier to pass the turn and find the opponent later. In this article we will implement all types of RPC – server-to-client and clientto-server. In the previous few paragraphs we implemented calls for server-to-client direction (we will write client’s responds a bit later). Now, we will code a response for future client-to-server calls. Each time when a player makes a turn – hits a certain cell – it sends the information about the cell hit to the server to record it, pass to another player and check if the game is over. To complete this task, we write function’s prototype using special syntax as shows in (Listing 1): Client.prototype.hit = function(cell, isX). Note, that this function will receive two parameters: cell – the cell number on the field and isX – boolean variable that indicates if the player hitting is playing for X’s.

Listing 2. TicTacToe.mxml





xmlns:mx="library://ns.adobe.com/flex/halo" width="320" height="340" xmlns:local="*"















































32



06/2009 (8)



Tic-Tac-Toe multiplayer mini-game



There will be two components in the game state: SimpleText (a text label) that will show if the current player can make a move, it’s visible property is bound to a boolean variable, so we could change it on a runtime depending on the server’s reply, and a Tile components, that will hold 9 Cells elements, that we will code later, and form 3x3 cell’s field. Implementing custom Cell component In this section we will extend Flex Group component (it is similar to Canvas component of Flex 3 SDK) with custom states and FXG to render our graphics. Cell component will be 100 pixels width and 100 pixels height and will draw X or O as shown in see (Figure 2). The full code of Cell.mxml file is in (Listing 3).

Listing 3. Cell.mxml





xmlns:mx="library://ns.adobe.com/flex/halo"







































































06/2009 (8)



33



Flash Media Server



Listing 4. TicTacToe.as

private var nc:NetConnection; private var gameStarted:Boolean; private var isX:Boolean; [Bindable] }



yourTurn = true;



private var yourTurn:Boolean; private function initApp():void {



private function gameOver(winner:Boolean):void { currentState = "init";



nc = new NetConnection();



result.text = "You " + (winner == isX?"won":"lost"); result.visible = true; yourTurn = false; } /*private function netStatusHandler(event:NetStatusEvent):void { switch (event.info.code) { case "NetConnection.Connect.Success" : break; case "NetConnection.Connect.Failed" : break; case "NetConnection.Connect.Rejected" : break; } }*/ protected function buttonClick(event:MouseEvent):void { var cell:Cell = event.currentTarget as Cell; if (gameStarted && yourTurn && cell.currentState == "empty") {



//nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); nc.client = new Object();



nc.client.startGame = startGame; nc.client.passTurn = passTurn; } nc.client.gameOver = gameOver;



private function connect():void { }



nc.connect("rtmp://82.144.221.48/TicTacToe");



private function startGame(isX:Boolean):void { currentState = "game"; gameStarted = true; this.isX = isX; yourTurn = isX; for each (var cell:Cell in container.getChildren()) } cell.currentState = "empty";



private function hit(cell:int):void { }



cell.currentState = isX?"X":"O"; hit(container.getChildIndex(event.currentTa rget as DisplayObject));



nc.call("hit", null, cell, isX);



private function passTurn(lastOpponentHit:int):void { it) as Cell;



var cell:Cell = container.getChildAt(lastOpponentH cell.currentState = isX?"O":"X";



}



}



yourTurn = false;



projects you will want to include this functionality as you usually start working with FMS after the connection was successful. In our case we exclude this function as our project is a tutorial and we want to avoid unnecessary code. In the previous chapters we discussed server-to-client RPC were used, and now we should register those functions, we called earlier from the server, to a client. NetConnection object has client property that catches any remote functions, called from a server to this client. To do so, we must declare and implement a function and assign it to NetConnection.client object. And don’t forget to create client object with new Object().



The rest of the code is obvious and handles the game start, player turns and game end.



Finishing and running the Project

The game is not completed and requires debugging and fine-tuning, for example, application needs additional coding for starting a new game after another game is finished, etc. If you wrote or copied the source code both to Flex and FMS, we are ready to run and test our game. Note, that this is a multiplayer game and we need to run 2 instances of the application. When you are ready, start the game on both tabs or windows of your brows-



er and try to play. Once a row or a column is filled with X’s or O’s, the game will over and the winner will be determined. Our game is lacking the implementation of game draw – when nobody filled the complete row or column and the there is no turns left. You can write this part of the code as a self-instruction and implement additional remote procedures to provide this functionality.



MAXYM GOLOVANCHUK

He is a Photoshop Certified Expert and TV producer, and he is using Adobe’s software for implementing entertainment solutions, including video delivery with Flash Media Server.



34



06/2009 (8)



Beginners



A Journey into Adobe Flex Charting Components [Part 2]

by Ali RAZA

Adobe Flex charting components are fabulously piquant features which not only provide almost all the most wanted charting controls but turn customization over to you. Creating a basic chart is as cushy a job as specifying a data provider and setting appropriate series for the chart, and Flex does all the underlying work for you.

Level of difficulty



A



What you will learn…

• Creating Charts with MXML and Actionscript • Customizing look and feel of Charts



What you should know…

• Basics of Adobe Flex 3, Actionscript 3.0 and MXML



dobe Flex enables developers to create spectacular, compelling and powerful dashboards with ease. Adobe Flex charting components are fabulously piquant features which not only provide almost all the most wanted charting controls but turn customization over to you. Creating a basic chart is as cushy a job as specifying a data provider and setting appropriate series for the chart, and Flex does all the underlying work for you. Truly marvelous. In this part, we’ll dig into creating, customizing and stylizing a chart using MXML and Actionscript 3. Let’s begin with declaring our simple dataset. In real world projects, you will get your data from some dynamic sources. There are three classrooms and each class lists the number of excellent, average and poor



students. Trust me, class two is not in my supervision see (Listing 1). Next, we declare a PieChart in mxml and add a PieSeries with its field property set to Average. A series tells the chart what data to display. A chart must have at least one Series of an appropriate type; PieChart uses PieSeries, and AreaChart uses AreaSeries. The field property of PieSeries tells the chart what data items to use for wedge drawing see (Listing 2). Save and Run the file and it will render something like shown in (Figure 1). Quite simple, isn’t it? Don’t worry, we have just started it. A chart can be modified to display information about each wedge on mouse over by setting showDataTips property of the Chart to true, likewise nameField of the chart series tells the chart to ascertain the name for each series.



Figure 1. First Basic Chart



Figure 2. Chart consists of separate wedges with Data Tips and Labels



36



06/2009 (8)



Adobe Flex Charting Components



Listing 1. Sample Data which will be used in the generation of the chart.

private var studentsPerformance:ArrayCollection = new ArrayCollection ([ {Class: "Class One", Excellent:30, Average: 50, Poor:20 }, {Class: "Class Two", Excellent:26, Average: 24, Poor:50 }, ]);



{Class: "Class Three", Excellent:45, Average: 38, Poor:17 }



Listing 2. First basic chart













Listing 3. Usage of data tips and explode radius property













Listing 4. Usage of styles





































































06/2009 (8)



37



Beginners



The labelPosition of the PieSeries determines how to display the labels for the wedges. In addition to that the wedges of the created PieChart can be separated or exploded by setting explodeRadius of PieSeries from 0 to 1.



Modify the code as shown in (Listing 3). You will see something like shown in (Figure 2). A chart without a legend is just like a road without a direction. No doubt, a user won’t misunderstand and end up in a Wrong Turn



sequel movie...but forethought is the best policy. So let’s add a legend using mx: Legend and pass the id of the chart to its dataProvider property.





Listing 5. Actionscript version of mxml based pie chart

private function createPieChart():void{ var chart:PieChart = new PieChart(); addChild(chart); chart.dataProvider = studentsPerformance; chart.showDataTips = true;



chart.percentHeight = chart.percentWidth = 100;



var pieSeries:PieSeries = new PieSeries(); addChild(pieSeries); pieSeries.setStyle("labelPosition", "callout"); pieSeries.nameField = "Class"; pieSeries.field = "Average"; pieSeries.explodeRadius = 0.1; var gEntryWhite:GradientEntry = new GradientEntry(); gEntryWhite.color = 16777215; gEntryBlue.color = 40447; var gEntryBlue:GradientEntry = new GradientEntry(); var gEntryGreen:GradientEntry = new GradientEntry(); gEntryGreen.color = 8453965; var gEntryOrange:GradientEntry = new GradientEntry(); gEntryOrange.color = 16758272;



var rGradient1:RadialGradient = new RadialGradient(); rGradient1.entries = [gEntryWhite, gEntryBlue]; var rGradient2:RadialGradient = new RadialGradient(); rGradient2.entries = [gEntryWhite, gEntryGreen]; var rGradient3:RadialGradient = new RadialGradient(); rGradient3.entries = [gEntryWhite, gEntryOrange];



pieSeries.setStyle("fills", [rGradient1, rGradient2, rGradient3]); chart.series = [pieSeries];



var legends:Legend = new Legend(); addChild(legends); } legends.dataProvider = chart;



Listing 6. Usage of multiple data series

















38



06/2009 (8)



Adobe Flex Charting Components



Figure 3. Chart with Legends and Colors



Figure 4. A doughnut chart



Now it’s time to get you familiar with chart styling. Flex provides dozens of properties to style and skin the chart; here we play with fills property of the PieSeries to apply three gradients for each of 3 wedges of the chart see (Listing 4). Save and Run the file. Looks promising! Isn’t it? See (Figure 3). Here is the equivalent version of this chart in Actionscript 3.0. This is also as simple as mxml version. First create a PieChart, set its properties, add a PieSeries, set its properties, and finally add a Legend and integrate it to PieChart and its done. See (Listing 5). PieChart can be further customized to render as a doughnut with a hole in its centre by setting innerRadius of the PieChart. If you are using the previously mentioned code, then make sure that explodeRadius property from the PieSeries is removed, otherwise it will muddle the chart with both a hole and distance between each wedge see (Figure 4). Another type of PieChart can be represented using multiple data series. Here is a Pie chart which uses two data series with identical data. The thing to note is that this time we are setting dataProvider of PieSeries rather than PieChart itself see (Listing 6). You will see something like shown in (Figure 5). Whether you want to create a Column chart or an Area Chart the steps remain quite same with different but relevant naming convention or some extra work in case of financial components. I am sure that this article would have given you a good kick start to unleash yourself over other charting types. There are still many things to discuss like effects and interaction and for this we’ll meet again with the third and hopefully the last part where we’ll create a dashboard based on our existing knowledge.



ALI RAZA

Ali is an Adobe Certified Expert in Flex 3 with AIR, a computer science student and senior flex developer in a UK based social networking company, possessing panoptic experience of five years in Graphics, Web and Multimedia Design. But today, he adores being in the enthralling world of Java, Adobe Flex, Flash, AIR and PHP



Figure 5. Chart with multiple data series



06/2009 (8)



39



Flash on Devices



Building video players for mobile devices

by Elad Elrom

Video is a ubiquitous and key element in compelling web content. It is relied upon by blog, news, music, web TV, social media, amateur, and movie production sites.

Level of difficulty



W



eb content designers and developers assume quality video delivery is a resource that is readily available and treat it as a standard part of the vernacular when creating products and services. Whether you are creating an application for mobile applications using Flash Lite or Flash 10, the same basic steps occur: • Creation of a streaming connection between Flash Player and the file, which can be stored, either on Flash Media Server (FMS) or your local system. • Integration of the connection with the video object • Playing of the video file. Let’s look at the code. We first create a NetConnection and establish connecting, then we create a NetStream streaming connection, integrate the connec-



tion to the video file and play the video file, as you can see below:

connection = new NetConnection(); connection.connect(null); netStream = new NetStream(connection); video.attachVideo(netStream); netStream.play("VideoFile.flv");



What you will learn…

• Creating video player for using Flash Lite and Flash Player 10



What you should know…

• ActionScript



The process is as simple as that and in an ideal world that is all that you need in order to play a video file. However, creating a compelling video stream experience is much more complex than that since the characteristics of the system playing the video can change rapidly while the video is playing and we should be able to respond to these changes. We also may want to respond to messages coming from FMS as well as cue points placed on the video.



Figure 1. Import video in Flash Professional



40



06/2009 (8)



Building video players for mobile devices



For instance, you may want to respond to a drop in users bandwidth speed by dynamically switching to a different video file following a set of pre-defined rules so the stream is not interrupted or you may want to change the buffer size once it’s filling up too quickly or too slowly. Additionally, you may want to respond to frame drops or insufficient bandwidth message coming from the streaming server.



Creating video playback component in a Flash Professional

In case you need to playback an external video file, Flash Professional offers a simple way to create a video component without writing one line of code. • To start, open Flash Professional CS4 and select File>New>Flash File. You can select either ActionScript 2.0 or 3.0. Next select Create. At this point you will have an FLA document see (Figure 1). • Save the FLA file as videoPlaybackComp onent.fla. • Choose Flash>Import>Import Video. • Select Load external video with playback component. • Select the video file you will be using. On your computer>Browse. Traverse to the location of the file. • On the next page, you can select from a set of predefined skins or you can create your own skin SWF and point to it see (Figure 2). Select Continue and complete the process. • You can see the video in the timeline and once you compile and run you will be able to playback the video see (Figure 3).



Figure 2. Import video Flash Professional skinning page



Creating the video player in Flash Lite

Now that you have a good understanding of how to build a simple video player using an external video file, we can put this knowledge to work and build a customized video player. Open Flash Professional CS4 and create new document, by selecting File>New. In the New Document window select Flash File (Mobile), set Flash Lite version to 3.0 and select Create in Device Central. Ensure the library window is open, Select Window>Library in case it’s closed. Right click in the Library Window and select New Video… The Video Properties windows opens up see (Figure 4). Set the Symbol name to: videoPlayer and the document should be set to at least Flash Lite 2.0, so in case it’s set for Flash Lite



Figure 3. videoPlaybackComponent application



Figure 4. Video properties window



06/2009 (8)



41



Flash on Devices



Listing 1. Action script code

this.playButton.onRelease = function() { } playVideo();



function playVideo() { connection = new NetConnection(); {



connection.onStatus = function(info) switch (info.code) { case "NetConnection.Connect.Success": { trace("Connected successfully to"); setNetStream(); } { } break;



default: trace("Error with bandwdith check: "+info.code);



}; }



}



connection.connect(null);



1.0, the document properties window will show up and will enable you to set the version of Flash Lite. Set it to Flash Lite 3.0. At this point you can see the video object in your library. Drag and drop the object to the stage and change the object instance name in the properties windows to video. We will create a play button that will allow the user to start the playback once the play button is pressed. We can utilize an existing button from the library, to do that click Window>Common Libraries>Buttons. That will open the Library window and you can select existing button assets see (Figure 5). Drag the asset to the timeline and double click the asset in the timeline to change the text in the button from Enter to Play. Set the name of the asset in the properties window to playButton. Create another layer in the timeline and name it actions. Paste the following action script code see (Listing 1) Compile and run and in Device Central you will be able to view the application in one of the emulators that support FLV file format see (Figure 6). Let’s examine the code. We set a method to handle the release of the button. Once the button is pressed and released the playVideo method is called.

this.playButton.onRelease = function() { } playVideo();



function setNetStream() { netStream = new NetStream(connection); video.attachVideo(netStream); } netStream.play("videofile_500.flv");



Listing 2. playVideo method

function playVideo() { connection = new NetConnection(); {



method creates the Netand listens to onStatus events. In case there is a success event, we call the setNetStream method see (Listing 2).

playVideo Connection



connection.onStatus = function(info) switch (info.code) { case "NetConnection.Connect.Success": { trace("Connected successfully to"); setNetStream(); } { } break;



default: trace("Error with bandwdith check: "+info.code);



}; }



}



connection.connect(null);



Figure 5. Flash Professional library buttons



42



06/2009 (8)



Flash on Devices



Listing 3. VideoPlayerExample.mxml

{







playButton.enabled = true; this.setNetStream(); break; } {



xmlns:mx="library://ns.adobe.com/flex/halo" creationComplete="creationCompleteHandler



case "NetStream.Play.StreamNotFound": trace("StreamNotFound: " + videoURL); break; } {







]]>



sume()" enabled="false" />



switch (event.info.code) case "NetConnection.Connect.Success":



44



06/2009 (8)



Building video players for mobile devices



method creates a new object and integrates the video object with the NetStream. We can now play the video.

NetStream setNetStream



Listing 4. creationCompleteHandler method





Creating video player for Flash 10

To create a customized video player for Flash 10, we will be using Flex Builder. Open Flex Builder or Eclipse. Select File>New>Flex Project. Set the project name to VideoPlayerExample and use the Flex 4 SDK in Flex SDK version. Select Finish to complete the creation of the project. Paste the following code into Video PlayerExample.mxml file see (Listing 3). Once you compile and run the app, you will be able to view the video playback. Let’s examine the code. We first create the application set the creation complete event to call creationCompleteHandler method see (Listing 4) We set global parameters that we will be using in our application such as the video URL location, the net connection and net stream.

private var videoURL:String = "videofile_H264.mp4"; private var connection:NetConnection; private var netStream:NetStream;











]]>



Listing 8. Handler for IO network errors





enabled="false" />



NetStream(connection);







netStream.addEventListener(NetStat usEvent.NET_STATUS, netStatusHandler); orEvent.IO_ERROR, onNetworkError);



netStream.addEventListener(IOErr







Listing 9. FxVideoDisplay





We can specify a client property. The property allows us to direct all the call back to the client we define.

netStream.client = new







xmlns:mx="library://ns.adobe.com/flex/halo"



CustomStreamClient();



var video:Video = new Video();



video.attachNetStream(netStream);







Once we are ready to play the video, we will play the video, seek to the 0.01 second and pause the video. The reason we do that is to display the first frame of the video and wait for user interaction to play the video.

netStream.play(videoURL); netStream.seek(0.01); netStream.pause();



Listing 10. VideoPlayerGumboExample.mxml









We also add the video component we set in this method to a placeholder we defined.

component.addChild(video);











import components.VideoSkin;



}







Handler for IO network errors see (Listing 7). We set a component as a placeholder so we can add the video object we are creating. The playButton Button will allow us to play the video. Notice that we start the button as enabled false so the user will not be able to







46



06/2009 (8)



Building video players for mobile devices



Listing 11. VideoSkin class

mxml/2009"







xmlns:d="http://ns.adobe.com/fxg/2008/dt"







[HostComponent("spark.components.VideoPlayer")]



Figure 7. Run the application



The MXML code to create the

source="flv file..."> VideoPlayer component looks as follows:



s:



source="videofile_H264.mp4" />











Listing 12. Skin component

mxml/2009"



xmlns:d="http://ns.adobe.com/fxg/2008/dt"







[HostComponent("spark.components.VideoPlayer")]



To create a video player you create the component and set the video file like so see (Listing 9). Once you compile and run the application, you can see the result in (Figure 7). As you can see the component includes a toolbar for common operations such as pause, stop, mute, fullscreen, volume and seek. The component can be skinned easily using VideoElement. Let’s take a look how you can skin the component: Create a new Flex project and call it VideoPlayerGumboExample. In the entry point, VideoPlayerGumboExample.mxml paste the following code see (Listing 10). Notice that we included the VideoDisplay component and we set the skinClass property to point to a class we will create. The VideoSkin class we will be creating includes the VideoElement and the toolbar see (Listing 11). Let’s examine the code. The component we are using is a Skin component, which is common when we create skins for Flex 4 components see (Listing 12). The VideoElement is necessary to skin the VideoDisplay component and we point to the video file we are using where the location of the folder is relative to the VideoPlayer component that defines the skin, not to the skin.





autoPlay="true"



Figure 6. Progressive download application deployed in Device Central emulator



Next we can define all the sub classes that are being used by the VideoDisplay component such as the pause, play, seek and volume as well as the different video states. The way the sub components are mapped is by the id name. Each sub component needs to correspond to the expected id.



06/2009 (8)



47



Flash on Devices



Listing 13. playButton skin for the Button





Additionally, notice that each button points to another skin class such as the playButton point to PlayButton skin.

skinClass="{PlayButton}" />







xmlns:mx="library://ns.adobe.com/flex/halo"







skinClass="{StopButton}" />











[HostComponent("spark.components.Button")]











Lastly, take a look at the playButton skin for the Button. We can define all the different states and the pixel (graphic). For graphic we used a simple box with border and a text field that holds the text play see (Listing 13). Create the same skin for the stopButton and name the class StopButton. The only difference is going to be the text field text property will be set to Stop. Once complete you can compile and run and see the result in (Figure 8).















id="labelElement" text="Play"/>



The article comes from AdvancED Flash on Devices



ELAD ELROM

Elad Elrom is a consultant, technical writer and technical lead. As a technical writer, Elad wrote books covering Flash technologies. He maintains an active blog and has spoken at several conferences regarding the Flash platform. He has helped companies follow the XP and Scrum methodologies to implement popular frameworks, optimize and automate built processors and code review, and follow best practices. Elad has consulted a variety of clients in different fields and sizes, from large corporations such as Viacom, NBC Universal, and Weight Watchers to startups such as MotionBox.com and KickApps.com.



Figure 8. Flash 10 progressive download application using Flash 10 skinning



48



06/2009 (8)



ActionScript Development



by Louis DiCarro



Creating a Custom ActionScript 3 Video Player

Video handling in ActionScript has changed from ActionScript 2. A lot of confusion has come from the change but it is actually very simple to create a video player. We will build a simple flv player to show how.



Level of difficulty



F



What you will learn…

• How to make a custom flv player in ActionScript 3



What you should know…

• You should be familiar with Adobe Flash CS4 and ActionScript 3



lash does provide components to display video but they are hard to customize the look and feel as well as the funtionality. As a developer, you want more control over the video elements and may also want custom behaviors triggered by events. We will build a basic player that can be expanded upon and grow as your needs do. To start this tutorial, create an ActionScript 3 Flash file called VideoPlayer.fla and save it into a directory of your choice. Next create an ActionScript file called VideoSample.as that will be saved in the same directory as the fla file. These files can be named any name you want, but the ActionScript file name must be the same name as the class you are importing (as you will see soon). Back in VideoPlayer.fla, set your document class to VideoSample. This can be done either in the Properties panel see (Figure 1) or Publish Settings... see (Figure 2). In the panel under the Flash tab, click the Settings button next to the ActionScript menu and set the document class in the text box. You will also need a flv to work with, in this example it is called sample.flv. Most of the editing we will be doing will be in the class file (VideoSample) and we will spend very little time in the fla. There will be some art created in the fla to keep thing simple. Our final product will look as demonstrated in (Figure 3).



• stop and rewind the video when it is finished • control the volume These may seem very obvious and basic, but it will help us in the long run. With our goals in place, we can now get to coding. Open the VideoSample.as file and put in place a basic class structure as in (Listing 1). Now that the structure is in place, we can proceed with getting the video on the stage. Import the flash.media.Video package by adding a line beneath the current import statement and typing import flash.media.Video;. Then add the following two lines into the VideoSample function.

videoDisplay = new Video(); addChild(videoDisplay);



You now have a video display on the stage. To make the object available to the entire class, we



Planning

Our first step after creating the files is to decide how our project is going to function. Specifically, what do we want it to do? This is a very important step in any project because planning defines the goals of the project and helps keep scope creep under control. Scope creep is when features keep getting added to the project to the point that the project never finishes. Here is a list of features: • • • • stream a video play the video pause the video stop and rewind the video



Figure 1. Adding the document class to the Project panel



50



06/2009 (8)



Creating a Custom ActionScript 3 Video Player



must declare it before the VideoSample function. Insert a line in between public class VideoSample extends Sprite and public function VideoSample. Then add to that line private var videoDisplay: Video. Your code should now look like (Listing 2). Let's take a quick look at what we did. First, we imported the package to make the functions of the Video object available to our class. You will need to do this for any kind of class you want to use. Then we created the video object by initializing a variable called videoDisplay. Once it is initialized, we add it to the stage using the addChild() function. Finally, we made the object available to the entire class, not just the initialization function, by defining it outside of the functions. We gave it a private designation because we only want this class to have access to it. The video object on the stage will not do much until we feed it some media. The way to get streamed media into a video object is by using NetConnection and NetStream. This is where most of the confusion starts when trying to add a video or flv to a project. Add the three import statements in (Listing 3) below the imports added earlier, the variables to the varible block and the rest of the code below the video statements added earlier. Breaking this down line by line will help you understand what is happening. First, we are creating a new NetConnection object which connects the SWF to outside resources. These resources could be video, images, xml or even a server. A listener is added to the object to catch if the connection cannot be made and then the connection is created. The next block starts with creating a NetStream object. This is the actual connection to the media, an flv in this case, using the NetConnection object. Another listener is attached to the object to track the streaming objects and then the object's delegate is set to the object itself. What this means is that when the stream is sending out messages, the object we have created (stream) will be the object that handles it. Another way to put it, the actual stream is sending out messages and the object will respond to these messages. Lastly, we set the stream to download or buffer 15 seconds before it starts playing. The last block of code connects the stream that we created above to the the video object we created earlier. This is the same as telling the video player to play the video that is coming in with the stream. Finally we turn smoothing on to keep the video looking good if it is resized.



Listing 1. Basic class structure

package { import flash.display.Sprite; {



public class VideoSample extends Sprite public function VideoSample() { } }



}



Figure 2. Adding the document class to the Publish Setting dialog



Figure 3. What our project will look like



06/2009 (8)



51



ActionScript Development



Listing 2. Setting up the video object

package { import flash.display.Sprite; public class VideoSample extends Sprite { private var videoDisplay:Video; public function VideoSample() { videoDisplay = new Video(); addChild(videoDisplay);



Listing 6. Play and pause functions

private var streamIsReady:Boolean = false;



private var vidStream:String = "sample.flv"; private function playVideo():void { if(!streamIsReady) { stream.play(vidStream); streamIsReady = true;



} { }



else stream.resume();



}



}



}



}



Listing 3. Setting up the streaming object

import flash.events.NetStatusEvent; import flash.net.NetConnection; import flash.net.NetStatus;



private function stopVideo():void { stream.pause();



private var connect:NetConnection; private var stream:NetStream;



}



stream.seek(0);



connect = new NetConnection(); connect.connect(null);



connect.addEventListener(NetStatusEvent.NET_STATUS, handleNetStatus);



stream = new NetStream(connect); stream.client = this;



stream.addEventListener(NetStatusEvent.NET_STATUS, handleNetStatus); stream.bufferTime = 15;



Listing 4. Event handlers for stream object

private function onMetaData(info:Object) { } trace(info);



private function handleNetStatus(e:NetStatusEvent):void { if(e.info.code == "NetStream.Play.Stop") { } { }



else if(e.info.code == "NetStream.Play.StreamNotFound") // handle error dialog for the user



}



Listing 5. Controlling the volume

import flash.media.SoundTransform;



private var transform:SoundTransform; transform = new SoundTransform(.5); stream.soundTransform = transform;



52



06/2009 (8)



Creating a Custom ActionScript 3 Video Player



So to play a video it takes three basic steps. First, create a connection from the SWF to the outside world (NetConnection). Second, use the connection in the first part to get a connection to the media using the object in the first step. Last, connect the streams to the video object. Remembering these three steps will make attaching media to your project much easier. We also need to add an event handler for the addEventListener statements. Add (Listing 4) to your code outside the VideoSample function but inside the class statement. We will add more later, but this is a basic framework so we don't get any errors. The event handler (as all event handlers) expects to be passed a parameter from the addEventListener function. In this case, a NetStreamStatus event is passed and we will translate the code that is in that event to handle certain parameters. We are not going to handle a non-connection event, but, if this were an actual project, we would display some message to the user. The onMediaData function is the result of the stream.client = this statement. The stream broadcasts an onMediaData event and this function catches the event. For this example, we are just going to trace out the info for us to inspect. One more piece of business that we must attend to before adding user interaction and that is sound control. This is another point of confusion that is very simple once you break down the steps. Add the code in (Listing 5) as we have before to the document with the statements still in the VideoSample function. While the flv is controlled by the NetStream class, this only controls the starting, playhead positioning and stopping of the video. To control the volume of the flv, we need to use the SoundTransform class. The SoundTransform controls the volume and panning of the sound from the flv. Examining the block of code in (Listing 5) the first line creates the SoundTransform object and passes the starting volume to it (.5). This is an optional value that ranges from 0 to 1. We just want the volume a little lower than the original because the sound on the flv is quite loud. Then we assign the SoundTransform object to the NetStream that we created earlier. That was a lot of work and now we are finally ready to add some functionality to get our video playing. Adding (Listing 6) to the class will will give the statements that are needed to start and stop the video. As a test to make sure everything is working properly, add the statement playVideo(); to the end of the code block in the VideoSample function (after the SoundTransform statements). When you test your project, you video should start playing after a few seconds.



What we are doing with the latest code is creating a variable streamIsReady to keep track of whether this is the first time the video is playing or not. If it is false, as in the playVideo() function, start the streaming and play the video. If it is true, meaning the

Listing 7. Events for the buttons

import flash.events.MouseEvent;



video has already streamed, pick up where the last place the playhead was in the stream. The stopVideo function stops the playhead then moves it back to the beginning of the video. These functions are the actions that we will wire our buttons to in the next section.



private var streamIsPlaying:Boolean = false; playBtn.buttonMode = true; playBtn.stop();



playBtn.addEventListener(MouseEvent.CLICK, handlePlayPause); stopBtn.buttonMode = true;



stopBtn.addEventListener(MouseEvent.CLICK, handleStop); volumeBtn.buttonMode = true; volumeBtn.stop(); volumeBtn.addEventListener(MouseEvent.CLICK, handleVolume);



private function handlePlayPause(e:MouseEvent):void { playVideo(); if(playBtn.currentLabel == "play") { } { } playBtn.gotoAndStop("pause");



else playBtn.gotoAndStop("play");



}



private function handleStop(e:MouseEvent):void { stopVideo(); { }



if(playBtn.currentLabel == "pause") playBtn.gotoAndStop("play");



}



private function handleVolume(e:MouseEvent):void { if(sndTransform.volume == .5) { sndTransform.volume = 0;



} {



volumeBtn.gotoAndStop("quiet");



else sndTransform.volume = .5;



}



volumeBtn.gotoAndStop("loud");



}



stream.soundTransform = sndTransform;



06/2009 (8)



53



ActionScript Development



Some buttons are needed and, instead of creating them through ActionScript, we will create the art on the stage and control them through ActionScript. The button movieclips will be multi-state, meaning the image of the button will reflect the state of the information it controls. The play button will switch between play and pause, the volume button will have sound and silence. Remove the playVideo() statement from the VideoSample class so the stream will not start until the play button is pressed. Create a movieclip for each button and art for the background. Add frames to the play and volume buttons to make each about 10 frames on the timeline. These extra frames are for the states with some padding for clarity. Add a layer to each button for the icons, adding a key frame



half way through on the play and volume buttons. These will be the two states of the button. Add the art to the icon layer. Then add a third layer to the play and volume buttons with a key frame in the same place as the icon layer. On this layer, we will add a label for each state. In the case of the play button, the key frames are named play and pause while on the volume button, they are named loud and quiet. If you were to test the movie now, the button movieclips would just loop, but we are not going to put ActionScript on the timeline as we would have in the past. We are going to handle it in the class instead as you will see in a moment. Put an instance of each button on the stage and name each instance. In the sample application the buttons were named stopBtn, playBtn, and volumeBtn.



On each movieclip, the button mode is set to true so it will broadcast events when clicked by the mouse. An event listener is added with handlers added later in the class and each movieclip is told to stop. By putting the stop function in the class, we keep each button's time line from playing. You will also see in each event handler, we jump to a labeled frame to reflect the state but use gotoAndStop() instead of gotoAndPlay(). The playVideo function is modified as in (Listing 8) to keep track of whether the stream is playing or not. All of the play and stop buttons call functions that call our original functions because when an event is broadcast, the receiving function is expecting to be passed a parameter. These extra functions also gives an opportunity to do some other tasks that pertain only to that function while leaving the core behavior available for other functions. The play and stop buttons both call the playVideo() and stopVideo() functions and change the icons based on what state they were in previously. The volume button runs a little differently but acts as when we first set up the SoundTransform in the VideoSample function. First we are checking what the current volume is set at – either 0 or .5. Based on the volume value, the SoundTransform object is updated to the opposite value and the icon of the button changed. The SoundTransform is once again applied to the stream object for the volume change to take affect.



Figure 4. Play and pause states of the play button Listing 8. Updated playVideo function

private function playVideo():void { if(!streamIsPlaying) { if(!streamIsReady) { stream.play(vidStream); streamIsReady = true; } { streamIsPlaying = true;



Conclusion

There are many ways to get outside media into Flash. This project is meant as a way to give developers a starting point in creating their own full-featured media players and an understanding of the mechanics. Other options that could be added is finer control of the volume with a slider instead of a button, a progress bar for streaming, video seek with a scrubber and countless others.



else stream.resume();



} {



}



streamIsPlaying = true;



else stream.pause();



LOUIS DICARRO

streamIsPlaying = false;



}



}



Louis DiCarro is a consultant based in NYC and has been working with Flash since the first version. He has taught web development at the college level and has worked for numerous large clients. He can be reached at louis.dicarro.ffd@gma il.com



54



06/2009 (8)



ActionScript Development



by Dennis Ippel



Harnessing FP10 Power with Away3D Lite

Away3D Lite 1.0 is the first open source 3D engine for Flash that uses new features offered by Flash Player 10 to speed up the rendering process. This article will go over the differences with the previous Away3D version and will point out which FP10 features are used.



Level of difficulty



A



way3D has become the most fully-fledged 3D engine for Flash. Thanks to a hardworking and dedicated team they’ve managed to become the standard for 3D development with Flash.



So where does Away3D Lite fit in best? Because of its small codebase (under 25K) it can easily be used in banners and widgets. But there are many other types of projects where it can be used. This first release of Away3D Lite has all the essential features: • 3DS, MD2, Collada & Metasequoia loaders • Basic primitives (Cone, Cube6, Cylinder, Plane, Skybox6, Sphere & Torus) • Cameras (Camera3D, TargetCamera3D, HoverCamera3D) • Basic materials (ColorMaterial, WireColorMaterial, BitmapFileMaterial, BitmapMaterial, WireframeMaterial)



Away3D Lite 1.0

This new Away3D version is more compact than the full-blown version. You’ll be missing some features that you can find in the non-lite versions. These features haven’t been left out; they just haven’t been added yet. Away3D Lite has been built from the ground up for Flash 10. This is a slow and tedious process, hence the absence of some features.

Listing 1a. Away3D Lite 1.0 example



What you will learn…

• Which Flash Player 10 features are used to make Away3D Lite faster • How to create a simple 3D scene with Away3D Lite



What you should know…

• • Basic 3D terminology Good knowledge of ActionScript 3.0



package { import __AS3__.vec.Vector;



public class Away3DLiteDemo extends Sprite { // -- engine private var scene private var cam private var view // -- materials : Camera3D; : View3D; : Plane; : Scene3D;



import away3dlite.cameras.Camera3D; ner3D;



import away3dlite.containers.ObjectContai import away3dlite.containers.Scene3D; import away3dlite.containers.View3D; import away3dlite.primitives.Cube6; import away3dlite.primitives.Plane; import flash.display.Bitmap; import flash.display.Sprite; import flash.events.Event; import flash.geom.Point; import flash.events.KeyboardEvent; import flash.geom.Vector3D; import away3dlite.materials.BitmapMaterial;



private var plane



[Embed( source="cubetexture1.jpg" )] private var CubeTexture1 private var CubeTexture2 [Embed( source="cubetexture2.jpg" )] : Class;



: Class;



private var cubeMaterial1 private var cubeMaterial2



BitmapMaterial; BitmapMaterial;



: :



import net.hires.debug.Stats; [SWF( backgroundColor="#3BB9FF",



// -- other private var ringCounter : uint;



frameRate="40", quality="high", width="800", height="600" )]



private var cubeContainers : Vector.;



56



06/2009 (8)



Harnessing FP10 Power with Away3D Lite



Listing 1b. Away3D Lite 1.0 example

: Number = 0; ) % 360;



private var cameraS



: Number = Math.PI / 180;



var cubeTexture : BitmapMaterial = cubeContainers.length % 2 == 0 ? cubeMaterial1 : cubeMaterial2;



public function Away3DLiteDemo () { } init();



for ( var i : uint = 0; i (); initEngine(); initMaterials(); initObjects(); } initListeners();



var radian : Number = ( degrees / 180 ) * Math.PI; cubeContainer.addChild( cube );



cube.width = cube.height = cube.depth = cubeSize; cube.x = center.x + Math.cos( radian ) * radius; cube.y = center.y – Math.sin( radian ) * radius; }



private function initEngine () : void { scene = new Scene3D(); view = new View3D(); view.scene = scene;



scene.addChild( cubeContainer ); }



cubeContainers.push( cubeContainer );



camera = new Camera3D();



private function initListeners () : void { addEventListener( Event.ENTER_FRAME, onEnterFrame ); stage.addEventListener( KeyboardEvent.KEY_DOWN, view.x = stage.stageWidth / 2; } keyDownHandler );



view.camera = camera; addChild( view ); }



addChild( new Stats() );



view.y = stage.stageHeight / 2;



private function initMaterials () : void { var cubeTexture1 : Bitmap = new CubeTexture1(); var cubeTexture2 : Bitmap = new CubeTexture2(); cubeMaterial1 = new BitmapMaterial( cubeMaterial2 = new BitmapMaterial( cubeMaterial1.smooth = true; cubeMaterial2.smooth = true; } cubeTexture1.bitmapData ); cubeTexture2.bitmapData );



private function onEnterFrame ( e : Event ) : void { var num : uint = cubeContainers.length; for ( var i : uint = 0; i ; : uint; : Class; : Class; private var scene : Camera3D; : View3D; : Plane; } : Scene3D;



private function initObjects () : void { for( var i : uint = 0; i (); initEngine(); initMaterials(); initObjects(); } initListeners();



cube.width = cube.height = cube.depth = cubeSize; cube.x = center.x + Math.cos( radian ) * radius; cube.y = center.y – Math.sin( radian ) * radius;



58



06/2009 (8)



Harnessing FP10 Power with Away3D Lite



Listing 2b. Away3D 3.4.0 Example

} scene.addChild( cubeContainer ); } var cubeContainer : ObjectContainer3D = if ( i % 2 == 0 ) else } cubeContainers[ i ];



cubeContainers.push( cubeContainer );



cubeContainer.rotationY++;



private function initListeners () : void { addEventListener( Event.ENTER_FRAME, onEnterFrame ); stage.addEventListener( KeyboardEvent.KEY_DOWN, view.x = stage.stageWidth / 2; } keyDownHandler );



cubeContainer.rotationY--;



camera.x = Math.sin( cameraAngle ) * 50;



camera.z = Math.cos( cameraAngle ) * 400; camera.lookAt( new Number3D( 0, 0, 0 ) ); cameraAngle += cameraSpeed; } view.render();



view.y = stage.stageHeight / 2;



private function onEnterFrame ( e : Event ) : void { var num : uint = cubeContainers.length; for ( var i : uint = 0; i Run Project (or command+Return on Mac OS), you will be able to view the scrollbar functional. Now that we have the scrollbar, we want to assign it to a list component. All the results will be placed in a list, and the user can use the scrollbar with association with that list. From the WIREFRAME COMPONENTS choose the Data List and drag and drop it in the stage see (Figure 13). Then select the scrollbar, and copy the component (from the top menu select Edit>Copy). Double click the Data List component, and you can edit the component’s part. Replace the default vertical scrollbar, and remove the horizontal scrollbar as well as adjust the size of each item in the list and add a rectangle that we can replace later with the user’s image see (Figure 14). When you have completed the converting the design to FXG code, save the file as body.fxp. Next, create a new Flash Catalyst Header project. Select From Adobe Photoshop PSD File… and import the Header.psd. In the artwork we have the two states normal and hover. The first step is to convert each of the normal artworks to a button. To select the button artwork right click and select Convert Artwork to Component>Button see (Figure 15).



After you have converted the artwork into Button, the button opens with all the different states. Go back to the main document, and copy the hover state.

Listing 1. Application entry file Main.mxml





Then paste it in the button Over and Down states, see (Figure 16). To select the search artwork, right click and select Convert Artwork to Component and then























Figure 7. Identify components wireframe



64



06/2009 (8)



Designer-Developer workflow



Listing 2. ModelLocator



package com.elad.twitter.model { import com.adobe.cairngorm.model.IModelLocator; import com.adobe.cairngorm.CairngormError; import com.adobe.cairngorm.CairngormMessageCodes; import com.elad.twitter.model.presentation.*; [Bindable] {



} /** * * Retrieves the Singleton instance of the ModelLocator * as well as an instance of LibraryModel and mainPM * * @return singleton instance of ModelLocator * */ public static function getInstance() : ModelLocator { if ( instance == null ) { instance = new ModelLocator( new Private() ); instance.libraryModel = new LibraryModel(); instance.mainPM = new MainPM( //todo: add instance } } return instance; instance.libraryModel );



import com.elad.twitter.model.domain.LibraryModel;



public final class ModelLocator implements IModelLocator /** * * Defines the Singleton instance of the application * ModelLocator * */ private static var instance:ModelLocator; /** * * The application domain Model. The application Domain Model classes structures * our application data and defines its behavior reducing the role of the ModelLocator and * increase decoupling of the view. * */ public var libraryModel:LibraryModel; /** * * The application main Presentation Model * */ public var mainPM:MainPM; // todo: add variable instance /** * * Defines the Singleton instance of the Application * ModelLocator * * @param inner class instance which restricts constructor access * */ public function ModelLocator(access:Private) { if ( access == null ) { throw new CairngormError( CairngormMessageCodes.SI NGLETON_EXCEPTION, "ModelLocator" ); } * */ } /** }



* Inner class which restricts constructor access to Private */ class Private {}



Listing 3. LibraryModel.

package com.elad.twitter.model.domain { [Bindable] /** * * Defines the LibraryModel which contain the application * persistence data such as state/model, variables.



public class LibraryModel { } // TODO: place all application data here



}



instance = this;



06/2009 (8)



65



ActionScript Development



Presentation model Personally, I found the best approach to be the presentation model. Here are some of the advantages of using the presentation model: • • • • You can tie it well with unit testing. The component is loosely coupled. You can replace the view more easily. It integrates well with MVC pattern and the new Flex architecture.

Figure 10. HUD convert artwork to component drop down menu



Figure 8. Flash Catalyst start page



Text Input see (Figure 17). Save the project as Header.fxp. Add interactivity Lastly, open LeftNav.psd and Footer.psd, and save the Flash Catalyst projects as LeftNav.fxp and Footer.fxp. At this point we did not add any navigation or footer components since we wanted to keep the project simple in nature, there is no need to convert artwork into components or add any interactivity.



Step 3 – Integration of Code into Application

Once the work with Catalyst is completed, files can be imported. The format is FXP (Flash XML Project), which is recognized by Flash Builder 4. There are many ways to use the FXG component such as inherence and composition. You can use them as is, or use the presentation model.



There are many types of implementations, so I am not going to go into detail. The idea is to have a ‘clean’ view that does not have any code, which allows you to easily make changes to the view and follow the Flex 4 and Catalyst architecture of separating pixels from the plumbing. By doing so you will be able to exchange the components and skins more quickly than having a component that holds code and visual components. I recommend importing the FXP project as a separate project and than copying and pasting the components, skins and assets into your existing project, placing them in a namespace that matches your application’s framework see (Figure 18). The next step is to create the presentation model to hold the view and logic of each component. For instance, for the Body component we will create BodyPM, which will hold the logic: We also need to modify the model locator to hold an instance of each component presentation model.



Figure 11. Component issues message in HUD



Figure 12. Set thumb in HUD



Figure 13. Wireframe components window



The last part is to add a component to hold the view for each component we imported from Catalyst. Integrate Flash Catalyst code into existing application The next step is to copy the code from each FXP project and rename the components. Next, we need to add references to the MainWindowView.mxml, which will hold all the components we imported from Catalyst. During this process you will find that you have to make all kind of changes to the code such as: • Refactor code to be more readable • Rename skins and components to names that make more sense • Adding id property for components • Make changes to states and transitions and properties to better fit business requirements Additionally, you may often find that you need to replace a component to better work with your data. For instance, replace



Figure 9. Flash Catalyst start page



66



06/2009 (8)



Designer-Developer workflow



Listing 4. MainPM, AbstractPM, and ThunderBolt

package com.elad.twitter.model.presentation { import com.adobe.cairngorm.control.CairngormEventDispat import com.elad.twitter.events.InitializationCommandCom import com.elad.twitter.events.PreInitializationCommandC import com.elad.twitter.model.domain.LibraryModel; import org.osflash.thunderbolt.ThunderBoltTarget; import mx.logging.Log; [Bindable] /** * * Defines the MainPM Value Object implementation * */ public class MainPM extends AbstractPM { /** * * Define an instance of ThunderBoltTarget * * @see org.osflash.thunderbolt.ThunderBoltTarget * @see mx.logging.Log * */ private var _target:ThunderBoltTarget = new /** * * Define an instance of the LibraryModel * */ public var libraryModel:LibraryModel; /** * Defualt constractor set the LibraryModel * @param LibraryModel * */ public function MainPM(libraryModel:LibraryModel) { } this.libraryModel = libraryModel; * */ override protected function handleCompleted():void { // remove event listeners CairngormEventDispatcher.getInstance().removeEventL istener( PreInitializationCommandCo } /** * Method to handle the view once preinit and init are completed ThunderBoltTarget(); } /** * Method to handle dubsequent shows of the application * */ override protected function handleSubsequentShows(): { void } /** * Method to handle first show of the application * */ override protected function handleFirstShow():void { // implements or leave default handleCompleted(); ompleted; pleted; cher; Handler );



} /**



* Method to handle first show of the application * */ override protected function handleInitialize():void { // track once initialize completed CairngormEventDispatcher.getInstance().addEventListe ner( InitializationCommandCompleted. ); COMPLETED, initializeCompletedHandler



// implements or leave default handleCompleted();



/** * Method to handle first show of the application * */ override protected function handlePreInitialize():void { // set filter for logging API and inject thunder bolt _target.filters = ["com.elad.twitter.commands.*"]; // track once pre-initialize completed CairngormEventDispatcher.getInstance().addEventListe ner( PreInitializationCommandComplet ed.COMPLETED, preInitializeCompleted } } Log.addTarget(_target); }



mpleted.COMPLETED, preInitializeCompl CairngormEventDispatcher.getInstance().removeEventL istener( leted.COMPLETED, initializeCompleted Handler ); InitializationCommandComp etedHandler );



// implements changes in view



06/2009 (8)



67



ActionScript Development



Listing 5. BodyPM

package com.elad.twitter.model.presentation { import com.elad.twitter.model.domain.LibraryModel; [Bindable] /** * * Defines the TemplatePM Value Object implementation * */ public class BodyPM extends AbstractPM {



Listing 6. Modify model locator to hold an instance of each component presentation model

public var bodyPM:BodyPM;



public var footerPM:FooterPM; public var headerPM:HeaderPM; public var leftnavPM:LeftNavPM;



public var mainwindowPM:MainWindowPM;



public static function getInstance() : ModelLocator { if ( instance == null ) { instance = new ModelLocator( new Private() ); instance.libraryModel = new LibraryModel(); instance.mainPM = new MainPM( instance.libraryModel ); instance.bodyPM = new BodyPM( instance.libraryModel ); ); ); instance.footerPM = new FooterPM( instance.libraryModel instance.headerPM = new HeaderPM( instance.libraryModel instance.leftnavPM = new LeftNavPM(



//----------------------------------------------------// // Variables // //---------------------------------------------------/** * * Define an instance of the LibraryModel * */ public var libraryModel:LibraryModel; //-----------------------------------------------------// // Getters and setters // //-----------------------------------------------------//----------------------------------------------------// // Constructor // //-----------------------------------------------------/** * Defualt constractor set the LibraryModel * @param LibraryModel * */ public function BodyPM(libraryModel:LibraryModel) { } this.libraryModel = libraryModel; } }



instance.mainwindowPM = new MainWindowPM( //todo: add instance return instance;



instance.libraryModel ); instance.libraryModel );



Listing 7. Component to hold view for each component imported from Catalyst













//----------------------------------------------------// // Methods // //----------------------------------------------------}















}



68



06/2009 (8)



ActionScript Development



Figure 16. Button states



Once you complete the process and import all the projects you can see the project structure in the package explorer, see Body project import into Flash Builder see (Figure 20). Refactor code to be more readable Once all the projects are imported it is recommended to refactor the project to your standards so it is more readable. Here is an example of refactoring the DownButton1.mxml in the Body.fxp project. Refactoring code to be more readable is a matter of personal taste and coding convention. For instance, take a look at the TagsListDownButton.mxml component created by Flash Catalyst. After refactoring the component it will be more readable see (Listing 10). Flash Catalyst generates names that are generic; changing the names will help in creating a code that is more coherent. See the table below that shows the original names and new component names. Adding id property to components Adding id property or renaming id property names should be done on a need to need basis. For instance, add an id to the list component in the Body project:

Figure 15. Convert artwork to button





Figure 14. Body Flash Catalyst project showing list components



DataGrid with List component or add a custom button that was left out, or, while integrating the application you may find that pieces that do not make sense may need to be changed. During that process the designer can help and provide any assets necessary. You may also need to get the business side involved in order to adjust documents or get in touch with the client to provide additional information. To import the project from Flash Catalyst into Flash Builder open Flash Builder and from the top context menu. Select File>Import Flex Project (FXP)… see (Figure 20). Follow the same process to import the following projects: • Body.fxp



• Footer.fxp • Header.fxp • LeftNav.fxp



Figure 17. Convert artwork to text input component



70



06/2009 (8)



Designer-Developer workflow



Listing 8. Add references to MainWindowView.mxml





xmlns:mx="library://ns.adobe.com/flex/halo"











arrowDown.png')" resizeMode="scale"











Listing 10. Refactored TagsListDownButton.mxml component





2009"



[HostComponent("spark.components.Button")]















initialize="modelLocator.mainPM.initialize()"> x="0" y="0"/> arrowDown.png')"



private var modelLocator:ModelLocator = ModelLocator. getInstance();



Listing 11. Adding click events to HeaderView.mxml





]]>







eader.components.MaxButton" eader.components.MinButton"



resizeMode="scale" d:userLabel="background"/>







ader.components.AxisButton"











Listing 9. TagsListDownButton.mxml component created by Flash Catalyst

















[HostComponent("spark.components.Button")] fx:Metadata>











06/2009 (8)



71



ActionScript Development



Figure 19. Project folder structure



Figure 18. Body project imported into Flash Builder



Figure 20. Import project into Flash Builder



Figure 21.Folder and files structure after adding presentation model classes into projects



Listing 12. Add event SearchTwitterAPIEvent.as



Listing 13. Add a key down event to RichEditableText component

keyDown=" new SearchTwitterAPIEvent(searchInputBox.text).di spatch()"



package com.elad.twitter.events { import com.adobe.cairngorm.control.CairngormEvent; import flash.events.Event; /** * * Defines the "SearchTwitterAPI" use-case which represent a specific * user based event or system event. * * @see com.adobe.cairngorm.control.CairngormEvent * */ public final class SearchTwitterAPIEvent extends { CairngormEvent















import com.elad.twitter.events.TagsSearchEvent;



[HostComponent("spark.components.TextInput") ]







public var keyword:String = ""; public static const SEARCHTWITTERAPI_EVENT:String ~CCC = "com.elad.twitter.events.SearchTwitterAPIEvent";















search.png')"



{



public function SearchTwitterAPIEvent(keyword:String) this.keyword = keyword; super( SEARCHTWITTERAPI_EVENT );



width="97" heightInLines="1"



}



public override function clone() : Event { var event:SearchTwitterAPIEvent = new SearchTwitterAP return event; IEvent(keyword);







}



}



}



72



06/2009 (8)



ActionScript Development



Listing 14. Implement logic to call Twitter service in SearchTwitterAPICommand

package com.elad.twitter.commands.services { import com.adobe.cairngorm.commands.ICommand; import com.adobe.serialization.json.JSON; } /** * * Handles the service result of the SearchTwitte rAPIDelegate * service invocation. * * @see mx.rpc.events.ResultEvent * */ public function result(data:Object) : void { // logging result to logging API logger.info("result"); var result:ResultEvent = data as ResultEvent; var feedsResults:Object; try { var str:String = String(data.result); feedsResults = JSON.decode(str);



import com.adobe.cairngorm.control.CairngormEvent; import com.elad.twitter.business.SearchTwitterAPIDelegate; import com.elad.twitter.events.SearchTwitterAPIEvent; import com.elad.twitter.model.ModelLocator; import com.elad.twitter.vo.TweetsCollectionVO; import flash.utils.getQualifiedClassName; import mx.collections.ArrayCollection; import mx.logging.ILogger; import mx.logging.Log; import mx.rpc.IResponder;



import mx.rpc.events.FaultEvent;



import mx.rpc.events.ResultEvent; public final class SearchTwitterAPICommand implements { ICommand, IResponder



/** * * Defines a local convenience reference to the application * ModelLocator implementations * */ private var model:ModelLocator = ModelLocator.getInsta nce(); } } {



catch (err:Error) // todo: handle errors messages Log.getLogger("There was and Error loading the Feed return; Manager Data :: ").error("fault");



/** * Create variable to point to this class. * * @private * */ private var logger:ILogger = Log.getLogger(getQualifiedCl assName(this).replace("::", ".")); }



model.bodyPM.tweetCollection = new TweetsCollectionVO( new ArrayCollection( feedsResults.results ) );



/** * * Handles the service fault of the SearchTwitter APIDelegate * service invocation. * * @see mx.rpc.events.ResultEvent * */ public function fault(info:Object) : void { var fault:FaultEvent = info as FaultEvent; // logging fault to logging API } logger.error("fault", fault); handles



/** * * Concrete ICommand implementation which * an SearchTwitterAPIEvent. * */ public function execute(event:CairngormEvent) : void { // logging command to logging API logger.info("execute"); var evt:SearchTwitterAPIEvent = event as var delegate:SearchTwitterAPIDelegate = new SearchTwi tterAPIDelegate( this ); SearchTwitterAPIEvent; }



}



delegate.getSearchResults(evt.keyword);



74



06/2009 (8)



Designer-Developer workflow



Listing 15. TweetVO.as

package com.elad.twitter.vo { import com.adobe.cairngorm.vo.IValueObject; [Bindable] /** * * Defines the AssetVO Value Object implementation * * @see com.adobe.cairngorm.vo.IValueObject * */ public class TweetVO implements IValueObject { public var created_at:String; public var from_user:String; public var id:String; public var from_user_id:String; public var iso_language_code:String; public var profile_image_url:String; public var source:String; public var text:String; } public function TweetsCollectionVO(collection: { ArrayCollection = null)



if (collection == null) { } { } _collection = new ArrayCollection();



else _collection = collection;



public function addItem(item:TweetVO):void { } _collection.addItem(item);



public function getItem(index:int):TweetVO { } { return _collection.getItemAt(index) as TweetVO;



public var to_user_id:String; {



public function readAssets(index:Number):TweetVO var retVal:TweetVO; return retVal;



public function TweetVO(item:Object) this.created_at = item.created_at; this.from_user = item.from_user; this.id = item.id; this.from_user_id = item.from_user_id; this.iso_language_code = item.iso_language_code; this.profile_image_url = item.profile_image_url; this.source = item.source; this.text = item.text; }



retVal = _collection.getItemAt(index) as TweetVO; } { } { }



public function get length():Number return _collection.length;



public function get collection():ArrayCollection return _collection;



this.to_user_id = item.to_user_id; }



}



}



}



Listing 16. TweetsCollectionVO.as

package com.elad.twitter.vo { import com.adobe.cairngorm.vo.IValueObject; import mx.collections.ArrayCollection; [Bindable] /** * * Defines the AssetCollectionVO Value Object implementation * * @see com.adobe.cairngorm.vo.IValueObject * */ public class TweetsCollectionVO implements IValueObject { private var _collection:ArrayCollection;



Listing 17. HTTPService component to access Twitter search API

2006/mxml" .*" >







]]>







url="http://search.twitter.com/search.json"



06/2009 (8)



75



ActionScript Development



Listing 18. SearchTwitterAPIDelegate.as

package com.elad.twitter.business { import com.adobe.cairngorm.business.ServiceLocator; import mx.rpc.AsyncToken; import mx.rpc.IResponder; import mx.rpc.http.HTTPService; /** * * Defines the associated Business Delegate for the "SearchTwitterAPI" * use-case. * * * The SearchTwitterAPIDelegate is utilized to abstract * an asynchronous service invocation in which the response is * to be relayed to an IResponder implementation. * * */ public final class SearchTwitterAPIDelegate { /** * * Defines the reference to the SearchTwitterAPICo mmand * instance. * */ private var responder:IResponder; /** * * Define reference to the service which can be one of the RPC (HttpService, WebService or RemoteService) * */ private var service:HTTPService; /** * * Instantiates a new instance of SearchTwitterAP IDelegate * and initializes a reference to the IResponder instance. * */ public function SearchTwitterAPIDelegate(responder: { IResponder)















scrollNav.png')"







x="561" y="464"/>



gsDataList"



service = ServiceLocator.getInstance().getHTTPService (Services.GET_TWITTER_SEARCH_RESULTS); ~CCC







this.responder = responder;



76



06/2009 (8)



To see the changes we made to the application download Step2 see (Figure 22).



Step 4 – Refactor

As you create different FXP projects there are cases where you are using very similar components and skins, and you want to avoid that and try to refactor so you take into account reusability, which is one of the building blocks of Object-Oriented programming. For instance, because a button label is different you should not have two button skins. You should adjust the skin so it can handle these two instances and remove one skin, which will make your application smaller in size and more optimized. A good idea is creating a folder named shared which can hold the components you will be sharing as well as components that are tweaked to be used in more than one component.



Step 5 – Develop

At this point we have a project with separate components and a great structure to build an application that can be scaled. We can now add code so we will be able to search twitter and display results. Remove chrome In our application we will be handling moving the application and minimizing, maximizing, and closing the application. To remove the AIR application chrome we first need to open Main-app.xml file and uncomment and set the following line of code:

none



Adding interactivity to header The next step is to allow moving, minimizing, and maximizing windows since we removed the chrome. Open HeaderView.mxml and add click events. Add event SearchTwitterAPIEvent.as. Once the user inserts a keyword query the event will be dispatched



ON the 'Net

• • • • • • • • Books: http://www.amazon.com/s/?url=search-alias%3Daps&field -keywords=Elad%2BElrom Blog: http://elromdesign.com/blog Blog2: http://advanced.flashmobilebook.com/ LinkedIn: http://linkedin.com/in/eladelrom Twitter: http://twitter.com/EladElrom Developer spotlight: http://www.adobe.com/devnet/spotlight/ spotlight_eelrom.html Oreilly: http://www.oreillynet.com/pub/au/3671 FlashMagazine: http://www.flashmagazine.com/About/user/403



Figure 22. Twitter AIR application screenshot



06/2009 (8)



77



ActionScript Development



and pass the keyword result to the command. We will set the application so that a keyword search will occur on every user gesture key



down event handler. Add a key down event to the RichEditableText component in the SearchTextInput.mxml component.



In the SearchTwitterAPICommand we will implement the logic to call the Twitter service. Creating value object to hold results Once we receive the response from the Twitter API we will create a collection to hold the results and assign them to the list. Every Tweet will hold the properties we are setting in TweetVO.as. To hold the collection of Tweets, we need to create a VO (Value Object) called TweetsCollectionVO.as and add properties to add an item and retrieve an item. Services.mxml component holds all the service components. In our case we only need a HTTPService component to access the Twitter search API. The delegate class is using the Services class to send a request and direct the result back to the command, see SearchTwitterAPIDelega te.as class. In the BodyView.mxml component we need to add a data provider for the list so it points to the collection we created. Lastly, we need to add code that will extract the data in TagRepeatedItem.mxml and create a renderer that will display the user profile image and the text of the tweet. To compare your application with ours see Step3/TwitterTag application. Once you compile you can see (Figure 23). The application is completed and you can place keyword into the search input box and see the results in the list we created.



Listing 20. Extract data in TagRepeatedItem.mxml





import com.elad.twitter.vo.TweetVO; import mx.events.FlexEvent; { protected function creationCompleteHandler(event:FlexEvent):void // TODO Auto-generated method stub var tweet:TweetVO = new TweetVO(this.data); image.source = tweet.profile_image_url; } text.text = tweet.text;







]]>







































ELAD ELROM

Elad Elrom is a rising star of the Flash development world. He brings a fresh perspective, a strong background, and an inherent knack for the more subtle aspects of the Flash platform. He’s been involved very early in a number of Adobe products. Elad Elrom is a consultant, technical writer and technical lead. As a technical writer, Elad wrote books covering Flash technologies. He maintains an active blog and has spoken at several conferences regarding the Flash platform. He has helped companies follow the XP and Scrum methodologies to implement popular frameworks, optimize and automate built processors and code review, and follow best practices. Elad has consulted a variety of clients in different fields and sizes, from large corporations such as Viacom, NBC Universal, and Weight Watchers to startups such as MotionBox.com and KickApps.com. Follow Elad on Twitter: http://twitter.com/ EladElrom



Figure 23. AIR application shows search results



78



06/2009 (8)



ActionScript Development



Migrating from AS2 to AS3

by Gábor Csomák

ActionScript went through a great and significant evolution in the last few years. The first ActionScript version had basic movie control with some interactive capability.



Level of difficulty



W

Benefits



What you will learn…

• • AS3 is: easy, fast, and fun Understanding basic AS3 codes



ith ActionScript 2, Flash became a powerful and easy programming language, with great opportunities for website development. People loved making games and websites with AS2. However, there were some main issues and problems, so it was easy to forecast that a new version of AS would arrive. It happened in 2006 with Flash 9. Some of you still use AS2 for Flash development. In this article, you’ll see that AS3 is fun, and learning it will save you time and effort; so don’t hesitate: dare to discover the novelties and the possibilities that you could use in your future.



• With knowledge of AS3, learning Flex 3 or 4 will be a piece of cake! • Binary data support (.txt, .pls, …) There are also some small treats as well, like: trace function with the possibility to have multiple parameters see (Listing 1), easy to handle double clicking, runtime frame-rate changing, re-parenting, for..in loops, and so on.



Mistaken assumptions

Why doesn't everybody uses AS3, and wipe AS2 out of the world? In my opinion, the main reason people are afraid of changing to AS3 are the following mistaken assumptions: • Difficult to learn: false! Actually it's very easy.. you'll just need to get used to some differences, and if you don't know something, just Google: what is in AS3? (Ex.: what is on(click) in AS3?) The result will give you countless forum threads, where the answers are, and the helpful programmer community will happily share their tips and tricks. So trust me, it won't be as hard as you assume. It just needs a bit of practice. • AS3 is only for class-based OOP programming: false! You can still use the same coding techniques! In fact this is the easiest way to learn it.



What you should know…

• Basic Flash coding experience



Let's see the main benefits of learning ActionScript 3: • Improved performance – AS3 is 10 to 100 times faster (!) than its previous version (mostly because of the new virtual machine: AVM2, and the hardware acceleration from Direct X and OpenGL) • You can use the newest Flash Player API technologies, like Google Maps, Flickr, and so on. • Easy way to import public libraries to save you time, and ensure quality. • Debugging AS3 is much faster, clearer, and easier. • AS3 is future proof, but who knows how long Adobe supports AS2. • Can be Object Oriented. (It's not necessary) • You could gain transferable skills to other OOP languages, such as Java, or C++.



funny quote

• • • • • • • • • • •



The Differences between ActionScript 2 and ActionScript 3 (found on actionscripter.co.uk/blog/?p=237) as3.0 is like a strict german mistress. Very harsh but gets good results. as2.0 is your stoner friend from college. as1.0 is for script-kiddies, designers and other non-technical people as2.0 is for girls as3.0 is for real men and woman as3.0 is carefully crafted formulaic pop – predictable, slick, reliable, dull as2.0 is glitchy electronica – some semblance of form, but playful with it as1.0 is a child bashing saucepans – imprecise, messy, but lots of fun as3.0 is a Japanese Chef’s knife. Finely crafted but requires care and technique in its use. as2.0 is a Machete. Great for hacking things, but useless for anything requiring fine detail or control. as1.0 is a plastic spoon.



80



06/2009 (8)



Migrating from AS2 to AS3



Listing 1. trace() in AS3

var str:String=" world!"







trace(„hello", str); // traces: „hello world!"



Listing 2. Calling onRelease() after pressing a button in AS2 and AS3

//In AS2: myBtn.on(release) { onRelease() }



onRelease = function(){ }



trace("myBtn pressed!");







//In AS3: myBtn.addEventListener(MouseEvent.CLICK, onRelease); function onRelease(myEvent:Event):void{ } trace("myBtn pressed!");







Listing 3. Modifying onRelease function go to adobe.com

function onRelease(e:Event):void{







var request:URLRequest = new URLRequest("http://www.adobe.com"); // Create a variable from the URLRequest Class and set the URL navigateToURL(request);



And if you like it, and want to be more effective, you can look up, what is OOP, and how to use it in Flash. Reduces Flash player base: false again! 99.6% of internet capable devices have FP9 support, and about 94.5% have FP10 support in US and Canada, in September 2009, based on statistics. There are some mobile devices which only handle FlasLite2. (Source and further information: http://www.adobe.com/products/ player_ census /-flashplayer/version_ penetration.html) With AS3 you can't write code on a timeline. I have a surprise for you! You can – and it is more obvious to read than in AS2. The process of development is slower: false. In Flex Builder – thanks to the Eclipse base – it's surprisingly fast to create ActionScript files, or Flex applications. Adobe is also working on the new code editor, and it'll hopefully become available in CS5. AS3 is bigger in code: I don't think so. Even more, if you'll get used to it, it 'll give you a clearer code for reading.



}



Examples

Let's write out first AS3 code: The first goal is to add an onClick event to the button named myBtn. You can see it in (Listing 2). In AS3 we add an event listener to the movie clip instance. The addEventListener function has two parameters: the first one is to define what will trigger the function given in the second parameter. The onRelease() function will have a parameter in AS3, and it's type is Event. You should try to add a breakpoint into the function, and see what myEvent variable contains. For example if you address myEvent.currentTarget, you'll get a pointer to the MovieClip pressed (in the example its myBtn). In (Listing 3) I've modified the code, so if you click myBtn, the browser will navigate to adobe.com. From this example you should also learn how to declare functions and variables (request is a var, and its type is URLRequest). In (Listing 4) you can see, how the Timer class works. Don't worry, it'll be easy to get used to the event listeners. I could go on, and show you more examples in this article, but I think I'll soon be out of space. But don't worry, most of this magazine is written in AS3, so you can see the new syntactic from the other articles, and you can also look up the Internet for more AS3 examples.



Listing 4. A simple timer example in AS3

function timerExample():void{



private var delay:uint = 3000; //delay will be 3 secs will triggerd 9 secs after start.



private var repeat:uint = 3; //repeats 3 times, so completeHandler private var myTimer:Timer = new Timer(delay, repeat);



myTimer.addEventListener(TimerEvent.TIMER, timerHandler);



myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, completeHandler);



myTimer.start(); //starting the timer function timerHandler(e:TimerEvent):void{



repeat--; //this is not the timers repeat property! }



trace(((delay * repeat) / 1000), " seconds left.");



//called if timer is completed } trace("Time's up.");



private function completeHandler(e:TimerEvent):void {



}



Listing 5. Loading a MovieClip to stage from the library

var myCircle:circle = new circle(); myCircle.x = 100; myCircle.y = 100;



Migration problems

However it'll be easy to migrate, you can have some nerve racking issues. I've collected some of these, to save you time and spare stressed moments.



addChild(myCircle);



06/2009 (8)



81



ActionScript Development



Table 1. Most important event types in AS3 AS2

onPress onRelease onReleaseOutside onRollOver onRollOut onDragOver onDragOut mouseDown mouseUp mouseMove onKeyDown onKeyUp onReleaseOutside



AS3

"mouseDown" ( MouseEvent.MOUSE _ DOWN) "mouseUp" ( MouseEvent.MOUSE _ UP), "click" (MouseEvent.CLICK) "mouseUp" ( MouseEvent.MOUSE _ UP) "mouseOver" ( MouseEvent.MOUSE _ OVER), "rollOver" ( MouseEvent.ROLL _ OVER) "mouseOut" ( MouseEvent.MOUSE _ OUT), "rollOut" ( MouseEvent.ROLL _ OUT) "mouseOver" ( MouseEvent.MOUSE _ OVER), "rollOver" ( MouseEvent.ROLL _ OVER) "mouseOut" ( MouseEvent.MOUSE _ OUT), "rollOut" ( MouseEvent.ROLL _ OUT) "mouseDown" ( MouseEvent.MOUSE _ DOWN) "mouseUp" ( MouseEvent.MOUSE _ UP) "mouseMove" ( MouseEvent.MOUSE _ MOVE) "keyDown" (KeyboardEvent.KEY _ DOWN) "keyUp" (KeyboardEvent.KEY _ UP) NONE "doubleclick" ( MouseEvent.DOUBLE _ CLICK)



(unavailable in AS2) Listing 6. Handling buttons with one function

import flash.events.MouseEvent; //if you import flash.events.*, you'll import everything from flash.events function clickHandler(event:MouseEvent):void { switch(event.currentTarget){ case myBtn1: Break; // do something...



case myBtn2: Break;



// do something...



case myBtn3: Break;



// do something...



}



}



myBtn1.addEventListener(MouseEvent.CLICK, clickHandler); myBtn2.addEventListener(MouseEvent.CLICK, clickHandler); myBtn3.addEventListener(MouseEvent.CLICK, clickHandler);



• underscores: _ x _ y _ rotation, _ parent is now x, y, rotation, parent • _ alpha=21 is now alpha=0.21 (in AS2 _ alpha was between 0 and 100, now alpha is between 0 and 1) • _ xmouse and _ ymouse is now mouseX and mouseY • _ xscale and _ yscale is now scaleX and scaleY • You'll use void instead of Void • The scope operator is now . instead of :: • random() is now Math.random() (Returns a pseudo-random number n, where 0



implementation of the concrete methods can have many forms. One of the methods in the interface is loadContent(), and you can probably think of several different algorithms that actually load content – SWF files, image files, XML file data, text file data. However, the algorithm that loads an SWF file uses different operations from one that loads the contents of an XML file. So, while two methods named loadContent() are similar in that they load external content, they’re very different in the



Builder creational











Factory Method creational



Adapter structural











Decorator structural











Observer behavioral











State behavioral











Strategy behavioral











Template Method behavioral



way in which they carry out the operation. As we all know, a family member may have two cousins, Alice and Jeff, and while they’re both cousins they are very different. In the same way, a method may be implemented in different ways to get a job done even though the jobs are similar. In setting up a Strategy interface, you have to plan ahead. Usually, when you build an interface, methods that return an object return the same kind of object. For example, your algorithm might return a Sprite, and all implementations of the method returns a Sprite. However, sometimes you want to return data as different data types. In work with XML files, a common practice is to load the contents of the XML file into an array. When a text file is loaded, however, the contents are typically placed into a string. In order to return more than a single data type, you need to type the return using a wildcard character, [*]. Thus, the second, method, getContent(): * uses the wildcard to send data back to the Client. (Listing 2) shows the code for the Strategy interface. Like most interfaces, this one is simple. The name, IStrategy follows the convention of placing a capital I as the leading character in the interface’s name. Notice that the loadContent() operation has two parameters, String and Function types. The String expects the file name of the XML or text file you will be loading. In this example, all of the files are in the same directory to keep it simple so you just need the file name. More typically, separate folders or even separate servers to store the data files, and so the String would be a full URL. The second parameter is a function used to trigger an operation that delivers the data once the external data are all loaded. This is important because the second function must wait to be called until the data are loaded. Triggering the second method before the first one has a chance to load all the data results in an empty package sent.











Concrete Strategy: LoadXML

The first of the two implementations of the IStrategy loads data from an external XML file. So the first thing we’ll need is an XML file with data. In this case, the XML file contains “data points” containing the name of a design pattern and the type of design pattern as being creational, structural or behavioral. (Listing 3) shows the sample XML file we’ll use. Save the file as FlexFlash.xml and store it in the same directory as the other files for this project. You really don’t need the id attributes in the dataPoint tags, but they can be handy if you want to pull out a specific pattern and type category. So, when you look at the



Listing 4.

var dpXML:XML=



Template Method behavioral



;







trace(dpXML.dataPoint.designpattern); trace(dpXML.dataPoint.category);



86



06/2009 (8)



Unconditional Patterns



implementation for loading the XML file data, you will not see a reference to the attribute in the dataPoint tags. If you are not familiar with the ECMAScript XML specification, you might want to take a peek at it. This is especially true if you’ve worked with XML for a while and are unfamiliar with E4X. (It’s not your father’s XML). In fact, if you’re very familiar with OOP but not with XML understanding EX4 may be easier because it works more like objects and properties. Known as Ecma-357, you can find the specs at: http://www.ecma-international.org/ publications/standards/Ecma-357.htm. Fortunately, you will find this new XML simplified over the older versions. Basically, an XML object is a lot like any ActionScript

Listing 5.

package { import flash.net.URLRequest; import flash.net.URLLoader; import flash.events.Event;



3.0 object. The XML objects use the operator (). to delineate its properties. The ActionScript 3.0 code in (Listing 4) shows how the XML tags can be retrieved as properties of an XML object. When the code in Listing 4 is run, the Output window shows the following:

Template Method behavioral



It’s way beyond the scope of this article to explain XML, but if you just think of XML as a set of objects with properties it’s not too difficult to understand. What this program will do is load XML and get the properties from its various objects and put them into an array.

Listing 6.

package {



All we need for loading XML data are an URLRquest object to locate the file, a URLLoader to pull up the data and an Array object to store the loaded data. An EventListener informs us when the data are loaded and triggers the fileUp() method that places the XML data into an array. Once that process is completed, it then triggers a dispatch event used to let the Client know that it can call the getContent() method to get the data. You may be thinking, now just a minute! The IStrategy has no fileUp() operation. That’s okay. As long as an implementation has all of the interface elements, it can add any other methods it wants to use. Both the loadContent() and getContent() methods are public so



import flash.net.URLRequest; import flash.net.URLLoader; import flash.events.Event;



import flash.events.EventDispatcher; public class LoadXML extends EventDispatcher implements { IStrategy



import flash.events.EventDispatcher; public class LoadText extends EventDispatcher implements { IStrategy



private var dataArray:Array;



private var xmlURL:URLRequest;



private var dataString:String; private var txtURL:URLRequest; private var contentLoader:URLLoader; public function loadContent(url:String, callBackFn: { Function):void



private var contentLoader:URLLoader; public function loadContent(url:String, callBackFn: { Function):void



xmlURL = new URLRequest(url);



contentLoader = new URLLoader(xmlURL); fileUp);



txtURL = new URLRequest(url);



contentLoader.addEventListener(Event.COMPLETE, }



}



contentLoader.addEventListener(Event.COMPLETE, fileUp);



contentLoader = new URLLoader(txtURL);



private function fileUp(e:Event):void { dataArray=new Array();



private function fileUp(e:Event):void { dataString = String(e.target.data);



var xmlNow = XML(e.target.data); {



// dispatch event to Client } dispatchEvent( new Event( Event.COMPLETE ) );



for each (var dataPoint:XML in xmlNow.dataPoint) dataArray.push(dataPoint.designpattern + ": type= " +dataPoint.category+ "\n");



// dispatch event to Client } dispatchEvent( new Event( Event.COMPLETE ) ); } }



}



public function getContent():* { } return dataString;



public function getContent():* { } return dataArray;



}



}



06/2009 (8)



87



ActionScript Development



that they can be used by the Client, but the fileUp() method is private and acts as an interlude to allow the data to be placed into an array before it is sent to the Client using the getContent() operation. (Listing 5) shows the full implementation. Note that the LoadXML class extends the EventDispatcher class. That is so that the class can use the EventDispatcher methods to alert the Client when the data are ready to ship.

Listing 7.

package { import flash.display.Sprite; import fl.controls.TextArea; import flash.events.Event; import fl.controls.Button; import fl.controls.Label; import flash.text.TextFormat; import flash.events.MouseEvent;



Concrete Strategy: LoadText

The LoadText implementation of IStrategy is almost identical to LoadXML with the exception that instead of an XML file, the LoadText class loads text from a text file. The first order of business is to create a simple text file with the following contents: Sometimes, all you need is a simple text file for the information. For example, a store owner may have daily Specials that are regularly updated. Like the following...



Today Only! Special sale on Conditional-Free design patterns! Save 30% off regular CPU costs! Once you put that into a text file, save the text file as test.txt. in the same directory as the other files for this project. Listing 6 shows the implementation of IStrategy for loading and delivering a string from a text file. It is slightly shorter because the algorithm for loading text from a text file does not entail storing the contents in array elements. It treats the entire contents as a single string.



lab.text = "Your Information"; formatBtn.color = 0xB64926; formatBtn.size = 12; 2)+40;



xmlBtn.x=textArea.stage.stageWidth/2-(textArea.width/ xmlBtn.y = textArea.y + textArea.height + 24; xmlBtn.label = "Show XML"; xmlBtn.setStyle("textFormat",formatBtn); currentXML);



public class ClientStrategy extends Sprite { private var showXML:Context=new Context(new LoadXML()); private var showText:Context = new Context(new private var textArea:TextArea=new TextArea(); private var textFormat=new TextFormat(); private var formatLab=new TextFormat(); private var formatBtn=new TextFormat(); private var xmlBtn:Button=new Button(); private var txtBtn:Button=new Button(); private var lab:Label=new Label(); public function ClientStrategy() { } setUI(); LoadText());



xmlBtn.addEventListener(MouseEvent.CLICK, addChild(xmlBtn);



txtBtn.x=xmlBtn.x + (xmlBtn.width + 10); txtBtn.y = xmlBtn.y; txtBtn.label = "Show Text";



txtBtn.setStyle("textFormat", formatBtn); currentTxt);



txtBtn.addEventListener(MouseEvent.CLICK, addChild(txtBtn);



} {



private function currentXML(e:MouseEvent) textArea.text = "";



} {



showXML.bringUp("FlexFlash.xml", displayXML);



private function currentTxt(e:MouseEvent) textArea.text = "";



private function setUI() { textFormat.color = "0x468966"; textFormat.size = 14; textFormat.font = "Verdana";



} {



showText.bringUp("test.txt", displayText);



private function displayXML(e:Event) var showNow:Array = showXML.deliverContent(); for (var dataNow in showNow) { }



textArea.setStyle("textFormat",textFormat); addChild( textArea );



textArea.width = 300,textArea.height = 200; textArea.x=textArea.stage.stageWidth/2textArea.y = textArea.stage.stageHeight/2(textArea.height/2); (textArea.width/2);



textArea.appendText(showNow[dataNow]);



} {



private function displayText(e:Event) var showNow:String = String(showText.deliverContent textArea.text = showNow; ());



formatLab.color = 0xFFB03B; formatLab.size = 24; addChild(lab); lab.width = 250; }



lab.x = textArea.x;



}



lab.y = textArea.y – 32;



lab.setStyle("textFormat",formatLab);



88



06/2009 (8)



Unconditional Patterns



As you can see, once the file is loaded, the method simply places the data in a string (dataString) which is ready to be delivered in the getContent() method. The fact that it is returning a string instead of an array doesn’t matter because the method uses the wildcard [*] as a return type.

fileUp()



• Client Class: private var

Context=new LoadXML());



The Client Class: ClientStrategy

Finally we’re all set to request the contents of either a text or XML file. Only a small part of the Client class (ClientStrategy) in fact uses the design pattern. Remember, all that a Client does is to make requests. The SetUI() function just builds the UI, and the actual calls are made through the currentXML() and currentText() functions. Each of those functions has two lines, and the first line just clears the text area. So, we’re really down to just a single line used in each Client call for either XML or text file data.

showXML.bringUp("FlexFlash.xml",



//This first step provides you with a Context instance with which you can call a function to get the data. • Client Class: showXML.bringUp("FlexFla sh.xml", displayXML); //Now your instance specifies the XML file you want and the callback function. (If you look at the ClientStrategy class carefully, you will find displayXML() – that’s the callback function for XML files). • Context Class:bringUp()>fetchData.l

Function);



Context(new



showXML:



classes so that your program can better handle change.



Are You Ready for Design Patterns?

Sometimes we get into programming ruts. If you perform the same kind of programming tasks day-in and day-out; you’re not going to start changing (improving) your practices unless you have a good reason to do so. We all know that the devil in self-development is the pseudowisdom, if it ain’t broke, don’t fix it. After all, you get paid the same whether your programming practices are mediocre or excellent – as long as your programs work and are done on time. When it comes to design patterns in ActionScript 3.0 programming, no one is going to tell you with a straight face that learning design patterns is easy. They’re not, and that’s why a lot of people cannot develop programs with them. However, more and more you will see design patterns as a requirement (or desired attribute) for job openings where ActionScript 3.0 skills are imperative. In a recent search for job openings at one online recruitment site for technology jobs where ActionScript was a requirement, 44 of the openings listed design patterns as desirable. (At the same technology job site, 1667 positions in all programming languages listed design patterns as a requirement!) So, if you’re looking for a practical reason to pick up a few design patterns, the job market is one. Besides being more marketable, being a better programmer has value in its own right. In a 1998 book about using OOP with JavaScript, Alexander Nakhimovsky and Tom Myers note that one reason to employ OOP is the pleasure of doing something well. I think that all programmers know that pleasure, whether it’s solving a tricky algorithm or discovering a new feature in the language. For me, that’s the addicting nature of programming, especially in ActionScript 3.0. For every level, there’s always a new challenge, and I cannot think of anything more worthwhile.



// The fetchData instances is typed as IStrategy and the concrete instance has been passed as LoadXML. The value of url is FlexFlash.xml and callBackFn is set to displayXML. • Next, the statement, EventDispatch



oadContent(url:String, callBackFn:



displayXML);



or

showText.bringUp("test.txt", displayText);



Event.COMPLETE, callBackFn ); // Listens for the signal that the data are loaded and sends the data to the callback function when ready. • LoadXML Class: loadContent(url:



er(fetchData).add EventListener(



Both of the instances are Context ones. However, because the Context has an aggregate relationship with the IStrategy interface, when the Context instances are instantiated, they are done so specifying the concrete strategy through the IStrategy interface. Thus, the lines:

private var showXML:Context=new private var showText:Context = new Context(new LoadText()) Context(new LoadXML());



//loads the data from the XML file and calls the fileUp() function when the content is loaded. • LoadXML Class: private function fileUp(e:Event):void //Takes the XML data and parses it into an array. When finished it dispatches an Event.COMPLETE message back to the displayXML function in the Client • Client Class: var showNow: //This is fired by the method which calls the deliverContent() method in the Context Class. • Context Class: return this.fetchData.g etContent(); //Calls the getContent() method in the LoadXML class and returns the data to the Client. • LoadXML Class: return dataArray; / /This is the final call to the LoadXML class to retrieve the loaded data. • Client Class: textArea.appendText(s howNow[dataNow]); The delivered data is placed into the text area component, one element at a time until all elements are there.

erContent()); displayXML() String = String(showText.deliv



String,



callBackFn:Function):void



not only instantiate the instances as Context types, they also specify the concrete Strategy. However, because the parameters of the Context constructor include an IStrategy type, the declarations are really typed as the interface implemented by the concrete strategies. So, while the instances are Context ones, they have an aggregate relationship to the IStrategy interface. What does that mean? Essentially, it’s a way to deal with instances that have more abstract characteristics. As such, it’s easier to add changes without the program locking up. Listing 7 shows the entire Client. Now that you’ve seen the entire Client, you can begin to better understand the wild ride this particular implementation takes. Stepping through it may help (we’ll use the XML call):



BILL SANDERS

Bill Sanders has been developing applications with and writing books about ActionScript, Flash Media Server and Flash/Flex for the past ten years. Some of the books he has published include ActionScript 3.0 Design Patterns [with Chandima Cumaranatunge] (O’Reilly), Learning Flash Media Server 3.0 (O’Reilly), Macromedia Flash MX Professional 2004 Kick Start (Sams), Macromedia Flash MX ActionScript: Complete Reference (McGraw-Hill). He has published over 60 books in all and is currently a professor in the Multimedia Web Design and Development program at the University of Hartford.



On the 'Net

• • http://www.as3dp.com http://www.sandlight.com



All of this may appear terribly convoluted, but once it is set up, you can easily add more implementations of IStrategy for further concrete Strategy classes. Likewise, you can add more Context classes or subclasses to add further flexibility. The whole point of this exercise is not to make things more difficult, but to establish looser relationships between



06/2009 (8)



89



ActionScript Development



Know your Language you must!

ActionScript 3 is a powerful language and with great power comes great responsibility. This quiz will measure your knowledge about the AS3 syntax, OOP in AS3 and the dark side of AS3. May the force be with you!



The Quiz:

1. What is the right trace output? var a = true; trace(a?"a":"b"); a) a b) b 2. Which lines of code can be compiled?:

trace(.toXMLString())



b) 5 c) 50 d) 100 e) won't compile 6. What will happen?



a) trace(10.toString()); b) trace(/dfgr/.source); c) trace(.toXMLString()); d) trace({a:12}.a.toString()); e) trace(true.toString()); f) trace([1,2,3].toString()); 3. What is the right trace output? var a = 10; trace((a=a*a,a/2)); a) 10 b) 5 c) 50 d) 100 e) won't compile 4. What is the right trace output? trace((var a=10*10,a/2)); a) 10 b) 5 c) 50 d) 100 e) won't compile 5. What is the right trace output? var f : Function; trace((f = function(){return 10},f()/2));



a) Compile Error b) Runtime Error c) trace "CloseTag" d) trace "CloseTag " 7. Which example can be compiled? a) package{class C1{function f1(){} function f1(i : int){}}} b) package{class C1{function f1(){} static function f1(i : int){}}} c) package{class C1{function f1(){} AS3 function f1(i : int){}}} 8. Which Constructor is OK? a) package{public class C1{public function C1(){}}} b) package{public class C1{function C1(){}}} c) package{public class C1{internal function C1(){}}} d) package{public class C1{private function C1(){}}} e) package{public class C1{public function C1():C1{return this;}}} f) package{public class C1{public function C1():void{}}} 9. Which example can be compiled? a) package{public class C1{public function C1(){super()}}} b) package{public class C1{public function C1(){this()}}} c) package{public class C1{public function foo(){super()}}} d) package{public class C1{public static function foo(){this}}} e) package{public class C1{public function foo(){super.foo()}}} 10. Which statement is wrong? a) I am able to import classes that are stored in a package with the name "default" (default is a keyword). Example: import default.ClassA;



a) 10



90



06/2009 (8)



Know your Language you must!



b) I am able to import classes that are stored in a sub package with name "default" (default is a keyword). Example import my.default.ClassA; c) I am able to import classes that are stored in a sub package with name "true" (true is a keyword). Example import my.true.ClassA; 11. What is the right trace output order? package { import flash.display.Sprite; trace("A"); public class Test extends Sprite{ trace("B"); function Test() { trace("C"); } trace("D"); } trace("E"); } trace("F"); a) A,B,C,D,E,F b) C,B,D,A,E,F c) B,D,A,E,F,C 12. Which example can be compiled? a) package{public class C1{namespace ns1; namespace ns2; ns1 function foo(){} ns2 function foo(){} }} b) package{public class C1{namespace ns1 = "ns"; namespace ns2 = "ns"; ns1 function foo(){} ns2 function foo(){} }} c) package{public class C1{namespace ns1; ns1 function foo(){} public function foo(){} }} d) package{public class C1{namespace ns1 = ""; ns1 function foo(){} public function foo(){} }} 13. What is the right trace output? trace(function(){return "hallo";}()) a) hallo b) won't compile



5) You are not allowed to make declarations inside of parenthesis but you are allowed to assign an annonymous function to a variable. So b) is correct. 6) In this question we make use of parenthesis, but also of inline XML. Inline XML has relaxative syntax so you can use AS comments inside XML and you can also inline AS with curly braces in inline XML. It is quite complicated but never the less d) is the correct answer. 7) AS3 is an object oriented language but method overloading is not supported. So a) is wrong, b) and c) are ok because in b) you don't overload but declare the method as static and in c) you declare it in a separate namespace. 8) In AS3 Constructors must be public and have no return type, so answers c) ,d) ,e) are wrong. Interesting case is b), it is correct although it has no modifier. It is still public - not internal as usual. 9) "super()" can only be called in the constructor, "this()" makes syntacticly no sense and "this" can't be placed in static methods. So the correct answers are a) and e). 10) This is an example of the dark side of ActionScript 3 normally all three answers should be wrong but b) is correct. So the right answers are a) and c) 11) When you first load a class into the memory, the static initializer code will be executed first. Just try it out, the correct answer is c). 12) As we already know from question 7), method overloading is not allowed but methods can be declared in different namespaces. If you have a namespace declared in your class and you don't initialize it with an URI, the package name, class name and the namespace name will be resolved as URI at runtime. That's why answer a) is correct. Answer b) is wrong because both namespaces have the same URI and so the methods are in the same namespace. Interesting fact is that methods without an explicit namespace are in the namespace with a blank URI. That's why c) is right and d) is wrong. To summaries it a) and c) are correct. 13) Functions in AS3 are closures and you can call a closure directly after declaring it. So a) is correct.



Summary

In this quiz we covered just a small part of AS3 specific language features. It's not a shame if you did not know all the answers and it is a shame if you write code that looks like code in questions 5, 6 or 10. Code must be clean and readable! We hope you had fun solving the puzzles. Maxim Zaks is lead programmer of FDT (Development Tool for Flash) at Powerflasher. Michael Plank is FDT evangelist at Powerflasher. Check out fdt.powerflasher.com



Resolution and explanation:

1) The question mark is a conditional operator. The syntax is quite simple: condition? positive case: negative case; So the right answer is a). 2) ActionScript 3 is a strict object oriented language. That means that it has no primitive types and every expression is an instance of an object. That's why you can use "." operator directly and call the methods. There is only one exception: the number literal. The Correct answers are b), c), d), e), f). 3) In ActionScript 3 you can concatenate expressions inside parenthesis and it will return the result of the last expression. Think of it like of an inline anonymous function. So answer c) is correct. 4) Same rules apply as in question 3) but inside the parenthesis you are not allowed to make declarations. e) is correct.



06/2009 (8)



91



Video



7 tips



for encoding to flash video

by Chaim Sajnovsky



01



Check sources well before converting:



A common error is to encode to flash video and don’t bother to analyze the source video first. Big mistake. A good start point is to get a great freeware software piece called GSpot (http://www.headbands.com/gspot/) and open your source with it. Gspot will tell you about all the important data: frame size, how was it encoded, datarate, etc. Once you know the frame size, you can easily get the aspect ratio. Aspect ratio is the relation between width and height, expressed as this: “4:3”. So if your source is 400 pixels width, and the height is 300 pixels height, the relation is clear. Mainly is based on the classic tv screen for standard resolution. Today we have a lot of 16:9 aspect ratio videos, coming for hd tv sets. Now, 16:9 aspect ratio is the classical cine movies screen. So have you seen the old effect that cine movies took when screened on tv? (I mean, old cine movies). You see distortion, and that is what you get 16:9 videos converted to 4:3. This is the effect I’m trying to avoid in this point: If you know the source video aspect ratio, just resize your video up or down following the same aspect ratio and nobody gets hurt. A nice, proportioned video is the output. But also think this: If your video is 400x300 and you convert it to 640x480, expect a lot of degradation. Up scaling videos is not too wise. Downscaling is generally harmless. Furthermore, internal conversion codecs love proportions. As rule of thumb, get your width and height to be multiples of 16. Why? This is a long explanation about internal codec architecture..



02 03

92



Best video formats to convert:



Here we go: you got the sources ready to convert. Wait a minute. Are you sure you want those sources as is? Flash video is a final video format, that means is a really optimized format. In plain English, very, very compressed. So why not asking for good sources when possible? Have you seen those pristine videos for movie trailers or those commercial ads? Asking yourself how they got that nice quality? The answer is, few converting steps. As much close you are from the original shoot, the better. I always ask for high quality quicktime files or .avi ones, and the less compressed and the higher the quality as possible. Otherwise, think about a ultra-compressed and optimized file ( one as divx, flv, h264) that has left a lot of information on his way, being converted AGAIN… You can see and even count the pixels with the naked eye.



Check well target kbps before converting:



I often hear this idea: The higher datarate I compress, the higher quality I get. True, but it has also a flipside problem: The higher the kbps we set, the higher our target kbps should be. Don’t rush to set a high data rate before you are really sure about 2 factors: Your target viewer internet connection and your web server throughput once loaded. The second point means, maybe your users have in deed a good internet connection, but make sure the server where you host your videos can deliver a sustained output for a lot of concurrent users. Ask your hosting/cdn provider about this point before encoding.



06/2009 (8)



7 tips for encoding to flash video



Let’s begin with the free ones: The classical FFMPEG is a good choice for general videos. Generally comes as a compiled utility to be run by command line. Also, you need to learn how to set the commands for settings. If you look for a more friendly version, get WINFF, a windows GUI based FFMPEG version (winff.org). About commercial solutions: There is a lot of tools for sure. My personal choices are for procoder 3, Sorenson squeeze 5, and main concept reference. They have a lot of source formats supported, ahd a lot of settings that you can play with in order to fine-tunning your coding. I would recommend to test several tools, and watch for speed, final quality and multiple settings. You can get the free demos at the relevant sites. Writing about settings is a little bit longer that this article scope. I further recommend you the Fabbio Sonatti blog: http://www.progettosinergia.com/flashvideo/flashvideoblog.htm. Fabio is the man if you really want to dive into flash video internals.



04



What tools should you use to convert?



In the old good (and basic) days of flash video, you only have an option: Sorenson codecs. Even we love those, Adobe saw flash video getting stuck in the race for keeping it as the king of internet video. But back then (back then I mean up to flash player 9 appeared, about year and a half ago) flash video has only one extension: .flv (stands for flash video..) Flv can be coded only with Sorenson codecs: Spark and VP6. Spark is a really old codec, not so efficient. VP6 adds better coding and optimization. Inside vp6 we can find some parameters to play, but not a lot. When flash player saw the light, the main feature was the support for h264 coded videos. This was revolutionary, because now the game is open for a myriad of h264 optimizations and parameters, and with a good internet connection, we can watch really good HD videos with a minimal amount of bitrate. As before, talking about h264 will take a lot, and it’s the subject for another article. But mainly we can say that the common extensions are .mp4 and Adobe owns format for h264 flash video, f4v. If you need more quality, go for h264. Bear in mind that coding to h264 takes a really huge amount of time compared to flv. But quality has a reward. If you need speed when converting and fastest reactions when play and seek, go for vp6. Vp6 also still has 2 pros over h264: You cannot work with alpha channel and cue points with the latter. Maybe we will see this fixed in a near future.



05



.flv or h264?



Flash video can be encoded(as another formats also) with constant bitrate or with variable bitrate. While constant bitrate (cbr) codes all the clip at the same bitrate no matters what changes in the video (more action, more color, totally black or total silence vs big band music), variable bitrate (vbr) acts in a more intelligent way. It analyzes first the picture, and then decides how much bitrate giving it depending on the changing abovementioned characteristics. But, cbr takes less time for encoding than vbr. Remember that you always set a maximum bitrate as limit for the vbr. A sort of cap, where the coder won’t pass this amount of kbps, but will profit from less than using the maximum when possible. Can this 2 ways affect our playout? Now, in flash video, basically, progressive video gets played from a http server. Streaming video from a rtmp server, as Flash media server, Wowza or Red 5. The rule of thumb says, cbr is better for streaming, and vbr is better of progressive. But Adobe people is always improving the flash player, so this could change any moment.



06



Constant bitrate vs variable bitrate



06/2009 (8)



07



One pass or two pass?

If you go for vbr, the option for 1 or 2 pass can be found at the coder software. But, what that it means? If you choose 1 pass, basically nothing changes from normal vbr coding. Now if you choose 2 pass, the coder will first analize the video and take notice about a lot of parameters, log that data and then based on the data chooses the best way to encoding the video. It’s as much as pre-analyze the video, take notes and then proceed to convert it. It’s much as improving the already improved vbr. Encoding for Flash video can be very successful or pretty poor if you don’t take heed on the small details. Happy encoding.



93



Interview



Mochi Media:

JAMESON HSU

 CEO OF MOCHI MEDIA Q: Tell us about Mochi Media.

A: We are currently the world's largest online games network powering a library of over 14,000 games that reach more than 100 million unique users each month. Mochi Media provides Flash game developers with services to monetize their games through micro-transactions and advertisements, as well as distribute and track their gaming content online in partnership with advertisers and online gamers. We are compatible with AS2 and AS3, and provide the most comprehensive tool suites online to enable developers to build compelling game experiences. Using our services, developers can make money from their games via micro-transactions and advertising, track distribution and usage analytics, and socialize their games through high scores and integration with social networks. In addition to this, Mochi Media’s tools help developers distribute their games to over 30,000 Web sites to reach more gamers online.



Why Micro-transactions will be a game changer for flash game developers

Jameson Hsu is CEO and cofounder of Mochi Media. Prior to founding Mochi Media, Jameson co-founded the award winning interactive design firm WDDG where he led partnerships with major brands such as Kraft, HP, Burger King and many more. Jameson has been focused on gaming and interactive advertising for over 10 years, working closely with Flash developers, industry leading artists, advertising agencies, and Fortune 500 clients to develop innovative marketing and communication solutions.

these tools, the more sites that hosted a game the more revenue the game developer made, effectively solving the problem of piracy for Flash games. We have now built out our developer tools even further to include our micro-transaction platform, Mochi Coins.



Q: What are you most excited about?

A: We are most excited about the future of our micro-transaction platform Mochi Coins, and the potential it has to empower developers to generate more complex and engaging games. There's so much talent out there in the developer community and Mochi Media has always been dedicated to giving them every means possible to create, experiment, and push Flash gaming to newer, greater places. Sean Cooper's Shadez 2: Battle For Earth is a great example of that – it's a groundbreaking game that adds complex game play and story elements that we haven't seen before in Flash games. Windosill by Vectorpark is another one. Both are very unique games where Mochi Coins offers a great monetization opportunity because these games are so good that people want to interact with them and buy upgrades or levels. Prior to this, developers have been focused on creating smaller, short-form games and we see the shift to micro-transactions as yet another way to reward their creativity and also increase the complexity and depth of Flash games.



Q: What are the origins of the company?

A: Mochi Media was founded in 2005 by Jameson Hsu and Bob Ippolito, with the mission of fueling the creativity of Flash game developers. Jameson and Bob both came from a professional game development background, and they wanted to create tools to solve existing problems that game developers faced. Before Mochi Media built its Flash game developer tools, Flash games were living on websites all over the web with no means of tracking them. Because Flash games could be easily stolen and posted to any Website, Web publishers were collecting advertising revenue on their sites from popular games without the game developers being compensated in any way. Mochi Media first developed an analytics tool called MochiBot that allowed developers to track what sites their games were being played on and followed that on with what is now Mochi Ads API, an ad network that places ads directly into the games. As a result of



96



06/2009 (8)



Mochi Media



Q: What impact do you think micro-transactions will have on Flash developers?

A: We believe micro-transactions are a game-changer for the Flash games industry. Micro-transactions have the potential to bring in significantly more revenue for game developers, which will in turn usher in a new era of better, more creative, more immersive, and more successful Flash games. If more indie developers can be making Flash games as their day job rather than a hobby, the industry will thrive. We’re optimistic that micro-transactions can help enable that.



to purchase in-game items and upgrades. Likewise, Rixty will allow gamers to trade change for Mochi Coins through Coinstar. Finally, we are allowing advertisers to unlock Mochi Coins for users, and recently launched a program with Old Navy that delivers free Mochi Coins in exchange for interaction with the advertiser’s content. Through these partnerships and our platform, we want to open up every avenue possible for developers to focus on creating great games.



Q: What is Mochi Media's role in this micro-transaction platform?

A: We're providing game developers with a very easy way to earn money by selling ingame items and upgrades. We take the hassle away from scaling your systems, managing payment providers, secure login and server side persistence of player data. What we're trying to do is remove as many barriers as possible for Flash developers to create highquality games. The Mochi Coins system creates a universal login and associated wallet that can be used across our entire network of games, regardless of what site the game is played on. We launched the service with payment partners such as Super Rewards and PayPal and just announced partnerships with alternative payment providers Rixty and Zong that are helping Mochi Coins reach a more global audience. Because many gamers in foreign countries don't have access to credit cards, mobile payment providers like Zong are really important because gamers can simply use their mobile phones



Q: What were the technological challenges faced in the development of Mochi Coins?

A: There are many challenges with designing a system that can be widely used by developers of varying expertise while also providing the flexibility required to accommodate the scope of use cases required. The APIs, item and store management interfaces, documentation, consumer experience and payment flow had to be thoroughly designed to give both developers and consumers the best experience possible. Mochi Media has core expertise in building scalable systems infrastructure. The platform infrastructure of Mochi Coins is built on essentially the same core sets of technologies used in MochiAds, MochiBot and our Leaderboards. By using the technology foundation of what the company was built on, we were able to get beta versions of our entire Mochi Coins platform out to developers within four weeks. Allowing developer feedback this early in the product cycle allowed us to easily plan and fine-tune the rest of the platform before its public release. Our platform had to run in numerous Flash environments, each of which may present its



own set of challenges. The Flash code we deliver must work in games that are written in either AS2 or AS3 and which may also be converted to standalone desktop games via Flash Projector. Any Flash developer who has developed code in mixed environments would understand the kinds of technical issues presented here. The Flash code must also integrate with user interface flows that span both the Flash game and our website away from the game. Providing the player with a seamless and reliable transition from the game to login, registration and payment flows outside of the game can be difficult. Finally we had to keep the security of our platform in mind during the entire process. Part of the reason why our login, registration, and payment flows are done away from the game is due to this. The Flash environment isn't built with the same set of security services that are offered in the web environment. Because of our domain expertise in both Flash and scalable platforms we were able to quickly work through all of the technical challenges in Mochi Coins.



Q: So these Mochi Coins will be featured in the new Shadez 2 game. What is so "groundbreaking" about Shadez?

A: Sean Cooper’s Shadez 2 is really emblematic of the bright future of Flash games because it showcases the capability of Flash to create high-quality games. When people think of Flash games, most think of simple games with simple graphics and game play, Shadez 2 is the antithesis of that – it's an incredible real-time-strategy game that has production quality on par with many commercially released titles. Sean also comes from the background of a professional game designer turned amateur Flash game developer who has matured into the professional Flash game developer. He has nearly 20 years of experience at Electronic Arts working on titles including the Bond series, Battlefield, Godfather, Syndicate series, Magic Carpet series, Populous, among others. But in 2007 he felt like he needed a new direction to pique his interest and he turned to Flash development. His background in console gaming and his skills as a developer are evident when you play the game. The detail in the game play is unparalleled in its complexity and sophistication. It's not just a great Flash game – it's a great game, period.



06/2009 (8)



97



Training



Academy Class

First Class Training for Creatives and Developers

Academy Class is the UK’s leading digital media training company specialising in desktop training in print & design, web design & development, media production and CAD, 3D & Games. We are the only UK training partner to be authorised by Adobe, Apple, Autodesk and Quark, and are also accredited by the Institute of IT Training.

Academy Class operates training facilities in Central London, Manchester, Glasgow, Newcastle, Birmingham and Leeds and also offers on-site training UK and Worldwide Popular classes include; • Adobe Photoshop, InDesign, Illustrator, Flash, Actionscript, Dreamweaver, Flex, Fireworks, Captivate, After Effects, Premiere, Creative Suite • Apple Final Cut Pro, Motion, Snow Leopard OSX, Logic, Color, DVD Pro • Autodesk 3ds Max, AutoCAD, Maya, Revit, MudBox, XSI • Also _Quark, AJAX, SEO, PPC, HTML, CSS, Cinema 4d Academy Class has delivered more Flex training courses in the UK than any other training company. Past clients include BBC, BSKYB, Westland, Boeringer, Accenture, American Express, Barclays Bank, the RAF and various government departments Flex training offering includes Public scheduled • Flex Jumpstart – zero to HERO – 5 days @ L1097+Vat • Flex 101:@ Developing RIAs – 3 days @ L897+Vat • Flex Data & Comms – 2 days @ L697+Vat Private and Bespoke • Flex: Using Actionscript – 2 days • Flex Charting and Dashboard Apps – 2 days • Flex: Extending & Styling Components – 2 days • Flex : Introducing Cairngorm – 1 day • AIR 101: Rookie – 1 day Quote FLEXMAG to get 20% discount off the last price on public scheduled courses

Free Flex Training: Bring your own laptop



The concept is simple: • We’ll supply the tutor, topic and the location. • You bring your own laptop installed with the right software for that session. This means we’ll be able to deliver our training sessions to you at low cost and sometimes maybe even free! We regularly run a Flex BYOL at either the Adobe offices or our own site in London and Manchester. More info about these sessions can be found here: http://www.bringyourownlaptop.co.uk/ Please visit www.AcademyClass.com to find out more about the courses at Academy Class or call our team on UK 0800 043 8889 to speak with one of our training team.



Bring your own laptop events are a new, fun and affordable way to learn new technology.



98



06/2009 (8)



Reviews



Shu Player for Adobe AIR

by Lee McColl Sylvester

For years, Flash developers have harnessed the power of third party software to make Flash an ultimate platform for desktop applications and, since the release of Adobe’s AIR, the number of such apps have increased exponentially. However, AIR doesn’t necessarily provide a replacement for third party SWF-to-Exe tools.



D



espite Flex and the Flash IDE outputting AIR apps directly and with AIR being promoted by Adobe themselves, software such as Multidmedia’s Zinc or Northcodes SWF Studio are still enjoying positive sales results due to their ability to empower developers with a means to extend the capabilities of their applications with OS native extensions. Everything from custom database drivers to audio synthesisers and more is possible, meaning developers are only limited by their imaginations. Adobe’s AIR platform, on the other hand, has taken the approach of maintaining an overly secure and restricted platform, which is probably a direct result of their relatively new appearance in the SWF-to-Exe marketplace. This means Adobe continue to have full control of the capabilities of the Flash platform in their new desktop app framework, but also inhibits the creative essence that is normally so abundant in the Flash community.



Enter the Shu Player

Creative Jar Technology (CJT), based in the UK, had been working with the Flash platform for many years and were quick to see the flaw in this design. Many years ago, CJT’s previous company incarnation had produced the first Mac based standalone extendable Flash player, so they were able to take this prior knowledge and promptly invent the Shu Player (www.shu-player.com). Named after the Egyptian God of Air, the Shu Player extends AIR apps in much the same way that SWF-to-Exe apps extend Flash, providing extra power to Flash developers and enabling them with infinite access to the underlying operating system.



interests with regard to licensing. With the legal restraints imposed by Adobe over the Flash platform and the AIR framework and runtime forcing a moral limitation over developers, CJT have ensured that all interests are met by releasing three distinct versions of their Shu Player. The primary incarnation of Shu is, in fact, called Shu. This is a full feature player which can be installed with distributed AIR apps for users that have the AIR framework already installed. Using this version of Shu means that developers do not have to worry about further licensing issues. The second version of Shu is known as ShuSA, which stands for Shu Standalone. Providing all of the same features as the Shu version, ShuSA builds on top of this functionality with the ability to package the AIR framework into a single runtime, perfect for CD-ROM applications that need to run on machines that do not have the AIR runtime pre-installed. When run, ShuSA applications do not install the AIR framework, but simply run AIR directly from the executable. The final Shu ensemble is known as ShuSA Lite. This Shu Player can also be used to package the AIR runtime into an executable, but lacks the feature set of added commands and extensibility, which can be perfect for those projects that do not need the added features Shu provides, but will still need to run on machines that do not have the AIR runtime. Developers choosing to use the standalone versions of Shu will need to acquire a custom license from Adobe on a per project basis.



• Access to MySQL databases • Launch files and applications • Open native message and prompt dialogs • Access to relative file paths, such as desktop, documents and the temp directory • Screen capture functionality What’s more, both versions also allow the developer to create custom dynamic link libraries for Mac OS and Windows, paving the way for infinite functionality possibilities. This, as you can imagine, makes AIR an all powerful platform for rich desktop applications.



Shu, the Future of AIR

Recently, Adobe announced the upcoming AIR 2.0 runtime and described its new ability to launch external applications, which is the first time AIR is able to natively access processes external to applications run within the runtime. AIR 2.0 will be a major release of the runtime, yet this very much requested feature will still pale in comparison to the extra functionality affordable with the Shu Player. Despite its occasional shortcomings, AIR is still the fastest adopted SWF-toExe framework to date. Many developers and organisations very much prefer the level of support and safety offered when adopting a product produced directly by Adobe. With the Shu Player playing ball with Adobe’s licensing terms and with a restricted AIR runtime being likely for quite some time to come, Shu is ensured to share in Adobe AIR’s very long and remarkable life.



Three Versions of Shu

CJT have spent a long time working with Adobe to help cater for their clients best



Shu Features

The features of Shu and ShuSA are modest but ultimately powerful. Both players provide the same commands, including:



100



06/2009 (8)



Reviews



Web Analytics Review:

by Dr. R. Adulseranee



Web-Stat (http://www.web-stat.com)



W



eb-Stat is a web traffic analysis tool that can be integrated into a Flash site, so long as your flash object is embedded in HTML. Web-Stat provides real time visitor tracking via a convenient dashboard. The site is user friendly and full of the necessary information to set up an account. The Sample Stats page shows you the results of the detailed traffic analysis you will be getting once you sign up and install Web-Stat on a website. Web-Stat offers a 30 day free demo for you to try on one of your sites. Setting up a free account is simple. All you need to do is to choose a user ID and a password. Additionally, you need to provide them



other types of media such as MP3, PDF, and Flash, read http://www.web-stat.com/help_event_ tracking.pl. When you are ready to get the Event Tracking, scroll down to the bottom of the page and type in your user ID and password to get the code. Follow the instruction on the page to get the event tracking to work on your Flash site. You’ll find that the process is quite easy. Overall, I’d recommend this service not only for Flash developers, but also to other developers to try out. You will be amazed not only by the range of information Web-Stat provides but also by the user friendliness and nice interface.



your site URL and an email address. You also have a choice of showing a counter on your site. Cookieless tracking, the watchdog feature, and other choices are available under Show additional options. Clicking the What if I want to cancel? link beneath the Create account >> button will show more information about cancelling your account. After signing up, the welcome page will walk you through the setup. Clicking the ctrl panel tab will take you to the login from where you can update your account, go to the stats center, and access the other features. To track



06/2009 (8)



101



Reviews



Viperdome Xplosive VX

by Lee McColl Sylvester

In our industry we continue to look for ways to lighten our workload and make the most of the time we have. Xplosive VX aims to reduce the work required to build Flash banners, ads or other such applications.



U



sing Flash to build banner ads or apply effects to text and images is big business. It could be said that a large majority of applications built with Flash facilitate this kind of use. Despite this, a proportionate number of developers producing this kind of content do not fit within the professional Flash developer role and thus would not be able to produce this kind of Flash content quickly. While there are many components available that produce enough eye catching effects to be the envy of every advertising campaign, they do little to speed up the overall task of producing these apps or, indeed, to make the task easier for the less savvy Flash developer.



these kinds of simple Flash applications both easy and fast. Providing numerous features common in banner ads, Xplosive VX exposes a simple point and click interface with no need to deal with timelines, drawing tools or code. Built in Flash itself, the software leads the developer through various choices for adding content, aiding in the construction of a Flash application without ever having to open up the Flash IDE. Once created, you can then export a finished SWF application file or save your project for editing later. Xplosive VX allows you to: • Insert background images • Choose from a selection of prebuilt background effects and animations • Add multi-line text blocks, either with or without added special effects • Import mp3 files for playback • Add a hyperlink to the whole movie



Filling the Gap

Xplosive VX, by www.viperdome.com, has been developed with the focus of making



Essentially, anything you could possibly need for an advert, website intro or even a glamorous button.



Conclusion

While many Flash developers may choose the freedom provided by the Flash IDE or even Flex, when building Flash adverts, Xplosive VX does offer an attractive solution for those who’d prefer something with a much shallower learning curve. What’s more, at only $37.95, Xplosive VX costs quite a bit cheaper than many Flash effects components offering a similar output. The Viperdome website does offer a trial version for free download, so it’s certainly worth having a go before committing. Who knows, Xplosive VX might just be the application you were looking for to speed up your daily workflow.



102



06/2009 (8)



Reviews



Flex 3 with Java

Author: Satish Kore Publisher:Packt Publishing Ltd. ISBN: 978-1-847195-34-0 Language: English Packt Special Offer: £22.49 Paperback: 304 pages Website: http://www.packtpub.com/flex-3-with-java



I



Four chapters follow which address debugging, styling, packaging & deployment along with globalization in greater detail with very good and understandable code examples. The last chapter is a step by step guide on developing an e-commerce book store. I was well-versed in my Java SE class, but the absence of Java EE was a bit of a hurdle in fully enjoying the Java side of the project section. You should have basic knowledge of Java EE to study it but if you don’t, even then you don’t want to deprive yourself of the other ingredients of Adobe Flex development. I felt that there was a need to include a topic on Data Visualization Components and Charting Components. I highly recommend it to any beginner or intermediate level developer or those who want to learn how different pieces of Flex framework are put together to make a server-side flex application. by Ali Raza



f you are in quest of an interesting and concise yet comprehensive book composed of project based step by step instructions, your search ends here. Flex 3 with Java is a magnificent work which doesn’t only target people who are seeking to get their hands dirty with Adobe Flex but also gives valuable information on some advanced topics as well. Once you finish reading this book, you will have a good understanding of application development with Adobe Flex using ActionScript 3, Java and BlazeDS. Although this is the first book of Satish Kore, the selection of topics, vision and shared knowledge prove the concern and dedication of the author. He did a splendid job and succeeded in making a place among the best books on Adobe Flex 3. In the first chapter, the author shows you how to install and configure Adobe Flex and introduces you to the development environment. The next two chapters briefly introduce the Adobe Flex Builder controls, layouts, mxml and ActionScript 3. You will learn how to make components both in mxml and ActionScript 3 in a ‘Flex Way’. The fourth and fifth chapters target external communication and XML. You will learn to talk to the wrapper using JavaScript as well as get proficiency in E4X while developing a book explorer. Later, three chapters will discuss server-side issues. The author will acquaint you with LiveCycle DS and Blaze DS. You will employ different data access methods available in the Flex Framework, like HTTPService, WebService, and RemoteObject, to interact with the server.



Packt, pronounced Packed, published its first book Mastering phpMyAdmin for Effective MySQL Management in April 2004 and subsequently continued to specialize in publishing focused books on specific technologies and solutions. Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today’s systems, applications, and frameworks. Our solutions-based books give you the knowledge and power to customize the software and technologies you’re using to get the job done. Packt books are more specific and less general than the IT books you have seen in the past. Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don’t. Packt is a modern, unique publishing company with a focus on producing cutting-edge books for communities of developers, administrators, and newbies alike. Packt’s URL, www.PacktPub.com, is an amalgamation of the words Packt and Publishing.



104



06/2009 (8)



Reviews



AdvancED Flex 3

Author: Shashank Tiwari, Jack Herrington, Elad Elrom, and Joshua Mostafa Publisher: friends of ED, an Apress Company, 2008 ISBN: 978-1-4302-1027-6 Pages: 610 Website: www.friendsofed.com



A



dvancED Flex 3 offers you the opportunity to transform yourself from a programmer into a developer. Some knowledge of ActionScript 3 and MXML is necessary, though. A Hello World! programmer can actually make it through the book, but it will probably be an overwhelming task. This book is more suitable for programmers who have made some simple applications, but want to move one step forward. The book has three parts, and it is advisable to read it from cover to cover: don't skip parts, and don't start from the middle of the book. Each part has a lot to offer; of course, alternative solutions are discussed, and you are free to read only the ones that suit your occasion best (see more in part's 2 review). The parts, and what they have to offer, are described below.



detail. The code provided is really detailed; the full thing is provided, so you don't have to regroup sparse bits of information. In order to learn how to synchronise the client and the server, you will have to understand some server-side code. However, you will familiarise yourself more with it in the second part (Integrating the Client and the Server). In this part, you will also find out how to tune your applications. Many aspects of performance are covered, such as scalability, latency, etc. You will learn how to include shared libraries in your applications, or how to call one SWF application from another. Moreover, you will learn how to use the profiler, and how to take advantage of other Flex features. The final chapter for this part is an introduction to AIR. One can find out how to create AIR applications with access to local data and the ability to self-update.



Integrating the Client and the Server

In the second part (4 chapters), you will learn how to integrate with server- and client-side technologies. Java, PHP and JavaScript are covered. Reading all chapters will reveal to you the logic behind integration; though, you may choose to read the chapter(s) corresponding to your preferable solution. Firstly, integrating with Java using services is presented. Both loose coupling and web services are described, with full-code examples. Then you will learn how to use data and media services. Emphasis is given to LiceCycle/BlazeDS data services and the Flash Media Server (FMS). FMS is only briefly described; however, BlazeDS is described in full detailed, to the extent that its description is suitable for completely new users. Finally, this part teaches you how your Flex application can talk to PHP and JavaScript.



Architecture & Design

The first part of this book (5 chapters), explains various architectural and design patterns. The big picture is given, as also examples of Cairngorm, PureMVC, and Fireclay. All examples are accompanied with code, and diagrams are given where necessary. Subsequently, you will learn how to build custom components, both in MXML and ActionScript. Styling visual components is explained; non-visual components are presented as well, i.e., formatters, validators, and effects. Source code is provided for everything. Moreover, advanced components are examined. A part about architecture and design wouldn't be complete if it didn't offer the reader the opportunity to create effective CRUD applications. The MVC framework and data binding are covered in



Advanced Topics

The last part (6 chapters) present advanced topics. In particular, Flex mashups, migrating Web 1.0 interfaces to RIA, interactive businessintelligence interfaces, working with Web 2.0 APIs, facilitating Audio and Video streaming, and using 3D are introduced. In this way, you can see what you have learned throughout the book in action. Enjoy! by Evangelos Kapros



06/2009 (8)



105




Share This Document



Other docs by Pedro Varela
Flash_and_Flex_06_2009
Views: 1029  |  Downloads: 22
by registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!