Flash & Flex Developer Magazine — HaXe New Way to Dock (1/2008)

Page 1




01/2008 (1)

Dear Readers,

I

would like to introduce this brand new magazine created especially for Flash and Flex fans. Here we deliver the first and the most important issue.

First of all, I would like to say hello to all of you and thank you for supporting me from the very beginning of this project. If you have any suggestions, any important questions or you would like to express your opinion you are more than welcome to share it with us; therefore do not hesitate and write your ideas or even complaints, because your feedback is mostly important to our team! Consequently, we will try to do our best in working on FFD magazine. Only with your help we can create this publication to be the best source of information about Flash and Flex related stuff.

Editor in Chief: Ewa Dudzic ewa.dudzic@ffdmag.com Executive Editor: Sylwia Stocka sylwia.stocka@ffdmag.com, Magdalena Błaszczyk magdalena.blaszczyk@ffdmag.com DTP Director: Sławomir Zadrożny slawomir.zadrozny@software.com.pl DTP Manager: Robert Zadrożny robert.zadrozny@software.com.pl DTP: Ireneusz Pogroszewski ireneusz.pogroszewski@software.com.pl Art Director: Agnieszka Marchocka agnieszka.marchocka@software.com.pl CD: Rafał Kwaśny rafal.kwasny@gmail.com Top Betatesters: Maxime Bornemann, Chetankumar Akarte, Lee Graham, Paul Brzek, Greg Murnock, Michel Romaniuk Senior Consultant/Publisher: Paweł Marciniak pawel@software.com.pl Production Director: Marta Kurpiewska marta.kurpiewska@software.com.pl Marketing Director: Ewa Dudzic ewa.dudzic@software.com.pl Subscription: subscription@software.com.pl Publisher: Software Wydawnictwo Sp.z.o.o 02-682 Warszawa, ul. Bokserska 1 worldwide publishing

Business addres: Software Media LLC 1521 Concord Pike, Suite 301 Brandywine Executive Center Wilmington, DE 19803 USA Tel: 1 917 338 3631 Tel: 1 866 225 5956 www.ffdmag.com

In this premiere issue, we tried to cover the most interesting topics. In the ActionScript Development arena Michel Romaniuk explains how to use haXe language, its installation, basic techniques and functions. You will also find several useful solutions in the Server-side Interaction section and some tips from the mobile and animation world. If you are a beginner and you have just got started with Flash techniques, do not worry, you will certainly find a valuable help and instructions. We teach you how to do a simple Pong Game. We encourage to joining our team – becoming FFD magazine's author and taking part in creating a great publication that will satisfy both advanced Flash and Flex users and the beginners. So let's combine our efforts – I am looking forward to reading your suggestions, ideas and general impression this issue made on you.

Software Media LLC 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 Print: 101 Studio, Firma Tęgi Printed in Poland Distributed in the USA by: Source Interlink Fulfillment Division, 27500 Riverview Centre Boulevard, Suite 400, Bonita Springs, FL 34134 Tel: 239-949-4450. 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.

To create graphs and diagrams we used company.

program by

CDs included to the magazine were tested with AntiVirenKit by G DATA Software Sp. z o.o The editors use automatic DTP system Mathematical formulas created by Design Science MathType™

ATTENTION!

Sylwia Stocka

Selling current or past issues of this magazine for prices that are different than printed on the cover is – without permission of the publisher – harmful activity and will result in judicial liability.

DISCLAIMER!

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.

4


www.ffdmag.com

Contents 06 In brief What's new in the Flash world...

08 CD Contents FFD TEAM There are some useful and up-to-date applications and 2 e-books.

50 Fast and Efficient Client-Server Communication in Flash and Flex using Hessian 2 EMIL ONG In this article, we present Hessian 2 – a fast, efficient, open binary protocol.

TOOLS

54 MySQL Database Integration with Flash

12 In this issue we will discuss the following tools: 3Dwall, WebsiteX5 and FDT 3.0.

CHETANKUMAR AKARTE In this tutorial, you will connect a Flash user interface with a MySQL database using PHP scripting.

FOR BEGINERS

SOUND&ANIMATION

16 How to Do a Pong Game with AS3

60 Website Banner

ALEJANDRO MIGUEL QUARTO In this article, you will learn how to do a simple Pong game engine using Adobe Flash CS3 and ActionScript 3.0.

KAROLINA SOBOLEWSKA In this tutorial, the author will try to present the basics of using Adobe Flash. The version used will be Adobe Flash CS3.

ActionScript DEVELOPMENT

66 Glass

20 Object-oriented Programming with AS3

JAN FILIPOWIAK In this tutorial, we will walk to the different phases of the development of the proposed solution, starting with the graphics in Photoshop and Flash.

ANTON KRASNOSCHOK In this article, we will go over all OOP principles in details – inheritance, classes, encapsulation, interfaces, design patterns and polymorphism.

24 Flash Desktop Applications Using haXe & SWHX MICHEL ROMANIUK From web-development to desktop application, haXe can also be used to create astounding widgets.

36 Deconstructing DelPadre.com NINO DEL PADRE This tutorial will outline the basic steps in creating the Del Padre Visual Productions 5.0 Flash site.

SERVER-SIDE INTERACTION 42 Flash Applications using Streaming Hessian 2 and Resin EMIL ONG The article will present how to write server-push clients in flex as well as servers in Java.

46 Flash Client-server Communication using Flash Remoting and WebOrb PAUL GRITSAY In this article, the author will shed some light on implementation of communication between your flash movie and server.

MOBILE WORLD 74 Flash Lite BILL VOLPE A very useful paper for mobile and web developers. It will cover some techniques of Adobe's Flash Lite.

BOOK REVIEW 76 Here you will find the revievs of two fantastic books. INTERVIEW 78 Interview with Bram Timmer FFD TEAM

COLUMN 80 Five Steps to Breathing Adobe AIR CHRIS CHARLTON

COMING UP 82 Here we present topics that will be discussed in the upcoming FFD Magazine.

5


In Brief Chemical Orange Chemical Orange is a free portal for playing Flash Lite games, it provides a complete solution for players by allowing them to access the mobile portal of the website at m.chemicalorange.com and download the games, play, and submit their score to the highscore list. Chemical Orange is now linked to from the mobile portal of Oman's second mobile operator (Nawras). All the games at Chemical Orange can be downloaded free of charge. Within the first three weeks after its launch, Chemical Orange games were downloaded more that 50,000 times. The Chemical Orange portal was launched in the eGames conference, the only annual gaming conference held in the Middle East. Currently Chemical Orange has two games available for download, both were made in Flash Lite 1.1 to ensure the maximum possible compatibility. The first game is a simple left-and-right target collection game and the second is a rhythm game, both were skinned into an ethnic Omani theme. Chemical Orange games weredeveloped using Flash CS3 and Fireworks CS3. Testing was done using Device Central CS3. Desktop website was developed using Flash CS3 and while mobile website was developed Dreamweaver CS3. www.chemicalorange.com/

New Flash Decompiler Trillix with Full Flash 9 Support

E

ltima has released a new major update to its well-known Flash decompiling utility. Flash Decompiler Trillix 3.1 now COMPLETELY supports Flash 5, 6, 7, 8 and 9 including AS 2.0 and 3.0 without any exceptions. It means that all users will no longer experience any issues with Flash movies, created in Adobe Flash 9 environment. Full Flash 9 and AS 3 support is ensured by improved overall stability of the application. As always, Flash Decompiler is your number one help in decompiling Flash

BEAU AMBUR ACQUIRES FLASHFORWARD CONFERENCE

B Figure 1. Mobile Phone Game – Al Kharafa

secureSWF Kindisoft, the leading provider of advanced obfuscation and protection tools for Rich Internet Applications (RIA), announces the release of secureSWF version 3.0. The major update extends its current abilities and allows customers to produce the most secure Adobe's Flash and Flex applications based on Actionscript v2.0 and v3.0. Because of ActionScript's flexibility, it is particularly vulnerable to decompilation. In effect, there exist many tools that can reproduce the original source code from the distributable SWF files, thus exposing your program's intellectual property to theft by those looking for security holes. Today, there are over 26 available tools that can decompile ActionScript from SWF files. secureSWF v.3.0 is designed to provide the greatest protection for Flash and Flex applications. It includes code protection and size reduction with advanced features such as Identifiers Renaming, Control Flow Obfuscation, Literal Strings Encryption, and Encrypted Domain Locking.

6

movies, converting them into FLA and editing them on the go. With Trillix you can extract SWF elements: sounds, images, videos, shapes, frames, morphs, fonts, texts, buttons, sprites and ActionScripts from any SWF file directly to your hard drive. Moreover, you can export Flash Video to AVI, MPEG, FLV and FLA, save sounds as WAV or MP3, images – as PNG, JPEG and BMP, texts as RTF, TXT and HTML. To learn more about the product please visit: www.flash-decompiler.com/

eau Ambur, CEO of Metaliq, announced today the acquisition of the Flashforward Conference and Film Festival. Metaliq, Inc., known for its cutting edge innovations for interactive technology, will be a Flashforward Conference premier sponsor. The next conference is scheduled for August 20-22, 2008 in San Francisco. The Flashforward Conference is the world’s original conference dedicated to interactive platforms. It was developed nine years ago and has been managed by lynda.com events and Lynda Weinman since 2005. Lynda recently transitioned the conference to Beau Ambur and Metaliq because of Beau’s impressive track record and his leadership role in the Flash industry. The Flashforward Conference and Film Festival is a historic event as the longest-running and largest gathering of Flash designers and developers in the world, said Lynda Weinman, Co-Founder of Flashforward and lynda.com. As the co-founder, it's extremely important to

me that the torch carry forward to a respected industry insider who will run the conference for the benefit of this talented and diverse audience. Beau Ambur is among an elite group of the most forward-thinking Flash developers, who understands community and how important this event is to this industry. It's an honor to pass the conference on to someone who is uniquely qualified to bring new ideas and vitality to an event that is near and dear to so many hearts. Metaliq’s unique and forward-thinking approach continues to extend and define what is possible in interactive technology on multiple platforms including Adobe Flash and Microsoft's Silverlight. The Flashforward Conference will be held August 20 – 22 in San Francisco, CA. The Flashforward Conference was the first event in the world focused on Macromedia, now Adobe, Flash. The Film Festival showcases talent and presents awards to those leading in innovation and design. www.flashforwardconference.com.

mod7 as a Finalist of the 2008 with Their Projects

F

or the first project – the Shift Control Website – mod7 is awarded a Finalist Certificate in the Best Business-to-Business Website category in the 2008 New York Festivals Innovative Advertising Awards.

Another project of mod7, the IEC Small Business Documentary, is awarded a Finalist Certificate in the Relationship Marketing category in the 2008 New York Festivals Innovative Advertising Awards.

01/2008 (1)


In Brief

Winners Announced for 2008 FITC Design + Technology Awards

F

lugtag Flight Lab Wins For Best In Show. BrightQube Wins For People's Choice. Toronto, Canada [April 22, 2008] – Flugtag Flight Lab (www.redbull.com/ flightlab) was the winner of the Best In Show Award at tonight's FITC Awards, part of the 7th Annual FITC Toronto – Design + Technology Festival (www.fitc.ca/toronto). The award was presented before a capacity crowd at Revival Nightclub in Toronto. Winners in all categories received a can opener encased in Plexiglas along with a year of bragging rights. The winners of this year's FITC Awards reflect the diversity and creativity of the new media industry both in Canada and around the world, says Shawn Pucknell, Founder of FITC and producer of the FITC Awards. Flugtag Flight Lab lets users design, build and fly their own paper flyer. It was developed by Less Rain (www.lessrain.com), a creative digital design agency with offices in Tokyo, Berlin and London. The site also won in the 3D category. The winning team, who work out of the company's Tokyo office, were not in attendance but sent an acceptance speech via video. This year's FITC award winners are: • 3D – Flugtag Flight Lab www.redbull.com/ flightlab, Less Rain • Advertisement – HP Paul Coelho www.hp.com/united-states/coelho /2007/ index.html, Goodby • Animation – Show Down Interactive www.grupowprojects.com/showdown/game, Grupo W

• Audio – 30 Days of Night Site w w w. s o n y p i c t u r e s . c o m / h o m e v i d e o / 30daysofnight/, Big Spaceship • E-commerce – Flight Club www.nike.com/ jumpman23/flightclub/demo.html, Blast Radius • Experimental – Sony BRAVIA www.colou rlikenoother.com, carlossulloa.com • Games – RoboBrawl robobrawl.com/, RED Interactive • Motion Graphics – Live Earth w w w. l a u n d r y m a t . t v /a r c h i v e _ s i t e s / liveearth/index.html, Laundry! • Multi-user – Spider-Man 3 Multiplayer Game flash.sonypictures.com/movies/ spiderman3/mp_game/, Big Spaceship • Narrative – American Gangster www.univ ersalpictures.com/awards/americangangster/, Project C • Self Promotion – Pixton www.pixton.com, Goodinson Design • Technical Excellence – Launchball www.sciencemuseum.org.uk/launchpad/ launchball/, Preloaded • Usability – 2009 Toyota Corolla: Live the Dream www.toyota.com/vehicles/minisite/ corolla/experience/, RED Interactive • Visual Design – Who the #I%$ is Fermin? www.grupowprojects.com/rexonapower/ whoisfermin, Grupo W The FITC Awards celebrate the hottest talents working in new media, with recognition given to individuals and teams working in 3D, animation, game design, motion graphics, rich media and video. This year's gala was hosted by producer, deejay and emcee More or Les(www.moreorles.ca/).

