Marmalade SDK Mobile Game Development Essentials - Sean Scaplehorn - E-Book

Marmalade SDK Mobile Game Development Essentials E-Book

Sean Scaplehorn

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Modern mobile devices are capable of supporting video games of amazing quality but there are so many different devices and platforms how can you support them all? The answer is to use the Marmalade SDK to write your code once and deploy it to all popular mobile platforms at the touch of a button.Marmalade SDK Mobile Game Development Essentials will provide you with everything you need to know to transfer your existing C++ videogame programming knowledge to mobile devices. From graphics and sound to input methods and actual deployment to device, this book covers the lot.Learn how to make use of keys, touch screen and accelerometer inputs for controlling your game.Take the pain out of supporting a varied range of target devices, both across multiple platforms and multiple specifications.Step by step from "Hello World" to a complete game, this book will show how to use the Marmalade SDK to develop games for mobile devices.Learn how to make dazzling 2D and 3D games complete with fully animated characters, music and sound effects that can be deployed to all the leading mobile platforms, whilst ensuring it can run on a wide range of possible devices, from low specification to high end.If you want to join the exciting world of mobile videogames then Learning Mobile Game Development with Marmalade will show you how to do so, fast!

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 484

Veröffentlichungsjahr: 2012

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Marmalade SDK Mobile Game Development Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Started with Marmalade
Installing the Marmalade SDK
Installing a development environment
Choosing your Marmalade license type
Downloading and installing Marmalade
Using the Marmalade Configuration Utility
Managing your Marmalade account and licenses
Viewing an overview of your account
Updating your profile information
Managing your licenses
Managing your user list
Creating a Marmalade project
Creating the "Hello World" project
The MKB file for the "Hello World" project
The source file for the "Hello World" project
Building the "Hello World" project
The build directory
The data directory
The app.config.txt file
The app.icf file
Building and running in the Windows simulator
Deploying a Marmalade project
Compiling the "Hello World" project for the ARM CPU
Deploying the "Hello World" project
Installing on Android devices