Flex and Seam at JavaOne 2008 There will be numerous mini-sessions happening this year at the Adobe booth at JavaOne 2008. I’ll be doing a Building High Performance RIAs session and a The Open Source RIA Stack session. Chet Haase (http://graphicsgeek.blogspot.com/) will be doing a Filthy Rich [Flex] Clients session. Bob Tierney will be doing a LiveCycle Data Services session and a LiveCycle and BEA session. Duane Nickull (http: //technoracle.blogspot.com/)will also be doing sessions. We also have one guest presenter, Igor Polevoy from Exadel (http://exadel.com/ web/portal/home), who will be demonstrating Flex and Seam integration with Flamingo(http: //code.google.com/p/exadel-flamingo/). Igor’s session will be at 1pm on Tuesday. Other session times are TBD – so stop by the booth on Tuesday to pickup a schedule. Also, make sure that you come to the Filthy Rich [Flex] Clients session with Stephan Jansen (of Parleys.com (http://www.parleys.com/display/V21Beta/ Home) and JavaPolis (http://javapolis.com/ confluence/display/JP08/Home)), Chet Haase, and myself which precedes the Adobe party on Wednesday night. Stop by the booth to pickup an invite. See you there!

ActionScript 3.0 Game Programming University Gary Rosenzweig's ActionScript 3.0 Game Programming University is a new book about Flash game development. You can start with chapter 1 and learn to program in ActionScript 3.0, and then go on to learn how to make games. Or, you can skip to a particular game and customize it for your own needs. Gary shows you how easy it is to create fun and addictive web-based games with the game development power of ActionScript 3.0 and Flash CS3 Professional. This book includes 16 complete games with source code and detailed descriptions of how each game was built. Through these games you’ll learn how to make your own creations. The code is easy to modify for use in your own projects and websites. Whether you are looking to learn ActionScript game programming or just need an instant library of game code, this book is for you!

FlashGoddess.com

F

lashGoddess.com is a resource and community site showcasing and promoting women who work with the Adobe Flash software. Profiles and spotlight interviews with talented designers, artists, coders, animators and authors are featured as well as tutorials, book reviews, a Gallery, and much more. FlashGoddess.com was one of HOW magazine's Top 10 sites to see for March 2004 and a SXSW Developer's Re-

01/2008 (1)

source Finalist in 2003. Founded in 2002 by Ann-Marie Cheung, FlashGoddess.com began as an experimental attempt to discover where all the Flash Goddesses were hiding. It has since grown to become an internationally recognized, inspirational site for those involved in the rich media industry. Flash Goddess www.flashgoddess.com

Figure 2. ActionScript 3.0 Game Programming University

7


In Brief Chemical Orange Chemical Orange is a free portal for playing Flash Lite games, it provides a complete solution for players by allowing them to access the mobile portal of the website at m.chemicalorange.com and download the games, play, and submit their score to the highscore list. Chemical Orange is now linked to from the mobile portal of Oman's second mobile operator (Nawras). All the games at Chemical Orange can be downloaded free of charge. Within the first three weeks after its launch, Chemical Orange games were downloaded more that 50,000 times. The Chemical Orange portal was launched in the eGames conference, the only annual gaming conference held in the Middle East. Currently Chemical Orange has two games available for download, both were made in Flash Lite 1.1 to ensure the maximum possible compatibility. The first game is a simple left-and-right target collection game and the second is a rhythm game, both were skinned into an ethnic Omani theme. Chemical Orange games weredeveloped using Flash CS3 and Fireworks CS3. Testing was done using Device Central CS3. Desktop website was developed using Flash CS3 and while mobile website was developed Dreamweaver CS3. www.chemicalorange.com/

New Flash Decompiler Trillix with Full Flash 9 Support

E

ltima has released a new major update to its well-known Flash decompiling utility. Flash Decompiler Trillix 3.1 now COMPLETELY supports Flash 5, 6, 7, 8 and 9 including AS 2.0 and 3.0 without any exceptions. It means that all users will no longer experience any issues with Flash movies, created in Adobe Flash 9 environment. Full Flash 9 and AS 3 support is ensured by improved overall stability of the application. As always, Flash Decompiler is your number one help in decompiling Flash

BEAU AMBUR ACQUIRES FLASHFORWARD CONFERENCE

B Figure 1. Mobile Phone Game – Al Kharafa

secureSWF by Kindisoft Kindisoft, the leading provider of advanced obfuscation and protection tools for Rich Internet Applications (RIA), announces the release of secureSWF version 3.0. The major update extends its current abilities and allows customers to produce the most secure Adobe's Flash and Flex applications based on Actionscript v2.0 and v3.0. Because of ActionScript's flexibility, it is particularly vulnerable to decompilation. In effect, there exist many tools that can reproduce the original source code from the distributable SWF files, thus exposing your program's intellectual property to theft by those looking for security holes. Today, there are over 26 available tools that can decompile ActionScript from SWF files. secureSWF v.3.0 is designed to provide the greatest protection for Flash and Flex applications. It includes code protection and size reduction with advanced features such as Identifiers Renaming, Control Flow Obfuscation, Literal Strings Encryption, and Encrypted Domain Locking.

6

movies, converting them into FLA and editing them on the go. With Trillix you can extract SWF elements: sounds, images, videos, shapes, frames, morphs, fonts, texts, buttons, sprites and ActionScripts from any SWF file directly to your hard drive. Moreover, you can export Flash Video to AVI, MPEG, FLV and FLA, save sounds as WAV or MP3, images – as PNG, JPEG and BMP, texts as RTF, TXT and HTML. To learn more about the product please visit: www.flash-decompiler.com/

eau Ambur, CEO of Metaliq, announced today the acquisition of the Flashforward Conference and Film Festival. Metaliq, Inc., known for its cutting edge innovations for interactive technology, will be a Flashforward Conference premier sponsor. The next conference is scheduled for August 20-22, 2008 in San Francisco. The Flashforward Conference is the world’s original conference dedicated to interactive platforms. It was developed nine years ago and has been managed by lynda.com events and Lynda Weinman since 2005. Lynda recently transitioned the conference to Beau Ambur and Metaliq because of Beau’s impressive track record and his leadership role in the Flash industry. The Flashforward Conference and Film Festival is a historic event as the longest-running and largest gathering of Flash designers and developers in the world, said Lynda Weinman, Co-Founder of Flashforward and lynda.com. As the co-founder, it's extremely important to

me that the torch carry forward to a respected industry insider who will run the conference for the benefit of this talented and diverse audience. Beau Ambur is among an elite group of the most forward-thinking Flash developers, who understands community and how important this event is to this industry. It's an honor to pass the conference on to someone who is uniquely qualified to bring new ideas and vitality to an event that is near and dear to so many hearts. Metaliq’s unique and forward-thinking approach continues to extend and define what is possible in interactive technology on multiple platforms including Adobe Flash and Microsoft's Silverlight. The Flashforward Conference will be held August 20 – 22 in San Francisco, CA. The Flashforward Conference was the first event in the world focused on Macromedia, now Adobe, Flash. The Film Festival showcases talent and presents awards to those leading in innovation and design. www.flashforwardconference.com.

mod7 as a finalist of the 2008 with their projects

F

or the first project – the Shift Control Website – mod7 is awarded a Finalist Certificate in the Best Business-to-Business Website category in the 2008 New York Festivals Innovative Advertising Awards.

Another project of mod7, the IEC Small Business Documentary, is awarded a Finalist Certificate in the Relationship Marketing category in the 2008 New York Festivals Innovative Advertising Awards.

01/2008 (1)


In Brief

Winners Announced for 2008 FITC Design + Technology Awards

F

lugtag Flight Lab Wins For Best In Show. BrightQube Wins For People's Choice. Toronto, Canada [April 22, 2008] – Flugtag Flight Lab (www.redbull.com/ flightlab) was the winner of the Best In Show Award at tonight's FITC Awards, part of the 7th Annual FITC Toronto – Design + Technology Festival (www.fitc.ca/toronto). The award was presented before a capacity crowd at Revival Nightclub in Toronto. Winners in all categories received a can opener encased in Plexiglas along with a year of bragging rights. The winners of this year's FITC Awards reflect the diversity and creativity of the new media industry both in Canada and around the world, says Shawn Pucknell, Founder of FITC and producer of the FITC Awards. Flugtag Flight Lab lets users design, build and fly their own paper flyer. It was developed by Less Rain (www.lessrain.com), a creative digital design agency with offices in Tokyo, Berlin and London. The site also won in the 3D category. The winning team, who work out of the company's Tokyo office, were not in attendance but sent an acceptance speech via video. This year's FITC award winners are: • 3D – Flugtag Flight Lab www.redbull.com/ flightlab, Less Rain • Advertisement – HP Paul Coelho www.hp.com/united-states/coelho /2007/ index.html, Goodby • Animation – Show Down Interactive www.grupowprojects.com/showdown/game, Grupo W

• Audio – 30 Days of Night Site w w w. s o n y p i c t u r e s . c o m / h o m e v i d e o / 30daysofnight/, Big Spaceship • E-commerce – Flight Club www.nike.com/ jumpman23/flightclub/demo.html, Blast Radius • Experimental – Sony BRAVIA www.colou rlikenoother.com, carlossulloa.com • Games – RoboBrawl robobrawl.com/, RED Interactive • Motion Graphics – Live Earth w w w. l a u n d r y m a t . t v /a r c h i v e _ s i t e s / liveearth/index.html, Laundry! • Multi-user – Spider-Man 3 Multiplayer Game flash.sonypictures.com/movies/ spiderman3/mp_game/, Big Spaceship • Narrative – American Gangster www.univ ersalpictures.com/awards/americangangster/, Project C • Self Promotion – Pixton www.pixton.com, Goodinson Design • Technical Excellence – Launchball www.sciencemuseum.org.uk/launchpad/ launchball/, Preloaded • Usability – 2009 Toyota Corolla: Live the Dream www.toyota.com/vehicles/minisite/ corolla/experience/, RED Interactive • Visual Design – Who the #I%$ is Fermin? www.grupowprojects.com/rexonapower/ whoisfermin, Grupo W The FITC Awards celebrate the hottest talents working in new media, with recognition given to individuals and teams working in 3D, animation, game design, motion graphics, rich media and video. This year's gala was hosted by producer, deejay and emcee More or Les(www.moreorles.ca/).

Flex and Seam at JavaOne 2008 There will be numerous mini-sessions happening this year at the Adobe booth at JavaOne 2008. I’ll be doing a Building High Performance RIAs session and a The Open Source RIA Stack session. Chet Haase (http://graphicsgeek.blogspot.com/) will be doing a Filthy Rich [Flex] Clients session. Bob Tierney will be doing a LiveCycle Data Services session and a LiveCycle and BEA session. Duane Nickull (http: //technoracle.blogspot.com/)will also be doing sessions. We also have one guest presenter, Igor Polevoy from Exadel (http://exadel.com/ web/portal/home), who will be demonstrating Flex and Seam integration with Flamingo(http: //code.google.com/p/exadel-flamingo/). Igor’s session will be at 1pm on Tuesday. Other session times are TBD – so stop by the booth on Tuesday to pickup a schedule. Also, make sure that you come to the Filthy Rich [Flex] Clients session with Stephan Jansen (of Parleys.com (http://www.parleys.com/display/V21Beta/ Home) and JavaPolis (http://javapolis.com/ confluence/display/JP08/Home)), Chet Haase, and myself which precedes the Adobe party on Wednesday night. Stop by the booth to pickup an invite. See you there!

ActionScript 3.0 Game Programming University Gary Rosenzweig's ActionScript 3.0 Game Programming University is a new book about Flash game development. You can start with chapter 1 and learn to program in ActionScript 3.0, and then go on to learn how to make games. Or, you can skip to a particular game and customize it for your own needs. Gary shows you how easy it is to create fun and addictive web-based games with the game development power of ActionScript 3.0 and Flash CS3 Professional. This book includes 16 complete games with source code and detailed descriptions of how each game was built. Through these games you’ll learn how to make your own creations. The code is easy to modify for use in your own projects and websites. Whether you are looking to learn ActionScript game programming or just need an instant library of game code, this book is for you!

FlashGoddess.com

F

lashGoddess.com is a resource and community site showcasing and promoting women who work with the Adobe Flash software. Profiles and spotlight interviews with talented designers, artists, coders, animators and authors are featured as well as tutorials, book reviews, a Gallery, and much more. FlashGoddess.com was one of HOW magazine's Top 10 sites to see for March 2004 and a SXSW Developer's Re-

01/2008 (1)

source Finalist in 2003. Founded in 2002 by Ann-Marie Cheung, FlashGoddess.com began as an experimental attempt to discover where all the Flash Goddesses were hiding. It has since grown to become an internationally recognized, inspirational site for those involved in the rich media industry. Flash Goddess www.flashgoddess.com

Figure 2. ActionScript 3.0 Game Programming University

7


CD Contents

CD Contents Applications You will find the following programs in Apps directory on the FFD CD. Most of them are full versions, without any time limitations, negotiated with the vendors especially for you. Some of them require activation keys which are provided below. A4Desk Flash Photo Gallery Builder from A4Flash An all-in-one software that creates interactive Flash photo gallery with many design skins to choose from. User can create a flash photo gallery or photo album with just a few mouse clicks. The photo gallery can then be placed on website, CDROM or used as a standalone application. No Flash knowledge, coding or design skill is required. Version 2.06 adds new templates installation function, and improves publishing options. Advanced users would benefit from the XML-driven albums by using scripts to generate the photo entries or simply edit them by any text editor. Activation Key: 2B5F-3834-R3A7-8D43 Retail price: $39 www.gallery.a4desk.com

Flash menus quickly and easily; fully customized, with font size, color, and animated Flash effects; background music for your Web site. Version 2.27 adds newly designed menu header templates, and new option for setting background music on or off for photo albums. Activation Key: 2F46-8575-T4E6-EFE8 Retail price: $19.95 www.a4menubuilder.com A4DeskPro Flash Website Builder from A4Flash An easy to use, all-in-one flash Web site builder. User can build their own Flash Web site and presentations, with multiple pages, sub-menus, and eye-catching flash animation effects using just few mouse clicks by selecting from a collection of pre-designed web site templates. The design possibility is unlimited. Version 1.19 adds new Flash Web site templates and more than 30 varieties included. Retail price: $49.95 www.a4deskpro.com

A4 Flash Menu Builder from A4Flash A4 Flash Menu Builder is an all-in-one, easy-to-use, templates-based Flash Menu Building software. It helps you to create professional looking Flash menu headers in minutes, with dropdown submenus, background image, music, and icon buttons. No any Flash programming, scripting, or design skills required. Features include: easy creation of Flash menu headers without coding; more attraction to your visitors, and faster loading speed; a variety of ready-to-use templates for you to choose from, and to build your

Figure 2. a4deskPro

Figure 1. a4menubuilder

8

IconLover from Aha-Soft IconLover is an all-in-one solution providing tools to create, edit, manage, store, search, import, download and convert icons and cursors of various formats including packed Windows Vista icons. The icon creation module has all the necessary features that will satisfy an experienced designer: Layers design model, alpha-blending, a wide range of special effects, sophisticated transformations, etc. No more switching between several applications! IconLover has all you need and shows it all in the same window using the popular tabbed interface. You can have an editor window in one tab and a browser window in another. It's easier than ever thanks

01/2008 (1)


01/2008 (1)

9


CD Contents

to a superbly efficient interface. IconLover saves time. Browse icon libraries, import icons from various resources (executables, dynamic link libraries, image collections) by simply clicking tabs in the IconLover window. Icon-Lover supports drag-and-drop. Drag files right from your Windows Explorer windows. Need to import multiple icons all at once? Want to convert multiple files into icons? Nothing could be easier. IconLover supports batch operations! You can accurately convert large collections with only a few mouse clicks. IconLover can work with a vast variety of formats. Convert to and from BMP, JPEG, GIF, PNG, TIFF, WMF, WBMP, CUR and more. Now you can even work with Unix icons and cursor resources (XPM and XBM). Retail price: $49.95 www.aha-soft.com/iconlover

Figure 3. Iconlover

Website X5 SMART from Incomedia If you want to create a personal or company site, a digital photo album or an interactive presentation, WebSite X5 allows you to go from the simple idea to the finished project, already published and perfectly visible on the web, in just 5 simple steps. Firstly, in the general settings you can enter the required information and choose the graphic template to use. You can choose from over 20 ready-to-use models and use the internal editor to edit your banner. If you want to create the map, enter the pages in order to define the layout of the site. The navigation menu will be dynamically created according to the map. In any moment you can change the map and use it to move between the different pages. You are able to create every page by simply dragging and dropping the available objects: Texts, Images, Flash animation, Video and Audio. Advanced settings allow you to customize the style of the navigation menus and define the style of the texts and of the scroll bar. Finally, export the site by publishing the site created on your space thanks to the supplied FTP engine. To install Smart you need the following product code E151272358412. We prepared a special upgrade offer for you. .Bbelow, there is the link where you can upgrade from Smart to Evolution (to find out

10

more about Evolution, see Tools section) at a discount of 24 %: www.websitex5.com/ promo/ffdmag Retail price: 34.95 www.websitex5.com

E-Books The Flash Anthology: Cool Effects and Practical ActionScript by Steven Grosvenor (provided by SitePoint) A practical and fun Flash book that shows readers over 60 Figure 4. Flash anthology practical techniques, solutions and cool effects to instantly use on their Website or project. The Flash Anthology makes an excellent task reference or it can be used for inspiration for future projects. The book tackles the majority of the most common building blocks for real world Flash applications-as one reviewer described "it covers everything that Flash does best. Topics covered include working with external data, debugging, animation, sound and video effects, flash forms and getting indexed by search engines. All the solutions are based on ActionScript, are completely customizable and come with suggested modifications. Examples are compatible with ActionScript 2 and Flash MX 2004. Foundation ActionScript 3.0 with Flash CS3 and Flex by Steve Webster, Todd Yard and Sean McSharry (provided by Friends of Ed) Whether you are a Flash designer wishing to add to your skill set or an experienced ActionScript developer who wants to get up to speed with the latest version, you'll find all you need to know in Foundation ActionScript 3.0 with Flash CS3 and Flex. This book covers all the essential techniques from the ground up, allowing you to get up and running quickly and easily. Starting with the fundamentals, youll learn about using ActionScript objects, manipulating sound and video, and harnessing the power of regular expressions and XML. The book concludes with two case studies to consolidate what you've learned and to introduce some more advanced techniques. This will give you a good grounding in the new and exciting world of ActionScript 3.0 and show you how it all fits together in larger applications, allowing you to go on and build your own professional sites. Michael Potter has updated the PHP RIA SDK to include new releases of AMFPHP (v 1.9 beta) as well as the latest WebORB for PHP release from the Midnight Coders (1.3.2). The free (as in speech) SDK is available now from the Adobe Flex Developer Center. You can join the mailing list to ask questions about the SDK, or if you want more information on connecting PHP and Flex together. There is a lot of exciting work going on in the world of PHP and Flex. Michael is going to have some more great news to share with you later this month.

01/2008 (1)


If the CD contents can't be accessed and the disc isn't physically damaged, try to run it in at least two CD drives. If you have experienced any problems with this CD, e-mail cd@ffdmag.com

01/2008 (1)

11


Tools

3D Wall Do you recall the movie “Minority Report” with Tom Cruise? If you do, then you may also remember a scene where Tom’s character is sorting through a collection document images using a virtual 3D wall.

T

he folks at the Flashloaded have created a component, named 3D Wall, that may well be on a way of bringing that movie magic into the today’s reality. 3D Wall is one of the coolest Flash components that I have the chance to review in recent history. The component, which uses the Papervision3D engine, permits the developer to create a three dimensional wall containing number of picture in rows and columns and then allowing the end user to navigate them in a very futuristic and engaging style. By giving the developer to control look of the wall, flat or set to any curvature, the guys at the Flashloaded have made it easy to create walls that can be as unique as the content they present. With over 60 parameters and features to customize, developers can be sure that unlimited number of looks can be created. Here are some of the features which are included: • • • • • • • • •

to read the User Guide available on the Flashloaded website since it gives more information on the installation, usage and the properties that are available. From the user prospective the functionality of the 3D Wall does not end there. The viewer of the 3D Wall can also scroll, tilt and zoom the wall freely based on their need at the specific type and with the built-in preloader

the transaction between the thumbs (small images) and the large images is seamless. I can hardly wait to start using the component in my application since the functionality and its controls make it a very desirable presentation object when it comes to making sure that our end user engaged in the functionality of our applications.

Flat or curved wall XML file controlled Built in preloader Adjustable number of rows and spacing Swivel camera Glow and Reflection Mouse events XML or Component Inspector Many, many more

3D Wall also allows the development team to capture ActionScript events that are fired up when the component performs specific action. There are over 10 events which are included. In addition to the event control 3D Wall permits the developer to add title to images, open URL with the Unclick event as well as control of other properties through the ActionScript properties. I would highly recommend for any of you who want to start to use the component 12

01/2008 (1)


Tools

WebSite X5 The easiest software for creating professional web sites and online shops without prior programming skills.

W

ebSite X5 is a completely visual software, structured as a guided intuitive process, that in just 5 steps allows the user to create, customize and publish professional web sites and online shops. Who Can Use It? • Individuals, associations or clubs that want an easy and creative software for the creation of web sites and photo albums. • Businesses that need a professional software to create sites and online shops. • Web Designer who want a complete and versatile software to produce sites to show their customers. • Public bodies and Schools who need an easy-to-use software to create their site. Why Is It Simple to Use? • No programming skills required. • Guided procedure for the creation of sites: for each step only the needed functions are presented. • Gallery of over 1000 ready-to-use graphic templates. • Online guide, available also in PDF and video tutorials. Why Is It Powerful? • No limit to the number of pages and web sites that can be created. • It includes: an e-commerce form pre-set for credit card payments, 3D button editor, FTP engine and tools for the creation of a reserved area, Feed RSS and multi-language sites. • Graphic editor to touch up images with the application of filters, frames and masks. • Sites created in XHTML, compatible with the main Browsers, navigable from mobile phones and indexable by search engines.

01/2008 (1)

Create Your Website In 5 Simple Steps If you want to create a personal or company site, an online shop, a digital photo album or an interactive presentation, WebSite X5 allows you to go from the simple idea to the finished project, already published and perfectly visible on the web, in just 5 simple steps. General Settings Enter the required information and choose the graphic template to use. You can choose from over 1000 ready-to-use models, use the internal editor to create your banner or create a customized model, even animated in Flash. Creation of the Map Enter the levels and the pages in order to define the layout of the site: you can use up to 4 different levels to organize an unlimited number of pages. The navigation menu will be dynamically created according to the map. In any moment you can change the map and use it to move between the different pages. Creation of the Pages Create every page by simply dragging and dropping the available objects. Texts with RollOver, Images, Flash animation, Video and Audio, Slide Show, formatted tables, galleries of images, HTML codes, email forms. Use the internal graphic editor to cut, rotate, correct or apply filters, masks and frames on the images. Advanced Settings Customize the style of the navigation menus even with 3D buttons. Define the style of the texts and of the scroll bar, then complete your site with elements such as: e-commerce cart, reserved area, Intro page and links to the different languages available; Feed RSS.

Exporting the Site Publish the site created on your space thanks to the supplied FTP engine. In case of updating, you can export only the modified files. It Assures • • • •

Compatibility with the main Browsers Compliance with standards Displaying on palm tops and mobile phones Optimization for search engines

Advanced Functions • • • • • •

E-commerce cart E-mail forms Reserved Area Credit card payments Multi-language sites Feed RSS

It Includes • • • • • •

Over 1.000 templates Menu generator FTP engine Graphic Editor 3D button Editor Guide and Video Tutorial

INCOMEDIA Incomedia is a leading company in the development and multimedia distribution software. Currently, Incomedia sells its products in more than 40 countries and Website X5 is available in thirteen languages. Try out our demo version and you will see there is an intuitive guided pathway, which allows you to create, personalise and publish your own Webpages in 5 logical steps. Not only home users, schools, small businesses, but also web professionals can create an impressive site that they can be proud of. For further information please visit www.websitex5.com to learn more about the many features, news, events and press awards.

13


Tools

FDT 3.0 Developed for internal by PowerFlasher, the FDT (Flash Development Tool) wowed freelancers so much that the company decided to launch it as a commercial product. Like Flex Builder, FDT is built upon the Eclipse framework and therefore has many similarities with other Eclipse-based tools, not least JDT upon which it is based.

F

DT 3.0 assists ambitious Flashdevelopers in many ways The Eclipse plug-in FDT 3.0 helps single developers and teams equally and has a lasting effect on code structure and productivity. FDT 3.0 combines features like no other IDE for Flashand ActionScript development.

Background Check If you search the web a little bit, you’ll find out that Powerflasher – the company behind FDT – is Germany’s biggest Multimedia Agency specialized in Flash. In 1997 the agency was founded by Carlo Blatz, best known for speaking appearances at several conferences all over the world. You might ask yourself: What drives a Multimedia Agency to develop a development tool? In the beginning the team was small and could handle the projects using the tools that were available. But soon – confronted with a growing demand – the company`s projects became more complex and asked for more advanced tools. Team-work and time were always of the essence. Most of the developers were familiar with Java and the JDT and missed the comfort of this IDE in their Flash IDE. So they planned and conducted a plug-in for Eclipse which was able to take over many small but yet time-consuming tasks. FDT – Flash Development Tool – was born. Powerflasher shared FDT with every Flash developers and freelancers they knew. The demands and desires of this huge community were crucial to FDT's further development and their influence made FDT big. By now more and more flash developers everywhere on the globe certify FDT to be a breath-taking tool: fun to work with, easy to handle, simplifying workflows, increasing efficiency and structuring source code well.

Developing Flash Applications with FDT 3.0 Over the last ten years the technology Flash changed. What once was a perfect way to 14

simply animate graphics has now become a powerful way to design sophisticated applications. Unfortunately Flash's own development environment doesn’t keep up with this change. That’s where FDT 3.0 comes into play. Many amenities like code completion for individual classes, automatically included imports or live syntax checking and error highlighting are only a few features you won’t give up when you get used to them. FDT supports both ActionScript 2 and ActionScript 3 and lists the content of AS3-library-files (SWCs) neatly arranged in an explorer window. Many templates and an individually configurable formatter make coding a lot easier and help disorganised coders to organise their source-code. Errors can be avoided by code completion. If an error occurs, it will be highlighted and FDT suggests how to fix these errors. If required, the FDT implements the fixes automatically. In contradiction to FlexBuilder the error checking and syntax highlighting happens in real-time – no compiling required. Several quick views of structures and data types help to survey classes and allow an easy navigation from one code-block to another code-block. Very helpful and powerful is the Refactoring. This feature assists you when you rename packages, classes, methods or attributes or when you move classes. If desired, FDT adjusts the affected sources automatically. All things considered FDT 3.0 offers coding comfort and is the perfect solution for Flash- and AS-developer who consider themselves satisfied with only the best.

//fdt.powerflasher.com. Demo movies show some of the core features in action. FDT 3.0 Basic is available for 299 Euro and is the perfect fit for upcoming professionals. FDT 3.0 Professional is available for 399 Euro. It brings all the basic features and additionally provides developers with Quick Views, SWC-Browsing and high-speed search and type hierarchy. First choice for developerteams or developers who have to deal with complex projects is FDT 3.0 Enterprise. This sophisticated product is equipped with advanced refactoring features and a debugger. A qualified support service responding to inquiries within 24 hours tops complete the

Give-and-take Since March 2008 FDT 3.0 is available in three different versions: Basic, Professional and Enterprise. The difference between those three versions lies in their feature range. All available features are described thoroughly at the FDT homepage: http:

01/2008 (1)


FDT 3.0

projects. All OS developers get FDT 3.0 Enterprise for free. All they need to do is to visit the FDT website and fill in a registration form. And nobody has to buy a big in a poke: a 30 days trial version is available online and on the magazines CD.

Future Events One of the major additions coming with one of the next free updates will be a MXML parser. This enables FDT to handle MXML files within ActionScript projects so that features like auto-completion are also available for classes defined in MXML. In a second step the implementation of a text editor is planned. This will offer the chance to use the FDT features which are currently available for AS-coding with MXML projects. Right know Powerflasher concentrates on an extended support for Macs. Few FDT features don't work properly on Macs. With the next free update those problems will be fixed.

FDTďšşTEAM

offer. Students are entitled to purchase FDT for half of the regular price. As mentioned a

01/2008 (1)

d

v

above, FDT is close to the Flash-community, that's why Powerflasher supports open source e

r

t

i

s

e

You can chat with Nico Zimmermann, founder of FDT and still one of the core developers at Flashbelt, Minneapolis on June 9th, 2008. If you would like to see FDT in action please contact Ariane Lucke-Vossel, alv@powerflasher.de and fix your appointment.

m

e

n

t

15


For Beginners

How to Do a Pong Game with AS3 One of the most used pourposes of using Flash as a development tool is to build Web Games. In this days, game development is not only a hobbie for some people; it mostly turned in a big bussines for individual persons that are not involved with companies. What you will learn...

What you should know...

• Flash CS3 Authoring Tool • Some programming expertise • Enjoy a bit math

• Basic classes usage • Mouse interaction • Basic AI for games

Level of difficulty

I

f you look at sites like MochiAds (www.mochiads.com who is great for all kind of development skills) you will notice that everyone in there is making money. Obviusly you need a good game to success, but if you think that you only used a few hours in flash, doing what you like to do; a few bucks can be a good deal. In this article, you will learn how to do a simple Pong game engine using Adobe Flash CS3 and ActionScript 3.0. I will not analize the code in depth, since you are supposed to be starting with AS3.0, i prefer to show you a simple way to develop a game, that can be reused in a lot of situations..How many games have a ball?

Art Assets After loading Flash CS3, you will notice a couple of options to start a new project. We will use 2 of this options for this example. Click on New ActionScript 3.0, and change the document properties to fit this ones (see Figure 1). First we need to set up our art assets in a library, pong games usually needs two items: paddle, and ball. So, start drawing a paddle like this one (see Figure 2). You can use the Flash drawing tools, or just import a picture. Once you get it, you need to select it, and press F8. In this way we are going to convert the draw into a MovieClip. MovieClips, are basically needed to be able to in16

teract with objects. Cos of that, this MovieClip will need to have special features. Fill the dialog with the information (see Figure 3.) Is specially important that you enable Export for ActionScript tilt, and put the paddle text in the Class label. By doing this, Flash will know that the paddle is an object that can be acceded by code. So, what you have to do, once you click OK, is just to delete the paddle from the stage. Next thing, is to build a ball. Do the same thing but, instead of using the text paddle in the Class label, use the text ball (without quotes). Delete the ball from the stage. Once you are done with the previus steps, you should have an empty stage, with 2 movieclips in the library. Usually, while working with AS3.0, is nice to avoid code in the .fla. Cos of that, our entire document, will be controlled by another object or class. I will call it game. The way to do that, is clicking on the stage, and then filling the text game in the Document class label.

write code, and you don't care about art assets. Click on File menu, then Save As, then use the name game.as, without quotes. Now, Flash will know that the game object is defined by game.as file. Write the code you see on the Listing 1 and then save. Line 1: define a package where are we going to build our Class. Line 2 -3: we need to import the paddle and ball class to our game class, then we can use it. Anyway, we haven't write any code for them yet. Line 4: since we are going to display movieclips, we need to import the flash class that let us do that.

Figure 1. Document properties

Figure 2. Paddle art asset

Coding Right now, we only have art assets, we need to write some code. If you think about each step you made as an object, then you will see that you have 3 objects: 1- paddle 2- ball 3- game The game object will handle the other 2 objects. Click on File menu, then New, and finally on ActionScript File. This means that you will only

Figure 3. Convert to MovieClip and export options dialog

01/2008 (1)


How to Do a Pong Game with AS3

Line 5: definition of the class, name should be the same that we used in the .as file while saving. Line 6: property that define the player object. Note we call player to a paddle object, that's why the : defining the var type. Line 7:cpu object definition. Line 8: ball definition. Line 9: Class constructor. This function with the same name than the class, is called when you create a new object.

Figure 4. Documment class input

Line 10: here, we setup the property defined in the Line 8. Every time you need to create an instance of an object, you need to use the New instruction. In this case, we need to send some parameters to the Ball constructor: x and y position. Line 11: same thing with the Player, but we send more parameters: x, y, a reference to our ball, a flag (0 or 1) determinig if the new paddle is automatically controlled or not, and finally i've added another parameter that means the maximun speed for the padde. Line 12: like line 11, but this time we send 0 in the flag parameter, and different position. Line 13 – 15: addChild is used to be able to add our instances to the screen and also, be able to see them. So, now you have the game class done, you just need to define what the ball, and the paddle is.

Create a new ActionScript File, and save it as ball.as. Our ball will have the following code (see Listing 2). Line 3: Since we need to update the ball position constantly, we need to use a Flash event (ENTER_FRAME), and that's why we import the events class. Line 4: Class definition, same name than the .as file Line 5-6: we will use acceleration along the x and y axis to move our ball. Line 7: ball radius Line 8: class constructor, note that we define 2 parameters as we called from the game class. Line 9-11: here is where we define the position by using the x and y properties, and also the radius.

Listing 1. Game class Game.as

myBall=new ball(stage.stageWidth/2,stage.stageHeight/

package {

player=new paddle(stage.stageWidth/

2)

import paddle;

2,stage.stageHeight-30,myBall,0,10)

import ball;

cpu=new paddle(stage.stageWidth/2,30,myBall,1,2)

public class game extends MovieClip {

addChild(cpu);

import flash.display.MovieClip;

addChild(player);

public var player:paddle; public var cpu:paddle;

public var myBall:ball;

public function game() {

}

}

}

addChild(myBall);

Listing 2. Ball class paddle.as

x+=Math.min(Math.sqrt((x-xDest)*(x-xDest))/

package {

} else {

import flash.display.MovieClip;

x-=Math.min(Math.sqrt((x-xDest)*(x-xDest))/

import flash.events.*;

public class paddle extends MovieClip {

private var xDest:Number;

private var maxSpeed:Number

if (Math.sqrt((y-myBall.y)*(y-myBall.y))<myBall.radius &&

Math.sqrt((x-myBall.x)*(x-myBall.x))<(width/2)+myBall.radius) { while (Math.sqrt((y-myBall.y)*(y-myBall.y))<myBall

public function

.radius) {

paddle(xpos:Number,ypos:Number,b:ball,automatic:int,maxS: x=xpos;

Number) {

}

if (x<myBall.x) {

myBall=b;

myBall.ac_x+=Math.sqrt((x-myBall.x)*(x-

isCPU=automatic;

} else {

maxSpeed=maxS

addEventListener(Event.ENTER_FRAME, update);

}

if (isCPU==1) { } else {

01/2008 (1)

myBall.x))/100;

myBall.ac_x*=1.02;

xDest=myBall.x; xDest=stage.mouseX;

if (x<xDest) {

myBall.x))/100;

myBall.ac_x-=Math.sqrt((x-myBall.x)*(x-

public function update(e:Event):void {

}

myBall.y-=myBall.ac_y;

myBall.ac_y*=-1;

y=ypos;

}

10,maxSpeed)

}

private var myBall:ball; private var isCPU:int;

10,maxSpeed)

}

}

}

}

myBall.ac_y*=1.02;

17


For Beginners Line 12: we add an event, in this case ENTER_ FRAME to be able to update the ball constantly. This function, needs to you send the name of a function as paremeter, in this case: update. Line 14: update function, here we are going to update the ball position every frame, and also check collisions against the sides, and check if any player lose the ball. Line 14-15: we add the x acceleration to the x property. Same thing with the y. Line 17-20: checks if the ball X position is lower than the 0 position (left), if this hap-

x+=ac_x

Line 10 – 14: we initialize the paddle properties by using the parameters when the object was called. Note that myBall, is a reference to the game ball, so is possible to us to know where the ball is. Line 15: we add an ENTER_FRAME event, related to the update function. Rememeber we want to call this function constantly. Line 17: update function declaration. Here we are going to move the user paddle and the CPU paddle. Line18 -22: since we need to move the paddles, we need to know where along the X axis, it should be. If the paddle is non player controlled, then we will use the ball's X as a destiny. IF not, it means is our paddle, then we use the Mouse's X. Line 23- 27: Now, that we have the destiny, we need to move it. I will use the distance formula inside a minimum comparation. This is to have maximun speeds... At bigger speeds, will be difficult to win. Basically, if the X of the paddle is lower than the goal, then we add a fraction of the distance along the X axis, and viceversa. Line 28: this comparation, will check if the ball is colliding against this ball, again is just a distance formula. Line 39- 31: once we know the ball is colliding with the paddle, we want to avoid overlapings between those two objects, so, while the distance between the paddle's Y and the ball's Y, is lower than the ball's radius, we move the ball back along its Y axis. Line 32: since we have a hit, we need to reverse the Y acceleration of the ball. Line 33 – 37: this is an extra value the or basic game, depending where the ball hit the paddle, then we alter the X acceleration too. Line 38-39: every one hit, we increase the ball speed, so the game turns hard.

if(x-radius<0){

Conclusion

On the 'Net • • •

www.actionscript.org www.alejandroquarto.com http://www.emanueleferonato.com/

pens, then we reverse the x acceleration after placing the ball at the correct limit. Line 21- 24: Same thing against the right side. Line 25-27: we check if the CPU miss the ball (CPU is at the top), if it is a miss, then we reset the position and accelerations by calling a reset function that we will define later. Line 28-30: again, we check a miss, but in this case the player miss. Line 32-37: this is the reset function, when called, it resets the ball properties to be the same than at the start. That's all for the ball. Now we only need to define the paddle class. Create a new ActionScript File, save it with the name paddle.as, and write this code (see Listing 3). Line 4: class definition, this is our paddle object.

Listing 3. Paddle class ball.as package {

import flash.display.MovieClip import flash.events.*;

public class ball extends MovieClip { public var ac_x=0.3 public var ac_y=1

public var radius:Number

public function ball(xpos:Number,ypos:Number) { x=xpos y=ypos

radius=width/2 }

addEventListener(Event.ENTER_FRAME, update);

public function update(e:Event):void { y+=ac_y

x=radius

}

ac_x*=-1

if(x+radius>stage.stageWidth){ x=stage.stageWidth-radius

}

ac_x*=-1

if(y<0){

reset() }

if(y>stage.stageHeight){

}

}

reset()

function reset(){ ac_x=0.1 ac_y=1

x=stage.stageWidth/2

}

18

}

}

y=stage.stageHeight/2

That's all the code. You can improve this game by adding counters, screens, better art, and different difficulty levels. Once you have a good game in your hands, you can try to submit it at MochiAds (www.mochiads.com), is free and you will possible have some money in return from advertising.

ALEJANDRO MIGUEL QUARTO Alejandro Miguel Quarto joined Persuasive Games Latin America, S.A. in 2006 as a General Manager, starting his career in interactive entertainment as a freelance programmer. In 2002 I've co-founded Platico Games Studio in Buenos Aires, Argentina where I have developed games for many well-known companies. As developer, he is an active contributor in communities like actionscript.org. and he also researches and writes examples and tutorials about Flash development. Alejandro's online profile: http://www.linkedin.com/in/amquarto Alejandro's personal blog: http://www.alejandroquarto.com

01/2008 (1)



ActionScript Development

Object-oriented Programming in AS3 by Anton Krasnoschok

Object-oriented programming (OOP) is a fundamental style of computer programming that uses "objects" and their interactions to design applications and programs. It is based on several techniques: encapsulation, modularity, polymorphism and inheritance. A lot of powerful programming languages now support OOP, including C++, Java, ActionScript 3.0. What you will learn...

What you should know...

• A common object-oriented programming paradigm • How to define class and interface in Action Script 3.0 • What is inheritance, encapsulation and polymorphism

• Familiar with general programming concepts such as data types, variables, loops, and functions • Familiar with OOP in ActionScript 2.0

Level of difficulty

A

dobe became greater when it introduced ActionScript 3.0. It is a complete update – language was rebuilt as a scale proper programming language with many improved features, such as the way it handles events, working with visual objects more effectively, additions like regular expressions. One of the greatest improvements is the object orientation. In ActionScript2 it was possible to code your application in object-oriented way; with ActionScript 3.0 it is completely mandatory. In this article, we will go through all OOP principles in details – inheritance, classes, encapsulation, interfaces, design patterns and polymorphism. Additionally, we will apply these to ActionScript 3.0 in the most effective way.

Class, Object Classes and objects are the fundamental building blocks of every project. A good understanding of the roles that classes and objects play, will help you to learn OOP. A class is an abstract representation of an object. A class stores information about the types of data that an object can hold and the behavior, that an object can exhibit. 20

possible to define a static property and an instance property with the same name in the same class body. For example, the code in Listing 4 defines a static variable named name and an instance variable of the same name.

Class Property Attributes For example, the code in Listing 1 creates a class named Preloader that contains one variable named progress and one method named Init. The following code creates object of class Preloader: var pr:Preloader = new Preloader();

ActionScript 3.0 introduced the package statement; the package name must be included in the package declaration. For instance, the code in Listing 2 declares class Preloader in package com.go4flash.ui. Class can be defined in many different ways. ActionScript 3.0 supports the following class attributes: • • • •

For

dynamic (allows properties to be added to instance at run time) final (cannot be extended by another class) internal (visible inside the current package) public (visible everywhere)

example, we can add new class ProgressBar to our package com.go4flash.ui (see Listing 3). This class is defined with internal attribute, therefore it means that ProgressBar is visible to references inside the com.go4flash.ui package. Internal attribute is default class attribute. In contrast to the previous versions of ActionScript, in ActionScript 3.0 it is

Property means anything that can be a member of a class including variables, constants and methods. In ActionScript 3.0, there is five attributes that can be used with any property of a class: • • • • •

internal (visible inside the same package) private (visible in the same class) protected (visible in the same class and derived classes) public (visible everywhere) static (specifies that a property belongs to the class, not to instances of the class)

Variables Variables can be declared with the var or const keywords. Variables declared with var keyword can be changed many times during the run time. Variables declared with const keyword are called constants and they can have values assigned to them only once.

Methods Methods are the functions which are a part of a class definitions. Methods are a definer that uses the function keyword. Functions which share the same name as class in which they are defined are called constructors. Any code that you include in the constructor method is executed when an instance of the class is created with a new keyword. For example, the code in Listing 5 defines a class named Preloader that contains a single property

01/2008 (1)


Object-oriented Programming in AS3

named progress. The initial value of the progress variable is set inside the constructor function. Constructor can only be public. You cannot use private, protected or internal attribute on a constructor.

Listing 1. Creating a class named Preloader public

private

Encapsulation: Hiding Details Encapsulation is an ability to hide and protect data. In other words, encapsulation makes a code object an object. Encapsulation has been used synonymously with other terms, such as component and module. In the context of OOP, encapsulation is often called a black box, which means you can see it while doing certain things, but you cannot see the inner workings (see Listing 6). In this case we do not need to know anything about _progress variable, but we have to know how to work with getProgress and setProgress methods (i.e. which parameters we have to send there). Get and set accessor functions, also called getters and setters, allow you to add to the programming principles of information hiding and encapsulation while providing an easy-to-use programming interface for the classes that you create. Get and set functions allow you to keep your class properties private to the class, however at the same time they allow users of your class to access those properties as if they were accessing a class variable instead of calling a class method. Let’s rewrite the previous example with getter and setter accessor functions (see Listing 7).

Inheritance: Avoid Redundant Coding Inheritance is a form of a code reuse which allows programmers to develop new classes that are based on the existing classes. Advantage of inheritance is the way it allows you to reuse the code from the base class and leave the existing code unmodified. Using inheritance, you can treat that class as a module that you can extend with additional properties or methods. You should use the extends keyword to indicate what a class inherits from another class. In the example in Listing 8, we will create base class (ancestor) named ComExt (Component Extension) and class Preloader (descendant) which will extend class ComExt.

01/2008 (1)

progress:Number;

public function Init(): }

}

{

progress = 0;

Listing 2. Declaring class Preloader in package com.go 4flash.ui package com.go4flash.ui{ public

Preloader { private

progress:Number;

public function setProgress(_progress:Number):

}

progress = _progress;

}

}

{

Listing 3. Adding new class package com.go4flash.ui{

internal

ProgressBar {

private

width:Number;

public function setWidth(_width:Number):

}

width = _width;

}

}

{

Listing 4. Defining the static and instance variable public

Preloader {

name:

= “

Preloader Name”;

name:

= “Preloader Name”;

pr:Preloader =

Preloader();

}

trace(pr.name);

trace(Preloader.name); // output:

Preloader Name

Listing 5. Initial value of the progress variable ste in the construction function public

public

Interfaces An interface is a set of method declarations which allows the unrelated objects to communicate with each other. The structure of an interface definition is similar to that of a class definition, except that an interface can contain only methods with no method bodies. Interfaces cannot include variables or constants but can include getters and setters. To define

Preloader {

Preloader {

progress:Number;

public function Preloader():vioid{

}

}

progress = 0;

pr:Preloader =

Preloader();

trace(pr.progress); // output: 0

21


ActionScript Development

Listing 6. Black box

Listing 9. Defining and implementing interfaces

public

public interface IComponent{

Preloader {

private

public get enabled():Boolean;

progress:Number;

}

public interface IPreloader{

public function getProgress():Number {

}

public function setProgress(_progress:Number): progress = _progress;

}

public get comName():

progress;

}

public set comName(_comName:

):

{};

public set enabled(_enabled:Boolean):

public

{};

get progress():Number {

}

set progress(_progress:Number):

comProgress = _progress;

{

}

function getSelected():

More then one

Preloader();

public

comName:

;

}

}

{

+_index; { ;

}

package com.go4flash.ui{

ComExt implements Selectable{

public function doSelect(_index:Number):

import com.go4flash.ext.ComExt; Preloader

}

ComExt {

public function getSelected():

public function Preloader(){ comName =

ComExt implements Selectable{

public function getSelected():

package com.go4flash.ui{

}

Grid

}

public

public

;

;

public function doSelect(_index:Number):

package com.go4flash.ext{

ComExt {

{

can implement this interface:

package com.go4flash.ui{

Listing 8. Creating base class

public

);

public interface Selectable{

trace(pr.progress); // output: 0.5

public

):

package com.go4flash.ui{

}

pr.progress = 0.5;

}

}

(

function doSelect(index:Number):

} pr:Preloader =

+data.

Listing 11. Defining an interface

comProgress;

public

ComExt{

public function setData(data:

comProgress:Number;

}

22

;

package com.go4flash.ui{

Preloader {

public

}

):

Listing 10. Adding common methods

private

}

{};

public get enabled():Boolean {};

}

;

Preloader implements IPreloader, IComponent {

public get comName():

}

public

}

;

public set comName(_comName:

public

{

Listing 7. Get and set functions

}

public set enabled(_enabled:Boolean):

;

}

}

}

{

+_index; { ;

01/2008 (1)


Object-oriented Programming in AS3

On the 'Net • • •

ht tp : //f le xblog.faratasystems .com/ ?p=153 h t t p : // w w w . o r e i l l y . c o m / c a t a l o g/ actionscript3qr h t t p : / / w w w . a d o b e . c o m / d e v n e t/ actionscript/articles/oop_as3.html

an interface, use the interface keyword. For example, let’s define the IComponent interface which contains method declarations that a class can use to manipulate with component properties: public interface IComponent{

public get enabled():Boolean;

public set enabled(_enabled:Boolean): void;

}

An interface definition contains only method interfaces. Any class that implements the interface is responsible for defining the method implementations. Interface definitions are often placed at the top level of the package. They cannot be placed inside a class definition or inside another interface definition. Interfaces can extend one or more other interfaces. For example, the following interface, IPreloader, extends the IComponent interface: public interface IPreloader extends IComponent {

public get comName():String;

public set comName(_comName:String): void;

}

In this case any class that implements the IPreloader must include implementations not only for the comName getter and setter methods, but also for the enabled getter and setter methods inherited from the IComponent interface. A class in ActionScript 3.0 language can implement more than one interface. The example presented in Listing 9 defines two interfaces IComponent and IPreloader, and a class Preloader that implements both of them.

Polymorphism Polymorphism is an ability to use a single method name for a method that behaves differently when applied to different data types. Let’s design classes to represent components Grid and List. This classes may have the following methods: • • •

doSelect

getSelected setData

First add all common methods that are applicable to all components to the class ComExt (see Listing 10). In the next step, add new behaviour that can be reused by multiply classes: an ability to select and get selected row. Let’s define an interface Selectable (see Listing 11). When the Grid class declares that it implements interface Selectable, it promises to provide implementation for all methods declared in this interface. In our case, there are two methods doSelect and getSelected. Why is it so important that the class will keeps the promise and implements all interface’s methods? An interface is a

Listing 12. Using doSelect() method package com.go4flash.ui{ public

ComInit {

public function ComInit (){ components:

=

components.push( components.push( components.push( components.push( (

}

}

}

01/2008 (1)

}

i:

();

Grid()); ());

description of some behavior(s). In our case, the behaviour Selectable means existence of a methods with the signature: doSelect(_index:Number) getSelected(

If any other class knows that Grid implements Selectable, it can safely call any method declared in the Selectable interface. A class cannot have two independent ancestors, but it can implement multiple interfaces. It needs to implement all methods declared in all interfaces, for example: class Grid extends ComExt implements Selectable, Editable {…}

If you are interested only in Selectable functions, you can cast the object only to those interfaces which you intend to use, for example: var seGrid:Grid = new Grid();

var sGrid:Grid = seGrid as Selectable;

Now, we will write class ComInit which will use defined classes Grid and List. It will create an array with a mix of Grids and Lists. Iterate through this array and cast it to Selectable interface, then call the method doSelect() on each object in this collection (see Listing 12). When you look at our ComInit, it looks like it calls the same method doSelect() on different types of objects, and it generates a different output for each type. This is an example of polymorphic behaviour. It allows you to avoid using a switch. You do not need to modify the code every time you add a new selectable component type. In practice, object-oriented programming has two parts. One part covers the strategies and techniques for designing a program, called object-oriented design; another part of OOP is the actual programming the structures that are available in a given programming language to build a program, using an object-oriented approach. Once programmers start learning OOP, they will start to understand why things go in a certain way and it makes everything easier.

());

Grid());

= 0; i < components.length;i++){

s: Selectable= components[i] as Selectable;

trace(s.doSelect(1));

ANTON KRASNOSCHOK Anton Krasnoschok is a freelance Flash developer based in the Ukraine. He was working at Freelance Flash Team on RentACoder.com and at RYACo. He liked to make large Flash project to learn how to organize his ActionScript code better. More information about him you can find in his online portfolio: http://www.linkedin.com/in/ antonkrasnoschok

23


ActionScript Development

Flash Desktop Applications Using haXe & SWHX As many flash coders should know now, haXe is more than MTASC compiler successor. haXe targets flash platform and gives you very efficient AS2 or AS3 bytecode. What you will learn:

What you should know:

• A new way to build Flash applications • ”Extending” Flash Player with some system functions • Deploy a desktop application

• Basic classes usage • Mouse interaction • Basic mathematics

Level of difficulty

B

ut haXe also targets the nekoVM which is a server-side virtual machine, giving you access to the database, file-system or some low-level system functions. This virtual machine can run in standalone, and that’s the starting point. In other words, by writing with haXe, you can link a flash to the server-side, and build powerful desktop applications. haXe Remoting is used to communicate transparently between the platforms, and SWHX is the layer that manages the flash and the server and that gives you a basic desktop and cross-platform API. The result is an executable desktop application with some dlls which are part of a light integrated runtime that can be used without installation and requires no extra. Depending on the libraries used for a desktop application project, most of time the application resulting is cross-platform and runs the same way on Windows, Mac OS X and Linux. This application is configurable using an xml file. So you can add and remove shortcuts, change their pictures, set the dock position on the screen and more, by editing an UserFriendly xml file. A big part of the application is client-side. In this context, the client-side is Flash Player. So the 24

Flash9 API will be used to parse the xml configuration, display the icons on the screen and compute the visual effects (some mathematics are welcome). And since haXe syntax is very similar to ActionScript, even the little part of server-side that handles the activation of the selected shortcut, will be very easy to understand for ActionScript developers. Server-side here represents the NekoVM that will be the used for its system functions and to launch an external application. But first, let us see what is needed to build the project.

What You Need The haXe installation goes first. Then we’ll need some third-party libraries like SWHX and

Systools for the system layer and FEffects used for some visual effects like motion tweens. haXe Installation There are several ways to install haXe on your system. You can choose the automatic installer, available for Windows, Mac OS X and Linux or proceed manually by downloading separately the haXe and Neko packages, and setting the environment variables. You can also download the sources from CVS and compile haXe with the latest available modifications. (Currently, last official release is 1.19) Take a look at http://haxe.org/download to get your installation. • Automatic installer on Windows: Download and launch the Windows installer: hxinst-win.exe. It automatically downloads the last version of the haXe and Neko packages and runs the setup. • Manual installation on Windows: Download and extract haxe-1.19-win.zip and

Figure 1. Screenshot of the dock (top of the screen)

01/2008 (1)


Flash Desktop Applications Using haXe & SWHX

neko-1.7.0-win.zip into a different or the same directory. Then in order to set up the environments variables and to make haXe and Neko available from anywhere on the system, you have to launch haxesetup.exe.

All the technical specifications are available as well as cross-platform (Windows, Mac OS X, and Linux) using haXe and SWHX except the Tray manager that is only available on Windows. The other specifications can be grouped into an xml-based configuration file.

Dock’s Configuration XML File In the XML file we need two kinds of information: the dock’s main configuration and the collection of shortcuts. So the XML can look like: in Listing 1. First comes a config node with the following attributes:

Then you’re ready to write haXe applications! Installation of the 3rd Party Libraries Using haxelib haXe comes with a tool named haxelib that works as the apt-get command on Linux. haxelib command is used to install/remove or upgrade libraries shared by the haXe community. You can find the available libraries at http: //lib.haxe.org/. To build the dock project, we need to install SWHX, Systools and FEffects. The SWHX installation includes automatically the Systools package, using this command in the prompt/terminal:

�����������

�����������

�����

������

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

��������

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

���� ���

haxelib install swhx

������ ���

���� ���

(You can run the SWHX examples using: haxelib run SWHX) To proceed for the installation of the FEffects library the command is:

���� ���

haxelib install feffects

�������� ���

�������� ���

The Dock This article is a short example of haXe & SWHX possibilities. It is absolutely not a reference or the best way to write dock’s applications. You can of course optimize the code, change the behaviour and add more functionalities. But for now, here are some main specifications of a Dock application:

Figure 2. haXe dock application structure Listing 1. Example of dock’s configuration XML file <fdock>

<config minSize="32" maxSize="128" spread="3" delay="250" spacing="2" fontSize="20" <shortcuts>

• Full-screen, transparent and always on top display • No taskba: a Tray Icon • Clean Quit application solution: popup menu Then come some candy options described below and configurable by editing the fdock.xml file: • Add / remove / modify shortcut-icons • The minimum and maximum size of the icon • The size of the magnifing effect • The location of the dock on the screen (left, right, top, bottom) • The delay while tweening to display the dock • The font size • The Icons spacing • Hiding or not the dock

01/2008 (1)

location="top" hidden="true" />

<shortcut name="My Application 1" path="C:\path_to_my_app1\myApp1.exe" icon="data\icons\myApp1Icon.png" />

<shortcut name="My Application 2" path="C:\path_to_my_app2\myApp2.exe" </shortcuts>

icon="data\icons\myApp2Icon.png" />

</fdock>

Listing 2. UI.hx file

{

ypedef Shortcut = name

: String,

// text displayed on rolling over a picture

icon

: String

// path to the picture to download and display

path }

: String,

// path to the application to launch

class UI {

static function main(){ /*…*/ }

// entry point

/*…*/ }

25


ActionScript Development •

minSize:

Size in pixels of the icon when not magnified maxSize: Maximum size in pixels of the icon while magnified spread: Number of icons that will be magnified while rolling over the dock delay: Delay, in ms, for the tweening to display the dock spacing: Space in pixels between icons fontSize: The font size of the text displaying the icon’s name loaction: top, left, bottom, right, are the dock’s screen positions available hidden: Boolean telling if the dock has to disappear from the screen when rolling out (motion tween)

• • • • • • •

Then one shortcuts node that contains one or several shortcut nodes with the following attributes

name:

The string that will be displayed under the icon • path: A string that specifies the shortcut’s application path • icon: The path to the picture to display for the shortcut Now that you know all the features you want to implement, let’s go deeper into the dock application and see its structure. Dock’s Whole Structure Most of work being done on client side, we can imagine a structure quite modular that separates the real dock work: manage, display and magnifing the icons, from the others application’s functions like communication with the server side and pictures’ loading. So we’ll work with the Dock and the UI class (User Interface).

Listing 3. Dock.hx file

minSize

: Int,

spread

: Int,

delay

: Int,

spacing

: Int,

maxSize : Int,

fontSize

}

hidden

// number of icons magnified while magnification // motion tween delay for dock's

{

Listing 4. UI extern class

apparition // space between icons

class UI

// font size used for the

displayed text

: DockLocation,

// location of the dock

{

on the screen (see DockLocation)

: Bool

var scene

// hide dock when rolling out?

: DockConfig;

// dock’s

configuration object : Array<Shortcut>; // list of

shortcuts

: Array<DockIcon>; // list of icons : Shortcut;

// used by the

image load queue

: String;

// text displayed while

: String;

// extern application's

static function main() : Void;

rolling over

function new() : Void;

path to launch when clicking

public var minScale

: Float;

// minimum icon's

public var maxScale

: Float;

// maximum icon's

public var amplitude

: Float;

// scale's amplitude

public var text (default, setText)

//

application entry point

function parseXml( e : flash.events.Event ) : Void;

//

parse xml and starts image loading

function loadIcons() : Void;

// used in loop

(shortcuts length)

function onLoadIcon( e : flash.events.Event ) : Void; //

create icons objects and dock instance

function click( e : DockIcon ) : Void;

class DockLabel extends Sprite

//

used to launch extern application using a server call

: String;

dock's label text getter/setter

26

// dock’s instance

: flash.net.URLLoader;

var currentShortcut

scale

{

: flash.display.Loader;

var icons

scale

}

var loader

var shortcuts

class DockIcon extends Sprite

: flash.display.Sprite; // root display

object

: Dock;

var config

bottom;

public var path

// store the

var dock

var urlLoader

top;

public var label

public static var instance : UI;

application instance

right;

{

/*...*/

}

left;

}

• DockConfig is a typedef, an object containing configuration values from the XML file • DockLocation is an enum containing available values for the dock location on the screen

class Dock

// minimum icon's size // maximum icon's size

enum DockLocation {

Dock’s objects:

}

: Int,

location

• Shortcut is a typedef, an object containing information from the XML file, as the pictures’ paths or the texts to display.

/*...*/

typedef DockConfig = {

This way, we will be able to implement the dock, alone, into another flash application, or a website for example. Now, let’s see how the work done by the flash and by the server is separated. This could look like it is presented in Figure 2. UI’s object:

//

}

01/2008 (1)


Flash Desktop Applications Using haXe & SWHX

• DockLabel is a class that manages the label that appears below the icons. • DockIcon is a little class extending Sprite. It contains the picture and extra parameters as shortcut paths or icon’s name. It’s a Dock’s object, the dock’s gasoline. Let’s see now, the application from the client side. haXe: a New Way to Make Flash Applications haXe will be used, here, to create a Flash9 content. Good news is that haXe generates a better and faster bytecode than Flash CS3 or Flex compilers.

Here are some call-backs functions too, called on an event: • A motion tween displaying the dock when rolling over the invisible part

• A motion tween hiding the dock when rolling out • Display icon’s name when moving on an icon • Call the call-back function given in initialization when clicking on an icon

Listing 5. Dock extern class class Dock extends flash.display.Sprite {

var target

: flash.display.DisplayObjectContainer;

var icons

: Array<DockIcon>;

var label

: DockLabel;

var config

: DockConfig;

// Icon's name label

var iconsContainer : flash.display.Sprite;

Overview of Client-side Objects As seen on the previous schema, UI.hx contains UI class and a Shortcut object. The UI class will be the main class, containing the application entry point see Listing 2. Then, the Dock class with its objects: see Listing 3.

// Display object

where the dock is attached

// Display object where icons are

attached

var bar

: flash.display.Sprite;

var tween

: feffects.Tween;

var sensor var totalDist

: flash.display.Sprite;

var openScale

Needed functionalities

: Float;

var offsetSensor

: Float;

var callBack

UI Class The UI class has to follow in order the steps below:

: Float;

var screenWidth

var screenHeight

The dock application will start with the static main function in the UI class.

: Float;

: Float;

// Background bar // Transparent sensor // FEffects Tween instance // used to compute magnify

// used by tween to compute dock’s visibility // used to compute dock’s location on the screen // margin when dock is hidden to capture mouse

events

: DockIcon -> Void;

// function stored to call when clicked

public function new( icons : Array<DockIcon>, config : DockConfig, callBack : DockIcon -> Void ) : Void;

// Initialize the dock

public function create( target : flash.display.DisplayObjectContainer ) : Void; public function destroy() : Void;

• Initialize the application and start loading the XML file • Parse the loaded XML: get the configuration and shortcut objects • Load the pictures • Create the Dock

function setLocation() : Void;

function createSensor() : Void; function createBar() : Void;

function createLabel() : Void; function createIcons() : Void; function magnify( ?e : flash.events.MouseEvent ) : Void;// called on dock’s mouse

It contains also a call-back method given to the Dock as parameter and used when an icon is clicked.

move

function setLabel( e : flash.events.MouseEvent ) : Void;

// called on icon’s

function fadeIn( e : flash.events.MouseEvent ) : Void;

// called on dock’s

function fadeOut( e : flash.events.MouseEvent ) : Void;

// called on dock’s

mouse move

Dock Class Dock class has a bit more work to do. First, we’ll use the dock constructor as an initialization function. Then, we will use 2 public methods to create and destroy the dock correctly. Create, is used to construct, attach display objects and to add the mouse listeners. All is removed into the destruct method. When create is called, these things are done, in the following order: Set the visual dock location on the screen Create the text label for each icon Create the icons Create the background bar Create the invisible visual sensor preventing a buggy behaviour (using transparent window) • A call of the magnifing function is called once, to initialize the icons position

roll over roll out

}

Listing 6. DockLabel extern class

{

• • • • •

01/2008 (1)

function click( e : flash.events.MouseEvent ) : Void; // called on icon’s click

lass DockLabel extends flash.display.Sprite public var text (default, setText) setter

var tf

var tfx

: String;

// dock's label text getter/

: flash.text.TextField;

: flash.text.TextFormat;

public function new( size : Int ) : Void ;

// Initialize the

label object

}

function setText( s : String ) : String;

// setter function for text

27


ActionScript Development • Apply the magnify when moving over the dock (independent of the selected icon) �����

DockLabel Class: The last class to view is a tiny tool class that will help to display custom text. It extends Sprite and does the following:

�����

Figure 3. onLoadIcon function (1) and createIcons function (2)

• Creates the TextField and the TextFormat to apply • Sets the TextField new text and apply the TextFormat through a setter function

Listing 7. Remoting call from flash to SWHX

{

unction click( e : DockIcon ) #if !local

var c = swhx.Connection.desktopConnect(); c.App.launch.call( [ e.path ] );

}

#end

Listing 8. Calculation of the icon’s scale var middleSize = ( config.minSize + config.maxSize ) / 2;

totalDist = config.spread * ( middleSize + config.spacing ); …

icon.amplitude = icon.maxScale – icon.minScale; …

var ref = iconsContainer.mouseX; …

dist =

Math.abs( ref – icon.x );

newScale = ( icon.minScale + icon.amplitude * ( totalDist –

dist ) / totalDist ) * openScale;

Listing 9. SWFMill library XML file <movie width="320" height="240" framerate="40" version="9"> <frame>

<library>

<font name="TahomaBold" import="assets/tahomabd.ttf" glyphs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678

</library>

9.,!?#'()[]{}+-*/= " />

</frame>

</movie>

Listing 10. UI.hx file import flash.net.URLRequest; import flash.net.URLLoader;

import flash.display.Loader; import flash.events.Event;

import flash.events.MouseEvent; import flash.display.Bitmap; import flash.display.Sprite; import Dock;

typedef Shortcut = {

name

: String,

icon

: String

path

28

: String,

// text displayed on rolling over a picture // path to the application to launch // path to the picture to download and display

01/2008 (1)


Flash Desktop Applications Using haXe & SWHX

{

Listing 10b. UI.hx file }

class UI {

sc.name = j.get( "name" );

public static var instance : UI;

sc.path = j.get( "path" ); sc.icon = j.get( "icon" );

// store the

application instance

var scene

: Sprite;

var urlLoader

: URLLoader;

var dock

var loader var config

: Dock;

// root display object // dock’s instance

: Loader;

: DockConfig;

}

// dock’s

: Array<Shortcut>;

var icons

: Array<DockIcon>; // array of icons

// array of

shortcuts

var currentShortcut

: Shortcut;

// used by

} {

Event.COMPLETE, onLoadIcon );

// Initialize the scene scene = flash.Lib.current;

}

scene.stage.scaleMode = flash.display.StageScaleMode.NO_

{

loader.load( new URLRequest( currentShortcut.icon ) ); function onLoadIcon( e : Event ) var bmp : Bitmap = e.target.loader.content; // Center the picture on coordinates (0,0)

config = cast {};

bmp.x = – bmp.width / 2;

icons = new Array();

// Much CPU consuming :(

shortcuts = new Array();

bmp.y = – bmp.height / 2; bmp.smoothing = true;

// Loading of the config XML file var url = new URLRequest( "data/fdock.xml" );

var icon = new DockIcon();

urlLoader = new URLLoader();

icon.label = currentShortcut.name;

urlLoader.addEventListener( Event.COMPLETE, parseXml );

{

loader = new Loader();

currentShortcut = shortcuts.pop();

// Initialize arrays and objects

}

loadIcons();

loader.contentLoaderInfo.addEventListener(

function new()

SCALE;

}

shortcuts.push( sc );

function loadIcons()

the image load queue

scene.stage.align = flash.display.StageAlign.TOP_LEFT;

}

}

// Start pictures' load queue

configuration object

var shortcuts

{

var sc : Shortcut = cast {};

icon.path = currentShortcut.path;

urlLoader.load( url );

icon.addChild( bmp );

// Proceed load queue or create the Dock when finished

function parseXml( e : Event )

loading all the pictures icons.unshift( icon );

if ( shortcuts.length != 0 )

urlLoader.removeEventListener( Event.COMPLETE, parseXml ); urlLoader = null;

loadIcons();

else

var xml = Xml.parse( e.target.data ).firstChild(); for ( i in xml.elements() ) {

{

if ( i.nodeName == "config" )

loader = null;

dock = new Dock( icons, config, click );

{

config.minSize = Std.parseInt( i.get( "minSize" ) ); config.maxSize = Std.parseInt( i.get( "maxSize" ) ); config.spread = Std.parseInt( i.get( "spread" ) );

}

config.spacing = Std.parseInt( i.get( "spacing" ) );

{

config.delay = Std.parseInt( i.get( "delay" ) );

config.fontSize = Std.parseInt( i.get( "fontSize" )

// Proceed a call to the server-side static

config.hidden = i.get( "hidden" ) == "true" ? true :

{

{

01/2008 (1)

function "App.launch"

false;

for ( j in i.elements() ) if ( j.nodeName == "shortcut" )

#if !local

var c = swhx.Connection.desktopConnect();

"location" ) );

if ( i.nodeName == "shortcuts" )

dock.create( scene );

// Connect to SWHX

config.location = Reflect.field( DockLocation, i.get(

// Set shortcut's array

}

function click( e : DockIcon )

);

}

loader.contentLoaderInfo.removeEventListener( Event.COMPLETE, onLoadIcon );

// Set the config object

c.App.launch.call( [ e.path ] );

}

#end

// Application's main entry point

static function main() {

instance = new UI()

29


ActionScript Development

Listing 11a. Dock.hx file

tf = new TextField();

import flash.display.Sprite;

tf.autoSize = flash.text.TextFieldAutoSize.LEFT; tf.selectable = false;

import flash.display.DisplayObjectContainer; import flash.text.TextField;

tf.width = 220;

tf.multiline = true;

import flash.text.TextFormat;

tf.wordWrap = true;

import flash.events.MouseEvent;

tf.embedFonts = true;

import flash.filters.GlowFilter; import feffects.Tween;

var spread =

typedef DockConfig = {

3, 3 ) ];

minSize

: Int,

// minimum icon's size

spread

: Int,

// number of icons magnified

maxSize

: Int,

delay

: Int,

spacing

: Int,

fontSize

: Int,

displayed text

hidden

: Bool

// dock's location on the // hide dock when rolling

out?

class Dock extends Sprite {

var target

bottom;

: String;

// text displayed while

rolling over

: String;

// extern

application's path to launch when clicking : Float;

// minimum icon's

public var maxScale

: Float;

// maximum icon's

scale scale

public var amplitude

: Float;

: DockConfig; : DockLabel;

// Icon's

name label

var iconsContainer : Sprite;

// Display

var bar

// Background

var sensor

public function new( size : Int )

: Tween;

// FEffects

: Float;

// Used to

: Float;

// Used by

Tween instance

var totalDist

compute magnify

var openScale

tween to compute dock’s visibility : Float;

var screenWidth

: String;

: TextField;

: TextFormat;

: Float; : Float;

: DockIcon -> Void;

var callBack

:

,

this.callBack = callBack;

tfx.size = size;

tfx.align = "center";

>,

:

:

->

)

// Initialize main values and constants

tfx.color = 0xFFFFFF; tfx.bold = true;

<

super();

this.icons = icons;

tfx.font = "TahomaBold";

//

callback function called on click (

{

// margin

offset when the dock is hidden

super();

tfx = new TextFormat();

//

Used to compute dock’s location on the

var screenHeight

// dock's label text getter/setter

var tfx

: Sprite;

var tween

var offsetSensor

public var text (default, setText) var tf

: Sprite;

bar

screen

// scale's amplitude

class DockLabel extends Sprite

30

: Array<DockIcon>;

object where icons are attached

public var minScale

{

: DisplayObjectContainer; // Display

object where the dock is attached

var label

class DockIcon extends Sprite

{

return s;

var config

right;

}

}

}

var icons

top;

public var path

tf.y = -tf.height / 2;

// font size used for the

screen (see DockLocation)

public var label

tf.x = -tf.width / 2;

// space between icons

: DockLocation,

tf.text = s;

tf.setTextFormat( tfx );

dock's apparition

left;

{

{

// motion tween delay for

location

addChild( tf );

function setText( s : String ) : String

while magnification

enum DockLocation

}

}

// maximum icon's size

} {

Math.round( tfx.size / 10 );

filters = [ new GlowFilter( 0x000000, 1, spread, spread,

import feffects.easing.Sine;

this.config = config; openScale = 0;

offsetSensor = 5;

var middleSize = ( config.minSize + config.maxSize ) / 2; totalDist = config.spread * ( middleSize + config.spacing

01/2008 (1)


Flash Desktop Applications Using haXe & SWHX

Listing 11b. Dock.hx file );

x = target.stage.stageWidth; case bottom :

}

rotation = 180;

public function create( target : DisplayObjectContainer )

x = target.stage.stageWidth;

{

screenWidth = target.stage.stageWidth; label.rotation = -rotation; icons.reverse();

// Display object skeleton creating this.target = target;

case left

rotation = 270;

bar = new Sprite();

icons.reverse();

sensor = new Sprite();

screenWidth = target.stage.stageHeight;

iconsContainer = new Sprite();

case top

addChild( label );

addChild( sensor ); addChild( bar );

}

target.addChild( this );

{

addChild( iconsContainer );

setLocation();

].width / 2;

createIcons();

var height = config.minSize + offsetSensor;

createBar();

gfx.beginFill( 0xFFFFFF, 0.01 );

createSensor();

gfx.clear();

gfx.lineTo( width, 0 );

// Dock's view initializing magnify();

gfx.lineTo( width, height ); gfx.lineTo( 0, height );

// Needed when hidden property is set to true in the

gfx.lineTo( 0, 0 );

config XML if ( config.hidden )

iconsContainer.y = bar.y = sensor.y = -

}

config.minSize;

{

// Setting the event listeners addEventListener( flash.events.MouseEvent.MOUSE_MOVE, magnify );

addEventListener( flash.events.MouseEvent.ROLL_OVER,

=

}

removeChild( sensor );

{

switch( config.location ) {

case right :

rotation = 90;

screenWidth = target.stage.stageHeight;

01/2008 (1)

;

gfx.endFill();

function createLabel()

removeEventListener( flash.events.MouseEvent.MOUSE_MOVE,

function setLocation()

/

gfx.lineTo( 0, 0 );

{

target.removeChild( this );

].

gfx.lineTo( 0, height );

removeEventListener( flash.events.MouseEvent.ROLL_OVER,

removeChild( label );

[

gfx.lineTo( width, height );

}

removeChild( iconsContainer );

+

gfx.lineTo( width, 0 );

removeEventListener( flash.events.MouseEvent.ROLL_OUT,

removeChild( bar );

.

gfx.beginFill( 0xFFFFFF, 0.5 );

public function destroy()

magnify );

*

gfx.lineStyle( 1, 0xFFFFFF, 1 );

// function that clean up the scene

fadeIn );

var gfx = bar.graphics;

gfx.clear();

fadeOut );

fadeOut );

function createBar()

.

fadeIn );

}

gfx.endFill();

var height = config.minSize;

addEventListener( flash.events.MouseEvent.ROLL_OUT,

{

var gfx = sensor.graphics;

var width = icons.length * config.minSize + icons[ 0

createLabel();

}

}

:

screenWidth = target.stage.stageWidth;

function createSensor()

// Dock's building

{

:

label = new DockLabel( config.fontSize );

label.visible = false;

function createIcons() var scope = this;

for ( i in 0...icons.length ) {

var icon = icons[ i ];

icon.addEventListener( flash.events.MouseEvent.MOUSE _MOVE, setLabel );

icon.addEventListener( flash.events.MouseEvent.CLICK , click );

icon.width = icon.height = config.minSize; if ( i == 0 )

icon.x = icon.width / 2;

else

31


ActionScript Development

Listing 11c. Dock.hx file

}

icon.x = icons[ i – 1 ].x + icons[ i – 1

function fadeIn( e )

].width + config.spacing;

{

icon.y = icon.width / 2;

icon.rotation = -rotation;

tween.stop();

// callback function that receive the intermediate

icon.minScale = icons[ 0 ].scaleX;

values from the tween

icon.maxScale = icon.minScale / config.minSize *

// and applies it to openScale propertie used to

icon.amplitude = icon.maxScale – icon.minScale;

var scope = this;

config.maxSize;

}

}

if ( tween != null )

compute the icons' size

iconsContainer.addChild( icon );

var update = function ( e ) {

{

scope.iconsContainer.y = scope.bar.y =

var ref = iconsContainer.mouseX;

scope.sensor.y = ( -scope.config.minSize

var icon : DockIcon;

) * ( 1 – e );

var previousIcon : DockIcon;

};

for ( i in 0...icons.length )

var end = function ( e )

{

// callback function called on end of the tween {

icon = icons[ i ]; resize dist =

Math.abs( ref – icon.x );

};

// Compute the new icon's scale

openScale;

"1" tween = new Tween( this, openScale, 1, config.delay );

dist ) / totalDist ) *

tween.setEasing( Sine.easeOut );

tween.setTweenHandlers( update, end );

// Ensure that scale isn't smaller than minScale icon.scaleX = icon.scaleY = newScale <

icon.minScale ? icon.minScale :

}

newScale;

tween.start();

function fadeOut( e ) {

// Place icon's on iconsContainer after scaling if ( i == 0 )

label.visible = false; if ( tween != null )

icon.x = icon.width / 2;

if ( i != 0 )

tween.stop();

icon.x = previousIcon.x + previousIcon.width /

var scope = this;

2 + icon.width / 2 + config.spacing;

var update = function ( e : Float )

icon.y = icon.width / 2; }

previousIcon = icon;

{

scope.iconsContainer.y = scope.bar.y =

dock on the edge iconsContainer.x = ( screenWidth – iconsContainer.width

scope.sensor.y = ( -scope.config.minSize

) / 2;

) * ( 1 – e );

bar.x = sensor.x = iconsContainer.x;

bar.width = sensor.width = iconsContainer.width;

};

sensor.height = iconsContainer.height + offsetSensor;

// Creating a numerical tween from actual openScale to "0"

var currentIcon = e.target;

tween = new Tween( this, openScale, 0, config.delay );

label.x = iconsContainer.x + currentIcon.x;

tween.setTweenHandlers( update, end );

label.text = currentIcon.label;

function click( e : MouseEvent )

32

scope.magnify();

var end = function ( e ){};

function setLabel( e )

{

scope.openScale = e;

if ( scope.config.hidden )

// resize the background and the sensor and center the

}

scope.label.visible = true;

// Creating a numerical tween from actual openScale to

newScale = ( icon.minScale + icon.amplitude * ( totalDist –

scope.label.y = scope.config.maxSize + scope.label.height / 2;

// Distance from the mouse cursor to the icon to

{

scope.magnify();

var dist;

var newScale;

}

scope.openScale = e;

if ( scope.config.hidden )

function magnify( ?e )

callBack( e.target );

tween.setEasing( Sine.easeOut );

}

}

tween.start();

01/2008 (1)


Flash Desktop Applications Using haXe & SWHX

Listing 12. Class App {

{

static var it

: systools.win.Tray;

the icon tray object (windows only)

// get the real screen's size to set the window in

static var window : swhx.Window; // Main window's instance

fullscreen mode var screenSize = systools.Display.getScreenSize();

// Function called from client (Flash) to lauch an

window = new swhx.Window( "FDock", screenSize.w,

external application static function launch( path : String ) { }

screenSize.h, swhx.Window.WF_ALWAYS_

ONTOP + swhx.Window.WF_TRANSPARENT +

new neko.io.Process( path, [] );

swhx.Window.WF_NO_TASKBAR ); // Creates the server thread

var server = new neko.net.RemotingServer();

// Creates the main right click menu (->exit function) static function createPopupMenu() {

// Creates the Flash window

var menu = new systools.win.Menus( true );

var flash = new swhx.Flash( window, server );

window.onRightClick = function()

var cnx : haxe.remoting.Connection;

menu.addItem( "Exit", 1 ); {

// Loads the Flash and creates the window server.addObject( "App", App );

case 1 :

flash.setAttribute( "src", "ui.swf" );

exit();

} }

// Creates the connection to the Flash object

switch( menu.showPopup( window.handle ) ) {

}

// Initialize the SWHX application swhx.Application.init();

// Instance of

flash.onSourceLoaded = function() {

return false;

window.show( true ); createPopupMenu();

// Creates the icon tray and listen to windows' hook message :

}

right click (->exit function)

static function createTray() {

flash.start();

// Main application's loop

it = new systools.win.Tray( window, "FDock.ico", "FDock" );

}

catch ( e : String )

trayMenu.addItem( "Exit", 1 );

{

var trayHook = window.addMessageHook( untyped systools. win.Events.TRAYEVENT );

if ( Std.string( trayHook.p2 ) == Std.string( {

systools.win.Events.RBUTTONUP ) )

switch( trayMenu.showPopup( window.handle ) ) {

} });

case 1 :

}

exit();

return 0;

static function exit() {

}

it.dispose();

swhx.Application.cleanup();

static function main() {

try

01/2008 (1)

swhx.Application.loop();

// In the case something goes wrong :)

var trayMenu = new systools.win.Menus( true );

trayHook.setNekoCallback( function ()

createTray();

// Display the Flash window

// Sets the icon's tray picture

{

cnx = swhx.Connection.flashConnect( flash );

}

}

}

systools.Dialogs.message( "Error", e, true ); exit();

Listing 13. Build.hxml file # swf9

-swf bin/ui.swf -swf-version 9

-swf-lib lib\lib.swf -main UI

-swf-header 600:300:40:999999 -cp src

-lib feffects -lib swhx #-D local --next # neko

-neko bin/app.n -main App -cp src

-lib swhx

33


ActionScript Development Header Classes View Now we can build some kind of extern / intrinsic classes to view the functions’ signatures and the way they will be implemented. Note that, these functions are made here to illustrate the example. We don’t need these functions as it but we will implement the functions’ body later (Listing 4, 5, 6). The Way All Works: We will focus to dock’s important functions, considering, everyone knows the basics like how to download external data or pictures, or how to parse a XML file.

The UI class contains the Remoting call to the server-side in the click function: see Listing 7. Note: Thanks to conditional compilation, we can set a compilation flag to specify if we are testing the flash movie alone (for debugging for example), or if we are to deploy it with SWHX. Without this feature, we should comment this function for debugging all the time, since this Remoting call needs External Interface and the standalone Flash Player throws an exception in this case. While building and debugging process we can switch with the –D local option.

�����

��� ������

Figure 4. createBar and createSensor functions

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

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

�����

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

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

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

Figure 5. Dock’s location on the screen

34

The UI class contains also pictures’ loading function. When the bitmaps are loaded, they are translated as shown on the schema (1) in Figure 3. So they are no more aligned on top left but the coordinates (0, 0) are centred. Note that this is the only visible work done on the icons by the UI class while attaching the bitmaps onto the icons. We’ll give these icons’ objects to the dock in the onLoadIcon event callback function. All next work on icons is made in the Dock class, beginning by createIcons function. Here, the icons are placed one after another including the spacing in an iconsContainer . Note that the first icon was placed as shown on schema (2) in Figure 3; the other icons are aligned horizontally on the first. Then the background bar is created. It will have always the same height but will be extended with the icons horizontally. Especially in this case, the application uses a transparent flash and a transparent window. So, a sensor, higher than the bar, is created in the background, as shown in Figure 4, in order to fix the cursor behaviour, and get the needed mouse events. The sensor will grow while magnifing: it will be expanded to be as long as the bar horizontally and expanded vertically to the maximumSize fixed in the config XML file. The sensor covers all the area used by the dock, it bounds, and a little more called offsetSensor needed in the case the dock is hidden. This offset is the height of the light grey rectangle in this schema: Next step is interesting because it offers the possibility to locate the dock on the screen (left, right, top, bottom). For the moment, all was build in a way that the dock is a rectangle aligned on top left of the screen. To get the right dock’s behaviour on each side, we have to rotate the entire scene this way: see Figure 5. Then the dock is positioned depending on the chosen side. For example, on the top or the left edge, the dock is positioned correctly (for the moment). To set the right position, the dock is translated to the right end of the screen (screen’s width). To set to the bottom, the dock is translated by the screen’s height. Finally, comes the heart of the application: the magnification. It’s the heart because the function magnify is called every time the mouse is moving on the sensor’s area…not because it does really hard work. This function computes the icon’s size depending on its distance from the mouse. The mouse coordinates are relative to iconsContainer, so the main scene’s rotation doesn’t have impact on them.

01/2008 (1)


Flash Desktop Applications Using haXe & SWHX

The function cheats a bit because the total distance that is taken for the calculation is an average depending on the icon’s size and the spread value (specified in the config XML file): see Listing 8. The openScale value depends on the dock’s state: hidden or visible. When the dock is closed, openScale equals 0, open 1. The intermediate values are given by the tween that occurs when the mouse rolls over the sensor, or leaves it. The tween from the FEffects package is a numerical tween between two values that you can assign to properties in a callback function. fadeIn and fadeout functions do that visual hiding-showing job. A last thing is the icon’s label: no special tricks here, except, the dock uses an embed font. So we need to create the media assets library containing this font. To do that, we’ll use SWFMill. This is the SWFMill XML used to build our media library (see listing 9). SWFMill outputs a SWF file that contains the embed font, using this command: Swfmill simple lib.xml lib.swf

Implementing the needed functions: the whole client-side see Listing 10. Server-side: You Never Thought It Was So Easy! There is less than 10 lines of code to write, for the server-side, to get a basic desktop application. The SWHX library includes some easyto-use methods like how to add a flash for example, launch the server, loop or clean up the application before closing it. Server-side Functionalities The dock application, on server-side, will start with the static main function in the App class. This class uses some basic functions to handle the Flash, the main window and the system events. As seen in the dock’s specifications, the application needs to run in transparent window mode, to be in front of all other windows, uses an icon tray and shows a popup

On the 'Net • • • •

http://www.haxe.org – (haXe official website) http://screenweaver.org – (SWHX official website) http://swfmill.org/ – (SWFMill official website) http://filt3r.free.fr/index.php/2008/05/ 06/52-flash-desktop-applications-usinghaxe-swhx – (Article about the dock)

01/2008 (1)

menu on right click (on the icon tray or the whole application). Implementing functions see Listing 12. Putting it Together and Getting a Flash Desktop Application Now that all classes are written, we have to build the whole. To build the application, this compilation file is used: see Listing 13. This haXe file contains 2 consecutive compilations: • To get the SWF file (used by the Flash Player) • To get the Neko file (used by the NekoVM) For both compilations, we set the used libraries, by the -lib option and the class path with -cp. The -main options tell the class where the entry point exist (static function main) For the Flash platform, we have to specify another option like -swf-version (to set flash9), -swf-lib to give your project a media assets library (here this library contains only the embed font used for the icon’s label) and swf-header option (used while testing the movie without SWHX see –D local compilation flag) Finally, we get 2 files: UI.swf and App.n To deploy all the application and link these 2 files, we’ll use the SWHX launcher. It’s an executable file that put all together. This file automatically launches a Flash movie called ui.swf and App.n located in the same folder. Some standard Dlls are included in this folder and some others are specific to the functions used in the application. For example, the dock uses some Systools functions, so we have to include systools.ndll in our project. Then, the dock application seeks for the configuration XML file called fdock.xml in the data folder, and the icon’s pictures are inside another folder called icons. So we have to ensure all files are at the right place. Finally, don’t forget to put the dock’s main icon in the main folder too. The Needed to Run and Distribute the Application Here comes the whole dock’s folder and files structure: • • • • • •

ui.swf

std.ndll app.n

FDock.ico

FDock.exe neko.dll

• • • • • • •

gc.dll

swhx.ndll

systools.ndll ui.ndll

zlib.ndll

regexp.ndll

[data]: fdock.xml,

• • • • • • •

[icons]:

8642-skorpiux-InternetExplorer7-

computer-128x128.png

Text-Edit-128x128.png

Msn-Messenger-2-128x128.png settings-128x128.png

11122-vinced33-firefox-128x128.png

7522-bananaboy-WindowsMediaPlaye r128x128.png 128x128.png

The icons are samples from the net. You can of course, put your own pictures. This is all you need to run your application or distribute it. No heavy integrated run-time is needed, since you add your own pieces of the application by adding specific Dlls to your project. In fact, you can write your own functions in C language, and add them to your project using Neko Dlls, contrary to AIR applications for example.

Conclusion: Why haXe and SWHX? In this article we have seen another way to build Flash applications using haXe. When linked to SWHX, you can build attractive desktop applications. Note that you can use SWHX with traditional Flash movies made with flex or flash CS3, but these examples focus on the haXe interoperability: haXe is platform-neutral and then free the web developer from being locked into one particular platform or technology. (N.Canasse) Finally, it’s a real pleasure to write all you need and deploy what you want, using a same and universal language.

MICHEL ROMECKI Michel Romecki: Passionated by computers and especially programming, he is an auto-didact coder. He worked as free-lance for few years, playing with design and code using mainly Flash. In 2004, he joined Prizee.com, one of the most popular casual gaming website. Today, he is the Manager of the Game Developpement Team, building internet games using haXe and open source tools. He teaches haXe and open source developpement at University. He is also an active member of the haXe and open source community.

35


ActionScript Development

Deconstructing delpadre.com by Nino Del Padre I get a lot of emails from around the world with one simple question I love your website, how did you do it? or How did you do this or that in Flash Well this simple question unfortunately does not have a simple answer however I will attempt to outline the basic workflow and techniques used to create the site. A site like this usually takes several programs to create. In this case I used Adobe Photoshop, Adobe After Effects, Adobe Flash and Autodesk Maya. I will outline the basic steps in creating the Del Padre Visual Productions 5.0 Flash site. Level of difficulty

36

01/2008 (1)


Deconstructing delpadre.com

01 Create the Site Layout in Photoshop After you plan out your site structure, links, pages and colors you can start creating the mockup in Photoshop. I created the interface with Photoshop’s Freeform Pen Tool, Vector shape tools and layer effects like bevel, satin and gradient overlays. I started creating and transforming primitive shapes to create a slick looking interface.

02

Building the Interface Continue to create sections of the site to accommodate your navigation and content areas. I added shapes with a pillow emboss to create more depth to the interface. I set the layer fill transparency to 0% and set the pillow emboss to smooth, depth to 1000, direction down, size of 1 and an angle of 14 degrees and an altitude of 48 degrees.

03 Cut it out After you have all of the elements for your site in position you should start exporting all the elements that you would like to animate in Flash separately. For Instance I wanted the interface to build itself during the intro of the site so I need to hide all the layers except the outer interface, crop the transparent areas around it and go to File>Save For The Web and choose PNG-24 Preset with Transparency Checked. Repeat this step for each item like buttons, logo, etc.

01/2008 (1)

37


ActionScript Development

04 Start a New After FX Comp The next step is to create the animation of the interface in Adobe After FX. I am using several Plugins by Trapcode (www.trapcode.com) Starglow, Shine and Particular. Create a new After FX composition the same size as your interface image. Import your interface png and add it to your new composition.

05

Animate the Starglow Mask Play around with Starglow until you get the look you want. I am using Luminance as the input channel and I checked the use mask button. I animated the mask radius, feather and position to animate the interface from the top right of the screen clockwise. I also keyframed the Threshold, Streak Length, Boost Light and the Opacity to achieve the final effect. To keyframe attributes in After FX you click on the clock icon and set your value at say the first keyframe and then move to the frame 30 and change the attribute and a keyframe will automatically be created.

06

Add Trapcode Starglow Add Trapcode Shine to your composition. Try some of the different presets under colorize. I used the heaven preset. I animated the Ray Length, Boost Light and Opacity values. This ads an overall glow to the interface.

38

01/2008 (1)


Deconstructing delpadre.com

07 Add Some Smoke

Add a new solid by clicking on Layer>New>Solid. Click Make Comp Size and click ok. Add the Particular pugin by choosing Effect>Trapcode>Particular. Choose a smoke preset and animate the emitter around the outer edge of the interface.

08

Export the Comp to Video Now its time to export your composition to video so you can import it into Flash. Go composition>Add to Render Queue. Go to your render Queue and click on Output Module and choose QuickTime as the format, click on format options and choose none as the compression type and 30 frames per second. Click on OK, set your output folder and click render.

09

Import Assets into Flash and Create New Project Create a new Flash project, set the frame rate to 30 and set the stage size to 1280 X 1024. Go to File>Import>Import Video. Choose your After FX output QuickTime and choose Embed video in SWF and play in timeline. Choose Embedded video. Choose Flash 8 High Quality (700kbs) preset, choose next and finish. The video will start encoding and will appear on the stage when completed.

01/2008 (1)

39


ActionScript Development

10 Create Timeline and Begin Animation Center the video on your stage and place a blank keyframe when the video is done playing once. On the next frame import your interface image you exported form Photoshop in step 3. Place it in the exact position on the stage that the video is. This will give the appearance of one smooth transition form the video to the still image of the interface animation. Continue to import elements from Step 3 into Flash on separate layers and animate them in various ways. After you import each image click on F8 to convert each image into a movie clip.

11

Add Sound Effects and Action Scripting Choose some sound FX that fit your animation style. High quality sound FX are important and can be found in sound FX libraries like Sound Ideas (www.soundideas.com) Time the sounds to your animation and choose stream sound time as you want the sound to sync with your timeline. Create interactivity for your buttons and timeline with Actionscript. We don’t have enough time to get into Action scripting techniques but the Flash Help Docs have many tutorials and more can be found on the web at sites like Ultrashock (www.ultrashock.com) and Kirupa (www.kirupa.com).

12

Optimize and Publish Your Movie When you’re done with your scripting and testing it’s a good idea to optimize your Flash movie to make the smallest possible file size while maintaining good quality. Make sure that your data rates on your audio are not too high and that your image quality setting are set high enough to look good but not take up too much file size. That’s it! This is a very broad tutorial but get a look at the workflow. The most important thing is to have fun!

40

01/2008 (1)


01/2008 (1)


Server-side Interaction

Flash Applications Using Streaming Hessian 2 and Resin

by Emil Ong

What do games, chat, and financial Flash applications all have in common? They are all client applications in client-server systems that need updates from the server. When an alien is firing a weapon at you, a friend is sending a message, or the market is making a huge shift, the client needs to get that information right away. What you will learn...

What you should know...

• The architecture of server-push applications and when and why to use them • How to write server-push clients in Flex • How to write server-push servers in Java

• Flex and ActionScript • Java programming • Java Servlet configuration

Level of difficulty

plication using the Hessian 2 protocol and the Resin application server. The client will use Flex and the server will be written in Java.

Writing the Client

T

here are ways to do this with traditional remoting technologies like SOAP or RPC. For example, the application can poll the server at a regular rate to get new updates. Polling is very tricky in practice however: you have to tune the polling rate perfectly or else you run into serious problems. If your polling rate is too slow, users might miss critical updates. If your polling rate is too fast, you may use up your server bandwidth and computing power unnecessarily during periods with fewer updates. Different rates may be more appropriate at different times. Illustration 1 shows this problem graphically: The client may have some requests return several events simultaneously, even if they happened after each other or long ago. Some requests might return no events, thus wasting network resources and server time. The problem with polling is that the client has to guess when there might be an update available. There is another solution: server-push. Server-push allows the server to tell the client when events are happening rather than having it guess. In this paradigm, a client connects once to a server and then updates are sent automatically over a constant connection. Illustration 2 shows this solution: Only the necessary network communication is used when events occur. In this article, we show you how to write both the client and server in a server-push ap42

Our application is a simple example of what can be done with server-push technology, but it illustrates a number of important concepts. In this section, we will show how events are received and processed from the server and how to struc-

ture the client side. The application consists of a Flash client implemented in Flex that receives lines of a Latin text from the server. These lines are displayed to the user as they arrive. See Illustration 3 for a screenshot of the client in action. Even though we are sending static content in this example, the same mechanism could be used to send more dynamic data sourced from a stock ticker, internal network statistics, or even other users. Because the server is in control of the data that the client receives and when it receives it, the client we show here could actually be used for dynamic content without modification! We'll implement the client in Flex using a Hessian 2 streaming service. Hessian 2 is a fast, efficient, streamable, binary protocol with numerous open source implementations in many languages. When we use the word streaming in

�������

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

����� ������

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

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

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

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

Figure 1. Problems with polling

01/2008 (1)


Flash Applications Using Streaming Hessian 2 and Resin

Listing 1. The client receives events from the server <?xml version="1.0"?> <mx:Application

xmlns:mx="http://www.adobe.com/2006/mxml" implements="mx.rpc.IResponder">

<hessian:HessianStreamingService xmlns:hessian="hessian.mxml.*" destination="server-push" responder="{this}"/>

<mx:Panel

title="Caucho Hessian Server-Push Demo" paddingTop="10" paddingBottom="10"

paddingLeft="10" paddingRight="10"> <mx:Script> <![CDATA[

[Bindable]

private var _state:ClientState = new ClientState(); public function result(data:Object):void {

var updater:Updater = Updater(data); updater.update(_state); }

public function fault(info:Object):void { ]]>

} </mx:Script>

<mx:Label text="The following messages have been received from the server:"/> <mx:List dataProvider="{_state}" width="100%"/> </mx:Panel>

</mx:Application>

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

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

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

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

this context, we don't necessarily mean streaming media such as video or audio. Rather we use the word stream to mean a sequence of events sent from the server to client. Using Hessian 2 allows us to receive these events from the server in the same way that Flex receives any other event: we register an event listener. Let's take a look at Listing 1. Users familiar with Flex RPC services like WebService might find the HessianStreamingService tag familiar. Using this tag makes the initial connection to the server. The destination attribute is a URL, in this case it is relative. The responder attribute specifies the listener for events that are received from the server. The event listener must implement the interface mx.rpc.IResponder. In this case, it is the Flex Application itself that implements that interface and will be the event listener directly. When events are received from the server, the function result() is invoked. In this example, events implement the interface example.Updater. This interface contains a function update() that modifies the client state. The class example.ClientState contains the lines of Latin that have been received from the server. There is only one type of Updater in this example, example.AddString, which adds a string to the client state. We structure the program in this way to show that you should think of the objects sent by the server as active events that operate on the client.

Writing the Server Now that we've seen how the client is implemented, let's take a look at the server. The server is implemented using Java and the server-push API in the Resin application server. For developers with Java experience, this API is very similar to the Java Servlet API. To implement a server-push service, you implement a class that extends com.caucho.servlet.come t.GenericCometServlet. There are two methods in this class that must be overridden to dealing with clients: •

service() – deals with the initial connec-

resume() – pushes data to the client

tion made by the client

������� ����

Figure 2. Streaming sends events as they happen

01/2008 (1)

�������

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

Let's first look at the service() method of our example service in Listing 5. First, we set

Figure 3. The client displays lines of a Latin text as they are received from the server

43


Server-side Interaction

Listing 2. ClientState implementation return;

package example {

public interface Updater {

}

}

if (lines.length > 6)

function update(state:ClientState):void;

lines.shift();

lines.push(value);

package example {

import mx.collections.ArrayCollection;

source = lines;

public class ClientState extends ArrayCollection {

public function get lines():Array

}

private var _lines:Array = new Array();

{

public function update(value:String):void {

if (value == null)

}

}

}

return _lines;

Listing 3. AddString class package example {

{

public class AddString implements Updater { private var _value:String;

}

public function update(state:ClientState):void

public function get value():String { }

{

return _value;

public function set value(st:String):void

_value = st;

}

}

}

state.update(value);

Listing 4. The service() method handles the initial client connection public boolean service(ServletRequest request, ServletResponse response,

req.setAttribute("comet.hessian", out);

throws IOException, ServletException

CometState state = new CometState(controller);

CometController controller) {

HttpServletRequest req = (HttpServletRequest) request;

// Add the comet state to the controller

HttpServletResponse res = (HttpServletResponse) response;

_timerService.addCometState(state);

Hessian2StreamingOutput out;

out = new Hessian2StreamingOutput(res.getOutputStream());

}

return true;

Listing 5. The resume() method pushes data to the client public boolean resume(ServletRequest request,

hessian");

ServletResponse response,

CometController controller)

Object command = controller.getAttribute("comet.comman

{

out.writeObject(command);

throws IOException, ServletException

d");

HttpServletRequest req = (HttpServletRequest) request;

out.flush();

HttpServletResponse res = (HttpServletResponse) response; Hessian2StreamingOutput out;

}

out = (Hessian2StreamingOutput) req.getAttribute("comet.

return true;

Listing 6. The run() method of the TimerService public void run() {

synchronized (_stateList) {

for (int i = _stateList.size() - 1; i >= 0; i--) { CometState state = _stateList.get(i);

44

if (! state.wake())

}

}

}

_stateList.remove(i);

01/2008 (1)


Flash Applications Using Streaming Hessian 2 and Resin

������

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

�����

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

�������

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

���������

����� ������

���������

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

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

Figure 4. Call graph of the application

public boolean wake() {

// close the connection after writing the poem twice if (2 * TEXT.length <= _index) {

_controller.close(); }

return false;

String text = TEXT[_index++ % TEXT.length];

_controller.setAttribute("comet.command", new AddString(text)); _controller.wake(); }

return ! _controller.isClosed();

On the Net • •

http://hessian.caucho.com/ – The Hessian 2 website http://www.caucho.com/ – The Caucho website, featuring Resin downloads

up a Hessian2StreamingOutput object: this will encode all our events and write them to the client. This encoder is saved in the request as an attribute called comet.hessian. Next we create a CometState object that keeps track of the client and add it to a timer service. The timer causes all CometStates that are registered with it to send an update to the client every second. Remember that even though we send static data at a regular rate in this example, this infrastructure is capable of sending dynamic data at arbitrary times. Now let's take a look at the resume() method in Listing 6. In this method, we first retrieve the Hessian2StreamingOutput that we created in the service() method. Next we get an object from the CometController using the key comet.command. This object is actually an event 01/2008 (1)

reference. That controller is used again here to pass the AddString event via the comet.command attribute. Finally, the controller's wake() method is called, which causes the controller to invoke the resume() method on service. The call graph of the server is shown in Illustration 4. This service is deployed on the Resin application server using the same configuration as a standard Java Servlet. One of the complications of writing server-push applications in the past has been that the developer has to worry about threads and management of client state. Resin's server-push infrastructure actually takes care of all of these details for you, meaning that complex applications can be written using the same techniques as we outlined here. CometController

Listing 7. CometState.wake() method

to send to the client. We'll see where that command comes from and what it is later. For now, we just take that command event and use the Hessian2StreamingOutput to send it to the client. The timer service that we saw in service() method above is what schedules data to be sent to the client in this example. The TimerService class is actually just a Java Runnable object whose run() method is invoked every second. Listing 7 shows the code for that run() method. Remember that we added a CometState object to the timer when we accepted a new client. The timer service keeps a list of those states called _stateList. When the run() method executes, it simply iterates through this list and calls the wake() method of each CometState. Notice what happens when a wake() returns false: it is removed from the list of states because a false return value means that the client has disconnected. Now let's look at what happens when the CometState.wake() method is called in Listing 8. First, we create a new event that adds the next line of the Latin text to the ClientState. Remember when we created the CometState object, we initialized it with a

Conclusion In this article, we've seen how to write both the client and server sides of a server-push application. We used Hessian 2 as the service protocol to send events from the server to the client. The actual server was written to run on the Resin application server, using its Server-Push API. Using these two technologies as a foundation, server-push is now much more accessible to Flex developers. Visit http://hessian.caucho.com/ to download Hessian 2 for free and to see this application in action. The Resin application server can also be downloaded for free from http: //www.caucho.com/. Both are open source projects from Caucho Technology.

EMIL ONG Emil is the Chief Evangelist of Caucho Technology. Before taking on this role, he was a software engineer at the company, working on Caucho's SOA and JavaEE offerings. With an M.S. in computer science from UC Berkeley, Emil also has a background in security and systems.

45


Server-side Interaction

Flash Client-server Communication Using Flash Remoting and WebOrb by Paul Gritsay It is not a secret that Flash was born as a tool for designers, letting them to create and integrate vector animated graphics into web content. Later it grew up: ActionScript language was implemented, which allowed animations to have some logic, rules, and be programmed. What you will learn...

What you should know...

• How to send data from a Flash movie to server using Flash Remoting • What your server should have for successful communication with a Flash movie. • Arrangement of flash-server dialog, sample ActionScript code needed.

• You must be familiar with ActionScript classes, Flash IDE and components. • You should have a basic knowledge of PHP • You should have access to your web server and be able to install needed packages on it

Level of difficulty

T

ogether with ActionScript2, Flash programming came into OOP paradigm. ActionScript3 presented new facilities and I believe AS became a true programming language. While transforming from Flash banners and menus to Flash Web applications, the needs of ActionScript developers has increased tremendously. In this article I will shed some light on implementation of communication between your flash movie and server. As an illustration we will create a flash class which will save a message into a file on a server. Let us create a very simple guestbook with a Flash form to post new messages. For this article I will talk about Flash 8 IDE and ActionScript2.

We named them txtName, txtComment and sendButton respectively. For easier implementation, we convert all this controls to a movie clip and link it to AS2 class file. To do so, select all controls and then press [Ctrl]+[F8], put name form1 as a movie clip name. Then, to link it to the future ActionScript class, you need to right click on form1 in Library, and select Linkage… item. We will create a class named sendMessageForm, so the form should be filled like shown on Figure 2. That is it. Now we go a bit into ActionScript. Create a new .as file and name it just as we named our class sendMessageForm.as. Refer to Listing 1 for sample code needed.

Now, if you test your movie, and input any data into Name and Comment field, they will be traced in Output window.

ActionScript Class structure In Listing 1 we are accessing the button and textfields via this[] , this is possible as we have the instances with proper names created in the ‘form1’ movie, which was then linked to sendMessageForm class. This is pretty useful technique, which may allow you to control complex timeline animations from within the code. One more helpful thing used in the above listing is Delegate class. This utility class allows

Figure 2. Linking movieclip with ActionScript class

Create Flash Form Open the Flash IDE and create a new Flash Document. Put needed elements on it, just as shown on Figure 1. Here we have a couple of text fields and a submit button to send data to the server. 46

Figure 1. Simple Flash Form content

Figure 3. Remoting components installed and ready to be used

01/2008 (1)


Flash Remoting and WebOrb

calling the function in needed scope. In our case we need onRelease button handler to interact with our class’ data, which will not be easy to implement if assigning the function directly as shown in Listing 2. In the listing ‘this’ is a reference of sendButton, and we need to use _parent to access sibling controls. Delegate class helps us to resolve the scope issue and function sendMessage() of the sendMessageForm class will be called when sendButton’s onRelease event occurs.

Install Flash Remoting Components To proceed with Flash Remoting you need to download and install it from Adobe website:

http://www.adobe.com/products/flashremoting/ downloads/components/ When installed a new entry should appear in the Components pane. It is Remoting Connector, placed under Data Components group. Note, you need to restart Flash IDE for this entry to appear. See Figure 3. Along with this installation, your Flash help content is updated with detailed info on Flash Remoting.

Prepare Server. Install WebOrb Next step is to prepare our server to be ready for communication with flash movie, in particular, with Flash Remoting. Especially for this purpose Action Message Format (AMF) was developed and we need a gateway

installed on our server, which supports that format. For that purpose, I would recommend trying WebOrb by Midnight Coders, which is free for personal and non-commercial usage. It is available at http://www.themidnightcoders.net/ downloadcenter/ For this article we will need WebOrb for PHP. Installation is quite simple, you just need to unpack the archive. So you may setup it to any subfolder on the server. We have it installed locally at http://localhost/ communication/ Now, you should note the following paths: • http://localhost/communication/WebOrb – it is a flash services gateway

Listing 1. Basic AS2 class, prepared to send data to server import mx.utils.Delegate; class sendMessageForm extends MovieClip {

function sendMessageForm() {

}

this["sendButton"].onRelease = Delegate.create(this,sendMessage);

private function sendMessage() {

var name:String = this["txtName"].text;

var comment:String = this["txtComment"].text; trace("name: "+name+"\nComment: "+comment); //here we will add Flash remoting code later, to send data to server

}

}

Listing 2. Accessing the movie clip’s data via _parent reference class sendMessageForm extends MovieClip {

function sendMessageForm() {

this[„sendButton”].onRelease = function() {

var name:String = this._parent[„txtName”].text;

var comment:String = this._parent[„txtComment”].text; trace(„name: „+name+”\nComment: „+comment);

}

}

}

01/2008 (1)

47


Server-side Interaction

Listing 3. Creating Flash Remoting service and setting the response handlers

import mx.remoting.Service;

var pc:PendingCall = service.saveMessage(name,comment);

import mx.remoting.PendingCall;

//set handlers for service responds

import mx.rpc.ResultEvent;

pc.responder = new RelayResponder(this, "getReply_

import mx.rpc.RelayResponder; import mx.rpc.FaultEvent; …

private function sendMessage()

result", "getReply_fault");

}

{

var name:String = this["txtName"].text;

private function getReply_result(re:ResultEvent):Void

var comment:String = this["txtComment"].text;

{

//this is called when service is called successfully //create service object, connect it to

//it returns a new url of saved message so

“SimpleGuestBook” service

navigate to it

//which is located at http://localhost/communication/ getURL(String(re.result));

Services/ SimpleGuestBook.php file }

var service:Service = new Service("http://localhost/ communication/Weborb/", null,

private function getReply_fault(fault:FaultEvent):Void

"SimpleGuestBook", null, null);

{

trace("Error occurred while saving the message");

//call saveMessage method of SimpleGuestBook service, }

passing our values

Listing 4. SimpleGuestBook.php file. PHP service class

<?php

dy>".$commentText."</body></HTML>";

class SimpleGuestBook {

//save it to the server

public function saveMessage($nameText,$commentText)

file_put_contents($temp_url , $content );

{

//return url for flash to navigate to //generate the page $temp_url = "../../guestbook/someurl.html"; $content = "<HTML><title>".$nameText." comment</title><bo

On the 'Net • •

• •

http://www.themidnightcoders.net – Official website of WebOrb gateway h t t p : // w w w. a d o b e . co m / p r o d u c t s/ flashremoting/downloads/components/ – Flash Remoting Homepage: http:/ /www.flashdaweb.com – Flash and web tutorials, tips and developments http://www.amfphp.org - alternative server solution for flash remoting http://en.wikipedia.org/wiki/Action_Message_Format - more info about AMF standard

• http://localhost/communication/Services – the directory where all PHP services are located 48

}

}

return $temp_url;

?>

PuttingThem All Together

Summary and Conclusion

Well, now we have everything ready to establish Flash client-to server communication. See Listing 3 with just a few new lines of code where we create a ServiceObject, call the service method and set the response handlers. Note a bunch of new imports. The code is pretty self explanatory. The only question left is the service. How is it created? See Listing 4 for more info. There are just few lines of php code: see Listing 4. Note, this php file should be located at http://localhost/communication/Services/Simple GuestBook.php That is it. Of course the functionality of the service is quite basic, however it is meant to show you the way to create your great and powerful Flash applications.

In this article we went over the information about the components of communication flash and client-server. Free tools are available for fellow developers to create nice flash movies, which will have a bit more interactivity in them. WebOrb and Flash Remoting components have much more functionality that I have described here. Try them, test them and you will be definitely rewarded for your efforts.

PAUL GRITSAY Paul is a co-founder of flashdaweb.com web resource – created to help in Flash and web developments. He has an extensive experience of both system and Flash software development and has written a number of Flash and ActionScript tutorials.

01/2008 (1)



Server-side Interaction

Fast and Efficient Client-Server Communication in Flash and Flex Using Hessian 2 by Emil Ong

In today's highly interactive Rich Internet Applications (RIAs), users expect engaging content with fast response times. More and more, that content is fetched in real-time from a service on the network. To minimize wait time and the chance of losing users, the time spent on the network must be optimized. What you will learn...

What you sholud know...

• How to write RPC applications in Flex and Flash with Hessian 2 • How to write Hessian 2 services in Java

• Flex or Flash programming • Java Servlet configuration

Level of difficulty

M

uch of the time taken up by network services is due to the service protocol used to communicate between client and server. Flash developers have a number of choices of protocols such as SOAP or propriety binary protocols. Unfortunately, SOAP can be slow and daunting to develop for and propriety binary protocols can be costly and lead to vendor lock in. In this article, we present Hessian 2, a fast, efficient, open binary protocol (See Daniel Gredler's independent evaluation of Hessian 2 along with other remoting protocols here: http: //daniel.gredler.net/2008/01/07/java-remotingprotocol-benchmarks/) with numerous open source implementations that solves the network service problems faced by Flex and Flash developers.

same API. Developers can use a number of languages and tools to develop Hessian 2 client applications. Flash and Flex are both supported as well as Java, Python, Ruby, and more. Let's take a look at a simple example with some code.

Hello World in Hessian 2 Listing 1 contains the MXML code for our Hello World application. The code sets up a simple panel with a text input and a button. Developers familiar with the Flex RPC API will notice that the <hessian:HessianService> tag is similar to <mx:WebService> tag: it sets up a connection to a service specified by the destination attribute. In this case, the destination is specified by a relative URL,

hello. The difference is that we are using Hessian 2 as the underlying protocol instead of SOAP. In this example, we're connecting to a Hello service that takes a name and generates a greeting for that name. When the user enters a string into the text input and either presses enter or clicks the button, a method is invoked using the HessianService. This method sends the name to the Hessian 2 service. Again, this is similar to Flex RPC Operations: the service contains a number of Operations that each have a send()method. The Operation we're using in this case is hello. Because Flash is completely non-blocking and single-threaded, the send()method returns immediately when invoked. The result of the invocation will be available in a Bindable property of the Operation called lastResult. We bind this property in a label below the text input. When it changes – that is, when the result is returned from the server – the text of the label changes. Developers who have used the Flex RPC WebService will notice that we did not explicitly specify operations. So how did the service

Applictaion Server

Hessian 2 Service A

Hessian 2 Service B

Hessian 2 Architecture What does a Hessian 2 service look like? Take a look at Illustration 1. We have an application server that's hosting two Hessian 2 services. On the client side, we have Flash in the browser. One Flash client may connect to service A, while another Flash client may connect to both services simultaneously. At the same time, the services may be exposed to a partner running Java, all using the 50

Flash Client

Flash Client

Java Client

Browser

Browser

Partner

Figure 1. A Hessian 2 Service and its Clients

01/2008 (1)


Flash and Flex Using Hessian 2

Listing 1. Hello World in MXML

title="Caucho Hessian Hello World"

<mx:Application

paddingTop="10" paddingBottom="10" paddingLeft="10"

xmlns:mx="http://www.adobe.com/2006/mxml"

paddingRight="10">

xmlns:word="*">

<hessian:HessianService xmlns:hessian="hessian.mxml.*"

<mx:HBox>

id="service" destination="hello"/>

<mx:Label text='Whom do you want to say "Hello" to?'/>

<mx:Panel title="Caucho Hessian Hello World"

<mx:TextInput id="who" maxChars="20" enter="sendText()"/>

paddingTop="10" paddingBottom="10"

<mx:Button label="Say Hello" click="sendText()"/>

paddingLeft="10" paddingRight="10">

</mx:HBox>

<mx:HBox>

<mx:Label id="outputLabel" text=''/>

<mx:Label text='Whom do you want to say "Hello" to?'/> <mx:TextInput id="who" maxChars="20"

enter="service.hello.send(who.text)"/>

</mx:Panel>

</mx:Application>

Listing 3. HelloWorld Java implementation

<mx:Button label="Say Hello" click="service.hello.send(who </mx:HBox>

.text)"/>

<mx:Label text='The server said: "{service.hello.lastResul t}"'/>

</mx:Panel>

package com.caucho.helloworld; public interface HelloWorld { public

hello(

}

who);

</mx:Application>

Listing 4. HelloWorld Java Interface

Listing 2. Invoking Hessian 2 from ActionScript

package com.caucho.helloworld;

<?xml version="1.0"?>

import com.caucho.hessian.server.HessianServlet;

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Script>

public

public

<![CDATA[

import hessian.client.HessianProxy;

import hessian.events.HessianResultEvent; private var proxy:HessianProxy = new HessianProxy("hello"); private function sendText():void

}

;

Listing 5. Submitting a Poem to the server ...

public function sendToServer(): {

var token:HessianAsyncToken = proxy.hello(who.text);

usedSet:

token.addEventListener(HessianResultEvent.HESSIAN_RESULT, result);

(

=

();

wordSprite:WordSprite in _words) {

(wordSprite.used)

public function result(event:HessianResultEvent):void

}

{

outputLabel.text = "The server said: \"" + event.result +

]]>

who)

+ who +

}

{

}

hello(

{

import hessian.client.HessianAsyncToken;

}

HelloWorldImpl

HessianServlet implements HelloWorld {

usedSet.push(wordSprite.word);

(usedSet.length > 0)

"\"";

...

}

_service.submit.send(usedSet);

</mx:Script> <mx:Panel

01/2008 (1)

51


Server-side Interaction know how to invoke the hello() method? Hessian2 does not require the explicit protocol documentation that SOAP and other protocols do. It is capable of invoking remote methods with arbitrary arguments in a dynamic fashion,

Figure 2. The Hello World application in action

freeing the developer from learning a new service specification like WSDL. Flash developers can also take advantage of Hessian2, but the API is a little different. The Flex version of Hessian 2 extends the Flex RPC API to be more familiar to developers transitioning from SOAP or other such service protocols. For Flash a new, but simple, API was developed to invoke the Hessian 2 services. Take a look at Listing 2. We use

Listing 6. Reading the most recent poems from the server <mx:Canvas

xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:word="*" implements="mx.rpc.IResponder" label="Read"> <mx:Script> <![CDATA[

import mx.collections.ArrayCollection; import mx.rpc.AsyncToken;

import mx.rpc.events.ResultEvent;

import hessian.mxml.HessianService; [Bindable]

private var _poems:ArrayCollection = new ArrayCollection(); private var _service:HessianService; public function refresh():void {

var token:AsyncToken = _service.getRecent.send();

token.addResponder(this); }

public function result(data:Object):void

{

var event:ResultEvent = data as ResultEvent; var poems:Array = new Array(); var index:int = 1;

for each(var wordSet:Object in event.result) { // Format the poems and put them into the list... } _poems.source = poems;

...

}

MXML to do the layout of the application, but all of the Hessian 2 related code is written in ActionScript. In this example, we now create a HessianProxy, the constructor of which takes the destination URL. To invoke the hello() method, we now invoke that method directly on the proxy and use the token that the method returns to set an event listener. When the result is returned from the server, the result() method is invoked with the value returned. So what does the server side look like? We implemented the Hessian 2 service in Java and deployed it on the Resin application server. Listings 3 and 4 show the interface and implementation of the HelloWorld service. The service simply exposes the hello() method which adds the greeting to the input string. To make the service work as a Hessian 2 service, the implementation class extends the HessianServlet class. This service is deployed as a Java webapp and just uses the standard Java servlet configuration. A More Complex Example: Word Play Now we'll take a look at a more complex example in which users submit content, which can be shared with others in real time. Have you ever been to a friend's house and created a poem on their refrigerator using those little word magnets? Do you ever wish you could share your poems with the whole word? This next example lets you do just that. We will create an application that gives you a set of words to arrange into a poem. You can then submit this poem to a server so that others can read the poem. You can also read poems written by others. The screenshot in Illustration 3 will give you an idea of the application. Let's take a look at the screenshot on the left first. In the Compose tab, we have a number of words on the left that a user drags to the right to compose the poem. Each word is actually a WordSprite object that contains the graphical representation of the word. Each WordSprite object also has a reference to a Word object that contains the word string and the position of the word within the poem. Once a user has composed their poem and presses the Send to Server button, the underlying Word objects within the WordSprites are sent as a set to the server to form the poem. This is where Hessian 2 comes in: the poem is sent by passing it as an argument to a HessianService Operation called submit. See

On the Net •

Figure 3. Word Play Application Screenshot

52

http://hessian.caucho.com/ - The Hessian 2 website

01/2008 (1)


Listing 5 for the function sendToServer() that is called when the Send to Server button is pressed. This function is defined within the implementation of the Compose tab. The array _words is local to the tab and contains all the WordSprites. The function looks for all WordSprites that are used (i.e. have been dragged to the right) and collects the associated words into the usedSet array. This array is then sent to the Word Play service. In this case, there is no return value from the service, so the lastResult field is not referenced. The service is implemented in Java and collects these submitted poems. Now let's look at the screenshot on the right. In the Read tab, the user can press the Get Poems from Server button to invoke another Hessian 2 Operation called getRecent. This invocation takes no arguments, but does return the 10 most recent poems submitted to the service, along with the semi-anonymized IP address of the submitter. Listing 6 shows part of the implementation of the Read tab. First notice that this tab implements the mx.rpc.IResponder interface. This allows the tab itself to be registered as an event listener when the call from the server returns. In the method refresh(), we invoke the Operation getRecent() and register the tab as the listener when the result is returned. The result() method is called with the 10 most recent poems from the server. This method takes the poems and formats them for the application. The user can now click on the poem list on the left to see the poem on the right.

Conclusion In this article, we've seen two concrete examples of using Hessian 2 to write Flash and Flex applications, but this is just a small sample of what can be done with this technology. There are numerous other applications from social networking to news and finance that can use Hessian 2. All of these can take advantage of the easy development approach we have shown here. To learn more about Hessian 2, including free downloads, implementations in other languages like Java and Python, and more tutorials, visit the official Hessian 2 website at http://hessian.caucho.com/.

EMIL ONG Emil Ong is the Chief Evangelist of Caucho Technology. Before taking on this role, he was a software engineer at the company, working on Caucho's SOA and JavaEE offerings. With an M.S. in computer science from UC Berkeley, Emil also has a background in security and systems. emil@caucho.com

01/2008 (1)


Server-side Interaction

MySQL Database Integration with Flash by Chetankumar Akarte In this tutorial, you will connect a Flash user interface with a MySQL database using PHP scripting. Adobe Flash does not have a way to directly connect to any database. You must connect using some type of middle tier language. What you will learn...

What you should know ...

• • • • •

• Intermediate knowledge of using Flash, including creating and running, using components and data binding • Basic knowledge of XML • Basic knowledge of PHP • Basic knowledge of MySQL • Basic knowledge of web server, including uploading and testing files on a web server

Setup MySQL Database Parse data through PHP Design Interface to display records Finalize design Uploading and Testing

Level of difficulty

have designed my XML structure (Listing 3.) which is as follows.

images inside a folder called images. Now you are ready with your database so we are now moving to our next section.

Parse Data through PHP

P

HP will make all resources available for us to communicate MySQL through Flash. Imagine you have some book reviews in MySQL database and want to display it using flash. We will go through several processes to accomplish the task.

Here we have to populate database tables to generate xml structure from table data. You can design your XML structure as you like. I

Figure 1. Expected XML Structure

Setup MySQL Database To work with the MySQL database, we first need to connect to the MySQL Database Server. PHP provides the mysql_connect() function to do this, and requires three strings as input: hostname, username and password. Open your preferred PHP Editor (I use EmEditor) and create a new document. Save it as connect_db.php and following lines (Listing 1.) into that file. Now we have to create the tables reviewinfo (in MySQL) which allows us to store our book review. Then we have to add data so we can test our application. Create these tables by running queries from Listing 2. in the MySQL client. I created a PHP file make_table.php which will take care of it all. Note that as we have populated the reviewinfo table with data. We are inserting JPG filenames into the ImagePath field. You will place your 54

Figure 2. Dynamic Text fields position with attached image file as txtPublisher get repeated

01/2008 (1)


MySQL Database Inegration with Flash

Listing 1. connect_db.php

is the obvious choice for delivering

<?php

multimedia over the Web. At the heart

class DB {

of Flash\'s power is ActionScript, the

function DB() {

product\'s powerful object-oriented scripting language. ActionScript is

// First update Host, Username, Password and Database. $this->host = "localhost"; $this->db = "DATABASE";

$this->user = "username"; $this->pass = "password";

based on JavaScript, mak','images/ illusion0.jpg'),

(2,'Foundation ActionScript Animation: Making Things

Move!','Keith Peters ','friends of

$this->link = mysql_connect($this->host, $this->user,

ED','English','1590595181','$15.50','Su

$this->pass);

re you can animate using motion tweens,

mysql_select_db($this->db); }

in fact we\'ll help you do that with

register_shutdown_function(array(&$this, 'close'));

our Flash Cartoon Animation book, but

isn\'t there something extra special in

making things move with just a few lines

function query($query) {

$result = mysql_query($query, $this->link);

}

return $result;

of code? In this book Keith P','images/ illusion2.jpg'),

(3,'Object Oriented ActionScript For Flash 8','Todd Yard, Peter Elst','friends of ED','Englis h','1590596196','$29.69 ','With the

function close() {

}

}

release of Macromedia Flash 8, Flash

mysql_close($this->link);

is now the most powerful and widely

used client software for the web, and

its the only one that runs on virtually

?>

every browser, on every platform. It

also features ActionScript, ','images/

Listing 2. make_table.php

illusion1.jpg')");

<?php

echo "<h3>Database created successfully!</h3>"

require_once("connect_db.php");

?>

//Connect to database $DB = new DB;

Listing 3. Row XML Structure

//Drop table if already exit mysql_query("DROP TABLE IF EXISTS `reviewinfo`");

<Books>

<Book>

//create table mysql_query("CREATE TABLE `reviewinfo` (

`SrNo` int(11) NOT NULL auto_increment, `Title` varchar(225) default NULL,

`Author` varchar(225) default NULL,

`Publisher` varchar(225) default NULL, `Lang` varchar(100) default NULL, `ISBN` varchar(20) default NULL,

`Price` varchar(10) default NULL,

`Review` varchar(512) default NULL,

`ImagePath` varchar(225) default NULL, PRIMARY KEY

<?xml version="1.0" encoding="UTF-8"?>

(`SrNo`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1");

<title> </title>

<Author> </Author>

<Publisher> </Publisher> <lang> </lang> <ISBN> </ISBN>

<Price> </Price>

<Review </Review>

<ImagePath> </ImagePath>

</Book> <Book>

<title> </title>

<Author> </Author>

<Publisher> </Publisher> <lang> </lang> <ISBN></ISBN>

//Insert Data mysql_query("insert into `reviewinfo` (`SrNo`,`Title`,`Author`

,`Publisher`,`Lang`,`ISBN`,`Price`,`Revi ew`,`ImagePath`) values

(1,'ActionScript : The Definitive Guide','Colin Moock, Gary Grossman','O\'Reilly','English','15

<Price> </Price>

<Review </Review>

<ImagePath> </ImagePath>

</Book> </Books>

65928520','$35.12','Macromedia Flash

01/2008 (1)

55


Server-side Interaction Now we have to write the PHP code to dynamically get the data from MySQL. These files fetch data from the MySQL tables and generate XML files similar to the ones which we have designed in our XML Structure. Create a new PHP file and name it reviews.php. Copy and paste the code Listing 4. reviews.php which parse database and we will have structured XML format expected see Figure 1.

Design Interface to Display Records We have finished the PHP and MySQL work. Now we have to design interface to display records. Create a new Flash document. File> Flash Document or by [Ctrl]+[N] and modify its property as width 550px and Height 400px and background color black. You can do this

through Modify> Document… or by [Ctrl]+[J]. Using Text Tool [T] draw 7 Dynamic Text fields and give them <Instance Name> as txtTitle, txtAuthor, txtPublisher, txtLanguage, txtISBN, txtPrice, txtReview respectively. Your new interface design should look something like Figure 2. Now insert new layer (layer 2) by Insert>Timeline>Layer. Now we to add two buttons so that we can switch between records (reviews) next or previous. Rather than design our own buttons we use buttons from Flash’s common library through Windows>Common Libraries>Buttons. I have selected two buttons rounded green back and rounded green forward from Playback Rounded Library. You may use these or you create your own. Drag both buttons from Library to New layer (layer 2) and give

Listing 4. reviews.php

count =

<?php

require_once("connect_db.php"); $DB = new DB;

$result = mysql_query("SELECT * FROM reviewinfo"); // Here we have selected all data from Table reviewinfo // and going to perse it as per our requirement. // And now we need to output an XML document echo '<?xml version="1.0" encoding="UTF-8"?>'; echo '<Books>';

while($row=mysql_fetch_array($result)){

In this section we are going to display data from XML which was received as an output of reviews.php. Insert a new layer (Action) by Insert> Timeline>Layer. Press [F9] (or Windows> Actions) to open Action Script Panel. We have to Load XML structure by defining a XML object. Take a look at the code below (Listing 5.) and put it in Action panel window.

0;

function loadData() { total

=

my_xml.firstChild.childNodes.length;

// take the data from the XML lines (line 0,1,2) and place that data inside text fields txtTitle.text=my_xml.firstChild.childNodes[count].childNodes[0] .firstChild.nodeValue;

txtAuthor.text=my_xml.firstChild.childNodes[count].childNodes[1 ].firstChild.nodeValue;

txtPublisher.text=my_xml.firstChild.childNodes[count].childNode s[2].firstChild.nodeValue;

txtLanguage.text=my_xml.firstChild.childNodes[count].childNodes [3].firstChild.nodeValue;

$line = '<Book>';

txtISBN.text=my_xml.firstChild.childNodes[count].childNodes[4].f

$line .= '<Author>'.$row[2].'</Author>';

txtPrice.text=my_xml.firstChild.childNodes[count].childNodes[5]

$line .= '<lang>'.$row[4].'</lang>';

txtReview.text=my_xml.firstChild.childNodes[count].childNodes[6

$line .= '<Price>'.$row[6].'</Price>';

picture.loadMovie(my_xml.firstChild.childNodes[count].childNode

$line .= '<ImagePath>'.$row[8].'</ImagePath>';

}

echo $line;

if

$line .= '<title>'.$row[1].'</title>';

$line .= '<Publisher>'.$row[3].'</Publisher>'; $line .= '<ISBN>'.$row[5].'</ISBN>';

$line .= '<Review>'.$row[7].'</Review>'; $line .= '</Book>';

irstChild.nodeValue;

.firstChild.nodeValue;

].firstChild.nodeValue;

s[7].firstChild.nodeValue, 1);

btnNext.onRelease

=

function()

{

=

function()

{

(count<(total-1))

count++;

echo '</Books>';

{

loadData();

?>

}else{

count=0;

Listing 5. Process XML Structure // define an XML object called "my_xml" my_xml = new XML();

// load data from an external XML file into "my_xml" object my_xml.load("reviews.php");

// ignore "white spaces", text nodes that only contain white space are discarded my_xml.ignoreWhite = 1;

}

("loadData" in this case) my_xml.onLoad = loadData;

loadData();

};

btnBack.onRelease if

(count>0)

count--;

{

loadData(); }else{

count=total-1;

// what to do when data is loaded ... Call a function

56

Finalize Design

// function contents

//connects to the database

}

the <Instance Name> as btnBack and btnNext. Now we have to display image. Press [Ctrl]+[F8] or Insert>New Symbol… to add new symbol. Name it pic and set its type to Movie Clip. Insert new layer (layer 3) and drag Movie Clip pic to it and give <Instance Name> as picture. After finishing the entire task my final skeleton of design looks (Figure 3.):

}

loadData();

};

01/2008 (1)


MySQL Database Inegration with Flash

Here we have defined an XML object called and load data from an external XML which we will get from reviews.php. Then ignored "white spaces", from text nodes that only contain white space and on Load event of my_xml called function loadData(). When function loadData() is called we first count all records and store the amount my_xml

in variable total. Then we have populated all values (see Listing 5). First variable count is set to 0 so by default first record will get display. Then on onRelease event of btnNext and btnBack records get changed. As btnNext get click and released first we check value of count is less than total record value -1 as XML pares data from 0 to n… and

we get count from 1to n… if condition satisfied we are going to increase value of count by 1 and called loadData(); to load data again. If condition is not satisfied that means we are on last record so in else part we set count to 0 and called loadData(); so we get first record after last record. We have applied same logic on btnBack but it will work opposite of the logic of btnNext. So on first record when we click and released btnBack we shift from first record to last.

Uploading and Testing First Update connect_db.php updates your host, Username, Password and Database in it. Create a folder on your web server. Upload all your files into this folder. This includes your HTML, SWF, and PHP files. Then run make_ table.php so you don’t need to worry about database. Create one more folder inside the folder and call it images. Upload all the images you specified in the database into this folder. That’s finished! You are ready to view your directory at the following URL: http:// yourlocalHost/yourDirectory/yourFile.html See Figure 4 for results when I tested.

Conclusion Figure 3. Final Skeleton of Design

MySQL integration is possible though there is not a built in method or Function to do this. We have done it! Here we have learned a few things about Flash and database integration. Once you have a better idea of what needs to be done, we can do anything with PHP, MySQL and Flash.

On the Net: • • • •

XML in Flash www.communitymx.com/ content/article.cfm?cid=D1CB3 How to make Flash 'communicate' with MySQL www.graphicaddicts.net/forums/ index.php/topic,1122.0.html Building with Flash and MySQL www.webmonkey.com/webmonkey/03/ 40/index1a.html Login Using Flash MX, PHP, and MySQL www.kirupa.com/developer/actionscript/ authentication.htm

CHETANKUMAR AKARTE

Figure 4. Final MySQL Flash Integrated Output

01/2008 (1)

Chetankumar Akarte is an Electronics Engineer and he loves programming. He is working on PHP, MySQL, CSS, XHTML, JavaScript, Flash and PhotoShop. His interests are reading books and magazines as well as writing. He has been working on several projects (www.xfunda.com or www.techfunda.com). Currently, he is working as a Software Developer at Green Point Technology Services, Navi Mumbai, INDIA. You can contact him for a feedback or any other suggestions : admin@tech-funda.com, chetan.akarte@gmail.com.

57


Subscribe

subscription@ffdmag.com www.buyitpress.com/en www.ffdmag.com


4 easy ways to subscribe: 1. Telephone

You can order by just calling us at:

1-917-338-3631 2. Online

Order in our online store and pay with your credit card:

www.buyitpress.com/en 3. Post

Complete the form below and mail it to: Software Media, LLC, 1521 Concord Pike, Suite 301 Brandywine Executive Center, Wilmington, DE 19803, USA

4. E-mail

Complete the form, scan it and e-mail to: subscription@ffdmag.com.

Flash&Flex Developer’s Magazine Order Form □ Yes, I’d like to subscribe to FFD Magazine from issue □ □ □ □ 1 2 3 4 Order information (□ individual user/ □ company) Title Name and surname Address Postcode Tel no.

Payment details: □ $39,99 □ €29,99 I understand that I will receive 6 issues over the next 12 months. Credit card: □ Master Card □ Visa □ JCB □ POLCARD □ DINERS CLUB

□□□□ □□□□ □□□□ □□□□ □□□□ □□□□ Issue number □□ □□□

Card no. Expiry date Security number

□ I pay by transfer: Nordea Bank

E-mail

IBAN: PL 49144012990000000005233698 SWIFT: NDEAPLP2

Date

Cheque:

Company name Tax Identification Number Office position Client’s ID* Signed**

□ I enclose a cheque for $ ____________________

(made payable to Software-Wydawnictwo Sp. z o.o.)

Signed Terms and conditions: Your subscription will start with the next available issue. You will receive 4 issues a year.


Sound&Animation

Website Banner by Karolina Sobolewska You will find banners created with Flash at practically every modern website. They make websites both dynamic and visually attractive.The original software for making Flash animations and banners was developed by Macromedia. Several years ago, Macromedia and its products were taken over by Adobe. This means that the latest Flash tools include keyboard shortcuts well known from other Adobe products. In this tutorial, I will try to present the basics of using Adobe Flash. The version used will be Adobe Flash CS3. Level of difficulty

60

01/2008 (1)


Website Banner

01 New Project Start by creating a new project to work on. Select File>New. A new workspace appears. Modify the workspace parameters by double clicking the small figure 12, just below the timeline. We’re making a banner for the main page of our site, so enter 470 for width and 70 for height. Enter 25 in the Frame rate field to ensure smooth banner animation.

02

Banner Elements Once the parameters are set, create layers to hold the banner elements. Call the first layer background, and the subsequent layers text1, text2, text3. Start by creating the background. You can use Flash for this (though this is generally for simple backgrounds only) or create your background using Photoshop. For this tutorial, we will use a photoshopped background. (Note, however, that Flash does not compress graphics like Photoshop can, so if you import a 2 MB image, your final banner will also be that big.)

03 Background and More Elements To make sure you don’t place the background on another layer, lock all layers except the background by clicking the padlock icons for layers text1, text2 and text3. Next, click the first frame of the background layer and press [Ctrl]+[R] to import a file. Having imported the file, add text to the other layers, each time making sure only the layer you’re working on is unlocked. To add text, click the [T] icon in the toolbar, and click the workspace to add text at the selected location. For convenience, you can also hide any layer by clicking the eye icon for the layer you want to hide.

01/2008 (1)

61


Sound&Animation

04 The Workspace

After all the banner elements have been inserted, we can start on the animation itself. Before you do that, it’s a good idea to restore the workspace to its default appearance – click Window>Workspace>Default. Start by creating the background for the entire animation. Unlock the background layer, click the first frame, move the slider, click frame 100, and press [F5]. A grey strip will appear – that’s the animation background. Depending on how long the animation is, you can keep expanding the background by repeating the process, i.e. clicking a frame (say 180) and pressing [F5].

05

Movie Clip Before you animate text1, click the first frame of the layer and press [F8]. From the menu that appears, select Movie clip and press OK. Creating text1 as a Movie clip lets you apply filters, which we will come to soon. Right-click the first frame and select Create motion tween. With the left mouse button, drag frame 1 to frame 10, then click frame 25 and press [F6] to create a keyframe. Now click frame 60 and press [F6], and do the same for frame 75.

0 6 Animating the First Text Let’s add a simple appearing/disappearing effect. Click the first frame of the text1 animation, then click the text itself. An options panel appears at the bottom of the screen. Select Alpha from the Color drop-down, and set the slider at 0%. The text disappears. Now click the last frame of the text1 animation, then click the text itself to display the same options panel again. Once more, select Alpha from the Color drop-down, and set the slider at 0%. The text disappears. Run your animation by pressing [Enter].

62

01/2008 (1)


Website Banner

07 Animating the Second Text

Lock and hide the text1 layer. Unlock text2. Right-click the first frame in the layer and select Create motion tween. With the left mouse button, drag the frame to frame 65. Now click frame 80 and press [F6], and do the same for frames 125 and 140. By now we’ve run out of background, but don’t worry. Click the first frame of the layer, then click the text, hold down [Shift] and drag the text left, outside the workspace.

08

Dynamics Select frame 65. Locate the Ease option at the bottom of the screen, and set it to 100. This will cause the text to enter the animation quickly and slow down towards the end. Click the last frame and drag the text onto the workspace to the right, then click frame 125 and set the Ease parameter to -100.

09 Animating the Third Text Lock and hide the text2 layer. Unlock and show the text3 layer. Right-click the text and select Create motion tween, then drag’n’drop the text to frame 135. Now click frame 150 and press [F6], and do the same for frames 190 and 205. Click frame 135 again, then click the text and enlarge it using [Shift]+[Q]. Again, set the text’s Alpha parameter to 0%. To add some dynamics, set Ease to -100. Click frame 205, then click the text and make it very small, and also set its Alpha to 0%.

01/2008 (1)

63


Sound&Animation

10 Completing the Background We still need to complete the background. Lock and hide the text3 layer. Unlock the background layer, click frame 210 and press [F5]. Note that the background is slightly longer than the animation to create a pause between the text appearing and disappearing.

11

Blurring Let’s also add a blur effect to the first text. Lock the background layer. Unlock and show the text1 layer. Click frame 10 within the text1 layer and select the text in the workspace. In the bottom panels, select Filters, click the plus symbol, select Blur, and click the padlock between Blur X and Blur Y to set the two parameters independently. Specify 75 for Blur X and 20 for Blur Y. Now click frame 75 and create the same effect, but swapping the values of Blur X and Blur Y. Note that even though you will already see a Blur effect, you need to add it once more, without deleting the existing one.

12 The Button Create a new layer above text3, and call it button. Use the Rectangle (R) tool to draw a rectangle covering the entire banner, then select the rectangle and press [F8]. From the menu that appears, select Button. Click OK and double click the rectangle. Move the up frame to the hit frame. The button has become transparent. Now click Scene1 below the timeline to switch back to the animation. Right-click the button and select Actions from the popup menu, then select Global functions > Browser/Network and double-click getURL. In the url field, enter the URL of the target website, including the http://www prefix. Close the window and test the banner by pressing [Ctrl]+[Enter].

KAROLINA SOBOLEWSKA The author is a student at the College of Information Technology in Katowice. Her interests include 2D graphics, Photoshop and creating Flash animations, as well as movie authoring using Adobe Premiere.

64

01/2008 (1)



Sound&Animation

Glass by Jan Filipowiak During my latest struggle with the graphics I came to a problem which required a creation of realistic glass. What made this project harder was the requirement that the glass was to mimic sliding door with a slide effect included. All interested in seeing the working solution should check the Internet site of Marks Hotel (www.markshotels.com) in the Bar and Restaurant section.

I

n this tutorial we will walk to the different phases of the development of the proposed solution starting with the graphics in Photoshop, followed by creation of the Flash animation using the exported graphic. After completing the project you will be able to modify the project and reuse it in other Internet pages. All of the files which are mentioned in this article can located on the attached CD. To begin the project you will need to use Photoshop and Flash. First step is to fire up both programs and then open a new Flash document. Set the document size and the number of frames using the Properties, located in the lower part of the screen. The Dimensions setting should read 658 x 530 px and the Frame Rate of 24. Next save Flash animation using the name glass.fla. Now let’s move the Photoshop.

66

Level of difficulty

01/2008 (1)


Glass

01 Picture Now you need to select the picture in the Photoshop. As I have mentioned earlier our animation mimic sliding door suggests that we should see an interior, example would be a hotel interior, but could be other uses as well. To prove it I will use the background of a Scottish island of Arran. First we have to make sure that the picture is usable in Flash. Therefore we will reduce [Alt]+ [Ctrl]+[I] the original image to the size of 658 x 350 px and trim it using the Rectangular Marquee Tool. Set the resolution to 72 dpi, and save it as arran.jpg.

02

Timeline Now switch back to Flash using the [Alt]+[Tab]. Here we have an empty document with one frame in the main timeline. We are interested in the 90-frame animation; the reason for it will become apparent later in our development phase. Let’s create a new layer and name it arran and give it a length of 90 frames.

03 Inserting the Picture Now we will insert the picture (arran.jpg) we have saved in the previous step. To do so click on the first frame in the arran layer and next import the picture using [Ctrl]+[R]. Position the picture in such way that it will fill the whole screen. To achieve it, click on the picture and in the Properties section, located in the lower part of the screen, make sure that X and Y fields are set to zero (0).

01/2008 (1)

67


Sound&Animation

04 Glazing Now let’s create the glass. Switch back to the arran.jpg picture in Photoshop, select Filter > Distort>Glass and set the values for the following field: Distortion: 5, Smoothness: 4, Texture: frosted, Scaling: 162%. You could use your own values if you prefer. The modified image should have the same size and resolution as the arran.jpg. Next save the modification under a new name of glass.jpg.

05

Introduction to Animation I think that now is the appropriate moment to explain why we have selected the 90 sec. frame setting for our Flash file. The reason for the setting is due to the fact that we are going to create two sequences in the final result. First sequence will be responsible for opening the sliding door and the second for closing it. Having created the glass.jpg file, we switch back to Flash again and over the arran layer we create a new layer called glass. On this layer we will place two animations, each one having 45 frames.

0 6 Two Sequences First sequence will open the sliding door, and the second will close the door. It is important that the glass layer is placed over the arran layer because glass has to cover the static image we have placed in our animation at the beginning of the exercise. Next, on the frame 46 of the glass layer we create Keyframe [F6].

68

01/2008 (1)


Glass

07 The First Mask Let’s start writing the first frame on our new glass layer. First create a new clip [Ctrl]+[F8], and lets give it a name of opened, select Movie Clip and click OK. Now we are in the clip and we can see it timeline. Now its time for the masks, this will be the used to create the sliding effect. First layer on the timeline will we will name Left mask, click on the first frame and create a rectangle using the Rectangle Tool or click the [R] key. Next in the Properties set the size to 329 x 530 (which is equal to half the animation window) and set the X and Y positions to zero (0).

08

The Second Mask Now we will create second layer names Right mask and after clicking on the first frame of the newly create layer we create rectangle identical to the one in the previous step. However its X position should be set to 329 px so that it aligns with the rectangle we created before. Here we have created our sliding doors and the only thing left is to open them.

09 Creating First Movement Using the layer Right mask select its 45 frame next hold down the [Shift] key and click on the 45 frame of the second layer Left mask. Having selected the two frames from both layers press the [F5] key which will gives us 45 frames on both layers. Next we will create Motion Tween on both frames.

01/2008 (1)

69


Sound&Animation

10 Creating Second Movement To do so click on any frame between the first and last frame of the Left mask layer and from the context menu choose first option (Create Motion Tween). Now click on the last frame of the layer, frame 45, and press the [F6] to create Keyframe. Repeat the same process again for the second layer – layer Right mask.

11

Creating Third Movement Let’s return to our main scene. Move the clip opened from the library to the first (1) frame of the glass layer. Position of the X and Y should be set to zero (0), next double click on the clip and select the last Keyframe on the Right layer. Using the same steps move the second mask to left setting the X position to 670, outside the right edge. Now on every layer click on any frame and in the Properties tab set the parameter Ease to -100. This will make for a smooth movement.

12 Cutting the Glass Now back to Photoshop. It is time to divide our Scottish background into two equal parts in the same size as our Flash masks. Using the Slice tool divide the image and save it into two separate jpg files (left_ cutting.jpg and right_cutting.jpg). Double check that the two pieces are have the correct size (329 x 530 px) to do that use the Slice select tool, press the right mouse key on each piece and select the Edit Slice Options from the context menu.

70

01/2008 (1)


Glass

13 Inserting Sections to Flash Going back to Flash we create two layers: one under the Right mask and name it Right cutting, second under Left mask giving it name Left cutting. Having done that we import [Ctrl]+[R] into the Right cutting our file right_cutting.jpg and we position exactly under the mask from the layer Right mask. Repeat the same process for the layer Left cutting using the left_cutting.jpg file. Using right mouse button on the Right mask layer choose the Mask from the menu, do the same thing to the layer Left mask.

14

Time for break Going back to our main timeline, we have two layers. In the top layer, glass, the range of 1 to 45 frames contains clip opened, which opens the sliding door. Rest of the range, 45-90 is remains empty. On the bottom frame, arran, our picture fills the range of frames from 1 to 90. What next? We opened the door and now we need to close it. To do that we create clip in the empty section of the glass frame.

15 Copying the clip Because we already have a clip opened ready it make no sense to build a new one, closed, from the scratch. Let’s click on the glass layer between the 1 and 45 frame, in the work area select the clip opened and copy into memory using [Ctrl]+[C]. Next select frame 46 or larger on the glass layer and past the clip using [Ctrl]+[V]. Position X and Y should be set to 0. Now click the right mouse button and select the Duplicate Symbol from the menu. In the name field type closed and we have the second clip ready.

01/2008 (1)

71


Sound&Animation

16 Closing the sliding door Working with the closed clip we click on the 1 frame of the Left mask layer and holding the [Shift] key we click on the last frame (45). Having marked all of the frames of the layer we press the right mouse button and from the menu we select Reverse Frames, this process reverses the animation. Repeat the same process on the Right mask layer. By using these steps when you go back to the main timeline you can test [Ctrl]+[Enter] the smoothness of the animation of opening and closing the door.

17

Fulfilling the process Even though that our main work is completed, our glass layer is not very clear, which cause it to loose its effect. Sure, we can see the movement however we still are missing the difference between the backgrounds behind the glass from what is visible when the door is closed. We will try to address this in the final steps of the exercise. By giving the glass frosted characteristics with leaf texture f and white line.

18 Adding texture To add texture we will reuse the graphics which we prepared earlier, by adding the leaf texture with the white line, cut into two pieces same as the mask and glass layers. Both of the pieces will be written in two png files (this format allows for see through effect): right_rime.png and left_rime.png. In Flash, we create new layers on top of the glass layer called rime and stripe. Change the 46 frame of the layer to Keyframe [F6]

72

01/2008 (1)


Glass

19 Animating Left Texture We create a new clip [Ctrl]+[F8] under the name of opened_texture. Next we create a new layer called Left texture and into the import into the 1 frame file left_ rime.png. We set the length of the frames to 45 and create Motion Tween with the parameter Ease set to -100. The last frame should be changed to Keyframe [F6], marked with cursor and we set the X position to 340, just as we did with the layer Left mask. Now return to the main scene and place the new clip on the 1 frame of the new layer. Left side of the sliding door should move to left along with the texture and white line.

20

Animating Right Texture For the right side we repeat the above process. Still in the clip opened_texture we create new layer above the Left texture and give it a name of Right texture. Into the first frame we import file right_rime.png setting its X position to 329 and Y to 0. Motion Tween with the parameter Ease set to -100 get set on the layer and the last frame becomes Keyframe [F6]. Graphics in the last frame should have the X position set to 670 and Y to 0. This will allow both glasses to slide together with the texture.

21 Closing the door with texture As the last point of the program we mark and copy [Ctrl]+[C] clip opened_texture into memory. Next we paste [Ctrl]+[V] the clip into the 46 frame of the same layer. By pressing the right mouse button on the pasted clip we select Duplicate Symbol from the menu. Next assign the closed_texture to the duplicated item. Select the duplicated clip, mark all of the frames and using the right mouse button we select the Reverse Frames option. We repeat the same operation on the second layer and finally test the animation [Ctrl]+[Enter].

As you can see the desired effect is not hard to achieve but the results show us how Photoshop and Flash can work together in great harmony. I came up with this trick, when trying to figure out how to show the entrance to the restaurant and bar in the Marks Hotel, which has the sliding door in real life. The glass could be uneven with irregular edges and door handles, etc. Door handle could be controlled with the click of a mouse button and the door can react to the user’s action upon sliding open. The animation can also be improved with actions just as I have done on the Internet page www.markshotels.com

01/2008 (1)

73


Mobile World

Flash Lite by Bill Volpe As the number of mobile devices and mobile users continues to grow world-wide, the need for talented mobile developers is at an all time high. If you are a mobile developer looking to develop applications utilizing Flash, then to get acquainted with Adobe’s Flash Lite is a no-brainer. What you will learn...

What you should know...

• Flash Lite

• Simply put, Flash Lite allows Flash development for mobile devices • It is primarily used to create vector graphicsbased animation programs • Flash Lite is fully capable of creating Games, Mobile Device User Interfaces, Applications, Screensavers, and other types of programs specific to certain devices

Level of difficulty

systems. In addition you will see that Flash Lite is compatible with Nokia, Motorola, Samsung, LG, and Sony Ericsson devices.

Developing With Flash Lite

A

s a web or media developer – Flash Lite offers the quickest and most effective way to build upon your existing skill set and create mobile content.

Why Should I Develop with Flash Lite: After viewing what some developers have done with Flash Lite, you will in fact be motivated to develop with Flash Lite. Adobe’s Exchange Beta Site provides a great selection of applications fellow developers have been working on: http: //www.adobe.com/cfusion/exchange. Not to mention that Flash Lite is highly portable, and runs on multiple operating

In order to develop with Flash Lite you will need a copy of Flash CS3 Professional from Adobe. You can try/buy the application here: http://www.adobe.com/products/flash/. Flash CS3 Professional supports emulators as well as scripting language compatible with Flash Lite. In addition, Flash CS3 Professional provides various mobile features including templates for Flash Lite applications. Also, Flash CS3 Professional comes preloaded with Adobe Device Central CS3 which provides the following: • Device Profiles • Device Emulators

• • • • •

Memory Mobile Phone CPU Effects Network, batteries, and date/time Device skins with active keypad for UI testing • Ability to switch between devices

A Basic Flash Document Just like Flash documents that run on our PCs and Macs, a basic Flash document for a mobile device typically consists of three things: • Assets or Media Objects • Images • Graphics • Text • Timeline • An area that decides when specific media objects should appear or not appear on the screen • ActionScript • Scripting language to handle user events and control timeline flow

Running Flash Lite on a Device In order to run Flash content on a mobile device, you will need the Flash Lite Player (unless it is already pre-installed on your device). If not, it can be downloaded separately from Adobe: http://www.adobe.com/products/ flashlite. A browser plug-in is also bundled for mobile browsers.

On the 'Net • • • •

Figure 1. Nokia N Series N95

74

Forum (http://www.forum.nokia.com) Flash Lite Discussion Board (http:// discussion.forum.nokia.com/forum/ forumdisplay.php?f=172) Flash Kit (http://www.flashkit.com) Flash Lite Tutorial Blog (http://flash-litetutorial.blogspot.com/)

BILL VOLPE Bill Volpe is a Mobile Web Marketing Manager in New York. He spends half of his time in front of his PC and the other half in front of mobile devices. The other half of the time (3 halves?) Bill enjoys traveling, hiking, cooking, and playing guitar for a local band. You can contact Bill directly via email: b.volpe@gmail.com.

01/2008 (1)


RECOMMENDED COMPANIES Eltima

mod7

Eltima is a global information technology company. Our team has a proven reputation for delivering high quality software solutions across a broad spectrum of technologies also focusing at professional shareware development. We provide software development, system integration and consulting services.

mod7 is a visual communications and interaction design agency specializing in interactive media, web design and motion graphics. A broad range of clients – from Electronic Arts to CBC – have been rocked by our passion for making killer interactive experiences. We can do the same for you. www.mod7.com

www.eltima.com

Amara

Kindisoft

With Flash software now the standard for website animations, Amara Software provides affordable animation software solutions to create a wide variety of Flash Player compatible text and photo effects and web animations.

Kindisoft started out as a vision; a vision to ensure the security of designers’ code, creativity, and intellectual property. These days, the Internet is becoming a more dynamic and interactive medium of communication, giving designers the freedom to express their selves in any way they want.

www.amarasoftware.com

www.kindisoft.com

almer/blank

Powerflasher

Almer/Blank is an interactive media development agency specializing in high-end Flash applications. We provide enterprise-level code and media development, creating innovative rich media experiences for Fortune 500 clients including one of the world famous companies

Powerflasher has become since its foundation in 1997 Europe’s leading multimedia agency specializing in Flash. Forty passionate coders, graphic artists and animators develop more than 1.000 interactive stunning yet user-friendly on- and offline human interface experiences for prestigious clients all over the globe.

www.almerblank.com

www.powerflasher.com


Book Review

PHP 6 and MySQL 5 for Dynamic Web Sites: Visual QuickPro Guide

Author: Larry Ullman Publisher: Peachpit Press, 2007 Pages: 640 Price: $ 26.99 With the latest edition of his best-selling book, Larry Ullman gives us an update anticipating the forthcoming arrival of the next version of one of the most commonly used languages on the Web, namely PHP. Anchored in the continuity of previous editions, this book is, as you shall see, the idyllic guide to any neophyte developer wishing to venture into the virtual world of dynamic Web pages. As the author likes to say: The focus of this book is on covering the most important knowledge in the most efficient manner. Well, let us face it, mission is fully accomplished. Unlike other books deemed tiring and disheartening, Larry Ullman and Peachpit Press were able to overcome this difficulty through a good visual and didactic approach. No room for ambiguity, the explanations are clear and precise, and the expert tips given at the end of each section are, for the vast majority, really useful. The chosen examples are realistic and, more importantly, the code is functional. You may be inclined to reuse it in your future projects. From the very basics to more thorny subjects like sessions,

preventing attacks or multilingual Web pages, almost everything you should know about PHP and MySQL is here. Beware all the same, the author gives no explanations about the HTML or CSS syntax that is being used, so be sure to know at least a bit on the subject before buying. In the same way, if you want to learn the advanced features of PHP, this book is not for you. Indeed, and this is a downside, it does not cover a significant topic: object-oriented programming. In order to do this, you must obtain its sequel, Advanced PHP 5 from the same author. Note that if you encounter any problem by exploring the book, Larry Ullman proposes to elucidate it directly on his dedicated website (http://www.dmcinsights.com/phpmysql3), and it is a rare thing. To sum up, if you ever wanted to learn PHP and MySQL the fast and efficient way, you may find the perfect book to fulfill your needs. A must have for any programmers new to Web development. by Maxime Bornemann

Adobe Flex 2: Training from the Source

Author: Jeff Tapper, Matthew Boles and James Talbot, with Benjamin Elmore and Michael Labriola Publisher: Adobe Press, 2006 Pages: 624 Price: $ 49.49 Since Rich Internet Applications (RIA) has gain in popularity, Adobe Flex 2 has become very well-known application among Flash developers. Getting started with Flex is a straight forward process and although it may be easier to learn than Flash IDE, you still need a reliable guide to the framework. The concept of this book is targeted at building Flex sample application called Flex Grocer. Flex Grocer is an e-commerce application design by the author to effectively focusing on the Flex Builder 2 Workbench, its Controls, Components, Handling Events and Data Structures; here we get an idea how to work with Adobe Flex 2 environment. Book follows the model of starting from the basic topics and progressing to more advance material. Entire book is in an instructional format, divided book into 25 chapters with setup instruction appendix, along with couple of recipes to test and the first chapter helps us to understand what constitutes Rich Internet Application. The book also comes with a CD that gives all the necessary resources you will need, from demo software to all

76

other related files (images, etc.), which are used while describing example in book. Product data for this application is provided in XML files, and later in the application can be controlled using ColdFusion and provided access database. This is a great book for those looking to start working with Flex framework. It offers you plenty of practical and useful examples that introduce many aspects of Flex. The possibilities of Adobe Flex 2 are countless, you may say nearly limitless and the examples described in the book are timely and can be reused in real life. The book also teaches how to create and how to built components with MXML and ActionScript 3.0 in practical, while performing example book provides practical knowledge of Flex 2. It is a good resource for a self study. by Chetankumar Akarte

01/2008 (1)



Interview

Interview with Bram Timmer BY MAXIME BORNEMANN

Bram Timmer is an award-winning designer, developer, and digital artist that specializes in innovative new media design. How would you introduce yourself? / Can you describe yourself in a few words? Bram Timmer is an award-winning designer, developer, and digital artist that specializes in innovative new media design. Bram applies his creativity and expertise across a variety of media, including: web design and development; e-learning and interactive media; print materials; packaging; information architecture; interactive installations; and illustration. Bram’s past and present clients include commercial and government institutions of all sizes, including MasterCard, Nivea, Hilton Garden Inn, SC Johnson, Adobe, CTV, CFL, Kraft, Hershey, Applebee's, TELUS, EnCana Corporation, Bombardier, Mount Allison University, University of Calgary, FITC, Kahn Consulting, Inc., amongst others. Bram is currently writing Monarch Series' first publication entitled Design Monarchs – Inspiration Forming Empires. The book features some of the industry's highest regarded design professionals and agencies.

How did you get into computer graphics? Looking back now, I notice I drew a lot and always found it interesting to express myself creatively through writing or drawing. When I was younger and still living in the Netherlands, I always wanted to be an architect. It was at this same time that I was introduced to Paint. Photoshop didn’t come into my possession until high school, though I didn’t take it seriously until I jumped into university where I had quite a few photo manipulation, haiku visualization, and web design assignments.

What software do you use? On a daily basis I’m always in Adobe Photoshop with a combination of Illustrator and frequent Flash, Dreamweaver, and InDesign. Outside of the 78

day-to-day processes I’ll make use of After Effects, Cinema 4D, 3D Studio Max, and Soundbooth together with a select few other applications.

How would you describe a typical week? In production stages of my months, I’ll wake up early by sunlight prying open my eyelids – never an alarm clock – and other times, random thoughts of work or emotions that overwhelm my attempt to sleep in. I’ll take the computer in my condo out of hibernation mode and turn on some tunes that will enforce and develop the mood I’d like to leave my condo with while I get ready for the day. I take a casual walk down to my studio and get cracking on the Mac Pro until someone in the building notifies me about lunch, which is forgotten on a regular basis when I’m not at my desk. Throughout the day I’ll receive emails and calls regarding meetings and potential new projects or current ones that need revisions which I sometimes squeeze in depending on the amount of work required on any given project and its due date. I’ll work till late in the night with headphones on or music playing and order some dinner along the way. When I’m not swamped with work, I’ll stroll in around noon and kill it by 5 or 6pm.

What is your favorite work? That’s a really hard question! The work I’m most proud of would have to be the work that has successfully helped my client achieve their goal or even beyond their expectations. That’s the biggest payoff for me. Regarding my personal prints or designs I’ll always go back to them over the course of time and want to edit them, improve them, it’s this continual struggle to create something near humanely perfect. I need to give every project some space after the design phase, because with my head so deep into the details, it’s easy to lose focus of the bigger picture.

Where do you get your inspiration from? What artists influence you? My main inspiration comes from the moods and emotions created within by the music I listen to. There is an exception to that however, when I’m writing I tend to shut off all sounds to focus on the text, which pulls the words from my head (experiences, emotions, etc.) rather than lyrics and beats. Outside of that there are day-to-day activities, people and friends you run in to and elaborate on ideas or collaborate with, galleries, books, and photography. Furthermore, contemporary artists and architecture throughout the world, galleries and museums such as the Kröller-Müller in the Netherlands and Bauhaus are large influences as well.

Have you ever wanted to do something else with your life? There are times that I still contemplate becoming an architect as designing a building is a huge task but I might consider that more realistically when I start reaching the humanly perfect state with my designs, otherwise I’ll always want to go back to the drawing board and reshape a roof, window or even a tile. Other than that I’d like to learn how to play an instrument, get more involved in creating music of my own. Other times I feel a short lived life as a racecar driver would be an interesting approach as I already really enjoy driving fast but most of the time I’m quite satisfied with the career path I’ve chosen and laid out for myself as it allows me to put on many different hats, oversee every step of the process and really enjoy the final product.

A final word to our readers? Do it because you have a love for it, because shocking their senses makes you happy. Try to balance your workload though, work tends to consume our lives but there is fun to mix in with work, it keeps ideas fresh and work entertaining! Contact: www.beside.ca

01/2008 (1)



Column

5 Steps To Breathing Adobe AIR E

arly this year Adobe set the stage with their 1.0 release of the Adobe Integrated Runtime, or AIR for short. Adobe AIR is desktop evolution of the Flash Platform. By bringing Flash technology to native desktops, Adobe provides a new playing field for developers and designers. If you're unfamiliar with the term runtime then an easy comparison would be Java with its JRE (Java Runtime Environment), which is required to be installed to run and interpret Java code. The same is with AIR interpreting both JavaScript and ActionScript code, and running applications on our native desktop machines. AIR applications can be developed in either JavaScript or ActionScript, and even with a combination of the two; there is even PDF integration available in AIR. Getting into Adobe AIR can be slightly challenging since it's new. Here is some guidance you'll need if you're about to breath some AIR.

Download and Install Adobe AIR It should be noted that Adobe AIR is currently available for Windows, Mac, and Linux desktops. Adobe AIR for Windows and Mac OS X are at version 1.0.1, while the Linux version is in a pre-release state but is still worth playing with. Download and install AIR for your platform. Adobe AIR is available for download at http://get.adobe.com/air. Linux users can check out their pre-release download at http://labs.adobe.com/ downloads/air_linux.html.

pixel powers and pull of anything we think should work. We'll learn. Adobe has provided us a layer of infinite pixel control and (high-def) rich media. Get excited. Start at these places to see what's AIR applications are already out: • Adobe AIR Marketplace – http://adobe.com/exchange • RIApedia – http://riapedia.com

Pre-plan Your AIR Application Before your team should get into project specifics, there are some early technological questions every AIR project should answer up front. First, will your AIR app be developed in JavaScript, ActionScript, or a combination of the two? Will you use the Flex framework or not? How much screen space will the app require? Can the application be maximized? Will the application create and use a custom file-type? Do you plan to store local data? Will the application connect to the Internet?

“One important question for every AIR application is weather or not you should invest in the digital signing of your AIR application”.

Lots of questions arise about any AIR project since we're not stuck in a simple web page anymore. One important question for every Get Familiar with AIR Apps out There AIR application is weather or not you should invest in the digital Below are links for you to see what people are already doing with Adobe signing of your AIR application. When installing AIR applications, AIR. Checking out what other applications are doing is important. New users are prompted with a security note showing the authenticity of ideas are inspired by old ideas and reading documentation will only take the publisher (you) and any digital certificate issued to the company your mind so far. It is crucial to you, clients, and Adobe to not see long and its application. If you think a digital certificate with worth cycles of run-of-the-mill AIR apps. To get people to care about your adopting then you can plan to spend a couple hundred dollars per applications it must impact them in some way. By reviewing what's application. Application signing is not required to develop, deploy, available in the AIR realm, we can all learn and see what best methods or install any AIR application; it is only for user comfort and are used in software. Since the technology and market are both relatively company IT policies. fresh, there is room to grow and new exciting roads for web developers An AIR developer doesn't need to decide what platform to develop to take. for since the AIR runtime is multi-platform by default; nor do we need to worry about what web browser (or version) isused since AIR “Since the technology and market are both doesn't require a web browser, and even has a web browser built in for relatively fresh, there is room to grow and developers provided by WebKit (similar to Apple's Safari). new exciting roads for web developers to If you're interested in a book to learn what an RIA requires in take.” planning and execution, I suggest checking out a book I co-wrote, Advanced Flex Application Development, published by Friends of ED. In bringing people next generation desktop applications, Our book covers RIA (Flex) project preparation, development, and work developers must merge principles and ideas from the desktop flow points covered from the start of a real-world project. era with things learned from the Internet boom to hit a winning Advanced Flex Application Development: Building Rich Media X; combination. Since it's the 21st century we should harness our ISBN: 1590598962; http://laair.org/book 80

01/2008 (1)


Get Your Tools Together Are you ready to develop and deploy AIR applications? What software will you use to get your AIR apps done? The common choices are Adobe Flex Builder 3, Aptana IDE, standard Eclipse, even Adobe Dreamweaver or Flash CS3 can do the job. The CS3 suites can download a free extension/update which provides the power to develop and compile Adobe AIR applications with a couple clicks. If you don't have any of these commercial applications, you can check out a free Eclipse-based software suite called Aptana or the Flex and AIR SDKs, which are free for download and offer compilers. Not only will you need an IDE or coding environment, but you will need a debugger of sorts. Flex Builder 3 comes with a visual debugger and the free SDK has a debugger as well. While I have yet to see third party debuggers for Flex/AIR, besides X-Ray by John Grden, I am optimistic that at least one crew will step up and show the AIR community something they never knew was missing so much – better debugging features.

“...the Flash platform is fun and amazing since there is immediate feedback and satisfaction...” For those in the education sector, students and teachers are offered free copies of Flex Builder 3 Pro, a $699 value. Check out http://adobe.com/ flex for more details and pricing information about Flex Builder or to download the Flex SDK. To download the AIR SDK, visit http://www.adobe.com/products/air/ tools for download and information.

Learn, Develop, and Learn Some More The web is still evolving and AIR takes us on a road parallel with our World Wide Web sites. Our desktop will fill the holes that sites leave open. New apps for a new world requires new knowledge. Learning and developing AIR applications gets easier and easier. Start with simple uses, simple interfaces, and simple goals. Looking forward, even with larger AIR projects development should be easy since everyone should look into frameworks like Flex or EXT-JS, making application develop a lot less painful. While there is a learning curve for every technology, I think the Flash platform is fun and amazing since there is immediate feedback and satisfaction. Refine your skills by investing time in reading related blogs, books, attending courses or events, attend a local user group meeting, download podcasts, videos, or anything that gives you insight or can spark good ideas. Nature has a history of telling us that if we don't adapt, we fail. Even Flash wasn't something that was always on the Internet but is everywhere now and most of us have adapted well to this shift; time for another shift. It is only natural for developers to expand and refine. Programmers are artists too, but every artist needs to get a little dirty otherwise they're not exploring the true potential of themselves and their platform. Read, listen, learn, write, chat... do all of these things and you will start to naturally breathe Adobe AIR.

Chris Charlton

Chris Charlton has tons of community involvement: authorized Adobe Flex Champion, Adobe User Group Manager for LA AIR, helps run LA Drupal, is co-author of the book Advanced Flex Application Development: Building RichMediaX, and teaches at the Rich Media Institute. • • • •

AIR Developer Center – http://adobe.com/devnet/air Flex Developer Center – http://adobe.com/devnet/flex ActionScript Developer Center – http://adobe.com/devnet/ actionscript LA AIR – my Adobe AIR user group in Los Angeles, member blogs available at http://laair.org

01/2008 (1)


Coming UP

Next issue available in October! in the next issue: You’ve already read everything? Don’t worry! Next issue of FFD will be available in three months. In 2/2008, the best practical and technical articles for all Flash and Flex developers.

Building modular Flash applications using XiLib for haXe An article on Adobe AIR Paper on advanced techniques and the use of Adobe Flex 3.0 On the CD Useful and commercial applications Penetration of most popular Flash tools A video tutorial

The current information on the magazine contents can be found on www.ffdmag.com




Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.