Installing on iOS devices
Installing on BlackBerry QNX devices
Installing on Bada devices
Summary
2. Resource Management and 2D Graphics Rendering
The Marmalade ITX file format
The CIwManaged class
Instantiating a class with the class factory
Parsing a class
Serializing a class
Resolving a class
The Marmalade resource manager
Adding IwResManager to a project
Specifying resources with a GROUP file
Loading groups and accessing resources
The CIwResource class
GROUP file serialization
Resource handlers
Graphics APIs provided by the Marmalade SDK
The s3eSurface API
The IwGL API and OpenGL ES
The Iw2D API
The IwGx API
Using IwGx to render 2D graphics
IwGx initialization and termination
Rendering a polygon
Materials and textures
Creating materials in code
Creating materials using an MTL file
Vertex streams
Color streams
UV streams
Drawing a polygon
Displaying the rendered image
Example code
The ITX project
The Graphics2D project
The Skiing project
The GameObject class
The ModeManager and Mode classes
Summary
3. User Input
Detecting key input
Initialization and update of key information
Detecting key state
Detecting key state changes using polling
Detecting key state changes using callbacks
Detecting character code input
Detecting character code input using polling
Detecting character code input using callbacks
Inputting strings
Detecting touch screen and pointer input
Determining available pointer functionality
Determining the type of pointer input
Determining the type of stylus input
Updating current pointer input status
Detecting single touch input
Detecting single touch input using polling
Detecting single touch input using callbacks
Detecting multi-touch input
Detecting multi-touch input using polling
Multi-touch input using callbacks
Recognizing gesture inputs
Detecting a swipe gesture
Detecting a pinch gesture
Detecting accelerometer input
Starting and stopping accelerometer input
Reading accelerometer input
Smoothing accelerometer input
Testing accelerometer input on the Windows simulator
Example code
The Gesture project
The Slide project
The Skiing project
Player rotation
The ModeTitle and ModeGameOver classes
The Camera class
The Input Manager classes
The SkierController class
Summary
4. 3D Graphics Rendering
A quick 3D graphics primer
Describing a 3D model
Specifying a model's vertex stream
Specifying a model's index stream
Specifying a model's color, UV, and normal streams
Performing 3D to 2D projection
Understanding matrices for 3D graphics
Converting between coordinate systems
Clipping planes
Lighting
Emissive lighting
Ambient lighting
Diffuse lighting
Specular lighting
Using IwGx to render 3D graphics
Preparing IwGx for 3D rendering
Setting lighting information
Model data for the cube
The view matrix
The model matrix
Rendering the model
Using a 3D modeling package to create model data
The Marmalade 3D exporter plugins
Installing the plugins
Exporting a model
The Blender plugin
Installing Blender and the exporter plugin
Exporting a model
The Marmalade 3D model datafile formats
The GROUP file
The MTL file
The GEO file
Loading and rendering an exported 3D model
Adding the IwGraphics API to a project
Loading and accessing an exported 3D model
Rendering an exported 3D model
Releasing 3D model data
Example code
The Cube project
The Cube2 project
The Skiing project
Migration to 3D
Addition of a collision detection system
Summary
5. Animating 3D Graphics
A quick 3D animation primer
Animating with model matrices
Animating by translation
Animating by rotation
Rotation using Euler angles
Rotation using axis-angle pairs
Rotation using quaternions
Animating by scaling
3D model animation
Using morph targets
Using boned animations
Using a 3D modeling package to create animation data
Exporting animations using the Marmalade 3D exporter plugins
Exporting animations using the Blender plugin
The Marmalade 3D animation file formats
The SKEL file
The SKIN file
The ANIM file
Loading and rendering an exported 3D animation
Adding the IwAnim API to a project
Loading and accessing a 3D animation
Playing back a 3D animation
Rendering a 3D animation
Exploring 3D animation further
Playing an animation backwards
Blending between animations
Detecting animation playback events
Optimizing animation playback
Playing sub-animations
Offset animations
Obtaining bone positions and rotations
Example code
The Flag project
The Skiing project
New gameplay features
Animations added
Summary
6. Implementing Fonts, User Interfaces, and Localization
Implementing fonts
Adding the IwGxFont API to a project
Creating a font resource
The GXFONT file format
Loading and accessing font resources
Drawing text using a font resource
Drawing text on screen
Text wrapping and justification
Changing font size at runtime
Optimizing drawing by preparing text
Implementing user interfaces
The IwUI API
The IwNUI API
Implementing our own user interface solution
Using a generic approach
Making good use of class inheritance
Implementing a data-driven system
Responding to user input events
Screen resolution and orientation
Adding template functionality
Localizing your project
Creating a text spreadsheet
Getting the text into the game
Comma-separated values files
Processing using a Python script
Selecting the correct language to use at runtime
Example code
The Font project
The UI project
The Skiing project
Summary
7. Adding Sound and Video
Multimedia support in Marmalade
The s3eAudio API
Starting audio playback
Pausing, resuming, and stopping playback
Changing volume
Other audio queries
End of track notification
The s3eSound API
Starting sound playback
Pausing, resuming, and stopping playback
Global sound settings
Sound notifications
The SoundEngine module
Adding the SoundEngine module to a project
Loading and accessing sound resources
Playing, stopping, and altering sound parameters
The s3eVideo API
Starting video playback
Determining video codec support
Pausing, resuming, and stopping video playback
End of video notification
Other video queries
Example code
The Sound project
The Video project
The Skiing project
Summary
8. Supporting a Wide Range of Devices
Accommodating a wide range of device types
Dealing with different screen resolutions
Using different resources for different screen resolutions
Checking device capabilities
Configuring your game using ICF file settings
Built-in ICF settings
Defining new ICF settings
Accessing ICF settings in code
Limiting ICF settings by platform and device
Creating multiple resource sets
Using build styles
Adding extra resource directories
Supported build style platforms
Specifying which build style to use
Using resource templates
Defining material templates
Defining image templates
Defining model templates
Defining animation templates
Defining GROUP file templates
Producing binary versions of resources
Compressing resources using the Derbh archiver
Creating a Derbh archive
Using a Derbh archive in code
The automatic Derbh method
Creating different deployment types
Specifying icons, application names, and other details
Specifying asset lists
Creating and using deployment types
Example code
The build styles project
The Skiing project
Summary
9. Adding Social Media and Other Online Services
Launching a web page in the device browser
Integrating with social media
Using Facebook
Creating a Facebook app
Creating a Facebook test user
Adding the s3eFacebook API to a Marmalade project
Checking for s3eFacebook support
Initialization and termination
Logging in and out of Facebook
Posting a message to a user's wall
Further s3eFacebook features
Using Twitter
Connecting to other types of online services
Supporting social gaming networks
Using Apple's Game Center
Using Scoreloop
Supporting in-app purchases
Adding in-app purchasing for iOS devices
Adding in-app purchasing for Android devices
Using advertising
Implementing iAd support for iOS devices
Using other advertising solutions
Example code
The Facebook project
The Skiing project
Summary
10. Extending Marmalade with the Extensions Development Kit (EDK)
Why is the EDK necessary?
Creating an extension for gyroscope input
Declaring the extension API
Making an extension for Windows
Creating a Windows extension
Implementing a Windows extension
Building a Windows extension
Making an Android extension
Installing the required software for Android development
Creating an Android extension
Implementing an Android extension
Building an Android extension
Making an iOS extension
Installing the required software for iOS development
Creating an iOS extension
Implementing an iOS extension
Building an iOS extension
Using the Gyroscope extension
Example code
The Gyroscope project
The GyroTest project
The Skiing project
Summary
Index

Marmalade SDK Mobile Game Development Essentials

Marmalade SDK Mobile Game Development Essentials

Copyright © 2012 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: November 2012

Production Reference: 1051112

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK

ISBN 978-1-84969-336-3

www.packtpub.com

Cover Image by Neha Rajappan (<[email protected]>)

Credits

Author

Sean Scaplehorn

Reviewers

Joshua Bycer

Tim Closs

Marc Evans

Jern-Kuan Leong

Ronald Tan Heng Neng

Francis Styck

Acquisition Editor

Kartikey Pandey

Lead Technical Editor

Dayan Hyames

Technical Editor

Charmaine Pereira

Copy Editors

Aditya Nair

Insiya Morbiwala

Project Coordinator

Amey Sawant

Proofreader

Maria Gould

Indexer

Tejal Soni

Graphics

Valentina D'silva

Production Coordinator

Prachali Bhiwandkar

Cover Work

Prachali Bhiwandkar

About the Author

Sean Scaplehorn is a programmer with 15 years of experience in the videogames industry work on projects for both console and mobile devices. He has worked on games published by companies including Sony, Electronic Arts, Konami, Square Enix and Namco.

Sean got his first home computer still at primary school which kickstarted his interest in programming.After learning to code from typing in listings printed in computer magazines he went on to write his own games shared with his school friends.He knew then that writing games was what he wanted to do when he grew up.

However, on leaving university, Sean spent a couple of years writingsoftware for printing che books.When he could stand it no longer he made the leap into videogames development and hasn't looked back.

He worked at Ideaworks3D, the company behind the Marmalade SDK, for four years.In this time he saw the Marmalade SDK evolve from in-house technology to being a product in its own right, when it was launched as the Airplay SDK.

Sean now works from his home in the South of England as a freelance game coder.

I would like to thank the following people for their help and support writing this book.To my wife Sandra and daughter Kara for their patience and understanding Daddy "wrote his book" and to Marc Evans, a longtime friend and colleague, for his invaluable feedback on my writing.

I would also like to thank Simon Pick for giving an eager young man the best first job in the games industry he could have wished for and Tim Closs, CTO of Marmalade, for kindly taking the time to review this book during its development to ensure its accuracy.

About the Reviewers

Joshua Bycer is a game industry analyst with over 7 years of experience examining game design and the trends of the industry. He has been published locally on game sites Gamasutra and QuarterToThree, and internationally in Igromania Magazine. He has maintained the blog site chronicgamedesigner.blogspot.com since 2007 and is in the process of setting up his new site game-wisdom.com

His goal is to expand critical writing on the industry to better examine future trends and raise the standard for critical analysis.

Tim Closs has over 20 years' experience of commercial software development, and joined Marmalade in 2004. As CTO, Tim has lead the creation and productization of the Marmalade SDK, and continues to drive the company's technology and product strategies. Tim holds a Mathematics degree and Theoretical Physics postgraduate diploma from Cambridge University.

Marc Evans has been developing software almost as long as he has been playing games, and is currently involved in improving the content creation experience for the artists and designers of major console games.

Jern-Kuan Leong has been interested in programming ever since he started playing computer games on his 286s. He spent career in enterprise software development, and quickly jumped into the games industry when the opportunity came. He has worked with LucasArts for years and more recently with NVIDIA. He continues to explore the joy of game programming and design to this day.

Ronald Tan Heng Neng has worked at Ubisoft, IBM and is currently the producer at 12 Gigs, Inc. (www.12gigs.com), a cross-platform social mobile casino games network in San Francisco Bay Area, with hit titles on Facebook, iOS, Android, and Amazon.

Since obtaining his BSc (Hons) in Business Information Technology at Birmingham City University (United Kingdom), Ronald has garnered more than a decade of professional program/project management experience. This valuable experience also led him back to his passion in games, with a focus on games production and execution. Ronald also holds the highly soughtafter Project Management Professional (PMP)® and Certified IT Project Manager (CITPM) certifications.

In his spare time Ronald enjoys reading, traveling, developing small games and blogging occasionally on topics he's passionate about at http://ronald-tan.com.

Francis Styck has been developing games since his college days at UNLV pursuing an Engineering degree in the 1980s when games were written in Assembly language on the Atari 800 and Commodore 64.He continued with his education at UNLV and graduated with an MBA in 2001.Today he is still writing games but now uses the power of C++, Marmalade and cocos2d-x to support many platforms and devices.You can stay in touch with Francis using LinkedIn at http://www.linkedin.com/in/styck.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

The modern mobile device is an immensely powerful piece of equipment. Technology has advanced to such an extent that the current generation of cell phones and tablets are able to host games and applications that are both graphically and sonically impressive, and can even be compared to the titles available on home consoles and computers.

However, writing a game that will run on the plethora of available devices is difficult. There are a number of different platforms to support (for example, Android and iOS) and each platform can have devices that range considerably in terms of capabilities and processing power.

This is where the Marmalade SDK comes to the rescue! Marmalade is a cross-platform solution that allows us to write the source code for a video game once in C++ (a language that most video game developers will already be familiar with) and then deploy it to a number of different platforms, including iOS, Android, and BlackBerry PlayBook.

In this book we shall be learning how to use the Marmalade SDK to implement all the features demanded of a modern mobile video game.

What this book covers

Chapter 1, Getting Started with Marmalade: We start our journey into the world of the Marmalade SDK by learning how to install the SDK and build a simple "Hello World" application. We will then discover how to deploy and run the finished program to a number of different mobile platforms.

Chapter 2, Resource Management and 2D Graphics Rendering: Most video games are media-rich experiences packed full of superb graphics and stunning sound effects and music. In this chapter we will first look at how Marmalade makes it easy for us to load graphics and other resources into memory by using the built-in resource handling system. We will then discover how to render simple two-dimensional graphics on the screen.

Chapter 3, User Input: Our games will need to allow the user to provide input to control the action; so in this chapter we will be looking at how to respond to keypad, touch screen, and accelerometer inputs.

Chapter 4, 3D Graphics Rendering: Mobile devices now feature graphics processing units that enable them to easily render beautiful 3D graphics. After a brief overview of the basics of 3D rendering, we will then learn how to use Marmalade to render a spinning cube, first by generating the 3D model data in code and later by discovering how we can use a 3D modeling package to create and export a 3D model that can be loaded and drawn in a Marmalade application.

Chapter 5, Animating 3D Graphics: Building on the foundation of the previous chapter, we will then cover how to make our 3D graphics more interesting by making them animated.

Chapter 6, Implementing Fonts, User Interfaces, and Localization: Before a user can even play the first level of our game, they will first need to navigate its menu system. This chapter covers Marmalade's support for font rendering, the ways in which a user interface can be constructed, and finishes up with a look at how to localize a game so it can support multiple languages.

Chapter 7, Adding Sound and Video: Sound and music are both very important aspects of a video game and can make a game feel much more immersive and exciting, so learning how to add these elements to a game is the main aim of this chapter. Marmalade. also allows us to display full motion video clips, so we'll take a brief look at this too.

Chapter 8, Supporting a Wide Range of Devices: Different mobile devices have different capabilities and can also vary in terms of both main processor and graphics rendering power. In this chapter we look at ways in which Marmalade helps us to support as wide a range of devices as possible by allowing our game to adapt to the hardware it is running on. We'll also look at using Marmalade's built-in support for compressing and decompressing files to reduce the size of our game's installation package.

Chapter 9, Adding Social Media and Other Online Services: Since most devices are now permanently connected to the Internet, this chapter explores some of the options available to us for adding online features to our games, from integration with Facebook to displaying adverts as a possible revenue stream.

Chapter 10, Extending Marmalade with the Extensions Development Kit (EDK): While the Marmalade SDK does a great job of standardizing most of the normal requirements of writing a videogame, such as displaying graphics or playing sounds, there sometimes comes the requirement to access a device feature that Marmalade does not support directly. This chapter shows how we can get access to the underlying SDK on Windows, iOS, and Android in order to access device features that we would otherwise not be able to.

What you need for this book

You will need the following in order to make full use of the content of this book:

An Internet-connected PC with at least 1GB RAM running Windows XP Service Pack 2, Vista, or Windows 7Microsoft Visual Studio 2005/2008/2010 (C++ Express editions are suitable for this)A licensed copy of the Marmalade SDK

The first chapter will explain how to install a suitable version of Microsoft Visual Studio, and how to obtain Marmalade and purchase a license for it.

For making iOS deployments, you will also need to have signed up to Apple's iOS Developer Program; further details on this are also provided in the first chapter.

For the chapters on 3D graphics, it will also be beneficial if you have one of the supported modeling packages available. Marmalade provides direct support for Autodesk 3DS Max and Autodesk Maya, but a cheaper alternative is the open source Blender package.

Who this book is for

This book is intended to show you how to use Marmalade to implement the features required by a video game. It is not intended as a guide on how to write a video game, although there is sample code provided for a simple game that grows alongside each chapter of the book.

Since the Marmalade SDK is implemented in C++, you are expected to already be able to code in this programming language.

You are also expected to have a working knowledge of the concepts involved in both 2D and 3D graphics rendering. Brief overviews are provided in the relevant chapters, but they are intended merely as a refresher and to introduce terminology used in later parts of the book.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "The value used for platform is normally just the name of the operating system."

A block of code is set as follows:

{OS=IPHONE} Message="Hello iOS!" {} {OS=QNX} Message="Hello BlackBerry!" {}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

{OS=IPHONE} Message="Hello iOS!" {} {OS=QNX} Message="Hello BlackBerry!" {}

Any command-line input or output is written as follows:

C:\PlayBook> blackberry-debugtokenrequest -cskpass <password> -keystoresigtool.p12 -storepass <password> -deviceId 0x<device id> debugtoken.bar

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: ""

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Downloading the color images of this book

We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/3363OT_images.pdf

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Getting Started with Marmalade

In this chapter, we will first be learning how to get the Marmalade SDK set up for development. While Marmalade is available in both Windows and Mac versions, the Windows version is the most developed of the two and is what we shall be primarily covering in this book. By the end of this chapter, we will know how to do the following:

Set up a Windows PC for development using the Marmalade SDKCreate and build a "Hello World" projectDeploy and run the "Hello World" project on several mobile platforms

So without further ado, let's get started!

Installing the Marmalade SDK

The following sections will show you how to get your PC set up for development using Marmalade, from installing a suitable development environment through to licensing, downloading, and installing your copy of Marmalade.

Installing a development environment

Before we can start coding, we will first need to install a version of Microsoft's Visual C++, which is the Windows development environment that Marmalade uses. If you don't already have a version installed, you can download a copy for free. At the time of writing, the Express 2012 version had just been released but the most recent, free version directly supported by Marmalade was still Visual C++ 2010 Express, which can be downloaded from the following URL:

http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express

Follow the instructions on this web page to download and install the product.

Note

For the Apple Mac version of Marmalade, the supported development environment is Xcode, which is available as a free download from the Mac App Store. In this book, we will be assuming that the Windows version of Marmalade will be used, unless specifically stated otherwise.

Choosing your Marmalade license type

With a suitable development environment in place, we can now get on to downloading Marmalade itself. First, you need to head over to the Marmalade website using the following URL:

http://www.madewithmarmalade.com

At the top of the website are two buttons labeled Buy and Free Trial. Click on one of these (it doesn't matter which, as they both go to the same place!) and you'll see a page explaining the licensing options, which are also described in the following table:

License type

Description

Evaluation

This is free to use but is time limited (currently 45 days), and while you can deploy it to all supported platforms, you are not allowed to distribute the applications built with this version.

Community

This is the cheapest way of getting started with Marmalade, but you are limited to only being able to release it on iOS and Android, and your application will also feature a Marmalade splash screen on startup.

Indie

This version removes the limitations of the basic license, with no splash screen and the ability to target any supported platform.

Professional

This version adds dedicated support from Marmalade should you face any issues during development, and provides early access to the new versions of Marmalade.

When you have chosen the license level, you will first need to register with the Marmalade website by providing an e-mail address and password.

Note

The e-mail address you register will be linked to your license and will be used to activate it later. Make sure you use a valid e-mail address when registering.

Once you are registered, you will be taken to a web page where you can choose the level of license you require. After confirming payment, you will be sent an e-mail that allows you to activate your license and download the Marmalade installer.

Downloading and installing Marmalade

Now that you have a valid license, head back to the Marmalade website using the same URL we used earlier.

If you are not already logged on to the website, do so using the Login link at the top-right corner of the web page.Click on the Download button, and you will be taken to a page where you can download both the most recent and previous releases of the Marmalade installer. Click on the button for the version you require, to start downloading it. Once the download is complete, run the installer and follow the instructions. The installer will first ask you to accept the End User License Agreement by selecting a radio button, and will then ask for an installation location.Next, enter the file location you want to install to. The default installation directory drops the minor revision number (so version 6.1.1 will be installed into a subdirectory called 6.1). You may want to add the minor revision number back in, to make it easier to have multiple versions of Marmalade installed at the same time.Once the installer has finished copying the files to your hard drive, it will then display the Marmalade Configuration Utility, which is described in greater detail in the next section. Once the Configuration Utility has been closed, the installer will then offer you the option of launching some useful resources, such as the SDK documentation, before it exits.

Note

It is possible to have more than one version of the Marmalade SDK installed at a time and switch between versions as you need, hence the advice regarding the installation directory. This becomes very useful when device-specific bugs are fixed in a new version of Marmalade, but you still need to support an older project that requires a different version of Marmalade.

Using the Marmalade Configuration Utility

The Marmalade Configuration Utility window appears at the end of the installation process, but it can also be launched from its shortcut icon:

Note

When launching the Marmalade Configuration Utility on Windows Vista or Windows 7, you should right-click on the icon and select the Run as administrator option, otherwise any changes that you make might not be applied.

The most important element is the License Information box. Below this is a button labeled Activate License... that allows you to activate your Marmalade installation. Follow these steps to get activated:

Click on the Activate License... button to display a dialog box that asks you to enter the e-mail address and password you used when obtaining your license.The dialog box also has a drop-down box labeled Machine ID (Ethernet MAC address), which you should make sure is set to the MAC address of an Ethernet port that will always be present on your computer. Normally you won't need to change this.Click on the OK button to connect to the Marmalade licensing server. You will be asked to select the license you want to install. (Normally there will only be a single option available.) Do so and click on OK.A summary of the End User License Agreement (EULA), appropriate to the type of license you are using, will be displayed, so click on OK to accept it. A reference to the full EULA is also provided in the dialog box.You should now see a message confirming successful license installation. At this point Marmalade is ready to go!

Before we finish here though, let's look at the other available options. The first is labeled Marmalade System (S3E) Base and consists of a drop-down box that allows you to select the version of the Marmalade SDK you want to use, if you have more than one installed of course!

Note

S3E is short for Segundo Embedded Execution Environment and this is the lowest layer of the Marmalade SDK. This naming convention was adopted by the SDK during its early days of development, and it remains to this day. As you will see later in this book, there are a great many APIs that are prefixed with this name.

The Default Build Environment lets you choose which development environment you wish to use, assuming you have more than one supported version of Visual C++ installed.

The drop-down box labeled RVCT ARM Compiler allows you to change the compiler that will be used when making a device build. (Most mobile devices contain an ARM CPU, so we must compile our code for this processor type.) Marmalade ships with the GCC compiler and uses this by default, but it can also make use of the RVCT C++ compiler from ARM, which is an additional purchase and can produce better optimized code. We normally do not need to change this setting and can leave it on the first option labeled Do not use RVCT.

The Advanced Options... button provides access to a more verbose project-building option and also some experimental parts of the SDK. You will not normally need to make any changes here.

Managing your Marmalade account and licenses

Before we get on to doing some actual coding, it is worth mentioning how you can manage your Marmalade license and account. If you head back to the Marmalade website and log on, you'll notice a link at the top-right corner of the site labeled My Account.

Hover your mouse pointer over this link, and a menu of options that allow you to change your account details and license usage will appear. The following sections provide further information on each of these options.

Viewing an overview of your account

The menu option called Overview takes you to a page where you can see your personal details along with a summary of the number of licenses and users you have set up under your account. From this screen, there are buttons that allow you to update your profile, modify registered user information, buy new licenses, and manage existing ones.

Updating your profile information

Clicking the Profile option in the My Account menu or clicking on the Update Profile Information button on the profile overview screen will display a page that allows you to alter information such as your name, contact information, address, and account login password. There is also a checkbox that allows you to sign up for e-mail news updates from Marmalade.

Managing your licenses

Clicking the Licenses link in the My Account menu or clicking on the button labeled Manage on the overview screen will take you to a page where you can upgrade the level of your license or buy further licenses for new team members.

The Manage Licenses section at the bottom of this page shows all the currently active licenses in your account, and also allows you to release a license that is currently in use so that it can be transferred to another computer.

Releasing a license is useful if you need to work on a different computer for some reason, or if you have a new development computer that you wish to transfer your license to. You can release a license as often as you like, but a single license can only be used on a single computer at a time.

Managing your user list

If you are working in a team then you will obviously need more than one Marmalade license, but you also need to manage who has access to those licenses. Clicking on the Users option in the My Account menu or clicking on the Manage Users button on the overview page allows you to do this.

This page shows a list of all the users assigned to your account, and also has an Invite Users section that allows you to add new users to your account. Enter their e-mail addresses in the boxes provided, and click the Send invite button to send them a mail telling them how to activate their own Marmalade account.

Creating a Marmalade project

With Marmalade installed, we can now get down to doing some coding, and what better place to start than with the classic example of a "Hello World" program.

Creating the "Hello World" project

To begin a new project, we must first create an MKB file, which is Marmalade's own project file format. We use MKB files to specify all the source files, libraries, and build options needed to build our project.

The MKB file is actually used to generate a Visual C++ project file, but whenever we want to add or remove a source file to our project, we must do so by editing the MKB file and regenerating the Visual C++ project file from it using Marmalade's make file builder script, which we'll be looking at in just a moment.

In addition to source files, the MKB file also allows you to list all the other datafiles and resource files that your application will need in order to run, as this information will be needed when it comes to deploying your application on different mobile platforms.

Marmalade does come with a small tool called the LaunchPad, which can be used to create a new project, but in the interest of learning how a Marmalade project is put together, we will go about creating everything from scratch instead.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

The MKB file for the "Hello World" project

Let's make a start on our "Hello World" project. Create a new directory to hold the project files, and then create a file called Hello.mkb in this directory and enter the following into it:

# # Main MKB file for Hello project # # Modules used by this project subprojects { iwgx } # The files that make up the project (source, data etc.) files { [SourceCode] (source) Main.cpp } # Settings to configure the deployment process deployments { name="Hello" caption="Hello World" }

The first section of Hello.mkb is the subprojects section, which lists all the additional code modules used by our application. In this instance, a code module is a library that can be added to our project either as a group of C or C++ source files or, alternatively, as pre-compiled, linkable object files accompanying header files. In the previous example, there is just one, iwgx, which is the Marmalade code module responsible for rendering graphics.

All the higher level modules within Marmalade are referenced in this manner, and you can also use this system to create your own modules to enable code re-use across projects. To create a subproject module we use an MKF file, which amounts to a little more than an MKB file with a different file extension! When we add an entry to the subprojects list, the Marmalade makefile builder script will search for a suitable MKF file that describes each subproject. We'll see detailed examples of how to do this later in the book.

The next section is labeled files, and this is where we list all the source code files for our project. It is possible to split your source files up into different directories. To make it easy, you simply put the directory name in brackets ((source) in our example) and then list all the source files in the directory below.

It is also possible to group the related files together into subsections, which we do using square brackets ([SourceCode] in our example). Any source files below this will be added to that section and will then appear in a separate folder in the Visual C++ Solution Explorer. There is no need for the directory and group names to match, and indeed you can have more than one directory in a group if you so wish.

Finally we have the deployments section, which is where various settings are made that control the process of deploying our application to different device types.

In our example we are making two settings. The name setting provides the filename of our final executable and is also used in file and directory names created for us by Marmalade, while caption sets the name that will appear under the application's icon when installed on a device.

Both the aforementioned settings are examples of general settings that apply across all device types, but there are also a great many other settings available, which are specific to particular platforms, such as iOS or Android. A full list of these can be found in the Marmalade Documentation help file that is installed as part of the Marmalade SDK, and we'll also be looking at this in Chapter 8, Supporting a Wide Range of Devices, of this book along with the additional sections of the MKB file that have not yet been shown for this example.

The use of whitespace in the MKB file is pretty much up to your own personal preference. Though most of the Marmalade examples tend to indent entries within blocks, tabs or spaces can also be used.

Comments can also be added using the hash (#) character. Everything after the hash character till the end of the current line is then considered a comment.

The source file for the "Hello World" project

We may now use the MKB file for our project but we still can't do anything with it yet, as we've told Marmalade that there is a source file called Main.cpp, which doesn't exist yet. If we were to try and use the MKB file to build the project, we would get an error reported about this missing file, so let's create it.

You will recall that we said that our Main.cpp file would reside in a directory called source in the MKB file, so first create this new subdirectory in the project directory. Now, create a file called Main.cpp in the source directory and enter the following into it:

//--------------------------------------------------------- // Learning Mobile Game Development with Marmalade // Chapter 1 - Hello //--------------------------------------------------------- // Marmalade SDK includes #include "IwGx.h" #include "s3eConfig.h" #include "s3eDevice.h" //--------------------------------------------------------- // Main entry point //--------------------------------------------------------- int main() { // Initialise Marmalade modules IwGxInit(); // Set a default message, then check the ICF file to see if // a proper message has been specified char lMessage[S3E_CONFIG_STRING_MAX] = "Hello!"; s3eConfigGetString("APP", "Message", lMessage); // Set screen clear colour to black IwGxSetColClear(0, 0, 0, 255); // Draw text at double default size IwGxPrintSetScale(2); // Loop until we receive a quit message while (!s3eDeviceCheckQuitRequest()) { // Allow device to process its internal events s3eDeviceYield(0); // Clear the screen IwGxClear(); // Display our message on screen IwGxPrintString(10, 10, lMessage); // Flush IwGx draw buffers to screen IwGxFlush(); // Swap screen double buffer IwGxSwapBuffers(); } // Terminate Marmalade modules IwGxTerminate(); return 0; }

The code should be fairly simple to follow, but here is a quick breakdown.

First we reference the include files to allow us to use the parts of Marmalade that are necessary for our application, and then we create our main entry point function main. This is equivalent to the main() function in a standard C or C++ program, except that it takes no parameters as Marmalade does not accept command-line parameters. It's quite hard to specify command-line parameters on mobile devices, so there really isn't any need!

The first thing our application needs to do is initialize Marmalade's rendering module with a call toIwGxInit(), which will initialize the screen and set up standard behavior such as double buffering of the display.

Next we allocate a character buffer that will contain the message that we will be displaying on screen. We initialize it to a default message to make sure that there is something to be shown, but we then use a call to the s3eConfigGetString function to see if another message has been specified in the application's configuration file, which will be explained in more detail shortly.

The following call toIwGxSetColClear sets the desired screen background color to black, and then the call toIwGxPrintSetScale tells Marmalade to display text using its built-in font (which is quite small in size) at double its default resolution.

We now enter our main processing loop that will continue until the s3eDeviceCheckQuitRequest function returns a true value, which will happen if the user quits the application or if the device sends a quit request to the application for any reason.

The first line of our main loop is a call to s3eDeviceYield. This is a very important function that must be called at regular intervals during our application, to allow the device's OS to perform important tasks such as handling events—user inputs, incoming phone calls, and so on. Under most circumstances, a single call to this function in the main loop is sufficient.

The value passed to s3eDeviceYield is the maximum time (in milliseconds) that our application will yield to the OS for. Normally this value is set to zero, which yields long enough for the device to process the events, but will return control to our application as soon as all the events have been processed.

Next, we call IwGxClear to clear the screen and then useIwGxPrintString to display a message on the screen. IwGxFlushcauses the Marmalade engine to then process all our drawing requests to yield a final screen image that we can then display to the world usingIwGxSwapBuffers.

Finally, outside the main loop, we call IwGxTerminate to shut down Marmalade's rendering engine, and finally return zero to indicate that our application was completed without any errors.

Building the "Hello World" project

Now that we have set up our project and written the necessary code, it is finally time to build it. To do this open a Windows Explorer window and navigate to the folder containing Hello.mkb, and then just double-click on the file. You might see a brief flash of a command-prompt window, but after a short delay, Visual C++ should automatically start up with our project.

The act of double-clicking the MKB file actually causes the Marmalade makefile builder script to be executed. This is actually a script written in the Python language, which takes the MKB file and outputs a Visual C++ solution file and other required elements. A file association is automatically set up when installing Marmalade, so you can either double-click the file, or alternatively use the command prompt to create your project by changing to the project directory and entering Hello.mkb.

Before we go on to compile and run the project though, let's take a quick look at what Marmalade has created for us.

If you look in the project directory, there should be two new directories, which are described in the following sections.

The build directory

One of the directories created by the MKB file will be named build_hello_vcxx, where the "xx" part is dependent on the version of Visual C++ you are using.

This directory is Marmalade's working directory and is where all the object files created during building are stored. It will also be the home to our deployment packages when it comes to making device builds.

A Visual C++ solution file created from the MKB file also lives in this directory, and while you can use these files to switch between projects, you should never add files or change project settings using the options in the Visual C++ IDE.

Note

Always make project changes to the MKB file, then either close Visual C++ and double-click the MKB file to rebuild the solution, or alternatively perform a build inside Visual C++ to update the solution file with any changes. You should not make changes directly within the Visual C++ IDE as they will be lost the next time that the MKB file is used to recreate the project file.

The data directory

The MKB file will also generate a directory called data, and this is where Marmalade requires you to place any files that your application will need to load, such as images, 3D model data, sound files, and others. While you can create this directory and these files yourself, and it will not cause a problem, we might as well let the makefile builder do it for us!

If you take a look inside the data directory, you will see that the build process has also created two more files called app.icf and app.config.txt. These files are used to configure your application and are explained in the following sections.

The app.config.txt file

This file provides a list of all the application-specific settings that can be made in the app.icf file, along with a description of what each setting does and how it is used. There are two reasons for using this file:

Adding entries to this file keeps your project settings documented in a single place, so other coders can check this file to see what a particular setting does.Any setting contained in the app.icf file that is not documented in the app.config.txt file will generate a runtime error message when you try to specify or access it in your program.

Additionally, the app.config.txt file also requires you to define a group name for your settings, which is specified by using square brackets.

If you look at the s3eConfigGetString function call in the "Hello World" project code, you will see an example of this. This call is trying to access a setting called Message from the group APP, so let's add this into the app.config.txt file now, to stop any asserts from firing when running our application. Edit the file and add the following lines to the bottom of it:

[APP] Message The message we want to display on screen

The app.icf file

The app.icf file is used to add the configuration settings to your application, and as already stated these must be either documented in your project's app.config.txt file or must alternatively be defined in a similar file within one of the subprojects used by your application.

Adding a configuration setting is simply a matter of adding the setting name followed by an equals sign and then the value you wish to use. You must also ensure that you add the setting to the correct group, using the same square bracket notation used in the app.config.txt file. Here's an example:

[APP] Message="Hello World"

The settings made in the app.icf file can then be accessed in code using the s3eConfigGetInt and s3eConfigGetString functions.

The app.icf file also has another couple of tricks up its sleeve, as settings can also be made that are specific to a certain platform or even specific to an individual device. Here's how you achieve this:

To limit the application to a particular platform add the line {OS=platform}, and any settings following this will only apply to that device platform. The value used for platform is normally just the name of the operating system, for example, ANDROID, BADA, or WINDOWS, although it is worth mentioning that you should use IPHONE to refer to iPhones, iPods, and iPads! If in doubt, you can use a call to s3eDeviceGetString(S3E_DEVICE_OS) to discover the value that you need to use for a particular operating system.To limit the application to a particular device or devices, add the line {ID=platform id}, and any following settings will only be applied when run on the specified device. The platform value is the same as that used previously, while the id is an identifier for a particular device. The format of the id value depends on the operating system, but you can discover what value to use for a particular device by calling s3eDeviceGetString(S3E_DEVICE_ID). It is also possible to provide a comma-separated list of id values if you need the settings to apply to more than one device.

Note that both of these settings will continue to take effect until a new OS or ID value is specified. If you wish to return to applying all the settings globally, just add {} after your last OS- or ID-specific setting.

Tip

It is good practice to ensure that your OS- or ID-specific sections always terminate with {}, as not doing so can lead to a major head-scratching session when you deploy to device and find that some setting you have just changed doesn't appear to be taking effect.

To illustrate the use of {} , let's add some settings to the "Hello World" project app.icf file. Open the file and add the following lines to the bottom of it:

[APP] {OS=ANDROID} Message="Hello Android!" {} {OS=BADA} Message="Hello Bada!" {} {OS=IPHONE} Message="Hello iOS!" {} {OS=QNX} Message="Hello BlackBerry!" {} {OS=WINDOWS} Message="Hello Windows!" {}

You should be able to see from this that we have specified a different message string for each different platform type that we wish to support.

Building and running in the Windows simulator

Now it's time for us to see the "Hello World" project in action. It is just a simple matter of compiling the code in Visual C++ and running it.

To compile the code, simply select Build | Build Solution or press the F7 key. Visual C++ will compile and link the Main.cpp file.

Now we can execute the program. Select Debug | Start Debugging or simply press F5. The Marmalade Windows Simulator will be launched, which will in turn load and execute our program. The following image shows what the "Hello World" project should look like when run in the Windows Simulator:

You will notice that the Windows Simulator contains a number of menu options. These allow you to make the Windows Simulator run in as close a manner to any device you choose as possible. The best way to see what you can change is to explore the menu options yourself, but here are a few of the more useful things you can do:

Accelerometer: Testing accelerometer inputs on Windows would be impossible without Configuration | Accelerometer.... This brings up a dialog box that allows you to use the mouse to rotate a 3D image of a phone, to simulate the accelerometer input.OpenGL ES version: The Windows Simulator option Configuration | GL... allows you to emulate different versions of OpenGL ES, which makes it easy to see what your game may look like on different types of hardware. It also allows you to disable OpenGL ES support entirely, which will then force Marmalade to use its built-in software renderer.Screen resolution: Mobile devices have a wide range of supported screen resolutions, so Configuration | Surface... allows you to select any size for the screen that you desire.Emulation of device suspend and resume: It is easy to forget that the primary function of many devices is actually that of a telephone rather than of a gaming platform, which means your application could potentially be interrupted at any time by an incoming call. Marmalade takes care of most of the fiddly details of handling this automatically, but there may still be situations when you need to do something special under such circumstances. The Windows Simulator allows you to test whether your application responds correctly by way of Events | Simulate Suspend and Events | Simulate Resume.

Deploying a Marmalade project

We have now managed to create and run our first Marmalade application, but running it on Windows isn't our ultimate goal. The whole reason for the Marmalade SDK is to make it easy for us to develop our application once and then deploy it on a whole range of mobile device platforms.

Of course we might need to alter some of our assets, for example, because we are targeting a wide range of different screen resolutions and want our application to look its best at all times, the code itself should need no modification in order to run successfully.

To illustrate this, we will now take the "Hello World" project and get it running on a number of different mobile device platforms.

Compiling the "Hello World" project for the ARM CPU

Running our project in Windows meant we were compiling our code using the standard Visual C++ compiler and therefore generating Intel x86 code. However, it is a fact that the vast majority of mobile devices available today contain some version or other of the ARM processor, so the first thing we need to do is compile our code for ARM.

Luckily, Marmalade has made this incredibly easy for us. At the top of the Visual C++ window, you should see a drop-down box that defaults to a setting called (x86) Debug.

If you open the drop-down box, you will see several build types pre-configured for us, but the one we are interested in is the GCC (ARM) Release option. Select this and build the solution again (Build | Build Solution or press F7