0% found this document useful (0 votes)
54 views565 pages

Navigating The Playground SDK - Tim Mensch

Uploaded by

jfcarrb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views565 pages

Navigating The Playground SDK - Tim Mensch

Uploaded by

jfcarrb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 565

Navigating the Playground SDK™

A User and Reference Guide


For Playground SDK 4.0

by Tim Mensch
Navigating the Playground SDK™

Published by PlayFirst, Inc.


160 Spear St, Suite 1300
San Francisco, CA 94105

Copyright © 2007-2009 PlayFirst, Inc. All rights reserved.

PlayFirst and Playground SDK are trademarks of PlayFirst, Inc.

Microsoft®, ActiveX®, Internet Explorer®, Windows®, Windows Vista®, Developer Studio®,


Visual C++®, Visual Studio®, MSN®, and DirectX® are registered trademarks of Microsoft
Corporation in the United States and other countries.

Mac OS® is a registered trademark of Apple Computer, Inc.

America Online®, AOL.com®, and AOL® are registered trademarks of AOL LLC.

Macromedia®, Flash®, and Director® are registered trademarks of Macromedia, Inc.

This book is an independent publication and is not affiliated with, nor has it been authorized,
sponsored, or otherwise approved by Microsoft Corporation.

Book was generated using Doxygen and LATEX.

Cover photo by Gabriela Rojas.

Printed by http://LuLu.com.

Print Version 2.0


Contents

0.1 Playground SDK™ Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix


0.2 Playground SDK™ Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

I User’s Guide 1

1 Introduction 3
1.1 Welcome to the Playground SDK™! . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 What’s on the Playground? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 Getting Started 7
2.1 How to Play on the Playground . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 A First Example Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.3 Game Assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.4 The Game Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.5 Dealing With User Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.6 Why Modal Windows Are Your Friend . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.7 How to use Playground SDK™ features. . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.8 What is Lua? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.9 Lua Makes it Easy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.10 What About Speed? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.11 What are the pitfalls? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

3 Playground Fundamentals 25
3.1 Dynamic Casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2 RTTI in TWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.3 How to Share and Play Well With Others . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.4 Using shared_ptr (TClassRef) Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
ii CONTENTS

3.5 Managing Assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28


3.6 Common Mistakes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.7 Your Very Own shared_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.8 Implementation Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.9 About the Playground SDK™ Hiscore System . . . . . . . . . . . . . . . . . . . . . . 30
3.10 Initialize The System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.11 Connecting to a debug server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.12 Set Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.13 Logging Scores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.14 Logging Medals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.15 Viewing local scores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.16 Figuring out what score the user can submit . . . . . . . . . . . . . . . . . . . . . . . 32
3.17 Submitting a score and medals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.18 Switching to the global score view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.19 Hiscore FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.20 Writing Debug Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.21 Dynamic Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.22 Game Version Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

4 Beta Versions 39
4.1 How to Create Limited Builds for Beta Testers . . . . . . . . . . . . . . . . . . . . . . 39
4.2 Tracking Game Metrics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.3 Writing Status on Elapsed Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.4 FirstPeek Module Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

5 Lua 47
5.1 About Lua . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.2 Using Lua to Script Your Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
5.3 How do I get Lua data in my C++ code? . . . . . . . . . . . . . . . . . . . . . . . . . 55

6 Particle System 57
6.1 Particles in a Scripting Language? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

7 Localization and Web Versions 65


7.1 The String Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.2 Quick and Easy Web Games . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

Navigating the Playground SDK


CONTENTS iii

8 Game Footprint 69
8.1 Smaller is Better . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
8.2 Shrinking Your Game . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

9 Utilities 71
9.1 FirstStage: The Playground Resource Editor . . . . . . . . . . . . . . . . . . . . . . . 71
9.2 FluidFX 2.0: Interactive Particle System Editor . . . . . . . . . . . . . . . . . . . . . . 90
9.3 sidewalk: Command Line Animation Creation . . . . . . . . . . . . . . . . . . . . . . 92
9.4 Filmstrip: Creating and Editing Animations . . . . . . . . . . . . . . . . . . . . . . . 95
9.5 3dsconvert: Creating 3d Models For Playground . . . . . . . . . . . . . . . . . . . . . 104
9.6 Creating a Playground Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
9.7 axtool: Testing Your Game in a Browser . . . . . . . . . . . . . . . . . . . . . . . . . . 105
9.8 xml2anm: Convert XML to ANM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

10 Advanced Features 109


10.1 Playing With the Big Kids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
10.2 Deriving a Custom Sprite Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
10.3 Sending Custom Application Messages . . . . . . . . . . . . . . . . . . . . . . . . . . 111
10.4 Calling a Lua Function from C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
10.5 Substituting a Custom TModalWindow . . . . . . . . . . . . . . . . . . . . . . . . . . 113

II Reference 115

11 Windowing Reference 117


11.1 Windowing and Widget Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

12 Lua Reference 119


12.1 Lua-Related Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
12.2 Query Values for Current Configuration in Lua. . . . . . . . . . . . . . . . . . . . . . 124
12.3 GUI-Related Constants in Lua. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
12.4 Text and Window Alignment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
12.5 Defined Message Types in Lua. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
12.6 Animation Script Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
12.7 Lua Particle System Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
12.8 Lua GUI Command Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

13 Vertex Rendering Reference 155

Playground 4.0.17.1
iv CONTENTS

13.1 Vertex Support for Triangle Rendering . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

14 Font Reference 157


14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
14.2 Quadratic Bezier Curves . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
14.3 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
14.4 Vector Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
14.5 File Format Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
14.6 Font Rasterization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
14.7 Notes on Font Sizes and Line Height . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
14.8 Call for Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160

15 Class and File Reference 161


15.1 str Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
15.2 T2dParticle Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
15.3 T2dParticleRenderer Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
15.4 TAnimatedSprite Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
15.5 TAnimatedTexture Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
15.6 TAnimTask Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
15.7 TAsset Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
15.8 TAssetMap Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
15.9 TBegin2d Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
15.10 TBegin3d Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
15.11 TButton Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
15.12 TButton::Action Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
15.13 TButton::LuaAction Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
15.14 TClock Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
15.15 TColor Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
15.16 TColor32 Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
15.17 TDialog Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
15.18 TDrawSpec Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
15.19 TEncrypt Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
15.20 TEvent Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
15.21 TFile Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
15.22 TFlashHost Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
15.23 TGameState Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242

Navigating the Playground SDK


CONTENTS v

15.24 TGameStateHandler Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 247


15.25 TImage Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
15.26 TLayeredWindow Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
15.27 TLight Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
15.28 TLitVert Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
15.29 TLuaFunction Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
15.30 TLuaObjectWrapper Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
15.31 TLuaParticleSystem Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
15.32 TLuaTable Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
15.33 TMat3 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
15.34 TMat4 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
15.35 TMaterial Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
15.36 TMessage Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
15.37 TMessageListener Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
15.38 TModalWindow Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
15.39 TModel Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
15.40 TParamSet Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
15.41 TParticleFunction Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
15.42 TParticleMachineState Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 315
15.43 ParticleMember Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
15.44 TParticleRenderer Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
15.45 TParticleState Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
15.46 TPfHiscores Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
15.47 TPlatform Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
15.48 TPoint Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
15.49 TPrefs Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
15.50 TPrefsDB Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
15.51 TRandom Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
15.52 TRect Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
15.53 TRenderer Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
15.54 TScreen Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
15.55 TScript Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
15.56 TScriptCode Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
15.57 TSimpleHttp Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
15.58 TSlider Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404

Playground 4.0.17.1
vi CONTENTS

15.59 TSound Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409


15.60 TSoundCallBack Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
15.61 TSoundInstance Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
15.62 TSoundManager Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
15.63 TSpeex Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
15.64 TSprite Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
15.65 TStringTable Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
15.66 TTask Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
15.67 TTaskList Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
15.68 TText Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
15.69 TTextEdit Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
15.70 TTextGraphic Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
15.71 TTextSprite Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
15.72 TTexture Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
15.73 TTransformedLitVert Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
15.74 TURect Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
15.75 TVec2 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
15.76 TVec3 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
15.77 TVec4 Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
15.78 TVert Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
15.79 TVertexSet Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
15.80 TWindow Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
15.81 TWindowHoverHandler Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . 518
15.82 TWindowManager Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
15.83 TWindowSpider Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
15.84 TWindowStyle Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
15.85 TXmlNode Class Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
15.86 debug.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
15.87 pftypeinfo.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
15.88 pflibcore.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544

III Appendix 545

A Forward Declarations 547


A.1 forward.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547

Navigating the Playground SDK


CONTENTS vii

B Annotated Class Listing 549


B.1 Class List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549

Playground 4.0.17.1
0.1 Playground SDK™ Documentation ix

0.1 Playground SDK™ Documentation


Many people made this documentation possible. I would like to thank Jim Brooks who wrote most
of the high score documentation, the web game documentation, some of the utility documentation,
and probably other sections I’m forgetting. In this edition, Brad Elelman contributed the chapter
describing how the Playground font engine works. Also new in this edition, Robert Crane wrote
most of the utilities chapter, as he has owned the tool chain since he started working with PlayFirst.
Cover design is by Juan Botero. Maria Waters helped out with valuable typesetting advice.
Thanks also go to the members of the PlayFirst team who spent time proofreading and making
suggestions as to how to improve the documentation: Jim Brooks, Dan Chao, Peri Cumali, Joshua
Dudley, Brad Edelman, Teale Fristoe, Oliver Marsh, Drew McKinney, Solveig Pederson, Ryan Pfen-
ninger, Shannon Prickett, Reggie Seagraves, and Eric Snider.
And I would also like to thank my wife Deborah, who dusted off her technical editor hat and
practically rewrote parts of the user’s guide to help make it easier for people to understand.

0.2 Playground SDK™ Design


Tim Mensch is the Playground SDK™ lead at PlayFirst, and he provides much of the design direc-
tion, but he doesn’t work in a vacuum.
Brad Edelman, the CTO of PlayFirst, contributed the initial groundwork to Playground, including
its fast, flexible, and portable font renderer. Brad is the one who makes sure Tim is doing his best
work on the library, keeping him focused on the end user experience—both the experience of the
user of the game and that of the user of the library.
Jim Brooks has been an ever–willing first consumer of early library features, and has contributed
no small amount of code to the library as well. From the OGG file reader to the high score system
to many useful tweaks and hours of advice and consultation, the library wouldn’t be the same
without him.
Eric Snider is our resident early adopter of the Mac version of Playground SDK, always willing to
test out new Mac builds to make sure they function as expected. He brings years of game-writing
wisdom to the design and direction of Playground.
Reggie Seagraves spent a year and a half developing the Mac version of Playground, and now
David Parks is maintaining and updating the Mac code.
Oliver Marsh was on the front lines of early adoption of new Playground features, and he was in-
valuable in helping debug the library, as well as in consultation on the Playground SDK™ particle
system.
Thanks also go to the QA department at PlayFirst, led by Christopher Dunn, for helping us iron
out the problems in the Playground SDK™: Amy Belden, Peri Cumali, Valerie Gorchinski, Adam
Gourdin, Devin Grayson, Bryan Kiechle, Cesar Lemus, Drew McKinney. Earlier QA efforts on
Playground were led by Rebekah Cunningham.
Finally, thanks to the many external developers who have asked questions and provided feedback
on Playground, either in person or on the developer site at https://developer.playfirst.com.

Playground 4.0.17.1
x CONTENTS

Navigating the Playground SDK


Part I

User’s Guide
Chapter 1

Introduction

1.1 Welcome to the Playground SDK™!

The Playground SDK™ is designed to provide all of the core features you’ll need to create a pol-
ished, successful downloadable game while handling many of the distractions that would other-
wise slow you down. A game written in Playground will run on multiple platforms, including
Windows, Windows-ActiveX, and Mac OS X 10.4. Playground is an object-oriented C++ library
that relies on Lua for scripting support. Familiarity with Lua is helpful, but not a requirement,
since most of the game is written in C++. Like C++ itself, Playground exposes both low-level
and high-level functionality, giving you the ability to directly modify textures and map them on
polygons at the lowest level, and a game-centric GUI/windowing system at the highest level.
While the Playground team has its own ideas as to how Playground should be used, we’ve tried
not to overly restrict the number of development paradigms that make sense. For example, button
messages can be set up to run entirely in Lua, or you can ignore Lua and simply process button
messages in C++. Dialogs can easily be specified in a human-friendly format based on Lua, or they
can be completely constructed by hand. Some developers are using their own custom libraries to
do just about everything, handing only polygons to Playground to render, though in those cases
it’s often harder to guarantee cross-platform portability.
We’re also constantly working on the Playground SDK™ to improve it; if you have a suggestion,
idea, or complaint about the SDK, please let us know so that we can address it! Internally the code
has been written for easy modification, so we’re not afraid to add new features if they seem useful.
You can learn more about Playground and share your ideas with others at the developer web
site and forum at https://developer.playfirst.com. Between active discussions, important an-
nouncements, and the latest released version of the SDK, it’s a place any active Playground devel-
oper should visit frequently.
4 Introduction

1.2 What’s on the Playground?

1.2.1 Basic Features


Playground currently supports Windows XP and Windows Vista, both in stand-alone and ActiveX
modes; and Mac OS X 10.4 or newer. Most Playground games will continue to run on Windows
98, Windows 98SE, Windows ME, Windows 2000, and Mac OS 10.39, though now that official
support has been dropped, PlayFirst is no longer fixing corner-case bugs with semi-broken video
card drivers.
Development is currently supported on Windows platforms using Visual Studio 2005 (8.0) or Vi-
sual C++ 2005, and on Mac OS X using Xcode.
The Playground SDK™ provides basic GUI features via its TWindow (p. 496) system, which sup-
ports message passing, Lua dialog/screen layout files, buttons, scroll bars, text entry, and image
layering. The Lua script subsystem (p. 22) is integrated so as to be an optional component, though
most developers choose to take advantage of it.
Playground supports the reading and display of JPG and PNG files, the latter with optional trans-
parency. Animations are handled through an animated texture and sprite system. For finer
grained control, the TRenderer::DrawVertices() (p. 376) API exposes full 3d triangle rendering
with color, pre-lit, or pre-transformed-and-lit vertices, for those developers who have their own
graphics library and who want to take advantage of the portability that Playground offers. Trian-
gle rendering is also the most supported path to 3d game development at present. For sound play-
back, Playground supports the OGG/Vorbis sound format, a free format (no royalties required)
that produces better quality sound than MP3 at similar bit rates.

1.2.2 Design Goals


The Playground SDK™ has several important design goals:

1. Portable (this page) to multiple platforms (OpenGL/DirectX, Mac/Windows, potentially


others)
2. Small, to keep download size small.
3. Robust (opposite).
4. Complete (opposite).
5. Separable, so that features not needed by a client are not linked in.
6. Readable. The coding practices include readable design, judicious use of macros, comments
on any code whose purpose isn’t obvious, and class and member names that clearly indicate
functionality.

1.2.3 Portability Concerns


There is a list of Coding Standards on the developer web site that, if you follow it, will help
make your game completely and immediately portable to other platforms. The Coding Standards

Navigating the Playground SDK


1.2 What’s on the Playground? 5

page is a living document—developers are a creative bunch, and from time to time they come up
with new and interesting ways to write code that’s not portable. As that happens, we add new
standards. In addition, in order to ensure that the Playground SDK™ is portable, all platform-
specific functionality you should need resides in the library. If there’s anything missing, please
ask for it!
All APIs exposed by the SDK hide platform-specific complexity behind an abstraction that spec-
ifies the intent of the request rather than the specific platform feature you need. For example,
application configuration data should be managed by the library with no reference in the API to
application-specific information such as a path. The TFile (p. 233) file abstraction allows you to
read and write files with no knowledge of the local file-system topology.

1.2.4 On Making a Library Robust


There’s more to making a library robust than just expunging the bugs; the design needs to take
into account how the library is likely to be used, making it as easy as possible for the user to write
correct code. Any time we come across a point in SDK design where we feel the need to warn the
user about a potential pitfall, we try to step back and reevaluate the design to see if there is a way
we can eliminate the need for a warning by making an architecture change. Warnings remain in
the documentation only in instances where we decide that the additional flexibility is worth the
risk.
Designing a robust SDK also involves evaluating the entire process of writing a game, keeping
track of the places that bugs tend to develop, and then handling as many of those problem domains
as possible in the library. While we can’t offload your game logic, we can make sure your game will
run on any target architecture, that you have access to container classes that are well documented
and thoroughly tested, and that the problems you do face concern the game you’re writing and
not the environment.

1.2.5 When is a Library Complete?


The Playground SDK™ will probably always be growing and evolving; how can we have com-
pleteness as a design goal? Conceptually, we intend Playground to be able to create any typical
casual downloadable game. We hope to make available in Playground any feature that you would
need to create any current game.
As we extend Playground in the future, improvements will fall into one of three categories. We’ll
be refining the core library, extending the API and making Playground more robust. We will aug-
ment the core library judiciously, when new features would have broad utility or require hardware
support. And we will be creating more specialized features that exist in layers on top of the cur-
rent library. Since these specialized components will be helpful to some, but not all, developers,
the game developer will have the option whether to link them into their game. This keeps Play-
ground’s download footprint smaller for developers who don’t need the optional functionality.

Playground 4.0.17.1
6 Introduction

Navigating the Playground SDK


Chapter 2

Getting Started

2.1 How to Play on the Playground

The easiest way to get started with the Playground SDK™ is to start with the skeleton application,
modifying the window name and splash screen sequence as appropriate for your product. Most of
the substance of your application will live in, or be spawned from, a class derived from TWindow
(p. 496)—the skeleton application creates several TWindow-derived classes.
The TWindow base class provides the functionality you would expect of a hierarchical window
class: Add children, set a position, draw, send and respond to messages or events, and other
standard supporting members and interfaces. Generic messages can be handled using TWin-
dow::OnMessage() (p. 511); other events trigger specific On∗() calls: TWindow::OnChar() (p. 513),
TWindow::OnMouseDown() (p. 512), etc. Note that your window will only get keyboard events
if the window currently has focus; see TWindowManager::SetFocus() (p. 525).
Custom windows are created from Lua resource files using dynamic creation; since C++ doesn’t
support named dynamic creation natively, we’ve added some support macros to enable that func-
tionality. Here’s an example of what that looks like:

// The TGame window definition header C++


class TGame : public TWindow
{
PFTYPEDEF_DC(TGame,TWindow) // Add the dynamic creation functions
...
}

// In the .cpp file:


PFTYPEIMPL_DC(TGame) // Define the TGame dynamic creation functions

Among other things, these macros will declare a ClassId() function that will return the unique
class of the window type. To add a new window type, you register it by passing the ClassId() of
the window to TWindowManager::AddWindowType (p. 526). From main.cpp in the skeleton:

TWindowManager * wm = TWindowManager::GetInstance(); C++


wm->AddWindowType("GameWindow",TGame::ClassId());
8 Getting Started

This sequence allows you to specify the position and size of the game window in a Lua resource
file, which (minimally) looks something like this:

GameWindow Lua
{
x=20, y=20, w=600, h=600
}

In this file you would also define any buttons that are children of that window, or alternately any
background or status windows that are separate from the game window. The hierarchy can work
however you like—a bunch of sibling windows that sit exactly next to each other, a strict hierarchy,
or a hybrid. See Using TWindows (p. 20) for more information on deriving a class from TWindow.
A number of window types are defined for you by Playground, including buttons (TButton
(p. 202)), text (TText (p. 433)), editable text (TTextEdit (p. 440)), and bitmaps (TImage (p. 249)).
Look at the derived classes in the TWindow documentation to see a complete list.
Assets are loaded and managed by Playground in reference-counted containers. The T∗Ref classes
are the containers, e.g., a TTextureRef (p. 548) holds a TTexture (p. 463) that you acquire from
TTexture::Get() (p. 465). See Game Assets (p. 13) for more information.
See TTexture::Draw and TTexture::DrawSprite (p. 467) for ways to draw your texture on the
screen. These draw calls should only be called in your derived TWindow::Draw() (p. 503) func-
tion, in a TBegin2d (p. 200) block.
3d models and sounds are handled similarly to textures: A TSound (p. 409) is acquired with
TSound::Get() (p. 410) and stored in a TSoundRef, and a TModel (p. 304) is acquired using
TModel::Get() (p. 306) and is stored in a TModelRef. You can play a TSound (p. 409) with
TSound::Play() (p. 410). Drawing the TModel (p. 304) is done with TModel::Draw() (p. 305) after
setting up the model’s texture, matrices, and lighting. See the section in TRenderer (p. 370) on
3d-related functions for more information.

Navigating the Playground SDK


2.2 A First Example Program 9

2.2 A First Example Program

2.2.1 The Main Program: Part One


In this section I will walk you through a skeleton application that demonstrates some basic func-
tionality. First, a bit of sample code:

C++
void Main(TPlatform* pPlatform, const char* /*cmdLine*/ )
{
InitializeGameState();

// Set the application name


pPlatform->SetWindowTitle(pPlatform->GetStringTable()->GetString("windowtitle"));

TSettings::CreateSettings();
TSettings::GetInstance()->InitGameToSettings();

This code is from main.cpp in the skeleton project. The functions are straightforward: The window
title is the text that appears in the bar at the top of the window. The InitGameToSettings() call
loads the application’s saved settings and initializes the window to full screen or windowed mode,
depending on the user’s saved preferences.

pPlatform->SetCursor( TTexture::GetSimple("cursor/cursor"), TPoint(1,1) ); C++


pPlatform->SetCursor( TTexture::Get("cursor/thumb.png"), TPoint(12,2), true );

TWindowManager * wm = TWindowManager::GetInstance();
wm->AddWindowType("GameWindow",TGame::ClassId());
wm->AddWindowType("MainMenu",TMainMenu::ClassId());
wm->AddWindowType("OptionsWindow",TOptions::ClassId());
wm->AddWindowType("HiscoreWindow",THiscore::ClassId());
wm->AddWindowType("ChoosePlayerWindow",TChoosePlayer::ClassId());
wm->AddWindowType("CreditsWindow",TCredits::ClassId());
wm->AddWindowType("Swarm", TSwarm::ClassId());
wm->AddWindowType("ChessPiece", TChessPiece::ClassId());

Here we set up a custom cursor for the application. Then, for convenience, we grab a pointer to
the window manager. Then we register several window creation commands, which will allow us
to easily specify our custom windows later.

// Start the Lua GUI script; this script will never exit C++
// in a typical Playground application.
wm->GetScript()->RunScript("scripts/mainloop.lua");

This last call to TScript::RunScript() (p. 392) causes our Lua main loop to begin.

2.2.2 What’s a Window Creation Command?


The window creation commands mentioned above are simple classes that are overridden to create
the custom game window. By "custom game window", we mean the window in which you plan
to do all of the interesting stuff that makes your game fun—drawing sprites and/or 3d objects

Playground 4.0.17.1
10 Getting Started

that dance around in response to user interaction. You can have more than one of these window
classes in your application, and you can even specify that several coexist on the same screen—but
in order for the screen building code to know how to create your custom window, your window
needs to have dynamic creation (p. 25) enabled.
First, in the class definition:

class TGame : public TWindow C++


{
PFTYPEDEF_DC(TGame,TWindow)

Then, in the implementation file:

PFTYPEIMPL_DC(TGame); C++

Pretty simple. If something needs to happen after the window has been created, you can override
either the TWindow::Init (p. 501) function, or the TWindow::PostChildrenInit (p. 502) function,
depending on when it needs to happen.
To enable the custom window in the window scripts, you just need to call TWindowMan-
ager::AddWindowType() (p. 526) with the window name and class id:

wm->AddWindowType("GameWindow",TGame::ClassId()); C++

And then the window will be created in the script with a simple:

... Lua
GameWindow
{
x=300,y=100,w=400,h=400
},
...

2.2.3 Lua Main Loop? Custom Window Creation? What’s this about?
The Playground SDK™ uses Lua as a way to achieve light cooperative multithreading, as well as
for dialog/window layout. In the Lua main loop script, you can specify the order of windows you
want to display, or a simple animation sequence, or pop up a modal dialog. When it’s time for the
script to pause (to wait for an animation or user input), you call a command that returns control to
the C++ code. Some commands, like DisplaySplash() (p. 144), implicitly return control and wait
for a specified amount of time before continuing. Others, like DoModal() (p. 145), pause to wait
for a particular event, such as the closing of a window. Here is the main Lua GUI loop:

-- Main game loop Lua


function Main()

DisplaySplash(
"splash/playfirst_animated_logo.swf",
"splash/playfirst_logo",4000
);
DisplaySplash("", "splash/distributor_logo",4000);

-- Push the game selection screen

Navigating the Playground SDK


2.2 A First Example Program 11

while true do
DoMainWindow("scripts/mainmenu.lua");
-- DoMainWindow will exit only if there are NO windows pushed on the stack, so
-- a PopModal()/PushModal() combination will not cause this to loop.
end
end

-- Return a function to be executed in a thread


return Main

That last return statement is important: When you call TScript::RunScript (p. 392), it just runs
through the script once and returns. What we want to happen is for it to be able to run in a
threaded manner. So TScript::RunScript (p. 392) watches for a return value from the script that it
just ran, and if it finds one that’s a function, it runs the function as a thread.
So what’s happening here? First, a call to DisplaySplash() (p. 144) displays a splash screen for
4000ms (or until the user hits a key). A second call to DisplaySplash() (p. 144) brings up the
second screen for 2000ms. Then an endless loop starts that consists entirely of bringing up the
game selection screen. Why is it an endless loop? Because the game selection screen destroys itself
when someone selects a game, and so when the user is done playing and the DoModal() (p. 145)
subroutine finally exits, the game will need to create a new game selection screen.

2.2.4 The Main Program: Part Two

Back to main.cpp to show you the rest of the main loop:

// The main C++ loop C++


TEvent event;
while(true)
{
pPlatform->GetEvent(&event);
if(event.mType == TEvent::kQuit)
{
break;
}

if (event.mType == TEvent::kClose)
{
TWindowManager::GetInstance()->GetScript()->RunScript("scripts/quitverify.lua");
}

if (event.mType == TEvent::kFullScreenToggle)
{
TSettings::GetInstance()->UpdateFullScreen();
}

// Pass the event to the Window manager for further processing


TPlatform::GetInstance()->GetWindowManager()->HandleEvent(&event);
}

Here we have our "message pump," the place where top level application messages get processed.
This code is pretty straightforward: Get an event, do something if we know how to react to it (i.e.,
if it’s a kClose event), and pass the event on to TWindowManager::HandleEvent() (p. 524) for
further processing. TWindowManagerHandleEvent() then propagates events appropriately; for

Playground 4.0.17.1
12 Getting Started

example, it triggers mouse and keyboard events on appropriate windows.

Navigating the Playground SDK


2.3 Game Assets 13

2.3 Game Assets

Game assets are loaded and managed by the library. Internally, they are reference counted, but
the reference count is updated entirely by C++ container classes. To use a bitmap texture loaded
from disk, for instance, you would acquire it from the library using TTextureGet() and keep it in a
TTextureRef (p. 548) instance. The TTextureRef handles the reference counting.
Here’s some code to illustrate:

class MyGame : public TWindow C++


{

...

void LoadAssets()
{
// Load myimage.png or myimage.jpg
mMyImage = TTexture::Get("images/myimage");
}

void Draw()
{
// Draw the image to the middle of an 800x600 screen
mMyImage->DrawSprite(400,300);
}

TTextureRef mMyImage ;
}

The basic idea is that you keep around a persistent TTextureRef for each image you need. If you
call TTextureGet more than once for the image you’ve already loaded, it will hand you a second
reference to the same image. When the last TTextureRef to a particular image is destroyed, the
image will be deallocated. Note that when you destroy a window and create a new window, as
when you are switching between game modes, it doesn’t actually delete the old window until you
have created the new window—so any assets in common are simply referenced and won’t need to
be reloaded.
A TTexture can currently be loaded from a JPG or a PNG file, and will be auto-converted to a bit
depth compatible with the current screen resolution. A TTextureRef acts like a pointer:

TTextureRef t = TTexture::Get("my.jpg"); C++


t->Draw( ... )

The example with TTexture (p. 463) above works similarly for TModel/TModelRef, if you plan to
use 3d models.

2.4 The Game Window

The skeleton is built of a number of custom window classes derived from TWindow (p. 496). In
a real game, each of these windows could be used to display a different part of the game or user
interface.

Playground 4.0.17.1
14 Getting Started

For example, in the Playground skeleton application the TSwarm class draws a swarm of but-
terflies. The butterflies are managed as sprites; here we create the sprites and assign them to a
container:

TSwarm::TSwarm() : C++
mLastUpdate(0),
mLevel(1)
{
mSpriteHolder = TSprite::Create();

// We’re going to lazy-load all of our textures


mAssetMap.SetAutoLoad(true);

TAnimatedTextureRef at= mAssetMap.GetAnimatedTexture("anim/cardinal");

if (at)
{
for (int i = 0 ;i<kNumSprites; ++i)
{
mSprites[i] = TAnimatedSprite::Create(i);
mSprites[i]->SetTexture(at);
mSprites[i]->Play();
TDrawSpec drawSpec(
TVec2( (float)((float)kBoundary+i*(float)(kWidth-kBoundary*2)/10.0F),
(float)((float)kBoundary+i*(float)(kHeight-kBoundary*2)/10.0F) ),
1,0.8F
);
drawSpec.mMatrix.Scale( 0.5F + TPlatform::GetInstance()->Rand()%1000/1000.0F );

mSprites[i]->GetDrawSpec()= drawSpec;
mVelocity[i]= TVec2(0,0);

mSpriteHolder->AddChild(mSprites[i]);
}
}

mHitCount = 0;
}

The member mSpriteHolder is a sprite itself, though it doesn’t have a texture assigned—rather it’s
only being used as a container. The same TAnimatedTexture (p. 182) is being assigned to each
sprite, but since each TAnimatedSprite (p. 175) keeps track of its frames independently, and the
script throws in some randomness, each butterfly flaps its wings independently.
Now that we have a bunch of butterfly sprites, let’s draw them. Here’s the start of the skeleton
application’s TSwarm::Draw:

void TSwarm::Draw() C++


{
TRenderer * r = TRenderer::GetInstance();
TBegin2d begin2d ;

mSpriteHolder->Draw();

That’s it—now the sprites are drawn on the screen. The particles (p. 57) also get drawn here. We’ll
go into more detail about them later.

Navigating the Playground SDK


2.4 The Game Window 15

2.4.1 Let’s Move!

Timed event processing is easy in Playground: You can either derive a class from TAnim-
Task (p. 191) and hand it to the current top modal window, or simply activate the internal
TWindow (p. 496) animation timer. Moving the sprites around in the skeleton is handled in
TSwarm::OnTaskAnimate–here is a simplified version for illustrative purposes:

bool TSwarm::OnTaskAnimate() C++


{
// Mark the screen as dirty so it will update
TWindowManager::GetInstance()->InvalidateScreen();

uint32_t now = GetWindowAnim()->GetClock()->GetTime();


TReal elapsedTime = (float)(now - mLastUpdate)/1000.0f;
mLastUpdate = now;

for (int i=0; i<kNumSprites; ++i)


{
// Get the distance from this butterfly to the mouse cursor.
TVec3 delta = TVec3(mLastMouse)-mSprites[i]->GetDrawSpec().mMatrix[2] ;

// Add the mouse "pull" to the velocity.


mVelocity[i] += delta * elapsedTime * mPull;

// Move the sprite position by the velocity


mSprites[i]->GetDrawSpec().mMatrix[2] += TVec3(mVelocity[i] * elapsedTime,0);
}
// Update the particle systems (pretend it’s always 16ms)
mParticles.Update(16);
mParticles2.Update(16);
return true;
}

Here TSwarm::OnTaskAnimate() iterates through the sprites and performs some simple math to
move the sprites around. Then it calls TLuaParticleSystemUpdate() on each particle system to
process their animation. Note that it’s calling those systems with a constant value; this tends to
keep the particle system looking more consistent.
To enable OnTaskAnimate(), you have to do one more thing:

void TSwarm::Init(TWindowStyle &style) C++


{
// Start the window animation to be called
// (at most) every 15 milliseconds
StartWindowAnimation( 15 );
}

The excerpt above is a simplified version of the code in the skeleton application (which also
bounces the butterflies off the edge, damps the velocity, and tries to prevent the butterflies from
clustering).
This is where the ongoing game logic typically takes place: In a routine that’s called at a particular
rate, so your game can always run at the same speed.
Be careful not to put more processing in a call like this than can comfortably be crunched in its
given time slot. If this call were to take longer than 15ms, for instance, then it would be executed

Playground 4.0.17.1
16 Getting Started

again on the very next update pass, and the game would slow down. You can prevent this and
keep your game at a constant speed by increasing the delay step so that it’s always longer than the
call takes.

2.4.2 Drawing 3d Objects

Here’s the start of a function in the skeleton responsible for rendering the chess piece window,
TChessPiece::Draw.

void TChessPiece::Draw() C++


{
// Getting a copy of TPlatform for convenience
TRenderer * r = TRenderer::GetInstance();
TRect screenRect ;
GetWindowRect(&screenRect);

{
TBegin3d begin3d;

// Set up our perspective projection matrix


r->SetPerspectiveProjection(0.1F,100.0F,PI/5.0f);

// Set up our rendering texture


r->SetTexture(mTexture);

// Set up our light


r->SetLight(0,&mLight);

// Set up our material


r->SetMaterial(&mMat);

So far it sets up a perspective projection matrix, a default texture, and a default material. Next it
needs to set up the world matrix and a light:

C++
TMat4 localMatrix ;
localMatrix.Identity();

// Build transform for yaw about board-y axis


localMatrix.RotateY(mYaw);

// Build transform for pitch about view-x axis

TMat4 pitch, view;


TRenderer::GetInstance()->GetViewMatrix(&view);
pitch.RotateAxis((TVec3)view[0], PI/6);

localMatrix = pitch*localMatrix ;

localMatrix[3][0] = 0;
localMatrix[3][1] = -0.75;
localMatrix[3][2] = 3;

mSpinLight.mDir.x = cos(mYaw*2) ;
mSpinLight.mDir.y = sin(mYaw*3) ;
mSpinLight.mDir.z = cos(mYaw*2) ;

Navigating the Playground SDK


2.5 Dealing With User Input 17

mSpinLight.mDir.Normalize();

// Set up our light


r->SetLight(1,&mSpinLight);
r->SetWorldMatrix(&localMatrix);

We’re spinning our chess piece around to mYaw radians and setting up a light at some other orbit
for interesting reflections here. Next we do the actual drawing of the model:

C++
if (mModel)
{
mModel->Draw();
}
begin3d.Done();
}

Note the TBegin3d (p. 201): It’s necessary to tell Playground whether you want it to be in 2d
or 3d mode before you actually do any drawing. This allows us to optimize certain aspects of
set-up, and makes this necessary overhead more explicit so that a game programmer knows that
switching between these modes is expensive.
Finally, we’re simply drawing a box around the window. Not brain surgery. Note TBegin2d
(p. 200), which is analogous to the TBegin3d (p. 201) above. TBegin2d (p. 200) and TBegin3d
(p. 201) are helper classes that automatically release the state on close of scope.
That’s all there is to it. So where did mModel come from? It was initialized in the TChessPiece
constructor along with mTexture:

C++
And there you have it!

2.5 Dealing With User Input


A TWindow-derived class will receive user input via the On∗() class of functions. If a user clicks
in a window, it will receive an TWindow::OnMouseDown() (p. 512) - TWindow::OnMouseUp()
(p. 512) pair. When a mouse moves over a window, it will receive TWindow::OnMouseMove()
(p. 512). Messages are passed from child to parent if the child doesn’t handle them.
Similarly, the window with the keyboard focus gets TWindow::OnChar (p. 513) when a key is hit.
For finer-grained control, TWindow::OnKeyDown (p. 514) and TWindow::OnKeyUp (p. 514) are
fired when a key is pressed and released. Messages sent from child windows, like the "button
pressed" message sent by TButton (p. 202), can be fielded by TWindow::OnMessage() (p. 511).

2.6 Why Modal Windows Are Your Friend


In the Playground SDK™ framework, when a message or event arrives at the window hierarchy,
it typically starts at a window and works its way up through parents looking for a handler. It
always stops looking if it encounters a TModalWindow (p. 298), however; modal windows act

Playground 4.0.17.1
18 Getting Started

as boundaries to the game context, and input never travels past them on the stack. In fact, the
TWindowManager (p. 519) maintains a stack of just TModalWindows, and you can query the top
modal window using TWindowManager::GetTopModalWindow() (p. 523).
When Playground starts up, it pushes a special modal window called TScreen (p. 387) on the top
of the window stack. This window must never be popped from the stack, or the game will exit.
The standard paradigm when switching between game modes is to pop the current modal win-
dow off the stack and push your new window; alternately, you can use the Lua function SwapTo-
Modal() (p. 151) if you are not creating custom-derived TModalWindows.
If you need to bring up a game-pausing event ("Are you sure you want to quit?"), you can push
another modal window onto the stack, and pop it when you’re finished. If you have a game with
sub-games, you can push a sub-game window onto the stack. When a new modal window is on
the stack, the previous window gets no messages, its TTask (p. 429) events stop firing, and its clock
stops. Messages and TTask (p. 429) events resume when the child modal window closes. Note
that in order to take advantage of its clock you need to explicitly assign the clock to the class that
needs it, e.g., TAnimTask (p. 191) or TAnimatedSprite (p. 175).
Modal window have no technical limit as to their depth; however it’s probably not wise to push
more than two to three levels, just from a user interface perspective.

Navigating the Playground SDK


2.7 How to use Playground SDK™ features. 19

2.7 How to use Playground SDK™ features.

2.7.1 Using TSprites


The TSprite (p. 419) class can be used to help manage the display of game objects. TSprite objects
are stored in reference-counted variables. You can use them individually, or you can create a
hierarchy of them.
A TSprite (p. 419) is an encapsulation of the following items:

• A texture to render.

• A layer value.

• A TDrawSpec (p. 223) for position/orientation/tint/scaling/alpha.

• A list of children.

When you create a TSprite you give it a layer, which is used only for sorting relative to its siblings
and parent: Higher numbered layers appear in front of lower numbered layers among siblings,
and negative layers appear behind the parent TSprite.
Each TSprite has an associated TTexture (p. 463), and an inherent TDrawSpec. The latter is used
to position and orient the sprite relative to its parent, and in general to determine how to draw the
texture. See the documentation on TDrawSpec (p. 223) for more details.
A related object, the TAnimatedSprite (p. 175), is identical to the TSprite with two exceptions:
It’s designed to be able to handle TAnimatedTexture (p. 182) particularly well, and it contains a
TScript (p. 389) for animating the TAnimatedTexture. A normal TSprite can have a TAnimated-
Texture assigned to it, since TAnimatedTexture inherits the TTexture interface, and therefore in
object-oriented terms is-a TTexture. However, since TAnimatedTexture objects can be reused, any
animation state has to be kept with each instance–in this case with the TAnimatedSprite object.

Why a TAnimatedSprite and a TAnimatedTexture?


A TAnimatedTexture (p. 182) is simply a list of frames. A TAnimatedSprite (p. 175) has a script
that plays back the frames. So there’s no concept of "Play" on TAnimatedTexture (p. 182), but there
is on TAnimatedSprite (p. 175).

2.7.2 Using TDrawSpec


A TDrawSpec (p. 223) includes the following information:

• A position.

• An orientation/scaling matrix

• A logical center to render the texture relative to.

• A tint value (that’s local to this sprite).

Playground 4.0.17.1
20 Getting Started

• An alpha value (that’s inherited by children).

There are two overloaded versions of TTexture::DrawSprite (p. 467). The first takes a set of sim-
plified parameters, and the second takes a TDrawSpec for increased control over how the image is
drawn. TDrawSpec (p. 223) comes with a convenience constructor that will allow you to set most
common values in-place. After it’s constructed, you can modify it with much more sophisticated
requests if you need to.
There were three reasons for the decision to migrate to a TDrawSpec-style interface: One, TTex-
ture::DrawSprite (p. 467) was really getting over-overloaded with confusingly similar parameter
lists. Two, the parameter lists were getting so long that it became quite annoying to set the ones
later in the list if you just needed to set one or two. And third, the DrawSprite parameters simply
weren’t flexible enough to do full inheritance of rotation/scale matrices, which is what we wanted
for the sprite system.

2.7.3 Using TWindows


TWindow (p. 496) and its descendants are for GUI elements. The typical Playground SDK™ model
is one where you create your game in a TWindow, possibly layered with TText (p. 433) windows
for score and other messages, and TImage (p. 249) windows for interface elements. The TWindow-
Draw() call is where you do the heavy lifting, actually drawing elements of your game. Depending
on your preferences, you can manage that part yourself entirely, drawing textures exactly where
you want them, or you can use a support class like TSprite (p. 419) to help manage the display of
your game objects for you.
TWindows clip what they and their children draw to their rectangle. For a GUI element, that’s
a feature: You can draw a block of text that’s clipped to the window, or you can draw an image
that’s zoomed so that its boundaries clip to the window. TWindows will receive mouse messages
when the mouse is within their bounds (note that mouse messages are also clipped to parent
windows), and TWindows can also receive the keyboard focus and thereby receive key events (see
TWindowManager::SetFocus() (p. 525)).
Many functions return a TWindow∗, and you will often need a derived class. The function
TWindow::GetCast<>() (p. 503) will get you that pointer with type safety (see Type Information
and Casting (p. 25) for details). Windows can optionally draw their contents (TWindow::Draw()
(p. 503)), contain other child windows, and respond to events or messages. Window updates and
messages are handled by the TWindowManager (p. 519) class, which is available from the single-
ton accessor TWindowManagerGetInstance().
To assist in debugging window hierarchies, in debug builds on Windows pressing "F2" will dump
the current hierarchy to the debug log.

2.7.4 Modifying TTexture Objects


When you’ve modified a texture in the game, you need to set up a texture-refresh-listener to mon-
itor whether the texture contents have been lost.
When DirectX loses a texture, it needs to be rerendered. This is handled by the library for textures
loaded from files that haven’t been modified, but any modified by the game via TRendererCopy-
Pixels, TTextGraphicDraw, or TRendererBeginRenderTarget need to be redrawn if they are lost.

Navigating the Playground SDK


2.7 How to use Playground SDK™ features. 21

The process is simple enough. Create a TTask-derived class and override DoTask:

class MyTextureListener: public TTask C++


{
public:
virtual bool DoTask()
{
RenderMyPrivateTextures();
}
};

Then call:

TPlatform::GetInstance()->AdoptTextureRefreshListener( new MyTextureListener() ); C++

Now any time that your texture needs to be redrawn (because of lost surfaces), your function
RenderMyPrivateTextures() will be called.

2.7.5 Using TTextGraphic Objects


You can use TTextGraphic (p. 447) to render to any texture, not only a render target. In this
example, assume the following class definition:

TTextureRef mTextTexture ; C++

And then the code:

mTextTexture = TTexture::Create(512, 512, true); C++


TColor color(1,1,1,0); // White background that’s transparent (alpha 0)
TPlatform::GetInstance()->FillRect(0,0,512,512,&amp;color,mTextTexture);

TTextGraphic * tg = TTextGraphic::Create(
"<outline color=\\"000000\\" size=\\"3\\">SWEET PAUSE</outline>",
512,512,TTextGraphic::kHAlignCenter,"fonts/arial.mvec", 60, TColor(1, 1, 1, 1) );
tg->SetNoBlend();
tg->Draw( TRect(0,0,512,512), 1, 0, 1, mTextTexture );
tg->Destroy();

When this is complete, mTextTexture ends up with SWEET PAUSE rendered in Arial font and a
black outline in a texture that’s transparent except for the text itself which is opaque. The TRect
(p. 364) in TTextGraphic::Draw (p. 449) can be used to position the text: Just bump down the top
Y coordinate for each successive render. The text size is determined in the TTextGraphic::Create
(p. 449) call–I arbitrarily chose 60 pixels tall, but feel free to customize to the appropriate height.

Playground 4.0.17.1
22 Getting Started

2.8 What is Lua?

Lua is a compact, fast, flexible, and extendable scripting language that is included as part of the
Playground SDK™. Its syntax has a few quirks that we put up with because we love it so much.
You can read more about Lua at http://www.lua.org. We’re currently using version 5.0x of Lua
in Playground, though we’re investigating an upgrade to the latest, 5.1.

2.9 Lua Makes it Easy

Using a scripting language to write the basic control flow of a game is a very powerful technique.
Take, for example the following code:

-- Main game loop Lua


function Main()

DisplaySplash(
"splash/playfirst_animated_logo.swf",
"splash/playfirst_logo",4000
);
DisplaySplash("", "splash/distributor_logo",4000);

-- Push the game selection screen


while true do
DoMainWindow("scripts/mainmenu.lua");
-- DoMainWindow will exit only if there are NO windows pushed on the stack, so
-- a PopModal()/PushModal() combination will not cause this to loop.
end
end

-- Return a function to be executed in a thread


return Main

Here the sequence is clear: Display one splash screen, then another, then enter main options loop.
There’s no jumping around from one place to another to see what happens next; it’s right there in
front of you. If you want to change the sequence, it’s a simple matter of adding or moving a line
of Lua code.
Or this code excerpt from a window definition:

Button Lua
{
x=40, y=40, -- Position of the button
label="Start Game", -- Button text
command=function()
SwapToModal("gamescreen.lua"); -- switch to the game screen
end;
}

Curly-braces in Lua define a table—they’re not used for scope, though they may appear to in the
previous example. The above syntax is a shortcut for calling the function "Button" with a single
table as the only parameter: Button( { x=40 ... } ).

Navigating the Playground SDK


2.10 What About Speed? 23

In this table we’re setting a few button characteristics, including its position, label, and a command
to execute when it’s pressed. The Lua command "function" actually defines a function right there
in the Button definition. It’s an anonymous function, in that it doesn’t have a name of its own, but
that’s OK, because in Lua functions are first-class data: You can assign them to variables, return
them from functions, or, as in the case above, add them to a table entry.
If the above example used DoModal() (p. 145) instead of SwapToModal() (p. 151), it would have
simply brought a window up on top of the current window—a standard "Modal" dialog, possibly
asking for user input. And that window could have its own actions embedded in its buttons.

2.10 What About Speed?


There are those who worry about the speed of a scripting language to write a game. And they’re
right: It’s not as fast as raw C++ code. But there are plenty of places in your code where you
don’t need the most speed possible: Responding to a button click and deciding what splash screen
to display next are two examples from above. The general 80/20 rule usually holds: more than
80% of the execution time is spent in 20% of the code. Some go further and say that 90% of the
execution time is spent in less than 10% of the code. So don’t write that part in Lua.
Lua interfaces to C and C++ very easily: It was written to be an embedded scripting language
(originally a configuration language). We’ve included template wrapper functions that allow you
to painlessly drop a member function of a class right into Lua. And it’s actually not that slow: It
compiles to an interpreted byte code. It benchmarks favorably against Perl, Ruby, PHP, JavaScript,
and Python. And it adds less than 40k of object code to the executable.

2.11 What are the pitfalls?


So what’s the catch? Well, we’re using the Lua "coroutine" feature to run the main window
thread—most of the time the main loop thread is waiting for a message to tell it what to do next.
We can use the Lua interpreter to run simple functions from our C code at that point, but that code
can’t itself yield, because that particular interpreter has already yielded. You can call a function
using TLuaFunction::Call() (p. 259) even if there’s a currently yielded function on the Lua stack,
but that function can’t itself yield. Nor can the function that you call directly or indirectly attempt
to resume the original yielded function, which by that point is buried under both the Lua and
system stacks.
The Playground SDK™ handles the first problem internally for the GUI script (the one you get
from TWindowManager::GetScript (p. 525)), so you don’t need to worry about it, since it will
take any code you run and inject it into the currently paused script, if it’s in a state where it can do
this.
The second problem, trying to yield across a C call, comes up most frequently when C/C++ code
that the Lua script calls attempts to inject its own function or pass a message into the running
Lua stack. Avoiding this is easy, though: Any calls that you expose to Lua should be restricted to
manipulating C++ data entirely, which could include, for instance, adding a message to a queue
that will later be injected in a Lua script or processed by your game.
In fact, the TMessage (p. 294) system works great for this; just create a message type for your game

Playground 4.0.17.1
24 Getting Started

with whatever payload you want, and trigger complex events in your game using those messages
rather than just calling the necessary code directly. By "complex", I mean events that themselves
may rely on the Lua interpreter to do something that might require a Yield or Resume.

Navigating the Playground SDK


Chapter 3

Playground Fundamentals

3.1 Dynamic Casting


C++ has support for runtime type information (RTTI), which includes the ability to safely dy-
namically cast from one type to another, but there are several shortcomings to the standard RTTI
support. For one, there is no dynamic creation support. For another, when classes are contained in
smart pointers, a straight dynamic_cast won’t work, because as far as C++ is concerned the objects
have no relationship to each other. Finally, there is no reflection in C++ classes–you can’t ask a
class what type it is and get a predictable response.
The Playground SDK™ RTTI system supports dynamic creation of classes, safe casting between
smart pointers to related classes, and identifying classes by name.

3.2 RTTI in TWindow


The TWindow (p. 496) hierarchy doesn’t require the use of the smart-pointer features, but does
use dynamic creation. Every TWindow-derived type includes a static member function ClassId().
TButtonClassId() will return the class identifier for the TButton (p. 202) class, for instance.
To find out if a TWindow∗ is a TButton, use the following pattern:

TWindow * window = .... C++


if (window->IsKindOf( TButton::ClassId() ))
{
// Our window is a button
}

Most of the time you’ll probably need to get a TButton directly. That’s where GetCast() comes in–it
works like dynamic_cast to cast our TWindow∗ to an appropriate type, returning a NULL pointer
if the cast is inappropriate:

TWindow * window = .... C++


26 Playground Fundamentals

TButton * button = window->GetCast<TButton>();

if (button)
{
// Our window is a button, and now we have a button to play with
}

Navigating the Playground SDK


3.3 How to Share and Play Well With Others 27

3.3 How to Share and Play Well With Others

When writing a game, some objects have clear owners: In the case of a button, it’s fine to allow
the enclosing window to own it and clean it up when it’s destroyed. But there are some situations
where an object or resource has no clear owner. The texture to draw on the button is one simple
example: You wouldn’t want the button to destroy the texture when it’s deleted for fear another
button on the screen is still using it.
One solution to this problem is to use reference-counted pointers: Smart containers that keep track
of how many references are currently held to them. The above example would keep the button
texture around until the last button window holding the texture container was deleted. Additional
tricks can allow you to keep a list of currently loaded textures, so that when each button requests
its texture they all get shared instances of the same texture.
You can use reference-counted pointers to manage your own game objects as well, but it’s impor-
tant to thoroughly understand the implications of using smart pointers before using them. It’s not
really that difficult, but there are a few common traps that you need to be aware of in order to
avoid stumbling into them.

3.4 Using shared_ptr (TClassRef) Classes

When you include pf/ref.h, you gain access to the shared_ptr template class. Several Playground
classes use shared_ptr internally, and provide convenience typedefs of the form TFooRef, indicat-
ing that it’s a reference-counted container for a Foo. A few common examples include:

• TTextureRef

• TModelRef

• TSoundRef

• TSpriteRef

The full set of Playground shared_ptr typedefs is defined in pf/forward.h (p. 547). In each case
where Playground intends you to use shared_ptrs, the associated class has a static member factory
named Get() (or prefixed by Get) when the class manages sharing of instances of the asset, or
Create() for when you need a new, unique item. See TTexture::Get() (p. 465) or TTexture::Create()
(p. 466) for two examples.
Part of the reason to have factories like this instead of allowing you to new objects and assign them
to shared_ptrs is to help avoid common reference-counted-pointer errors by never encouraging
you to operate on the raw pointers. If you always hold one of these objects in an appropriate Ref
(e.g., TTextureRef) container for as long as you intend to use it, passing it from place to place as a
Ref, and never converting it to a pointer at all, then it’s really hard to make a mistake that would
cause the reference counting mechanism to fail.

Playground 4.0.17.1
28 Playground Fundamentals

3.5 Managing Assets


Another common strategy to handle assets is to have an asset pool that a particular portion of
your game can draw assets from. Sometimes that portion is the entire game, where you can load
up assets at the beginning during a loading screen. Sometimes you want to load some assets at the
start of a level, and then release them when the next level starts.
Playground also supports this pattern: Create a TAssetMap (p. 196) for your level, or for the whole
game, or both, and use it to hold references to all of your game assets. When you’re done with that
portion of the game, destroy the TAssetMap and all of those assets will be released. Here’s the best
part: If you "load" the next section of your game before you delete the old TAssetMap, any assets
in common will simply be referenced and not reloaded!
You can use a TAssetMap in either a strict mode where it requires that any asset you request
through it must already be referenced, or in a more forgiving mode where you can request
an asset it doesn’t have yet and it will both load and hold a reference to the asset. See TAs-
setMap::SetAutoLoad() (p. 197) for details.

3.6 Common Mistakes


So what are the common mistakes you need to be aware of? Well, here’s one:

// This is BAD! Don’t do it! C++


TTexture* someTexture = TTexture::Get("foo.png").get();

Assuming the texture isn’t referenced elsewhere, the code above will assign a dangling pointer to
someTexture. By the time the assignment occurs, the texture object will have been destroyed.

// Correct C++
TTextureRef someTexture = TTexture::Get("foo.png");

Keeping it in a TTextureRef ensures that you keep a reference to it when the temporary on the
right hand side of the assignment operator is destroyed.

// This is also BAD! Don’t do it either! C++


void Foo( TTexture* texture )
{
TTextureRef textureRef(texture); // ERROR!
}

TTextureRef someTexture = TTexture::Get("foo.png");


Foo( someTexture.get() ); // BAD BAD BAD

In the example above, when someTexture leaves scope, it will delete the texture. Funny thing is,
when textureRef leaves scope, it will also delete the texture. This is not considered a good thing. If
you have a good memory debug tool in place, you’ll find this right away because it will alert you
right when it happens. Without malloc debugging active, some time later, in an unrelated part
of your game, it will probably crash when allocating or freeing memory. And where it crashes
may change between debug and release builds, because the memory allocators work differently
in debug and release. In other words, this is a bug you never want to lay the groundwork for by

Navigating the Playground SDK


3.7 Your Very Own shared_ptr 29

using raw pointers when you should be using shared_ptrs.


Again, simply passing the reference around as a reference solves the problem:

// Correct C++
void Foo( TTextureRef texture )
{
...
}

TTextureRef someTexture = TTexture::Get("foo.png");


Foo( someTexture ); // No pointer necessary

3.7 Your Very Own shared_ptr


The shared_ptr template class can be used to manage game assets as well. If you’re using
shared_ptrs in your own classes, though, you can end up with a cyclic reference that never gets
freed: A holds a reference to B and vice versa. When all references to A and B are freed, you still
have these two referring to each other. All is not lost, however. One or both of these references
can be a "weak" reference. If A owns B, but B needs a reference back to A, then you can make the
pointer in A a shared_ptr and the one in B a weak_ptr. That way when the last reference to A is
released, it will destroy A. If another object still holds a reference to B, it won’t be destroyed when
A releases its reference–but B’s weak reference to A will magically NULL itself, so that B knows A
has been destroyed.

3.8 Implementation Details


Technical details for the current implementation can be found at http://boost.org/libs/smart_
ptr/smart_ptr.htm
Feel free to look at the documentation there to understand more about the philosophy and design
decisions behind smart pointers. However, we are using a subset of the full Boost libraries, so don’t
expect all of the features they describe to be available. We do use weak_ptr internally to handle
our Get() functions (so we know if an asset has already been loaded, and to correctly return the
existing shared_ptr), but we reserve the right to reimplement the shared_ptr if we decide there’s a
compelling reason.

Playground 4.0.17.1
30 Playground Fundamentals

3.9 About the Playground SDK™ Hiscore System


Playground includes a hiscore management system that can be used to keep track of your players’
highest scores in multiple categories in your game. For games that are published by PlayFirst, the
system also includes the ability to connect with PlayFirst servers and share high scores globally.

3.10 Initialize The System


For PlayFirst published builds, you’ll need to set the PlayFirst-provided encryption key using
TPlatform::SetConfig() (p. 340).

// This line typically appears in TSettings/settings.cpp C++


TPlatform::GetInstance()->SetConfig(TPlatform::kEncryptionKey,ENCRYPTION_KEY);

TPfHiscores *pHiscores = new TPfHiscores();

The game name on Windows is extracted from the program’s resource: look in the project’s .RC
file for the ProductName to set the name.

3.11 Connecting to a debug server


Until your game is officially launched, the PlayFirst hiscore server will not know how to accept
submissions from your game. Therefore, to test your implementation of the hiscore system, you
need to use a local server.
To connect to the fake local server:

1. Place the pfservlet_stub.dll in the same folder you are loading the pfhiscore.dll from (or in
the same folder as your .exe if you are using a static lib). The system will detect the existence
of this dll, and if it can find it, it will use a local server instead of connecting to one over the
Internet.
2. Make sure that you are correctly setting up the TPlatform::SetConfig (p. 340) settings for
kPFGameHandle, kPFGameModeName, and kEncryptionKey. This is done in Playgroun-
dInit() (p. 544) in the Playground Skeleton sample application.
3. You are now set up to use the hiscore system without connecting to a server. Note that
this will create a file called "serverdata.txt" file in the same folder as the dll that will store
information between executions so you can test building up long lists of scores. Also, note
that this local server does not contain all the functionality as the real online server (i.e. it does
not contain the profanity name filter and it will also not correctly filter the scores by "daily",
"weekly", etc.) but it does have enough functionality for you to fully test your game.
4. The pfservlet_stub.dll comes with 2 user accounts created for testing PlayFirst user submis-
sions. They are "testname" with password "testpass" and "testname2" with "testpass2".
5. Refer to the values recorded in "serverdata.txt" to verify that your score and medals submis-
sions were successful.

Navigating the Playground SDK


3.12 Set Properties 31

3.12 Set Properties


As the user plays the game, you need to set various properties with the hiscore system. If the user
changes player names/profiles, call:

pHiscores->SetProperty(TPfHiscores::ePlayerName, PLAYERNAME); C++

If the user changes game modes, call:

pHiscores->SetProperty(TPfHiscores::eGameMode, GAMEMODE); C++

If the user changes languages, call:

pHiscores->SetProperty(TPfHiscores::eLanguage, LANGUAGE); C++

3.13 Logging Scores


At the end of a game (or when quitting a story-mode game where you want to log a score), you
need to log the players score so it will be eligible for a hiscore. In addition to logging a score, you
should also log game specific data (i.e. "5" for someone who has reached level 5, etc.). Please do
not put text inside the game specific data, as it makes it difficult to localize. The game has the
chance to parse out this game specific data later on and put it in visible form. The server currently
supports up to 60 characters of data.

// Log a score of 500 points, replace existing score by this player, C++
// and pass in the GAMEDATA string defined elsewhere...
pHiscores->KeepScore(500, true, GAMEDATA);

3.14 Logging Medals


When a user earns a medal, you can log the medal for submission to the server.

pHiscores->KeepMedal(PFGAMEMEDALNAMES[0], TPfHiscores::eMedalType_Game); C++

3.15 Viewing local scores


On the local score screen, you can view all the logged local scores. To view the local scores for the
current game mode:

pHiscores->GetScoreCount(true); C++
for (int i = 0; i < numScores; i++)
{
int rank;
char name[16];
bool anon;

Playground 4.0.17.1
32 Playground Fundamentals

int score;
char gameData[64];

if (pHiscores->GetScore(true, i, &rank, name, 16, &anon, &score, gameData, 64))


{
char outputTest[512];
sprintf(outputTest, "%d) %s (%d) %d\n", rank, name, anon, score);
DEBUG_WRITE((outputTest));
}
}

In the local scores screen, you can also change the game mode by setting the game mode property,
and then recalling the code above for the new game mode.

3.16 Figuring out what score the user can submit


Once in the local score screen, you can figure out if the current player has a score eligible to submit:

if (pHiscores->GetUserBestScore(TPfHiscores::eLocalEligible,&score, &rank, gameData, 32)) C++


{
// display what the users current eligible score is to submit
}
else
{
// user has no eligible scores to submit
}

3.17 Submitting a score and medals


To submit a score, you either submit an anonymous score or a user/password official score. They
both use the same call. If you submit data with a password, it will also submit any medals that
have been logged. You can control whether you are submitting medals and scores, or just one
individually. It is recommended that you submit everything at once if the UI allows it - but if the
UI is specific to just medals you may need to only submit medals. Once you submit the score and
medals, you need to poll for the status of the submission to check for any errors:

pHiscores->SubmitData(USERNAME, PASSWORD, REMEMBERSETTINGS, TPfHiscores::kSubmitAll); C++


TPfHiscores::EStatus status;
char errorMsg[256];
bool qualified
status = mpHiscores->GetServerRequestStatus(errorMsg, 256, &qualified);
while (status == TPfHiscores::ePending)
{
status = mpHiscores->GetServerRequestStatus(errorMsg, 256, NULL);
}
if (status == TPfHiscores::eError)
{
DEBUG_WRITE((errorMsg));
}
else if (status == TPfHiscores::eSuccess)

Navigating the Playground SDK


3.18 Switching to the global score view 33

{
if (qualified)
{
// inform user of qualified score
}
else
{
// inform user that score did not qualify
}

3.18 Switching to the global score view


The first thing you need to do when switching to the global score view is get the available cate-
gories from the server. The categories are things like "last 24 hours" or "all time records".

pHiscores->RequestCategoryInformation(); C++
TPfHiscores::EStatus status;
char errorMsg[256];
status = mpHiscores->GetServerRequestStatus(errorMsg, 256, NULL);
while (status == TPfHiscores::ePending)
{
status = mpHiscores->GetServerRequestStatus(errorMsg, 256, NULL);
}

if (status == TPfHiscores::eError)
{
DEBUG_WRITE((errorMsg));
}
else if (status == TPfHiscores::eSuccess)
{
int numTables = pHiscores->GetCategoryCount();

for (int i = 0; i < numTables; i++)


{
char name[16];
if (pHiscores->GetCategoryName(i, name, 16))
{
char outputTest[512];
sprintf(outputTest, "TABLE: %s\n", name);
DEBUG_WRITE((outputTest));
}
}
}

Now that you’ve obtained the categories, you can request scores for a specific category. Note that
before you call RequestScores() you must have set a proper game mode with SetProperty() and
you must have received the category information with RequestCategoryInformation().

pHiscores->RequestScores(CATEGORYNUM); C++
TPfHiscores::EStatus status;
char errorMsg[256];

Playground 4.0.17.1
34 Playground Fundamentals

status = mpHiscores->GetServerRequestStatus(errorMsg, 256, NULL);


while (status == TPfHiscores::ePending)
{
status = mpHiscores->GetServerRequestStatus(errorMsg, 256, NULL);
}
if (status == TPfHiscores::eError)
{
DEBUG_WRITE((errorMsg));
}
else if (status == TPfHiscores::eSuccess)
{
int numScores = pHiscores->GetScoreCount(false);

for (int i = 0; i < numScores; i++)


{
int rank;
char name[16];
bool anon;
int score;
char gamedata[64];

if (pHiscores->GetScore(false, i, &rank, name, 16, &anon, &score, gameData, 64))


{
char outputTest[512];
sprintf(outputTest, "%d) %s (%d) %d %s\n", rank, name, anon, score, gameData);
DEBUG_WRITE((outputTest));
}
}
}

Finally, you can determine the user’s current ranking in the currently fetched table from:

int score; C++


int rank;
char gameData[64];

if (mpHiscores->GetUserBestScore(TPfHiscores::eGlobalBest, &score, &rank, gameData, 64))


{
// user is ranked
}
else
{
// user is not ranked
}

3.19 Hiscore FAQ

Question: How can I connect to the PlayFirst hiscore server to test my implementation?
Answer: You should be able to fully test your hiscore implementation against the pfservlet_stub.
If it works with this stub (and you have configured TPlatform::SetConfig (p. 340) just like the
Playground Skeleton does in PlaygroundInit() (p. 544)), it will work when your game goes "live".
Question: Hiscores is not working. Can I get any information about why it is failing?

Navigating the Playground SDK


3.19 Hiscore FAQ 35

Answer: You should check your logfile. Depending on the error, some information may be dis-
played in the logfile which may make it obvious why your hiscore submission is failing.
Question: QA is telling me that hiscores fail on their server, but they work fine on my stub. What
is the difference?
Answer: Make sure that you are using the PlayFirst provided key.h file, which correctly specifies
the exact names for:

• The game handle (in Windows, this is set in the resource file)
• The encryption key
• The game modes
• The medal names

Question: I can view global hiscores, but all the submissions fail. What is wrong?
Answer: If you can successfully view hiscores but not submit them, then your encryption key is
incorrect.
Question: When I submit a hiscore with medals in it, I get an error in my logfile about invalid
XML. What does that mean?
Answer: (This question involves an older version of the API that is being deprecated - use Keep-
Score/KeepMedals/SubmitData to avoid this problem). XML must be "well-formed". A common
mistake is to forget to close the XML tag with a forward slash. Note that using XML is no longer
necessary for submitting medals - use the KeepMedals and SubmitData calls and this will be han-
dled automatically.
Question: I am seeing weird results when I submit a score and medals. Sometimes I see the "Did
Not Qualify" response, but then the score gets recorded anyway. Other times the system lets me
submit the same score over and over again. What is going on?
Answer: (This question involves an older version of the API that is being deprecated - use Keep-
Score/KeepMedals/SubmitData to avoid this problem). This is most likely because you are issu-
ing several server requests but only looking for one response. Each call to the server must then
poll GetServerRequestStatus() before the next call should take place. One specific situation that
can cause this behavior is if you submit a score, then submit medals, and then poll the server.
The response you get back from the server will be the response to the medals submission only.
Therefore, the response to the score submission is lost completely. The correct thing to do in this
situation would be to submit a score, then poll the server. Once a response is received, a medal
submission could continue, polling for a response to that as well.
Question: Why are there 2 different ways of submitting medals?
Answer: (This question involves an older version of the API that is being deprecated - use Keep-
Score/KeepMedals/SubmitData to avoid this problem). Medals can be associated with a score
(by using the serverData parameter in TPfHiscores::LogScore() (p. 333)), or they can be submit-
ted independently by using TPfHiscores::SubmitMedals() (p. 335). In some games, you can only
earn a new medal at the same time you earn a new hiscore (i.e. you can only earn a medal by
beating a new level, which also means your total score goes up). In this case, by associating a
medal with a score in TPfHiscores::LogScore() (p. 333), you don’t have to worry about how to
submit medals - they will be submitted when the user submits their score. In other games, you

Playground 4.0.17.1
36 Playground Fundamentals

can earn a medal without earning a new score (i.e. by replaying a previous level and completing a
series of events that unlocks a new medal). In this case, the user needs to submit their medals sep-
arately from their hiscore, because they may not have any hiscores to submit. In this case, more
UI needs to be added to the game to inform the user when they have a medal to submit, since
you cannot depend on the existence of a submittable hiscore in order to submit medals. Note that
TPfHiscores::submitScore() and TPfHiscores::SubmitMedals() (p. 335) should never be called im-
mediately one after the other - you always need to poll TPfHiscores::GetServerRequestStatus()
(p. 330) after each hiscore server call.
Question: How do I know if I should be running in full hiscore mode, anonymous hiscore mode,
or local hiscore mode?
Answer: You can use the following to determine which mode to run in:

• TPlatform::GetInstance() (p. 339)->IsEnabled(TPlatform::kHiscoreAnonymous) - use this to


detect anonymous mode
• TPlatform::GetInstance() (p. 339)->IsEnabled(TPlatform::kHiscoreLocalOnly) - use this to
detect local mode

Question: What is the difference between the full, anonymous, and local hiscore modes?
Answer: This is described in the Production Guidelines document, and your PlayFirst producer
can provide you with the full details about this. Additionally, the Playground Skeleton application
demonstrates each of these 3 modes, which you can test by changing the settings.xml file. The basic
differences between the modes are:

• In "full" mode the user can use a PlayFirst account and password to submit their hiscore.
Scores associated with a PlayFirst account have a special icon displayed next to them. There
is a text description about the PlayFirst global hiscores system, and a description of how to
register for an account.
• In "anonymous" mode users can submit hiscores only with an "anonymous" account. There
is no mention of PlayFirst in the hiscore system, though some text about a Privacy Policy
may be displayed. Please contact your producer for the exact text.
• In "local" mode there is no way to submit a hiscore to the global hiscore system. The user
can only see scores that they have earned on their local computer. There is no mention of the
PlayFirst hiscore system in this mode.

Navigating the Playground SDK


3.20 Writing Debug Messages 37

3.20 Writing Debug Messages


The Playground SDK™ defines a number of useful macros for debugging your code:

• DEBUG_WRITE() (p. 538) Writes messages to the debug log in debug builds.
• ERROR_WRITE() (p. 539) Writes messages to the debug log in debug and release builds.
• TRACE_WRITE() (p. 539) Writes the current line, function, and file to the debug log (in
debug builds only).
• ASSERT() (p. 538) Breaks in debug builds and prints ASSERT condition to the debug log;
removed in release build.
• VERIFY() (p. 539) Breaks in debug builds and prints VERIFY condition to the debug log; just
prints the condition to the log in release build. Guaranteed NOT to be removed in release
build. Useful for evaluating a function return value where the function has side effects (it
does something important).

On Windows, all printing to the log is mirrored in the debugger output window in debug build.
In release builds, the debug log is capped at 100k, but in debug build it is not limited in size.

3.21 Dynamic Debugging


Playground defines several hot keys to help you debug your application. Most are available only
during debug builds.

• Alt-F1 Bring up a display that includes current game vital statistics, including Playground
build version, frames-per-second, allocated memory, and allocated texture memory. This
works even in release builds.
• F2 Dump a window hierarchy to the debug log.
• Shift-F2 Draw a yellow rectangle on the border of the window the mouse is currently rolling
over.
• F3 Dump all currently allocated assets to the debug log.

Playground 4.0.17.1
38 Playground Fundamentals

3.22 Game Version Numbers


The version number for your game is read from the file version.h into your resource file (e.g.,
skeleton.rc, via version.rch).
If you’re developing a game for PlayFirst, then when it is submitted to PlayFirst to be built, your
copy of version.h is replaced by a machine generated version for each new build.
Considering this is true, if you’re working with PlayFirst to publish your Plaground SDK game,
you should be sure to:

• Only edit right hand side values in version.h


• Not add additional definitions to version.h
• Not change your game’s resource file (e.g., skeleton.rc or version.rch) to have a hard-coded
version number, or otherwise prevent it from reading and using the version number in ver-
sion.h

You may change the version information defined in version.h for your own purposes, as long as
you keep to the same format. However, please remember that for games released through Play-
First, this file is overwritten by PlayFirst’s release engineering process. This means that the build
numbers that your game has for your own builds will differ from the official builds that PlayFirst
generates. This is by design. If you violate the guidelines here, you will be asked to change your
code back, so that your game source code will not break the PlayFirst release engineering process.

Navigating the Playground SDK


Chapter 4

Beta Versions

4.1 How to Create Limited Builds for Beta Testers


When it’s time to send out your game to hordes of beta testers, the last thing you want to do is
send them your entire high-profile moneymaker: Even with copy-protection wrapped around it,
you’ll only slow down the crackers, who will have an unprotected version of your game up as
soon as a few days or a week after you’ve distributed it.
This may also be true of the final build once you post it on your site, but in the case of particularly
popular games, if a user really wants to play it sooner than later, they’ll be willing to download a
cracked version if the real build isn’t available.
Playground supports the development of limited builds using the same source and assets as your
final build. It does this by parsing one of two text files that indicate files and folders that the
internal file system should ignore; in the build you send out, if those files aren’t included in the
package, then that’s content that they can’t pirate. Using the text files you can simulate that content
being removed without creating a new entire development environment, or a second copy of your
assets tree.
To enable this feature, you need a settings.xml file if you don’t have one already. It should look
like:
<?xml version="1.0" ?>
<settings>
<firstpeek>1</firstpeek>
</settings>

...or if you already have one, then just add the <firstpeek> line above.
If it isn’t obvious, the number should be ’1’ for FirstPeek and ’0’ for the normal release build. This
file goes in the assets folder next to strings.xml.
In the folder that CONTAINS assets you need two more files:
final.txt firstpeek.txt
These files list asset filenames or that should be EXCLUDED from each view. This way you can
exclude files or folders from FirstPeek using firstpeek.txt, and you can exclude FirstPeek-only
40 Beta Versions

assets from the final build.


The files are each read in and fed through strtok with " \t\n\r" as the tokens: Any whitespace
will separate filenames. The filename needs to match EXACTLY the filename on disk. Be careful
with case sensitivity here–Playground doesn’t normalize the case, so your case will need to match
exactly.
There are no wildcards. You must name a complete path to a file:
path/to/file.jpg
...or the path to a folder:
path/to/folder
If you want to exclude a glob of files, you’ll need to pipe the glob to a text file and the list into the
above format. The paths are all relative to the assets folder.
At runtime, to tell the difference between FirstPeek and normal builds, you can use: TPlat-
form::GetInstance() (p. 339)->IsEnabled( TPlatform::kFirstPeek ). That way you can make run-
time game-play decisions–though that’s not completely safe as a protection method on its own,
since a cracker would only need to change one value to disable FirstPeek mode.
On the Mac, in order to make this work, you’ll need to add a build step that copies final.txt and
firstpeek.txt to the application bundle so the game can read them. On the build machine, these
files will need to be deleted, since we don’t want them in the package.

4.2 Tracking Game Metrics


The TGameState (p. 242) singleton allows you to easily accumulate game metrics for your First-
Peek build. Using the SetState() and GetState() calls as outlined below, you can automatically
accumulate state information about how the user is playing your game, and it will be written to
the file user:metrics.txt.
The metrics are only actually calculated and written to the output file when the module first-
peek.pfmod is placed in the game’s assets folder. PlayFirst will automatically include first-
peek.pfmod with FirstPeek builds, and the PlayFirst game wrapper will automatically collect that
file from the client’s computer and forward it back to PlayFirst for analysis.
Below are examples of how to set up and collect the metrics for your FirstPeek builds.

4.2.1 The Interface and States


All of the examples below use the TGameState (p. 242) interface to talk to the FirstPeek DLL. To
get that interface, you simply use the following code block.

TGameState * gs = TGameState::GetInstance(); C++

The C++ examples below assume a TGameState (p. 242) pointer called gs. On the other hand,
the Lua examples don’t need one! From within the Lua GUI script, SetState() and GetState() are
available directly:

Lua
Navigating the Playground SDK
4.2 Tracking Game Metrics 41

SetState("MyState", "1" );

The above line sets a state variable named "MyState" to the value "1". Later you can retrieve that
value:

state = GetState("MyState"); Lua

Note that you can call TGameState::SetState() (p. 243) regardless of whether it’s a FirstPeek ver-
sion. In a normal release of your game, the call will simply do (almost) nothing.
Sometimes you just want to record that someone has done something, like the fact that they started
story mode. In that case, you can just call:

gs->SetState("StartedStoryMode",1); C++

If you have a state that keeps track of how many times a user does something, you can prefix it
with the ++ operator:

gs->SetState("++LemonadeUsed"); // increment the LemonadeUsed state C++

A state starts out with value 0, so you can use the above line to count how many times the player
uses a lemonade power-up.
Later you will be able to write the state value to the FirstPeek log file, either immediately on
request, at a particular time delay, or at the end of the game, as I will describe below.

4.2.2 FirstPeek Timers


A common need in a FirstPeek game is to have timers that record, for example, how long the
player spends in different sections of the game–including how long they spend playing an entire
game session. To achieve this, at the start of the game, you’d typically write the following line to
start a session timer.

gs->SetState("SessionTime", 1) ; // start our session timer C++

Setting the state of any variable to "1" starts a timer with that name, and setting it to "0" pauses that
timer. The overhead is minimal, so don’t worry about setting a variable to "1" even if you don’t
intend to use it as a timer.
If you want to start and stop a timer that keeps track of the time spent in the main menu, you
could use the following code.

-- in the mainmenu.lua file Lua


SetState("MainMenuScreenTime", 1) ;

-- in each button command that exits


-- the main menu, call this function
function LeaveMainMenu()
SetState("MainMenuScreenTime", 0) ;
end

...

Playground 4.0.17.1
42 Beta Versions

Button
{
name = "startthegame";
command = function() LeaveMainMenu(); StartGame(); end;
}

...

Sometimes you’ll want to restart a timer so you can use it again. In that case you can set it to the
special value "restart".

gs->SetState("LevelPlayTime","restart"); Lua

It’s OK to set a timer to "restart" even if it’s never been used before. You can stop the timer normally
by setting it to "0".

4.2.3 Writing an Immediate Status Line

To write out stats during gameplay, such as at the end of a level, you start by naming the status
line block, and then adding status arguments to it one at a time until you’re done, at which point
you end the status line.
A simple example:

gs->SetState("begin-status","LevelCompleteStory"); // Name the status line Lua


gs->SetState("add-state","LemonadeUsed"); // Add the current state of LemonadeUsed
gs->SetState("end-status","LevelCompleteStory"); // End the status line

A few things here. First, the block is defined between a "begin-status" and an "end-status" com-
mand. Every value you add between those commands will be added to the status line.
The "add-state" command takes the name of a state that you’ve defined earlier, and it writes out
the current value of that state. You need to have previously set that state to some value, or it will
just write out an empty string.
There are two other commands you can use to add entries to the log line:

gs->SetState("begin-status","LevelCompleteStory"); // Name the status line Lua


gs->SetState("add-state","LemonadeUsed"); // Add the current state of LemonadeUsed
gs->SetState("add-timer","LevelPlayTime"); // Add the timer value LevelPlayTime
gs->SetState("add-value",score); // Add a constant value
gs->SetState("end-status","LevelCompleteStory"); // End the status line

The "add-timer" command writes out the value of a state variable that’s being used as a timer.
It needs a different command than "add-state" because its state value is simply "1" or "0"–and
that’s not what you want. To reiterate, when you SetState("LevelPlayTime",1), it effectively
starts an internal timer associated with the key "LevelPlayTime", and later when you call Set-
State("LevelPlayTime",0), that timer is paused.
Finally, "add-value" adds the constant you give it in the second parameter directly. There’s no
lookup performed–in the example above, it simply writes the score (presumably an integer) to the
log file line directly.

Navigating the Playground SDK


4.3 Writing Status on Elapsed Time 43

4.2.4 Write Status Line on Exit

A frequent need is to write a status line when the game exits. You could use the above "begin-
status"/"end-status" calls to write the line as your game quits, but we’ve made it even easier.
Instead you can set up a block at the start of the game that it holds onto until the game is being
quit, and on exit it will write out this status line with the values of the states at that time.
A simple example:

gs->SetState("begin-session","SessionData"); Lua
gs->SetState("add-timer","SessionTime"); // Add the session timer to the output
gs->SetState("add-timer","StoryModeSessionTime"); // Add a story mode timer
gs->SetState("add-timer","MainMenuScreenTime"); // How much time spent on the main menu?
gs->SetState("add-timer","ComicScreenTime"); // And how much on the comics?
gs->SetState("add-timer","HelpScreenTime"); // And how much on the help screen?
gs->SetState("add-state","LemonadeUsed"); // Add the current state of LemonadeUsed
gs->SetState("end-session","SessionData"); // Finish recording SessionData output

When the game exits, it will automatically write a SessionData line to the FirstPeek data file with
the final results of the states and timers listed. You can also use "add-value", but keep in mind
that you’re sending it a constant, and that the constant will therefore be defined at the start of the
game rather than later on. If you want to add a variable, then you should set it using SetState()
instead–that’s what it’s for!
Keep in mind that you should only call "begin-session"/"end-session" once during your game. If
you call it more than once, the results are undefined.

4.3 Writing Status on Elapsed Time

You can create status lines that write their output at specific elapsed times. This is similar to
"begin-session", but instead of at the end of a game session, it writes its data after a certain elapsed
time.
The elapsed time calculation is cumulative across sessions: Once they’ve played the game for 15
minutes TOTAL, the 15-minute timer will fire and write the data. It doesn’t matter if they play it
in one sitting or play 5 3-minute games–it keeps track of the cumulative elapsed time.
For example:

gs->SetState("begin-elapsed(15)","FifteenMinutesUsed"); // Start a 15-minute elapsed time record Lua


gs->SetState("add-state","LemonadeUsed"); // Have they used that lemonade yet?
gs->SetState("end-elapsed(15)","FifteenMinutesUsed"); // End the record.

Obviously the "15" above is the number of minutes of cumulative gameplay to compare with. If
the game has been played for more than 15 cumulative minutes on launch, this log file line will be
silently ignored.

Playground 4.0.17.1
44 Beta Versions

4.4 FirstPeek Module Reference


These command are used as the key in TGameState::SetState() (p. 243) as described above, with
the meaning of the value varying based on the command, as described below.

4.4.1 begin-status/end-status
Parameters:
value The name of the output line.

Begin and end a status line. The status line is written to metrics.txt immediately on receiving the
end-status command.
The line is written in CSV format, with the name, date, time, and cumulative elapsed time as the
first four parameters. Additional parameters can be added with the various add-∗ keys, below.

4.4.2 begin-session/end-session
Parameters:
value The name of the output line.

Begin and end a session line. The session block is written to metrics.txt when the game exits, using
the status variables as they are defined at that point.
See begin-status/end-status (this page) above for details status line format.

4.4.3 begin-elapsed(time)/end-elapsed(time)
Parameters:
time The number of elapsed minutes to use.
value The name of the output line.

Begin and end an elapsed-time data block. The elapsed time block is written to metrics.txt when
the game has been played (cumulatively across all sessions) the number of minutes given as time.
See begin-status/end-status (this page) above for details status line format.

4.4.4 add-timer
Parameters:
value Name of the key to time.

Add the elapsed time that a key has been set to a non-zero value as a parameter to the current
status line block. The value is queried when the status line block is actually written.

Navigating the Playground SDK


4.4 FirstPeek Module Reference 45

Must be within a status line block (begin-status/end-status (opposite), begin-session/end-session


(opposite), begin-elapsed(time)/end-elapsed(time) (opposite)) to have any effect; an error other-
wise.

4.4.5 add-timer
Parameters:
value Name of the key to query.

Add the value of the given key as a parameter to the current status line block. The value is queried
when the status line block is actually written.
Must be within a status line block (begin-status/end-status (opposite), begin-session/end-session
(opposite), begin-elapsed(time)/end-elapsed(time) (opposite)) to have any effect; an error other-
wise.

4.4.6 add-timer
Parameters:
value Constant value to add.

Add the given value (literal) as a parameter to the current status line block. This value is set
immediately, and not queried when the block is actually written.
Must be within a status line block (begin-status/end-status (opposite), begin-session/end-session
(opposite), begin-elapsed(time)/end-elapsed(time) (opposite)) to have any effect; an error other-
wise.

Playground 4.0.17.1
46 Beta Versions

Navigating the Playground SDK


Chapter 5

Lua

5.1 About Lua


Lua is an embedded scripting language that’s very fast and has a very small footprint. It’s also
very extensible, and very easy to link to C or C++ functions.
A few Lua quirks you should know to make reading Lua code eaiser:

• Line comments in Lua start with double-dash (−−)

• Block comments are between − − [[ and −−]].

• Lua’s syntax is free-form–whitespace is irrelevant in most circumstances.

• Use of semi-colon to terminate a statement is optional, though it can enhance readability.

• Single or double quotes can be used to frame a string. [[ and ]] will frame a multi-lined string.

You can read more about Lua syntax at http://www.lua.org . We’re linking with the base library,
the string library, and the table manipulation library at present. In debug builds of the library,
the debug library is also linked in. TLuaParticleSystem (p. 264) additionally links with the math
library.

5.2 Using Lua to Script Your Game


The examples that are covered in Why Use Lua? (p. 22) are entirely concerned with scripting
the overall game state flow and in-game events. But what if you want to use Lua to script more
interesting behaviors in your game? The Playground SDK™ fully supports arbitrary Lua threads
running at whatever rates you specify, which can control anything from game AI to animations.
The set-up requirements have been minimized wherever we can, but you should still expect to put
some effort into connecting your C++ code to Lua. The benefits are great, and the effort will be
worth it.
48 Lua

At the most basic level, you need to create a TScript-derived class with your added functionality.
Here is an example:

class MyClass Lua


{
public:
int MyMemberFunction( str param1, int param2 );
}

...

TScript * script = new TScript ;


MyClass * myClass = new MyClass ;

ScriptRegisterMemberDirect(
script, "LuaNameForMyMemberFunction", myClass, MyClass::MyMemberFunction );

script->DoLuaString(" a = LuaNameForMyMemberFunction( ’test param’, 4 ); ");

See how the constructor binds the C++ member functions directly to Lua functions. See Reg-
isterMemberDirect() for a list of the valid parameter types you can use. For an explanation of
TMessage (p. 294), see the advanced topic Sending Custom Application Messages (p. 111).

5.2.1 When to Yield

The Lua interpreter supports cooperative multithreading. In practice, this means that a script
that is going to persist needs to explicitly or implicitly yield periodically. The most basic yield
command is Yield, which returns control to the C++ code immeidately.
But that doesn’t take into account when your script may want to be run next; TScript (p. 389)
derives from TAnimTask (p. 191) so that it can resume running on a schedule. You can register
your TScript as a task, either at the TModalWindow (p. 298) level or at a global level in TPlatform
(p. 336). Conceptually the difference is that TModalWindow tasks are only executed when the
TModalWindow is the top modal window; another modal window will pause the tasks of any
windows beneath it. Note that the "Adopt" symantics (TPlatform::AdoptTask (p. 345)) means that
you are relinquishing control of the script. It won’t be deleted when it’s done executing, because it
never flags itself as "done" animating, but if the context that owns it is destroyed (i.e., the TPlatform
or TModalWindow), it will be deleted at that point.

5.2.2 Subclassing Existing Window Types

To subclass from an existing window type (for example, if you want to have a button that has
some custom behavior in it), all you need to do is be sure that your derived class calls the base
class for any virtual functions it overrides. For example, if you derive from TButton (p. 202) and
create a PostChildrenInit() call in your derived class, you’ll need to call TButtonPostChildrenInit()
to ensure that the base class gets properly initialized.

Navigating the Playground SDK


5.2 Using Lua to Script Your Game 49

5.2.3 Lua Dialog Creation Internals

Here is a brief description of the syntax of the internals of dialog-description Lua files. The first
thing to note is that instead of calling functions with ordered parameter lists, which is the norm in
Lua, we’re calling with the table (Lua’s map/hash/dictionary) syntax: Function{}. This allows us
to have both positional and named parameters.
At the most basic, in the Lua script you need to use the function MakeDialog:

MakeDialog Lua
{
...
}

Inside the body of MakeDialog is a list of (potentially nested) window creation commands. A
typical window will start with an image background:

MakeDialog Lua
{
Bitmap
{
image="background.png"
}
}

This is pretty simple so far. The Bitmap command will create a TImage (p. 249) window scaled to
the size of background.png. There are ways to override this, but we’ll get to that later.
Now say that you also want a button:

PropFont = { Lua
"fonts/prop.mvec",
15,
Color(0,0,91,255)
};

BasicButtonGraphics =
{
"controls/lozengeup.png",
"controls/lozengedown.png",
"controls/lozengeover.png"
};

MakeDialog
{
Bitmap
{
image="background.png", -- Note that this is a list, and needs commas

-- The optional mask tag says to use "backgroundmask.png" as the


-- alpha channel for the "background.png" image.
mask="backgroundmask.png",

Button
{
x=kCenter, y=-40, -- See below for coordinate options
name="button3", -- The name used to look up the button

Playground 4.0.17.1
50 Lua

font=PropFont, -- The button text font


graphics=BasicButtonGraphics, -- The button graphics
label="foo", -- The default button label
sound="click.ogg", -- Sound to play when button is clicked
rolloversound="over.ogg", -- Sound to play when button is rolled over
scale=0.7 -- scales the size of the button
}
}
}

There are several new things here worth mentioning. We’ve added a font for the button text, and
graphic images for the various button states. Note that the graphics entry is a table with three
items: The first is the "up" image, the second is the "down" image, and the third is the roll-over
image. You can skip the third image if the down and roll-over image should be the same.
The font itself is a table with three entries: The font filename (relative to the assets directory), the
font height in pixels, and the font color.
The x and y coordinates can be simple coordinates from the upper left corner of their window, but
there are also other convenient options:

• Positive x and y are normal positions.


• A constant, kCenter, added to x or y will position the window relative to the center (based
on width or height) in x or y directions. For example, kCenter+0 centers the window, and
kCenter+3 centers the window 3 pixels to the right of the center of the parent.
• You can subtract a value from kMax to specify the window origin from the right or bottom
of the parent window. x=kMax-20 means to put the window twenty pixels from the right
edge, for instance.
• You can set alignment values using the align tag and one (or two, added together)
of the window alignment constants. See Text and Window Alignment. (p. 128).
The alignment values change what edge or corner you’re specifying: If you say
align=kHAlignRight+kVAlignBottom, then x and y will specify the bottom right corner of
the window. Mixing alignment values with the kMax constant is supported, but kCenter
overrides any alignment setting for that dimension.
• Negative x and y are relative to the opposite edges. This feature is deprectated and will be
removed from Playground 4.1. Instead use offsets from kMax, or alignment settings. When using
"align" tag, this feature is disabled.

Now let’s add a text field:

... Lua
Text
{
x=0,y=kMax-80,w=kMax,h=-kMax, -- The entire dialog, minus the bottom 80 pixels
font=PropFont, -- The text font
label="This is text"
},

The x and y coordinates work the same for the text field as above. We’ve chosen not to name this
field, which is okay since it’s just static text (it will get a window id of -1). But we have two new

Navigating the Playground SDK


5.2 Using Lua to Script Your Game 51

fields: w and h for width and height. Similar to x and y, a positive number is a number of pixels.
In addition:

• A constant, kMax, specifies that the rectangle should grow to fill available space.

• A positive width or height grows from the right of or down from the corresponding position,
while a negative width or height grows the opposite direction.

• The kMax constant can be negated as well, filling to the left or up from the x,y coordinate.

5.2.4 Styles
Repeating information for each and every widget is tiresome and mistake prone. To address this,
there is a concept of a current style. It’s recommended that most features in your project are
defined using styles.

PropFont = { Lua
"fonts/prop.mvec",
15,
Color(0,0,91,255)
};

BasicButtonGraphics = {
"controls/lozengeup.png",
"controls/lozengedown.png",
"controls/lozengeover.png"
};

DefaultStyle = {
font=PropFont,
graphics=BasicButtonGraphics,
x=0,y=0,w=kMax,h=kMax
}

BottomEdgeButton = {
parent = DefaultStyle,
y=-40
}

BodyText= {
parent = DefaultStyle,
y=-80,h=-kMax
}

MakeDialog
{
SetStyle(DefaultStyle),
Bitmap
{
image="background.png",
SetStyle(BodyText),
Text
{
label="This is text that goes in the body"
},
SetStyle(BottomEdgeButton),

Playground 4.0.17.1
52 Lua

Button
{
x=kCenter, -- The y coordinate is set already.
name="button3", -- The name used to look up the button
label="foo" -- The default button label
sound="click.ogg" -- Sound to play when button is clicked
rolloversound="over.ogg", -- Sound to play when button is rolled over
},
TextEdit -- creates a user editable text edit field
{
password=true, -- "*" instead of letters to hide passwords
length=26 -- max characters user can type into edit field
ignore="#!@" -- ignore ’#’,’!’, and ’@’ if typed by the user
};
}
}

There are several new things in this example: The styles are also Lua tables, with one notable extra
field: "parent" refers to the parent of a style. When MakeDialog is looking for a property, it looks
first in the table passed to the creator function (e.g., Bitmap{}), and then in the current style, and
then in the parent style(s).
The current style only exists in the "scope" of the list it’s defined in.
So we start by setting the DefaultStyle, because that’s just a good habit to have. Next we set a style
for the BodyText, and the Text{} creator function suddenly gets much simpler. Finally we set the
style for the Button, and it also ends up simpler.
There are two notable advantages to styles: One is that you can apply one style to many widgets,
and then when you change the style it affects all of the widgets. Another is that you can then move
these styles to another file entirely and apply them to all of the dialogs in your entire project. See
the Lua command "require", which includes another Lua file in the current file.
If you want buttons that are radio or toggle style, you can specify those as follows:

... Lua
Button
{
type=kToggle,
graphics= {
"offImage.png",
"onImage.png",
"offRolloverImage.png",
"onRolloverImage.png"
}
},

-- Mark the start of a new radio group. Every radio button from this
-- tag to the next BeginGroup() will be in the same group.
BeginGroup(),

Button
{
type=kRadio,
graphics= {
"offImage.png",
"onImage.png",
"offRolloverImage.png",

Navigating the Playground SDK


5.2 Using Lua to Script Your Game 53

"onRolloverImage.png"
}
}

Playground 4.0.17.1
54 Lua

Lua is a language that’s designed to be easy to edit and to have flexible data representations.
As such, it makes a great place to put data that you need for your game. It’s easy enough to
understand that your game designers/level editors can easily tweak parameters for various levels.
If you have an in-game level editor, it might make more sense to have it save out XML, since then
it can read and write exactly the same file, as well as retain human readability.
On the other hand, if your game needs scripted actions to occur, scripting those actions in Lua is
very attractive. But how much Lua is appropriate? More the point, how much Lua can you use
and still expect to be supported by PlayFirst? The answer, approximately, is a lot—as long as the
usage falls into a few patterns:

1. Retrieving data. You can have as many Lua files containing game data as you want.
2. Game-play subroutines that execute and quit. This is the classic scripted action. When some
event in the game occurs, then you call a Lua function that determines what happens.
3. Simple animation behaviors. Animations in the Playground SDK™ are handled via Lua
scripts, and the animations can call very simple C++ functions or set Lua variables at specific
points.

The main game thread shouldn’t live in Lua—yet. There isn’t enough support for our engineers
to track what’s going on if there’s a problem that we need to diagnose. When would we be fixing
problems in your game? PlayFirst frequently assigns engineers to fix compatibility problems that
crop up on a system in our lab—if you can’t reproduce the problem on your system, how can you
fix it?
In addition, we’re missing one of the most important game development tools in Lua at the mo-
ment: A profiler. Lua is fast for a scripting language, but still much slower than C++. If a lot of
your game is written in Lua, you’ll likely eventually need to optimize it. The first step in optimiza-
tion should always be to profile, and we have no way to profile your Lua code yet.
One more problematic issue occurs when you end up with a stack that looks like: C->Lua->C-
>Lua and the Lua code tries to yield control back to C. The problem appears when your Lua code
calls a C function that then calls more Lua code that tries to yield. Since pushing a modal dialog
within Lua has an implicit yield, this happens more often than you’d expect. This won’t happen
in Lua code that doesn’t use Lua threads, but the Lua UI thread in the Playground SDK™ depends
on Lua threads to function, and the logical place for your game code to exist would be in the same
engine as the UI thread—and that would require you to yield execution from time to time for the
UI thread to function. We’re investigating Lua Coco to see if it will work with Playground on the
PC and Mac, which, if it works as advertised, will eliminate this issue. Again, stay tuned.
So, while we encourage you to use Lua for the three patterns listed above, we ask that the majority
of the game logic exist in C++ until our Lua tools improve.

Navigating the Playground SDK


5.3 How do I get Lua data in my C++ code? 55

5.3 How do I get Lua data in my C++ code?


Say you’d like to use Lua scripts to do some of your configuration, or you have some Lua code
that generates a table that you’d like to access in C++. How do you get to the data? Well, one way
is to use the Lua API described at http://www.lua.org, and there are some things that you will
have to do that way. But there’s an eaiser way: the Playground SDK™ has a number of simple
wrappers that allow you direct access to Lua data. The wrappers are very light in code impact,
but not heavily optimized.
The Lua object wrapper base class is TLuaObjectWrapper (p. 261), and it pulls the top object
off of the Lua stack and wraps it in a C++ structure. During the life of the TLuaObjectWrapper
(p. 261) object, the wrapped object is guaranteed not to be deleted by the Lua garbage collection or
reference counter. The TLuaObjectWrapper (p. 261) class can only perform basic operations on a
Lua object: Push it on the Lua stack, query whether it is a string or number, or attempt to convert
it to a string or number. The derived class TLuaTable (p. 269) is intended to manage and read a
Lua table.

Playground 4.0.17.1
56 Lua

Navigating the Playground SDK


Chapter 6

Particle System

6.1 Particles in a Scripting Language?

6.1.1 A Particle "Shader Language"


The Playground SDK™ particle system uses Lua as its definition language. On learning this, the
first question that comes to any developer’s mind who has been around the block more than once
is often, "Particles need to be driven by very fast code—how can one be driven by a scripting lan-
guage?" Lua is possibly the best data-definition language in common use today, and it’s designed
to be embedded. It’s quite fast, but it’s still not as fast as some tightly written C++ code. So yes, if
the particles were simulated in Lua, it would be nowhere near as fast as a particle system written
in C++. And with particles, you really want them to be as fast as possible, so you can support as
many particles as possible.
So what if you just use Lua to define the structures you need for the particle system? That way
you get to lean on the user-friendliness and interactivity of a scripting language, while still taking
advantage of the speed of C++ by having the actual particle processing done in the faster language.
That’s what we’ve done: The Lua code defines a number of operations that are then performed in
a tight C++ loop on each particle. In some sense this is similar to writing a vertex or pixel shader,
only for particles. Basing the language in Lua allows us to take advantage of the existing scripting
engine in Playground.

6.1.2 Playing With Particles


The easiest way to get a feel for a new system is to see it in action. Let’s start with a very simple
particle script:

--------------------------- Lua
-- Initialization phase

-- Set the particle texture


SetTexture("star");
58 Particle System

-- Initialize the raw particles--do this last in the Initialization Phase


SetNumParticles(1);

---------------------------
-- Action phase

-- Create an initial particle


CreateParticles( 1 );

So far our particle system isn’t very interesting. It creates one particle in the middle of the screen
that just sits there. Let’s make it fall:

--------------------------- Lua
-- Initialization phase

-- Allocate a velocity particle property as a Vec2


pVelocity = Allocate(2) ;

-- Set the particle texture


SetTexture("star");

-- Initialize the raw particles--do this last in the Initialization Phase


SetNumParticles(1);

---------------------------
-- Action Phase

-- Animate the velocity


pVelocity:Anim( pVelocity + fTimeScale(Vec2(0,800)) );

-- Animate the position


pPosition:Anim( pPosition + fTimeScale(pVelocity) );

-- Create an initial particle


CreateParticles( 1 );

There are two new things here. First, we’re allocating a velocity. While we can move the parti-
cle without giving it a velocity (by adding a constant value to the pPosition property), it’s more
interesting if each particle can keep track of a velocity value.
Second, we add two animation lines. These add actions to the particles that occur in declaration
order to every particle on every TLuaParticleSystem::Update() (p. 265) call. Let’s break down one
of these lines more carefully:

-- Animate the velocity Lua


pVelocity:Anim( pVelocity + fTimeScale(Vec2(0,800)) );

Translated into English, this says: On each step of the animation, assign the property pVelocity the
value (pVelocity + fTimeScale (p. 139)(Vec2 (p. 139)(0,800)). The part with fTimeScale (p. 139)(
Vec2 (p. 139)(0,800)) says to scale the value Vec2 (p. 139)(0,800) by the current elapsed time, so you
can give it a number in units/second and it will scale the value appropriately.
Similarly, the next line adds a time-scaled pVelocity to pPosition. What is a pPosition? I’m glad
you asked...

Navigating the Playground SDK


6.1 Particles in a Scripting Language? 59

6.1.3 Particle Properties

Each particle in a system has a number of programmable properties. Each property is a set of
one to four floating point values. The default particle type is a T2dParticle (p. 171), which has a
number of innate properties, listed below along with their Lua names and sizes:

• A 2d Position (pPosition, TReal[2])

• A 2d Up-vector where 0,-1 make a particle "upright" (pUp, TReal[2])

• A scale (pScale, TReal[1])

• An RGBA color (pColor, TReal[4])

• A frame (pFrame, TReal[1]) for use with animated particles.

The actual texture isn’t a particle property in the same sense, in that all of the particles in a system
share the same texture. The texture can be a TAnimatedTexture (p. 182) to allow for animated
particles, but it has to be one texture shared by all the particles due to the nature of the rendering.
The basic idea is that the particle script sets down how to initialize these properties for each particle
as it’s created, and then how to animate these properties on each frame.

6.1.4 The Particle Lua File

The order of operations in a typical particle configuration file is:

1. Create any custom particle properties.

2. Set the particle texture and blend mode.

3. Set the number of particles in the system.

4. Set up the particle initializer functions.

5. Set up the particle animation functions.

6. Define an Update function that creates particles.

The order of the first three operations above is strict; the rest are just by convention. In addition to
the innate properties of a 2d particle, you can create custom properties and use them however you
like. A common property to create would be a particle velocity, for instance, to give each particle
its own motion. Another common property is an age: Some animated effects rely on a particle’s
age to calculate, so that a particle can, for example, fade from one color to another.
But not all particle systems need velocity (a set of twinkling stars wouldn’t move, for example),
and simple particles don’t need an age, so you can add just the extra values you need. When you
do need a custom particle property, you can name it however you like—this is Lua, after all.

Playground 4.0.17.1
60 Particle System

6.1.5 Operations in the Particle Script


When you create a particle property like pVelocity, you get an object instance that you’ve seen do
a few things. First, it can add particle initialization functions using the :Init() member function.
Second, it can add particle animation functions using the :Anim() member function. The third
thing that it does is a bit more subtle: When you put it in an equation, it returns an object that
references the particle property that it represents.
Let’s bring back the :Anim example:

pVelocity:Anim( pVelocity + fTimeScale(Vec2(0,800)) ); Lua

The equation pVelocity = pVelocity + f TimeScale(Vec2(0, 800)) is then executed every frame. This
is a standard equation that applies gravity to every particle.

6.1.6 A More Interesting Example


Here’s an example from the sample application that includes a data source:

-- ------------------------------------------------------------ Lua
-- Initialization phase

-- Define our custom particle properties


pVelocity = Allocate(2) ; -- Allocate a Vec2 velocity member
pAge = Allocate(1) ; -- Allocate a TReal age member
pSpin = Allocate(1); -- Allocate a TReal spin member
pSpinSpeed = Allocate(1); -- Allocate a TReal spin member

Here we create more particle members; first the familiar pVelocity, and then three others. pAge
keeps track of the age of a particle, pSpin keeps track of an initial orientation, and pSpinSpeed
keeps track of a particle’s rotational velocity. These elements are each unique for each particle in
this particle system.

-- dLocus is a data source. The new FluidFX 2.0 defines dLocus for us, Lua
-- but in case you want to load this particle system in a context
-- where you have no data source defined, this code will give dLocus
-- a default value.
if not dLocus then
dLocus= Vec2(0,0) ;
end

In the sample application we add a data source to the particle system and call it dLocus. We still
want the sample to work in FluidFX, however, since we don’t want to give up the ability to edit
the particle system in real time, so we add these lines of code to conditionally define dLocus to
just be Vec2 (p. 139)(0,0) when it hasn’t been defined already.

-- Set the particle texture Lua


SetTexture("star");

-- Set the blend mode


SetBlendMode(kBlendNormal);

-- Set the size of the particle pool.

Navigating the Playground SDK


6.1 Particles in a Scripting Language? 61

SetNumParticles(400);

Here we’re setting the blend mode, though it’s not necessary since kBlendNormal is the default.
See the section on TRenderer::SetBlendMode() (p. 377) for more information on blend modes.
We’re also setting the number of available particles in the pool to a higher number so that we
don’t run out too quickly.

-- ------------------------------------------------------------ Lua
-- Action Phase

pPosition:Init( fPick( Vec2(-10,0), Vec2(10,0) ) + dLocus );

-- Pick a velocity from a range


pVelocity:Init( fRange( Vec2(-200,-300), Vec2(200,120) ) );

Here we set the initialize function for pPosition to select a point 10 pixels to the left or 10 pixels to
the right of the mouse, which is retrieved from the data source dLocus. Then we select a velocity in
the given range: the fRange() (p. 138) function will take its arguments and return values randomly
within the range in each dimension. So for a Vec2 (p. 139)() with the parameters above, it will
return -200...200 in the X direction and -300...120 in the Y direction.
The function fRange() (p. 138) will work with scalars, Vec3() (p. 139) and Color() (p. 143) values
similarly.

-- Start color (tint) off as white (natural color of image) Lua


pColor:Init( Color(1,1,1,1) );

-- Start scale out as 0.5


pScale:Init( 0.5 );

-- Start age as 0 milliseconds


pAge:Init(0);

These are simple enough: Set the initial pColor to a constant white color value, the initial pScale
to a constant 0.5, and the initial pAge to 0 seconds.

-- Start initial rotation as a random angle Lua


pSpin:Init( fRange( 0, 2*3.1415927 ) );

-- Start spin velocity random from -10 to 10


pSpinSpeed:Init( fRange( -10, 10 ) );

Here we’re again using fRange() (p. 138), this time with scalars, to initialize the particle parameters
with values within a range.

-- ------------------------------------------------------------ Lua
-- Particle Parameter Animation Functions

pVelocity:Anim( pVelocity + fTimeScale(Vec2(0,400)) );


pPosition:Anim( pPosition + fTimeScale(pVelocity) );
pScale:Anim( pScale + fTimeScale(1) );

First we see the familiar velocity and position equations. Then we see something new: Animating
the scale value. This equation will add one to scale per second: fTimeScale() (p. 139) again scales

Playground 4.0.17.1
62 Particle System

its parameter to the fraction of time that’s passed, so after a second pScale will go from 0.5 to 1.5.

pAge:Anim( pAge+fAge() ); Lua


pColor:Anim( fFade( pAge,Color(1,1,1,1), 500, Color(1,0,0,1), 1000, Color(1,1,1,0) ) );
pSpin:Anim( pSpin + fTimeScale( pSpinSpeed ) );
pUp:Anim( f2dRotation( pSpin ) );

Three new functions here. First is fAge() (p. 135), which takes no parameters. Instead it just returns
the amount of time in the current update step in milliseconds, so with the equation above the pAge
parameter will always equal the particle’s age in milliseconds.
The second new function is fFade() (p. 137), which performs a linear interpolation between multi-
ple values. The first parameter to fFade() (p. 137) is the current age in milliseconds, the next is the
initial value, and following that are pairs of deltas and values to interpolate between. In this case,
it starts with Color(1,1,1,1) (p. 143), and then over the next 500ms interpolates to Color(1,0,0,1)
(p. 143), then over the next 1000ms interpolates to Color(1,1,1,0) (p. 143). There isn’t a limit to how
main pairs you can add to this sequence, as long as you end with a value and not a delta.
The next line calculates a new pSpin value by using fTimeScale() (p. 139) to increment pSpin by
the value of pSpinSpeed once per second. The last new function is f2dRotation() (p. 135), which
produces a 2d vector based on a value in radians, which is what we’ve been calculating in pSpin.

Anim( fExpire( fGreater(pAge,2500) ) ); Lua

Here’s a different concept: A function that doesn’t return a value. Each of the functions so far has
been implicitly assigned to a particle parameter. This one just executes its function and ignores
any return value.
Which is fine, because it is a function with a side effect. From the inside of the parenthesis:
fGreater() (p. 137) returns true (a non-zero value) if its first parameter is greater than its second.
Then the function fExpire() (p. 136) tests its parameter, and if true, flags the particle for destruction.
In other words: If the particle’s age parameter exceeds 2500ms, kill it.

-- A global variable that we can set from outside Lua


gActive = 1

-- A function to run as we’re executing


-- seconds - how many seconds have elapsed
function Update(seconds)
if gActive>0 then
-- Create 10 particles per second
CreateParticles( seconds * 10 );
end
end

What’s all this then? OK, more fun stuff. First, we’re setting a global Lua variable. There’s nothing
magical about this—nothing you can’t read about in a Lua manual, anyway. We’re just setting
the variable gActive to a value of 1. Thing is, from C++ you can use TScript::SetGlobalNumber
(p. 395)("gActive",0) to turn of new particle generation without stopping the animation.
It’s important not to add any more animation or initialization rules in the Update() function. Every
time you call Anim() or Init() it adds another animation or initialization function to the particle
processing chain, so if you add additional functions in Update() the processing chain will get
longer and longer, and your particle processing will get slower and slower.

Navigating the Playground SDK


6.1 Particles in a Scripting Language? 63

Playground ships with a particle editor to help test and refine your particle systems. For informa-
tion about the particle editor see FluidFX 2.0: Interactive Particle System Editor (p. 90).

6.1.7 Advanced Tip: Arithmetic


In addition to using the addition and multiplication operators in Lua to add together particle
properties and function results, you can also use numerical constants with addition, multiplica-
tion, subtraction, and division. It’s important to note that if you use a constant, though, it needs to
come after the particle property or function result that you’re modifying.

pSpin:Anim( pSpin + fTimeScale( pSpinSpeed*0.5 ) ); Lua

This code will take the value in pSpinSpeen and multiply it by the constant 0.5 before running it
through the fTimeScale function. In this case, you could just as easily have written:

pSpin:Anim( pSpin + fTimeScale( pSpinSpeed )*0.5 ); Lua

But this is an error:

-- ERROR: Lua can’t handle multiplying a number by a USERDATA in this case Lua
pSpin:Anim( pSpin + fTimeScale( 0.5*pSpinSpeed ) );

You can also multiply vectors by a scalar:

pVelocity:Anim( pVelocity + fTimeScale(Vec2(0,250)*10) ); Lua

Obviously, in this case you could simply change the constant 250 to 2500, but if you’ve assembled
a vector from several values and want to scale the entire result, you can do that.
The order of operands is important here: It always needs to be Vector∗Scalar, even if the scalar is
already a Lua userdata that represents a value.

Playground 4.0.17.1
64 Particle System

Navigating the Playground SDK


Chapter 7

Localization and Web Versions

7.1 The String Table


Playground SDK™ applications rely on a single XML file that contains all of the strings used in
the application. This XML file is easily modified by translators for localization. The XML file is
stored in the Microsoft Excel XML save format, which can also be edited using OpenOffice Calc.
When an app launches, it automatically attempts to load in a string table from the assets directory.
Note that the file will contain other XML that supports the Excel save format, and the Cell and
Data tags can contain attributes.
A single string mapping looks like:

<Row> XML
<Cell><Data>title</Data></Cell>
<Cell><Data>My Game Title</Data></Cell>
</Row>

The file is expected in the root of the assets folder, and should be called strings.xml.
See TStringTable (p. 427) for more information. The global string table is available from TPlat-
form::GetStringTable() (p. 341).
66 Localization and Web Versions

7.2 Quick and Easy Web Games


Running your game as a web application with Playground is simple - you don’t even need to
recompile your game. For more information about how to run your game as a web applicaion,
please read the axtool: Testing Your Game in a Browser (p. 105) section under the Playground
Utilities (p. 71) section.
However, there are a few things to keep in mind when developing the web version of your game:

• It is important that your web version not have a completely functional game executable. It
is not enough to remove data from your game and use the same executable as the download
version. This would allow users to simply copy over their web version executable and un-
lock a full version of the download game. Please make sure to limit the functionality of your
web game with code changes as well as data changes.
• Playground will automatically resize your game to fit in whatever window the website puts
your game in. An average window size is 480x360, though some sites will use smaller win-
dows and others will use larger windows. You do not have to do any extra work to get
your game to show up properly in that size window. However, because your game will be
running in a smaller window, you may want to shrink your assets and then scale them up
dynamically in-game (i.e. using the scale parameter in DrawSprite). For example, if you
shrink your assets by 25% and then scale them up in code by 25%, your game will run in a
600x450 window with no visual loss. If you do the same thing by 40%, your game will run
in a 480x360 window with no visual loss. Shrinking your assets in this manner can help you
reduce the size of your web game download.
• To implement the "Download" button functionality, you need to do two things:
– The download URL will be available in TPlatform::GetConfig( TPlat-
form::kDownloadURL ).
– To launch the download page, use TPlatform::OpenBrowser() (p. 341).
• If your game uses the hiscore system, it is important that your game be allowed to run in
"anonymous" hiscore mode. The command line to main() will contain a -anon # parameter,
which you need to parse. If # is 0, you can run the full hiscore system. If it is 1, you need to
run anonymous mode. If it is 2, you need to run in local high score mode.
• If your game displays the PlayFirst logo anywhere aside from the splash screen, you need
to look for the "-hidelogo 1" parameter being passed into the command line. If this value is
present, you need to hide these logos on every screen except the main menu screen, where
this logo is allowed to remain.
• Avoid saving data between sessions. The TPrefs (p. 352) and TPfHiscores (p. 325) construc-
tors have optional arguments that will disable session data saving.
• You will likely need to revisit some of your UI and increase the size of text to make sure it is
readable in the small 480x360 windows.
• If your game uses the PlayFirst Hiscore System (p. 30), you will want to add separate hiscore
modes for your web game, but make sure the web game can still view the downloadable
game modes hiscores when connected to the global hiscore system.

Navigating the Playground SDK


7.2 Quick and Easy Web Games 67

• In order for your game to be accepted for use on MSN, you need to:
– Implement all the functionality appropriate to your game described in gamestate.h. See
some examples in the sample application.
– Submit two builds of your game, one with cheats on, one with cheats off, so it is easy to
test the web functionality.
– Detect if the game is an MSN build by checking for the string "msn" in TGameS-
tate::GetState(TGameState::kSystemMode).
– When in MSN mode:
1. Instead of calling TPlatform::OpenBrowser() (p. 341) to launch a download, you
need to call TGameState::SetState( TGameState::kDownloadButton ).
2. Remove all "Try Again" buttons from your game - at the end of your game the only
option should be to quit.
3. Because MSN has their own high score system, you should not go to the high score
screen in game. Instead, you should either go to an upsell screen if the user presses
the high score button, or you should remove the high score buttons from your
game.
4. Your game score needs to be sent to TGameState::SetState( TGameState::kScore,
score ) at least prior to the end of the game, but more often is better.
5. Whenever a game ends (either by being over or by the user quitting the
game in progress), call TGameState::SetState(TGameState::kGameOver). At this
point, MSN zone may switch to an upsell screen and then redirect your game
to either go to the main menu, or possibly restart the current game mode
(you need to poll the TGameState::QueryRestartMode() (p. 243) and TGameS-
tate::QueryJumpToMenu() (p. 244) functions to determine whether or not to do
this).

• In order for your game to be accepted for use on the AOL.com® site, you will need to do the
following:
– Detect for the string "aol" in TGameState::GetState(TGameState::kSystemMode), which
means you are running an AOL service build.
– If you are in AOL service mode, you need to:
1. Display the AOL logo on the splash screen. An AOL logo has been included with
your Playground delivery, and is located in the addons/webgames/AOL folder
(two logos have been provided, one that is baked onto the PlayFirst splash screen,
and one that is seperate - you can use whichever file is easier for you). If you are
using the DisplaySplash() (p. 144) Lua function to display your splash screen, you
can put logic in the Lua script to determine which splash screen to display. For in-
structions on how to use an overlay with DisplaySplash, refer to the DisplaySplash
documentation.
2. Only have download buttons on 2 screens: the main menu, and the upsell screen.

Playground 4.0.17.1
68 Localization and Web Versions

Navigating the Playground SDK


Chapter 8

Game Footprint

8.1 Smaller is Better


When shipping a downloadable game, the smaller it is, the more likely it is that people will suc-
cessfully download it. More than that, bandwidth also costs money, and though you may not see
that cost directly, a larger footprint may mean your game gets promoted less than a game with an
equivalent conversion rate but with a smaller footprint.

8.2 Shrinking Your Game


There are a number of strategies you can use to reduce footprint without reducing perceived con-
tent. Here we’ll go into a few of them.

8.2.1 Reducing PNG Footprint


PNG32 files offer less-than-ideal compression for images that have photographic detail or gradi-
ents, but sometimes you need a mask layer for an image. There are two common ways to approach
this problem.
First, you can run your PNG files through a conversion script that splits the RGB layers from the
mask layer, and then place the RGB layers into a much-better-compressed JPG file, leaving the
mask in a monochrome PNG8 file. The key advantage of this technique is that you get a high
quality image attached to a lossless mask at a much better compression ratio. Masks tend to
compress especially well in PNG. The disadvantage of this technique is that your source code (or
at least Lua code) needs to change to load the masks–it’s not automatic.
Second, you can run your PNG files through a conversion process to convert them to PNG8-with-
transparency. This is a bit more difficult than it seems, because most popular tools don’t correctly
read files saved in this format. Adobe Fireworks is one of the few that can successfully read
and write this format, though there is also a free command line tool called pngquant that we use
at PlayFirst to reduce PNG32 to PNG8 files. The advantage of this conversion is that your files
70 Game Footprint

become 1/4 of their previous size, with no change of source code; the disadvantage that they’re
reduced to an 8-bit palette, so if the image consists of many different color gradients, it may hurt
image quality.
It’s easy enough to experiment and figure out which of these two techniques works with each of
your image types.

8.2.2 Small Files Can Be Smaller!


Just because you have a directory of 2-4k PNG files that together add up to a megabyte, don’t
assume that they’re already small and shrinking them won’t help. Files like that are almost always
going to compress well to PNG8-with-transparency, as described above. And we’ve frequently
pulled an extra 768k out of one of those megabyte-sized folders, even though the individual files
are small.

8.2.3 Reducing JPEG and OGG Footprint


JPEG and OGG/Vorbis files each have variable compression ratio. During development it’s tempt-
ing to save each of these files at a high quality, but when it comes time to ship and you’re looking
for some extra room, it pays to experiment with higher compression settings. Due to the nature
of the lossy compression of both JPG and OGG/Vorbis, some files will compress much better than
others with no perceivable loss in quality.

8.2.4 Reducing Image Size in Web Games


If you’re producing a Web version of your game, you might want to consider reducing asset di-
mensions to reduce your footprint even more. While the game will work just fine with original
assets, and will automatically shrink down to the smaller dimensions required by web sites, this
means that you’re sending 800x600 images to the site even though it’s only displaying them at
400x300 or 640x480.
One easy way to reduce asset size when the assets are specified in a Lua Bitmap{} call is to add an
appropriate "scale" parameter to Bitmap{}. Say you’re reducing your assets to 640x480. 800/640 =
1.25, so if you add a scale parameter of 1.25 to each bitmap you downsize, the asset will display
at the same logical size in the game. If the web game is actually displayed at 640x480, it will end
up displaying the resulting bits at 1:1; if it’s displayed smaller (down to 400x300 on some sites)
then it still ends up being scaled down, but not as much as if you were sending original 800x600
artwork.

Navigating the Playground SDK


Chapter 9

Utilities

9.1 FirstStage: The Playground Resource Editor

Figure 9.1: FirstStage Logo

9.1.1 Welcome to FirstStage


FirstStage is a RAD editor designed specifically for the Playground SDK which allows you to
design window layouts for uses such as dialog boxes, main menus, etc.
By simply clicking on window types on the toolbar, you can rapidly design complex window
layouts which would take much longer if editing the Lua files by hand.
Using FirstStage, you can create windows with buttons, images, text fields, text input boxes, and
even custom windows.
72 Utilities

9.1.2 Getting Started


If you are not already running FirstStage, you can find the program in the bin folder of the Play-
ground SDK. It is called FirstStage.exe.
When you run FirstStage, you will be presented with a screen similar to this one.

Figure 9.2: FirstStage Default Screen

If this is the first time you have run FirstStage, then you will be presented with a folder selector
asking you to select your game folder. Go ahead and point it to your game folder. For the skeleton
project, this is usually

[PlaygroundSDK folder]\skeleton.

Once this is done, it will give confirmation of the assets folder in the output window. Check that
it is correct before you proceed.

9.1.3 Your First Dialog


You will notice that by default, there is already some code in the Lua script editor. This is the basic
template code that all window layouts use. When we create new window controls, the code for
them will appear inside the MakeDialog block.
Let’s go ahead and start building a dialog box.

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 73

PLEASE NOTE: For this example, we are going to be using assets from the skeleton folder which
is included with the Playground SDK distribution. You are free to substitute your own assets in
this example if you already have them prepared.
If you want to follow this example and use the skeleton’s assets, make sure your game folder is
pointing to the skeleton application game folder by selecting Extra/Select game folder... in the
menu.
Click on the Bitmap button in the tool bar. An image selector dialog will appear with the game
folders on the left and thumbnail pictures of your assets on the right.
Go into the backgrounds folder and select dialog.png. Your cursor will change and there will be a
rectangle that follows your mouse cursor. This rectangle represents the size of the image.
Move the box until it is properly on screen and click the left mouse button to place the bitmap. A
dialog box will then pop up asking you to enter a unique name for this new bitmap. Let’s just call
it TestWindow.
Press ok and you see your bitmap appear on screen. This bitmap will be our background for the
dialog box.
If you move your mouse over the bitmap, you will see that it has a yellow focus rectangle around
it. Select the bitmap by clicking on it. It should now have a red box surrounding it indicating
that it has been selected. You should also notice that the bitmap code in the Lua window has been
highlighted. This is to show you what code is involved in making this window.
Next, let’s add some text to the window.
Click on the Text tool in the tool bar. The cursor should change to a text image.
Move the cursor to somewhere inside your bitmap and click and drag out a box. This will be the
dimensions of our new text box.
When you release the mouse, a dialog box will appear.
Set the ID Name to gTextBox.
Set the label to HelloMsg. The Label is actually a unique identifier for the translations file which
we will explain in more detail below.
Click on the middle button in the Text Alignment and then press OK.
One great feature about the Playground SDK is that it can do automatic translating of strings
for you. This means that when you create a text control in FirstStage, you also have to add a
translation entry for the new string. Luckily, FirstStage makes this process easy by displaying a
translations editor each time you create a control that has text. You will notice that a new entry
has been created and selected in the translations table which corresponds with your new text. Go
ahead and change the text in the translations column to "Hello There" (without the quotes) and
press enter. Then press the OK button to save your new entry.
Your new text box should appear. If you move your mouse over the text area, a highlight rectangle
should appear around the area that you specified for the text.
You should have something similar to this on screen:

Playground 4.0.17.1
74 Utilities

Figure 9.3: Basic Dialog

Let’s add some more stuff!!


A dialog box wouldn’t be complete without an OK button.
Click on the Button tool.
The button control dialog box will pop up asking for some details.
Set the ID name to gDlgOK.
Set the label to OK. This label already has an entry in the translation file so you won’t be prompted
to add a new entry.
Select the "default" checkbox.
We will keep the default style button so just press the OK button.
You should now see a box following your mouse pointer around. This is the dimensions of your
new button. Use this as a guide to where you want to place the button.
Click the left mouse button to place your new button on your dialog.
You should now see a button appear at the bottom of your dialog.
If the button isn’t located in the right place, hover over the new button until it is highlighted and
then click your left mouse button. The highlight rectangle should turn red.
Now click and drag with your left mouse button to reposition the button to where you want it.
The end result should look like this:

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 75

Figure 9.4: Dialog with button

You have just created your first dialog box. Click on the Save button and save your new dialog as
my_dialog.lua.

9.1.4 The Main Toolbar

Figure 9.5: FirstStage Toolbar

Here is a brief description of what each tool button does:

Figure 9.6: New Button

This will create a new blank script. The current list of scripts can be seen in the Scripts window.

Playground 4.0.17.1
76 Utilities

Figure 9.7: Open Button

This will load a script from disk and add it to the Scripts window.

Figure 9.8: Save Button

This will save the currently selected script to disk.

Figure 9.9: Run Button

If you type in any changes in the script window, you will need to press the Run Script button to
refresh the changes in the visual display.

Figure 9.10: Undo Button

Will undo any changes made to the script.

Figure 9.11: Redo Button

Will re-apply any changes that were made to the script.

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 77

Figure 9.12: Select Button

FirstStage can be in either of two states when building a dialog. Firstly, there is Select mode which
allows you to create new windows and move windows. The other state is Scale Mode which
allows you to scale the size of any selected windows.

Figure 9.13: Scale Button

If you need to change the size of a window control, like an image, click the Scale Mode button,
then select the window(s) that you want to resize, then click and drag the left mouse button to
resize the window.

Figure 9.14: Add Button Control Button

If you want to add a push button, a check box, or something similar use the Add Button tool. For
more information on the use of Add Button, see Add Button Control (p. 79).

Figure 9.15: Add Bitmap Control Button

Most dialog boxes start with a bitmap as the background and then you layer buttons and text
boxes on top of the bitmap. So, adding an image can be seen as the first step in building a new
dialog. For more information on the use of Add Image, see Add Bitmap Control (p. 80).

Figure 9.16: Add Text Control Button

Playground 4.0.17.1
78 Utilities

You use a static text box when you want to display information to the user. Text is automatically
translated through Playground SDK, so all you need to do is enter the text ID and then fill in the
translation XML file with the correct translation. For more information on the use of Add Static
Text, see Add Static Text Control (p. 81)

Figure 9.17: Add Text Edit Control Button

If you want the user to be able to type some input on the screen, use a Text Edit control. You
can adjust a lot of parameters for the use of the Text Edit when placing the control. For more
information on the use of Add Text Edit, see Add Text Edit Control (p. 82).

Figure 9.18: Add Custom Window Control Button

Custom windows are the basic building blocks of any Playground derived game. In C++, all of
your game code resides inside a custom window (a TWindow (p. 496)) so that it can be visual-
ized on screen. Using the custom window tool, you can define the size and position of a custom
window which can later be referenced inside your game. For more information, see Add Custom
Window Control (p. 84).

Figure 9.19: Toggle Grid Display

Grid snapping is very useful when you have a lot of controls on your screen and you want to
align them so that it looks neat and professional. Pressing the Grid Snapping button will toggle
the use of grid snapping on/off. If you want to adjust any aspect of the grid snapping properties,
for instance the grid size, just right click the Grid Snapping button and the Grid Properties dialog
will be displayed. For more information on the grid properties, see Grid Properties (p. 85).

Figure 9.20: Load Background Button

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 79

To change the background of the screen, click the Bkg tool button. You will be asked for a valid
bitmap. Bitmaps can be any JPG or PNG file. To remove the bitmap from the screen, go to Extra/-
Clear Background.

Figure 9.21: Help Button

Clicking this button will display the help that you are reading now.

9.1.5 Add Button Control

Figure 9.22: Add Button Control Button

If you want to add a button to your screen, press the Button tool. You will be presented with the
button properties screen.

Figure 9.23: Button Control Properties

Playground 4.0.17.1
80 Utilities

The ID name is a unique name to give to this new control so that Lua can differentiate between
the different windows. Typical IDs are names like gOkButton, gFullScreenCheckBox, etc.
The Label is the text identifier for this label. Common identifiers can be "OK", "Cancel", "Hel-
loMsg", etc. If the identifier does not exist in the translations file, you will be presented with the
translations editor once you hit ok. At that point, you can type in the English equivalent for your
identifier. See The Translations Editor (p. 88) for more information.
The Close Modal checkbox will tell your game that you want to close the parent dialog when the
window is closed.
The Default checkbox will tell the game that this is the default button.
The Cancel checkbox will tell the game to abort the window.
The Style drop down list holds a list of all the global styles for this Lua file. Pick a style that
suites the type of button that you want to create. Commonly used styles are "ButtonStyle" and
"LongButtonStyle". You can make your own custom button styles which will also show up in this
list.
Press the OK button once you have filled in the details.
As mentioned, you wil be taken to the translations editor if your label doesn’t already exist.
The cursor will then change to indicate that you are in the Add Button mode. Move your mouse
to where you would like to place your button. Use the box outline that is following your mouse as
a guide to where you would like to place your button.

9.1.6 Add Bitmap Control

Figure 9.24: Add Bitmap Control Button

Bitmaps are very important to the look and feel of your dialog. Typically, you would use a bitmap
for the background of your dialog.
To place a bitmap onto the canvas, first select the Bitmap tool button.
You will be presented with an image selector window. Use the folder tree on the left to navigate
to your image. If your folder is not in the tree list, then you possibly may not have configured
FirstStage to be pointing to your game folder. Use the menu option Extra/Select Game to Modify...
to change to the proper game folder and try again. Select the image you want to use and press OK.
Once you have selected your bitmap, move your mouse around the screen. You will notice that the
mouse cursor has changed to a bitmap icon and there is a rectangle following your cursor. This
rectangle represents the dimensions of your new bitmap. You now have an idea how big your
bitmap will be on screen.
At this point, you have two options:
1. If you are happy with the size and position of the bitmap on screen, then press the left mouse

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 81

button to place your new image.


2. If on the other hand the image is too big or too small, you can hold down the control key and
then click and drag a new size for your bitmap. When you are dragging out a size, you will notice
that the aspect stays constant. This is because images scale equally in both dimensions. Once you
are happy with the new size of your image, release your mouse button to place your image.
You will now be presented with the bitmap properties dialog:

Figure 9.25: Bitmap Control Properties

You only have one parameter that you need to fill in which is the Name for this image. Type in a
unique name for the image and press OK to see your image on screen.

9.1.7 Add Static Text Control

Figure 9.26: Add Text Control Button

Text boxes are great for displaying information to the user. The text displayed in a text box is
automatically translated via Playground into the correct language.
To create a text area on screen, click on the Text tool button. The cursor will change to indicate you
are in this mode.
Next, with your left mouse button, click and drag out a box where you want your text to be
displayed.
You will then be presented with the Text Properties dialog:

Playground 4.0.17.1
82 Utilities

Figure 9.27: Text Control Properties

The ID name is a unique name to give to this new control so that Lua can differentiate between
the different windows. Typical IDs are names like gTextBox, gInfoBox1, etc.
The Label is an identifier into the translations file for the text you want displayed. See The Trans-
lations Editor (p. 88) for more information on the translation file editor.
The Text Alignment is where you want the text displayed in relation to the boundaries of your box
dimensions. Use the grid of buttons to pick how you want your text aligned. The top left button
will mean that your text is aligned to the top left of your text box. The middle button would mean
your text is aligned to the middle of your text box, etc.
Press the OK button to see your new text box on screen.

9.1.8 Add Text Edit Control

Figure 9.28: Add Text Edit Control Button

A TextEdit control is typically used to allow the user to type a response for use in game. A typical
example is a user’s name or password.

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 83

To create a text edit area on screen, click on the TextEdit tool button. The cursor will change to
indicate you are in this mode.
Next, with your left mouse button, click and drag out a box where you want your input box to be
displayed.
You will then be presented with the TextEdit Properties dialog:

Figure 9.29: Text Edit Control Properties

The ID name is a unique name to give to this new control so that Lua can differentiate between
the different windows. Typical IDs are names like gPasswordInput, gUserNameInput, etc.
The Label is the default text that should be displayed in the edit field.
The Length is the maximum number of characters that can be entered.
The Ignore chars is a list of letters that you do NOT want the user to be able to use.
The Password entry checkbox can be set if you want the user’s typed text to be masked for privacy.
The Text Alignment is where you want the text displayed in relation to the boundaries of your box

Playground 4.0.17.1
84 Utilities

dimensions. Use the grid of buttons to pick how you want your text aligned. The top left button
will mean that your text is aligned to the top left of your text box. The middle button would mean
your text is aligned to the middle of your text box, etc.
Press the OK button to see your new TextEdit box on screen.

9.1.9 Add Custom Window Control

Figure 9.30: Add Custom Window Control Button

Custom windows are used as a canvas for your TWindow (p. 496) derived classes in your game.
You need to create a custom window to be able to see your game on screen.
Click on the custom window button and left click and drag out a box on screen in the position and
size that you want for your custom window.
You will then be presented with the Custom Window Properties dialog:

Figure 9.31: Custom Window Properties

The Class name is the name of your c++ TWindow (p. 496) derived class that you have defined in
game.
The Window Name is the unique ID that you want to give to this window.
Press the OK button to add your custom window.

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 85

9.1.10 Grid Properties

Figure 9.32: Grid Properties Button

The grid snapping properties can be accessed by right clicking the Grid tool button in the tool bar
or by selecting Extra/Change Grid Properties... in the menu.
The following dialog box will be displayed:

Figure 9.33: Grid Properties Dialog

The Enable Horizontal Snapping checkbox allows you to enable/disable snapping in the hori-
zontal direction. The text field following this option is the distance in pixels between each column.
The Enable Vertical Snapping checkbox allows you to enable/disable snapping in the vertical
direction. The text field following this option is the distance in pixels between each row.
The Window Snapping Alignment is the edge that you which your windows to be snapped to.
By default, windows will snap to grid lines using the top left edge of the window.
The Display Snapping Grid on Screen checkbox allows you to toggle the visibility of the grid on
screen. This does not disable snapping.

Playground 4.0.17.1
86 Utilities

9.1.11 Context Menu

If you hover over a window, for instance a bitmap or a button on the canvas, and you click your
right mouse button, a small popup menu will be displayed similar to this one:

Figure 9.34: Game Screen Context Menu

Hide Window(s) will hide the selected windows.


Delete will delete the code for the selected window from the Lua script.
Copy will copy the window code to the clipboard.
Bring to Front will move the order that the window is drawn so that it will be in front of the other
windows.
Sent to Back will reorder the selected window so that all other windows are drawn first.
Unhide All will unhide any windows that were hidden with the "hide window" command.
Align will bring up the alignment dialog. From here, you can snap all selected windows to a
certain orientation.
Distribute will bring up the distribute dialog. This will allow you to space the selected windows
out in a direction.
The remaining items in the menu are the current list of windows that are beneath the mouse. If
you are having problems selecting a window, you can use this list to find and click on the window
that you want to select.

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 87

9.1.12 Alignment Dialog

When working with a lot of window’s controls, like buttons, it is important to have the ability to
align a certain edge of these controls so that they look neat. This is very simple to do with the
alignment dialog. To access the alignment dialog, first select the windows that you want to align,
then either right click on one of the windows and select "Align..." or select Edit/Align selected
objects... in the menu.

Figure 9.35: Alignment Dialog

There are three parts to the alignment dialog.


1. The Alignment Region - These three options specify where you want the windows aligned.
Extents of Selection - will calculate the bounding region of all selected windows and align to one
of the edges.
Extents of parent window - will align the objects to a border of the parent window of the selected
windows.
Group to extents of parent window - will align all selected windows as one group to a border of
the parent window.
2. The edge to align to - these are the items along the top and side of the dialog. Choose the edges
that you want your selected objects to align to.
3. Align to Grid - setting this option will make sure that all of the selected windows will snap to
the current grid settings once they have been adjusted.

Playground 4.0.17.1
88 Utilities

9.1.13 Distribute Dialog

Figure 9.36: Distribute Dialog

The Distribute dialog is very similar to the alignment dialog but with a slight difference. If you
distribute the windows, you are affectively spacing the windows out evenly along a certain axis.
Typically, you might have three buttons that you want spaced evenly along the bottom of the
screen. You would select all three windows and then use the distribute tool to space them out
correctly.
Left, Center, Right, Top and Bottom refer to the edge of the controls which you want to distribute.
For instance, if you selected to distribute "Top", then all the controls would be evenly spaced based
on the tops of the controls.
If you select, "Spacing" as an option, then FirstStage will make sure that the space between each
control is exactly the same.

9.1.14 The Translations Editor

The translation editor is a dialog that allows you to enter new values or modify old values of
strings which are found inside the strings.xml file located in your assets folder.
String entries are always defined as a key/value pair. So, you will always start with a key string
that is a unique identifier for the value string which is the normal text. For example, "HelloMsg"
would be the key and "Hello there everybody!" would be the value. The key string is what you
enter into your label section when creating a button or text control. The text will then automatically
be replaced with the value for that key when it is displayed on screen.
The translations editor can be activated in two ways. Firstly, if you were to create a new button
or text control and you entered a label that currently doesn’t exist in the strings.xml file, then the

Navigating the Playground SDK


9.1 FirstStage: The Playground Resource Editor 89

translations editor will automatically be opened and your new value added. Alternatively, you
can access the editor at any time by selecting View/Show Strings Editor... from the main menu.
The editor is broken up into three sections. At the top, you have a filter search box. If you start
typing in the mask field, you should notice that your list of displayed strings will be reduced to
only those strings that match your typed text. This is a very quick way of finding a string in a
huge list of items. The "Filter on ID" option (default) means that it will try and match your mask
string with a string in the identifier field and similarly, the "Filter on Translation" will search on the
translation field. If you select "Substring" matching (default) then your mask must exist inside the
field. Example, if your mask was "ing", it would match strings with "fishing", "cooking", etc. The
wildcard search is a bit different. Using wildcard searches allows you to be more precise with your
selections. You could enter a mask like "c∗ing" and it would match "cooking" but not "fishing".
The next section is the key/value cells where you can edit your data. The left column is the index
number for the key/value in the xml file. The next column is the key and the last column is the
translation for that key. All of the columns can be resized by dragging the splitter area between
each column. You can double click on a column header to change the sorting order. Double click
once for ascending and double click it again for descending order. Double click on a cell to edit
the contents of that cell.
The last section has some buttons which help manage your strings. Currently, you can Add and
Delete key/value items. Click Add to add a new key/value to the end of the list. If you want to
delete an item, first click on either the key or the translation part of the item and then press the
delete button.
Once you have finished with your strings, press the OK button to save your changes or press
Cancel to abort your changes.

9.1.15 The Image Selector Dialog

The Image Selector Dialog is a visual way of being able to navigate your game folders for assets.
The dialog is automatically triggered when you create a new Bitmap control.
The column on the left side of the dialog is a list of all of the folders in your game. Whenever you
click on one of these folders, the images in that folder are displayed in the column on the right of
the dialog.
Once you have found the image that you want to use, you can either double click on the icon to
choose it or you can click once on the icon and then press the OK button.

Playground 4.0.17.1
90 Utilities

9.2 FluidFX 2.0: Interactive Particle System Editor

Figure 9.37: FluidFX Logo

9.2.1 What is FluidFX?


FluidFX is an editor for particle systems specified in the Particle System Shader Language (p. 57)
that is supported natively in Playground. It features:

• Colorized editing of Lua file.


• Editing of multiple particle systems at once, and displaying them together.
• Simplified editing of parameters to allow artists to edit and create their own custom particle
systems.
• Dynamic data input stream that you can move around by simply dragging it with your
mouse.
• Loadable background image.
• Displays the particles as you will see them in the game using the Playground SDK renderer.

9.2.2 How does FluidFX work?


The easiest way to explain how FluidFX works is by loading an existing file.
Run FluidFX, click Open, then find the Playground skeleton folder for some good examples in the
assets/fx folder. Start out by loading fire.lua. The first thing you’ll probably notice is that there’s
no Lua code visible on load–just a set of sliders and other controls. The Lua code is still around–
you just need to click on the "Script" tab to see it. But the point is that artists can actually use

Navigating the Playground SDK


9.2 FluidFX 2.0: Interactive Particle System Editor 91

FluidFX to tweak the code without ever seeing the code–so a programmer can create a template
particle system with the appropriate parameters and then let and artist run with it.

9.2.3 Creating Controls in FluidFX


So how do you create those controls? You can look at some examples and create them by hand, or
you can have FluidFX create them for you. Start out by loading spinstars.lua, which doesn’t have
any embedded controls.
First, let’s create our own copy by selecting "Save System As..." and giving it a new name. Now
when we mess with it, we won’t risk breaking the original file.
Next, let’s create our first control: Gravity. On line 76, you can see the standard gravity equation.
The relevant number here is "400", so select it with the mouse by double-clicking on it. Once
the "400" is selected, you can right click on the selected text and you’ll get a context menu; select
"Slider."
In the slider dialog, fill in the values as you see below:

Figure 9.38: Slider Dialog

The first value is the variable name that’s used in the script. Technically you don’t need to change
this, but it’s certainly good practice. The Label field is the label that’s displayed by the slider in
the properties window. The default value is the value that the slider will be set to initially–more
on that in a bit. Then the range that the slider will set the value to at each extreme. Press OK.
If you look, there’s no slider yet on the properties tab, since the new script code that’s been created
hasn’t been executed yet. Scroll to the top of the script pane for a moment to look at it.

gGravity = GUI_Slider( Lua


400,
"Gravity",
-100,1000);

Playground 4.0.17.1
92 Utilities

That code is what, in FluidFX, will create a slider control. The variable, gGravity, will be modified
as you move the slider. In fact, The first value, 400, is actually the value assigned to gGravity, and
will be changed in the Lua file as you move the slider. Try it now to see what I mean: Hit the "Go"
button, switch to the Properties tab, move the slider, and then switch back to the Script tab. The
new value should be visible there in the script.
You can also create a multiple-selection control, and a texture-selection control. Examples of both
of these are present in fire.lua, though the principle is the same for both.
For more information on writing new particle systems, see A Lua-Driven Particle System (p. 57).

9.2.4 Creating Collections of Particle Systems


You can load more than one particle system into FluidFX by clicking the plus icon ("New System")
in the Particle Systems window. You will have the option to select a particle system definition file.
When multiple particle systems exist, they all animate simultaneously. You can adjust their relative
positions by selecting the "System" mode on the toolbar, and then selecting the system you want
to move in the Particle Systems window. Select the "Global" mode to move all the systems at once.
When you have created several systems that you want to save together, you can use the "Save
Collection..." option to create a particle system collection. A particle system collection is a Lua file
that, when loaded into a TFxSprite, will load several systems at the same relative positions that
you set up in FluidFX.

9.3 sidewalk: Command Line Animation Creation


The sidewalk command line tool will take a sequence of bitmaps and convert it to an image (or
a pair of images) and an XML file with the offsets necessary to reproduce the original sequence.
It can also help you compress your assets folder by resaving images as PNG8, increasing JPG
compression, and can even split images into two part JPG/PNG masked images.

9.3.1 Sidewalk Command Line Options


If you run sidewalk.exe with no parameters, you’ll get the usage statement:

sidewalk v4.0.17.1011
Usage 1/Create XML animation:
sidewalk [options] animdesc.xml [ folder/fileroot* ]

Options:
--mask : Separate output into two layers, image and mask
--opaque : No transparency in PNG file.
--reg=x,y : Force registration point to x,y.
--scale=# : Scale an animation by #, where 1.0 means no change.
--filter=type : Set the scaling filter type. Options are:
Box
Triangle
Hermite
Hanning

Navigating the Playground SDK


9.3 sidewalk: Command Line Animation Creation 93

Hamming
Blackman
Gaussian
Quadratic
Cubic
Mitchell [default]
Lanczos
Bessel
-8 : Output 8 bit png
-f # : ’fuzzy’ bounding box value, between 0 and 1.
-o : Output individual frames as well as combined frames into
’frames’ folder.
-p : Reorder frames for optimal packing. This does not .
reorder the way frames are indexed, only reorders them in
the output file.
-i : Ignore size restrictions. This disables the requirement that
all images fit into a 1024x1024 texture. Note that if you use
this flag, the resulting image cannot be used directly to draw
in a game, but it may be used to hold data, etc.
-v : Verbose output
--noclear : Don’t clear transparent pixels to adjacent color.

For a new animdesc.xml file, you need to specify the source file
wildcard or name.

Usage 2/Compress Images:


sidewalk crunch [options] [path/to/search]

Options:
--nochanges : Just walk through the tree and report what would be
done.
--summary : Provide simple summary.
--fullcsv : Provide detailed CSV report, including files that can’t
be optimized.
--csv : Provide detailed CSV report of files that can be
optimized
--jpegquality=## : Set maximum JPEG quality: Any JPEG currently of higher
than this will be recompressed to the given quality.
Default is 85.
--jp2rate=## : Set JPEG2000 rate, 0.0-100.0, where 100 is lossless.
Default is 4.0. The meaning is different than for JPEG quality.
At 50, the file will be 50% of original size, and at 4, it will be 4%.
--samplefactor=## : PNG8 resampling factor. Smaller for higher quality.
Valid values are [1-10].
--splitmask : Split PNG RGBA files into JPG/PNG files. As of
Playground 4.0.16, now automatically supported.
[default on]
--nosplitmask : Disable splitmask feature.
--norecurse : Don’t recurse into subfolders.
--splitonly : Only split images to .jpg/.mask.png.
--png8only : Only compress images to png8.
--jp2only : Only compress images to JPEG2000 .jp2 format.
--mirror : Copy all files that do not need processing to output folder.
--output=folder : Set output folder (for new images) to folder. Defaults
to "crunched".
-v : Verbose output
--quality-threshold=## : Optimize JP2 output to ## quality. 1.0=good, 5.0=extreme compression. Note! CPU intensive.

Playground 4.0.17.1
94 Utilities

9.3.2 Example Animation Usage

To create a new animation, you need to start with a sequence of frames; PNG files are best, because
they can have an embedded transparency layer. Note that if they are PNG files stored with an
embedded transparency layer, that layer needs to be non-empty or the resulting PNG file will be
completely empty. They should also all be the same size; if your animation moves, the initial
frame should be large enough to encompass the entire animation, unless you want the motion to
be handled at runtime.
Once you have this sequence, save it in a folder by itself. The frames should alphabetize to be the
correct sequence; if they’re numbered, the numbers should have leading zeros (0001,0002, etc.) to
ensure they come out in the right order if there are more than 10 frames.

9.3.3 Example Animation Usage

Let’s say we want to create an animation out of a series of PNG files: frame00.png, frame01.png,
etc. To convert these files to a new animation control file "myanim.xml", you would call:

C:\dust devil>sidewalk.exe myanim.xml frame*.png


Processing frame: frame00.png
Processing frame: frame01.png
Processing frame: frame03.png
Processing frame: frame04.png
Compositing frame: frame00.png
Compositing frame: frame01.png
Compositing frame: frame03.png
Compositing frame: frame04.png

C:\dust devil>dir myanim*


Volume in drive C has no label.
Volume Serial Number is C4A8-160F

Directory of C:\dust devil

09/12/2006 03:42 PM 2,
270 myanim.png
09/12/2006 03:42 PM 497 myanim.xml
2 File(s) 2,
767 bytes

You can see above that it created myanim.xml and myanim.png. You need to copy these to the
same folder in your assets/ tree. All you need to do to load the file is reference myanim.xml,
however–it knows what its external files are called.
Here we assume that both of the above files are copied to "assets/anim":

TAnimatedTextureRef anim = TAnimatedTexture::Get("anim/myanim"). C++

And that’s it, now we have an animation in the game.

Navigating the Playground SDK


9.4 Filmstrip: Creating and Editing Animations 95

9.3.4 Modifying Transparent Pixels

As of v4.0.14, sidewalk now modifies transparent pixels to match adjacent non-transparent colors.
As transparent pixels shouldn’t actually render, this may seem like a strange feature, but it turns
out that these transparent pixels can "bleed" into their adjacent non-transparent pixels.
Remember that the renderer, when given a non-exact pixel location, will average adjacent pixels
to determine what color values to draw at a particular location. Say you have a pixel that’s com-
pletely transparent, with alpha value 0. It still has RGB values of course, but you don’t intend
them to render. Say the RGB values are 0,0,0, complete black. Also, let’s assume that your object
is white, RGBA 1,1,1,1.
Now when it attempts to render your object offset by 0.5 pixels, the first pixel it draws will be
an average of the transparent pixel, 0,0,0,0, and the opaque one, 1,1,1,1. So you end up with
0.5,0.5,0.5,0.5. This sounds fine–unless the background you’re rendering to is a very light color.
Then your white object rendered to a white background will have a 50% transparent, 50% grey
border.
Sidewalk corrects for this by taking that 0,0,0,0 and looking for an adjacent non-transparent pixel.
It then takes the color from that pixel– in our case it would become 1,1,1,0. Now when it averages
with its adjacent pixel, it will be come 1,1,1,0.5, which is really what you wanted.
If you don’t want this behavior, the option –noclear will disable this clearing of transparent pixels.

9.4 Filmstrip: Creating and Editing Animations

Figure 9.39: Filmstrip

Filmstrip is Playground’s animation frame sequencer. You can create new animations or load
existing xml or anm animation files.

Playground 4.0.17.1
96 Utilities

A variety of animations can be defined using the Lua scripting language to specify the name of the
animation and the order of frames to play for that animation.
Also, for each frame, you can adjust a multitude of properties including rotation, scale, alpha and
more.
Filmstrip has a group of dockable windows that allow you to control all aspects of the editor.
Below is an explanation of each window:

9.4.1 Script Window

The script window holds the Lua script which defines the animations that make up the animation
file. A typical script might look like this.

function DoAnim()
delay(20);
while true do
frames{
1,1,1,1,2,2,2,3,4,5,7,4,3,2
};
end
end

For more information on how to control animation through Lua, see the "Animation Script Func-
tions" section.

9.4.2 Animations Window

When you define new animations in the script window, the animation names will automatically
be displayed in the Animations Window. To play an animation, either click on the name of the
animation and press the play button in the window’s toolbar, or just double click the animation
name. To stop the animation from playing, press the stop button in the window’s toolbar. You can
advance one frame at a time by pressing the frame advance button and likewise play frames in
reverse by pressing the reverse button in the toolbar.

9.4.3 Animation Frames Window

This window holds a list of frame numbers that make up the loaded sprite sheet. All animations
are composed from these frames. To see a particular frame, click on the frame number in the list.
You can also display multiple frames at once by clicking on the first frame in the sequence and
then holding down shift and clicking the last frame in the sequence. On screen, you will see all the
frames in the sequence being drawn at once but they will all be ghosted apart from the last frame.
The ghost effect is called "onion skinning". More on onion skinning later.
The Animation Frames toolbar has some buttons which can help in modifying your animation
frames.

Navigating the Playground SDK


9.4 Filmstrip: Creating and Editing Animations 97

Figure 9.40: Anim Frames Toolbar

From left to right,

• Frame Reverse - go back one frame in the animation


• Frame Advance - go forward one frame in the animation
• Delete Current Frame - Delete the selected frame number from the list.
• Insert Blank Frame - Insert a blank frame before the currently selected frame.
• Duplicate Frame - Insert a copy of the current frame. See below.
• Move Current Frame - Move the selected frame to a different location in the list. You will be
presented with an input box. Specify the new location for the frame and press OK.

9.4.4 Duplicating Frames


You have the following options when duplicating a frame:

Figure 9.41: Duplicate Frames Dialog

• Insert Blank Before - Insert a blank frame before the currently selected frame.

Playground 4.0.17.1
98 Utilities

• Insert Blank After - Insert a blank frame after the currently selected frame.

• Insert Before "x" - Create a blank key frame before the specified frame.

• Append Blank Frame - Add a blank frame to the end of the list of frames.

• Duplicate Frame - Make a copy and insert right after the current frame. You will end up with
two exact frames together.

• Insert Duplicate Before "x" - Make a copy of the current frame and insert the new frame
before frame "x".

• Append Duplicate - Make a copy of the current frame and add it to the end of the list of
frames.

9.4.5 Anchors Window

When dealing with animations, anchors are a great way of retrieving reference points for each
frame. See Anchors (p. 103) for more information on anchors. The Anchors Window allows you
to manage your anchors. All of the anchors for the loaded animation are displayed as a tree list in
the Anchors Window. If you click on the name of the anchor, it will select it. You can then use the
Delete button in the toolbar to delete the anchor or press the Rename button to rename the anchor.
There are a couple of ways to create new anchors. One way is to press the New Anchor button in
the tool bar. It will pop up a dialog asking for a name for this new anchor.

9.4.6 History Window (Hidden by default)

The History Window displays all actions that have been performed inside the editor. You can
either use Ctrl-Z and Ctrl-Y to undo and redo or you can click on any item in the history to revert
back to when that action was created. This allows you to do a block of undos in one go.

9.4.7 Frame Inspector Window

This window gives you access to all of the editable properties for each frame on your sprite sheet.
Click on any frame number in the Animation Frames window and you will see the properties for
that frame updated in the Frame Inspector. It might look something like this:

Navigating the Playground SDK


9.4 Filmstrip: Creating and Editing Animations 99

Figure 9.42: Frame Inspector

• The Name field can be used as an identifier for this frame. For instance, instead of frame 10
just being called 10, you could type in "WalkStart" and then in your Lua script, you could
refer to this frame as WalkStart.

• The Image Details section is only for display purposes and shows the pixel offset information
for this frame in the sprite sheet.

• The x Reg and y Reg fields are the registration values (or offsets) for this frame.

• The Alpha field represents the alpha level for this frame. You can adjust the alpha by using
the slider or by typing in a value in the edit box.

• The next section is the matrix for this frame. It is made up of a rotation and translation
section. Normally, you would adjust the matrix for a frame by using the Move, Rotate, and
Scale tools rather than hand typing in values into the Inspector but if you want to enter exact
numbers, you can use these matrix entries to do so.

9.4.8 The Main Tool Bar


The tool bar in Filmstrip has most of the common tasks that you will use when using the program.
From left to right, these are:

Figure 9.43: Filmstrip Toolbar

Playground 4.0.17.1
100 Utilities

New - Create a new sprite sheet from a series of images. See Creating a New Animation (opposite)
for more information.
Open - Open an XML animation or an ANM animation. ANM files are the binary version of the
XML file which helps if you have a lot of data to load. If you want to create an ANM file, first load
your XML animation and then choose File/Export to ANM from the main menu.
Save - Save the current animation file back to disk. If you want to save your animation to a
different file, choose File/Save as from the main menu.
Undo/Redo - These buttons are the standard button to allow you to undo any mistakes you make.
Select/Move/Rotate/Scale - These buttons are "state" buttons and are used to manipulate the cur-
rent frame of animation. If you click on either Move, Rotate, or Scale buttons, you will notice that
the cursor will change to match the mode that you selected. The move button allows you to move
the position of the current frame. Select the move button and then click and drag the left mouse
button around the screen. You will notice the frame moves position. The rotate button will rotate
the frame. Similar to move, press the rotate button and then click and drag the left mouse button
left and right to rotate the image. The scale button will scale the image in both width and height.
Click on the scale button and then click and drag the left mouse button to see the image scale. If
you hold down the control key, the image will scale uniformly in width and height. Use the Select
button when you don’t want to make any more modifications to the frame.
Move/Rotate/Scale data entry - If you want to type in exact values for a particular mode, right
click on the button and a data entry dialog will appear. Say, for instance, that you want to move
the image ten pixels to the left. Right click on the Move tool button and a dialog will appear. Click
on the Relative radio button because you want to move the position based on the current position.
Type -10 in the x field and press OK. You will notice that the frame has jumped ten pixels to the
left.

Figure 9.44: Onion Mode Settings Dialog

Onion - This toggles onion skinning mode. Onion skinning was a term adopted by traditional cell
animators a long time ago and it means when you can see the last couple of frames of animation
while you are editing the current frame. It is most helpful when you are trying to adjust details of
the current frame and you need a reference of the last frame to compare it to. If you right click on
the Onion toolbar button, you will get a dialog with settings you can adjust.

• Previous frames to show is how many frames you want to see before the current frame.

Navigating the Playground SDK


9.4 Filmstrip: Creating and Editing Animations 101

• Subsequent frames to show is how many frames to draw past the current frame.

• Ramp alpha values means that the previous and subsequent frames will have gradually less
alpha the further they are away (in frames) from the current frame number.

• Wrap onion display means that the display of the frames will wrap around the end frames of
your animation. For example, say you had an animation with 10 frames and you had your
onion skin previous frames set to 5. If you were on frame 2, you would see frames 2,1,10,9,8,
and 7. If you had Wrap turned off, you would only see frames 2 and 1.

Grid - Toggle frame grid view. The frame grid view will display all of the current frames in a 2D
grid. If there are more frames than can fit on screen, move your mouse to the right of the game
window and a vertical scroll bar will appear. Depending on the grid options set, you can also move
the mouse to the bottom of the game window and a frame scale slider will appear which allows
you to change the display scale for the frames. The current frame has a highlighted background
and you can change the current frame by clicking on the cell of the frame you want.
The frame grid settings can be accessed by right clicking the grid tool bar button. Click Grid
Settings (next page) for more information.
Bkg - This allows you to set a background image for the screen so that you can test your animations
against a background.

9.4.9 Creating a New Animation

Figure 9.45: New Animation Dialog

Playground 4.0.17.1
102 Utilities

Create a new sprite sheet from a series of images. The result will then be loaded into Filmstrip for
you to add your animations. When you press New, it will bring up the Create New Animation
dialog box which looks like this:

• Name is the name of the xml file to create on disk.

• Path is the path to one of the images that will be in the new animation. If you select the
button to the right, you can browse to the folder with your images. Select any one of the
images in the sequence you want to build and press Open.

• The Options are the same as the options in Sidewalk which is explained here sidewalk:
Command Line Animation Creation (p. 92)
• Clear Old XML button will delete any xml file of the same name before it begins compiling
the new images. This is helpful if you want to make sure that the XML has been built from
scratch rather than just updated.

• The Create button will start the build process. When you press the Create button, a window
will appear on screen which is sidewalk being activated to build your new animation file.
Once the process have been completed, the result will appear in the Output Window at the
bottom of the screen.

9.4.10 Grid Settings


The frame grid settings can be accessed by right clicking the grid tool bar button. You will be
presented with a dialog like this:

Figure 9.46: Grid Properties Dialog

Grid Size represents the width and height of each cell of the grid.

Navigating the Playground SDK


9.4 Filmstrip: Creating and Editing Animations 103

Scale Mode specifies how to scale each frame in the cell. The options are:

• Don’t Scale Don’t use any automatic scaling technique. The user can manually change the
scale with the scale slider.

• Scale Down to Fit Reduce the size of the frame only if it doesn’t fit inside the cell.

• Always Scale to Fit Always rescale the frame so that it fills the cell.
Show Frame Numbers will display the frame number in the top left of each cell.

9.4.11 Anchors
Anchor points are used to track animated offsets; for instance, the hand of a character that needs
to have an object attached might get an animated anchor. There are a couple of ways to create an
anchor in Filmstrip. One way is to move your mouse where you want to create an anchor and then
click the right mouse button. A menu will pop up. Select "Add anchor here" to create an anchor at
that point. The other way to create an anchor is to use the "Add new Anchor" button in the toolbar
of your anchors window. You will be prompted for the name of the new anchor. Enter a name and
press OK. A new anchor is created and will be automatically located at the top left of the game
screen. You will then need to move it to where you want on your animation.
To move an anchor, simply move your mouse until it is over the anchor and then click and drag
with your left mouse button to the new location.
If you want to delete an anchor, you can either right click on the anchor and select "Delete this
anchor" or you can select the anchor in the Anchors Window and press the delete button in the
Anchors window toolbar.
When you move an anchor, it only moves the position of the anchor for the current frame you are
on. If you want to move the anchor to a new position for ALL frames, hold down the ALT key
while dragging your anchor.

9.4.12 Filmstrip and Sidewalk


Filmstrip uses the utility called Sidewalk (found in the Playground SDK bin folder) to create new
animations. As such, the first time you want to create a new animation, you might need to direct
Filmstrip to where your copy of sidewalk can be found. Filmstrip tries to do an intelligent search
for a version of sidewalk, but if it can not find it you will be prompted to locate it yourself. Once
Sidewalk has been located, you shouldn’t be asked again. You can redirect Filmstrip to a different
version of Sidewalk by using the menu item "Extra/Change Sidewalk location" in the main menu.

9.4.13 File Associations


If you develop under Windows XP, you can tell Filmstrip to associate all XML and ANM files
with Filmstrip so that if you double click on an XML or ANM file in Windows Explorer, it will
automatically run Filmstrip and load that animation. To tell Filmstrip to associate XML and ANM
files, use the menu item "Extra/Associate XML/ANM files" from the main menu.

Playground 4.0.17.1
104 Utilities

Figure 9.47: Compress Graphics Dialog

9.4.14 Compress "Crunch" Game Art


Filmstrip supplies a handy shortcut to the crunch command built into Sidewalk. All of the crunch
features are selectable through the compress dialog found under the Extras/Compress Graphics...
main menu
Refer to sidewalk: Command Line Animation Creation (p. 92) for an explanation of the crunch
options.

9.5 3dsconvert: Creating 3d Models For Playground


To create models for use in Playground, you convert .3ds files into a .mesh file. The utility for
doing this is called 3dsconvert. Options for this utility are:

• -i [input]: name of .3ds file to convert.

• -id [inputdir]: name of directory to convert all .3ds files from.

• -o [outputfile]: name of file to output (default uses name of .3ds file) If there is more than
one mesh in the file, and -m is not used, the files will be named [outputfile]1.mesh [output-
file]2.mesh ...

Navigating the Playground SDK


9.6 Creating a Playground Font 105

• -m: use names of .3ds meshes for output file name if both -m and -o are used, output names
will be of form [outputfile]_[meshname].mesh.

• -od [outputdir]: name of directory to output files in.

• -s [amount]: how much to scale the model by (default 1.0).

• -center [xyz]: recenter across an axis - specify any combination of xyz. This happens before
the yzflip.

• -invert [xyz]: invert across an axis - specify any combination of xyz. This happens before the
yz flip, so -invert z first inverts the z axis, then flips it with y.

• -uvflip [uv]: This will flip texture coordinates from 0-1 to 1-0 - specify any combination of
uv.

• -yzfilp: this will flip the y and z axis (default off)

9.6 Creating a Playground Font


To create a font you need the Macromedia® Flash® software. In the Playground SDK™ distribu-
tion is a bin folder, where you can find two different font template .fla files, one for Flash® MX
and one for Flash® 8.
To create the font, first, from within the Flash® software:

1. Open the appropriate font template in your version of Flash®.

2. Select the text field and change it to be the font you want.

3. Publish the swf.

After you’ve completed the above, you need to drag and drop the resulting swf file onto the
swf2mvec.exe program, also within the bin distribution. That program will emit an mvec file
next to the swf file. Name that mvec file and add it to your assets folder, and then you can load it
as a font.

9.7 axtool: Testing Your Game in a Browser


The axtool utility can help you configure your system to be able to run your game in an Internet
Explorer browser on your system. Here are the basic steps you need to follow:

1. Create two files in your game build directory, activex.bat and activextest.bat, based on the
example files included under the bin\axtool\samplefiles folder. Copy these files into your
game folder and add the appropriate information for your game. You can generate the
GUIDs using a tool that ships with the Microsoft® Developer Studio® development sys-
tem called guidgen.exe, which is installed in the Common7\Tools folder in your Developer
Studio installation folder.

Playground 4.0.17.1
106 Utilities

2. Create an empty text file at c:\pfaxdebug.txt. Without this text file at the root of your C drive,
the game will not run.

3. Open up a command prompt window (in Vista, ensure that you’re running the command
prompt as administrator).

4. Run the axtool.bat script that is in your utilities\bin\axtool folder. Run the utility like this:

axtool [gamefolder] test debug C++

• The gamefolder should be the path to your gamefolder (the folder that contains the
activex.bat file, etc.)
• test and debug are required parameters for testing the game locally.
• Note that this script assumes you have Visual Studio® 2005 installed in the default
location. If you do not, you can override where it looks for Visual Studio by defining a
VSNETPATH environment variable to the path. For example:

set VSNETPATH="C:\\Program Files\\Microsoft Visual Studio 2005" C++

or

set VSNETPATH="C:\\msdev\\install" C++

After you’ve completed the above steps, you’ll have an html file in your game folder. To test your
game in a window:

1. Open up the html file in Internet Explorer (it will not run in other browsers).

2. Internet Explorer may ask you if you want to install the ActiveX® control; allow it to install.

3. A window will appear that will say something like "Run with -wnd=123456." This means
your game is now ready to run in the window. You can now launch your game in the de-
bugger, and instead of running in its own window, it will show up in the Internet Explorer
window.

9.8 xml2anm: Convert XML to ANM


The ANM format was created to help speed the loading of animation files. As a binary format
it can be loaded by Playground much more quickly than the more verbose and human readable
XML format.
Currently you need to modify your game source to look for ANM files instead of XML files, so
you’ll need to perform the conversion in your development builds–it can’t be done automatically
at build time. We’re considering changing this in a future release.
To use, you call it on the command line with one or more of the following options:

xml2anm: converts an animation XML file into a binary ANM file


flags:

Navigating the Playground SDK


9.8 xml2anm: Convert XML to ANM 107

-f <filename> - converts one file from xml to anm


-o <outputname> - if using -f, optional argument to specify outputfile
-d <directoryname> - converts all xml files in directory to anm files
-r - turns on recusrion for -d option
-1 - writes old version 1 file

Playground 4.0.17.1
108 Utilities

Navigating the Playground SDK


Chapter 10

Advanced Features

10.1 Playing With the Big Kids


This section has a number of quick examples and how-tos that cover more advanced concepts.
Most Playground SDK™ games contain few or none of these techniques, but some problem do-
mains have very simple solutions when you have the right tools. Here are some of the more
sophisticated tools for you to use when the situations arise.
Some of the examples are very brief—after all, if you’re reading this section, you’re an expert
looking for an example of an advanced technique. If you’re not sure why you’d want to do some
of these things, then you likely don’t need to do them.

10.2 Deriving a Custom Sprite Type


As part of a discussion on the forums about attaching text to a sprite, it became obvious that one
easy way would be to create a custom sprite type that, instead of (or in addition to) drawing a
texture, also drew a line of text.
If you want your own custom-derived sprite, here’s a quick approximation of what that code
would need to look like. Our derived class will be called TTextSprite (p. 454).
First a declaration:

// Forward declaration C++


class TTextSprite ;

// Reference counted pointer wrapper


typedef shared_ptr<TTextSprite> TTextSpriteRef ;

class TTextSprite : public TSprite


{
PFSHAREDTYPEDEF(TSprite);
protected:
// Internal Constructor. Use TTextSprite::Create() to get a new sprite.
TTextSprite(int32_t layer);
110 Advanced Features

public:
// Destructor.
virtual ~TTextSprite();

// Factory method
static TTextSpriteRef Create(int32_t layer=0);

// Our Draw call


virtual void Draw(const TDrawSpec & drawSpec=TDrawSpec(), int32_t depth=-1);

private:
TTextGraphic mTextGraphic ;
TRect mTextRect;
}

And then highlights from the implementation:

PFTYPEIMPL(TTextSprite); C++
// Call the protected TSprite constructor
TTextSprite::TTextSprite( int32_t layer ) : TSprite( layer )
{
}

// Public creation call, to ensure all TTextSprites are wrapped


// in TTextSpriteRefs correctly
TTextSpriteRef TTextSprite::Create( int32_t layer )
{
TTextSprite * as = new TTextSprite(layer);
TTextSpriteRef ref( as );

return ref ;
}

// The actual Draw call


void TTextSprite::Draw(const TDrawSpec & drawSpec, int32_t depth)
{
if (!mEnabled)
{
return;
}
TDrawSpec localSpec = mDrawSpec.GetRelative(drawSpec);

// This assumes you have an mTextRect which is the desired rectangle size
// for your text.
TRect rect = mTextRect+TPoint(localSpec.mMatrix[2].x,localSpec.mMatrix[2].y) ;
mTextGraphic->Draw( rect, 1, 0, localSpec.mAlpha );

TSprite::Draw(drawSpec,depth);
}

Note that I didn’t include the math for extracting the rotation from the matrix, so this text will
draw at the location but not the rotation of a sprite. I leave the extraction of the rotation as an
exercise for the reader.

Navigating the Playground SDK


10.3 Sending Custom Application Messages 111

10.3 Sending Custom Application Messages

The TMessage (p. 294) type is intended to encapsulate any complex client message. The Play-
ground SDK™ encapsulates TMessage (p. 294) as a Lua user-type, so you can pass a TMessage
(p. 294) object around within Lua. If you want to have Lua pass complex message objects back to
your C++ game, you can easily have a Lua object send a message to your game window where
you can interpret its contents and trigger the correct game actions.
To start, derive your message type from TMessage (p. 294) and add any extra information to your
derived class. For example, say you have a script that triggers an explosion animation that requires
some additional processing in C++ code:

// A custom user message with information about an explosion C++


class TriggerExplosion : public TMessage
{
// This allows the class to have run time type id information
PFTYPEDEF_DC(TriggerExplosion,TMessage);
public:
int x,y;
float size ;
};

...

// In a C++ file, define the runtime type id


PFTYPEIMPL(TriggerExplosion);

Now we have a new custom message type, and we need a way to create it from within Lua. Since
we can use ScriptRegisterDirect() (p. 120) to expose a C++ function to Lua, we can create an
instance in C++ and return it to Lua directly:

// A function that creates a new explosion message C++


TMessage * NewExplosion( int x, int y, float size )
{
TriggerExplosion * te = new TriggerExplosion;
te.x = x ;
te.y = y ;
te.size = size ;
te.mName ="TriggerExplosion";
return te ;
}

The TMessage∗ will be deleted by the Lua garbage collection when it is no longer used, so you
won’t need to delete it yourself.
Here’s how you might use the above code:

// The main game class (excerpts of relevant parts) C++


class MainGameWindow
{
public:
MainGameWindow()
{
// ...
ScriptRegisterDirect(
TWindowManager::GetInstance()->GetScript(),

Playground 4.0.17.1
112 Advanced Features

"NewExplosion",
NewExplosion);

// Make sure that messages are routed to us.


TWindowManager::GetInstance()->GetTopModalWindow()->SetDefaultFocus(this);
// ...
}

// ...
virtual bool OnMessage(TMessage * message)
{
TriggerExplosion * te = message->GetCast<TriggerExplosion>() ;

if (te) // this is a TriggerExplosion, so process it


{
x = te->x ;
y = te->y ;
size = te->size ;
HandleExplosion(x,y,size) ; // This would do the extra work
return true ;
}

// Check for other message types here...

// ...

return false ; // We didn’t handle the message


}
// ...
}

Then, in a Lua script:

-- Send a message that indicates we want an explosion at this location Lua


PostMessage( NewExplosion(12,32,0.232) ) ;

This will send a message that will be delivered to the "default focus" window (see TModalWin-
dow::SetDefaultFocus (p. 300)), and from there can be handled by your custom game window
class. If you need a message to go to more than one destination, then you should set up a de-
fault focus window that can dispatch the message to the appropriate destination. The TMessage
(p. 294) will be deleted by Lua in a normal garbage collection pass.

10.4 Calling a Lua Function from C++


For a simple example of calling a Lua function from C++,see the following.

function DoSomething() Lua


DebugOut("I’ve been called");
end

Foo = { fn=DoSomething };

TWindowManager::GetInstance()->GetScript()->RunScript("test.lua"); C++

Navigating the Playground SDK


10.5 Substituting a Custom TModalWindow 113

TLuaTable * table = TWindowManager::GetInstance()->GetScript()->GetGlobalTable("Foo"); C++


TLuaFunction * fn = table->GetFunction("fn");
fn->Call();
delete fn;
delete table;

This prints out "Lua: I’ve been called" in the debug log. You should be able to keep around the fn
pointer indefinitely–I just delete it here since I’m creating it in a local pointer.
If your routine returns values, they will be pushed onto the stack in order–and this Call function
only supports one result, so you’ll only get the first one. You can use the TScript::PopString()
(p. 392), TScript::PopNumber() (p. 392), or direct Lua C stack access functions to extract the return
value from the stack.

10.5 Substituting a Custom TModalWindow


Here’s a trick that’s useful to replace TModalWindow (p. 298) as the default modal window that
Lua’s scripts push. Remember that this created and pushed every time your game calls DoModal()
(p. 145), DisplayDialog() (p. 144), or even just PushModal() (p. 149), so you probably want it to
behave, in general, similarly to a TModalWindow (p. 298).
To start with, create a class that derives from TModalWindow (p. 298):

// In the header C++


class TMyModalWindow : public TModalWindow
{
PFTYPEDEF(TMyModalWindow,TModalWindow);
...
}

// In the implementation file


PFTYPEIMPL(TMyModalWindow);

Then you need a piece of code that acts like the Lua version of PushModal() (p. 149):

str PushMyModal( str name ) C++


{
TMyModalWindow * window = new TMyModalWindow();
window->SetName(name);
TWindowManager::GetInstance()->PushModal(window);

return window->GetID();
}

Once you have that function set up, you simply need to register it:

ScriptRegisterDirect( TWindowManager::GetInstance()->GetScript(), "PushModal", PushMyModal ); C++

Once you’ve done that, then every TModalWindow (p. 298) created by Lua will instead be one of
your derived TModalWindow (p. 298) classes.
Like most of the advanced tips, this one comes with caveats. Be careful having your window draw
anything–the current TModalWindow (p. 298) is intentionally invisible. And for obvious reasons,

Playground 4.0.17.1
114 Advanced Features

the class TDialog (p. 221) will not suddenly derive from your TModalWindow–and the function
TWindowManager::DisplayDialog() (p. 523) creates a TDialog (p. 221) window, so any dialogs
created using that function won’t use your new TModalWindow (p. 298).
The other reason this is in the advanced section is that it really would be a bad idea to abuse this
trick: One might be tempted to swap in various kinds of TModalWindows depending on what
game mode you were currently in, for example. And that might even work. But considering that
Lua executes effectively as a "light" thread, and it’s hard to know what its current state is at any
one time–and things can synchronize differently depending on the speed of your computer. So
use caution.

Navigating the Playground SDK


Part II

Reference
Chapter 11

Windowing Reference

11.1 Windowing and Widget Functionality

11.1.1 Detailed Description


Everything related to windows and their descendents: buttons, sliders, image windows, and cus-
tom windows.

Modules
• Ignore This Group Please

Classes
• class TButton
• class TDialog
• class TImage
• class TLayeredWindow
• class TScreen
• class TText
• class TTextEdit
• class TWindow
• class TWindowSpider
• class TWindowHoverHandler
• class TWindowManager
118 Windowing Reference

Navigating the Playground SDK


Chapter 12

Lua Reference

12.1 Lua-Related Documentation

12.1.1 Detailed Description

Documentation on predefined Lua constants and functions, as well as C++ interfaces to Lua.
See the section on Lua Scripting (p. 47) for more information.

Files

• file luapluscd.h

Classes

• class TLuaTable
• class TScript
• class TScriptCode

Defines

• #define ScriptRegisterMemberFunctor(script, name, ptr, functor)


• #define ScriptRegisterFunctor(script, name, functor)
• #define ScriptRegisterMemberDirect(script, name, ptr, directfunctor)
• #define ScriptRegisterDirect(script, name, directfunctor)
• #define ScriptUnregisterFunction(script, name)
120 Lua Reference

Functions

• template<typename Func>
void lua_pushdirectclosure (lua_State ∗L, Func func, unsigned int nupvalues)
• template<typename Callee, typename Func>
void lua_pushdirectclosure (lua_State ∗L, Callee ∗callee, Func func, unsigned int nupvalues)
• template<typename Callee>
void lua_pushfunctorclosure (lua_State ∗L, Callee ∗callee, int(Callee::∗func)(lua_State ∗),
unsigned int nupvalues)

12.1.2 Define Documentation


#define ScriptRegisterDirect(script, name, directfunctor)
Register a "Direct" called function: A function that will be called by Lua directly with appropriate
parameters. This can be contrasted with ScriptRegisterMemberFunctor() (opposite), which calls
a function with the standard Lua function signature.
Supported parameter types include:

• bool
• [unsigned] char
• [unsigned] [short] int (unsigned and short are optional)
• [unsigned] long
• lua_Number
• float
• const char∗
• str (p. 161)
• const LuaNil&
• lua_CFunction
• TLuaTable (p. 269) ∗ (see below for important notes)
• TMessage∗
• const void∗ (return from Lua only)
• const LuaLightUserData& (return from Lua only)

For TLuaTable ∗ as parameter, the pointer will exist for the duration of your function, but will be
deleted in the next application event loop, so don’t keep it around.
For TLuaTable ∗ as a return type, you will need to return a TLuaTable (p. 269) pointer that persists
past the end of the function; you are still responsible for deleting the pointer.
See also:
Using Lua to Script Your Game (p. 47)

Navigating the Playground SDK


12.1 Lua-Related Documentation 121

#define ScriptRegisterFunctor(script, name, functor)

Register a function with the standard Lua signature.


The function signature should match:
int FN( lua_State ∗ L );
Parameters:
script Script to add functor to.
name Lua name of function.
functor The function to call.
See also:
Using Lua to Script Your Game (p. 47)

#define ScriptRegisterMemberDirect(script, name, ptr, directfunctor)

Register a "Direct" called function: A function that will be called by Lua directly with appropriate
parameters.
Parameters:
script Script to add functor to.
name Lua name of function.
ptr Pointer to "this" in the class we’re binding to.
directfunctor The member function to call.

See ScriptRegisterDirect for supported parameter types.


See also:
ScriptRegisterDirect (opposite)
Using Lua to Script Your Game (p. 47)

#define ScriptRegisterMemberFunctor(script, name, ptr, functor)

Register a member function with the standard Lua signature.


The function signature should match:
int FN( lua_State ∗ L );
Parameters:
script Script to add functor to.
name Lua name of function.
ptr Pointer to "this" in the class we’re binding to.
functor The member function to call.
See also:
Using Lua to Script Your Game (p. 47)

Playground 4.0.17.1
122 Lua Reference

#define ScriptUnregisterFunction(script, name)


Unregister a function that was previously registered using ScriptRegisterDirect() (p. 120), Scrip-
tRegisterMemberDirect() (previous page), ScriptRegisterFunctor() (previous page) or ScriptReg-
isterMemberFunctor() (previous page).

12.1.3 Function Documentation

template<typename Callee, typename Func> void lua_pushdirectclosure (lua_State ∗ L,


Callee ∗ callee, Func func, unsigned int nupvalues)
Push a function on the Lua stack that will be called "directly" with a custom parameter list and
return value ("directly"). More details are available in lua_pushdirectclosure(lua_State∗ L, Func
func, unsigned int nupvalues) (this page)
See ScriptRegisterMemberDirect() (previous page) for a simplified wrapper to this function.
Advanced user function; can be safely ignored by most users.
Parameters:
L Lua state.
callee A pointer to the class instance you want to bind your caller to.
func Member function to call.
nupvalues Number of upvalues (usually 0; see Lua docs)
See also:
lua_pushdirectclosure(lua_State∗ L, Func func, unsigned int nupvalues) (this page)
ScriptRegisterMemberDirect (previous page)

template<typename Func> void lua_pushdirectclosure (lua_State ∗ L, Func func, unsigned


int nupvalues)
Push a function on the Lua stack that will be called "directly" with a custom parameter list and
return value ("directly").
See ScriptRegisterDirect() (p. 120) for a simplified wrapper macro.
Advanced user function; can be safely ignored by most users.
With this function you can expose any class member function that uses the supported parameter
and return value types to a Lua script.
See ScriptRegisterDirect() (p. 120) for supported parameter types.
Parameters:
L Lua state.
func Function to call.
nupvalues Number of upvalues (usually 0; see Lua docs)
See also:
ScriptRegisterDirect (p. 120)

Navigating the Playground SDK


12.1 Lua-Related Documentation 123

template<typename Callee> void lua_pushfunctorclosure (lua_State ∗ L, Callee ∗ callee,


int(Callee::∗)(lua_State ∗) func, unsigned int nupvalues)
Push a member function on the Lua stack that will be called as a standard Lua callback function.
The standard function signature takes a parameter lua_State∗ and returns int.
This will allow you to create a member function and have Lua call it directly.
Advanced user function; can be safely ignored by most users.
Parameters:
L Lua state.
callee A pointer to the class that your function is a member of.
func Function to call.
nupvalues Number of upvalues (usually 0; see Lua docs)

Playground 4.0.17.1
124 Lua Reference

12.2 Query Values for Current Configuration in Lua.

12.2.1 Detailed Description


These values are passed to GetConfig() to query various configuration states. See GetConfig() for
more information.

Constants

• luaConstant kCheatMode
• luaConstant kComputerId
• luaConstant kInstallKey
• luaConstant kGameName
• luaConstant kGameVersion
• luaConstant kEncryptionKey
• luaConstant kHiscoreLocalOnly
• luaConstant kHiscoreAnonymous

12.2.2 Constant Documentation


luaConstant kCheatMode
Cheat mode enabled?

luaConstant kComputerId
This computer’s unique ID.

luaConstant kEncryptionKey
The encryption key.

luaConstant kGameName
The name of the game.

luaConstant kGameVersion
The version number of this build.

luaConstant kHiscoreAnonymous
This is an anonymous hiscore build

Navigating the Playground SDK


12.2 Query Values for Current Configuration in Lua. 125

luaConstant kHiscoreLocalOnly
This is a local hiscore build

luaConstant kInstallKey
The key that indicates how this game was installed.

Playground 4.0.17.1
126 Lua Reference

12.3 GUI-Related Constants in Lua.

12.3.1 Detailed Description


These constants are available in the Lua GUI script.

Constants

• luaConstant kPush
• luaConstant kToggle
• luaConstant kRadio
• luaConstant kAllLayers
• luaConstant kCenter
• luaConstant kMax
• luaConstant kDefault

12.3.2 Constant Documentation


luaConstant kAllLayers
SelectLayer() (p. 149) constant to select all layers for edit.

luaConstant kCenter
Position-relative-to-center: Add this constant to an x/y position to make it relative to a centered
object. In other words, if you make x=kCenter, the object will be centered horizontally. If you add
one (x=kCenter+1), the object will be one pixel to the right of where it would have been centered.

luaConstant kDefault
Button Text Alignment: Default for type of button.

luaConstant kMax
Width or position maximum. In the case of position, you can subtract an amount from kMax to
make the position relative to the opposite edge. For a width or height, you can use -kMax to
indicate the window should "grow" in the opposite direction of the x or y position: w=-kMax
means that x specifies the right edge of the window, and that it should grow to the left edge of the
parent.

luaConstant kPush
Button Type: Push button.

Navigating the Playground SDK


12.3 GUI-Related Constants in Lua. 127

luaConstant kRadio
Button Type: Radio button.

luaConstant kToggle
Button Type: Toggle button.

Playground 4.0.17.1
128 Lua Reference

12.4 Text and Window Alignment.

12.4.1 Detailed Description


These Lua constants are used both as text alignment in Text() (p. 152) windows, and general Win-
dow() (p. 153) alignment using the align tag. Combine flags in Lua using normal addition (+),
since Lua doesn’t support bitwise or.

Constants
• luaConstant kHAlignLeft
• luaConstant kHAlignCenter
• luaConstant kHAlignRight
• luaConstant kVAlignTop
• luaConstant kVAlignCenter
• luaConstant kVAlignBottom

12.4.2 Constant Documentation


luaConstant kHAlignCenter
Horizonal alignment: Center.

luaConstant kHAlignLeft
Horizontal alignment: Left.

luaConstant kHAlignRight
Horizonal alignment: Right.

luaConstant kVAlignBottom
Vertical alignment: Bottom.

luaConstant kVAlignCenter
Vertical alignment: Center.

luaConstant kVAlignTop
Vertical alignment: Top.

Navigating the Playground SDK


12.5 Defined Message Types in Lua. 129

12.5 Defined Message Types in Lua.

Constants
• luaConstant kGeneric
• luaConstant kCloseWindow
• luaConstant kDefaultAction
• luaConstant kButtonPress
• luaConstant kPressAnyKey
• luaConstant kQuitNow
• luaConstant kModalClosed
• luaConstant kTextEditChanged
• luaConstant kCommandOnly
• luaConstant kSliderValChanged
• luaConstant kSliderMouseUp
• luaConstant kSliderPageUp
• luaConstant kSliderPageDown
• luaConstant kUserMessageBase

12.5.1 Constant Documentation


luaConstant kButtonPress
A button was pressed.

luaConstant kCloseWindow
A request to close a window. Name of message must be window ID to close (TWindow::GetID()
(p. 515))

luaConstant kCommandOnly
This message is empty; it’s being sent to run the accompanying command.

luaConstant kDefaultAction
A request for the default window action.

luaConstant kGeneric
A generic message

luaConstant kModalClosed
A notification that a modal window was closed.

Playground 4.0.17.1
130 Lua Reference

luaConstant kPressAnyKey
An "any key" was pressed.

luaConstant kQuitNow
A request to terminate the application with prejudice.

luaConstant kSliderMouseUp
The mouse has been released on a slider

luaConstant kSliderPageDown
Someone clicked below the slider handle to create a virtual page-down.

luaConstant kSliderPageUp
Someone clicked above the slider handle to create a virtual page-up.

luaConstant kSliderValChanged
A slider value changed

luaConstant kTextEditChanged
New information has been typed into/removed from a text edit field

luaConstant kUserMessageBase
First ID available for client applications.

Navigating the Playground SDK


12.6 Animation Script Functions 131

12.6 Animation Script Functions

12.6.1 Detailed Description


Supporting Lua functions for the animation system.

Functions

• function delay (ms)


• function pause (ms)
• function showFrame ()
• function fadeout (numberOfFrames)
• function fadein (numberOfFrames)
• function setAlpha (a)
• function frames (framelist)
• function loop (times, framelist)
• function run (table)
• function die ()
• function halt ()
• function isPlaying (depth)
• function stop (depth)
• function random (min, max)

12.6.2 Function Documentation


function delay (ms)
Set the delay time that will be used by showFrame.
Alternately you can call pause(ms) (next page) to pause for a given number of milliseconds.
Parameters:
ms Delay in Milliseconds

function die ()
Kill this animation. The sprite still exists, but with no running script.

function fadein (numberOfFrames)


Do an algorithmic fade-in over the number of frames given. Must call frames() (next page) with a
framelist to make this work, since that’s where the fade-out logic lives.

Playground 4.0.17.1
132 Lua Reference

function fadeout (numberOfFrames)


Do an algorithmic fade-out over the number of frames given. Must call frames() (this page) with
a framelist to make this work, since that’s where the fade-out logic lives.

function frames (framelist)


Display the frames in the given list, once each, with the delay between frames given by delay()
(previous page)
Parameters:
framelist A table with a list of frames.

function halt ()
Pause the script indefinitely: The script and animation still exists, but won’t be updated again until
an external event changes its state to non-paused.

function isPlaying (depth)


Return true if a child is playing or paused. Won’t search past the given depth; -1 means to keep
searching.
Parameters:
depth Levels of children to test for playing.

function loop (times, framelist)


Loop the given frame list.
Parameters:
times Number of times to loop
framelist A table with a list of frames.

function pause (ms)


Pause the animation for the given number of milliseconds
Parameters:
ms Delay in Milliseconds

function random (min, max)


Return a random number between min and max inclusive.
Parameters:
min The lowest number it might return.

Navigating the Playground SDK


12.6 Animation Script Functions 133

max The highest number it might return.

function run (table)


Run an animation in a different XML file: Loads the XML file and associated images and script,
and then executes the given function.
Expected call pattern is run{ "file.xml" } with optional named parameters
Parameters:
table A table consisting of a file to read and several optional parameters:
• function The name of a function to call to start the animations (default DoAnim)
• image The name of an image to override the default image.
• mask The name of a mask image to override the default mask image.

Example: run{ "file.xml", function="DoFirstAnim", image="usethisimage.png" };

function setAlpha (a)


Set the current alpha of this animation.

function showFrame ()
Show the current frame and pause for the delay given in the last call to delay() (p. 131)

function stop (depth)


Stop this animation, and children animations as deep as the given depth parameter.
Parameters:
depth How deep to stop children.

Playground 4.0.17.1
134 Lua Reference

12.7 Lua Particle System Reference

12.7.1 Detailed Description


Supporting Lua functions for the particle system. These functions and constants are available in
any TLuaParticleSystem (p. 264) specification Lua script.
For more information about using the Lua Particle System, see A Lua-Driven Particle System
(p. 57).

Modules
• Blending Constants.

Functions
• function fDistance (a, b)
• function fOpenCycle (lower, upper, steps)
• function fClosedCycle (lower, upper, steps)
• function fAlpha (color, alpha)
• function fDebug (...)
• function fFade (age, state1, time1, state2,{time2, state3,...})
• function fPick (value1{, value2...})
• function fRange (value1, value2)
• function fExpire (value)
• function f2dRadius (radius{, center})
• function f2dRotation (radians)
• function fAge ()
• function fTimeScale (value)
• function fLess (a, b)
• function fLessEqual (a, b)
• function fGreater (a, b)
• function fGreaterEqual (a, b)
• function Done ()
• function RandomFloat ()
• function RandomRange (low, high)
• function Allocate (size)
• function CreateParticles (particles)
• function Value (x)
• function Vec2 (x, y)
• function Vec3 (x, y, z)
• function Color (r, g, b, a)
• function NewParticleGenerator ()

Navigating the Playground SDK


12.7 Lua Particle System Reference 135

12.7.2 Function Documentation


function Allocate (size)
Allocate a particle register.

• size Number of floats in this register Returns a particle register handle.

function Color (r, g, b, a)


An RGBA color made up of floating point values from 0-1.

function CreateParticles (particles)


Create particles. Takes a floating point value which is accumulated, so that if you tell it to create
1.5 particles twice, it will end up producing one particle the first time and two the second time.

function Done ()
Signal to the Lua particle engine that this particle system considers itself to be done.

function f2dRadius ()
Pick a random point on a circle with a given radius.

• radius The radius of the circle.


• center [optional] The center of the circle. Defaults to (0,0)
• Return a Vec2() (p. 139) point on the given circle.

function f2dRotation (radians)


Calculate the x,y point on a unit circle corresponding to the given value in radians.

• radians The point, on the circle, in radians.


• Return a point on the unit circle.

function fAge ()
Return elapsed time.

• Return elapsed time.

function fAlpha (color, alpha)


Replace (or set) the alpha value of a color.
color A color or Vec3() (p. 139). alpha New alpha value. Return A color with the given alpha value.

Playground 4.0.17.1
136 Lua Reference

function fClosedCycle (lower, upper, steps)


Cycles the ouput value from low value to high value, in a given number of steps. In a "closed"
cycle, the exact top value is reached on the last step.
Each time the function is called the next step in the cycle is returned.
For example:

fClosedCycle(0,1,3) Lua

...will return, on successive calls: 0,0.5,1,0,0.5,1

fClosedCycle( Vec2(0,0), Vec2(1,1), 3) Lua

...will return, on successive calls: (0,0),(0.5,0.5),(1.0,1.0),(0,0),(0.5,0.5),(1.0,1.0)

• lower Lower bound.


• upper Upper bound, which is never quite reached.
• steps Steps in the cycle.

function fDebug ( ...)


Write out debug info.
Any parameters given to this function will have their current values written out to the debug log.
All parameters must evaluate to a particle value, i.e. a scalar, Vec2() (p. 139), Vec3() (p. 139), or
Color() (p. 143).
Warning:

Very slow–there is even overhead in a release build! You’ll want to comment these out before
shipping your game.

function fDistance (a, b)


Return the distance between two points. "Points" can be from 1-4 dimensions.

• a First point (used to determine number of dimensions)


• b Second point
p
• Return scalar 2 (x1 − x2 )2 + (y1 − y2 )2 + (z1 − z2 )2 + (w1 − w2 )2 , where any dimensions not in-
cluded in the given points are treated as zero.

function fExpire (value)


Kill a particle if the given test returns a non-zero value.

• value Value to test. If non-zero, then kill this particle.


• No Return Value

Navigating the Playground SDK


12.7 Lua Particle System Reference 137

function fFade (age, state1, time1, state2)


Interpolate a value between states over time.

• state1..n The values to interpolate between.

• time1..n-1 The time to transition between stateN and stateN+1.

• Return an interpolated value. Value will have the same dimensions as input.

function fGreater (a, b)


Test for a greater than b.

• a First operand.

• b Second operand.

• Return true if a>b.

function fGreaterEqual (a, b)


Test for a greater than or equal to b.

• a First operand.

• b Second operand.

• Return true if a>=b.

function fLess (a, b)


Test for a less than b.

• a First operand.

• b Second operand.

• Return true if a<b.

function fLessEqual (a, b)


Test for a less than or equal to b.

• a First operand.

• b Second operand.

• Return true if a<=b.

Playground 4.0.17.1
138 Lua Reference

function fOpenCycle (lower, upper, steps)


Cycles the ouput value from low value to high value, in a given number of steps. In an "open"
cycle, the exact top value is never actually returned.
Each time the function is called the next step in the cycle is returned.
For example:

fOpenCycle(0,1,3) Lua

...will return, on successive calls: 0,0.333,0.666,0,0.333,0.666

fOpenCycle( Vec2(0,0), Vec2(1,1), 3) Lua

...will return, on successive calls: (0,0),(0.333,0.333),(0.666,0.666),(0,0),(0.333,0.333),(0.666,0.666)


For example if you wanted to to spawn twenty particles that explode like a firework from a central
point (dLocus):

pPosition:Init( dLocus ); Lua


pVelocity:Init( f2dRotation( fOpenCycle( 0,6.28,32 ) ) );
pPosition:Anim( pPosition + fTimeScale(pVelocity) );

• lower Lower bound.

• upper Upper bound, which is never quite reached.

• steps Steps in the cycle.

function fPick ()
Pick one of several values randomly.

• value1..n The values to choose.

• Return One of the given values.

function fRange (value1, value2)


Pick a random value in a range. The values can be any number of dimensions from 1-4. For
dimensions greater than one, the result is calculated memberwise, so result[1] becomes a random
value in the range value1[1]-value2[1], etc.

• value1 First bound.

• value2 Second bound.

• Return a value within the range of given values, with the same dimensionality.

Navigating the Playground SDK


12.7 Lua Particle System Reference 139

function fTimeScale (value)


Scale a value by elapsed time. Useful for adding a fractional velocity to position, e.g., so that
velocity can be stored in pixels/second.

• value Value to scale, which is in units/second.


• Return a value in actual units.

function NewParticleGenerator ()
Return a new particle-time calculator. Returns a function that can be used as follows:

NewParticles = NewParticleGenerator() Lua


PPS = 100 -- 100 particles per second
...
function Update( ms )
newParticles= NewParticles( PPS, ms )
CreateParticles( newParticles )
...

function RandomFloat ()
Return a random floating point value, 0-1

function RandomRange (low, high)


Return a random value between low and high, inclusive

function Value (x)


Wrap a scalar value with the proper Lua metatable. Shouldn’t be necessary for most isolated
values, but can be useful if you want to have equations of the form Value(100)-pAge, since having
100-pAge won’t work because of the way Lua resolves operator handling.

function Vec2 (x, y)


Create a 2d vector.

function Vec3 (x, y, z)


Create a 3d vector.

Playground 4.0.17.1
140 Lua Reference

12.8 Lua GUI Command Reference


Lua GUI script function and constant documentation. These functions and constants are available
in the Lua script available from TWindowManager::GetScript() (p. 525).

Functions
• function Color (r, g, b, a)
• function FColor (r, g, b, a)
• function DoWindow (window)
• function MakeDialog (dialogcommands)
• function Window (table)
• function Text (table)
• function TextEdit (table)
• function StripKeyFromLabel (label)
• function Button (window)
• function Bitmap (table)
• function EnableWindow (name, enable)
• function BeginGroup ()
• function GetTag (tab, tag,...)
• function SetDefaultStyle (style)
• function SetStyle (style)
• function AppendStyle (style)
• function SetFocus (name)
• function WaitForCloseMessage (id)
• function DoModal (fileToRead)
• function ModalReturn (value)
• function DisplaySplash (splashMovie, splashGraphic, time)
• function Yield ()
• function ReadFile (fileToRead)
• function CloseWindow (param)
• function CustomCreator (s)
• function GetString (id, p1, p2, p3, p4, p5)
• function CreateNamedMessage (type, name)
• function PostMessage (message)
• function PostMessageToParent (message)
• function GetTimer ()
• function PushModal (name)
• function GetLabel (name)
• function SetLabel (name, label)
• function SetCommand (name, command)
• function GetButtonToggleState (name)

Navigating the Playground SDK


12.8 Lua GUI Command Reference 141

• function SetButtonToggleState (name, state)


• function TagHotKey (hotkey, label)
• function SetBitmap (name, image, scale)
• function PopModal (r)
• function SwapToModal (name)
• function DisplayDialog (t)
• function SelectLayer (layer)
• function Group (t)
• function FitToChildren ()
• function Pause (time, waitForKey)
• function RegisterHotkey (hotkey, buttonName)

12.8.1 Function Documentation


function AppendStyle (style)
Add a table of traits to the current style.

-- Add two traits to the current active style Lua


AppendStyle{ font="fonts/myfont.mvec", x=123 };

The added elements are only added locally; when another style is selected, the appended elements
are discarded.
If you want to permanently change a named style, it’s actually pretty easy: Styles are actually Lua
tables, which are passed around as references, so modifications are always to the original table.
So, to add a trait to a style MyDefaultStyle, you would just use the Lua member accessor:

MyDefaultStyle.font = "fonts/myfont.mvec"; Lua

...or...

MyDefaultStyle["font"] = "fonts/myfont.mvec"; Lua

Parameters:
style (table) A table that describes a style.

function BeginGroup ()
Begin a group of radio buttons. Use before the first radio button in a group.

function Bitmap (table)


Create a bitmap window (TImage (p. 249))
Remarks:
Supported tags include:

Playground 4.0.17.1
142 Lua Reference

• alpha (boolean) True to force the image to have an alpha channel. (default=false)
• hflip (boolean) True to horizontally flip the image. (default=false)
• image (string) Name of the file to load.
• mask (string) Optional image mask (transparency layer) to apply.
• mipmap (boolean) True to force the image to be created with mipmaps. (default=false)
• rotate (boolean) Rotate the image by 90 degrees.
• scale (number) Scale to apply to the image. 1.0==normal image size. (default=1.0)
• vflip (boolean) True to vertically flip the image. (default=false)
• Other generic window tags.
See also:
Window() (p. 153)
Parameters:
table (table) The table that describes the bitmap.
Returns:
A function that does the actual window creation.

function Button (window)


Create a TButton (p. 202)
This function is defined, by default, in the style.lua file that is included with the Playground
Skeleton application.
Remarks:
Supported tags include:
• beginGroup (boolean) This button is the first in a radio-button group.
• close (boolean) This button closes its window/dialog if true.
• command (function) The function to call when the button is clicked. During the function
you can call GetButtonName() to determine the name of the calling button.
• default (boolean) Button is a default button.
• flags (number) Button label text alignment.
• graphics (table) An array of up to four images for the button: Three for push-buttons (Up,
RollOver, Down), Four for toggle and radio buttons (Up, RollOver-Up, Down, RollOver-
Down). If the array has fewer than 3 or 4 images, additional images are duplicated from
the last given image.
• hflip (boolean) Horizontally flip the button images.
• label (string) Default button text label.
• mask (string) Specify a click mask for the button.
• on (boolean) True if the (toggle or radio) button should default to being "on".

Navigating the Playground SDK


12.8 Lua GUI Command Reference 143

• rotate (boolean) Rotate the button image by 90 degrees.


• sendToParent (boolean) Send any button message to the parent of the current top modal
window.
• scale (number) Scale to apply to the button graphics.
• sound (string) Name of sound to play when button pressed.
• rolloversound (string) Name of sound to play when mouse rolls over the button.
• type (number) Button type (kPush, kToggle, kRadio).
• vflip (boolean) Vertically flip the button images.
• Other generic window tags.
Parameters:
window (table) The table that describes the button.
Returns:
A function that does the actual window creation.
See also:
Window() (p. 153)
BeginGroup() (p. 141)

function CloseWindow (param)


Ask the current level of modal window to close and return.
Parameters:
param (string or number) The value that should be returned from the DoModal() (p. 145)
that spawned this window.

function Color (r, g, b, a)


Return a color given r,g,b and optionally alpha. Values should range from 0-255.
Parameters:
r (number) Red value, 0-255.
g (number) Green value, 0-255.
b (number) Blue value, 0-255.
a (number) (optional) Alpha value, 0-255.
Returns:
A table that can be used to represent a color.

function CreateNamedMessage (type, name)


Create a named message

Playground 4.0.17.1
144 Lua Reference

Parameters:
type (number) The integer type of the message.
name (string) The name of the message.
Returns:
A TMessage (p. 294) ∗ wrapped as a Lua object. Pass to PostMessage or PostMessageToParent.
See also:
PostMessage (p. 148)
kCloseWindow (p. 129)
kDefaultAction (p. 129)
kButtonPress (p. 129)
kPressAnyKey (p. 130)
kQuitNow (p. 130)
kModalClosed (p. 129)

function CustomCreator (s)


A function to call with any custom window types, to allow FirstStage to parse the window de-
scription.
Parameters:
s (string) Name of custom window creator.

function DisplayDialog (t)


Present a modal dialog.
Parameters:
t (table) A table, with a string as the first array element that names a Lua file that describes the
dialog, and additional optional parameters to pass to the dialog. Parameters are passed
in global gDialogTable.

function DisplaySplash (splashMovie, splashGraphic, time)


Display a splash movie or bitmap.
For more information on how to format your Flash content to display correctly on Windows and
Mac, see TFlashHost (p. 239).
Note: It is possible to have an overlay display on top of the splash screen bitmap (i.e. for a dis-
tributor logo). This can only be done on top of a bitmap, not a SWF. To do this, you should have a
definition for a variable called "splashoverlay" inside your current default style. For example:

SplashOverlayStyle = { Lua
splashoverlay= Bitmap{ x=30, y=50, image="playfirstlogo" };
};
Then before you call DisplaySplash, call:
SetDefaultStyle(SplashOverlayStyle);

Navigating the Playground SDK


12.8 Lua GUI Command Reference 145

Note that you can also use the default style to control the overall scale of your splash screen graphic
(i.e. scale it up or down):

SplashOverlayStyle = { Lua
splashoverlay= Bitmap{ x=30, y=50, image="playfirstlogo" };
scale=1.3333333
};

There are three tags you can specify in the style before displaying a splash: disableAbort - (default
is false) - if this is true, the user cannot click through the splash screen. translate - (default is
false) - if this is true, the movie will trigger the Flash translation pipeline (see TFlashHost::Play).
allowInput - (default is false) - if this is true, the flash movie will display the system cursor and
accept mouse clicks.
Parameters:
splashMovie (string) Name of SWF file to play.
splashGraphic (string) Name of bitmap to display if Flash fails.
time (number) Time to show bitmap.

function DoModal (fileToRead)


Push a modal window onto the window stack.
Parameters:
fileToRead (string) The name of a Lua file to read that describes the window to push.

function DoWindow (window)


Note:
This function is for advanced users only.

Internal function that actually creates the window. This is the function that the script commands
ultimately call to create the window.
Parameters:
window (table) Table that describes the window.

function EnableWindow (name, enable)


Enable or disable a window by name.
Parameters:
name (string) Name of the window to enable or disable.
enable (boolean) True to enable, false to disable window.
Returns:
True if window was found and enabled/disabled, false if no window by this name found.

Playground 4.0.17.1
146 Lua Reference

function FColor (r, g, b, a)


Return a color given floating point r,g,b and optionally alpha. Values should run from 0-1.
Parameters:
r (number) Red value, 0-1.
g (number) Green value, 0-1.
b (number) Blue value, 0-1.
a (number) (optional) Alpha value, 0-1.
Returns:
A table that can be used to represent a color.

function FitToChildren ()
Cause a window to be resize to encompass current children
Intended to be used in a MakeDialog() (p. 148) context: Actually returns a function that, when
called, will resize the top window on the stack.

function GetButtonToggleState (name)


Get the toggle state of a button
Parameters:
name (string) Name of the button to query.
Returns:
True if the button is "On", false if "Off".

function GetLabel (name)


Get a label from a TText- or TTextEdit-derived window.
Parameters:
name (string) The name of the window to retrieve the label from.

function GetString (id, p1, p2, p3, p4, p5)


Get a string from the string localization table.
Parameters:
id (string) String to look up.
p1..5 (optional string) Optional parameters for string substitution. See
TStringTable::GetString (p. 427) for more information.
Returns:
A string from the string table, or ##### if no string is found

Navigating the Playground SDK


12.8 Lua GUI Command Reference 147

function GetTag (tab, tag, ...)


Get a tag from the table or environment. In normal usage, pass only two parameters.
Parameters:
tab (table) Table with window definition.
tag (string) The tag to query.
Returns:
The tag, either from the table or from the current style. Returns nil if tag isn’t found.

function GetTimer ()
Get the global timer value (TPlatform::Timer (p. 344))
Returns:
Number of milliseconds since the game was started.

function Group (t)


Group a set of windows together.

• t The table containing the windows to group.

Example

Code that creates two buttons based on a common name.

function TwoButtons( name ) Lua


-- First create a table of the window parts using name
t = {
Button { name=name.."buttona", ... },
Button { name=name.."buttonb", ... }
};
-- Return the table
return Group(t);
end
...
-- Then use your function
MakeDialog
{
Bitmap
{
x=0,y=0,
TwoButtons( "test" ),
... -- The rest of the dialog definition can go here
}
}

Parameters:
t (table) A table of window-creation command results.

Playground 4.0.17.1
148 Lua Reference

function MakeDialog (dialogcommands)


Create a dialog. Parses through a table (dialogcommands) which is made up of creator functions
like Bitmap and Button.
The internal operation of MakeDialog assumes that actual function closures are in the table. Win-
dow creation functions like Bitmap() (p. 141) actually return a function closure that is added to the
table.
Parameters:
dialogcommands (table) A table of window creation commands.

function ModalReturn (value)


Return a value from a modal dialog.
Parameters:
value (string or number) A value to return from a modal window.

function Pause (time, waitForKey)


Pause for a specified amount of time.
Parameters:
time (number) Number of milliseconds to wait.
waitForKey (optional boolean) True to abort on a keypress. Defaults to false.

function PopModal (r)


Pop the a particular modal window NOW. Will pop that window and any modal windows that were
pushed on top of that window.
Parameters:
r (string) Window ID or name to pop.

function PostMessage (message)


Post a message to the current message listeners, the current focus, or failing those options, the top
modal window.
Parameters:
message (TMessage*) A message created with CreateNamedMessage or a user function that
returns a TMessage (p. 294) ∗.
See also:
CreateNamedMessage (p. 143)

Navigating the Playground SDK


12.8 Lua GUI Command Reference 149

function PostMessageToParent (message)


Post a message to the parent of the current top modal window.
Parameters:
message (TMessage*) A message created with CreateNamedMessage or a user function that
returns a TMessage (p. 294) ∗.
See also:
CreateNamedMessage (p. 143)

function PushModal (name)


Push a modal window onto the modal window stack. Name the window.

• name (string) Name of the new modal window


Parameters:
name (string) The name of the new modal window.
Returns:
An id that can be passed to WaitForCloseMessage() (p. 153).

function ReadFile (fileToRead)


Read and run a Lua file in the assets folder.
Parameters:
fileToRead (string) Lua file to read.

function RegisterHotkey (hotkey, buttonName)


Register a hot key with the current top modal window. When the key is pressed, it will act as if
the button with the given name has been pressed.
Parameters:
hotkey (string) The key to tie to this button.
buttonName (string) The name of the button to press.
See also:
TModalWindow::AddHotKey()

function SelectLayer (layer)


Select a layer in a TLayeredWindow (p. 252) (like a TButton (p. 202)).
Parameters:
layer (number) The layer number to select.

Playground 4.0.17.1
150 Lua Reference

function SetBitmap (name, image, scale)


Set an image on a TImage-derived window.
Parameters:
name (string) Name of the TImage (p. 249) window.
image (string) New image name.
scale (optional number) Optional scale value.

function SetButtonToggleState (name, state)


Set the toggle state of a button

• name Name of the button to query


• state True to set the button to "On" (TButton::SetOn (p. 205)), false for "Off".
Parameters:
name (string) Name of the button to query.
label (boolean) True to set the button to "On" (TButton::SetOn (p. 205)), false for "Off".

function SetCommand (name, command)


Set a command on a TButton-derived window.
Parameters:
name (string) The name of the button.
command (function) The new command to assign..

function SetDefaultStyle (style)


Set the current default style at a global level. Do not call within a window definition.
Parameters:
style (table) A table that describes a style.

function SetFocus (name)


Set the focus to be window "name".
Parameters:
name (string) Name of window to receive the input focus. Usually a TextEdit window.

function SetLabel (name, label)


Set a label on a TText- or TTextEdit-derived window.
Parameters:
name (string) The name of the TText (p. 433) or TTextEdit (p. 440) window to modify.

Navigating the Playground SDK


12.8 Lua GUI Command Reference 151

label (string) The new label value to set.

function SetStyle (style)


Set the default style within a window definition. The style is selected in the current layer only;
after the closing brace of the current layer, the previously selected style will be restored.
A style is a Lua table with the following form:

MyStyle = Lua
{
parent=DefaultStyle, --- Optionally inherit from style table "DefaultStyle".
tag=value, --- Set tag to value. Any window tag can be set in a style.
tag2=value2, --- etc...
tag3=value3,
};

When the window creation code searches for a tag, it first searches the window creation script
table, then the current style, then parent of the style, and so forth until it finds the tag. Most tags
have a default value that they fall back to when not defined.
Parameters:
style (table) A table that describes a style.

function StripKeyFromLabel (label)


Search a label for & characters, and when found, return the label with the & removed, and the
hot-key the & preceeded.
Parameters:
label (string) The label to be parsed.
Returns:
cleanedLabel,key Two parameters are returned: the cleaned label and the specified key, as-
suming that the & preceeded a valid key character (low-ASCII).

function SwapToModal (name)


Swap the contents of the top level modal window with the window elements contained in an
external definition.
Parameters:
name (string) Name of Lua file to load with new definition.

function TagHotKey (hotkey, label)


Find the first instance of the letter referred to in the given hotkey spec, and tag it in the label so
that it comes out underlined.

Playground 4.0.17.1
152 Lua Reference

Parameters:
hotkey (string) The key to find.
label (string) The label to add an underline tag to.
Returns:
The label with markup to underline the appropriate hot key.

function Text (table)


Create a TText (p. 433) window.
Remarks:
Supported tags include:
• flags Text alignment flags.
• label Text to render.
• Other generic window tags.
Parameters:
table (table) The table that describes the control.
Returns:
A function that does the actual window creation.
See also:
Window() (opposite)
GUI-Related Constants in Lua. (p. 126)

function TextEdit (table)


Create an editable text (TTextEdit (p. 440)) window.
Remarks:
Supported tags include:
• flags Text alignment flags.
• label Initial text.
• password A password field that should be shown as ’∗’s
• length Maximum length of editable field.
• ignore Characters to disallow in edit field.
• utf8 Allow all UTF-8 characters in edit field.
• Other generic window and text tags.
Parameters:
table (table) The table that describes the control.

Navigating the Playground SDK


12.8 Lua GUI Command Reference 153

Returns:
A function that does the actual window creation.
See also:
Text() (opposite)
Window() (this page)
GUI-Related Constants in Lua. (p. 126)

function WaitForCloseMessage (id)


Pause to wait for a particular modal window to close. Pass in the id that was returned from
PushModal() (p. 149), and when that modal window closes this routine will fall out.
Parameters:
id (string) The modal window id, returned from PushModal() (p. 149).

function Window (table)


Create a generic window.
Remarks:
Tags are Lua table entries that contain data that define how the window will be created. Tags
that are not specified in a particular window table are sought in the current style and its
parents.

Supported tags include:

• x, y Window position. Can be specified as an offset from kCenter or kMax.

• w, h Window width and height. Can be specified as an offset from kMax.

• name Window name (used as a handle to search for window and identify it at runtime).

• align Window alignment: A combination of horizontal and vertical alignment flags. See Text
and Window Alignment. (p. 128). Disables special processing of negative position values.

To center a window, specify its x or y position as kCenter, or specify align=kHAlignCenter or


align=kVAlignCenter. To have a window fill its maximum width or height, specify kMax for that
dimension. You can add offsets to either kCenter or kMax to specify a position relative to that
logical anchor. See kCenter (p. 126) or kMax (p. 126) documentation for details.
Using kCenter will override any alignment flags for that axis.
Window position can be specified as negative, which indicates an offset from the opposite edge
(similar to kMax-position). Negative x and y use is deprecated, and will be removed from 4.1. This feature
is disabled if you add an align tag to the window.
Window width and height can be specified as negative, which indicates that x and y are describing
the right or bottom edge of the window.

Playground 4.0.17.1
154 Lua Reference

Parameters:
table (table) The table that describes the control.
Returns:
A function that does the actual window creation.
See also:
kCenter (p. 126)
kMax (p. 126)

function Yield ()
Yield control to C++ code. Returns any parameters passed to Resume().
Returns:
Any values passed to Resume()

Navigating the Playground SDK


Chapter 13

Vertex Rendering Reference

13.1 Vertex Support for Triangle Rendering

13.1.1 Detailed Description


When rendering to triangles or lines using TRenderer::DrawVertices() (p. 376), you need to set up
your vertices using functionality provided in this section.

Classes
• struct TVert
• struct TLitVert
• struct TTransformedLitVert
• class TVertexSet

Functions
• void CreateVertsFromRect (const TVec2 &pos, TTransformedLitVert ∗vertices, TVec2
∗corners, const TVec2 ∗uv, const TMat3 &matrix, float alpha, const TColor &tint)

13.1.2 Function Documentation


void CreateVertsFromRect (const TVec2 & pos, TTransformedLitVert ∗ vertices, TVec2 ∗
corners, const TVec2 ∗ uv, const TMat3 & matrix, float alpha, const TColor & tint)
Create some vertices based on a rectangle and some transformation information. This is a utility
function that is used by several parts of the library internally, but has been exposed because of its
general usefulness.
The resulting vertices can be passed to TRenderer::DrawVertices() (p. 376) with the rendering
type of TRenderer::kDrawTriFan (p. 373).
156 Vertex Rendering Reference

Parameters:
pos Position on screen to anchor rectangle.
vertices An array of four vertices to fill.
corners An array of four corners (first is upper left, then clockwise) relative to x,y that define
the rectangle to create vertices for. Will be transformed by CreateVertsFromRect.
uv An array of two uv coordinates (upper left/lower right).
matrix A transformation matrix to apply to the rectangle.
alpha An alpha value to encode in the vertices.
tint A tint value to encode into the vertices.

Navigating the Playground SDK


Chapter 14

Font Reference

14.1 Introduction

The MVEC File Format is Playground SDK’s font file format. Each glyph is stored as a series of
vector line and curve drawing commands. Because of the vector representation, the glyphs can be
smoothly scaled to many sizes.
Playground’s font rendering is somewhat unconventional, but is designed to make it easy to get
predictable results with a wide variety of fonts and when localizing games to many languages.

14.2 Quadratic Bezier Curves

MVEC’s use quadric Bezier curves, which are defined by 3 control points. The CURVETO com-
mand uses p0 as the current point, and takes additional points as data used as p1 and p2 . The
path of the curve B(t) is defined by:

B(t) = (1 − t)2 p0 + 2t(1 − t)p1 + t 2 p2 ,t ∈ [0, 1]

14.3 Data Types

The MVEC file format uses the following data types:


158 Font Reference

BYTE 1 byte
ULONG 4 bytes: a 32-bit unsigned long in little-endian
byte order
USHORT 2 bytes: a 16-bit unsigned short in
little-endian byte order
VALUE 2 bytes: a 16-bit signed short in little-endian
byte order used to represent a real number.
It’s a 16-bit fixed point representation with
9-bits of integer and 7-bits of decimal. So, if x
is float, then VALUE = (short)(x∗128).

14.4 Vector Commands


The MVEC file format uses the following commands to control how a glyph is drawn. All com-
mand arguments are of type VALUE.
START (2 bytes) Start the glyph 0x01 0x05

MOVETO (5 bytes) Move the "pen" to an x, y 0x04 x y


coordinate
LINETO (5 bytes) Draw a line from the current 0x05 x y
pen position to an x, y
coordinate
CURVETO (9 bytes) Draw a curved line 0x06 x1 y1 x2 y2
(quadratic Bezier) from the
current pen position to x2, y2
with x1, y1 as the control
point
STOP (1 byte) End the glyph 0x08

14.5 File Format Specification


Header (4 bytes)

MVC4

Glyph Count (2-bytes)

USHORT
UNUSED VALUES (6-bytes) reserved for future use

Glyph Table (18-bytes per glyph)


For each glyph in the font:

ULONG (Unicode value for the glyph)


VALUE (minimum X coordinate for the glyph)

Navigating the Playground SDK


14.6 Font Rasterization 159

VALUE (maximum X coordinate for the glyph)


VALUE (minimum Y coordinate for the glyph)
VALUE (maximum Y coordinate for the glyph)
VALUE (x value to advance before drawing the next glyph)
ULONG (offset from the beginning of the file for this glyph’s vector commands)

The remainder of the file is the vector commands for each glyph.
Note: The "advance" value is similar to "kerning" but rather than it being the space between ad-
jacent Glyphs, it’s the space between the starting points for adjacent glyphs. MVEC currently
does not support Kerning tables where character spacing is specialized based on which glyphs are
neighboring each other.

14.6 Font Rasterization

When drawing a glyph, the vectors are rasterized and then filled in using an odd/even fill rule.
That is, for each scan line, from left to right, the first scan line encountered starts the fill, the next
scan line stops the fill, and so on.

14.7 Notes on Font Sizes and Line Height

Fonts are a whole world in and of themselves. There is a rich history and great reasons for a wealth
of complexity. Playground SDK tries to simplify and make fonts practical from the perspective of
a programmer who thinks about fonts as "text that fits in a rectangle".
As such, Playground SDK makes the notion of "line height" primary. All scaling issues are derived
from that constraint. The concepts of "point size" and "leading" are therefore secondary. So in
Playground SDK, the size at which a font is rendered is specified as its line height, where line
height is the exact height in pixels needed to display a line of text at that size, including line-
spacing. (Note a feature is provided to add additional line-spacing when desired for visual effect,
but it is not necessary to use this for text to be adequately spaced).
Playground defines the "tallest" ascender as the glyph for the letter "W".
It defines the "deepest" descender as the deepest descender in the set of "low-ASCII" (UNICODE
values < 128) excluding the glyph for underscore (glyph 95: _).
A line is then defined as follows, 15% of the line will be "above the W", and 5% of the line will
be below the deepest descender (frequently this is "y"). Note that some novelty fonts don’t have
typical descenders (e.g. they are all caps style) — thus, the more algorithmic approach to selecting
the deepest descender. In the other direction, due to more variability in styles, "W" proves to be a
more reliable option.

Playground 4.0.17.1
160 Font Reference

Figure 14.1: Font Example

Given this definition, a scale factor is selected to be applied to the font’s glyphs for the requested
line-height.
After these determinations are made, all glyphs in the font are analyzed. If a particular glyph
would ascend past the top of the line, or descend past the bottom of the line, it is assigned a
y-axis-only scale-factor that will "squish" it to fit.
This scaling approach shows an English language bias, but has been proven to yield beautifully
localized games in languages including Western and Eastern European languages (e.g. Dutch,
Russian) to Asian languages (e.g. Japanese, Korean) to Middle Eastern Languages (e.g. Arabic.
Note that for Arabic, Playground has a string table pre-processing tool to handle UNISCRIBE
issues for right-to-left and cursive texts.)
This scaling approach was derived experimentally, so it "just works" by taking into account things
that were actually encountered across many fonts and many games. For example, the top margin
is bigger than the bottom margin to better accommodate Western European extended glyphs, e.g.,
Á or Ė.

14.8 Call for Help


We’d LOVE it if someone wrote a direct TrueType to MVEC font conversion tool. :-) Especially one
that allowed for easy select of different subsets of glyphs, e.g., Latin-1, Latin-1 + Korean, etc.
Currently, MVEC fonts are most easily created with the swf2mvec utility supplied with Play-
ground. The Adobe SWF file format specifies font vectors in a very similar manner, so the
swf2mvec utility is able to extract MVECs from swfs. However, a more direct conversion tool
would be nice to have.

Navigating the Playground SDK


Chapter 15

Class and File Reference

15.1 str Class Reference


#include <pf/str.h>

15.1.1 Detailed Description


Reference-counted string class.

Operator Definitions
• const char operator[ ] (uint32_t i) const
• str & operator= (const str &s)
• str & operator= (const char ∗p)
• str operator+ (const str &) const
• str operator+ (char) const
• bool operator== (const str &) const
• bool operator< (const str &) const
• bool operator> (const str &) const
• bool operator<= (const str &) const
• bool operator>= (const str &) const
• bool operator!= (const str &s) const
• str & operator+= (const str &s)
• str & operator+= (const char c)

Public Types
• enum eFlags { kCaseInsensitive, kReplaceAll, kReverse }
162 Class and File Reference

Public Member Functions


• str ()
• str (const char ∗s)
• str (const char ∗s, size_t len)
• str (const str &s)
• ∼str ()
• int_fast8_t compare (const str &s) const
• uint32_t length () const
• uint32_t size () const
• bool empty () const
• str & assign (const char ∗s, size_t len)
• str & append (const char ∗s, size_t len)
• str substr (uint32_t pos, int32_t length=npos) const
• int32_t to_int () const
• TReal to_float () const
• void reserve (uint32_t size)
• const char ∗ c_str () const
• void format (const char ∗formatstring,...)
• int32_t find (str searchString, uint32_t flags=0, uint32_t start=0) const
• int32_t find (char searchChar, uint32_t flags=0, uint32_t start=0) const
• str & replace (str searchString, str replaceString, uint32_t flags=0, uint32_t start=0)
• void erase (uint32_t start, int32_t count=npos)
• void unique ()
• uint32_t overlay (int32_t start, const char ∗buffer, uint32_t count, bool bTerminate=true)
• void downcase ()
• unsigned int find_first_of (str s, unsigned int start=0)
• unsigned int find_first_not_of (str s, unsigned int start=0)

Static Public Member Functions


• static str dupchar (uint32_t number, char c=’ ’)
• static str getFormatted (const char ∗formatstring,...)
• static str getFormattedV (const char ∗formatstring, va_list va)
• static int sizeof_utf8_char (const char ∗s)
• static uint32_t utf8length (const char ∗p)
• static str from_utf32 (uint32_t utf)
• static uint32_t to_utf32 (const char ∗utf8)

Static Public Attributes


• static const int32_t npos

Navigating the Playground SDK


15.1 str Class Reference 163

Classes

• class TStringData

15.1.2 Member Enumeration Documentation

enum str::eFlags
Flags for str::find (p. 168) and str::replace (p. 168).
Enumerator:
kCaseInsensitive Case insensitive search.
kReplaceAll Replace all instead of just the first match.
kReverse Search starting from end of string and working backwards. start in this case means
characters from end of string.

15.1.3 Constructor & Destructor Documentation

str::str ()
Create an empty string.

str::str (const char ∗ s)


Create a string from a null-terminated string.
Parameters:
s Pointer to a null terminated string.

str::str (const char ∗ s, size_t len)


Create a string from a buffer and length. Embedded zeros in the source buffer will cause length()
(p. 165) to return shorter than len.
Parameters:
s Pointer to a buffer.
len Length of buffer. String will be created at this length.

str::str (const str & s)


Copy constructor.
Parameters:
s String to copy and add a reference to.

Playground 4.0.17.1
164 Class and File Reference

str::∼str ()
Destructor.

15.1.4 Member Function Documentation


int_fast8_t str::compare (const str & s) const
Compare this string with another.
Parameters:
s String to compare with.
Returns:
Similar to strcmp
• -1 when this string is less than other string
• 0 when strings are equal
• 1 when this string is greater than other string

const char str::operator[ ] (uint32_t i) const


Read-only character access.

str& str::operator= (const str & s)


Assignment operator.
Parameters:
s Source string.
Returns:
A reference to this string.

str& str::operator= (const char ∗ p)


Assignment operator.
Parameters:
p Source char ∗ (c-style string).
Returns:
A reference to this string.

str str::operator+ (const str &) const


Concatenation.

Navigating the Playground SDK


15.1 str Class Reference 165

str str::operator+ (char) const


Concatenation.

bool str::operator== (const str &) const


Equality/inequality.

bool str::operator!= (const str & s) const


Equality/inequality
Parameters:
s String to compare against.

str& str::operator+= (const str & s)


Concatenation.

uint32_t str::length () const


Get the current string length.
Returns:
Length of string not counting null character.

uint32_t str::size () const


Get the current string length.
Returns:
Length of string not counting null character.

bool str::empty () const


Test whether the string is empty.
Returns:
True if empty.

str& str::assign (const char ∗ s, size_t len)


Assign a certain number of characters to str (p. 161).
Parameters:
s Base of string to copy.
len Number of characters.

Playground 4.0.17.1
166 Class and File Reference

Returns:
A reference to this.

str& str::append (const char ∗ s, size_t len)


Append a certain number of characters to str (p. 161).
Parameters:
s Base of string to copy.
len Number of characters.
Returns:
A reference to this.

str str::substr (uint32_t pos, int32_t length = npos) const


Extract a substring.
Parameters:
pos Position to start extracting.
length Number of characters to extract.
Returns:
A new string with the specified characters.

int32_t str::to_int () const


Convert a string to an integer.
Returns:
An integer conversion of the string. If the string begins with non-digits, returns 0.

TReal str::to_float () const


Convert a string to a floating point value.
Returns:
A float conversion of the string. If the string begins with non-digits, returns 0.

void str::reserve (uint32_t size)


Reserve at least size bytes in the internal string buffer.
Parameters:
size Number of bytes to reserve.

Navigating the Playground SDK


15.1 str Class Reference 167

const char∗ str::c_str () const


Get a const char ∗.
Returns:
A const char ∗ to the internal data.

Referenced by TScript::PopBool().

void str::format (const char ∗ formatstring, ...)


Format a string using a printf-style format string.
Warning:

Strings for %s must be passed as char∗ arguments!


Parameters:
formatstring Format string.

static str str::dupchar (uint32_t number, char c = ’ ’)


Create a string consisting of a number of identical characters.
Parameters:
number Number of characters.
c Character to duplicate.
Returns:
A str (p. 161) with the requested duplicated characters.

static str str::getFormatted (const char ∗ formatstring, ...)


Create a formatted string using a printf-style format.
Warning:

Strings for %s must be passed as char∗ arguments!


Parameters:
formatstring Format string.

Referenced by TWindow::GetID().

static str str::getFormattedV (const char ∗ formatstring, va_list va)


Create a formatted string using a printf-style format.
Warning:

Strings for %s must be passed as char∗ arguments!

Playground 4.0.17.1
168 Class and File Reference

Parameters:
formatstring Format string.
va var-args argument list.

int32_t str::find (str searchString, uint32_t flags = 0, uint32_t start = 0) const


Find a substring.
Parameters:
searchString String to find.
flags eFlags for options.
start Search start.
Returns:
An offset into the string where found; npos if not found.

int32_t str::find (char searchChar, uint32_t flags = 0, uint32_t start = 0) const


Find a character in this string.
Parameters:
searchChar Character to search for.
flags eFlags for options.
start Start search position.
Returns:
An offset into the string where found; npos if not found.

str& str::replace (str searchString, str replaceString, uint32_t flags = 0, uint32_t start = 0)
Search-and-replace a substring.
Parameters:
searchString String to find.
replaceString String to replace found string with (can be empty).
flags eFlags for options.
start Search start.
Returns:
A reference to this str (p. 161).

void str::erase (uint32_t start, int32_t count = npos)


Erase a range of characters in the string
Parameters:
start First character to erase.
count Number of characters to erase. npos for the rest of the string.

Navigating the Playground SDK


15.1 str Class Reference 169

void str::unique ()
Force this instance of this string to be unique; prepare for modification.

uint32_t str::overlay (int32_t start, const char ∗ buffer, uint32_t count, bool bTerminate = true)
Overlay a string into the current string.
Parameters:
start Start of the new overlay as an index into the current string. Can be (or extend) beyond
the end of the string. Can also be npos, to indicate the end of the string.
buffer String to overlay. Is 8-bit safe (can contain NULL bytes).
count Size of string to overlay.
bTerminate True to add a NULL character in the str (p. 161) at the end of this overlay.
Returns:
The character index past the end of the overlayed characters.

void str::downcase ()
Convert this string to lower-case in place.

unsigned int str::find_first_of (str s, unsigned int start = 0)


Find the first character that matches the set given by s.
Parameters:
s Set of characters to search for.
start First character to inspect.
Returns:
The offset of the first character that matches, or str::length() (p. 165) no characters match.

unsigned int str::find_first_not_of (str s, unsigned int start = 0)


Find the first character that doesn’t match any in the set given by s.
Parameters:
s Set of characters to compare with.
start First character to inspect.
Returns:
The offset of the first character that does not match, or str::length() (p. 165) if all characters
match.

static int str::sizeof_utf8_char (const char ∗ s)


Calculate the size of a UTF8 character.

Playground 4.0.17.1
170 Class and File Reference

Parameters:
s Pointer to the character.
Returns:
Number of bytes in this character. Zero if the character is a null terminator.

Referenced by utf8length().

static uint32_t str::utf8length (const char ∗ p)


Calculate the length, in characters, of a UTF-8 string.
Parameters:
p Pointer to const char ∗ string of UTF-8 characters.
Returns:
The number of UTF-8 characters in a string.

References sizeof_utf8_char().

static str str::from_utf32 (uint32_t utf)


Convert a UTF-32 character code point to UTF-8.
Parameters:
utf UTF-32 value.
Returns:
A str (p. 161) with a single UTF-8 character.

static uint32_t str::to_utf32 (const char ∗ utf8)


Convert a UTF-8 character to a UTF-32 character.
Parameters:
utf8 Pointer to a 1-4 byte UTF-8 character.
Returns:
A UTF-32 character.

15.1.5 Member Data Documentation


const int32_t str::npos
Non-position in string. Similar to STL.

Navigating the Playground SDK


15.2 T2dParticle Class Reference 171

15.2 T2dParticle Class Reference


#include <pf/2dparticlerenderer.h>

15.2.1 Detailed Description


Basic Particle Values.
See also:
T2dParticleRenderer (next page)

Public Attributes
• TVec2 mPosition
• TVec2 mUp
• TReal mScale
• TColor mColor
• TReal mFrame

15.2.2 Member Data Documentation


TVec2 T2dParticle::mPosition
Particle position. Referenced as pPosition in a Lua particle script.

TVec2 T2dParticle::mUp
Current up vector of particle. Referenced as pUp.

TReal T2dParticle::mScale
Current scale of particle. Referenced as pScale.

TColor T2dParticle::mColor
Current particle color. Referenced as pColor.

TReal T2dParticle::mFrame
Current frame of the particle animation (as int). Referenced as pFrame.

Playground 4.0.17.1
172 Class and File Reference

15.3 T2dParticleRenderer Class Reference


#include <pf/2dparticlerenderer.h>
Inheritance diagram for T2dParticleRenderer:

TParticleRenderer

T2dParticleRenderer

15.3.1 Detailed Description


A particle renderer that expects 2d particles. This is the default particle renderer used by TLua-
ParticleSystem (p. 264).
T2dParticleRenderer (this page) defines five particle registers:

• pPosition [2] The 2d position of a particle.

• pUp [2] The 2d "up" vector of a particle.

• pScale [1] The current particle scale.

• pColor [4] The current particle color.

• mFrame [1] The current particle frame (when using a TAnimatedTexture (p. 182)).
See also:
T2dParticle (previous page)
TLuaParticleSystem (p. 264)

Public Member Functions


• T2dParticleRenderer ()
• virtual ∼T2dParticleRenderer ()
• virtual void Draw (const TVec3 &at, TReal alpha, const ParticleList &particles, int maxPar-
ticles)
• void SetParticleSize (const TVec2 &size)
• void SetBlendMode (TRenderer::EBlendMode mode)
• virtual void SetTexture (TTextureRef texture)
• virtual void SetRendererOption (str option, const TReal(&value)[4])
• virtual uint32_t GetPrototypeParticleSize ()
• virtual TReal ∗ GetPrototypeParticle ()
• virtual str GetLuaInitString ()

Navigating the Playground SDK


15.3 T2dParticleRenderer Class Reference 173

15.3.2 Constructor & Destructor Documentation


T2dParticleRenderer::T2dParticleRenderer ()
Default Constructor.

virtual T2dParticleRenderer::∼T2dParticleRenderer ()
Destructor.

15.3.3 Member Function Documentation


virtual void T2dParticleRenderer::Draw (const TVec3 & at, TReal alpha, const ParticleList &
particles, int maxParticles)
Render the particles.
Parameters:
at Location to render particles.
alpha Alpha to render particles with.
particles The list of particles to render.
maxParticles The maximum number of particles this particle system is expecting to render.
MUST be greater than the number of particles or Bad Things will happen.

Implements TParticleRenderer (p. 320).

void T2dParticleRenderer::SetParticleSize (const TVec2 & size)


Size of the particle object to render.
Parameters:
size Width and height of particle square on screen in pixels.

void T2dParticleRenderer::SetBlendMode (TRenderer::EBlendMode mode)


Set the blend mode for a particular layer.
Parameters:
mode Blend mode

virtual void T2dParticleRenderer::SetTexture (TTextureRef texture)


Set the texture for the particle.
Parameters:
texture Texture to use.

Implements TParticleRenderer (p. 321).

Playground 4.0.17.1
174 Class and File Reference

virtual void T2dParticleRenderer::SetRendererOption (str option, const TReal(&) value[4])


Set a renderer-specific option.
Parameters:
option Option to set.
value Value to set option to, in the form of an array of TReals. Not all values in array are
relevant for all options.

Implements TParticleRenderer (p. 321).

virtual uint32_t T2dParticleRenderer::GetPrototypeParticleSize ()


Size of the array of TReals returned by GetPrototypeParticle.
Returns:
Number of reals.

Implements TParticleRenderer (p. 321).

virtual TReal∗ T2dParticleRenderer::GetPrototypeParticle ()


Get an initialized particle that will be copied over each particle after creation but before running
initializers.
Returns:
A pointer to an array of TReals.

Implements TParticleRenderer (p. 321).

virtual str T2dParticleRenderer::GetLuaInitString ()


Get a TLuaParticleSystem (p. 264) initialization string.
Returns:
A valid Lua string that will be executed by a TLuaParticleSystem (p. 264) that uses this ren-
derer.

Implements TParticleRenderer (p. 321).

Navigating the Playground SDK


15.4 TAnimatedSprite Class Reference 175

15.4 TAnimatedSprite Class Reference


#include <pf/animatedsprite.h>
Inheritance diagram for TAnimatedSprite:

TSprite

TAnimatedSprite

15.4.1 Detailed Description

A TSprite (p. 419) with an attached TScript (p. 389). Similar to TSprite (p. 419), a TAnimated-
Sprite (this page) should only ever be stored as a reference, but it will work to store one in either
a TAnimatedSpriteRef or a TSpriteRef.
Typically you will assign a TAnimatedTexture (p. 182) to a TAnimatedSprite (this page); however,
it is legal to assign a normal TTexture (p. 463) to a TAnimatedSprite (this page) instead. Obviously
the animation script will be unable to change "frames" if a normal TTexture (p. 463) is attached,
however.

Initialization/Destruction

• void SetClock (TClock ∗clock)


• virtual ∼TAnimatedSprite ()
• static TAnimatedSpriteRef Create (int32_t layer=0)

Drawing

• virtual void Draw (const TDrawSpec &drawSpec=TDrawSpec(), int32_t depth=-1)

Animation Control

• void Play (str functionName="DoAnim")


• void Stop ()
• void Pause (bool pause, int32_t depth=-1)
• void Die ()
• bool IsPlaying (int32_t depth=-1)
• bool IsDone (int32_t depth=-1)

Playground 4.0.17.1
176 Class and File Reference

Frame Access
• void SetCurrentFrame (int32_t frame)
• int32_t GetCurrentFrame ()

Script and Texture Access


• TScript ∗ GetScript ()
• TScriptCodeRef GetScriptCode ()
• void NewScript ()
• void NewThread ()
• virtual void SetTexture (TTextureRef texture)
• TAnimatedTextureRef GetAnimatedTexture ()
• uint32_t GetNumAnchors ()
• uint32_t GetNumFrames ()

Utility
• TAnimatedSpriteRef GetRef ()

Public Member Functions


• virtual bool HitTest (const TPoint &at, const TDrawSpec &parentContext, int32_t opacity=-
1, int32_t depth=-1)
• virtual TRect GetRect (const TDrawSpec &parentContext, int32_t depth=-1)

Protected Member Functions


• TAnimatedSprite (int32_t layer)

15.4.2 Constructor & Destructor Documentation


TAnimatedSprite::TAnimatedSprite (int32_t layer) [protected]
Default Constructor.
Parameters:
layer The initial layer for the sprite.

virtual TAnimatedSprite::∼TAnimatedSprite ()
Destructor.

Navigating the Playground SDK


15.4 TAnimatedSprite Class Reference 177

15.4.3 Member Function Documentation


virtual bool TAnimatedSprite::HitTest (const TPoint & at, const TDrawSpec & parentContext,
int32_t opacity = -1, int32_t depth = -1)
Test to see if a point is within our sprite.
Parameters:
at Point to test.
parentContext The parent context to test within–where is this sprite being drawn, and with
what matrix? Alpha and color information is ignored.
opacity Level of opacity to test for; -1 for a simple bounding box test, or 0-255 for alpha color
value, where 0 is transparent (and will therefore always succeed).
depth Depth of children to test. Zero means only test this sprite. -1 means test
Returns:
true if point hits us.

Reimplemented from TSprite (p. 424).

virtual TRect TAnimatedSprite::GetRect (const TDrawSpec & parentContext, int32_t depth =


-1)
Get the rect of this sprite.
Parameters:
parentContext The parent context to test within–where is this sprite being drawn, and with
what matrix? Alpha and color information is ignored.
depth Depth of children to test
Returns:
Rectangle that includes this sprite.

Reimplemented from TSprite (p. 424).

static TAnimatedSpriteRef TAnimatedSprite::Create (int32_t layer = 0)


Factory
Parameters:
layer Layer of sprite.
Returns:
A reference to a new sprite.

void TAnimatedSprite::SetClock (TClock ∗ clock)


Set the animation to use the passed in clock as its timer. To be effective, must be called before a call
to Play() (next page) is issued.

Playground 4.0.17.1
178 Class and File Reference

Parameters:
clock Clock to use for timing. If NULL, then the global timer is used.

virtual void TAnimatedSprite::Draw (const TDrawSpec & drawSpec = TDrawSpec(), int32_t


depth = -1)
Draw the sprite and its children.
Parameters:
drawSpec The ’parent’ drawspec–the frame of reference that this sprite is to be rendered in.
Defaults to a default-constructed TDrawSpec (p. 223). See TDrawSpec (p. 223) for more
details on what is inherited.
depth How many generations of children to draw; -1 means all children.
See also:
TDrawSpec (p. 223)

Reimplemented from TSprite (p. 422).

void TAnimatedSprite::Play (str functionName = "DoAnim")


Plays an animation script
Parameters:
functionName Name of lua function to run. By default this is "DoAnim"

void TAnimatedSprite::Stop ()
Stops an animation script that’s already playing.
Scripts will retain global variable settings even after they’re stopped.

void TAnimatedSprite::Pause (bool pause, int32_t depth = -1)


Pauses/un-pauses a specific animation. An alternative to calling Pause() (this page) on several
different TAnimatedTextures is to have them all use the same TClock (p. 213), and pause the clock
instead.
Parameters:
pause true to pause/false to un-pause
depth How many levels to recurse in modifying child animations.

void TAnimatedSprite::Die ()
Stop and eradicate the script associated with an animation.
Any variables saved in the global environment will be erased. The next time you call Play() (this
page) or GetScript() (opposite) it will reload any associated TAnimatedTexture() script.

Navigating the Playground SDK


15.4 TAnimatedSprite Class Reference 179

bool TAnimatedSprite::IsPlaying (int32_t depth = -1)


Test whether or not the animation is currently playing.
Parameters:
depth How many levels to recurse in testing child sprite animations to see if they’re playing.
Default is -1 which means to recurse with no limit.
Returns:
True if the animation or one of its children is playing.

bool TAnimatedSprite::IsDone (int32_t depth = -1)


Return whether or not the animation has signalled it’s really done by calling die() (p. 131).
Parameters:
depth How many levels to recurse in testing child animations.
Returns:
true if the animation is done.

void TAnimatedSprite::SetCurrentFrame (int32_t frame)


Set the current animation frame.
Does not affect children.
Parameters:
frame Frame number.

int32_t TAnimatedSprite::GetCurrentFrame ()
Get the current animation frame.
Returns:
Current animation frame number.

TScript∗ TAnimatedSprite::GetScript ()
Gets the current script associated with this animation. Creates a script if one doesn’t exist already.
DO NOT CACHE this pointer: this script can change over time. As long as you don’t call Die()
(opposite) on this animation or reload it from a file, it will copy its environment across scripts,
so you can set global variables and be reasonably assured that when you hit "Play" it will retain
them–even if it’s running in a different TScript (p. 389) (technically a different thread).
Returns:
The current script.

Playground 4.0.17.1
180 Class and File Reference

TScriptCodeRef TAnimatedSprite::GetScriptCode ()
Get a reference to the compiled script code, to allow you to keep a reference to it so that it won’t
be reloaded next time you run the same animation.
Returns:
A reference to the loaded script, or an empty reference if no script was loaded, or if the script
was run from a string or XML file.

void TAnimatedSprite::NewScript ()
Reset the script to a virgin one that has been initialized with the proper animation functions.
Not necessary to call prior to LoadScript or InitXML, as these functions will call it if no script has
been loaded. However, if you want a clean interpreter state, you can call this function.

virtual void TAnimatedSprite::SetTexture (TTextureRef texture)


Set the texture of the sprite object. Can be a TAnimatedTexture (p. 182) or a regular TTexture
(p. 463); if it’s a TTexture (p. 463), the script and animation control functions will only be relevant
to any child sprites that have TAnimatedTextures assigned.
Parameters:
texture Texture to use.

Reimplemented from TSprite (p. 424).

TAnimatedTextureRef TAnimatedSprite::GetAnimatedTexture ()
Return an animated texture, if one is attached. If no texture is attached, or if a normal TTexture
(p. 463) is attached, return an empty reference.
Returns:
A TAnimatedTextureRef, if one is bound to this sprite.

uint32_t TAnimatedSprite::GetNumAnchors ()
Get the number of anchors in the bound animation.
Returns:
Number of anchors. Returns zero if there is no animated texture attached.

uint32_t TAnimatedSprite::GetNumFrames ()
Get the number of frames in the bound animation.
Returns:
Number of frames in the animation. Returns one (1) if there is no animated texture attached.

Navigating the Playground SDK


15.4 TAnimatedSprite Class Reference 181

TAnimatedSpriteRef TAnimatedSprite::GetRef ()
Get the TAnimatedSpriteRef for this TAnimatedSprite (p. 175).

Playground 4.0.17.1
182 Class and File Reference

15.5 TAnimatedTexture Class Reference


#include <pf/animatedtexture.h>
Inheritance diagram for TAnimatedTexture:

TAsset

TTexture

TAnimatedTexture

15.5.1 Detailed Description


This class encapsulates the concept of an animated texture. This kind of texture is placed directly
in video RAM, so be conservative about how large you allow concurrent game animations to
become: Consider that a 1024x1024x32 bit texture takes up 4Mb of video RAM, so if you are trying
to display more than 10 such textures simultaneously you may start getting performance problems
as textures are swapped in and out of video RAM.
A TAnimatedTexture (this page) loads in an xml (or anm) file describing the animation, and an
image file with multiple source frames.
Additionally, the xml file can describe hot spots, where other textures can be attached.
A Lua script can be embedded in the TAnimatedTexture (this page) which can be played back by
a TAnimatedSprite (p. 175). The TAnimatedTexture (this page) doesn’t have playback capability
itself because it represents the raw texture object, and you can have multiple instances of it on the
screen at once.
When you use TTexture::Lock() (p. 469) on a TAnimatedTexture (this page), you will lock the
full texture surface–which means that TAnimatedTexture::GetWidth() (p. 189) and TAnimat-
edTexture::GetHeight() (p. 189) will return the wrong values. Instead, you should call TTex-
ture::GetWidth() (p. 469) and TTexture::GetHeight() (p. 469). For example:

TAnimatedTextureRef at = ...; C++


uint32_t w = at->TTexture::GetWidth() ; // This gives you the real texture width

Factory Methods/Destruction

• static TAnimatedTextureRef Get (str assetName, str imageOverride="", str maskOver-


ride="")
• static str GetHandle (str assetName, str imageOverride="", str maskOverride="")
• virtual ∼TAnimatedTexture ()

Navigating the Playground SDK


15.5 TAnimatedTexture Class Reference 183

Drawing Methods
• virtual void CopyPixels (int32_t x, int32_t y, const TRect ∗sourceRect, TTextureRef _dst)
• virtual void DrawSprite (TReal x, TReal y, TReal alpha, TReal scale, TReal rotRad, uint32_t
flags)
• virtual void DrawSprite (const TDrawSpec &drawSpec)

Frame Sequence Information/Update


• uint32_t GetNumFrames ()
• void SetCurrentFrame (int32_t frame)
• int32_t GetCurrentFrame ()
• int32_t GetFrameByName (str name)
• TRect GetAnimationBoundingBox ()
• TRect GetBoundingBox (int32_t frame)
• TRect GetFrameRect (int32_t frame)
• TReal GetFrameAlpha (int32_t frame)

Anchor Point Support (not needed for most animations).


Anchor points are used to track animated offsets; for instance, the hand of a character that needs
to have an object attached might get an animated anchor.

• bool GetAnchorPoint (str name, int32_t ∗x, int32_t ∗y)


• bool GetAnchorPoint (int32_t frame, str name, int32_t ∗x, int32_t ∗y)
• uint32_t GetNumAnchors ()
• bool GetAnchorInfo (int32_t anchorNum, int32_t ∗x, int32_t ∗y, str ∗name)

Image and Frame Data


The data that specifies how each frame needs to be rendered.

• TPoint GetRegistrationPoint ()
• TPoint GetRegistrationPoint (int32_t frame)
• virtual uint32_t GetWidth ()
• virtual uint32_t GetHeight ()

Utility Functions
• str GetScript ()
• str GetPath ()
• TAnimatedTextureRef GetRef ()

Playground 4.0.17.1
184 Class and File Reference

Public Types
• enum { kNoFrame }

Protected Member Functions


• TAnimatedTexture ()
• virtual void Restore ()

Protected Attributes
• TAnimatedTextureData ∗ mATData

15.5.2 Constructor & Destructor Documentation


TAnimatedTexture::TAnimatedTexture () [protected]
Construction is through the factory method.

virtual TAnimatedTexture::∼TAnimatedTexture ()
Destructor.

15.5.3 Member Function Documentation


static TAnimatedTextureRef TAnimatedTexture::Get (str assetName, str imageOverride = "",
str maskOverride = "")
Get a TAnimatedTextureRef given an animation name. The animation name should be an xml or
anm file describing the animation.
Parameters:
assetName Name of the xml or anm file which contains the animation data. You can leave off
the extension and it will search first for .xml, and then for .anm.
imageOverride Optional image file name to load for this texture, instead of using image
named in the xml file
maskOverride Optional mask file name to load for this texture, instead of using mask named
in the xml file
Returns:
A TAnimatedTextureRef. This ref will be NULL if it is unable to load.

static str TAnimatedTexture::GetHandle (str assetName, str imageOverride = "", str


maskOverride = "")
Get the handle that an animated texture will be registered in the global asset manager as.

Navigating the Playground SDK


15.5 TAnimatedTexture Class Reference 185

Parameters:
assetName Name of asset.
imageOverride Image Override (if any)
maskOverride Mask Override (if any)
Returns:
A string that represents the handle of the object.

virtual void TAnimatedTexture::CopyPixels (int32_t x, int32_t y, const TRect ∗ sourceRect,


TTextureRef _dst)

Delegates to TTexture::CopyPixels() (p. 468), which means that it will copy from the multi-frame
source image, not from the individual frame.
Parameters:
x Left side of resulting rectangle.
y Top edge of resulting rectangle.
sourceRect Source rectangle to blit. NULL to blit the entire surface.
_dst Destination texture. NULL to draw to back buffer.
See also:
TTexture::CopyPixels (p. 468)

Reimplemented from TTexture (p. 468).

virtual void TAnimatedTexture::DrawSprite (TReal x, TReal y, TReal alpha, TReal scale,


TReal rotRad, uint32_t flags)
Draw a normal texture to a render target surface as a sprite. This draws a texture with optional
rotation and scaling. Only capable of drawing an entire surface–not a sub-rectangle.
Will draw the sprite within the currently active viewport. X and Y are relative to the upper left
corner of the current viewport.
DrawSprite can be called inside TWindow::Draw() (p. 503) or a BeginRenderTarget/EndRender-
Target block.
Parameters:
x x Position where center of sprite is to be drawn.
y y Position where center of sprite is to be drawn.
alpha Alpha to apply to the entire texture. Set to a negative value to entirely disable alpha
during blit, including alpha within the source TTexture (p. 463).
scale Scaling to apply to the texture. 1.0 is no scaling.
rotRad Rotation in radians.
flags Define how textures are drawn. Use ETextureDrawFlags for the flags. Default behavior
is eDefaultDraw.

Reimplemented from TTexture (p. 467).

Playground 4.0.17.1
186 Class and File Reference

virtual void TAnimatedTexture::DrawSprite (const TDrawSpec & drawSpec)


Draw an animated texture. Draws the current frame of the animated texture.
Parameters:
drawSpec The TDrawSpec (p. 223) to use to draw the sprite.
See also:
TTexture::DrawSprite (p. 467)

Reimplemented from TTexture (p. 468).

uint32_t TAnimatedTexture::GetNumFrames ()
Get number of frames in this animation
Returns:
Number of frames in animation.

void TAnimatedTexture::SetCurrentFrame (int32_t frame)


Set the current frame of the animation.
Parameters:
frame Frame to set animation to, from 0 to n-1, where n is the number of frames.

int32_t TAnimatedTexture::GetCurrentFrame ()
Get the current frame of the animation
Returns:
frame Current frame of animation, from 0 to n-1, where n is the number of frames.

int32_t TAnimatedTexture::GetFrameByName (str name)


Get a frame by the frame’s name
Parameters:
name Name of frame to retrieve.
Returns:
frame Frame number, or -1 if it doesn’t exist;

TRect TAnimatedTexture::GetAnimationBoundingBox ()
Get the bounding rectangle for this animation.
Returns:
a TRect (p. 364) that would contain the entire animation.

Navigating the Playground SDK


15.5 TAnimatedTexture Class Reference 187

TRect TAnimatedTexture::GetBoundingBox (int32_t frame)


Get the bounding rectangle for a specific animation frame
Returns:
a TRect (p. 364) that would contain the current frame of the animation
Parameters:
frame Frame to query.
Returns:
The bounding box of this frame.

TRect TAnimatedTexture::GetFrameRect (int32_t frame)


Get the location of a specific frame inside the animation texture.
Returns:
a TRect (p. 364) that would contain the frame inside the animation texture
Parameters:
frame Frame to query.
Returns:
The location of this frame inside the animation texture.

TReal TAnimatedTexture::GetFrameAlpha (int32_t frame)


Get the alpha value associated with a frame.
Parameters:
frame Frame to retrieve the alpha value from.
Returns:
0.0 (transparent) - 1.0 (opaque).

bool TAnimatedTexture::GetAnchorPoint (str name, int32_t ∗ x, int32_t ∗ y)


Get anchor point information for the current frame of the animation
Parameters:
name Name of anchor point to retrieve
x [out] Fills in with x coordinate of anchor point if it exists
y [out] Fills in with y coordinate of anchor point if it exists
Returns:
true if the anchor point exists, false otherwise

Playground 4.0.17.1
188 Class and File Reference

bool TAnimatedTexture::GetAnchorPoint (int32_t frame, str name, int32_t ∗ x, int32_t ∗ y)


Get anchor point information for the selected frame of the animation
Parameters:
frame Frame index of frame to query.
name Name of anchor point to retrieve
x [out] Fills in with x coordinate of anchor point if it exists
y [out] Fills in with y coordinate of anchor point if it exists
Returns:
true if the anchor point exists, false otherwise

uint32_t TAnimatedTexture::GetNumAnchors ()
Get number of anchors in this frame of animation
Returns:
Number of anchors in this frame of animation.

bool TAnimatedTexture::GetAnchorInfo (int32_t anchorNum, int32_t ∗ x, int32_t ∗ y, str ∗


name)
Get anchor information
Parameters:
anchorNum Which anchor to fetch
x [out] Fills in with x coordinate of anchor point if it exists
y [out] Fills in with y coordinate of anchor point if it exists
name [out] Fills in name of anchor
Returns:
true if anchorNum is valid, false otherwise

TPoint TAnimatedTexture::GetRegistrationPoint ()
Get the initial image registration point.
The registration point is point from which the image coordinates are calculated.
Returns:
Registration point

TPoint TAnimatedTexture::GetRegistrationPoint (int32_t frame)


Get the registration point of a frame.
Parameters:
frame Frame number

Navigating the Playground SDK


15.5 TAnimatedTexture Class Reference 189

Returns:
Registration point

virtual uint32_t TAnimatedTexture::GetWidth ()


Get the width of the texture. This gets the size of the texture as requested at creation or load;
the actual internal size of the texture may vary. If you’re using this texture as a source for TRen-
derer::DrawVertices (p. 376), see GetInternalSize.
Returns:
Width of the texture in pixels.

Reimplemented from TTexture (p. 469).

virtual uint32_t TAnimatedTexture::GetHeight ()


Get the height of the texture. This gets the size of the texture as requested at creation or load;
the actual internal size of the texture may vary. If you’re using this texture as a source for TRen-
derer::DrawVertices (p. 376), see GetInternalSize.
Returns:
Height of the texture in pixels.

Reimplemented from TTexture (p. 469).

str TAnimatedTexture::GetScript ()
Get the animation script that was embedded in the XML file.
Returns:
Animation script

str TAnimatedTexture::GetPath ()
Get the path to the source data file.
Returns:
A string that represents the path to the source data file.

TAnimatedTextureRef TAnimatedTexture::GetRef ()
Get a shared pointer (TAnimatedTextureRef) to this texture.
Returns:
A TAnimatedTextureRef that shares ownership with other Refs to this texture.

Reimplemented from TTexture (p. 471).

Playground 4.0.17.1
190 Class and File Reference

virtual void TAnimatedTexture::Restore () [protected]


Restore an asset.
Reimplemented from TAsset (p. 195).

15.5.4 Member Data Documentation


TAnimatedTextureData∗ TAnimatedTexture::mATData [protected]
Internal implementation data.

Navigating the Playground SDK


15.6 TAnimTask Class Reference 191

15.6 TAnimTask Class Reference


#include <pf/animtask.h>
Inheritance diagram for TAnimTask:

TTask

TAnimTask

TScript

15.6.1 Detailed Description


The TAnimTask (this page) interface. Used as a "callback" for animation or other timed repeating
tasks. Can also be used as a simple delayed task: You can call TPlatform::AdoptTask() (p. 345)
to adopt a TAnimTask-derived class that will trigger after its delay expires, and then just have its
Animate() (next page) call return false to let it be destroyed.
See also:
TTask (p. 429)

Public Member Functions

• TAnimTask (TClock ∗clock=NULL)


• void SetDelay (uint32_t delay, bool autoRepeat=true, bool resetTime=true, bool forceFre-
quency=false)
• void Pause ()
• uint32_t GetTimeUntilReady ()
• virtual bool Animate ()=0
• void RunOnDraw (bool enable)
• void SetClock (TClock ∗clock)
• TClock ∗ GetClock ()
• uint32_t GetTime ()

15.6.2 Constructor & Destructor Documentation


TAnimTask::TAnimTask (TClock ∗ clock = NULL)
Constructor

Playground 4.0.17.1
192 Class and File Reference

Parameters:
clock Clock that this anim task uses to determine how much time has passed. If this parame-
ter is null then the global clock is used.

15.6.3 Member Function Documentation

void TAnimTask::SetDelay (uint32_t delay, bool autoRepeat = true, bool resetTime = true,
bool forceFrequency = false)
Set the animation delay.
Parameters:
delay Number of milliseconds to wait to call DoTask().
autoRepeat Repeat this delay after every task.
resetTime Reset the time so that the (initial) delay is counted from now rather than from the
last task event time.
forceFrequency Force the frequency to be the same as the delay implies; will run the Ani-
mate() (this page) call multiple times if more than twice the time of delay has elapsed
since the last call.

Will not work if resetTime is also true, since resetTime causes the time to be set to the now+delay
after the first call, and as such forceFrequency will never cause it to loop.

void TAnimTask::Pause ()
Pause the current task. Prevents the Animate task from being called.
Resume by calling SetDelay() (this page) or RunOnDraw() (opposite), as appropriate.

uint32_t TAnimTask::GetTimeUntilReady ()
Get the number of milliseconds before this task will be ready to trigger again.
Returns a negative number if the next call to Ready() would be true immediately.
Returns:
Number of milliseconds before this task is ready. Returns UINT_MAX if task is disabled.

virtual bool TAnimTask::Animate ()


Define this function to add the actual animation task.
Returns:
True to continue, false when we’re done.

Implemented in TScript (p. 395).

Navigating the Playground SDK


15.6 TAnimTask Class Reference 193

void TAnimTask::RunOnDraw (bool enable)


Enable the "Run on Draw" feature, which executes this task prior to every actual screen update. If
you want the task to run on draw as well as on a timer, set up the timer using SetDelay() (opposite)
normally. If you want to only get called when the screen is about to update, then call Pause()
(opposite) before you call RunOnDraw() (this page). Calling Pause after you call RunOnDraw will
disable RunOnDraw.
Parameters:
enable True to enable "Run on Draw", false to disable.

void TAnimTask::SetClock (TClock ∗ clock)


Set the reference clock. Useful for having one clock that can be paused and resumed to pause and
resume a set or class of TAnimTasks.
Parameters:
clock Clock to use to time animations.

TClock∗ TAnimTask::GetClock ()
Get the reference clock.
Returns:
A pointer to the currently associated clock.

uint32_t TAnimTask::GetTime ()
Get the current elapsed time of the attached clock.
Returns:
Current elapsed time.

Playground 4.0.17.1
194 Class and File Reference

15.7 TAsset Class Reference


#include <pf/asset.h>
Inheritance diagram for TAsset:

TAsset

TModel TScriptCode TSound TTexture

TAnimatedTexture

15.7.1 Detailed Description

The interface class for game assets.


Playground-defined TAssets are managed internally by the engine such that if you have a reference
to one anywhere in your game, and you request a new one by the same name, it will retrieve the
reference rather than reloading the asset.

Public Member Functions

• virtual ∼TAsset ()
• TAssetRef GetRef ()

Protected Member Functions

• virtual void Release ()


• virtual void Restore ()

Friends

• class TAssetManager

15.7.2 Constructor & Destructor Documentation

virtual TAsset::∼TAsset ()
Destructor.

Navigating the Playground SDK


15.7 TAsset Class Reference 195

15.7.3 Member Function Documentation


TAssetRef TAsset::GetRef ()
Get a reference to this asset. Do not call in a constructor!
Reimplemented in TAnimatedTexture (p. 189), TModel (p. 306), TSound (p. 411), and TTexture
(p. 471).

virtual void TAsset::Release () [protected]


Release an asset.
Reimplemented in TModel (p. 307).

virtual void TAsset::Restore () [protected]


Restore an asset.
Reimplemented in TAnimatedTexture (p. 190), and TModel (p. 306).

Playground 4.0.17.1
196 Class and File Reference

15.8 TAssetMap Class Reference


#include <pf/assetmap.h>

15.8.1 Detailed Description


A collection of assets that simplifies asset reference-holding.
If your game has sections or levels that use a particular set of assets, you can allocate them and
store them into a TAssetMap (this page). Then when the level is complete you can release the
TAssetMap (this page). This will prevent any glitches from dynamically loading art while the
game is running.
Simple usage looks like:

// In your class: C++


TAssetMap mMyMap ;

// In your initialization code:


mMyMap.AddAsset("image1");
mMyMap.AddAsset("image2");

// Later in your game code:


TTextureRef myImage = mMyMap.GetTexture("image1");

After you’ve referenced an image, calling TTexture::Get() (p. 465) on that image will retrieve the
reference; however, calling TAssetMap::GetTexture (p. 198) will help you in one of two ways,
depending on the state of TAssetMap::SetAutoLoad() (opposite):

• If SetAutoLoad is false (default), it will ASSERT in debug build that the texture isn’t found if
you forgot to add it to the map.
• If SetAutoLoad is true, it will load it and hold the reference until the map is destroyed. That
way the next time you reference it, it will be able to retrieve the already loaded version, even
if you’ve released the in-game reference.
See also:
Game Assets (p. 13)
TAsset (p. 194)

Public Member Functions


• TAssetMap ()
• virtual ∼TAssetMap ()
• void SetAutoLoad (bool autoLoad)
• void AddAsset (str assetHandle, TAssetRef asset=TAssetRef(), bool silent=false)
• void AddAssets (const char ∗assets[ ])
• TSoundRef GetSound (str asset)
• TModelRef GetModel (str asset)

Navigating the Playground SDK


15.8 TAssetMap Class Reference 197

• TTextureRef GetTexture (str asset)


• TAnimatedTextureRef GetAnimatedTexture (str asset)
• TScriptCodeRef GetScriptCode (str asset)
• bool QueryAsset (str asset)
• void Release ()

15.8.2 Constructor & Destructor Documentation


TAssetMap::TAssetMap ()
Default Constructor.

virtual TAssetMap::∼TAssetMap ()
Destructor.

15.8.3 Member Function Documentation


void TAssetMap::SetAutoLoad (bool autoLoad)
Activate auto-loading of textures.
When this flag is false, requesting a texture that doesn’t exist will assert. When it’s true, it will
simply attempt to load it on demand.
Parameters:
autoLoad True to auto-load.

void TAssetMap::AddAsset (str assetHandle, TAssetRef asset = TAssetRef(), bool silent =


false)
Add an asset to the map.
Parameters:
assetHandle Name of asset to add.
asset Pointer to asset to associate with assetHandle. Optional.
silent True to supress warnings.

void TAssetMap::AddAssets (const char ∗ assets[ ])


Add an array of assets to the map. Array is NULL terminated.
For example:

const char * assets[]= C++


{
"checkers/flipper",
"checkers/exploder",
"checkers/heavy",

Playground 4.0.17.1
198 Class and File Reference

"checkers/helium",
"checkers/rowClear",
NULL
}

TAssetMap map;
map.AddAssets(assets);

Note you can add flags to TSound (p. 409) and TTexture (p. 463) references. See TSound::Get()
(p. 410) and TTexture::Get() (p. 465) for details.
Parameters:
assets Array of assets to add.

TSoundRef TAssetMap::GetSound (str asset)


Get a sound asset from the map.
Parameters:
asset Asset handle to retrieve. Must be exactly the same string that was specified to add the
asset.
Returns:
A TSoundRef. Will be empty (NULL) if the asset is not found, or is of an improper type.

TModelRef TAssetMap::GetModel (str asset)


Get a model asset from the map.
Parameters:
asset Asset handle to retrieve. Must be exactly the same string that was specified to add the
asset.
Returns:
A TModelRef. Will be empty (NULL) if the asset is not found, or is of an improper type.

TTextureRef TAssetMap::GetTexture (str asset)


Get a texture asset from the map.
Parameters:
asset Asset handle to retrieve. Must be exactly the same string that was specified to add the
asset.
Returns:
A TTextureRef. Will be empty (NULL) if the asset is not found, or is of an improper type.
Note that if you use GetTexture() (this page) to retrieve a TAnimatedTexture (p. 182), it will
succeed and return the TAnimatedTextureRef cast to a TTextureRef.

Navigating the Playground SDK


15.8 TAssetMap Class Reference 199

TAnimatedTextureRef TAssetMap::GetAnimatedTexture (str asset)


Get an animated texture asset from the map.
Parameters:
asset Asset handle to retrieve. Must be exactly the same string that was specified to add the
asset.
Returns:
A TAnimatedTextureRef. Will be empty (NULL) if the asset is not found, or is of an improper
type.

TScriptCodeRef TAssetMap::GetScriptCode (str asset)


Get a reference to a pre-loaded, pre-compiled Lua script.
Parameters:
asset Asset handle to retrieve. Must be exactly the same string that was specified to add the
asset.
Returns:
A TScriptCodeRef. Will be empty (NULL) if the asset is not found, or is of an improper type.

bool TAssetMap::QueryAsset (str asset)


Query the TAssetMap (p. 196) for an asset; will return true if an asset has been registered success-
fully with the map.
Parameters:
asset Asset to query.
Returns:
True if found.

void TAssetMap::Release ()
Release ALL managed assets. All previously added assets are released and their records are
purged. After calling this you can again add assets as usual.
Note that assets that are still referenced elsewhere in your code (or by, e.g., existing TSpriteRefs)
will not be destroyed.
A release will happen implicitly on destruction of the TAssetMap (p. 196).

Playground 4.0.17.1
200 Class and File Reference

15.9 TBegin2d Class Reference


#include <pf/renderer.h>

15.9.1 Detailed Description


Helper class to wrap 2d rendering.
When you construct this class it activates a TRenderer::Begin2d() (p. 380) state, and when it’s
destroyed, it calls TRenderer::End2d() (p. 381). You can also stop the state early by calling TBe-
gin2d::Done() (this page).
This allows you to create a local stack variable that will automatically disable TRen-
derer::Begin2d() (p. 380) mode when it leaves scope.

Public Member Functions


• TBegin2d ()
• ∼TBegin2d ()
• void Done ()

15.9.2 Constructor & Destructor Documentation


TBegin2d::TBegin2d ()
Default constructor.
References TRenderer::Begin2d(), and TRenderer::GetInstance().

TBegin2d::∼TBegin2d ()
Destructor.
References Done().

15.9.3 Member Function Documentation


void TBegin2d::Done ()
We’re done with 2d for now!
References TRenderer::End2d(), and TRenderer::GetInstance().
Referenced by ∼TBegin2d().

Navigating the Playground SDK


15.10 TBegin3d Class Reference 201

15.10 TBegin3d Class Reference


#include <pf/renderer.h>

15.10.1 Detailed Description


Helper class to wrap 3d rendering.
When you construct this class it activates a TRenderer::Begin3d() (p. 381) state, and when it’s
destroyed, it calls TRenderer::End3d() (p. 381). You can also stop the state early by calling TBe-
gin3d::Done() (this page).
This allows you to create a local stack variable that will automatically disable TRen-
derer::Begin3d() (p. 381) mode when it leaves scope.

Public Member Functions


• TBegin3d ()
• ∼TBegin3d ()
• void Done ()

15.10.2 Constructor & Destructor Documentation


TBegin3d::TBegin3d ()
Default constructor.
References TRenderer::Begin3d(), and TRenderer::GetInstance().

TBegin3d::∼TBegin3d ()
Destructor.
References Done().

15.10.3 Member Function Documentation


void TBegin3d::Done ()
We’re done with 3d for now!
References TRenderer::End3d(), and TRenderer::GetInstance().
Referenced by ∼TBegin3d().

Playground 4.0.17.1
202 Class and File Reference

15.11 TButton Class Reference


#include <pf/button.h>
Inheritance diagram for TButton:

TWindow

TLayeredWindow

TButton

15.11.1 Detailed Description


Encapsulation for button functionality. Handles push-buttons, radio buttons, and toggles. Also
handles mouse-over highlighting.
A TButton (this page) is implemented as a TLayeredWindow (p. 252) with 3 or 4 layers, depending
on the type of button (a kPush button only needs three layers, while the other types need four).
If you define a button in Lua, you can use the special options defined in the documentation of the
Lua call Button() (p. 142).

Derived Button virtual functions.


Functions that a derived TButton (this page) class can override to respond to button state changes
with custom behaviors and/or animations.

• virtual void StateUpdate (EMouseState newState, EMouseState previousState)

Public Types
• enum EButtonType { kPush, kToggle, kRadio, kNumTypes }
• enum EButtonLayer { kUp, kDown, kOver, kOverOn }
• enum EMouseState { kMouseIdle, kMousePush, kMouseOver, kMouseActivated }
• enum EButtonCreateFlags { kGroupStart, kSendMessageToParent, kCloseWindow, kDe-
faultButton, kCancelButton }

Public Member Functions


• TButton ()
• ∼TButton ()

Navigating the Playground SDK


15.11 TButton Class Reference 203

• void SetType (EButtonType type)


• void Toggle ()
• EButtonType GetType ()
• EMouseState GetState ()
• void SetOn (bool on)
• bool GetOn ()
• bool IsDefault ()
• bool IsCancel ()
• void AddFlags (uint32_t flags)
• void SetTooltip (str tooltip)
• void SetLabel (str label)
• str GetLabel ()
• virtual bool OnMouseLeave ()
• virtual bool OnMouseUp (const TPoint &point)
• virtual bool OnMouseDown (const TPoint &point)
• virtual bool OnMouseMove (const TPoint &point)
• virtual bool Press ()
• void SetCommand (TButton::Action ∗action)
• bool DoCommand ()
• void SetSound (EMouseState state, str sound)
• void SetClickMask (TTextureRef texture)
• virtual void Init (TWindowStyle &style)
• virtual bool OnNewParent ()
• virtual void PostChildrenInit (TWindowStyle &style)

Classes
• class Action
An abstract action class for button actions.

• class LuaAction
A class that wraps a Lua command in an action.

15.11.2 Member Enumeration Documentation


enum TButton::EButtonType
The type of a TButton (opposite). These constants are also available in the Lua GUI thread.
Enumerator:
kPush A normal "push" button.
kToggle A 2-state toggle button.

Playground 4.0.17.1
204 Class and File Reference

kRadio One of several "radio" buttons in a group. Must call BeginGroup() (p. 141) before the
first button in the Lua script, or call TButton::AddFlags(kGroupStart) on the first button
in the group.
kNumTypes Number of button types (not a real type).

enum TButton::EButtonLayer
The button layers.
Enumerator:
kUp Button is in "up" or "off" state.
kDown Button is in "down" or "on" state.
kOver Button is in roll-over state (and is off for toggles and radio buttons).
kOverOn Button is in roll-over state and is "on".

enum TButton::EMouseState
TButton (p. 202) internal dynamic state.
Enumerator:
kMouseIdle Button mouse state is idle.
kMousePush Button is being pushed by a mouse click.
kMouseOver Button is being rolled over by the mouse.
kMouseActivated A transient state indicating that the button has been activated. Reverts
immediately to kMouseIdle.

enum TButton::EButtonCreateFlags
Button creation flags.
Enumerator:
kGroupStart This button is the first in a group.
kSendMessageToParent Send the button’s message to the parent modal.
kCloseWindow Automatically send the parent TModalWindow (p. 298) a close message
when this button is pushed.
kDefaultButton This button is default button in the local context.
kCancelButton This button is a cancel button in the local context.

15.11.3 Constructor & Destructor Documentation


TButton::TButton ()
Constructor.

TButton::∼TButton ()
Destructor.

Navigating the Playground SDK


15.11 TButton Class Reference 205

15.11.4 Member Function Documentation


void TButton::SetType (EButtonType type)
Set the button’s type.
Parameters:
type New type for button.

void TButton::Toggle ()
Toggle the button’s state. Button must be of type kToggle, or this method will ASSERT.

EButtonType TButton::GetType ()
Get the button’s type.
Returns:
Type of the button.

EMouseState TButton::GetState ()
Get the current mouse state of the button.
Returns:
The state of the button with regards to the mouse.

void TButton::SetOn (bool on)


Set a toggle or radio button on.
Parameters:
on True to set to on. False to set to off (toggle only).

bool TButton::GetOn ()
Return whether a particular radio button is on.
Returns:
True for on.

bool TButton::IsDefault ()
Return true if this is a default button.
Returns:
True if default.

Playground 4.0.17.1
206 Class and File Reference

bool TButton::IsCancel ()
Return if this is a cancel button.
Returns:
True if this button should abort the window.

void TButton::AddFlags (uint32_t flags)


Add flags to the current button.
Parameters:
flags Flags to add. Does not erase flags.

void TButton::SetTooltip (str tooltip)


Set the tooltip for this button.
Warning:

Not implemented yet!


Specification subject to change.
Parameters:
tooltip A string for the tooltip.

void TButton::SetLabel (str label)


Set the label for this button
Parameters:
label Text to place in the label for this button

str TButton::GetLabel ()
Get the label for this button.
Returns:
The button’s label.

virtual bool TButton::OnMouseLeave ()


Notification that the mouse has left the window.
Reimplemented from TWindow (p. 513).

virtual bool TButton::OnMouseUp (const TPoint & point)


Mouse up handler.

Navigating the Playground SDK


15.11 TButton Class Reference 207

Parameters:
point Mouse position.

Reimplemented from TWindow (p. 512).

virtual bool TButton::OnMouseDown (const TPoint & point)


Mouse down handler.
Parameters:
point Mouse position.

Reimplemented from TWindow (p. 512).

virtual bool TButton::OnMouseMove (const TPoint & point)


Mouse motion handler.
Parameters:
point Mouse position.

Reimplemented from TWindow (p. 512).

virtual bool TButton::Press ()


Press the button from C++: Equivalent to clicking on the button.
Returns:
true if the window is still around by the end; false if it’s been closed and/or removed from the
hierarchy.

void TButton::SetCommand (TButton::Action ∗ action)


Set the current TButton::Action (p. 210) associated with the button’s action. Create a TBut-
ton::LuaAction (p. 211) to wrap a Lua command. The TButton (p. 202) expects to own the com-
mand, and will delete it on TButton (p. 202) destruction.
Parameters:
action Action (p. 210) to bind to button.

bool TButton::DoCommand ()
Do the command associated with this button
Returns:
True if the window was deleted as a result of the command.

Playground 4.0.17.1
208 Class and File Reference

void TButton::SetSound (EMouseState state, str sound)


Set a sound for a specific button state
Parameters:
state Which mouse state triggers the sound
sound name of sound file to play

void TButton::SetClickMask (TTextureRef texture)


Set a click mask for the button. A click mask is an image where anything black (all pixels have
RGB of less than 20) in the image is considered outside the button, and the mouse will not activate
the button if it is in a black area.
Parameters:
texture texture to use as the click mask

virtual void TButton::StateUpdate (EMouseState newState, EMouseState previousState)


Called when the button is activated so that a derived class may trigger an animation or change the
button’s state.
Call the base class if you want to add behavior to the default behavior; otherwise you will need to
take responsibility for changing the button’s appearance.
Parameters:
newState State we’re transitioning to.
previousState State we’re transitioning from.

virtual void TButton::Init (TWindowStyle & style)


Do Lua initialization.
Supported tags include:

• close (bool) This button closes its window/dialog if true.

• flags (number) Button label text alignment.

• graphics (table) An array of up to four images for the button: Three for push-buttons (Up,
RollOver, Down), Four for toggle and radio buttons (Up, RollOver-Up, Down, RollOver-
Down). If the array has fewer than 3 or 4 images, additional images are duplicated from the
last given image.

• label (string) Default button text label.

• scale (number) Scale to apply to the button graphics.

• sound (string) Name of sound to play when button pressed.

• rolloversound (string) Name of sound to play when mouse rolls over the button.

Navigating the Playground SDK


15.11 TButton Class Reference 209

• type (number) Button type (kPush, kToggle, kRadio).


• Other generic window tags.
Parameters:
style Style definition for button.

Reimplemented from TWindow (p. 501).

virtual bool TButton::OnNewParent ()


Handle any initialization or setup that is required when this window is assigned to a new parent.
No initialization of the window has happened prior to this call.
Returns:
True on success; false on failure.
See also:
Init (opposite)
PostChildrenInit (this page)

Reimplemented from TWindow (p. 501).

virtual void TButton::PostChildrenInit (TWindowStyle & style)


Do post-children-added initialization when being created from Lua.
Any initialization that needs to happen after a window’s children have been added can be placed
in a derived version of this function.
Warning:

Remember to always call the base class if you’re overriding this function.
Parameters:
style Current style environment that this window was created in.

Reimplemented from TWindow (p. 502).

Playground 4.0.17.1
210 Class and File Reference

15.12 TButton::Action Class Reference


#include <pf/button.h>
Inheritance diagram for TButton::Action:

TButton::Action

TButton::LuaAction

15.12.1 Detailed Description


An abstract action class for button actions.

Public Member Functions


• virtual void DoAction (TButton ∗button)=0

15.12.2 Member Function Documentation


virtual void TButton::Action::DoAction (TButton ∗ button)
Override this member to perform the action.
Parameters:
button A pointer to the button triggering the action.
Returns:

Implemented in TButton::LuaAction (opposite).

Navigating the Playground SDK


15.13 TButton::LuaAction Class Reference 211

15.13 TButton::LuaAction Class Reference


#include <pf/button.h>
Inheritance diagram for TButton::LuaAction:

TButton::Action

TButton::LuaAction

15.13.1 Detailed Description


A class that wraps a Lua command in an action.

Public Member Functions


• LuaAction (TLuaFunction ∗action)
• ∼LuaAction ()
• virtual void DoAction (TButton ∗button)

Public Attributes
• TLuaFunction ∗ mAction

15.13.2 Constructor & Destructor Documentation


TButton::LuaAction::LuaAction (TLuaFunction ∗ action)
Constructor
Parameters:
action A TLuaFunction (p. 259) to wrap.

TButton::LuaAction::∼LuaAction ()
Destructor.

15.13.3 Member Function Documentation


virtual void TButton::LuaAction::DoAction (TButton ∗ button)
Override this member to perform the action.

Playground 4.0.17.1
212 Class and File Reference

Parameters:
button A pointer to the button triggering the action.
Returns:

Implements TButton::Action (p. 210).

15.13.4 Member Data Documentation


TLuaFunction∗ TButton::LuaAction::mAction
The wrapped action.

Navigating the Playground SDK


15.14 TClock Class Reference 213

15.14 TClock Class Reference


#include <pf/clock.h>

15.14.1 Detailed Description


The TClock (this page) class encapsulates timer functionality.
When you have a need for a time source in your game, you can instantiate a TClock (this page)
object that has its own Start, Stop, Reset, and Pause controls.
TClocks can be assigned to TAnimTask (p. 191) objects to control when they animate.
For example, if you create a TClock (this page) in your game, you can use it to time the animations
your game employs. When implementing game-pause functionality, if all animations that should
pause reference the game TClock (this page) object, then you can pause your game by simply
pausing the TClock (this page).

Public Member Functions

• TClock ()
• virtual ∼TClock ()
• void Start (void)
• bool Pause (void)
• void Reset (void)
• uint32_t GetTime (void)
• void SetTime (uint32_t t)
• bool GetPaused ()

15.14.2 Constructor & Destructor Documentation


TClock::TClock ()
Constructor.

virtual TClock::∼TClock ()
Destructor.

15.14.3 Member Function Documentation


void TClock::Start (void)
Start the timer. Has no effect on a running timer.

Playground 4.0.17.1
214 Class and File Reference

bool TClock::Pause (void)


Pause the timer. Will have no effect on a paused timer.
Returns:
true if timer was paused already.

void TClock::Reset (void)


Pauses and zeros a timer.

uint32_t TClock::GetTime (void)


Get the current running millisecond count.
Returns:
Number of milliseconds clock has been allowed to run.

void TClock::SetTime (uint32_t t)


Set the current clock time.
Resets the clock and sets the current elapsed time.
Parameters:
t Value to set the current time to.

bool TClock::GetPaused ()
Return whether the clock is paused.
Returns:
True if paused.

Navigating the Playground SDK


15.15 TColor Class Reference 215

15.15 TColor Class Reference


#include <pf/pftypes.h>

15.15.1 Detailed Description


An RGBA color value. TColor (this page) stores the color values as TReals.
See also:
TColor32 (p. 218)

Public Member Functions

• TColor ()
• TColor (TReal R, TReal G, TReal B, TReal A)
• void Init (uint32_t R, uint32_t G, uint32_t B, uint32_t A)
• bool operator== (const TColor &color) const
• bool operator!= (const TColor &color) const

Public Attributes

• TReal r
• TReal g
• TReal b
• TReal a

15.15.2 Constructor & Destructor Documentation


TColor::TColor ()
Constructor. Zeros colors by default.

TColor::TColor (TReal R, TReal G, TReal B, TReal A)


Construct from floating point values.
Values are expected to range from zero to one.
Parameters:
R Red.
G Green.
B Blue.
A Alpha, where 0 is transparent and 1 is opaque.

Playground 4.0.17.1
216 Class and File Reference

15.15.3 Member Function Documentation

void TColor::Init (uint32_t R, uint32_t G, uint32_t B, uint32_t A)


Integer initializer; expects color values from 0-255.
Parameters:
R Red (0-255)
G Green (0-255)
B Blue (0-255)
A Alpha (0-255)

bool TColor::operator== (const TColor & color) const


Compare two colors.
Parameters:
color Right-hand color to compare with.
Returns:
True on equality.

References a, b, g, and r.

bool TColor::operator!= (const TColor & color) const


Compare two colors.
Parameters:
color Right-hand color to compare with.
Returns:
True on non-equality.

15.15.4 Member Data Documentation

TReal TColor::r
Red value, 0-1.
Referenced by operator==().

TReal TColor::g
Green value, 0-1.
Referenced by operator==().

Navigating the Playground SDK


15.15 TColor Class Reference 217

TReal TColor::b
Blue value, 0-1.
Referenced by operator==().

TReal TColor::a
Alpha value, 0-1.
Referenced by operator==().

Playground 4.0.17.1
218 Class and File Reference

15.16 TColor32 Struct Reference


#include <pf/pftypes.h>

15.16.1 Detailed Description


A 32-bit platform native color value. Used in some structures to save space and/or map to
platform-specific structure layouts. The internal color value should not be accessed directly if
you want your code to work cross-platform.

Public Member Functions

• TColor32 ()
• TColor32 (const TColor &c)
• TColor32 (uint8_t r, uint8_t g, uint8_t b, uint8_t a)
• TColor32 (uint32_t c)
• uint8_t Alpha () const
• uint8_t Red () const
• uint8_t Green () const
• uint8_t Blue () const
• void SetAlpha (uint8_t a)
• void SetRed (uint8_t r)
• void SetGreen (uint8_t g)
• void SetBlue (uint8_t b)

Public Attributes

• uint32_t color

15.16.2 Constructor & Destructor Documentation


TColor32::TColor32 ()
Default constructor.

TColor32::TColor32 (const TColor & c)


Build a TColor32 (this page) from a TColor (p. 215).
Parameters:
c Source color.

Navigating the Playground SDK


15.16 TColor32 Struct Reference 219

TColor32::TColor32 (uint8_t r, uint8_t g, uint8_t b, uint8_t a)


Build a TColor32 (opposite) from RGBA values.
Parameters:
r R (0-255)
g G (0-255)
b B (0-255)
a A (0-255)

TColor32::TColor32 (uint32_t c)
Build a TColor32 (opposite) from an unsigned long ARGB (A is highest byte).
Parameters:
c An "ARGB"-order packed color.

15.16.3 Member Function Documentation


uint8_t TColor32::Alpha () const
Read color alpha (0-255).

uint8_t TColor32::Red () const


Read color red (0-255).

uint8_t TColor32::Green () const


Read color green (0-255).

uint8_t TColor32::Blue () const


Read color blue (0-255).

void TColor32::SetAlpha (uint8_t a)


Write color alpha (0-255).

void TColor32::SetRed (uint8_t r)


Write color red (0-255).

void TColor32::SetGreen (uint8_t g)


Write color green (0-255).

Playground 4.0.17.1
220 Class and File Reference

void TColor32::SetBlue (uint8_t b)


Write color blue (0-255).

15.16.4 Member Data Documentation


uint32_t TColor32::color
Raw, platform-specific color value.
Warning:

Do not modify directly! The meaning of this value may change from video card to video card,
or from OS X to Windows, or from Intel to PowerPC Macs.

Navigating the Playground SDK


15.17 TDialog Class Reference 221

15.17 TDialog Class Reference


#include <pf/dialog.h>
Inheritance diagram for TDialog:

TWindow

TModalWindow

TDialog

15.17.1 Detailed Description


A generic modal dialog

Public Types
• enum { kResponseOK }

Public Member Functions


• TDialog (str initFileName, str bodyText, str titleText)
• virtual ∼TDialog ()
• virtual bool OnMessage (TMessage ∗message)
• virtual bool OnNewParent ()

Protected Types
• enum { kHttpLink }

15.17.2 Constructor & Destructor Documentation


TDialog::TDialog (str initFileName, str bodyText, str titleText)
Default Constructor
Parameters:
initFileName Dialog spec file.
bodyText Text for the body of the dialog
titleText Text for the title of the dialog.

Playground 4.0.17.1
222 Class and File Reference

virtual TDialog::∼TDialog ()
Destructor.

15.17.3 Member Function Documentation


virtual bool TDialog::OnMessage (TMessage ∗ message)
Handle a message.
Parameters:
message Payload of message.
Returns:
True if message handled; false otherwise.

Reimplemented from TModalWindow (p. 302).

virtual bool TDialog::OnNewParent ()


Do the real initialization on being added to the hierarchy.
Returns:
true on success.

Reimplemented from TModalWindow (p. 302).

Navigating the Playground SDK


15.18 TDrawSpec Class Reference 223

15.18 TDrawSpec Class Reference


#include <pf/drawspec.h>

15.18.1 Detailed Description


2d drawing parameters for use in DrawSprite.

Public Member Functions


• TDrawSpec (const TVec2 &at=TVec2(), TReal alpha=1, TReal scale=1, uint32_t flags=0)
• TDrawSpec GetRelative (const TDrawSpec &parent) const

Public Attributes
• TMat3 mMatrix
• TVec2 mCenter
• TColor mTint
• TReal mAlpha
• TRect mSourceRect
• uint32_t mFlags
• TRenderer::EBlendMode mBlendMode

Static Public Attributes


• static const int32_t kFlipHorizontal
• static const int32_t kFlipVertical
• static const int32_t kUseSourceRect
• static const int32_t kUseCenter

15.18.2 Constructor & Destructor Documentation


TDrawSpec::TDrawSpec (const TVec2 & at = TVec2(), TReal alpha = 1, TReal scale = 1,
uint32_t flags = 0)
Default constructor with optional arguments for convenience.
Parameters:
at Position to draw the object.
alpha Alpha level of the object, 0-1.
scale The scale of the object, where 1.0 is its actual size.
flags Options flags. See mFlags.

References mMatrix, and TMat3::Scale().

Playground 4.0.17.1
224 Class and File Reference

15.18.3 Member Function Documentation

TDrawSpec TDrawSpec::GetRelative (const TDrawSpec & parent) const


Create a new TDrawSpec (previous page) that is a combination of this TDrawSpec (previous
page) and a parent reference frame.
The new TDrawSpec (previous page) will have a combined matrix, combined alpha, and inherited
relative flip flags (kFlipVertical + kFlipVertical = no flip, same for kFlipHorizontal). Blend modes
are inherited only if this TDrawSpec (previous page) is set to kBlendINVALID.
Other parameters stay the same as this class and are NOT inherited.
Parameters:
parent Parent to combine
Returns:
New combined TDrawSpec (previous page)

References TRenderer::kBlendINVALID, kFlipHorizontal, kFlipVertical, mAlpha, mBlendMode,


mFlags, and mMatrix.

15.18.4 Member Data Documentation

const int32_t TDrawSpec::kFlipHorizontal


Flip texture horizontally.
Referenced by GetRelative().

const int32_t TDrawSpec::kFlipVertical


Flip texture vertically.
Referenced by GetRelative().

const int32_t TDrawSpec::kUseSourceRect


Use the source rectangle field.

const int32_t TDrawSpec::kUseCenter


Use the center field.
Warning:

If you set kUseCenter on the TDrawSpec (previous page) of a TAnimatedSprite (p. 175), you
will disable the automatic positioning of the TAnimatedSprite (p. 175), and the animation
will no longer work as expected.

Navigating the Playground SDK


15.18 TDrawSpec Class Reference 225

TMat3 TDrawSpec::mMatrix
3x3 matrix including the offset and relative orientation (and scaling) of the sprite.
Use mMatrix[2] to set the position where the center of sprite is to be drawn.
Use mMatrix.Scale() to set the scale of the sprite.
Referenced by GetRelative(), and TDrawSpec().

TVec2 TDrawSpec::mCenter
Logical center of the texture in pixels; can be outside of the texture. Drawing of the texture will be
done relative to this point: If this point is (0,0), it will draw relative to the upper left corner of the
image, for instance.
This is not the parameter to use to set the position of an object; for that, see TDrawSpec::mMatrix
(this page). If you misuse the mCenter field to position a sprite, you will likely run into problems
with inherited positions and TAnimatedTexture (p. 182) drawing. The mCenter field isn’t inher-
ited (as it’s intended to specify the reference point of this sprite), and TAnimatedTexture (p. 182)
uses mCenter internally to properly position the animation after sidewalk has cropped all of the
frames.
This parameter is not inherited when used with TSprite::Draw() (p. 422), so if you want to modify
the center of a sprite you need to modify the sprite’s TSprite::GetDrawSpec() (p. 425) and not the
environment passed in to TSprite::Draw() (p. 422).
mFlags must have kUseCenter set to cause this field to be valid. Otherwise the actual center of the
texture is used.
See also:
kUseCenter (opposite)

TColor TDrawSpec::mTint
Vertex coloring for the texture. The alpha channel of this color is ignored. Default value on con-
struction is pure white.
Applies only to this object–for sprites, does NOT get inherited by child sprites.

TReal TDrawSpec::mAlpha
Alpha to use to draw sprite. Zero is completely transparent and one is completely opaque (subject
to blend mode and texture alpha values).
This value is multiplicatively inherited in child sprites using GetRelative() (opposite).
Referenced by GetRelative().

TRect TDrawSpec::mSourceRect
Source rectangle to extract image from.

Playground 4.0.17.1
226 Class and File Reference

This parameter is NOT inherited when used with TSprite::Draw() (p. 422), so if you want to mod-
ify the source rectangle of a sprite you need to modify the sprite’s TSprite::GetDrawSpec() (p. 425)
and not the environment passed in to TSprite::Draw() (p. 422).
mFlags must have kUseSourceRect set to activate.

uint32_t TDrawSpec::mFlags
Options for drawing. Inherits flip flags with an XOR, so if a parent and child are, e.g., both hori-
zontally flipped, the child will be drawn normally.
Options include kFlipHorizontal (p. 224), kFlipVertical (p. 224), kUseSourceRect (p. 224), and
kUseCenter (p. 224).
Referenced by GetRelative().

TRenderer::EBlendMode TDrawSpec::mBlendMode
Blend mode to use, if any; set to TRenderer::kBlendINVALID (p. 373) to use current mode (de-
fault). Inherited when parent mode set and child is kBlendINVALID.
Referenced by GetRelative().

Navigating the Playground SDK


15.19 TEncrypt Class Reference 227

15.19 TEncrypt Class Reference


#include <pf/encrypt.h>

15.19.1 Detailed Description


A class that encapsulates an encryption engine.

Public Member Functions

• TEncrypt (str encryptionKey)


• ∼TEncrypt ()
• str EncryptStr (str input)
• str DecryptStr (str input)
• uint32_t EncryptBinary (const void ∗input, uint32_t inLength, void ∗output, uint32_t out-
Length, bool base64)
• uint32_t DecryptBinary (const void ∗input, uint32_t inLength, void ∗output, uint32_t out-
Length, bool base64)
• uint32_t GetLastSize ()

15.19.2 Constructor & Destructor Documentation


TEncrypt::TEncrypt (str encryptionKey)
Constructor
Parameters:
encryptionKey Key to use for encrypting/decrypting. The key should consist of valid Base64
characters(0-9,a-z,A-Z,+,/) and be correctly formatted (i.e. user proper ’=’ suffix).

TEncrypt::∼TEncrypt ()
Destructor

15.19.3 Member Function Documentation


str TEncrypt::EncryptStr (str input)
Parameters:
input Str to encrypt.
Returns:
returns the input encrypted as a Str.

Playground 4.0.17.1
228 Class and File Reference

str TEncrypt::DecryptStr (str input)


Parameters:
input Str to decrypt. This str (p. 161) must have been created with EncryptStr to ensure proper
decryption.
Returns:
returns the decrypted str (p. 161).

uint32_t TEncrypt::EncryptBinary (const void ∗ input, uint32_t inLength, void ∗ output,


uint32_t outLength, bool base64)
Parameters:
input Data to encrypt
inLength Length of input in bytes
output Buffer to place encrypted data into.
outLength Size of output buffer.
base64 true to fill the buffer with base64 characters, so it can be passed around as a string.
false will fill the buffer with binary data.
Returns:
returns 0 if successful. Otherwise, if output is NULL or outLength is too small for the resulting
data, then returns the size in bytes that the output buffer must be to hold the encrypted data.

uint32_t TEncrypt::DecryptBinary (const void ∗ input, uint32_t inLength, void ∗ output,


uint32_t outLength, bool base64)
Parameters:
input Data to decrypt. This data must have been encrypted with EncryptBinary to ensure
proper decryption.
inLength Length of input in bytes
output Buffer to place decrypted data into.
outLength Size of output buffer.
base64 true if the incoming buffer is in base64, false if the incoming buffer is in binary
Returns:
returns 0 if successful. Otherwise, if output is NULL or outLength is too small for the resulting
data, then returns the size in bytes that the output buffer must be to hold the decrypted data.

uint32_t TEncrypt::GetLastSize ()
Get the last decrypted or encrypted data size.
Returns:
Size of last encrypted or decrypted data.

Navigating the Playground SDK


15.20 TEvent Class Reference 229

15.20 TEvent Class Reference


#include <pf/event.h>

15.20.1 Detailed Description


System event encapsulation.

Key Codes
Use these constants to refer to the given keys in your code when processing an OnKeyDown()
message.
See also:
TWindow::OnKeyDown (p. 514)

• static int32_t kUp


• static int32_t kDown
• static int32_t kLeft
• static int32_t kRight
• static int32_t kEnter
• static int32_t kEscape
• static int32_t kTab
• static int32_t kPaste
• static int32_t kPageUp
• static int32_t kPageDown
• static int32_t kBackspace
• static int32_t kDelete

Public Types
• enum EEventCode { kIdle, kNull, kClose, kQuit, kMouseDown, kExtendedMouseEvent,
kMouseUp, kMouseMove, kMouseLeave, kMouseHover, kKeyDown, kKeyUp, kChar,
kUTF32Char, kRedraw, kTimer, kDisplayModeChange, kActivate, kFullScreenToggle }
• enum EKeyFlags { kShift, kControl, kAlt, kExtended }

Public Attributes
• int32_t mType
• int32_t mKey
• TPoint mPoint
• EKeyFlags mKeyFlags

Playground 4.0.17.1
230 Class and File Reference

15.20.2 Member Enumeration Documentation

enum TEvent::EEventCode

Event codes.
Enumerator:
kIdle Idle event processing time.
kNull EMPTY event.
kClose A close request (Alt-F4, clicking close button).
kQuit A QUIT NOW event.
kMouseDown Mouse down.
kExtendedMouseEvent Right Mouse Button/Wheel down.
kMouseUp Mouse up.
kMouseMove Mouse move.
kMouseLeave Mouse has left the window. You must TWindowMan-
ager::AddMouseListener() (p. 524) the mouse to receive this message; note that
TButton-derived classes automatically capture the mouse on mouse-over.
kMouseHover Mouse has hovered over a point on the window.
kKeyDown Key down.
kKeyUp Key up.
kChar translated character event
kUTF32Char translated utf32 event
kRedraw Redraw the screen now.
kTimer A timer has triggered.
kDisplayModeChange The display mode has changed.
kActivate Our application has activated/deactivated. mKey is set to 0 on deactivate, or 1 on
activate.
kFullScreenToggle The user has toggled full screen mode. mKey is set to 0 on windowed
mode, or non-zero on full screen mode.

enum TEvent::EKeyFlags

Event key flags.


Enumerator:
kShift Shift is pressed.
kControl Control (or command) is pressed.
kAlt Alt key is pressed.
kExtended Reserved.

15.20.3 Member Data Documentation

int32_t TEvent::kUp

Up arrow key.

Navigating the Playground SDK


15.20 TEvent Class Reference 231

int32_t TEvent::kDown
Down arrow key.

int32_t TEvent::kLeft
Left arrow key.

int32_t TEvent::kRight
Right arrow key.

int32_t TEvent::kEnter
Enter key. On keyboards with more than one key of this description, the same constant is returned
for both.

int32_t TEvent::kEscape
The "Esc" key.

int32_t TEvent::kTab
The Tab key.

int32_t TEvent::kPaste
The "Paste" keyboard combination. Typically Control-V on Windows, Command-V on OS X.

int32_t TEvent::kPageUp
The Page-Up key.

int32_t TEvent::kPageDown
The Page-Down key.

int32_t TEvent::kBackspace
The backspace key.

int32_t TEvent::kDelete
The Delete key.

Playground 4.0.17.1
232 Class and File Reference

int32_t TEvent::mType
Type of event
See also:
EEventCode (p. 230)

int32_t TEvent::mKey
Key for keyboard events.

TPoint TEvent::mPoint
Point for mouse events.

EKeyFlags TEvent::mKeyFlags
Flags for key events.

Navigating the Playground SDK


15.21 TFile Struct Reference 233

15.21 TFile Struct Reference


#include <pf/file.h>

15.21.1 Detailed Description


A file reading abstraction. All file access from Playground games should be handled through this
abstraction.
File names must consist ONLY of the following characters:

• a-z : Lowercase letters


• 0-9 : Digits
• - : Hyphen
• _ : Underscore
• . : Dot

Paths must be separated by forward slash ("/"). All files must be specified without a leading slash.
A file in "assets/bitmaps/" called "my.png" would be loaded with the handle "bitmaps/my.png".
To access a writable folder, prefix the file name with either user:, common:, or desktop: to get to
either the user’s personal data folder, the system’s common data folder, or the desktop folder. You
may NOT write to the assets folder during the game –it will ASSERT in debug build if you try.
There is a set of C stdio-compatible routines that you can use to port existing fopen-style interfaces:

• pf_open()
• pf_close()
• pf_seek()
• pf_tell()
• pf_getc()
• pf_gets()
• pf_read()
• pf_write() (only to user:, common: and desktop: folders)
• pf_eof()
• pf_error()
• pf_ungetc()

If you absolutely must use fscanf(), you can use pf_fgets to get a line of text, and then use sscanf()
to parse the line. However, in general it is be much better to read and write the data as XML using
TXmlNode (p. 532).

Playground 4.0.17.1
234 Class and File Reference

Public Member Functions

• TFile ()
• ∼TFile ()
• bool Open (str path, eFileMode mode=kReadBinary)
• bool IsValid () const
• bool AtEOF ()
• void Close ()
• void Seek (long offset, eFileSeek seek)
• long Tell ()
• long Size ()
• long Read (void ∗buffer, unsigned long bytes)
• long Write (const void ∗buffer, unsigned long bytes)
• void Unget ()

Static Public Member Functions

• static bool Exists (str handle)


• static str Source (str handle)
• static str GetCWD ()
• static bool GetNextFile (str folder, str ∗file, bool subfolders=false)
• static void ScanForResources ()
• static void ShutDownFileSystem ()
• static void ScanFolderForResources (str folder, str prefix="")
• static void AddMemoryFile (str memoryFileName, void ∗base, uint32_t size)
• static void AddFileMask (const char ∗mask, bool add=true)
• static bool DeleteFile (str filename)

Friends

• class TPlatformData

15.21.2 Constructor & Destructor Documentation


TFile::TFile ()
Default constructor.

TFile::∼TFile ()
Destructor.

Navigating the Playground SDK


15.21 TFile Struct Reference 235

15.21.3 Member Function Documentation

bool TFile::Open (str path, eFileMode mode = kReadBinary)


Open an existing file. Closes any file this TFile (p. 233) previously had open, and attempts to open
the given file.
Parameters:
path Path to file
mode Mode to open file
Returns:
true on success.

bool TFile::IsValid () const


Return true if the file was opened successfully.
Returns:
True on success; false on failure.

bool TFile::AtEOF ()
Return true if the file is at the EOF.
Returns:
True on EOF.

void TFile::Close ()
Close a file. Optional; file is automatically closed on destruction of the TFile (p. 233)

void TFile::Seek (long offset, eFileSeek seek)


Seek to a specific file position.
Parameters:
offset Offset from reference position.
seek Which reference position to use.

long TFile::Tell ()
Get the current file position.
Returns:
Current offset into the file.

Playground 4.0.17.1
236 Class and File Reference

long TFile::Size ()
Get the file’s size.
Returns:
File size in bytes.

long TFile::Read (void ∗ buffer, unsigned long bytes)


Read bytes into buffer.
Parameters:
buffer Buffer to fill.
bytes Bytes to read.
Returns:
bytes read

long TFile::Write (const void ∗ buffer, unsigned long bytes)


Write bytes to file from buffer.
Parameters:
buffer Buffer to read bytes from.
bytes Bytes to write.
Returns:
bytes written

void TFile::Unget ()
"Unget" one character. Semantics are similar to ungetc, in that you can only ever "unget" one
character.
Unlike ungetc, it will only unget exactly the previous character you just read–there is no option to
select a character to unget.
Ungetting past the beginning of the file is not allowed.

static bool TFile::Exists (str handle)


Test to see if a file exists. Expects a standard resource handle.
Parameters:
handle Resource handle.
Returns:
True if file exists

Navigating the Playground SDK


15.21 TFile Struct Reference 237

static str TFile::Source (str handle)


Return the source of the file.
Parameters:
handle Handle of the file to query.
Returns:
"filesystem" if it’s a normal file, "memoryfile" if it’s a memory file, an empty string if file isn’t
found, or the name of the source .pfp file.

static str TFile::GetCWD ()


Get the current working directory.
Returns:
Current working directory.

static bool TFile::GetNextFile (str folder, str ∗ file, bool subfolders = false)
Iterate through the files in a folder.
Parameters:
folder Folder to search. File globs are NOT supported currently.
file Pointer to a string to receive each file name.

Start iteration with an empty string, and pass the value you received previously to get the next
value in the iteration.
Parameters:
subfolders True to return files in subfolders as well.
Returns:
True if successful; false to signal end of iteration.

static void TFile::ScanForResources ()


Internal function: Scan for updated file resources.
Called by Playground on application startup. If the file system changes this needs to be called
again to update the internal cache.

static void TFile::ShutDownFileSystem ()


Clear out the file system cache.

static void TFile::ScanFolderForResources (str folder, str prefix = "")


Scan a folder (and subfolder) for files.

Playground 4.0.17.1
238 Class and File Reference

Parameters:
folder Folder to scan.
prefix File system prefix to expect.

static void TFile::AddMemoryFile (str memoryFileName, void ∗ base, uint32_t size)


Add a virtual file to the file system. After you call this function, opening a file with the given name
for read will supply the given data. The data is not copied, so you are responsible for ensuring
that the data buffer continues to exist for as long as the memory file is available. In other words,
the client owns the memory block, and must ensure its lifetime exceeds that of the memory file
entry.
Opening the file for write is not currently supported.
Parameters:
memoryFileName Name of the virtual file to add.
base Pointer to the start of the virtual file data. Pass NULL to delete the virtual file.
size Size of the virtual file.

static void TFile::AddFileMask (const char ∗ mask, bool add = true)


Add a set of files-to-be-ignored to TFile (p. 233). These files will not be "visible" to the TFile (p. 233)
file system.
Paths should be given the same as a path would be given to TFile::Open() (p. 235).
Entries in this string are space (or line) separated.
Each entry matches either one complete file path, or one complete folder path. Folders are NOT
matched in user: or common:–only complete file paths are matched.
Passing in an entry of -∗ will clear the entire file mask. If you put this at the start of your string, it
will clear the file mask before adding the rest of the files in your string.
Parameters:
mask A space-delimited string of complete file or folder paths.
add True to add the files to the mask (ignore the files in the list); false to remove the files from
the mask (to make them show up again).

static bool TFile::DeleteFile (str filename)


Delete a file from user: or common:, or dereference a memory file. For a memory file, just removes
the entry in the file table: No memory is deallocated, as the client owns the memory.
Note that if you try to delete a file that you currently have open, the behavior is undefined.
Parameters:
filename Filename to delete. Must be prefixed by user: or common:.
Returns:
True on success.

Navigating the Playground SDK


15.22 TFlashHost Class Reference 239

15.22 TFlashHost Class Reference


#include <pf/flashhost.h>

15.22.1 Detailed Description


An embedded Flash-playback routine.
Can be used in-game for cut-scenes. Flash animation will play until it’s "done", at which point
control will return to the game.
From within Lua, you can call DisplaySplash() (p. 144) to display a Flash animation and an op-
tional replacement bitmap.
To ensure that the Flash file plays correctly on the Mac, you should:

1. Have an 800x600 stage in your Flash content (assuming your display resolution is 800x600).
2. Have an empty first frame, and then place an 800x10 rectangle shape cast member at (0,-30).
(Again, assuming that 800 is the display width.)

This will guarantee that the Flash stage size is calculated correctly by Playground. The Mac version
of Playground uses WebKit to load an HTML file that loads an SWF file that loads the Flash content
(it’s complicated, but necessary). Flash does not have a method to determine the stage size of the
loaded clip, however. You can get the dimensions of the movie clip, but these are computed as the
bounding box of the objects onstage, and this is what we are using when we decide how much we
need to scale the loaded content to fit 800x600.
This is why the rectangle shape is necessary: So that Playground can retrieve the 800 width and
determine that it doesn’t need to scale the resulting Flash file.

Public Member Functions


• TFlashHost (const char ∗filename)
• ∼TFlashHost ()
• bool Start (bool bLoop=false, bool bTranslate=false, bool bAllowInput=false)
• void Stop ()
• long GetTotalFrames ()
• long GetFrameNum ()
• bool IsPlaying ()

15.22.2 Constructor & Destructor Documentation


TFlashHost::TFlashHost (const char ∗ filename)
Constructor.
Parameters:
filename Flash file to play.

Playground 4.0.17.1
240 Class and File Reference

TFlashHost::∼TFlashHost ()
Destructor.

15.22.3 Member Function Documentation


bool TFlashHost::Start (bool bLoop = false, bool bTranslate = false, bool bAllowInput =
false)
Start Flash file.
Flash movies need to be in Flash 4 format to provide the most compatibility across all systems.
Translatable movies need to be Flash 6.
It is possible to translate a Flash movie by setting the bTranslate parameter to true. When translate
mode is turned on, any string in the string table that begins with "FLASH_" will be sent to the
Flash movie for translation. If all of the text in the Flash movie is set up as dynamic text, and
each text box references a variable that is named after an entry in your strings.xml file (minus the
"FLASH_"), then translation will succeed. You will also want to embed the font you want inside
of your movie, so that if the user doesn’t have the font installed on their system the font will still
show up correctly.
For example, if you have a dynamic text variable in your movie named "text_box_1", and have an
entry in your strings.xml table named "FLASH_text_box_1", then at run time, "text_box_1" in your
flash movie will be set to whatever the value of "FLASH_text_box_1" is in your strings.xml file.
It is recommended that inside the Flash movie itself, incomplete text is used when doing layouts.
That way it will be obvious if it has been forgotten to add any text to the translation pipeline. If
the text inside the movie is correct, it is not clear whether or not the movie is using the original
text or the translated text until someone actually goes in to translate the strings.xml file.
Parameters:
bLoop Loop file.
bTranslate Send translated strings to the movie.
bAllowInput If this is true, the system cursor will be shown and mouse clicks will be sent to
the flash movie. If it is false, the cursor will be hidden and clicks will be sent to the game
only.
Returns:
True on success.

void TFlashHost::Stop ()
Stop playing file.

long TFlashHost::GetTotalFrames ()
Get the total number of frames.
Returns:
Number of frames.

Navigating the Playground SDK


15.22 TFlashHost Class Reference 241

long TFlashHost::GetFrameNum ()
Get the current frame number.
Returns:
Frame number.

bool TFlashHost::IsPlaying ()
Test to see whether the animation is playing.
Returns:
True if playing.

Playground 4.0.17.1
242 Class and File Reference

15.23 TGameState Class Reference


#include <pf/gamestate.h>

15.23.1 Detailed Description


An object that allows the game to communicate state information to the system. This allows the
system to, for example, interact with MSN or Zylom web hooks. In Playground-published games
this system is also used to collect game metrics.
See also:
Tracking Game Metrics (p. 40)

Public Member Functions


• void SetState (str key, int32_t value=0)
• void SetState (str key, str value)
• str GetState (str key)
• bool QueryRestartMode ()
• bool QueryJumpToMenu ()
• bool QueryMuteGame ()
• bool QueryPauseGame ()

Static Public Member Functions


• static TGameState ∗ GetInstance ()
• static void RegisterHandler (TGameStateHandler ∗handler)

Static Public Attributes


• static const char ∗ kCmdLine
• static const char ∗ kLevel
• static const char ∗ kSubLevel
• static const char ∗ kPause
• static const char ∗ kMute
• static const char ∗ kBreakNow
• static const char ∗ kScore
• static const char ∗ kGameMode
• static const char ∗ kGameOver
• static const char ∗ kNoMoreContent
• static const char ∗ kDownloadButton
• static const char ∗ kUpsellFrequency

Navigating the Playground SDK


15.23 TGameState Class Reference 243

• static const char ∗ kRestartButton


• static const char ∗ kSystemMode
• static const char ∗ kMaxLevel

15.23.2 Member Function Documentation


static TGameState∗ TGameState::GetInstance ()
Get an instance to the global game state object.

void TGameState::SetState (str key, int32_t value = 0)


Set a numeric key value.
To time states in a FirstPeek build, set a state to "1" when active and "0" when inactive. States
always set in this manner will have their time written to the FirstPeek file.
Parameters:
key Key to set.
value Value to set it to.

void TGameState::SetState (str key, str value)


Set a string key value.
Parameters:
key Key to set.
value Value to set it to.

str TGameState::GetState (str key)


Get a string key value.
Parameters:
key Key to read.
Returns:
Current state of key.

bool TGameState::QueryRestartMode ()
Query this function frequently; if it ever returns true, immediately restart the current game mode
at level 1.
Returns:
true to restart game mode.

Playground 4.0.17.1
244 Class and File Reference

bool TGameState::QueryJumpToMenu ()
Query this function frequently; if it ever returns true, immediately exit the current game mode and
bring up the main menu.
Returns:
true to go to menu.

bool TGameState::QueryMuteGame ()
Query this function to determine the mute state displayed in the game.
As your user modifies the mute state within the game, you should call SetState() (previous page)
with kMute to notify the system of the change.
Returns:
true to mute game.

bool TGameState::QueryPauseGame ()
TPlatform::GetEvent() (p. 341) will handle QueryPauseGame() (this page); no user code is re-
quired to handle it correctly.
Returns:
True to pause game; false otherwise.

static void TGameState::RegisterHandler (TGameStateHandler ∗ handler)


Register a game state handler.
Parameters:
handler Handler to register.

15.23.3 Member Data Documentation

const char∗ TGameState::kCmdLine


Key to pass command line into attached game monitor. This allows plug-in to interpret its own
command line options.
This option is handled by Playground; there’s no need for a game to use it.

const char∗ TGameState::kLevel


State key for setting current game level. If your game has no concept of levels, then set this to a
constantly increasing value.

Navigating the Playground SDK


15.23 TGameState Class Reference 245

const char∗ TGameState::kSubLevel


State key for setting current game sub-level. (optional).

const char∗ TGameState::kPause


State key to let the system know your game has been paused or resumed. Value is non-zero for
pause and zero for resume.

const char∗ TGameState::kMute


State key to indicate the game is in MUTE state. Use this to enable or disable muting from within
the game. Monitor QueryMuteGame() (opposite) to determine actual game mute settings.

const char∗ TGameState::kBreakNow


Key to signify that the game is at a pause in the action and can be stopped. This should ideally be
triggered at the end of each level. Value is ignored.

const char∗ TGameState::kScore


State key for score. In games with no score, this can be safely ignored. Call this function every
game loop.

const char∗ TGameState::kGameMode


State key for game mode. Should be set when user has selected a mode and is about to start
playing. Value should be a one word description of the game mode, like "Story" or "Endless".

const char∗ TGameState::kGameOver


State key for game over. Value is ignored. Be sure to set the final score value BEFORE calling
kGameOver.

const char∗ TGameState::kNoMoreContent


State key for no more free content in a Web version. Value is ignored. Set this after the player has
beaten the last level available in a trial version of the game or has otherwise played past the end
of the available content.

const char∗ TGameState::kDownloadButton


Download button pressed: In a Web game, there will be a "download (and buy) the real game"
button. When it’s pressed, call SetState(kDownloadButton).

Playground 4.0.17.1
246 Class and File Reference

const char∗ TGameState::kUpsellFrequency


The frequency you should use to display upsell screens. The game should show an upsell screen
at the end of any level divisible by this number. Default is 0, which indicates that the game should
use its default upsell frequency.

const char∗ TGameState::kRestartButton


Query this value to determine whether a restart button should be displayed instead of an "OK"
button on an upsell screen. In the case that you’ve displayed a restart button, call SetState() (p. 243)
with this value to indicate the restart button has been pressed.

const char∗ TGameState::kSystemMode


Key used to query the current system mode(s). Return result may have several modes separated
by commas, including "web", "msn", "zylom", "metrics", etc.

const char∗ TGameState::kMaxLevel


Key used to query what level the game should cap out at; used by some web providers to vary
how many levels can be played. Default is -1, which indicates no limit.

Navigating the Playground SDK


15.24 TGameStateHandler Class Reference 247

15.24 TGameStateHandler Class Reference


#include <pf/gamestatehandler.h>

15.24.1 Detailed Description


A handler for game state actions. Typically implemented by Playground or PlayFirst.

Public Member Functions


• virtual ∼TGameStateHandler ()
• virtual bool SetState (const char ∗key, const char ∗value)=0
• virtual const char ∗ GetState (const char ∗key, const char ∗value)
• virtual bool QueryRestartMode ()
• virtual bool QueryJumpToMenu ()
• virtual bool QueryMuteGame ()
• virtual bool QueryPauseGame ()

15.24.2 Constructor & Destructor Documentation


virtual TGameStateHandler::∼TGameStateHandler ()
Virtual Destructor

15.24.3 Member Function Documentation


virtual bool TGameStateHandler::SetState (const char ∗ key, const char ∗ value)
Handle SetState() (this page). Handler can modify the key or value.
Parameters:
key State to set.
value New state value.
Returns:
True if the state has been handled, and you’d like to eat the state. If you return true, it will
not perform any other operations on this state, though it will still be cached by TGameState
(p. 242).

virtual const char∗ TGameStateHandler::GetState (const char ∗ key, const char ∗ value)
Get the value of a state.
Parameters:
key Value to retrieve.

Playground 4.0.17.1
248 Class and File Reference

value Cached value (the last value set at this key).


Returns:
Potentially modified state value.

virtual bool TGameStateHandler::QueryRestartMode ()


Handle QueryRestartMode() (this page)
Returns:
True to request a restart.

virtual bool TGameStateHandler::QueryJumpToMenu ()


Handle QueryJumpToMenu() (this page)
Returns:
True to jump to the main menu.

virtual bool TGameStateHandler::QueryMuteGame ()


Handle QueryMuteGame() (this page)
Returns:
True to mute the game.

virtual bool TGameStateHandler::QueryPauseGame ()


Allow the handler to force the pause of the game; this is handled internally by Playground.
Returns:
True to pause the game

Navigating the Playground SDK


15.25 TImage Class Reference 249

15.25 TImage Class Reference


#include <pf/image.h>
Inheritance diagram for TImage:

TWindow

TImage

15.25.1 Detailed Description

The TImage (this page) class is a TWindow (p. 496) that contains and draws a TTexture (p. 463).
It is not intended that the windowing system be used to render sprites in your game–that’s what
the sprite system is for. Among other things, there is a limited flexibility in rendering options.
A TImage (this page) will automatically set its kOpaque flag based on SetAlpha() (next page)–a
SetAlpha() (next page) of less than 1 will reset the flag. In Lua initialization you can also use
"alpha=true" to reset the flag.

Event Handlers

Functions to override to handle events in a window.

• virtual void Draw ()

Public Member Functions

• TImage (bool staticImage=true)


• virtual ∼TImage ()
• void SetTexture (TTextureRef texture, TReal scale=1.0f)
• TTextureRef GetTexture ()
• void SetAlpha (TReal alpha)
• TReal GetAlpha ()
• TReal GetScale ()
• void SetRotate (bool rotate)
• void SetDrawFlags (uint32_t flags)
• virtual void Init (TWindowStyle &style)

Playground 4.0.17.1
250 Class and File Reference

15.25.2 Constructor & Destructor Documentation


TImage::TImage (bool staticImage = true)
Default Constructor.
Parameters:
staticImage Default behavior assumes that the image will change infrequently, and therefore
sets kInfrequentChanges and tries to cache the image.

Create a TImage (previous page) with staticImage set to false for an image that will change fre-
quently.

virtual TImage::∼TImage ()
Destructor.

15.25.3 Member Function Documentation


virtual void TImage::Draw ()
Draw the window. TImage (previous page) can draw only a portion of the window when only a
part of the image needs to be redrawn.
Reimplemented from TWindow (p. 503).

void TImage::SetTexture (TTextureRef texture, TReal scale = 1.0f)


Set the image texture.
Parameters:
texture New texture.
scale Amount to scale texture by when drawing

TTextureRef TImage::GetTexture ()
Get the current image texture.
Returns:
A reference to the bound image.

void TImage::SetAlpha (TReal alpha)


Set the alpha for this image
Parameters:
alpha Alpha value. 1.0==opaque.

Navigating the Playground SDK


15.25 TImage Class Reference 251

TReal TImage::GetAlpha ()
Get the current alpha of this image.
Returns:
A value from 0 (transparent) to 1 (opaque).

TReal TImage::GetScale ()
Get the current scale of this TImage (p. 249)
Returns:
Scale from 0 - 1

void TImage::SetRotate (bool rotate)


Set this image to be rotated right (clockwise) by 90 degrees.
Parameters:
rotate True to rotate.

void TImage::SetDrawFlags (uint32_t flags)


Set the draw flags for this image (including flip horizontal and flip vertical).
Parameters:
flags Draw flags to use: A combination of TDrawSpec::kFlipVertical (p. 224) and/or
TDrawSpec::kFlipHorizontal (p. 224).

virtual void TImage::Init (TWindowStyle & style)


Initialize the Window. Called by the system only in Lua initialization.
When you create your own custom window, this is where you put your own custom initialization
that needs to happen before children are created. Fundamental window initialization is handled
in every class by this function, so when you override this function you almost always want to
call your base class to handle base class initialization.
Parameters:
style The Lua style that was in effect when this window was created. This style contains
all parameters specified explicitly for the window as well as parameters defined in the
current style. Parameters set locally override ones in the style.

Reimplemented from TWindow (p. 501).

Playground 4.0.17.1
252 Class and File Reference

15.26 TLayeredWindow Class Reference


#include <pf/layeredwindow.h>
Inheritance diagram for TLayeredWindow:

TWindow

TLayeredWindow

TButton

15.26.1 Detailed Description


A TLayeredWindow (this page) is a TWindow (p. 496) with multiple layers which can be switched
between. This can be used for animation, or for button presses, for instance.

Public Types

• enum { kAll }

Public Member Functions

• TLayeredWindow (uint32_t numberOfLayers)


• virtual ∼TLayeredWindow ()
• void SetCurrentLayer (int32_t layer=kAll)
• int32_t GetCurrentLayer ()
• uint32_t GetNumLayers ()
• virtual void OrphanChild (TWindow ∗child)
• virtual bool AdoptChild (TWindow ∗child, bool initWindow=true)

15.26.2 Constructor & Destructor Documentation


TLayeredWindow::TLayeredWindow (uint32_t numberOfLayers)
Default Constructor
Parameters:
numberOfLayers Number of layers to create.

Navigating the Playground SDK


15.26 TLayeredWindow Class Reference 253

virtual TLayeredWindow::∼TLayeredWindow ()
Destructor.

15.26.3 Member Function Documentation


void TLayeredWindow::SetCurrentLayer (int32_t layer = kAll)
Select the layer of this window to display or add children to. Children added when one layer is
selected will be added only to that layer, and therefore only displayed when that layer is selected.
Parameters:
layer The new active layer. Set to kAll to add children to all layers; layer 0 will be displayed
in that state.

int32_t TLayeredWindow::GetCurrentLayer ()
Get the current active layer.
Returns:
An zero-based index to the current active layer.

uint32_t TLayeredWindow::GetNumLayers ()
Get the number of layers.
Returns:
The number of layers associated with this window.

virtual void TLayeredWindow::OrphanChild (TWindow ∗ child)


Remove a child from this window, releasing ownership.
Removes this child from all window layers.
Parameters:
child child to remove.
See also:
TWindow::OrphanChild (p. 504)

Reimplemented from TWindow (p. 504).

virtual bool TLayeredWindow::AdoptChild (TWindow ∗ child, bool initWindow = true)


Add a child to this window. Adds it to the current window layer only.
Parameters:
child Child to add.

Playground 4.0.17.1
254 Class and File Reference

initWindow Whether to run the init function OnNewParent() (p. 501) on this window.
Returns:
True if successful. False if OnNewParent() (p. 501) returned false, in which case child was
NOT added.
See also:
TWindow::AdoptChild (p. 503)

Reimplemented from TWindow (p. 503).

Navigating the Playground SDK


15.27 TLight Struct Reference 255

15.27 TLight Struct Reference


#include <pf/light.h>

15.27.1 Detailed Description

A 3d light.

Public Types

• enum ELightType { kDirectional, kPointSource, kSpotLight }

Public Member Functions

• TLight ()

Public Attributes

• ELightType mType
• TColor mDiff
• TColor mSpec
• TColor mAmb
• TVec3 mPos
• TVec3 mDir
• TReal mRange
• TReal mAttenuation [3]
• TReal mTheta
• TReal mPhi

15.27.2 Member Enumeration Documentation

enum TLight::ELightType
Light types.
Enumerator:
kDirectional A directional light source.
kPointSource A point source light.
kSpotLight A spotlight.

Playground 4.0.17.1
256 Class and File Reference

15.27.3 Constructor & Destructor Documentation


TLight::TLight ()
Default constructor, which resets the light parameters to a white directional light.
References mAttenuation.

15.27.4 Member Data Documentation


ELightType TLight::mType
Type of light.

TColor TLight::mDiff
Diffuse value.

TColor TLight::mSpec
Specular value.

TColor TLight::mAmb
Ambient value.

TVec3 TLight::mPos
Position of light. No meaning for directional light sources.

TVec3 TLight::mDir
Direction of light. No meaning for point source light sources.

TReal TLight::mRange
Effective range of light. No meaning for directional light sources.

TReal TLight::mAttenuation[3]
Attenuation factors: Constant, Linear, and Quadratic. Attenuation is calculated based on the fol-
lowing equation:

1
A=
a 0 + a 1 D + a 2 D2

Where a0 − a2 are mAttenuation[0]-mAttenuation[2], and D is the distance of the light source to


the vertex, normalized to 0,1 over the range of the light.

Navigating the Playground SDK


15.27 TLight Struct Reference 257

Referenced by TLight().

TReal TLight::mTheta
Angle of inner cone of spotlight, in radians.

TReal TLight::mPhi
Angle of outer edge of spotlight dropoff, in radians.

Playground 4.0.17.1
258 Class and File Reference

15.28 TLitVert Struct Reference


#include <pf/vertexset.h>

15.28.1 Detailed Description


3d untransformed, lit vertex.

Public Attributes
• TVec3 pos
• uint32_t RESERVED
• TColor32 color
• TColor32 specular
• TVec2 uv

15.28.2 Member Data Documentation


TVec3 TLitVert::pos
Position in 3d space.

uint32_t TLitVert::RESERVED
UNUSED (must be zero).

TColor32 TLitVert::color
Vertex color.

TColor32 TLitVert::specular
Vertex specular component.

TVec2 TLitVert::uv
Vertex texture coordinate.

Navigating the Playground SDK


15.29 TLuaFunction Class Reference 259

15.29 TLuaFunction Class Reference


#include <pf/pflua.h>
Inheritance diagram for TLuaFunction:

TLuaObjectWrapper

TLuaFunction

15.29.1 Detailed Description


A wrapper for a Lua function

Public Member Functions


• TLuaFunction (lua_State ∗state)
• void Call ()
• bool IsFunction ()

15.29.2 Constructor & Destructor Documentation


TLuaFunction::TLuaFunction (lua_State ∗ state)
Constructor.
Parameters:
state State to extract Lua function from. Pulls the top item off the stack and binds it to this
TLuaFunction (this page).

15.29.3 Member Function Documentation


void TLuaFunction::Call ()
Call the function.
References TLuaObjectWrapper::Push().

bool TLuaFunction::IsFunction ()
Test to verify that we’re actually bound to a function.
Returns:
True if our bound object is a Lua function.

Playground 4.0.17.1
260 Class and File Reference

References TLuaObjectWrapper::Push().

Navigating the Playground SDK


15.30 TLuaObjectWrapper Class Reference 261

15.30 TLuaObjectWrapper Class Reference


#include <pf/pflua.h>
Inheritance diagram for TLuaObjectWrapper:

TLuaObjectWrapper

TLuaFunction TLuaTable

15.30.1 Detailed Description


Wrap a Lua object for use within C++ code. Keeps a reference to the Lua object so it won’t be
garbage collected.

Public Member Functions

• TLuaObjectWrapper (lua_State ∗state)


• TLuaObjectWrapper (TLuaObjectWrapper &other)
• virtual ∼TLuaObjectWrapper ()
• void Push ()
• bool IsString ()
• bool IsNumber ()
• bool IsTable ()
• str AsString ()
• lua_Number AsNumber ()
• lua_State ∗ GetState ()

Protected Attributes

• lua_State ∗ mState

15.30.2 Constructor & Destructor Documentation


TLuaObjectWrapper::TLuaObjectWrapper (lua_State ∗ state)
Initialize our function with the object found on top of the stack. Pops object from stack.
Parameters:
state Lua state.

Playground 4.0.17.1
262 Class and File Reference

TLuaObjectWrapper::TLuaObjectWrapper (TLuaObjectWrapper & other)


Copy constructor.
Parameters:
other State to copy.

References Push().

virtual TLuaObjectWrapper::∼TLuaObjectWrapper ()
Destructor.

15.30.3 Member Function Documentation


void TLuaObjectWrapper::Push ()
Push our object onto the stack. Note a Lua object can only be pushed onto the stack of the Lua
interpreter that it was extracted from and originally created in.
Referenced by TLuaFunction::Call(), TLuaTable::GetSize(), TLuaFunction::IsFunction(), and TLu-
aObjectWrapper().

bool TLuaObjectWrapper::IsString ()
Is this object a string?
Returns:
True if it is a string.

bool TLuaObjectWrapper::IsNumber ()
Is the object a number?
Returns:
True if the object is a number.

bool TLuaObjectWrapper::IsTable ()
Is the object a table?
Returns:
True if a table

Referenced by TLuaTable::TLuaTable().

str TLuaObjectWrapper::AsString ()
Convert the object to a string.

Navigating the Playground SDK


15.30 TLuaObjectWrapper Class Reference 263

Returns:
A string representation of the object, if one is available.

lua_Number TLuaObjectWrapper::AsNumber ()
Convert the object to a number.
Returns:
A numeric representation of the object, if one is available.

lua_State∗ TLuaObjectWrapper::GetState ()
Get the current state associated with this object.
Returns:
A Lua state.

Playground 4.0.17.1
264 Class and File Reference

15.31 TLuaParticleSystem Class Reference


#include <pf/luaparticlesystem.h>

15.31.1 Detailed Description


A particle system driven by Lua scripts.
Particle system documentation is at A Lua-Driven Particle System (p. 57)

Public Member Functions


• TLuaParticleSystem (TParticleRenderer ∗r=NULL)
• virtual ∼TLuaParticleSystem ()
• void Draw (const TVec3 &at)
• virtual bool Init (str spec)
• void NewScript ()
• virtual void Update (int ms)
• void RegisterFunction (str name, PFClassId processId)
• void AdoptFunctionInstance (str name, TParticleFunction ∗function)
• int32_t RegisterDataSource (str name, TParticleFunction ∗function)
• TParticleFunction ∗ GetDataSource (int32_t source)
• ParticleMember Allocate (uint8_t size)
• TParticleFunctionRef GetParticleFunction (str type)
• TScript ∗ GetScript ()
• TScriptCodeRef GetScriptCode ()
• bool IsDone ()
• void SetDone ()
• void ResetDone ()
• uint32_t GetParticleCount ()
• void SetAlpha (float a)
• TParticleRenderer ∗ GetParticleRenderer ()

Static Public Member Functions


• static TRandom ∗ GetRandom ()
• static void SetErrorHandler (TFailure ∗failureHandler)
• static TFailure ∗ GetErrorHandler ()

Classes
• struct PInstruction

Navigating the Playground SDK


15.31 TLuaParticleSystem Class Reference 265

15.31.2 Constructor & Destructor Documentation


TLuaParticleSystem::TLuaParticleSystem (TParticleRenderer ∗ r = NULL)
Default Constructor
Parameters:
r Particle renderer to use. If NULL, will create a T2dParticleRenderer (p. 172).

virtual TLuaParticleSystem::∼TLuaParticleSystem ()
Destructor.

15.31.3 Member Function Documentation


void TLuaParticleSystem::Draw (const TVec3 & at)
Draw the system.
Parameters:
at Where to draw it. For 2d particles, the third component just sets the Z-depth to draw the
particles.

virtual bool TLuaParticleSystem::Init (str spec)


An initializer with a client-defined specification. Note that this doesn’t call NewScript() (this page)
for you–it’s acting more like a "Load()" call, and will likely have its name changed in 4.1 to better
reflect its behavior.
Parameters:
spec Client spec.

void TLuaParticleSystem::NewScript ()
Reset the script to a virgin state.

virtual void TLuaParticleSystem::Update (int ms)


Update particle system.
Parameters:
ms Number of milliseconds to advance system.

void TLuaParticleSystem::RegisterFunction (str name, PFClassId processId)


Register a function type with the particle system. This interface allows you to create a new operator
that can be used in the particle system.

Playground 4.0.17.1
266 Class and File Reference

Parameters:
name Name of process to use (or to replace).
processId The PFClassId of the class that provides the function. See Type Information and
Casting (p. 25) for more information.
See also:
AdoptFunctionInstance (this page)

void TLuaParticleSystem::AdoptFunctionInstance (str name, TParticleFunction ∗ function)


Register a function type with the particle system. This interface allows you to create a new operator
that can be used in the particle system.
Adopt semantics are used: You need to create a TParticleFunction-derived class instance and pass
it in. Lifetime management is then handled by the TLuaParticleSystem (p. 264).
For example:

AdoptFunctionInstance("fNewFunction", new MyParticleFunction ); C++

Parameters:
name Name of process to use (or to replace).
function A new instance of the class that provides the function. The TLuaParticleSystem
(p. 264) will delete this function on destruction.
See also:
RegisterFunction (previous page)

int32_t TLuaParticleSystem::RegisterDataSource (str name, TParticleFunction ∗ function)


Register a data source.
Parameters:
name Name of data source in Lua, e.g., "dSpriteVelocity"
function Class that contains the data accessor
Returns:
Data source index.

TParticleFunction∗ TLuaParticleSystem::GetDataSource (int32_t source)


Get a registered data source by index.
Parameters:
source Data source index to read (must be negative).
Returns:
The data source.

Navigating the Playground SDK


15.31 TLuaParticleSystem Class Reference 267

ParticleMember TLuaParticleSystem::Allocate (uint8_t size)


Allocate a particle variable.
This function is typically called from Lua to allocate custom particle variables, and by the renderer
to allocate the default particle members.
Parameters:
size Size of particle variable (1-4) in TReal values.
Returns:
A ParticleMember (p. 319) struct that refers to the newly allocated member.

TParticleFunctionRef TLuaParticleSystem::GetParticleFunction (str type)


Get a new instance of a particle function associated with a named type.
Parameters:
type A registered particle function type.
Returns:
A reference-counted pointer to a newly created particle function.

TScript∗ TLuaParticleSystem::GetScript ()
Get a pointer to the attached particle system script.
Returns:
A pointer to the current script.

TScriptCodeRef TLuaParticleSystem::GetScriptCode ()
Get a reference to the asset-type TScriptCodeRef. This allows Lua scripts to be pre-loaded once
and maintained in the asset system.
Returns:
A reference to the TScriptCode (p. 398) object that contains the (compiled) Lua code.

bool TLuaParticleSystem::IsDone ()
Is the particle system done?
Returns:
True if done; false otherwise.

void TLuaParticleSystem::SetDone ()
Flag the particle system as done.

Playground 4.0.17.1
268 Class and File Reference

void TLuaParticleSystem::ResetDone ()
Not done any more!

uint32_t TLuaParticleSystem::GetParticleCount ()
Get number of current active particles.
Returns:
The current number of particles active.

void TLuaParticleSystem::SetAlpha (float a)


Set the alpha of this particle system.
Parameters:
a Alpha (transparency) of this system. 0 is transparent, 1 opaque.

static TRandom∗ TLuaParticleSystem::GetRandom ()


Get the particle system random number generator.
Returns:
A pointer to the particle system random generator.

TParticleRenderer∗ TLuaParticleSystem::GetParticleRenderer ()
Get the embedded particle renderer.
Returns:
A pointer to the TParticleRenderer (p. 320) associated with this particle system.

static void TLuaParticleSystem::SetErrorHandler (TFailure ∗ failureHandler)


Bind an error handler to all TLuaParticleSystems.
Parameters:
failureHandler Handler to add.

static TFailure∗ TLuaParticleSystem::GetErrorHandler ()


Get the current error handler.
Returns:
A pointer to the current error handler, if any.

Navigating the Playground SDK


15.32 TLuaTable Class Reference 269

15.32 TLuaTable Class Reference


#include <pf/luatable.h>
Inheritance diagram for TLuaTable:

TLuaObjectWrapper

TLuaTable

15.32.1 Detailed Description


A wrapper for Lua table access in C++.

Public Member Functions


• TLuaTable (lua_State ∗state)
• TLuaTable (TLuaObjectWrapper &lobj)
• uint32_t GetSize ()
• str GetString (const char ∗key, str defaultValue="")
• str GetString (lua_Number key, str defaultValue="")
• lua_Number GetNumber (const char ∗key, lua_Number defaultValue=0)
• lua_Number GetNumber (lua_Number key, lua_Number defaultValue=0)
• void Assign (str key, str value)
• void Assign (lua_Number key, str value)
• void Assign (str key, lua_Number value)
• void Assign (lua_Number key, lua_Number value)
• void Assign (lua_Number key, TLuaObjectWrapper ∗luaObject)
• void Assign (str key, TLuaObjectWrapper ∗luaObject)
• void Erase (str key)
• void Erase (lua_Number key)
• bool GetBoolean (const char ∗key, bool defaultValue=false)
• TLuaFunction ∗ GetFunction (const char ∗key)
• TLuaTable ∗ GetTable (const char ∗key)
• TLuaTable ∗ GetTable (lua_Number key)
• TColor GetColor (str key, const TColor &defaultValue=TColor(0, 0, 0, 0))
• TColor GetColor (lua_Number key, const TColor &defaultValue=TColor(0, 0, 0, 0))
• TLuaObjectWrapper ∗ GetNext (TLuaObjectWrapper ∗∗key)
• bool PushValue (const char ∗key)
• bool PushValue (lua_Number key)

Playground 4.0.17.1
270 Class and File Reference

Static Public Member Functions


• static TLuaTable ∗ Create (lua_State ∗state)
• static void DeferDelete (TLuaTable ∗table)

15.32.2 Constructor & Destructor Documentation


TLuaTable::TLuaTable (lua_State ∗ state)
Constructor
Parameters:
state The lua_State pointer of the table. Use GetState() (p. 263) on a TScript (p. 389) to get
the current state.

TLuaTable::TLuaTable (TLuaObjectWrapper & lobj)


Construct from a TLuaObjectWrapper (p. 261)
Parameters:
lobj Object wrapper that presumably wraps a table.

References ASSERT, and TLuaObjectWrapper::IsTable().

15.32.3 Member Function Documentation


static TLuaTable∗ TLuaTable::Create (lua_State ∗ state)
Create a new table, and wrap it in a TLuaTable (previous page).
Parameters:
state State of Lua interpreter to use.
Returns:
A new (empty) TLuaTable (previous page). You’re responsible for deleting it.

uint32_t TLuaTable::GetSize ()
How many elements in the indexed portion of the table?
Returns:
Number of elements in the array portion of the table.

References TLuaObjectWrapper::Push().

str TLuaTable::GetString (const char ∗ key, str defaultValue = "")


Get a string from the table.

Navigating the Playground SDK


15.32 TLuaTable Class Reference 271

Parameters:
key The key to the string.
defaultValue Default value if key isn’t found.
Returns:
A copy of the string, if one exists at that key. Otherwise an empty string.

str TLuaTable::GetString (lua_Number key, str defaultValue = "")


Get a string from the table.
Parameters:
key The key to the string.
defaultValue Default value if key isn’t found.
Returns:
A copy of the string, if one exists at that key. Otherwise an empty string.

lua_Number TLuaTable::GetNumber (const char ∗ key, lua_Number defaultValue = 0)


Get a lua_Number from a key in the table.
Parameters:
key Key to look up.
defaultValue Default value if key isn’t found.
Returns:
A lua_Number, if one is found. Zero otherwise.

lua_Number TLuaTable::GetNumber (lua_Number key, lua_Number defaultValue = 0)


Get a lua_Number from a key in the table.
Parameters:
key Key to look up.
defaultValue Default value if key isn’t found.
Returns:
A lua_Number, if one is found. Zero otherwise.

void TLuaTable::Assign (str key, str value)


Assign a string to a string key.
Parameters:
key Key to set.
value Value to set.

Playground 4.0.17.1
272 Class and File Reference

void TLuaTable::Assign (lua_Number key, str value)


Assign a string to a numeric key.
Parameters:
key Key to set.
value Value to set.

void TLuaTable::Assign (str key, lua_Number value)


Assign a number to a string key.
Parameters:
key Key to set.
value Value to set.

void TLuaTable::Assign (lua_Number key, lua_Number value)


Assign a number to a numeric key.
Parameters:
key Key to set.
value Value to set.

void TLuaTable::Assign (lua_Number key, TLuaObjectWrapper ∗ luaObject)


Assign a TLuaObjectWrapper-wrapped Lua object to a numeric key.
Parameters:
key Key to assign object to in table.
luaObject Object to assign.

void TLuaTable::Assign (str key, TLuaObjectWrapper ∗ luaObject)


Assign a TLuaObjectWrapper-wrapped Lua object to a string key.
Parameters:
key Key to assign object to in table.
luaObject Object to assign.

void TLuaTable::Erase (str key)


Erase the key/value pair located at key in the table.
Parameters:
key Key to erase.

Navigating the Playground SDK


15.32 TLuaTable Class Reference 273

void TLuaTable::Erase (lua_Number key)


Erase the key/value pair located at key in the table.
Parameters:
key Key to erase.

bool TLuaTable::GetBoolean (const char ∗ key, bool defaultValue = false)


Get a boolean value from a key in the table.
Parameters:
key Key to look up.
defaultValue Default value if key isn’t found.
Returns:
The value of the key as a boolean (using lua_toboolean()) if the key is found. False otherwise.

TLuaFunction∗ TLuaTable::GetFunction (const char ∗ key)


Get a TLuaFunction (p. 259) from a key in the table.
Parameters:
key Key to look up.
Returns:
A TLuaFunction (p. 259), if that slot in the table has a lua function. NULL otherwise. You
should eventually delete this pointer.

TLuaTable∗ TLuaTable::GetTable (const char ∗ key)


Acquire an embedded Lua table from within this table.
Parameters:
key Key where table is stored.
Returns:
A new TLuaTable (p. 269) pointer which you must eventually delete.

TLuaTable∗ TLuaTable::GetTable (lua_Number key)


Acquire an embedded Lua table from within this table.
Parameters:
key Key where table is stored.
Returns:
A new TLuaTable (p. 269) pointer which you must eventually delete.

Playground 4.0.17.1
274 Class and File Reference

TColor TLuaTable::GetColor (str key, const TColor & defaultValue = TColor(0, 0, 0, 0))
Get a TColor (p. 215) from a table of four values.
In Lua, if you define a color using the Color() (p. 143) function, you define it using values from
0-255. If you define using FColor() (p. 146), the values are from 0-1.
Parameters:
key Key of table.
defaultValue Default value to return if no table found.
Returns:
A TColor (p. 215).

TColor TLuaTable::GetColor (lua_Number key, const TColor & defaultValue =


TColor(0, 0, 0, 0))
Get a TColor (p. 215) from a table of four values.
In Lua, if you define a color using the Color() (p. 143) function, you define it using values from
0-255. If you define using FColor() (p. 146), the values are from 0-1.
Parameters:
key Key of table.
defaultValue Default value to return if no table found.
Returns:
A TColor (p. 215).

TLuaObjectWrapper∗ TLuaTable::GetNext (TLuaObjectWrapper ∗∗ key)


Takes a key and returns the key/value pair for the next key in the table. The key you pass in
should start out NULL to start the iteration.
Warning:

If you stop an iteration in the middle, you’re responsible for deleting the last key you’ve
received in addition to the normal deletion of the last value.
Example Usage

TLuaObjectWrapper *key=NULL; C++


TLuaObjectWrapper *value;
while ( (value=options->GetNext(&key))!=NULL)
{
// Here we have a key/value pair.
str keyString = key->GetString(); str valueString =
value->GetString(); // this gets it as a string; you can also GetNumber()
// if you need a table, you can TLuaTable table(value);

delete value; // Delete the value once you’ve extracted it.

Navigating the Playground SDK


15.32 TLuaTable Class Reference 275

Parameters:
key Pointer to variable to receive next key. Initialize it to NULL to start the iteration, and
leave the previous key in place to iterate.
Returns:
A pointer to a TLuaObjectWrapper (p. 261). You must delete this pointer when you’re done
with it. Returns NULL after the last table item.

bool TLuaTable::PushValue (const char ∗ key)


Push the value at a particular string key onto the Lua stack.
Parameters:
key Key of value to retrieve.

bool TLuaTable::PushValue (lua_Number key)


Push the value at a particular numeric key onto the Lua stack.
Parameters:
key Key of value to retrieve.

static void TLuaTable::DeferDelete (TLuaTable ∗ table)


Internal function to defer the delete of a table until the next event loop.
Parameters:
table Table to delete later.

Playground 4.0.17.1
276 Class and File Reference

15.33 TMat3 Class Reference


#include <pf/mat.h>

15.33.1 Detailed Description


2d Matrix with 2x2 rotation component and TVec2 (p. 475) offset component.

Construction and Initialization.

• TMat3 ()
• TMat3 (TReal m00, TReal m01, TReal m02, TReal m10, TReal m11, TReal m12, TReal m20,
TReal m21, TReal m22)
• TMat3 (TVec3 v0, TVec3 v1, TVec3 v2)
• TMat3 (const TMat3 &rhs)
• TMat3 & operator= (const TMat3 &rhs)
• TMat3 & Identity ()

Accessors

• TVec3 & operator[ ] (TIndex i)


• const TVec3 & operator[ ] (TIndex i) const
• TIndex Dim () const

Assignment Operators

• TMat3 & operator+= (const TMat3 &rhs)


• TMat3 & operator-= (const TMat3 &rhs)
• TMat3 & operator∗= (const TMat3 &rhs)
• TMat3 & operator∗= (TReal rhs)
• TMat3 & operator/= (TReal rhs)

Scaling and rotation

• TMat3 & Scale (TReal x, TReal y)


• TMat3 & Scale (TReal s)
• TMat3 & Rotate (TReal radians)
• static TMat3 GetRotation (TReal radians)

Navigating the Playground SDK


15.33 TMat3 Class Reference 277

Related Functions
(Note that these are not member functions.)

• bool operator== (const TMat3 &lhs, const TMat3 &rhs)


• bool operator!= (const TMat3 &lhs, const TMat3 &rhs)
• TVec3 operator∗ (const TMat3 &lhs, const TVec3 &rhs)
• TVec2 operator∗ (const TMat3 &lhs, const TVec2 &rhs)
• TVec3 operator∗ (const TVec3 &lhs, const TMat3 &rhs)
• TVec2 operator∗ (const TVec2 &lhs, const TMat3 &rhs)
• TMat3 operator∗ (const TMat3 &lhs, TReal rhs)
• TVec2 Multiply2x2 (const TMat3 &lhs, const TVec2 &rhs)
• TVec2 Multiply2x2 (const TVec2 &lhs, const TMat3 &rhs)
• TMat3 Multiply2x2 (const TMat3 &lhs, const TMat3 &rhs)
• TVec2 operator% (const TVec2 &lhs, const TMat3 &rhs)
• TVec2 operator% (const TMat3 &lhs, const TVec2 &rhs)
• TMat3 operator% (const TMat3 &lhs, const TMat3 &rhs)
• TVec3 operator∗ (const TVec3 &lhs, const TMat4 &rhs)

15.33.2 Constructor & Destructor Documentation


TMat3::TMat3 ()
Default constructor. Initializes to identity.

TMat3::TMat3 (TReal m00, TReal m01, TReal m02, TReal m10, TReal m11, TReal m12, TReal
m20, TReal m21, TReal m22)
Construct from individual values.

TMat3::TMat3 (TVec3 v0, TVec3 v1, TVec3 v2)


Construct from three vectors.

TMat3::TMat3 (const TMat3 & rhs)


Copy construction.

15.33.3 Member Function Documentation


TMat3& TMat3::operator= (const TMat3 & rhs)
Assignment.

Playground 4.0.17.1
278 Class and File Reference

TMat3& TMat3::Identity ()
Initialize to an identity.

TVec3& TMat3::operator[ ] (TIndex i)


Array Accessor
Parameters:
i The row number, from 0-2.
Returns:
a reference to the TVec3 (p. 481) that represents the row.

const TVec3& TMat3::operator[ ] (TIndex i) const


Array Accessor
Parameters:
i The row number, from 0-2.
Returns:
a reference to the TVec3 (p. 481) that represents the row.

TIndex TMat3::Dim () const


Dimensions of this array.

TMat3& TMat3::operator+= (const TMat3 & rhs)


Assignment operator.
Parameters:
rhs The right-hand-side of the assignment.
Returns:
a reference to this.

TMat3& TMat3::operator-= (const TMat3 & rhs)


Assignment operator.
Parameters:
rhs The right-hand-side of the assignment.
Returns:
a reference to this.

Navigating the Playground SDK


15.33 TMat3 Class Reference 279

TMat3& TMat3::operator∗= (const TMat3 & rhs)


Assignment operator.
Parameters:
rhs The right-hand-side of the assignment.
Returns:
a reference to this.

TMat3& TMat3::operator∗= (TReal rhs)


Assignment operator.
Parameters:
rhs The right-hand-side of the assignment.
Returns:
a reference to this.

TMat3& TMat3::operator/= (TReal rhs)


Assignment operator.
Parameters:
rhs The right-hand-side of the assignment.
Returns:
a reference to this.

TMat3& TMat3::Scale (TReal x, TReal y)


Scale this matrix in two dimensions. Assumes that this matrix is used as a 2d matrix.
Parameters:
x Scale in X dimension.
y Scale in Y dimension.
Returns:
this matrix.

Referenced by TDrawSpec::TDrawSpec().

TMat3& TMat3::Scale (TReal s)


Scale this matrix. Assumes this matrix is used as a 2d matrix.

Playground 4.0.17.1
280 Class and File Reference

Parameters:
s Amount to scale X and Y axes.
Returns:
this matrix.

static TMat3 TMat3::GetRotation (TReal radians)


Get a rotation matrix.
Parameters:
radians Rotation in radians.
Returns:
A new matrix that represents the given rotation frame.

TMat3& TMat3::Rotate (TReal radians)


Rotate this matrix in place.
Parameters:
radians Radians to rotate the matrix by. Only changes the orientation portion of the matrix;
position is unchanged.
Returns:
A reference to this matrix.

15.33.4 Friends And Related Function Documentation


bool operator== (const TMat3 & lhs, const TMat3 & rhs) [related]
Equality.
Returns:
True on equal.

bool operator!= (const TMat3 & lhs, const TMat3 & rhs) [related]
Inequality.
Returns:
True on not equal.

TVec3 operator∗ (const TMat3 & lhs, const TVec3 & rhs) [related]
Matrix multiplication with a vector.

Navigating the Playground SDK


15.33 TMat3 Class Reference 281

Returns:
M∗v

TVec2 operator∗ (const TMat3 & lhs, const TVec2 & rhs) [related]
Matrix multiplication with a vector.
Returns:
M∗v

TVec3 operator∗ (const TVec3 & lhs, const TMat3 & rhs) [related]
Matrix multiplication with a vector.
Returns:
vT ∗ M

TVec2 operator∗ (const TVec2 & lhs, const TMat3 & rhs) [related]
Matrix multiplication with a vector.
Returns:
vT ∗ M

TMat3 operator∗ (const TMat3 & lhs, TReal rhs) [related]


Member-wise scaling of the vector. Note this won’t necessarily do what you want if you’re trying
to produce a scale vector. See TMat3::Scale() (p. 279).
Returns:

a00 ∗ s a10 ∗ s a20 ∗ s


a01 ∗ s a11 ∗ s a21 ∗ s
a02 ∗ s a12 ∗ s a22 ∗ s

TVec2 Multiply2x2 (const TMat3 & lhs, const TVec2 & rhs) [related]
A restricted 2x2 matrix vector multiply. Does the rotation/scaling but no translation of the vector.
Parameters:
lhs Matrix left-hand-side of the multiply
rhs Vector right-hand-side.
Returns:
Matrix[2x2]∗Vector

Referenced by operator%().

Playground 4.0.17.1
282 Class and File Reference

TVec2 Multiply2x2 (const TVec2 & lhs, const TMat3 & rhs) [related]

A restricted 2x2 matrix vector multiply. Does the rotation/scaling but no translation of the vector.
Parameters:
lhs Vector left-hand-side of the multiply
rhs Matrix right-hand-side.
Returns:
Vector∗Matrix[2x2]

TMat3 Multiply2x2 (const TMat3 & lhs, const TMat3 & rhs) [related]

A restricted 2x2 matrix-matrix multiply.


Parameters:
lhs Matrix left-hand-side.
rhs Matrix right-hand-side.
Returns:
Matrix[2x2]∗Matrix[2x2], with lhs[2] as the translation component.

TVec2 operator% (const TVec2 & lhs, const TMat3 & rhs) [related]

Restricted-multiply operator.
See also:
Multiply2x2() (previous page)
Returns:
Multiply2x2(lhs,rhs)

References Multiply2x2().

TVec2 operator% (const TMat3 & lhs, const TVec2 & rhs) [related]

Restricted-multiply operator.
See also:
Multiply2x2() (previous page)
Returns:
Multiply2x2(lhs,rhs)

References Multiply2x2().

Navigating the Playground SDK


15.33 TMat3 Class Reference 283

TMat3 operator% (const TMat3 & lhs, const TMat3 & rhs) [related]
Restricted-multiply operator.
See also:
Multiply2x2() (p. 281)
Returns:
Multiply2x2(lhs,rhs)

References Multiply2x2().

TVec3 operator∗ (const TVec3 & lhs, const TMat4 & rhs) [related]
Matrix multiplication with a vector.
Returns:
vT ∗ M

Playground 4.0.17.1
284 Class and File Reference

15.34 TMat4 Class Reference


#include <pf/mat.h>

15.34.1 Detailed Description


3d Matrix with 3x3 rotation component and TVec3 (p. 481) offset component.

Construction and Initialization.


• TMat4 ()
• TMat4 (TReal m00, TReal m01, TReal m02, TReal m03, TReal m10, TReal m11, TReal m12,
TReal m13, TReal m20, TReal m21, TReal m22, TReal m23, TReal m30, TReal m31, TReal
m32, TReal m33)
• TMat4 (TVec4 v0, TVec4 v1, TVec4 v2, TVec4 v3)
• TMat4 (const TMat4 &rhs)
• TMat4 & operator= (const TMat4 &rhs)
• ∼TMat4 ()

Accessors
• TVec4 & operator[ ] (TIndex i)
• const TVec4 & operator[ ] (TIndex i) const

Assignment operators.
• TMat4 & operator+= (const TMat4 &rhs)
• TMat4 & operator-= (const TMat4 &rhs)
• TMat4 & operator∗= (const TMat4 &rhs)
• TMat4 & operator∗= (TReal rhs)
• TMat4 & operator/= (TReal rhs)

Initializers.
• TMat4 & Identity ()
• TMat4 & LookAt (const TVec3 &pos, const TVec3 &at, const TVec3 &up)
• TMat4 & Perspective (TReal nearPlane, TReal farPlane, TReal fov, TReal aspect)
• TMat4 & OffsetPerspective (TReal nearPlane, TReal farPlane, TReal fov, TReal aspect,
const TVec2 &offsets)
• TMat4 & Orthogonal (TReal left, TReal right, TReal bottom, TReal top, TReal zNear, TReal
zFar)

Navigating the Playground SDK


15.34 TMat4 Class Reference 285

Manipulators

• TMat4 & RotateAxis (const TVec3 &axis, TReal a)


• TMat4 & RotateX (TReal a)
• TMat4 & RotateY (TReal a)
• TMat4 & RotateYPR (TReal yaw, TReal pitch, TReal roll)
• TMat4 & RotateZ (TReal a)
• TMat4 & Scale (TReal x, TReal y, TReal z)
• TMat4 & Translate (const TVec3 &v)

Utility Mmbers

• TMat4 Transpose () const


• TMat4 Adjoint () const
• TMat4 Inverse () const
• TReal Determinant () const

Public Types

• enum { kDIM }

Related Functions
(Note that these are not member functions.)

• TMat3 operator∗ (const TMat3 &lhs, const TMat3 &rhs)


• bool operator== (const TMat4 &lhs, const TMat4 &rhs)
• bool operator!= (const TMat4 &lhs, const TMat4 &rhs)
• TMat4 operator∗ (const TMat4 &lhs, const TMat4 &rhs)
• TVec4 operator∗ (const TMat4 &lhs, const TVec4 &rhs)
• TVec3 operator∗ (const TMat4 &lhs, const TVec3 &rhs)
• TVec4 operator∗ (const TVec4 &lhs, const TMat4 &rhs)
• TMat4 operator∗ (const TMat4 &lhs, TReal s)
• TMat4 operator/ (const TMat4 &lhs, TReal s)

15.34.2 Constructor & Destructor Documentation


TMat4::TMat4 ()
Default constructor. Initializes to identity.

Playground 4.0.17.1
286 Class and File Reference

TMat4::TMat4 (TReal m00, TReal m01, TReal m02, TReal m03, TReal m10, TReal m11, TReal
m12, TReal m13, TReal m20, TReal m21, TReal m22, TReal m23, TReal m30, TReal m31,
TReal m32, TReal m33)
Construct from individual values.

TMat4::TMat4 (TVec4 v0, TVec4 v1, TVec4 v2, TVec4 v3)


Construct from vectors.

TMat4::TMat4 (const TMat4 & rhs)


Copy construction
Parameters:
rhs Copy source.

TMat4::∼TMat4 ()
Destruction.

15.34.3 Member Function Documentation


TMat4& TMat4::operator= (const TMat4 & rhs)
Assignment operator.
Parameters:
rhs Right hand side of the equation.

TVec4& TMat4::operator[ ] (TIndex i)


Array Accessor
Parameters:
i The row number, from 0-2.
Returns:
a reference to the TVec4 (p. 487) that represents the row.

const TVec4& TMat4::operator[ ] (TIndex i) const


Array Accessor
Parameters:
i The row number, from 0-2.

Navigating the Playground SDK


15.34 TMat4 Class Reference 287

Returns:
a reference to the TVec4 (p. 487) that represents the row.

TMat4& TMat4::operator+= (const TMat4 & rhs)


Assignment.

TMat4& TMat4::operator-= (const TMat4 & rhs)


Assignment.

TMat4& TMat4::operator∗= (const TMat4 & rhs)


Assignment.

TMat4& TMat4::operator∗= (TReal rhs)


Assignment.

TMat4& TMat4::operator/= (TReal rhs)


Assignment.

TMat4& TMat4::Identity ()
Make this matrix the identity.
Returns:
A reference to this.

TMat4& TMat4::LookAt (const TVec3 & pos, const TVec3 & at, const TVec3 & up)
Change this matrix to be a view matrix that’s oriented to "look at" a point.
Parameters:
pos Viewer position.
at Point we’re looking at.
up Local "up" vector.
Returns:
A reference to this.

TMat4& TMat4::Perspective (TReal nearPlane, TReal farPlane, TReal fov, TReal aspect)
Make this matrix a perspective matrix.

Playground 4.0.17.1
288 Class and File Reference

Parameters:
nearPlane Distance from viewer to the near plane.
farPlane Distance from viewer to the far plane. The smaller your ratio of far to near, the
higher Z-buffer resolution you get.
fov The field of view in radians.
aspect The aspect ratio of the resulting view.
Returns:
A reference to this.

TMat4& TMat4::OffsetPerspective (TReal nearPlane, TReal farPlane, TReal fov, TReal


aspect, const TVec2 & offsets)
Make this matrix an offset perspective matrix.
In order to display a partially clipped 3d window (say you wanted to allow a window to scroll off
the screen), you need to have a perspective matrix that has been skewed to display part of a larger
projection.
Parameters:
nearPlane Distance from viewer to the near plane.
farPlane Distance from viewer to the far plane. The smaller your ratio of far to near, the
higher Z-buffer resolution you get.
fov The field of view in radians.
aspect The aspect ratio of the resulting view.
offsets The amounts to skew the x and y portions of the matrix. If you want to clip 20% of the
left edge, you’d set offsets.x to 0.2. Similarly if you want to clip 20% of the bottom edge,
you’d set y to -0.2.
Returns:
A reference to this.

TMat4& TMat4::Orthogonal (TReal left, TReal right, TReal bottom, TReal top, TReal zNear,
TReal zFar)
Make this matrix an orthogonal projection matrix that transforms objects within the given box into
view coordinates.
Parameters:
left Left side of box.
right Right side of box.
bottom Bottom of box.
top Top of box.
zNear Near side of box.
zFar Far side of box.
Returns:
A reference to this.

Navigating the Playground SDK


15.34 TMat4 Class Reference 289

TMat4& TMat4::RotateAxis (const TVec3 & axis, TReal a)


Rotate this matrix around an axis.
Parameters:
axis A unit vector that defines an axis to rotate around.
a Number of radians to rotate matrix.
Returns:
A reference to this.

TMat4& TMat4::RotateX (TReal a)


Rotate this matrix around the X axis.
Parameters:
a Number of radians to rotate matrix.
Returns:
A reference to this.

TMat4& TMat4::RotateY (TReal a)


Rotate this matrix around the Y axis.
Parameters:
a Number of radians to rotate matrix.
Returns:
A reference to this.

TMat4& TMat4::RotateYPR (TReal yaw, TReal pitch, TReal roll)


Rotate this matrix around all three axes, given as Yaw, Pitch, and Roll.
Parameters:
yaw Number of radians to rotate matrix around Y axis.
pitch Number of radians to rotate matrix around X axis.
roll Number of radians to rotate matrix around Z axis.
Returns:
A reference to this.

TMat4& TMat4::RotateZ (TReal a)


Rotate this matrix around the Z axis.
Parameters:
a Number of radians to rotate matrix.

Playground 4.0.17.1
290 Class and File Reference

Returns:
A reference to this.

TMat4& TMat4::Scale (TReal x, TReal y, TReal z)


Scale this matrix
Parameters:
x Scale to apply to X axis.
y Scale to apply to Y axis.
z Scale to apply to Z axis.
Returns:
A reference to this.

TMat4& TMat4::Translate (const TVec3 & v)


Translate this matrix by a vector.
Parameters:
v Amount to translate.
Returns:
A reference to this.

TMat4 TMat4::Transpose () const


Return a transposed matrix.
Returns:
A new transposed matrix.

TMat4 TMat4::Adjoint () const


Matrix adjoint function.

TMat4 TMat4::Inverse () const


Return an inverse of the matrix.
Returns:
An inverse copy of the matrix.

TReal TMat4::Determinant () const


Calculate the determinant of the matrix.

Navigating the Playground SDK


15.34 TMat4 Class Reference 291

Returns:
The determinant.

15.34.4 Friends And Related Function Documentation


TMat3 operator∗ (const TMat3 & lhs, const TMat3 & rhs) [related]
Matrix multiplication.
Returns:
M1 ∗ M2

bool operator== (const TMat4 & lhs, const TMat4 & rhs) [related]
Equality.
Returns:
True on equal.

bool operator!= (const TMat4 & lhs, const TMat4 & rhs) [related]
Inequality.
Returns:
True on not equal.

TMat4 operator∗ (const TMat4 & lhs, const TMat4 & rhs) [related]
Matrix multiplication.
Returns:
M1 ∗ M2

TVec4 operator∗ (const TMat4 & lhs, const TVec4 & rhs) [related]
Matrix multiplication with a vector.
Returns:
M∗v

TVec3 operator∗ (const TMat4 & lhs, const TVec3 & rhs) [related]
Matrix multiplication with a vector.
Returns:
M∗v

Playground 4.0.17.1
292 Class and File Reference

TVec4 operator∗ (const TVec4 & lhs, const TMat4 & rhs) [related]
Matrix multiplication with a vector.
Returns:
M∗v

TMat4 operator∗ (const TMat4 & lhs, TReal s) [related]


Matrix scaling.
Returns:

a00 ∗ s a10 ∗ s a20 ∗ s a30 ∗ s


a01 ∗ s a11 ∗ s a21 ∗ s a31 ∗ s
a02 ∗ s a12 ∗ s a22 ∗ s a32 ∗ s
a03 ∗ s a13 ∗ s a23 ∗ s a33 ∗ s

TMat4 operator/ (const TMat4 & lhs, TReal s) [related]


Matrix scaling.
Returns:
(1/s) ∗ M

Navigating the Playground SDK


15.35 TMaterial Struct Reference 293

15.35 TMaterial Struct Reference


#include <pf/pftypes.h>

15.35.1 Detailed Description


A rendering material.

Public Attributes
• TColor mcDiff
• TColor mcAmb
• TColor mcSpec
• TColor mcEmit
• TReal mfPower

15.35.2 Member Data Documentation


TColor TMaterial::mcDiff
Diffuse value.

TColor TMaterial::mcAmb
Ambient value.

TColor TMaterial::mcSpec
Specular value.

TColor TMaterial::mcEmit
Emit (glow) value.

TReal TMaterial::mfPower
Specular reflectance. Zero to disable specular.

Playground 4.0.17.1
294 Class and File Reference

15.36 TMessage Class Reference


#include <pf/message.h>

15.36.1 Detailed Description


Application message base class. Actual messages being passed around by the application will
either use TMessage (this page) directly or derive from TMessage (this page), depending on
whether they need additional payload.
Warning:

Never use C++ or C style casting to coerce a TMessage (this page) to another type; always
use GetCast<>() (p. 296). When a message is sent from Lua, it is wrapped in a TLuaMes-
sageWrapper, which will report the mType of the contained TMessage-derived message–and
it has a GetCast operator that will give you the actual contained message. But casting it to
your target object will result in undefined (and certainly incorrect) behavior, so it’s best to
always use GetCast.

Type Information and Casting

• PFClassId ClassId ()
• virtual bool IsKindOf (PFClassId type)
• template<class TO>
TO ∗ GetCast ()

Public Types

• enum EMessageID { kGeneric, kCloseWindow, kDefaultAction, kButtonPress, kPres-


sAnyKey, kQuitNow, kModalClosed, kTextEditChanged, kCommandOnly, kSlider-
ValChanged, kSliderMouseUp, kSliderPageUp, kSliderPageDown, kUserMessageBase }

Public Member Functions

• TMessage (int32_t type=kGeneric, str name="", TWindow ∗destination=NULL)


• virtual ∼TMessage ()

Public Attributes

• int32_t mType
• str mName
• TWindow ∗ mDestination

Navigating the Playground SDK


15.36 TMessage Class Reference 295

15.36.2 Member Enumeration Documentation


enum TMessage::EMessageID
System-level predefined message IDs. Start user message IDs at kUserMessageBase
Enumerator:
kGeneric A generic message–the derived class determines the type.
kCloseWindow Close the current window if you get this message ID.
kDefaultAction Trigger the default action (done by pressing "enter" equivalent).
kButtonPress Button pressed.
kPressAnyKey Unhandled user input.
kQuitNow Time to exit the application.
kModalClosed A modal window closed.
kTextEditChanged New information has been typed into/removed from a text edit field.
kCommandOnly This message is empty; it’s being sent to run the accompanying command.
kSliderValChanged A slider value changed.
kSliderMouseUp The mouse has been released on a slider.
kSliderPageUp Someone clicked above the slider handle to create a virtual page-up.
kSliderPageDown Someone clicked below the slider handle to create a virtual page-down.
kUserMessageBase First ID available for client applications.

15.36.3 Constructor & Destructor Documentation


TMessage::TMessage (int32_t type = kGeneric, str name = "", TWindow ∗ destination =
NULL)
Constructor.
Parameters:
type Message type.
name Message name.
destination Optional destination window.

virtual TMessage::∼TMessage ()
Destructor.

15.36.4 Member Function Documentation


PFClassId TMessage::ClassId ()
Get the ClassId.
Returns:
A ClassId that can be passed to IsKindOf.
See also:
Type Information and Casting (p. 25)

Playground 4.0.17.1
296 Class and File Reference

bool TMessage::IsKindOf (PFClassId type)


Determine whether this message is derived from type.
Parameters:
type ClassId() (previous page) of type to test.
See also:
Type Information and Casting (p. 25)

template<class TO> template< class TO > TO ∗ TMessage::GetCast ()


Safely cast this message to another type.
Returns:
A cast pointer, or NULL.
See also:
Type Information and Casting (p. 25)

15.36.5 Member Data Documentation


int32_t TMessage::mType
The EMessageID of this message, or a user defined type (starting at kUserMessageBase).

str TMessage::mName
Name of this message.
For a button message, this is the name of the button that is sending the message.

TWindow∗ TMessage::mDestination
Optional TWindow (p. 496) destination.

Navigating the Playground SDK


15.37 TMessageListener Class Reference 297

15.37 TMessageListener Class Reference


#include <pf/messagelistener.h>

15.37.1 Detailed Description


A message listener–a class that you override and register with the TWindowManager (p. 519) if
you want to listen for broadcast messages.

Public Member Functions


• virtual ∼TMessageListener ()
• virtual bool OnMessage (TMessage ∗message)=0

15.37.2 Constructor & Destructor Documentation


virtual TMessageListener::∼TMessageListener ()
Destructor.

15.37.3 Member Function Documentation


virtual bool TMessageListener::OnMessage (TMessage ∗ message)
This function will be called for each broadcast message that’s delivered.
Parameters:
message The message being delievered.
Returns:
True if the message was processed. No more searching for handlers will occur, and the mes-
sage will be deleted by the caller if necessary.

Playground 4.0.17.1
298 Class and File Reference

15.38 TModalWindow Class Reference


#include <pf/modalwindow.h>
Inheritance diagram for TModalWindow:

TWindow

TModalWindow

TDialog TScreen

15.38.1 Detailed Description


Base class for any window that can be a modal window.
Adds a number of functions to the default TWindow (p. 496):

• Handles tasks that are associated with a modal window.

• Manages a TClock (p. 213) that automatically gets paused when the modal is covered by
another modal.

• Does some internal bookeeping relevant to the window stack and opaque full-screen win-
dows.

• Handles dispatching key messages to a default focus window.

Construction/destruction
• TModalWindow ()
• virtual ∼TModalWindow ()

Modal Window Task Handling


• void AdoptTask (TTask ∗task)
• bool OrphanTask (TTask ∗task)
• void DestroyTasks ()

Focus and Key Handling


• void SetDefaultFocus (TWindow ∗focus)
• TWindow ∗ GetDefaultFocus ()

Navigating the Playground SDK


15.38 TModalWindow Class Reference 299

• virtual void AddHotkey (str key, str buttonToPress)


• virtual bool OnKeyDown (char key, uint32_t flags)
• static str NormalizeKeyString (str key)

Message handlers
TModalWindow handles these messages for you.

• virtual void OnSetFocus (TWindow ∗previous)


• virtual bool OnNewParent ()
• virtual bool OnMessage (TMessage ∗message)
• virtual bool OnChar (char key)
• void DoModalProcess (TTask::ETaskContext context=TTask::eNormal)

Public Member Functions


• TClock ∗ GetClock ()
• virtual void PostChildrenInit (TWindowStyle &style)

15.38.2 Constructor & Destructor Documentation


TModalWindow::TModalWindow ()
Default constructor.
Sets window type to include kModal.

virtual TModalWindow::∼TModalWindow ()
Destructor.

15.38.3 Member Function Documentation


void TModalWindow::AdoptTask (TTask ∗ task)
Add a task to the modal window’s task list. Task list takes ownership of the task and will delete it
when the task notifies that it is complete.
Parameters:
task Task to add.

bool TModalWindow::OrphanTask (TTask ∗ task)


Remove a task from the task list. Does not delete the task, but rather releases ownership; calling
function now owns task.

Playground 4.0.17.1
300 Class and File Reference

Parameters:
task Task to remove.
Returns:
true if task was removed, false if task was not found

void TModalWindow::DestroyTasks ()
Destroy all tasks this window owns. Used when the window is about to be destroyed.
Destruction is "safe"–tasks will be added to a destroy list if the list is being iterated.

void TModalWindow::SetDefaultFocus (TWindow ∗ focus)


Set the window that will receive an "implicit" focus when no other window has the focus.
Parameters:
focus Default focus target. NULL to remove the default focus.

TWindow∗ TModalWindow::GetDefaultFocus ()
Get the current default focus

virtual void TModalWindow::AddHotkey (str key, str buttonToPress)


Add a hot key to the current modal window.
When someone presses the given key, the given button name will be pressed.
To create more arbitrary commands that don’t press visible buttons, create invisible buttons that
can be "pressed" by name.
Parameters:
key Key to bind this button to. Can include:

• Ctrl+ for control, e.g., "Ctrl+C" would be control-c.

• Alt+ for the alt key, e.g., "Alt+C" would be alt-C.

• Shift+ for the shift key, e.g., "Shift+Alt+C" would be shift-alt-C.

If the key starts with ’@’, then ANY modifiers will be accepted, e.g., "@A" would work for an
(uncaptured) "A", "Ctrl-A", "Alt-A", etc.
Parameters:
buttonToPress The name of the button to press. An empty string will delete the key associa-
tion.

Navigating the Playground SDK


15.38 TModalWindow Class Reference 301

virtual bool TModalWindow::OnKeyDown (char key, uint32_t flags)


Raw key hit on keyboard: TModalWindow (p. 298) will check to see if it’s a "hot" key, and if so,
then trigger the appropriate child button.
Parameters:
key Key pressed on keyboard.
flags TEvent::EKeyFlags (p. 230) mask representing the state of other keys on the keyboard
when this key was hit.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented from TWindow (p. 514).

static str TModalWindow::NormalizeKeyString (str key) [protected]


Take a string with a key description and normalize the description.
For example:

* alt-SHIFT-Ctrl-f
*

would return

* shift-ctrl-alt-F
*

The normalized string always sorts the operators in the order shift, ctrl, alt, and presents them in
lower case. The key name itself is capitalized.
This function is used internally to normalize the key string in AddHotkey() (opposite) and
TModalWindow::OnKeyDown() (this page)–there’s no need for you to call it yourself unless
you’re extending TModalWindow (p. 298).
Parameters:
key Key to normalize.
Returns:
A normalized string.

virtual void TModalWindow::OnSetFocus (TWindow ∗ previous)


This window is receiving the keyboard focus.
Parameters:
previous The window that was previously focused. Can be NULL.

Reimplemented from TWindow (p. 515).

Playground 4.0.17.1
302 Class and File Reference

virtual bool TModalWindow::OnNewParent ()


Handle any initialization or setup that is required when this window is assigned to a new parent.
No initialization of the window has happened prior to this call.
Returns:
True on success; false on failure.
See also:
Init (p. 501)
PostChildrenInit (opposite)

Reimplemented from TWindow (p. 501).


Reimplemented in TDialog (p. 222).

virtual bool TModalWindow::OnMessage (TMessage ∗ message)


Handle a message.
Parameters:
message Payload of message.
Returns:
True if message handled; false otherwise.

Reimplemented from TWindow (p. 511).


Reimplemented in TDialog (p. 222).

virtual bool TModalWindow::OnChar (char key)


Translated character handler.
Parameters:
key Key hit on keyboard, along with shift translations.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented from TWindow (p. 513).

void TModalWindow::DoModalProcess (TTask::ETaskContext context = TTask::eNormal)


Handles any modal processing that needs to happen.
Processes tasks in the task list. This is called internally by the system once per frame in
TTask::eNormal (p. 429) state and once in TTask::eOnDraw (p. 429) state.
Parameters:
context The context the processes should be called in.

Navigating the Playground SDK


15.38 TModalWindow Class Reference 303

TClock∗ TModalWindow::GetClock ()
Get a reference to the clock associated with this modal window. This clock will be automatically
paused and unpaused when other modal windows hide and reveal this modal window.
Returns:
A pointer to the clock.

virtual void TModalWindow::PostChildrenInit (TWindowStyle & style)


Do post-children-added initialization when being created from Lua.
Any initialization that needs to happen after a window’s children have been added can be placed
in a derived version of this function.
Warning:

Remember to always call the base class if you’re overriding this function.
Parameters:
style Current style environment that this window was created in.

Reimplemented from TWindow (p. 502).

Playground 4.0.17.1
304 Class and File Reference

15.39 TModel Class Reference


#include <pf/model.h>
Inheritance diagram for TModel:

TAsset

TModel

15.39.1 Detailed Description


A 3d model.

Public Member Functions

• void Draw ()
• bool Pick (uint32_t iWndX, uint32_t iWndY, TReal ∗pfPickDist, TVec3 ∗pvHit)
• str GetName ()
• long GetPolyCount ()
• uint32_t GetTriangleCount ()
• const uint16_t ∗ GetTriangles ()
• const TVert ∗ GetVertices ()
• uint32_t GetVertexCount ()
• TModelRef GetRef ()

Static Public Member Functions

• static TModelRef Get (str assetName)

Public Attributes

• TModelData ∗ mData

Protected Member Functions

• virtual void Restore ()


• virtual void Release ()

Navigating the Playground SDK


15.39 TModel Class Reference 305

15.39.2 Member Function Documentation


void TModel::Draw ()
Draw the model using the current texture, material, and transformation matrix.
Any texture used with TModel::Draw (this page) must be square and have dimensions that are
powers of two.

bool TModel::Pick (uint32_t iWndX, uint32_t iWndY, TReal ∗ pfPickDist, TVec3 ∗ pvHit)
Cast a ray at the model and determine whether it’s been hit. Uses current transformation matrix
to position model.
Parameters:
iWndX X in TScreen (p. 387) coordinates.
iWndY Y in TScreen (p. 387) coordinates.
pfPickDist Pointer to a float that starts out initialized to the maximum distance the cast ray
should collide with polygons. On return contains the actual distance from the screen to
the model.
pvHit The 3d point where the cast ray intersects the model.
Returns:
True if model hit; false otherwise.

str TModel::GetName ()
Get the name of the asset as it was created.
Returns:
The name of the asset.

long TModel::GetPolyCount ()
Get the number of polygons (triangles) in the model
Deprecated

This function will be replaced by GetTriangleCount() (this page).


Returns:
Number of triangles.

uint32_t TModel::GetTriangleCount ()
Get the number of triangles in the triangle array.
Returns:
Number of triangles.

Playground 4.0.17.1
306 Class and File Reference

const uint16_t∗ TModel::GetTriangles ()


Get a pointer to an array of uint16_t values triples that indicate vertex indices that define triangles.
Returns:
A pointer to triangle indices.

const TVert∗ TModel::GetVertices ()


Get an array of the model’s vertices.
Returns:
A pointer to an array of TVert (p. 493) vertices.
See also:
GetVertexCount (this page)

uint32_t TModel::GetVertexCount ()
Get the number of vertices in the model.
Returns:
A count of vertices in the vertex array.
See also:
GetVertices (this page)

TModelRef TModel::GetRef ()
Get a reference to this asset. Do not call in a constructor!
Reimplemented from TAsset (p. 195).

static TModelRef TModel::Get (str assetName)


Factory
Parameters:
assetName Asset id of the model
Returns:
A TModelRef of the model

virtual void TModel::Restore () [protected]


Restore an asset.
Reimplemented from TAsset (p. 195).

Navigating the Playground SDK


15.39 TModel Class Reference 307

virtual void TModel::Release () [protected]


Release an asset.
Reimplemented from TAsset (p. 195).

15.39.3 Member Data Documentation


TModelData∗ TModel::mData
Implemenation details.

Playground 4.0.17.1
308 Class and File Reference

15.40 TParamSet Class Reference


#include <pf/luaparticlesystem.h>
Inheritance diagram for TParamSet:

TParamSet

TParticleState

15.40.1 Detailed Description


A set of parameters or return values, depending on context.

Public Member Functions


• void ResetPartial (uint32_t base, uint8_t ∗s, uint32_t count)
• void Reset (uint8_t ∗s, uint32_t count)
• TParamSet (TReal ∗p, uint8_t ∗s, uint32_t count)
• uint8_t GetCount ()
• uint32_t GetOffset (uint8_t param)
• uint8_t GetSize (uint8_t entry)
• void Redirect (TReal ∗p)
• template<typename Type>
Type & Param (uint8_t param)
• TReal & GetReal (uint32_t index)
• TReal GetReal (uint32_t index) const

Static Public Attributes


• static const uint32_t kMaxParams

15.40.2 Constructor & Destructor Documentation


TParamSet::TParamSet (TReal ∗ p, uint8_t ∗ s, uint32_t count)
Create a TParamSet (this page)
Parameters:
p Set of parameter values (must be count∗4 in TReals)
s Sizes of parameters (must be count int8_t values)
count Number of parameters.

Navigating the Playground SDK


15.40 TParamSet Class Reference 309

References Reset().

15.40.3 Member Function Documentation


void TParamSet::ResetPartial (uint32_t base, uint8_t ∗ s, uint32_t count)
Reload part of a ParamSet with return parameters.
Parameters:
base New first parameter in set
s A pointer to a local list of parameter sizes (number of floats in each parameter).
count Number of parameters. Must be less than or equal to original parameter count.

References ASSERT, and kMaxParams.


Referenced by TParticleMachineState::InitReturnValues(), TParticleMachineState::Push(), and Re-
set().

void TParamSet::Reset (uint8_t ∗ s, uint32_t count)


Reload a ParamSet with return parameters.
Parameters:
s A pointer to a local list of parameter sizes (number of floats in each parameter).
count Number of parameters. Must be less than or equal to original parameter count.

References ResetPartial().
Referenced by TParamSet().

uint8_t TParamSet::GetCount ()
Get the current parameter count
Returns:
Number of parameters in the set.

Reimplemented in TParticleState (p. 324).


Referenced by TParticleState::GetCount(), and TParticleState::GetReal().

uint32_t TParamSet::GetOffset (uint8_t param)


Get the offset of the nth entry in the set.
Parameters:
param Parameter entry to query.
Returns:
Offset (in TReals) into the set.

Playground 4.0.17.1
310 Class and File Reference

Reimplemented in TParticleState (p. 323).


Referenced by TParticleState::GetOffset(), TParticleMachineState::GetOffset(), TParticleMachineS-
tate::GetReal(), and TParticleMachineState::Push().

uint8_t TParamSet::GetSize (uint8_t entry)


Get the size of a particular entry.
Parameters:
entry Entry to query.
Returns:
Size (in TReals) of entry.

Referenced by TParticleMachineState::GetSize().

void TParamSet::Redirect (TReal ∗ p)


Point this at a new parameter set (typically a new particle).
Parameters:
p

Reimplemented in TParticleState (p. 323).


Referenced by TParticleState::Redirect().

template<typename Type> Type& TParamSet::Param (uint8_t param)


Parameter extractor.
Parameters:
Type Type of parameter to extract.
param Parameter base (which parameter number this is)
Returns:
A reference of type Type to the parameter that can be read or written to.

Reimplemented in TParticleState (p. 323).


Referenced by TParticleMachineState::Param().

TReal& TParamSet::GetReal (uint32_t index)


Get a raw real value.
Parameters:
index Index of real to extract.

Navigating the Playground SDK


15.40 TParamSet Class Reference 311

Returns:
A value in the set.

Reimplemented in TParticleState (p. 323).


Referenced by TParticleState::GetReal(), TParticleMachineState::GetReal(), and TParticleMa-
chineState::Push().

TReal TParamSet::GetReal (uint32_t index) const


Get a raw real value.
Parameters:
index Index of real to extract.
Returns:
A value in the set.

15.40.4 Member Data Documentation


const uint32_t TParamSet::kMaxParams
The maximum number of parameters that can be passed.
Referenced by ResetPartial().

Playground 4.0.17.1
312 Class and File Reference

15.41 TParticleFunction Class Reference


#include <pf/luaparticlesystem.h>

15.41.1 Detailed Description


A user data source.

Public Member Functions


• virtual void InitFrame ()
• virtual uint8_t GetReturnSize (int paramCount, uint8_t ∗sizes)=0
• virtual bool Process (TParticleState &particle, TParticleMachineState &params)=0
• PFClassId ClassId ()
• virtual bool IsKindOf (int type)
• template<class TO>
TO ∗ GetCast ()

Static Public Member Functions


• static TParticleFunction ∗ CreateFromId (PFClassId id)

Public Attributes
• str mName

15.41.2 Member Function Documentation


virtual void TParticleFunction::InitFrame ()
Optional initializer that’s called once per particle render frame.

virtual uint8_t TParticleFunction::GetReturnSize (int paramCount, uint8_t ∗ sizes)


Initialize parameters.
For DataSource functions, incoming parameters will always be
Parameters:
paramCount Number of parameters in array.
sizes Pointer to size array (NULL for registered data sources).
Returns:
Size of parameter in TReals.

Navigating the Playground SDK


15.41 TParticleFunction Class Reference 313

virtual bool TParticleFunction::Process (TParticleState & particle, TParticleMachineState &


params)
Process function or fetch data
Parameters:
particle Particle being processed.
params [in/out] parameters
Returns:
True on success; false if parameters are incorrect.

static TParticleFunction∗ TParticleFunction::CreateFromId (PFClassId id)


Dynamic creation.
Parameters:
id The PFClassId of the class to create.
Returns:
A new TParticleFunction-derived class instance.

PFClassId TParticleFunction::ClassId ()
The class id of this class.

virtual bool TParticleFunction::IsKindOf (int type)


Query whether this class IsKindOf another class.
Parameters:
type The ClassId of the class to compare to.
Returns:
True if class is, or is derived from, target class.

template<class TO> TO∗ TParticleFunction::GetCast ()


Safely cast this class to another class.
Parameters:
TO Class to convert to.
Returns:
A cast pointer, or NULL if this class is unrelated to the target.

Playground 4.0.17.1
314 Class and File Reference

15.41.3 Member Data Documentation


str TParticleFunction::mName
The name of the function; will be set internally when it’s registered.

Navigating the Playground SDK


15.42 TParticleMachineState Class Reference 315

15.42 TParticleMachineState Class Reference


#include <pf/luaparticlesystem.h>

15.42.1 Detailed Description


The internal state of a TLuaParticleSystem (p. 264).

Public Member Functions

• TParticleMachineState (TParamSet &paramSet, TLuaParticleSystem ∗lps)


• template<typename Type>
Type & Param (int8_t param)
• TReal & GetReal (uint32_t index)
• uint8_t GetSize (int8_t param)
• void Push (TReal ∗r, uint8_t size)
• template<typename Type>
void Push (Type value)
• void Leave ()
• uint8_t GetCount ()
• uint32_t GetOffset (uint8_t param)
• void InitReturnValues (uint8_t ∗s, uint32_t count)
• void SetNumParams (uint8_t num)
• uint8_t GetNumParams ()
• TParticleFunction ∗ GetDataSource (int32_t source)

15.42.2 Constructor & Destructor Documentation


TParticleMachineState::TParticleMachineState (TParamSet & paramSet, TLuaParticleSystem
∗ lps)
A set of function parameters.
Parameters:
paramSet The stack to initialize function parameters from.
lps A pointer to the associated TLuaParticleSystem (p. 264).

15.42.3 Member Function Documentation


template<typename Type> Type& TParticleMachineState::Param (int8_t param)
Parameter extractor.

Playground 4.0.17.1
316 Class and File Reference

Parameters:
Type Type of parameter to extract.
param Parameter base (which parameter number this is)
Returns:
A Type reference that can be read or written to.

References ASSERT, and TParamSet::Param().

TReal& TParticleMachineState::GetReal (uint32_t index)


Get a TReal value directly from the stack.
Parameters:
index Index of value.
Returns:
The value from the stack.

References TParamSet::GetOffset(), and TParamSet::GetReal().

uint8_t TParticleMachineState::GetSize (int8_t param)


Get the size of one of the parameters.
Parameters:
param Parameter to query.
Returns:
Size of parameter.

References ASSERT, and TParamSet::GetSize().

void TParticleMachineState::Push (TReal ∗ r, uint8_t size)


Push a value onto the stack.
Parameters:
r Pointer to the value array.
size Size of the value array.

References TParamSet::GetOffset(), TParamSet::GetReal(), and TParamSet::ResetPartial().


Referenced by Push().

template<typename Type> void TParticleMachineState::Push (Type value)


Push a value onto the stack. Invalidates incoming parameter list.

Navigating the Playground SDK


15.42 TParticleMachineState Class Reference 317

Parameters:
Type
value

References Push().

void TParticleMachineState::Leave ()
Exit a function (removes any remaining parameters; a NOP if the function pushed any return
values).

uint8_t TParticleMachineState::GetCount ()
Get the local parameter count
Returns:
Number of parameters in the set.

uint32_t TParticleMachineState::GetOffset (uint8_t param)


Get the offset of a parameter on the stack.
Parameters:
param The parameter number to retrieve. The stack is an array of TReal values, but they
logically group into parameters, so if the first parameter is a Vec3() (p. 139), the second
parameter offset will be 3.
Returns:
The offset to the requested parameter.

References TParamSet::GetOffset().

void TParticleMachineState::InitReturnValues (uint8_t ∗ s, uint32_t count)


Reload with return parameters.
Parameters:
s A pointer to a local list of parameter sizes (number of floats in each parameter).
count Number of return values.

References TParamSet::ResetPartial().

void TParticleMachineState::SetNumParams (uint8_t num)


Set the number of parameters being passed to the current function
Parameters:
num Number of parameters

Playground 4.0.17.1
318 Class and File Reference

uint8_t TParticleMachineState::GetNumParams ()
Get the number of parameters passed.
Returns:
The number of incoming parameters.

TParticleFunction∗ TParticleMachineState::GetDataSource (int32_t source)


Get a registered data source by index.
Parameters:
source Data source index to read (must be negative).
Returns:
The data source.

Navigating the Playground SDK


15.43 ParticleMember Struct Reference 319

15.43 ParticleMember Struct Reference


#include <pf/luaparticlesystem.h>

15.43.1 Detailed Description


A particle member value. When additional values are added to a particle (beyond what exists in
the base particle values), each is allocated as a ParticleMember (this page).

Public Member Functions


• ParticleMember (int16_t base=0, uint16_t size=0)

Public Attributes
• int16_t mBase
• uint16_t mSize

15.43.2 Constructor & Destructor Documentation


ParticleMember::ParticleMember (int16_t base = 0, uint16_t size = 0)
Constructor
Parameters:
base Base index (in TReals) of this member.
size Size of this member in TReals.

15.43.3 Member Data Documentation


int16_t ParticleMember::mBase
Index in TReals into the particle.

uint16_t ParticleMember::mSize
Size of this member.

Playground 4.0.17.1
320 Class and File Reference

15.44 TParticleRenderer Class Reference


#include <pf/particlerenderer.h>
Inheritance diagram for TParticleRenderer:

TParticleRenderer

T2dParticleRenderer

15.44.1 Detailed Description

The abstract particle renderer class: This class is used by TLuaParticleSystem (p. 264) to wrap an
actual particle renderer. This way you can use TLuaParticleSystem (p. 264) to drive the default 2d
particle system or other more complex systems.

Public Member Functions

• virtual void Draw (const TVec3 &at, TReal alpha, const ParticleList &particles, int maxPar-
ticles)=0
• virtual void SetTexture (TTextureRef texture)=0
• virtual void SetRendererOption (str option, const TReal(&value)[4])=0
• virtual TReal ∗ GetPrototypeParticle ()=0
• virtual uint32_t GetPrototypeParticleSize ()=0
• virtual str GetLuaInitString ()=0

15.44.2 Member Function Documentation

virtual void TParticleRenderer::Draw (const TVec3 & at, TReal alpha, const ParticleList &
particles, int maxParticles)
Render the particles.
Parameters:
at Location to render particles.
alpha Alpha to render particles with.
particles The list of particles to render.
maxParticles The maximum number of particles this particle system is expecting to render.
MUST be greater than the number of particles or Bad Things will happen.

Implemented in T2dParticleRenderer (p. 173).

Navigating the Playground SDK


15.44 TParticleRenderer Class Reference 321

virtual void TParticleRenderer::SetTexture (TTextureRef texture)


Set the texture for the particle.
Parameters:
texture Texture to use.

Implemented in T2dParticleRenderer (p. 173).

virtual void TParticleRenderer::SetRendererOption (str option, const TReal(&) value[4])


Set a renderer-specific option.
Parameters:
option Option to set.
value Value to set option to, in the form of an array of TReals. Not all values in array are
relevant for all options.

Implemented in T2dParticleRenderer (p. 174).

virtual TReal∗ TParticleRenderer::GetPrototypeParticle ()


Get an initialized particle that will be copied over each particle after creation but before running
initializers.
Returns:
A pointer to an array of TReals.

Implemented in T2dParticleRenderer (p. 174).

virtual uint32_t TParticleRenderer::GetPrototypeParticleSize ()


Size of the array of TReals returned by GetPrototypeParticle.
Returns:
Number of reals.

Implemented in T2dParticleRenderer (p. 174).

virtual str TParticleRenderer::GetLuaInitString ()


Get a TLuaParticleSystem (p. 264) initialization string.
Returns:
A valid Lua string that will be executed by a TLuaParticleSystem (p. 264) that uses this ren-
derer.

Implemented in T2dParticleRenderer (p. 174).

Playground 4.0.17.1
322 Class and File Reference

15.45 TParticleState Class Reference


#include <pf/luaparticlesystem.h>
Inheritance diagram for TParticleState:

TParamSet

TParticleState

15.45.1 Detailed Description


A particle state. A particle state is made up of some number of floating point values and an
indication of elapsed milliseconds.
Note the private inheritance: We don’t want to expose TParamSet::Reset (p. 309) on a TParti-
cleState (this page), but we want the TParamSet (p. 308) implementation.

Public Member Functions


• TParticleState (TReal ∗p, uint8_t ∗s, uint32_t count, uint32_t ms)
• template<typename Type>
Type & Param (uint8_t param)
• TReal & GetReal (uint32_t index)
• uint32_t GetOffset (uint8_t param)
• void Redirect (TReal ∗p)
• uint32_t GetCount ()
• uint32_t GetMS ()
• bool GetAlive ()
• void KillParticle ()

15.45.2 Constructor & Destructor Documentation


TParticleState::TParticleState (TReal ∗ p, uint8_t ∗ s, uint32_t count, uint32_t ms)
Constructor.
Parameters:
p A pointer to an array of TReals that will be used as the dynamic particle state. Must be
count∗4 TReals.
s A pointer to an array of bytes that indicate parameter sizes.
count The number of members in the particle.
ms The number of milliseconds that have passed in this time step.

Navigating the Playground SDK


15.45 TParticleState Class Reference 323

15.45.3 Member Function Documentation


template<typename Type> Type& TParticleState::Param (uint8_t param)
Parameter extractor.
Parameters:
Type Type of parameter to extract.
param Parameter base (which parameter number this is)
Returns:
A Type reference that can be read or written to.

Reimplemented from TParamSet (p. 310).

TReal& TParticleState::GetReal (uint32_t index)


Get a raw real value.
Parameters:
index Index of real to extract.
Returns:
A value in the set.

Reimplemented from TParamSet (p. 310).


References ASSERT, TParamSet::GetCount(), GetOffset(), and TParamSet::GetReal().

uint32_t TParticleState::GetOffset (uint8_t param)


Get the offset of the nth entry in the set.
Parameters:
param Parameter entry to query.
Returns:
Offset (in TReals) into the set.

Reimplemented from TParamSet (p. 309).


References TParamSet::GetOffset().
Referenced by GetReal().

void TParticleState::Redirect (TReal ∗ p)


Point this at a new parameter set (typically a new particle).
Parameters:
p

Playground 4.0.17.1
324 Class and File Reference

Reimplemented from TParamSet (p. 310).


References TParamSet::Redirect().

uint32_t TParticleState::GetCount ()
Get the current parameter count
Returns:
Number of parameters in the set.

Reimplemented from TParamSet (p. 309).


References TParamSet::GetCount().

uint32_t TParticleState::GetMS ()
Get the number of milliseconds being processed.
Returns:
Time elapsed in milliseconds.

bool TParticleState::GetAlive ()
Query whether this particle is still alive.
Returns:
True if alive.

void TParticleState::KillParticle ()
Kill this particle (mark for destruction).

Navigating the Playground SDK


15.46 TPfHiscores Class Reference 325

15.46 TPfHiscores Class Reference


#include <pf/pfhiscores.h>

15.46.1 Detailed Description


TPfHiScores - class that manages local and global hiscore saving and viewing.
This is the backend class for managing hiscores. It has the ability to save and load local hiscores as
well as submit and retrieve hiscores from the server.
For information about how to test your hiscore implementation against a debug server, please see
the PlayFirst Global High Scores (p. 30) information.
Localization - the hiscore system can be localized by including a file called "hiscore.xml" in the
same data directory as the .dll or the .exe if you are using a static lib. The contents of this xml file
should be:

<hiscore> XML
<language>en</language>
<defaulterror>Unable to connect to server. Please try again later.</defaulterror>
</hiscore>

The language parameter will override any setting used with eLanguage property in SetProperty()
(p. 327). Language should be ISO-639 (e.g. "en", "jp", "fr", "en_CA"). The default error string is
what is displayed in the case of not being able to connect to the server.

Public Types
• enum EStatus { eSuccess, ePending, eError }
• enum EProperty { eLanguage, ePlayerName, eGameMode }
• enum EMedalType { eMedalType_Game, eMedalType_Mode }
• enum EUserScore { eLocalEligible, eGlobalBest }
• enum ESubmitMode { kSubmitScore, kSubmitMedal, kSubmitAll }

Public Member Functions


• TPfHiscores (bool saveData=true)
• ∼TPfHiscores ()
• void SetProperty (EProperty property, str value)
• void KeepScore (int32_t score, bool replaceExisting, const char ∗gameData)
• void KeepMedal (const char ∗medalName, EMedalType type, str gameData)
• bool GetRememberedUserInfo (str ∗userName, str ∗password)
• void SetRememberedUserInfo (str userName, str password)
• void RequestCategoryInformation ()
• int32_t GetCategoryCount ()
• bool GetCategoryName (int32_t n, char ∗name, uint32_t bufSize)

Playground 4.0.17.1
326 Class and File Reference

• void RequestScores (int32_t categoryIndex)


• EStatus GetServerRequestStatus (char ∗msg, uint32_t bufLen, bool ∗pQualified)
• int32_t GetScoreCount (bool local)
• bool GetScore (bool local, int32_t n, int32_t ∗pRank, char ∗name, uint32_t bufSize, bool
∗pAnonymous, int32_t ∗pScore, char ∗gameData, uint32_t gameDataBufferSize)
• bool GetUserBestScore (EUserScore userScore, int32_t ∗pScore, int32_t ∗pRank, char
∗gameData, uint32_t gameDataBufferSize)
• int GetNumMedalsToSubmit ()
• int GetNumMedalsEarned ()
• bool GetEarnedMedalInfo (int index, str ∗medalName, EMedalType ∗type, str
∗gameMode, str ∗gameData)
• bool SubmitData (str username, str password, bool bRemember, ESubmitMode submit-
Mode)
• void ClearScores ()
• uint32_t EncryptData (const void ∗toEncrypt, uint32_t len, char ∗buf, uint32_t bufLen)
• uint32_t DecryptData (const char ∗toDecrypt, void ∗buf, uint32_t bufLen)
• void LogScore (int32_t score, bool replaceExisting, const char ∗gameData, const char
∗serverData=NULL)
• bool SubmitScore (str username, str password, bool bRemember)
• bool SubmitMedals (const char ∗medalsData, str username, str password, bool bRemember)

15.46.2 Member Enumeration Documentation


enum TPfHiscores::EStatus
After sending a request to the hiscore server, this is the status of the request.

enum TPfHiscores::EProperty
The various properties that can be set for the hiscore module.

enum TPfHiscores::EMedalType
The various medal types for use in KeepMedal() (p. 328)
Enumerator:
eMedalType_Game Medals that are awarded for the entire game, regardless of what mode
the user is in.
eMedalType_Mode Medals that are awarded per game mode (the user can earn this medal
once in each game mode).

enum TPfHiscores::EUserScore
The various modes for calling GetUserBestScore() (p. 331)

Navigating the Playground SDK


15.46 TPfHiscores Class Reference 327

enum TPfHiscores::ESubmitMode
Submit modes
Controls what type of data is submitted
Enumerator:
kSubmitScore Submit the user’s best score to the server.
kSubmitMedal Submit the user’s medals to the server.
kSubmitAll Submit all available data to the server. It is recommended that this mode be used
whenever the UI permits - that way all of the user’s data is submitted with one call.

15.46.3 Constructor & Destructor Documentation


TPfHiscores::TPfHiscores (bool saveData = true)
Default constructor
This initalizes the hiscores system. Among other things, it loads in a preference file off disk which
contains all the stored local scores.
The game name and encryption key must be set in the global configuration prior to constructing.
See TPlatform::SetConfig() (p. 340) for details. For standalone builds, see the standalone hiscore
documentation.
Parameters:
saveData Whether or not data should be saved between sessions, default is true. For exam-
ple, in a web game you might not want scores to persist between sessions, in which case
saveData should be false.

TPfHiscores::∼TPfHiscores ()
Default destructor

15.46.4 Member Function Documentation


void TPfHiscores::SetProperty (EProperty property, str value)
Sets a given property
Parameters:
property Which property to set. eLanguage - which language to set (ISO-639 (e.g. "en", "jp",
"fr", "en_CA")). The default language is "en". Note that this property will have no ef-
fect if you are using the "hiscore.xml" localization file described above. ePlayerName -
This is the local player name. This will be used for logging and returning local scores.
eGameMode - Once the game mode is set, it will be used for all score submission and
retreivals.
value Value to set the property to (for example, if property is eLanguage, value might be
"en").

Playground 4.0.17.1
328 Class and File Reference

void TPfHiscores::KeepScore (int32_t score, bool replaceExisting, const char ∗ gameData)


Log a score for the current player.
This stores a score for the current player into the local score table. A score must be logged before
it can be submitted. The score is logged for the player name set with SetPlayerName()
Parameters:
score the score the user is submitting
replaceExisting should this score submission replace an existing user score, or create a new
one? Typical usage is that story/career mode games replace an existing score, whereas
arcade modes allow a new score with each submission.
gameData game specific scoring information (up to 60 chars supported by server) - it is im-
portant that this be data that is additional scoring information (i.e. last level reached)
and not scoring interpretation information (i.e. awarded the "Best Ever" trophy) so that
the server can adjust awards later on. Also, this game data should not include any text
that would need to be localized. Therefore, it should just be numbers if at all possible.

void TPfHiscores::KeepMedal (const char ∗ medalName, EMedalType type, str gameData)


Log a medal for the current player.
This stores a medal for the current player. A medal must be logged before it can be submitted. The
medal is logged for the player name set with SetPlayerName()
If a player has already earned this particular medal, then this call does nothing. It is possible to
tell if this call changes the number of medals the player has by calling GetNumMedalsToSubmit()
(p. 331) before and after this call.
Parameters:
medalName The name of the medal the user earned. The same names used to fill in the
TPlatform::kPFGameMedalName (p. 347) config settings should be used here.
type The type of medal earned
gameData This string can be used to keep game specific information about how this medal
was earned. This data will not be transmitted to the server, and is just kept for retrieval
with GetEarnedMedalInfo() (p. 332). An example use might be a time stamp so that
when GetEarnedMedalInfo() (p. 332) is called to display a UI, a date can be displayed
along with the medal.

bool TPfHiscores::GetRememberedUserInfo (str ∗ userName, str ∗ password)


Retreives a username and password if one has been saved.
If the user submits their score with the bRemember flag set to true, then the username and pass-
word are saved, so that next time the user does not have to type them again.
Parameters:
userName str (p. 161) to hold user name
password str (p. 161) to hold password

Navigating the Playground SDK


15.46 TPfHiscores Class Reference 329

Returns:
- if the user/pass have been saved, this returns true and fills in the user/pass. if it has not
been saved, it returns false and does nothing to username and password.
If the user/pass have been saved, this returns tru and fills in the user/pass. If it has not been
saved, it returns false and does nothing to the username and password.

void TPfHiscores::SetRememberedUserInfo (str userName, str password)


Saves a user name and password.
Saves a user name and password without logging any score information.
Parameters:
userName If NULL or "" will delete any previously saved information.
password If NULL or "" will delete any previously saved information.

void TPfHiscores::RequestCategoryInformation ()
Submit a request to the server to retreive category information.
After calling this function, GetServerRequestStatus() (next page) must be polled until a result is
ready.

int32_t TPfHiscores::GetCategoryCount ()
Return the number of categories available for hiscores.
You must have retrieved the category information with RequestCategoryInformation() (this page)
first.
Returns:
Number of categories available.

bool TPfHiscores::GetCategoryName (int32_t n, char ∗ name, uint32_t bufSize)


Fill in a table name.
You must have retrieved the category information with RequestCategoryInformation() (this page)
first.
Parameters:
n Which category to fetch.
→ name Fills in category’s name
bufSize Size of name buffer.
Returns:
Returns false if category information has not been properly initialized.

Playground 4.0.17.1
330 Class and File Reference

void TPfHiscores::RequestScores (int32_t categoryIndex)


Submit a request to the server to retreive hiscores.
After calling this function, GetServerRequestStatus() (this page) must be polled until a result is
ready.
Parameters:
categoryIndex Which category is requested (use GetCategoryCount() (previous page) to see
how many categories are available)

EStatus TPfHiscores::GetServerRequestStatus (char ∗ msg, uint32_t bufLen, bool ∗ pQualified)


Return the status of the last server request.
After calling any functiont that contacts the server, this function must be polled until a result is
ready.
Parameters:
msg If EStatus is eError, an error message will be placed inside msg
bufLen Buffer length of msg.
pQualified For SubmitData() (p. 332), if EStatus is eSuccess, this fills in whether or not the
score qulaified for a global record.
Returns:
The current status of the request. If it is eError, the request failed and the message inside msg
should be displayed to the user.

int32_t TPfHiscores::GetScoreCount (bool local)


Retrieve the number of scores currently downloaded from the server.
To retrieve a server score, you must have retrieved the score information with RequestScores()
(this page) first.
Parameters:
local True to retrieve for local scores.
Returns:
Number of scores.

bool TPfHiscores::GetScore (bool local, int32_t n, int32_t ∗ pRank, char ∗ name, uint32_t
bufSize, bool ∗ pAnonymous, int32_t ∗ pScore, char ∗ gameData, uint32_t gameDataBufferSize)
Fill in all the various score information for a given score.
To retrieve a server score, you must have retrieved the score information with RequestScores()
(this page) first.
Parameters:
local True for local high scores, false for global.

Navigating the Playground SDK


15.46 TPfHiscores Class Reference 331

n Index into the score table.


→ pRank Fills in score’s rank in current table.
→ name Fills in player’s name.
bufSize Size of name buffer.
→ pAnonymous Fills in whether score is anonymous or not.
→ pScore Fills in score
→ gameData Fills in game specifc data
gameDataBufferSize Size of gameData buffer that can be filled in.
Returns:
Returns false if scores are not properly intialized.

bool TPfHiscores::GetUserBestScore (EUserScore userScore, int32_t ∗ pScore, int32_t ∗ pRank,


char ∗ gameData, uint32_t gameDataBufferSize)
Fill in all the various score information for a given user.
Depending on the userScore type passed in, different score information will be filled in.
Parameters:
userScore Type of score to fetch: eLocalEligible - the user’s best local score eligible for sub-
mission (one that has not already been submitted). eGlobalBest - the user’s best score on
the current global score table (obtained from RequestScores() (opposite)).
→ pScore Fills in the user’s score.
→ pRank Fills in score’s rank in current table.
→ gameData Fills in game specifc data.
gameDataBufferSize Size of gameData buffer that can be filled in.
Returns:
Returns false if the user has no eligible score, or if the game cannot find a user score in the
current table.

int TPfHiscores::GetNumMedalsToSubmit ()
Returns the number of medals that a user has earned but has not submitted to the server with
SubmitData() (next page).
This call does not return the total number of medals a user has earned, only the number of medals
that have not yet been submitted.
This result of this call is not dependent on the current game mode - it returns a total number of
medals across all game modes.

int TPfHiscores::GetNumMedalsEarned ()
Returns the number of medals that a user has earned, regardless of whether or not they have been
submitted.
This only reflects the number of medals that the user has earned according to locally saved data.
It does not fetch anything from the server.

Playground 4.0.17.1
332 Class and File Reference

This result of this call is not dependent on the current game mode - it returns a total number of
medals across all game modes.
The result from this call can be used to index into GetEarnedMedalInfo() (this page).

bool TPfHiscores::GetEarnedMedalInfo (int index, str ∗ medalName, EMedalType ∗ type, str ∗


gameMode, str ∗ gameData)

Returns stored medal info for the current user. Calling GetNumMedalsEarned() (previous page)
will let you know how many medals can be retrieved.
Parameters:
index Index of medal to be retrieved.
→ medalName Fills in the name of the medal (if medalName is not NULL).
→ type Fills in the type of the medal (if type is not NULL)
→ gameMode Fills in the gameMode that the medal was earned in (if gameMode is not
NULL).
→ gameData Fills in the gameData associated with the medal (if gameData is not NULL).
Returns:
Returns false if the passed in index is out of range. Otherwise returns true

bool TPfHiscores::SubmitData (str username, str password, bool bRemember, ESubmitMode


submitMode)

Submit the current user’s best score and medals to the server.
After calling this, you should poll GetServerRequestStatus() (p. 330) to check for errors or suc-
cessful submission.
Only one call to SubmitData() (this page) can be made at a time. You can not issue a second
call until GetServerRequestStatus() (p. 330) has returned a result. Issuing a second call before
GetServerRequestStatus() (p. 330) returns a result may result in undefined behavior.
Medals will only be submitted if a password is used. If a password is not used, then medals will
be saved until the next time a password-enabled submission is made.
All of a user’s available medals are submitted - the types of medals are not filtered by the current
game mode.
Parameters:
username Name to submit the score under.
password The user’s playfirst password. If this is NULL or "", then an anonymous submis-
sion is issued.
bRemember If this is true, then the module saves the username and password for future use.
If it is false, it deletes any previously saved username and password.
submitMode What data to submit. When possible kSubmitAll should be used so that all user
data is submitted. However, in certain UI presentations, it may only be appropriate to
submit medals but not scores, or vice versa.

Navigating the Playground SDK


15.46 TPfHiscores Class Reference 333

Returns:
If score submission is not possible, this returns false (i.e. the player has already submitted
their best score, or if they do not have any scores or medals for this game mode, etc.).

void TPfHiscores::ClearScores ()
Clear the local scores for the current game mode.
This will delete the current local scores for the current game mode. It cannot be undone.

uint32_t TPfHiscores::EncryptData (const void ∗ toEncrypt, uint32_t len, char ∗ buf, uint32_t
bufLen)
Encrypt a byte stream.
This will encrypt the passed in byte stream, and returns a string encoded in base64 (so it can be
passed around like a string).
Parameters:
toEncrypt The bytestream that is to be encrypted.
len The length of data to encrypt - note that if you are encrypting a text string you will want
to encrypt the null terminator too, so you should pass in strlen(toEncrypt) + 1.
→ buf The buffer to fill in with the encrypted string.
bufLen The size of the buffer. If this is too small, the function will return the size needed to
encrypt the string, and will not fill in buf at all.
Returns:
0 on success, or else returns the length of the buffer needed to encrypt this string.

uint32_t TPfHiscores::DecryptData (const char ∗ toDecrypt, void ∗ buf, uint32_t bufLen)


Decrypt a string.
This will decrypt a null terminated Base64 string into a byte stream.
Parameters:
toDecrypt A null terminated Base64 string to decrypt.
→ buf The buffer to fill in with the decrypted string.
bufLen The size of the buffer. If this is too small, the function will return the size needed to
decrypt the string, and will not fill in buf at all.
Returns:
0 on success, or else returns the length of the buffer needed to encrypt this string.

void TPfHiscores::LogScore (int32_t score, bool replaceExisting, const char ∗ gameData, const
char ∗ serverData = NULL)
Deprecated

This function has been replaced by KeepScore() (p. 328). Please use that instead.

Playground 4.0.17.1
334 Class and File Reference

Log a score for the current player.


This stores a score fore the current player into the local score table. A score must be logged before
it can be submitted. The score is logged for the player name set with SetPlayerName()
Parameters:
score the score the user is submitting
replaceExisting should this score submission replace an existing user score, or create a new
one? Typical usage is that story/career mode games replace an existing score, whereas
arcade modes allow a new score with each submission.
gameData game specific scoring information (up to 60 chars supported by server) - it is im-
portant that this be data that is additional scoring information (i.e. last level reached)
and not scoring interpretation information (i.e. awarded the "Best Ever" trophy) so that
the server can adjust awards later on. Also, this game data should not include any text
that would need to be localized. Therefore, it should just be numbers if at all possible.
serverData an optional XML formatted string that will enable certain hiscore-related features
on the hiscore server. The XML must be well-formed.

Currently available features are:


Medals: Medals are awards given to users that complete certain tasks in the game. A medal
has two parameters. The "name" parameter is the identification name of the medal. The "per"
parameter can either be "type" or "game" - "type" means that this medal is specific to the current
game mode, whereas "game" means that this medal is a global medal awarded across all game
modes.
Examples: To submit 2 medals for this score:

<medal name="medal1" per="game"/> XML


<medal name="medal2" per="type"/>

bool TPfHiscores::SubmitScore (str username, str password, bool bRemember)


Deprecated

This function has been replaced by SubmitData() (p. 332). Please use that instead.

Submit a new score to the server.


After calling this, you should poll GetServerRequestStatus() (p. 330) to check for errors or suc-
cessful submission.
Parameters:
username Name to submit the score under.
password The user’s playfirst password. If this is NULL or "", then an anonymous submis-
sion is issued.
bRemember If this is true, then the module saves the username and password for future use.
If it is false, it deletes any previously saved username and password.
Returns:
If score submission is not possible, this returns false (i.e. the player has already submitted

Navigating the Playground SDK


15.46 TPfHiscores Class Reference 335

their best score, or if they do not have any scores for this game mode, etc.).

bool TPfHiscores::SubmitMedals (const char ∗ medalsData, str username, str password, bool
bRemember)
Deprecated

This function has been replaced by SubmitData() (p. 332). Please use that instead.

Submit medal information for the current player to the server.


After calling this, you should poll GetServerRequestStatus() (p. 330) to check for errors or suc-
cessful submission
This stores the medals information for the current player into the local score table. The medals
information must be logged before it can be submitted. The medals are logged for the player
name set with SetPlayerName()
Parameters:
medalsData A well-formed XML string that specifies medal information to be stored on the
server.
username Name to submit the score under.
password The user’s playfirst password.
bRemember If this is true, then the module saves the username and password for future use.
if it is false, it deletes any previously saved username and password.
Returns:
If the medals submission is not possible, this returns false.

Medals are awards given to users that complete certain tasks in the game. A medal has two pa-
rameters. The "name" parameter is the identification name of the medal. The "per" parameter can
either be "type" or "game" - "type" means that this medal is specific to the current game mode,
whereas "game" means that this medal is a global medal awarded across all game modes.
Examples:

<medal name="dinerdash7_frag50" per="type" type="dinerdash7_counterstrike"/> XML


<medal name="dinerdash7_frag50" per="type" type="dinerdash7_fragfest"/>
<medal name="dinerdash7_frag100" per="type" type="dinerdash7_fragfest"/>
<medal name="dinerdash7_killedRonaldMcDonald" per="game"/>
<medal name="dinerdash7_killedBurgerKing" per="game"/>

Playground 4.0.17.1
336 Class and File Reference

15.47 TPlatform Class Reference


#include <pf/platform.h>

15.47.1 Detailed Description


The platform-specific functionality encapsulation class.
This class is created within the library and exists in one global instance that can be acquired any-
where in the application using the static function TPlatform::GetInstance() (p. 339).

Display Related Functions


• enum ECursorMode { kCursorModeAbsolute, kCursorModeDelta }
• void SetDisplay (uint32_t width, uint32_t height, bool fullscreen)
• void GetDisplay (uint32_t ∗pWidth, uint32_t ∗pHeight, bool ∗pbFullscreen)
• void SetCursor (TTextureRef texture, TPoint hotSpot, bool hardware=false)
• void ShowCursor (bool show)
• void SetCursorPos (const TPoint &at)
• void SetCursorMode (ECursorMode mode)
• ECursorMode GetCursorMode () const
• bool IsForeground ()
• void SetForeground ()
• bool SetFullscreen (bool bFullscreen)
• bool IsFullscreen ()
• void AdoptTextureRefreshListener (TTask ∗rn)
• bool OrphanTextureRefreshListener (TTask ∗rn)

Configuration values
Use these values in GetConfig() to get the related setting, or with SetConfig() to change the related
setting (for writable values).
See also:
TPlatform::GetConfig (p. 339)
TPlatform::SetConfig (p. 340)

• static const char ∗ kComputerId


• static const char ∗ kCheatMode
• static const char ∗ kDownloadURL
• static const char ∗ kInstallKey
• static const char ∗ kEncryptionKey
• static const char ∗ kHiscoreLocalOnly

Navigating the Playground SDK


15.47 TPlatform Class Reference 337

• static const char ∗ kHiscoreAnonymous


• static const char ∗ kBuildTag
• static const char ∗ kFirstPeek
• static const char ∗ kGameName
• static const char ∗ kPublisherName
• static const char ∗ kTextGraphicSpriteRender
• static const char ∗ kGameVersion
• static const char ∗ kPFGameHandle
• static const char ∗ kPFGameModeName
• static const char ∗ kPFGameMedalName
• static const char ∗ kVsyncWindowedMode
• static const char ∗ kUTF8Mode
• static const char ∗ kAutoMergeMask
• static const char ∗ kOverlayWindowMouseEvents
• static const char ∗ kVerboseDebug
• static const char ∗ kMonitorFrequency
• static const char ∗ kFlashMajorVersion
• static const char ∗ kSpriteAlwaysTestChildren
• static const char ∗ kAdjustAnimatedParticles
• static const char ∗ kFPUPrecision

Platform Environment and Information


• static TPlatform ∗ GetInstance ()
• static str GetConfig (str setting, str defaultSetting="")
• static bool IsEnabled (str setting)
• static void SetConfig (str setting, str value)
• class TSoundManager ∗ GetSoundManager ()
• class TWindowManager ∗ GetWindowManager ()
• TTaskList ∗ GetTaskList ()
• class TStringTable ∗ GetStringTable ()

System Commands
Commands that interact with the operating system.

• void SetWindowTitle (str title)


• void OpenBrowser (const char ∗url)
• void GetEvent (TEvent ∗pEvent)
• bool StringToClipboard (str copyString)
• str StringFromClipboard ()
• void Exit (int32_t exitValue=0)

Playground 4.0.17.1
338 Class and File Reference

Timer and user event functions


Functions that can be used to set up and cancel timers, query elapsed time, and pause the applica-
tion.

• uint32_t Timer ()
• void Sleep (uint32_t ms)
• bool OrphanTask (TTask ∗task)
• void AdoptTask (TTask ∗task)

Randomness
/∗∗ Return a random integer. Clients are encouraged to use this as opposed to the stdlib version
for maximum compatibility, and this random number generator is randomly seeded at application
startup.
Returns:
A random integer from 0 to 0xFFFFFFFF.

• uint32_t Rand ()

Public Types

• enum ExtendedMouseEvents { kMouseRightUp, kMouseRightDown, kMouseMiddleUp,


kMouseMiddleDown, kMouseScrollLeft, kMouseScrollRight, kMouseScrollUp, kMous-
eScrollDown }

15.47.2 Member Enumeration Documentation


enum TPlatform::ExtendedMouseEvents
These mouse button constants are here to allow you to respond to the use of other mouse buttons.
PlayFirst game design constraints forbid the use of any other than the left mouse button as a
"necessary" part of the user interface. In other words, any other buttons on the mouse or mouse
wheel needs to be a supplemental interface for convenience of power users.
Enumerator:
kMouseRightUp Mouse right-button-up event.
kMouseRightDown Mouse right-button-down event.
kMouseMiddleUp Mouse middle-button-up event.
kMouseMiddleDown Mouse middle-button-down event.
kMouseScrollLeft Mouse scroll-left-button event.
kMouseScrollRight Mouse scroll-right-button event.
kMouseScrollUp Mouse scroll-up-button event.
kMouseScrollDown Mouse scroll-down-button event.

Navigating the Playground SDK


15.47 TPlatform Class Reference 339

enum TPlatform::ECursorMode
These mouse button constants are here to allow you to respond to the use of other mouse buttons.
PlayFirst game design constraints forbid the use of any other than the left mouse button as a
"necessary" part of the user interface. In other words, any other buttons on the mouse or mouse
wheel needs to be a supplemental interface for convenience of power users.

15.47.3 Member Function Documentation


static TPlatform∗ TPlatform::GetInstance ()
Get the singleton TPlatform (p. 336).
Returns:
The one-and-only TPlatform (p. 336).

During normal game operation, it can be assumed that TPlatform (p. 336) always exists.

static str TPlatform::GetConfig (str setting, str defaultSetting = "")


Query for a configuration setting. Settings are collected from settings.xml, and can be overridden
by command line options.
Options are set on the command line using one command line parameter, options. Options are
concatenated using HTTP-GET semantics: Multiple options are appended using &.
For example, to set option "first" to 1 and option "second" to 2, you would use the command line:
options=first=1&second=2
This somewhat odd syntax allows us to pass in a stream of arbitrary options from HTML through
the ActiveX wrapper code.
Parameters:
setting Setting to query.
defaultSetting The value to return if the setting is not already configured.
Returns:
Value of that setting, or the value of defaultSetting if the setting is not found.
See also:
kCheatMode (p. 345)
kComputerId (p. 345)
kInstallKey (p. 346)
kBuildTag (p. 346)
kGameName (p. 346)
kGameVersion (p. 347)
kEncryptionKey (p. 346)
kHiscoreLocalOnly (p. 346)
kHiscoreAnonymous (p. 346)
kPublisherName (p. 346)

Playground 4.0.17.1
340 Class and File Reference

static bool TPlatform::IsEnabled (str setting)


Query as to whether a setting is enabled. Uses the same settings as GetConfig() (previous page).
Parameters:
setting Setting to query.
Returns:
True if setting is enabled.
See also:
GetConfig() (previous page)

static void TPlatform::SetConfig (str setting, str value)


Set a client configuration value.
Use this to set the encryption key, or to store a value to later be retrieved by GetConfig() (previous
page).
Parameters:
setting Setting to modify
value New value for setting.
See also:
GetConfig() (previous page)

class TSoundManager∗ TPlatform::GetSoundManager ()


Get the sound manager.
Returns:
The application sound manager.

class TWindowManager∗ TPlatform::GetWindowManager ()


Get the application window manager.
Returns:
The TWindowManager (p. 519) created by TPlatform (p. 336).

TTaskList∗ TPlatform::GetTaskList ()
Get the application task list.
Returns:
The TTaskList (p. 431) that holds the system’s tasks.

Navigating the Playground SDK


15.47 TPlatform Class Reference 341

class TStringTable∗ TPlatform::GetStringTable ()


Get the string table
Returns:
The TStringTable (p. 427) created by TPlatform (p. 336)

void TPlatform::SetWindowTitle (str title)


Set the window application title.
Parameters:
title Title of application.

void TPlatform::OpenBrowser (const char ∗ url)


Open a URL in a Web browser on the target system.
Parameters:
url URL to open.

void TPlatform::GetEvent (TEvent ∗ pEvent)


Get an event from the application event queue.
See also:
TWindowManager::HandleEvent() (p. 524)
Parameters:
pEvent Event to process.

bool TPlatform::StringToClipboard (str copyString)


Send a string to the system clipboard.
Parameters:
copyString String to copy.

str TPlatform::StringFromClipboard ()
Retrieve a string, if any, from the current clipboard.
Returns:
A string representation of the current copy buffer.

Playground 4.0.17.1
342 Class and File Reference

void TPlatform::Exit (int32_t exitValue = 0)


Exit the program.
This function does return, but the program will exit on its next pass through the main event loop.
Parameters:
exitValue Exit code.

void TPlatform::SetDisplay (uint32_t width, uint32_t height, bool fullscreen)


Initialize the current display mode.
Parameters:
width Width of target display
height Height of target display
fullscreen True for fullscreen.

void TPlatform::GetDisplay (uint32_t ∗ pWidth, uint32_t ∗ pHeight, bool ∗ pbFullscreen)


Get the current display parameters.
Parameters:
pWidth Width of display.
pHeight Height of display.
pbFullscreen True for fullscreen.

void TPlatform::SetCursor (TTextureRef texture, TPoint hotSpot, bool hardware = false)


Set a mouse cursor to an image. Use 100% magenta (RGB=255,0,255) for transparent color in a
software cursor. For hardware cursors, a normal image with alpha is appropriate.
Playground retains both the hardware and software cursor, and uses the one appropriate to the
current hardware and windowing state. Because of this, you should always provide both a soft-
ware and hardware cursor to Playground when you want to be sure the custom cursor will be
visible.
Parameters:
texture Texture to use. Set to TTextureRef() (p. 548) (i.e., NULL) to disable software cursor.
A software cursor texture needs to be a power-of-two in size and square. A hardware
texture must be exactly 32x32 pixels, must not be simple, and uses normal alpha trans-
parency (magenta will be magenta!).

You should always supply both a software cursor and a hardware cursor if you want a custom
cursor to be available.
Parameters:
hotSpot Point within texture that the hot spot should be (i.e., the point where the clicking
happens).
hardware True to set the hardware cursor, false to set the software cursor.

Navigating the Playground SDK


15.47 TPlatform Class Reference 343

void TPlatform::ShowCursor (bool show)


Show or hide the cursor.
Parameters:
show True to show the cursor.

void TPlatform::SetCursorPos (const TPoint & at)


Set the cursor position.
Deprecated

This API doesn’t quite work as expected on the Mac, and so will be removed from a fu-
ture version of Playground. To achieve relative cursor functionality, please use SetCursor-
Mode(TPlatform::kCursorModeDelta) instead.
Parameters:
at Position to set mouse cursor, in application window coordinates.

void TPlatform::SetCursorMode (ECursorMode mode)


Set the cursor mode.
Parameters:
mode Set the data mode for kMouseMove events.

ECursorMode TPlatform::GetCursorMode () const


Get the cursor mode.

bool TPlatform::IsForeground ()
Return true if the application is currently the foreground window.
Returns:
True if application is in the foreground.

void TPlatform::SetForeground ()
Set the game window to the foreground. On some systems, this is more of a request than an action,
but it will get the user’s attention.

bool TPlatform::SetFullscreen (bool bFullscreen)


Convenience function for toggling fullscreen.
Parameters:
bFullscreen True for full-screen.

Playground 4.0.17.1
344 Class and File Reference

Returns:
True on success.

bool TPlatform::IsFullscreen ()
True if the window is full screen.
Returns:
True on full screen.

void TPlatform::AdoptTextureRefreshListener (TTask ∗ rn)


Add a Texture Refresh Listener: On some platforms (DirectX) there are situations that cause all
textures to be destroyed. If you have a texture that was created by loading it from a file or resource,
it will be automatically rebuilt by the library. If your texture is created programmatically, however,
you will need to recreate it manually when a texture-loss event occurs.
The library internally maintains a list of Texture Refresh Listeners that all get called when system
textures need to be rebuilt. Add a TTask (p. 429) listener to the list using this function.
Note that the TTask::DoTask() (p. 430) return value is respected, so be sure to return true unless
you want your refresh listener to self-destruct.
Parameters:
rn A Texture Refresh listener to add to the internal list of functions to call when all textures
(surfaces) are lost.

bool TPlatform::OrphanTextureRefreshListener (TTask ∗ rn)


Remove a Texture Refresh Listener.
Parameters:
rn The Listener to remove.
Returns:
true if listener was removed, false if listener was not found
See also:
AddTextureRefreshListener()

uint32_t TPlatform::Timer ()
A count in milliseconds since the program has initialized,
Returns:
Time value in milliseconds.

Navigating the Playground SDK


15.47 TPlatform Class Reference 345

void TPlatform::Sleep (uint32_t ms)


Sleep the program for a number of milliseconds.
Parameters:
ms Number of milliseconds to sleep.

bool TPlatform::OrphanTask (TTask ∗ task)


Release a task from the global task list. Releases ownership of the TTask (p. 429) pointer to the
calling function.
Parameters:
task Task to release.
Returns:
true if task was removed, false if task was not found

void TPlatform::AdoptTask (TTask ∗ task)


Add a task to the global task list. Transfers ownership to the global task list, which will expect to
destroy the task when it is complete.
Parameters:
task Task to adopt.

15.47.4 Member Data Documentation


const char∗ TPlatform::kComputerId
Unique Computer Identifier
See also:
GetConfig (p. 339)

const char∗ TPlatform::kCheatMode


Cheat mode. Be sure to set your kEncryptionKey before querying this value.
See also:
GetConfig (p. 339)
kEncryptionKey (next page)

const char∗ TPlatform::kDownloadURL


In a Web game, this is the URL that the browser should be set to when you click the "Download"
button in the game.

Playground 4.0.17.1
346 Class and File Reference

const char∗ TPlatform::kInstallKey


A key unique to the install of this application.
Used to detect which portal the game was installed from.

const char∗ TPlatform::kEncryptionKey


The application’s encryption key.
The application MUST set this key to a key assigned by PlayFirst to function correctly with pref-
erences, high scores, and the cheat enabler.
See also:
kCheatMode (previous page)

const char∗ TPlatform::kHiscoreLocalOnly


Query as to whether hiscore mode is local-only.

const char∗ TPlatform::kHiscoreAnonymous


Query as to whether hiscore mode is anonymous only.

const char∗ TPlatform::kBuildTag


Query how this particular build has been tagged. Build tagging may be used to enable/disable
certain feature sets.

const char∗ TPlatform::kFirstPeek


Query whether this build is a "first peek" build: A limited-functionality public beta version.

const char∗ TPlatform::kGameName


What is the name of this game? Defined to be the string "gamename".
Set this in your "Main" routine to set the name your game should report to the high score server. If
you want to change the name your game gets in the data folder, you must call this function from
PlaygroundInit() (p. 544).
See also:
PlaygroundInit (p. 544)

const char∗ TPlatform::kPublisherName


What is the name of the publisher of this game?
In order for this setting to have an effect on the user folders for the application, it must be set in
the special initialization routine PlaygroundInit() (p. 544).

Navigating the Playground SDK


15.47 TPlatform Class Reference 347

See also:
PlaygroundInit (p. 544)

const char∗ TPlatform::kTextGraphicSpriteRender


Call TPlatform::SetConfig( TPlatform::kTextGraphicSpriteRender, 1 ) to default all new TText-
Graphic (p. 447) instances to "sprite rendering" mode.
See also:
TTextGraphic::SetSpriteRender (p. 449)

const char∗ TPlatform::kGameVersion


What version/build is this EXE? Defined to be the string "version". Call TPlatform::GetConfig
(p. 339)( TPlatform::kGameVersion (this page)) to query the version number of your game. Do
not read version.h directly.

const char∗ TPlatform::kPFGameHandle


This value is the game handle that the game uses to communicate with any PlayFirst services,
such as the hiscore system. This value should be set with the PFGAMEHANDLE value in key.h
on application startup. See the Playground Skeleton sample for code that does this.

const char∗ TPlatform::kPFGameModeName


This value is the prefix to the game mode names used to communicate with the PlayFirst His-
core system. To get the game mode name, you need to add on the number for the game mode
you want, starting with index 1. So for example, to get the first game mode, you could ask for
str(kPFGameModeName) + "1". This value should be set with the PFGAMEMODENAMES value
in key.h on application startup. See the Playground Skeleton sample for code that does this.

const char∗ TPlatform::kPFGameMedalName


This value is the prefix to the medal names used to communicate with the PlayFirst Hiscore sys-
tem. To get the medal name, you need to add on the number for the game mode you want, starting
with index 1. So for example, to get the first medal, you could ask for str(kPFGameMedalName)
+ "1". This value should be set with the PFGAMEMEDALNAMES value in key.h on application
startup. See the Playground Skeleton sample for code that does this.

const char∗ TPlatform::kVsyncWindowedMode


Instruct Playground to wait for the vertical blanking period to start prior to drawing to the screen
in windowed mode. Has no effect on full-screen mode, which always flips its buffer at the vertical
refresh.
Can minimize "tearing" when enabled. Does cause the game to pause to wait for the screen vertical
refresh to happen, which can seriously slow down the frame rate of your game by causing it to

Playground 4.0.17.1
348 Class and File Reference

skip frames when the time to compute core logic and render a frame takes slightly longer than one
video frame to calculate.
For instance, if the game takes 1/60 of a second (16.66ms) to perform all calculations and finish
rendering, but the monitor is set to a 70Hz update, setting this flag will cause the screen to update
at only 35FPS (half of 70FPS), since by the time one frame is complete, it will have already missed
the next video synchronization. As a result, the game will need to wait for the following frame
vertical refresh to draw. If you can only draw once every two frames at 70Hz, you’ll get a 35Hz
(35FPS) update.
Set the value to "1" to enable, or "0" to disable this feature. Defaults to being disabled.

const char∗ TPlatform::kUTF8Mode


Enable UTF-8 support mode.

• Enables TWindow::OnUTF8Char() (p. 514) dispatch.

• When enabled, OnChar() will only be called for low-ASCII characters, and only if no
OnUTF8Char() has already handled the character.

Warning:

This mode has not yet been approved for use in PlayFirst-developed games.
Must be enabled in PlaygroundInit() (p. 544) section.

const char∗ TPlatform::kAutoMergeMask


Automatically merge any .mask.png files when loading a .jpg file. When you call:
TTexture::Get (p. 465)("foo.jpg");
...then if kAutoMergeMask is enabled, it will look for foo.mask.png and, if found, automatically
perform a TTexture::GetMerged (p. 465)("foo.jpg", "foo.mask.png").

const char∗ TPlatform::kOverlayWindowMouseEvents


Enable mouse event routing to overlay windows.

const char∗ TPlatform::kVerboseDebug


Enable verbose debug info from Playground.

const char∗ TPlatform::kMonitorFrequency


Query the current monitor frequency. Returns "0" if the monitor frequency is not available. Can
change when the computer switches between full screen and windowed mode.

Navigating the Playground SDK


15.47 TPlatform Class Reference 349

const char∗ TPlatform::kFlashMajorVersion


Raise the minimum major Flash version that your game requires.
The value should be a version number in quotes. For instance, to require the Flash 8 control to be
installed on a system, set the value to "8".

const char∗ TPlatform::kSpriteAlwaysTestChildren


Always do HitTest() on sprite children, even if the parent TSprite (p. 419) doesn’t have a texture.

const char∗ TPlatform::kAdjustAnimatedParticles


When using animated textures for particle systems, automatically adjust the position of each par-
ticle so that the animation frames play in the correct positions.

const char∗ TPlatform::kFPUPrecision


Enable this in PlaygroundInit() (p. 544) to enable high-precision floating point.

Playground 4.0.17.1
350 Class and File Reference

15.48 TPoint Class Reference


#include <pf/point.h>

15.48.1 Detailed Description


The TPoint (this page) class is a 2d integer point representation.

Public Member Functions

• TPoint ()
• TPoint (int32_t x, int32_t y)
• bool operator== (const TPoint &point) const
• bool operator!= (const TPoint &point) const
• TPoint & operator+= (const TPoint &point)
• TPoint operator+ (const TPoint &point) const
• TPoint & operator-= (const TPoint &point)
• TPoint operator- (const TPoint &point) const
• TPoint operator- ()

Public Attributes

• int32_t x
• int32_t y

15.48.2 Constructor & Destructor Documentation


TPoint::TPoint ()
Default constructor. Zeros all members.

TPoint::TPoint (int32_t x, int32_t y)


Initializing constructor.

15.48.3 Member Function Documentation


bool TPoint::operator== (const TPoint & point) const
Equality.
References x, and y.

Navigating the Playground SDK


15.48 TPoint Class Reference 351

bool TPoint::operator!= (const TPoint & point) const


Inequality.

TPoint& TPoint::operator+= (const TPoint & point)


Add a point to this point.
References x, and y.

TPoint TPoint::operator+ (const TPoint & point) const


Memberwise addition.

TPoint& TPoint::operator-= (const TPoint & point)


Subtract a point from this point.
References x, and y.

TPoint TPoint::operator- (const TPoint & point) const


Memberwise subtraction.

TPoint TPoint::operator- ()
Negation.

15.48.4 Member Data Documentation


int32_t TPoint::x
Horizontal coordinate.
Referenced by TRect::Contains(), operator+=(), operator-=(), and operator==().

int32_t TPoint::y
Vertical coordinate.
Referenced by TRect::Contains(), operator+=(), operator-=(), and operator==().

Playground 4.0.17.1
352 Class and File Reference

15.49 TPrefs Class Reference


#include <pf/prefs.h>

15.49.1 Detailed Description


The TPrefs (this page) class is designed to help with the saving of preferences for a game. Prefer-
ences can be stored at either a global level or a user level.
See note about unique installs in the TPrefs() (this page) constructor comments.

Public Member Functions


• TPrefs (bool saveData=true)
• ∼TPrefs ()
• uint32_t GetNumUsers ()
• void DeleteUser (uint32_t userNum)
• int32_t GetInt (str prefName, int32_t defaultValue, int32_t userIndex=kGlobalIndex)
• void SetInt (str prefName, int32_t value, int32_t userIndex=kGlobalIndex, bool save=true)
• str GetStr (str prefName, str defaultValue, int32_t userIndex=kGlobalIndex)
• void SetStr (str prefName, str value, int32_t userIndex=kGlobalIndex, bool save=true)
• int32_t GetBinary (str prefName, void ∗buffer, uint32_t bufferLen, int32_t
userIndex=kGlobalIndex)
• void SetBinary (str prefName, const void ∗data, uint32_t dataLength, int32_t
userIndex=kGlobalIndex, bool save=true)
• void SavePrefs ()
• str GetUserStr (int32_t userIndex)
• void SetUserStr (int32_t userIndex, str data)

Static Public Attributes


• static const int32_t kGlobalIndex

15.49.2 Constructor & Destructor Documentation


TPrefs::TPrefs (bool saveData = true)
Constructor.
Prior to calling the constructor, you need to set the application encryption key. See TPlat-
form::SetConfig() (p. 340).
Warning:

Be sure to save the game periodically during play. Any time the user has, e.g., gained a new
level, or any other significant event the game should remember, you should tell it to write a

Navigating the Playground SDK


15.49 TPrefs Class Reference 353

save file. The reason is that, when your game is wrapped in DRM, when the DRM expires it
will often directly send a kQuit message, which terminates the (default) game loop.

If there are performance reasons you don’t want to write the file frequently, you can use the
option in SetInt() (next page) and SetStr() (p. 355) to NOT write the file immediately; as long
as the setting has been given to TPrefs (opposite), it will be written on game exit.
Selecting a Specific Configuration

In order to prevent games from being downloaded multiple times and being able to use the same
saved games, a TPrefs (opposite) object attempts to distinguish between unique installs of the
game. It does this by looking at the directory the game is running from.
Therefore, for debugging purposes, if you want your game to always be treated as the same install,
you can hand create an install.txt file in the assets folder. This file can do two things:
1) If the file is empty, TPrefs (opposite) will load/save preferences as if it was running from the
most recently created preferences location (or create a new location if one doesn’t exist).
2) If the file is not empty, it will treat the contents of this file as the install path, and read/save
games as if it was that install. (example: putting C:/game/mygame in the install.txt file will make
the TPrefs (opposite) object pretend the game is running from c:/game/mygame
Parameters:
saveData Whether or not data should be saved between sessions, default is true. For exam-
ple, in a web game you might not want scores to persist between sessions, in which case
saveData should be false.

TPrefs::∼TPrefs ()
Destructor

15.49.3 Member Function Documentation

uint32_t TPrefs::GetNumUsers ()
Get the number of users. Users must be numbered sequentially, and there may not be more than
1023 users.
Returns:
The number of currently created users in the preferences.

void TPrefs::DeleteUser (uint32_t userNum)


Deletes the current user at the specified slot, and slides all users above that slot down. If user 2 is
deleted, then user 3 becomes user 2, 4 becomes 3, etc.

Playground 4.0.17.1
354 Class and File Reference

Parameters:
userNum Which user to delete

int32_t TPrefs::GetInt (str prefName, int32_t defaultValue, int32_t userIndex = kGlobalIndex)

Gets an int from the preferences.


Parameters:
prefName Name of preference to get.
defaultValue If this preference has not been set, what value should be returned.
userIndex Which user to get from, or if this is kGlobalIndex then get from the global pref-
erences. Users must be numbered sequentially, and there may not be more than 1023
users.
Returns:
Returns the stored int if it exists, or else defaultValue if it does not exist.

void TPrefs::SetInt (str prefName, int32_t value, int32_t userIndex = kGlobalIndex, bool save
= true)

Sets an int in the preferences.


Parameters:
prefName Name of preference to set.
value Value to set preference to.
userIndex Which user to set, or if this is kGlobalIndex then set a global preference. Users must
be numbered sequentially, and there may not be more than 1023 users.
save If this is true, commits preferences to disk. if false, preferences are changed in memory
only, until a different preference is set with save set to true, or until SavePrefs() (p. 356)
is called.

str TPrefs::GetStr (str prefName, str defaultValue, int32_t userIndex = kGlobalIndex)

Gets a str (p. 161) from the preferences.


Parameters:
prefName Name of preference to Get.
defaultValue If this preference has not been set, what value should be returned.
userIndex Which user to get from, or if this is kGlobalIndex then get from the global pref-
erences. Users must be numbered sequentially, and there may not be more than 1023
users.
Returns:
Returns the stored str (p. 161) if it exists, or else defaultValue if it does not exist.

Navigating the Playground SDK


15.49 TPrefs Class Reference 355

void TPrefs::SetStr (str prefName, str value, int32_t userIndex = kGlobalIndex, bool save =
true)
Sets a str (p. 161) in the preferences.
String length is limited to 4Mb-16 bytes.
Parameters:
prefName Name of preference to set.
value Value to set preference to.
userIndex Which user to set, or if this is kGlobalIndex then set a global preference. Users must
be numbered sequentially, and there may not be more than 1023 users.
save If this is true, commits preferences to disk. if false, preferences are changed in memory
only, until a different preference is set with save set to true, or until SavePrefs() (next
page) is called.

int32_t TPrefs::GetBinary (str prefName, void ∗ buffer, uint32_t bufferLen, int32_t userIndex =
kGlobalIndex)
Gets a binary block from the preferences.
Parameters:
prefName Name of preference to get.
buffer Address of location to store data in.
bufferLen Size of buffer in bytes.
userIndex Which user to get from, or if this is kGlobalIndex then get from the global pref-
erences. Users must be numbered sequentially, and there may not be more than 1023
users.
Returns:
If the preference does not exist, -1 is returned. If buffer is successfully filled in with the pref-
erence, 0 is returned. If the preference exists and buffer is NULL or bufferLen is too small to
store the data, then the size that the buffer needs to be is returned.

void TPrefs::SetBinary (str prefName, const void ∗ data, uint32_t dataLength, int32_t
userIndex = kGlobalIndex, bool save = true)
Sets a block of binary data in the preferences.
Binary data size is limited to 4Mb-16 bytes.
Parameters:
prefName Name of preference to set.
data Address of data to set in preferences.
dataLength Size of data in bytes.
userIndex Which user to set, or if this is kGlobalIndex then set a global preference. Users must
be numbered sequentially, and there may not be more than 1023 users.
save If this is true, commits preferences to disk. If false, preferences are changed in memory
only, until a different preference is set with save set to true, or until SavePrefs() (next
page) is called.

Playground 4.0.17.1
356 Class and File Reference

void TPrefs::SavePrefs ()
Commit preferences to permanent storage.

str TPrefs::GetUserStr (int32_t userIndex)


Gets all the user data as a str (p. 161).
Parameters:
userIndex Which user to get data from.
Returns:
A str (p. 161) containing all the user’s data.

void TPrefs::SetUserStr (int32_t userIndex, str data)


Sets a user data from a passed in str (p. 161). In order to maintain proper functionality this should
only be called with a str (p. 161) return from GetUserStr.
Parameters:
userIndex Which user to set data.
data String to set.

15.49.4 Member Data Documentation


const int32_t TPrefs::kGlobalIndex
An index to pass in as a userIndex parameter to any get/set function to get/set a global preference.

Navigating the Playground SDK


15.50 TPrefsDB Class Reference 357

15.50 TPrefsDB Class Reference


#include <pf/prefsdb.h>

15.50.1 Detailed Description


The TPrefsDB (this page) class is designed to help with the saving of preferences for a game.
Preferences can be stored at either a global level or a user level.
See note about unique installs in the TPrefsDB() (this page) constructor comments.
TPrefsDB (this page) differs from TPrefs (p. 352) in the method of saving the data; it uses a
database format that can save part of the file instead of rewriting the entire file each time, so if
your game has a large data save requirement, it will likely be much faster to save if you switch
from TPrefs (p. 352) to TPrefsDB (this page).

Public Member Functions

• TPrefsDB (bool saveData=true)


• ∼TPrefsDB ()
• uint32_t GetNumUsers ()
• void DeleteUser (uint32_t userNum)
• int32_t GetInt (str prefName, int32_t defaultValue, int32_t userIndex=kGlobalIndex)
• void SetInt (str prefName, int32_t value, int32_t userIndex=kGlobalIndex, bool save=true)
• str GetStr (str prefName, str defaultValue, int32_t userIndex=kGlobalIndex)
• void SetStr (str prefName, str value, int32_t userIndex=kGlobalIndex, bool save=true)
• int32_t GetBinary (str prefName, void ∗buffer, uint32_t bufferLen, int32_t
userIndex=kGlobalIndex)
• void SetBinary (str prefName, const void ∗data, uint32_t dataLength, int32_t
userIndex=kGlobalIndex, bool save=true)
• void SavePrefs ()

Static Public Attributes

• static const int32_t kGlobalIndex

15.50.2 Constructor & Destructor Documentation


TPrefsDB::TPrefsDB (bool saveData = true)
Constructor.
Prior to calling the constructor, you need to set the application encryption key. See TPlat-
form::SetConfig() (p. 340).

Playground 4.0.17.1
358 Class and File Reference

Parameters:
saveData Whether or not data should be saved between sessions, default is true. For exam-
ple, in a web game you might not want scores to persist between sessions, in which case
saveData should be false.

TPrefsDB::∼TPrefsDB ()
Destructor

15.50.3 Member Function Documentation


uint32_t TPrefsDB::GetNumUsers ()
Get the number of users. Users must be numbered sequentially, and there may not be more than
1023 users.
Returns:
The number of currently created users in the preferences.

void TPrefsDB::DeleteUser (uint32_t userNum)


Deletes the current user at the specified slot, and slides all users above that slot down. If user 2 is
deleted, then user 3 becomes user 2, 4 becomes 3, etc.
Parameters:
userNum Which user to delete

int32_t TPrefsDB::GetInt (str prefName, int32_t defaultValue, int32_t userIndex =


kGlobalIndex)
Gets an int from the preferences.
Parameters:
prefName Name of preference to get.
defaultValue If this preference has not been set, what value should be returned.
userIndex Which user to get from, or if this is kGlobalIndex then get from the global pref-
erences. Users must be numbered sequentially, and there may not be more than 1023
users.
Returns:
Returns the stored int if it exists, or else defaultValue if it does not exist.

void TPrefsDB::SetInt (str prefName, int32_t value, int32_t userIndex = kGlobalIndex, bool
save = true)
Sets an int in the preferences.

Navigating the Playground SDK


15.50 TPrefsDB Class Reference 359

Parameters:
prefName Name of preference to set.
value Value to set preference to.
userIndex Which user to set, or if this is kGlobalIndex then set a global preference. Users must
be numbered sequentially, and there may not be more than 1023 users.
save If this is true, commits preferences to disk. if false, preferences are changed in memory
only, until a different preference is set with save set to true, or until SavePrefsdb() is
called.

str TPrefsDB::GetStr (str prefName, str defaultValue, int32_t userIndex = kGlobalIndex)


Gets a str (p. 161) from the preferences.
Parameters:
prefName Name of preference to Get.
defaultValue If this preference has not been set, what value should be returned.
userIndex Which user to get from, or if this is kGlobalIndex then get from the global pref-
erences. Users must be numbered sequentially, and there may not be more than 1023
users.
Returns:
Returns the stored str (p. 161) if it exists, or else defaultValue if it does not exist.

void TPrefsDB::SetStr (str prefName, str value, int32_t userIndex = kGlobalIndex, bool save =
true)
Sets a str (p. 161) in the preferences.
String length is limited to 4Mb-16 bytes.
Parameters:
prefName Name of preference to set.
value Value to set preference to.
userIndex Which user to set, or if this is kGlobalIndex then set a global preference. Users must
be numbered sequentially, and there may not be more than 1023 users.
save If this is true, commits preferences to disk. if false, preferences are changed in memory
only, until a different preference is set with save set to true, or until SavePrefsdb() is
called.

int32_t TPrefsDB::GetBinary (str prefName, void ∗ buffer, uint32_t bufferLen, int32_t userIndex
= kGlobalIndex)
Gets a binary block from the preferences.
Parameters:
prefName Name of preference to get.
buffer Address of location to store data in.
bufferLen Size of buffer in bytes.

Playground 4.0.17.1
360 Class and File Reference

userIndex Which user to get from, or if this is kGlobalIndex then get from the global pref-
erences. Users must be numbered sequentially, and there may not be more than 1023
users.
Returns:
If the preference does not exist, -1 is returned. If buffer is successfully filled in with the pref-
erence, 0 is returned. If the preference exists and buffer is NULL or bufferLen is too small to
store the data, then the size that the buffer needs to be is returned.

void TPrefsDB::SetBinary (str prefName, const void ∗ data, uint32_t dataLength, int32_t
userIndex = kGlobalIndex, bool save = true)
Sets a block of binary data in the preferences.
Binary data size is limited to 4Mb-16 bytes.
Parameters:
prefName Name of preference to set.
data Address of data to set in preferences.
dataLength Size of data in bytes.
userIndex Which user to set, or if this is kGlobalIndex then set a global preference. Users must
be numbered sequentially, and there may not be more than 1023 users.
save If this is true, commits preferences to disk. If false, preferences are changed in memory
only, until a different preference is set with save set to true, or until SavePrefsdb() is
called.

void TPrefsDB::SavePrefs ()
Commit preferences to permanent storage.

15.50.4 Member Data Documentation


const int32_t TPrefsDB::kGlobalIndex
An index to pass in as a userIndex parameter to any get/set function to get/set a global preference.

Navigating the Playground SDK


15.51 TRandom Class Reference 361

15.51 TRandom Class Reference


#include <pf/random.h>

15.51.1 Detailed Description


A deterministic random number generator.
Based on the Mersenne Twister algorithm, it has a period of 219937 − 1 iterations, it’s as fast as or
faster than rand(), and it’s equally distributed in 623 dimensions.

Public Member Functions


• TRandom ()
• void Seed (uint32_t s)
• void SeedArray (unsigned long init_key[ ], uint32_t key_length)
• uint32_t SaveState (void ∗buffer, uint32_t bufferLength)
• void RestoreState (void ∗buffer)
• unsigned long Rand32 ()
• TReal RandFloat ()
• double RandDouble ()
• int32_t RandRange (int32_t bottom, int32_t top)

15.51.2 Constructor & Destructor Documentation


TRandom::TRandom ()
Default Constructor.

15.51.3 Member Function Documentation


void TRandom::Seed (uint32_t s)
Seed with a 32-bit number.
Parameters:
s A random 32-bit seed. Once seeded with a particular number, the sequence will always be
the same.

void TRandom::SeedArray (unsigned long init_key[ ], uint32_t key_length)


Seed with array. Use this if 4 billion possible sequences are not enough.
Parameters:
init_key Array of long integers.
key_length Number of long integers in the array.

Playground 4.0.17.1
362 Class and File Reference

uint32_t TRandom::SaveState (void ∗ buffer, uint32_t bufferLength)


Get the current random number generator state, which you can then use to restore to a known
state using RestoreState.
Parameters:
buffer - buffer to store state in
bufferLength - number of bytes in buffer
Returns:
0 if successful, otherwise returns the length that buffer needs to be for success;

void TRandom::RestoreState (void ∗ buffer)


Restore random number generator state from SaveState
Parameters:
buffer Buffer to read state from.

unsigned long TRandom::Rand32 ()


Generates a random unsigned long.
Returns:
A random 32-bit integer that is equally random across all 32 bits.

TReal TRandom::RandFloat ()
Generates a random number on [0,1)-real-interval
Returns:
A number between zero and one, never equalling 1.0

double TRandom::RandDouble ()
Generates a random number on [0,1)-real-interval, that is random out to double-precision granu-
larity. Since a double has (on the Wintel reference platform) more bits of precision than an int/long,
it takes two calls from Rand32 and combines them into a double precision random number.
Returns:
A number between zero and one, never equalling 1.0

int32_t TRandom::RandRange (int32_t bottom, int32_t top)


Generates a random integer between the two parameters, inclusive. Will generate all options
equally, including bottom and top.

Navigating the Playground SDK


15.51 TRandom Class Reference 363

Parameters:
bottom Lowest number that will be returned.
top Highest number that will be returned.
Returns:
A random integer.

Playground 4.0.17.1
364 Class and File Reference

15.52 TRect Class Reference


#include <pf/rect.h>
Inheritance diagram for TRect:

TRect

TURect

15.52.1 Detailed Description


A rectangle.
Like the Windows RECT class, the right and bottom (X2/Y2) coordinates are one past the edge of
the rectangle.

Public Member Functions


• TRect ()
• TRect (int32_t X1, int32_t Y1, int32_t X2, int32_t Y2)
• TRect (const TPoint &topLeft, const TPoint &bottomRight)
• int32_t GetWidth () const
• int32_t GetHeight () const
• bool operator== (const TRect &r) const
• bool operator!= (const TRect &r) const
• TRect & operator+= (const TPoint &p)
• TRect & operator-= (const TPoint &p)
• bool Contains (const TRect &r) const
• bool Contains (const TPoint &p) const
• bool IsInside (const TPoint &p) const
• bool Overlaps (const TRect &rect) const
• void Union (const TRect &rect1, const TRect &rect2)
• void Intersect (const TRect &rect1, const TRect &rect2)
• TPoint & GetTopLeft ()
• const TPoint & GetTopLeft () const
• TPoint & GetBottomRight ()
• const TPoint & GetBottomRight () const

Static Public Member Functions


• static TRect FromXYWH (int32_t x, int32_t y, int32_t w, int32_t h)

Navigating the Playground SDK


15.52 TRect Class Reference 365

Public Attributes
• int32_t x1
• int32_t y1
• int32_t x2
• int32_t y2

15.52.2 Constructor & Destructor Documentation


TRect::TRect ()
Default constructor. Zeros all members.

TRect::TRect (int32_t X1, int32_t Y1, int32_t X2, int32_t Y2)


Initializing constructor.

TRect::TRect (const TPoint & topLeft, const TPoint & bottomRight)


Construct a TRect (opposite) from two points.
Parameters:
topLeft Upper left corner of the TRect (opposite).
bottomRight Lower right corner of the TRect (opposite).

15.52.3 Member Function Documentation


static TRect TRect::FromXYWH (int32_t x, int32_t y, int32_t w, int32_t h)
Build a TRect (opposite) from the upper left corner and the desired width and height.
Parameters:
x X coordinate of the upper left corner.
y Y coordinate of the upper left corner.
w Width
h Height
Returns:
A new TRect (opposite) calculated from X,Y,W,H

int32_t TRect::GetWidth () const


Get the width of the rectangle.
Returns:
Exclusive width of the rectangle. (x2-x1)

Playground 4.0.17.1
366 Class and File Reference

int32_t TRect::GetHeight () const


Get the height of the rectangle.
Returns:
Exclusive height of the rectangle. (y2-y1)

Referenced by TTextGraphic::Draw().

bool TRect::operator== (const TRect & r) const


Equality.
References x1, x2, y1, and y2.

bool TRect::operator!= (const TRect & r) const


Inequality.

TRect& TRect::operator+= (const TPoint & p)


Move a rect by a point.
Parameters:
p Point to offset rect by.
Returns:
A reference to this.

TRect& TRect::operator-= (const TPoint & p)


Move a rect by a point.
Parameters:
p Point to offset rect by.
Returns:
A reference to this.

bool TRect::Contains (const TRect & r) const


Test to see whether a rectangle is inside this rectangle.
Parameters:
r TRect (p. 364) to test.
Returns:
True if r is inside this.

Navigating the Playground SDK


15.52 TRect Class Reference 367

References x1, x2, y1, and y2.

bool TRect::Contains (const TPoint & p) const


Test to see whether a point is inside this rectangle.
Parameters:
p Point to test.
Returns:
True if inside. If p.x==x2 or p.y==y2, the test fails.

References TPoint::x, and TPoint::y.

bool TRect::IsInside (const TPoint & p) const


Test to see whether a point is inside this rectangle.
Deprecated

This function is going to be deleted in favor of the more clearly named TRect::Contains()
(opposite).
Parameters:
p Point to test.
Returns:
True if inside. If p.x==x2 or p.y==y2, the test fails.

bool TRect::Overlaps (const TRect & rect) const


Test to see if another rectangle overlaps this rectangle.
Parameters:
rect Rectangle to test.
Returns:
True on overlap.

References x1, x2, y1, and y2.

void TRect::Union (const TRect & rect1, const TRect & rect2)
Make this rectangle the union of the two parameter rectangles. Can pass this rectangle as either
parameter.
Parameters:
rect1 First

Playground 4.0.17.1
368 Class and File Reference

rect2 Second

void TRect::Intersect (const TRect & rect1, const TRect & rect2)
Make this rectangle the intersection of the two parameter rectangles. Can pass this rectangle as
either parameter.
Warning:

Assumes the two rectangles overlap. Resulting value is undefined if the original rectangles
do not overlap.
Parameters:
rect1 First
rect2 Second

TPoint& TRect::GetTopLeft ()
Get a TPoint (p. 350) that represents the upper left corner of the rectangle.
Returns:
Corner point

Referenced by TWindow::ClientToParent(), TWindow::ClientToScreen(), TWin-


dow::ParentToClient(), and TWindow::ScreenToClient().

const TPoint& TRect::GetTopLeft () const


Get a TPoint (p. 350) that represents the upper left corner of the rectangle.
Returns:
Corner point

TPoint& TRect::GetBottomRight ()
Get a TPoint (p. 350) that represents the lower right corner of the rectangle.
Returns:
Corner point

Referenced by TWindow::ClientToParent(), TWindow::ClientToScreen(), TWin-


dow::ParentToClient(), and TWindow::ScreenToClient().

const TPoint& TRect::GetBottomRight () const


Get a TPoint (p. 350) that represents the lower right corner of the rectangle.
Returns:
Corner point

Navigating the Playground SDK


15.52 TRect Class Reference 369

15.52.4 Member Data Documentation


int32_t TRect::x1
Upper left corner x coordinate.
Referenced by Contains(), TTextGraphic::Draw(), operator==(), and Overlaps().

int32_t TRect::y1
Upper left corner y coordinate.
Referenced by Contains(), TTextGraphic::Draw(), operator==(), and Overlaps().

int32_t TRect::x2
Lower right corner x coordinate.
Referenced by Contains(), operator==(), and Overlaps().

int32_t TRect::y2
Lower right corner y coordinate.
Referenced by Contains(), operator==(), and Overlaps().

Playground 4.0.17.1
370 Class and File Reference

15.53 TRenderer Class Reference


#include <pf/renderer.h>

15.53.1 Detailed Description


The interface to the rendering subsystem. Available as a singleton while the game is running using
TRenderer::GetInstance() (p. 374).

Raw Primitive Drawing.


Routines for drawing groups of lines or triangles, given either 2d or 3d vertex data. Must be called
in a window Draw() function, or between BeginRenderTarget/EndRenderTarget.
Respects the currently active 2d or 3d rendering environment. Functions are indifferent to Be-
gin2d/Begin3d/End2d/End3d.

• enum EDrawType { kDrawPoints, kDrawLines, kDrawLineStrip, kDrawTriangles,


kDrawTriStrip, kDrawTriFan }
• static const int kMaxIndices
• void DrawVertices (EDrawType type, const TVertexSet &vertices)
• void DrawIndexedVertices (EDrawType type, const TVertexSet &vertices, uint16_t
∗indices, uint32_t indexCount)

2d/3d Agnostic Code


These functions allow you to modify the 2d or 3d rendering environment. Some of these states are
cleared/reset by calling Begin2d or Begin3d, so don’t expect any state to be preserved across those
calls.

• enum EShadeMode { kShadeFlat, kShadeGouraud }


• enum EBlendMode { kBlendNormal, kBlendOpaque, kBlendAdditiveAlpha, kBlendSub-
tractive, kBlendMultiplicative, kBlendINVALID }
• enum EFilteringMode { kFilterPoint, kFilterLinear }
• enum ETextureMapMode { kMapClamp, kMapWrap, kMapMirror }
• void SetShadeMode (EShadeMode shadeMode)
• bool RenderTargetIsScreen ()
• void SetTexture (TTextureRef pTexture=TTextureRef())
• TTextureRef GetTexture ()
• void SetBlendMode (EBlendMode blendMode)
• void SetFilteringMode (EFilteringMode filteringMode)
• void SetTextureMapMode (ETextureMapMode umap, ETextureMapMode vmap)
• void SetZBufferWrite (bool writeToZbuffer)
• void SetZBufferTest (bool testZbuffer)

Navigating the Playground SDK


15.53 TRenderer Class Reference 371

• void SetColorWrite (bool colorWrite)


• bool GetColorWrite ()
• void ClearZBuffer ()
• bool GetZBufferWrite ()
• bool GetZBufferTest ()

Scene Management Functions


Enable drawing to a render target or the backbuffer, or set up a 2d or 3d rendering context.
Drawing to the backbuffer is usually handled by the system; by the time a TWindow::Draw()
(p. 503) function is called, you are already in a rendering state.

• enum ERenderTargetMode { kFullRenderRGB1, kFullRenderRGBX, kMergeRender-


RGB1, kMergeRenderRGBX, kMergeRenderXXXA }
• bool BeginRenderTarget (TTextureRef texture, ERenderTargetMode mode)
• void EndRenderTarget ()
• bool BeginDraw (bool needRefresh)
• void EndDraw (bool flip=true)
• bool Begin2d ()
• void End2d ()
• bool Begin3d ()
• void End3d ()
• bool InDraw () const

3d-Related functions
• enum ECullMode { kCullNone, kCullCW, kCullCCW }
• void SetWorldMatrix (TMat4 ∗pMatrix)
• void SetViewMatrix (TMat4 ∗pMatrix)
• void SetProjectionMatrix (TMat4 ∗pMatrix)
• void SetView (const TVec3 &eye, const TVec3 &at, const TVec3 &up)
• void SetPerspectiveProjection (TReal nearPlane, TReal farPlane, TReal fov=PI/4.0f, TReal
aspect=0)
• void SetOrthogonalProjection (TReal nearPlane, TReal farPlane)
• void GetWorldMatrix (TMat4 ∗m)
• void GetViewMatrix (TMat4 ∗m)
• void GetProjectionMatrix (TMat4 ∗m)
• void SetAmbientColor (const TColor &color)
• void SetCullMode (ECullMode cullMode)
• void SetMaterial (TMaterial ∗mat)
• void SetLight (uint32_t index, TLight ∗light)
• bool ToggleHUD ()

Playground 4.0.17.1
372 Class and File Reference

• bool In2d () const


• bool In3d () const
• void SetOption (str option, str value)
• str GetOption (str option)

Information
• str GetSystemData ()
• bool GetTextureSquareFlag ()

2d-Related Functions
• void FillRect (const TURect &rect, const TColor &color, TTextureRef dst=TTextureRef())
• bool IsCapturePending ()
• void SetCaptureTexture (TTextureRef texture)
• TTextureRef GetCaptureTexture ()

Public Member Functions


• ∼TRenderer ()
• void SetViewport (const TRect &viewport)
• void GetViewport (TRect ∗viewport)
• void SetClippingRectangle (const TURect &clip)
• TRect GetClippingRectangle ()
• void PushClippingRectangle (const TURect &clip)
• void PopClippingRectangle ()
• void PushViewport (const TRect &viewport)
• void PopViewport ()

Static Public Member Functions


• static TRenderer ∗ GetInstance ()

15.53.2 Member Enumeration Documentation


enum TRenderer::EDrawType
Type for DrawVertices.
Enumerator:
kDrawPoints DrawVertices renders the vertices as a collection of isolated points.
kDrawLines DrawVertices renders the vertices as a set of isolated line segments.
kDrawLineStrip DrawVertices renders the vertices as a line strip.

Navigating the Playground SDK


15.53 TRenderer Class Reference 373

kDrawTriangles DrawVertices renders each group of 3 vertices as a triangle.


kDrawTriStrip DrawVertices renders the vertices as a triangle strip.
kDrawTriFan DrawVertices renders the vertices as a triangle fan.

enum TRenderer::EShadeMode
Shading modes.
See also:
TRenderer::SetShadeMode (p. 376)
Enumerator:
kShadeFlat Flat shading with no shading across a polygon.
kShadeGouraud Gouraud shading with smooth shading across a polygon.

enum TRenderer::EBlendMode
Blending modes for SetBlendMode() (p. 377)
Enumerator:
kBlendNormal Normal alpha drawing.
kBlendOpaque Draw with no alpha. This mode requires your texture to be square and each
side be a power of two in order to work consistently.
kBlendAdditiveAlpha Additive drawing, respecting source alpha. Useful for "glowing" ef-
fects.
kBlendSubtractive Subtractive drawing; useful for shadows or special effects.
kBlendMultiplicative Multiplicative drawing; can also be used for shadows or special ef-
fects.
kBlendINVALID Invalid blend mode.

enum TRenderer::EFilteringMode
Filtering modes.
See also:
SetFilteringMode (p. 377)
Enumerator:
kFilterPoint Point-filtering: Select the nearest pixel.
kFilterLinear Bilinear (or trilinear for MIPMAPs) filtering: Blend the nearest pixels.

enum TRenderer::ETextureMapMode
The various texture map modes.
See also:
TRenderer::SetTextureMapMode() (p. 377)

Playground 4.0.17.1
374 Class and File Reference

Enumerator:
kMapClamp Clamp the texture to 0,1.
kMapWrap Repeat texture coordinates. Uses the fractional part of the texture coordinates
only. Do not expect wrap to work with arbitrarily large numbers, as some video cards
limit wrapping to as little as ±4.
kMapMirror Mirror coordinate: 0->1->0->1.

enum TRenderer::ERenderTargetMode
Modes for TRenderer::BeginRenderTarget (p. 379).
Enumerator:
kFullRenderRGB1 Render RGB with an opaque alpha. Does not preserve the current texture
contents.
kFullRenderRGBX Render RGB with an undefined alpha. Does not preserve the current
texture contents. Alpha contents are undefined.
kMergeRenderRGB1 Render RGB with an opaque alpha, preserving the current texture con-
tents; entire final surface (not just areas that are overdrawn) will get an opaque alpha.
Note that this call is actually slower than kFullRenderRGB1, since the existing texture
data needs to be copied to the render surface.
kMergeRenderRGBX Render RGB with an opaque alpha, preserving the current texture con-
tents; final surface alpha is unchanged. Note that this call is actually slower than kFull-
RenderRGBX, since the existing texture data needs to be copied to the render surface.
kMergeRenderXXXA Render Alpha without modifying RGB pixels. RGB of original image
will be preserved.

enum TRenderer::ECullMode
Possible cull modes.
Enumerator:
kCullNone No culling.
kCullCW Cull faces with clockwise vertices.
kCullCCW Cull faces with counterclockwise vertices.

15.53.3 Constructor & Destructor Documentation

TRenderer::∼TRenderer ()
Destructor

15.53.4 Member Function Documentation

static TRenderer∗ TRenderer::GetInstance ()


Accessor

Navigating the Playground SDK


15.53 TRenderer Class Reference 375

Referenced by TBegin3d::Done(), TBegin2d::Done(), TBegin2d::TBegin2d(), and TBe-


gin3d::TBegin3d().

void TRenderer::SetViewport (const TRect & viewport)


Set the current rendering viewport. Only affects the 3d rendering functions, as the viewport is
overridden internally by the TTexture::Draw functions.
Parameters:
viewport Viewport

void TRenderer::GetViewport (TRect ∗ viewport)


Get the current rendering viewport.
Parameters:
viewport Viewport

void TRenderer::SetClippingRectangle (const TURect & clip)


Set the current screen clipping rectangle.
Parameters:
clip Rectangle to clip to in screen coordinates.

TRect TRenderer::GetClippingRectangle ()
Get the current screen clipping rectangle.

void TRenderer::PushClippingRectangle (const TURect & clip)


Push a clipping rectangle onto the internal stack.
Parameters:
clip Clipping rectangle to push.

void TRenderer::PopClippingRectangle ()
Pop a clipping rectangle from the internal stack.

void TRenderer::PushViewport (const TRect & viewport)


Push a viewport on the internal viewport stack.
Parameters:
viewport Viewport

Playground 4.0.17.1
376 Class and File Reference

void TRenderer::PopViewport ()
Restore a viewport from the viewport stack.

void TRenderer::DrawVertices (EDrawType type, const TVertexSet & vertices)


Draw a set of vertices using the current environment.
There is a hard limit on the number of vertices of TVertexSet::kMaxVertices (p. 495).
Parameters:
type Type of data to draw.
vertices A set of vertices.

void TRenderer::DrawIndexedVertices (EDrawType type, const TVertexSet & vertices,


uint16_t ∗ indices, uint32_t indexCount)
Draw a set of vertices using the current environment.
There is a hard limit on the number of vertices of TVertexSet::kMaxVertices (p. 495), and on the
number of indices of kMaxIndices.
Parameters:
type Type of data to draw.
vertices A set of vertices.
indices An array of indices into the set of vertices.
indexCount The number of indices.

void TRenderer::SetShadeMode (EShadeMode shadeMode)


Set the shade mode.

bool TRenderer::RenderTargetIsScreen ()
Query as to whether the current render target is the screen.

void TRenderer::SetTexture (TTextureRef pTexture = TTextureRef())


Set the current rendering texture.
Parameters:
pTexture Texture to assign. Default parameter is NULL texture.

TTextureRef TRenderer::GetTexture ()
Get the currently assigned texture.
Returns:
The current texture.

Navigating the Playground SDK


15.53 TRenderer Class Reference 377

void TRenderer::SetBlendMode (EBlendMode blendMode)


Set the current blend mode. The blend mode is reset to "normal" when calling either Begin2d or
Begin3d.
Parameters:
blendMode The new blend mode.

void TRenderer::SetFilteringMode (EFilteringMode filteringMode)


Set the current filtering mode to use when scaling images.
Parameters:
filteringMode Mode to use.

void TRenderer::SetTextureMapMode (ETextureMapMode umap, ETextureMapMode vmap)


Set the texture map mode for use when texture coordinates extend beyond the edge of the internal
texture.
NOTE that the internal texture is almost always square and a power of two, so most textures
should be limited to those constraints when using wrapping modes.
Parameters:
umap Texture map mode for U coordinates.
vmap Texture map mode for V coordinates.

void TRenderer::SetZBufferWrite (bool writeToZbuffer)


Enable or disable writing to zbuffer.
Parameters:
writeToZbuffer True to write to zbuffer.
See also:
SetZBufferTest (this page)

void TRenderer::SetZBufferTest (bool testZbuffer)


Enable zbuffer test.
Parameters:
testZbuffer True to test zbuffer when drawing.
See also:
SetZBufferWrite (this page)

Playground 4.0.17.1
378 Class and File Reference

void TRenderer::SetColorWrite (bool colorWrite)


Enable writing of RGB color data. Default is on.
If you disable writing of RGB color data, no visible drawing will happen, though if zbuffer writing
is still active drawing will still occur to that plane.
Parameters:
colorWrite True to enable writing.

bool TRenderer::GetColorWrite ()
Get the current "color write" state.
Returns:
True if color writing is enabled.
See also:
SetColorWrite (this page)

void TRenderer::ClearZBuffer ()
Clear the ZBuffer. Done automatically by BeginDraw() (p. 380) and BeginRenderTarget() (oppo-
site).

bool TRenderer::GetZBufferWrite ()
Query ZBuffer-write state.
Returns:
True if ZBuffer writing is enabled; false otherwise.
See also:
SetZBufferWrite (previous page)

bool TRenderer::GetZBufferTest ()
Query ZBuffer-test state.
Returns:
True if ZBuffer testing is enabled; false otherwise.
See also:
SetZBufferTest (previous page)

str TRenderer::GetSystemData ()
Get data about the current system.

Navigating the Playground SDK


15.53 TRenderer Class Reference 379

Returns:
A system data string.

bool TRenderer::GetTextureSquareFlag ()
Query whether textures on this computer will be created as square internally. You can always
create textures of any shape, but internally a texture may be extended to the next power-of-two,
square size that will fit your requested texture size.
Note that texture dimensions will be rounded up to the next power-of-two on cards that require
it; always query TTexture::GetInternalSize() (p. 469) if the exact texture dimensions are relevant.
Returns:
True if textures will always be square, internally.

bool TRenderer::BeginRenderTarget (TTextureRef texture, ERenderTargetMode mode)


Start rendering to a texture. Must NOT be called during a Draw() update. After being called, all
rendering commands without a texture target will be directed instead to the texture passed in to
BeginRenderTarget() (this page).
If you are rendering to a texture that you will be completely covering with content, use one of the
"full" render modes (kFullRenderRGB1 or kFullRenderRGBX). Note that in a full mode that if you
don’t cover the surface you may get garbage left over in the rendering buffer in any untouched
areas of the image.
If your image already has content that you want to render on top of, use one of the merge modes.
If you want your resulting image to have an alpha component, you’ll need to render it in two
passes. This is because a lot of video cards don’t have the ability to render alpha to a buffer–but
they do have the ability to redirect alpha to the RGB channels. So that’s what kMergeRenderXXXA
does: It sets up the rendering pipeline to render just the alpha to the RGB channels, and then copies
the resulting data back into your texture alpha channel. The usage pattern looks like this:

TTextureRef myTexture = .... ; // Create your texture C++


TRenderer * r = TRenderer::GetInstance();
if (r->BeginRenderTarget(myTexture,TRenderer::kFullRenderRGBX))
{
DoRendering(); // Paint the full texture
r->EndRenderTarget();
}

if (r->BeginRenderTarget(myTexture,TRenderer::kMergeRenderXXXA))
{
DoRendering(); // Paint the full texture again, this time
r->EndRenderTarget(); // to get alpha information
}

Warning:

Will not render to areas of a surface beyond the extents of the screen surface (800x600 by
default). This allows us to use the most compatible render-to-surface modes.

Playground 4.0.17.1
380 Class and File Reference

Additionally, by using the most compatible modes, this is not a fast operation. It is best used to
pre-render an image that will be used multiple times rather than attempting to execute it every
frame.
Parameters:
texture Texture to render to.
mode Render target mode.
Returns:
True on success.

void TRenderer::EndRenderTarget ()
Complete the rendering to a texture.
See also:
BeginRenderTarget (previous page)

bool TRenderer::BeginDraw (bool needRefresh)


Open an internal draw context. Called automatically by the system.
Typically internal use only. This function is called by the system prior to your TWindow::Draw() (p. 503)
and TWindow::PostDraw() (p. 503) calls.
Parameters:
needRefresh True if we should refresh the screen (for support of dirty- rectangle drawing).
Usually false, meaning you’re redrawing the entire screen.
Returns:
True on success. If BeginDraw() (this page) returns false, do not call EndDraw() (this page).

void TRenderer::EndDraw (bool flip = true)


Close and complete an internal draw context. Also presents the completed rendered screen.
Parameters:
flip Flip or blit the back buffer to the screen.

bool TRenderer::Begin2d ()
Begin 2d rendering. Any calls to TTexture::Draw∗() functions should happen between a Begin2d()
(this page) and End2d() (opposite) call.
It’s a good idea to minimize renderer state changes, as they can be expensive on some cards. Try
to group most of your 2d rendering together in as few Begin2d() (this page) groups as possible.
Clears all 3d matrices when called. You can set the view and world matrix between Begin2d() (this
page) and End2d() (opposite), but they will be cleared again on End2d() (opposite).

Navigating the Playground SDK


15.53 TRenderer Class Reference 381

You can use the helper class TBegin2d (p. 200) to automatically close the block on exiting the
scope.
Returns:
True on success. False on failure, which can mean that you are already in a Begin2d() (op-
posite) state, you are in a Begin3d() (this page) state, or some other aspect of the engine has
gotten into a bad state. Check log file messages for details.
See also:
TBegin2d (p. 200)

Referenced by TBegin2d::TBegin2d().

void TRenderer::End2d ()
Finish a 2d rendering set.
See also:
Begin2d (opposite)

Referenced by TBegin2d::Done().

bool TRenderer::Begin3d ()
Begin 3d rendering. Any calls to TModel::Draw (p. 305)∗() functions should happen between a
Begin3d() (this page) and End3d() (this page) call. Also, calls to DrawVertices() (p. 376) with
vertex types TLitVert (p. 258) or TVert (p. 493) should be within a Begin3d() (this page) block.
It’s a good idea to minimize renderer state changes, as they can be expensive on some cards. Try
to group most of your 3d rendering together in as few Begin3d() (this page) groups as possible.
You can use the helper class TBegin3d (p. 201) to automatically close the block on exiting the
scope.
Returns:
True on success. False on failure, which can mean that you are already in a Begin3d() (this
page) state, you are in a Begin2d() (opposite) state, or some other aspect of the engine has
gotten into a bad state. Check log file messages for details.
See also:
TBegin3d (p. 201)

Referenced by TBegin3d::TBegin3d().

void TRenderer::End3d ()
Finish a 3d rendering set.

Playground 4.0.17.1
382 Class and File Reference

See also:
Begin3d (previous page)

Referenced by TBegin3d::Done().

bool TRenderer::InDraw () const


Query as to whether we’re currently in a drawing mode.
Returns:
True if we’re between BeginDraw() (p. 380) and EndDraw() (p. 380), or BeginRenderTarget()
(p. 379) and EndRenderTarget() (p. 380).

void TRenderer::FillRect (const TURect & rect, const TColor & color, TTextureRef dst =
TTextureRef())
Fill a rectangle, optionally specifying a destination texture.
Unlike TTexture::Draw∗() calls, FillRect can be used to draw a rectangle in any texture type, and
does not depend on the Begin2d/End2d state. Will not blend using the alpha value; instead
it writes the alpha value as part of the color into the destination, when the destination texture
supports alpha.
In the case of screen fills, the alpha value is never used, since to draw an alpha value to the screen
is meaningless (the screen surface is never used as a source texture).
Parameters:
rect Rectangle to fill; this rectangle is either relative to the upper left corner of the current
viewport or window (when dst is NULL), or is relative to the upper left corner of the
texture.
color Color to draw–this color (RGBA) will be written verbatim into the surface across the
rectangle with no blending, such that all pixels in the rectangle will exactly equal the
RGBA color specified.
dst Optional destination texture. Current viewport and window coordinates are ignored
when dst is non-NULL.

bool TRenderer::IsCapturePending ()
Query as to whether the previously set capture texture is still waiting to be filled with the screen
render.
Returns:
True if the capture texture is still pending.

void TRenderer::SetCaptureTexture (TTextureRef texture)


Set a capture texture. This texture will be filled with the results of the next screen update. Techni-
cally, the next EndDraw() (p. 380) will trigger a copy of the back-buffer surface to the given texture;
EndDraw() (p. 380) typically is called at the end of a screen update by TWindowManager (p. 519).

Navigating the Playground SDK


15.53 TRenderer Class Reference 383

The capture texture MUST be exactly the size of the screen, or SetCaptureTexture() (opposite) will
silently fail (or ASSERT in debug builds).
Parameters:
texture Texture to fill.

TTextureRef TRenderer::GetCaptureTexture ()
Get the current capture texture from the renderer.
After a texture is filled, this function will return an empty texture.
Returns:
The texture that’s waiting to be filled with the results of a screen render. An empty TTextur-
eRef if SetCaptureTexture() (opposite) hasn’t been called, or after the texture has been filled.

void TRenderer::SetWorldMatrix (TMat4 ∗ pMatrix)


Set the world matrix.
Playground uses a World/View/Projection transformation model. This method allows you to set
the current world matrix.
Parameters:
pMatrix New world matrix.

void TRenderer::SetViewMatrix (TMat4 ∗ pMatrix)


Set the view matrix.
Playground uses a World/View/Projection transformation model. This method allows you to set
the current view matrix.
Helper function SetView() (next page) can be used to set the view matrix based on a location, a
look-at target, and an up vector.
Parameters:
pMatrix New view matrix.

void TRenderer::SetProjectionMatrix (TMat4 ∗ pMatrix)


Set the projection matrix.
Playground uses a World/View/Projection transformation model. This method allows you to set
the current projection matrix.
Projection can be set up automatically using SetPerspectiveProjection.
See also:
SetPerspectiveProjection (next page)

Playground 4.0.17.1
384 Class and File Reference

Parameters:
pMatrix New projection matrix.

void TRenderer::SetView (const TVec3 & eye, const TVec3 & at, const TVec3 & up)
Set the view matrix based on the viewer location, a target location, and an up vector.
Parameters:
eye The viewer’s location.
at The target location.
up Up vector.

void TRenderer::SetPerspectiveProjection (TReal nearPlane, TReal farPlane, TReal fov =


PI/4.0f, TReal aspect = 0)
Set a perspective projection matrix.
Parameters:
nearPlane Distance to near plane.
farPlane Distance to far plane.
fov Field of view in radians.
aspect Aspect ratio of view (0 to calculate the aspect ration from the viewport size).

void TRenderer::SetOrthogonalProjection (TReal nearPlane, TReal farPlane)


Set an orthogonal projection matrix.
Parameters:
nearPlane Distance to the near plane.
farPlane Distance to the far plane.

void TRenderer::GetWorldMatrix (TMat4 ∗ m)


Get the current world matrix.
Parameters:
m A matrix to fill with the current world matrix.

void TRenderer::GetViewMatrix (TMat4 ∗ m)


Get the current view matrix.
Parameters:
m A matrix to fill with the current view matrix.

Navigating the Playground SDK


15.53 TRenderer Class Reference 385

void TRenderer::GetProjectionMatrix (TMat4 ∗ m)


Get the current projection matrix.
Parameters:
m A matrix to fill with the current projection matrix.

void TRenderer::SetAmbientColor (const TColor & color)


Set the scene’s ambient color.
Parameters:
color New ambient color.

void TRenderer::SetCullMode (ECullMode cullMode)


Set the current cull mode of the 3d render.
Parameters:
cullMode The new cull mode.

void TRenderer::SetMaterial (TMaterial ∗ mat)


Set the current rendering material.
Parameters:
mat Material to set.

void TRenderer::SetLight (uint32_t index, TLight ∗ light)


Set up one of the scene lights.
Parameters:
index Index to light to initialize.
light Light data.

bool TRenderer::ToggleHUD ()
Toggle the HUD
Returns:
true if HUD was previously active.

bool TRenderer::In2d () const


Currently in Begin2d mode.

Playground 4.0.17.1
386 Class and File Reference

Returns:
True if in Begin2d mode.

bool TRenderer::In3d () const


Currently in Begin3d mode.
Returns:
True if in Begin3d mode.

void TRenderer::SetOption (str option, str value)


Set a renderer option.
Parameters:
option Option to set.
value Value to set.

str TRenderer::GetOption (str option)


Get a renderer option.
Parameters:
option Option to get.
Returns:
Value.

15.53.5 Member Data Documentation


const int TRenderer::kMaxIndices
The maximum number of indices that can be passed into DrawIndexedVertices() (p. 376).

Navigating the Playground SDK


15.54 TScreen Class Reference 387

15.54 TScreen Class Reference


#include <pf/screen.h>
Inheritance diagram for TScreen:

TWindow

TModalWindow

TScreen

15.54.1 Detailed Description


The base level modal window. Top-level application control logic can be handled at this level by
deriving from TScreen (this page) and implementing a handler for DoModalProcess.
TScreen (this page) also handles caching of the window background, so TScreen::Draw should
NOT be overridden.

Public Member Functions


• void ClearBackground (bool clear)
• void NeverClearBackground (bool neverClear)
• void SetBackgroundColor (const TColor &color)
• TColor GetBackgroundColor ()

15.54.2 Member Function Documentation


void TScreen::ClearBackground (bool clear)
Tell the screen to clear its background.
This should only be done in a situation where you have a sparse set of windows covering the
background.
Parameters:
clear True to clear the background.

void TScreen::NeverClearBackground (bool neverClear)


Tell the screen to never clear its backrgound
This causes the screen to never redraw the background, even if is the only window.

Playground 4.0.17.1
388 Class and File Reference

Parameters:
neverClear True to never clear the background.

void TScreen::SetBackgroundColor (const TColor & color)


Set the background color.
Note this will only have an effect if ClearBackground() (previous page) is set to true.
Parameters:
color Color to clear the background.

TColor TScreen::GetBackgroundColor ()
Get the current background color.
Returns:
The current background color.

Navigating the Playground SDK


15.55 TScript Class Reference 389

15.55 TScript Class Reference


#include <pf/script.h>
Inheritance diagram for TScript:

TTask

TAnimTask

TScript

15.55.1 Detailed Description


An encapsulation for a Lua script context.
A TScript (this page) can be used in multiple ways. If you create a thread that yields, then you
can either use TScript::Resume (p. 393) to explicitly resume the thread, or you can register it as
a TAnimTask (p. 191) with an appropriate dispatch (commonly TPlatform::AdoptTask (p. 345)
or TModalWindow::AdoptTask (p. 299)). If you’re calling functions that exit normally, then you
don’t need to do anything beyond calling the function or executing Lua code using DoLuaString()
(p. 393), RunScript() (p. 392), or RunFunction() (p. 395).
The script syntax is Lua-standard. There are a few predefined functions that are useful to know:

• DebugOut() will print a string to the debug log.

• DumpTable() will dump a table recursively to the debug log.

• toparams() will take a table as a parameter and return the indexed members as multiple
return values. You can use this to pass the members of a table to a vararg function, for
instance.
See also:
Lua Scripting (p. 47)
http://www.lua.org

Global Script Settings


Set the path that all Lua scripts will search.

• void SetLuaPath (str luaPath)


• int32_t RunFunction (int32_t nargs=0, int32_t nresults=1)
• static str GetLuaPath ()

Playground 4.0.17.1
390 Class and File Reference

Construction/Destruction
• TScript (lua_State ∗luaState=NULL)
• virtual ∼TScript ()

Lua Data Constructors


Functions that are used to push new data on the Lua stack.

• void SetGlobalLightUserData (const char ∗name, void ∗userData)

Lua Data Accessors


Functions that are used to access parameters from the Lua table on the top of the stack.

• lua_State ∗ GetState ()
• TColor PopColor ()
• class TFont PopFont ()
• str PopString ()
• TRect PopRect ()
• lua_Number PopNumber ()
• bool PopBool ()

Client Interface
Functions that are commonly used by a client.

• bool RunScript (str filename)


• TScript ∗ NewThread ()
• void DoLuaString (str luaCommand, int32_t length=-1, int nresults=0)
• virtual bool InjectFunction ()
• int32_t Resume (int32_t narg=0)
• bool CoroutineActive (int32_t narg=0)

Lua Global Data Accessors


Functions that read global data from the Lua state. These are used both inside a creator and
globally.

• str GetGlobalString (str name)


• str GetGlobalTableString (str name, int32_t index)
• TLuaTable ∗ GetGlobalTable (str name)
• void SetGlobalString (str name, str value)
• void SetGlobalNumber (str name, lua_Number value)
• lua_Number GetGlobalNumber (str name)

Navigating the Playground SDK


15.55 TScript Class Reference 391

TTask Overrides
Functions that handle TTask (p. 429) behavior.

• virtual bool Animate ()

15.55.2 Constructor & Destructor Documentation


TScript::TScript (lua_State ∗ luaState = NULL)
Default Constructor
Parameters:
luaState This one is really for internal use only. TScript (p. 389) really only "plays well" with
Lua scripts created by Playground.

virtual TScript::∼TScript ()
Destructor.

15.55.3 Member Function Documentation


void TScript::SetGlobalLightUserData (const char ∗ name, void ∗ userData)
Set a global variable to a Lua light userdata value.
Parameters:
name Name of global.
userData Value of userdata.

lua_State∗ TScript::GetState ()
Get the current Lua state.

TColor TScript::PopColor ()
Pop a TColor (p. 215) from the stack
Returns:
A TColor (p. 215) from the top of the Lua stack.

class TFont TScript::PopFont ()


Pop a TFont from the stack
Returns:
A TFont from the top of the Lua stack.

Playground 4.0.17.1
392 Class and File Reference

str TScript::PopString ()
Pop a string from the stack
Returns:
A string from the top of the Lua stack.

TRect TScript::PopRect ()
Pop a TRect (p. 364) off the top of the stack.
Returns:
A TRect (p. 364)

lua_Number TScript::PopNumber ()
Pop a number from the stack
Returns:
A number from the top of the Lua stack.

bool TScript::PopBool ()
Pop a boolean from the stack.
Returns:
A bool from the top of the Lua stack.

References ASSERT, str::c_str(), and ERROR_WRITE.

bool TScript::RunScript (str filename)


Run a Lua script in the current environment.
If the Lua script returns a value at the top level, that value is assumed to be a function that is to be
run as a thread.
RunScript loads the script from the resource and then runs it using RunFunction. See RunFunction
for important restrictions and limitations.
Parameters:
filename Filename to read
Returns:
true on success.
See also:
RunFunction (p. 395)

Navigating the Playground SDK


15.55 TScript Class Reference 393

TScript∗ TScript::NewThread ()

Create a new TScript-derived class of the same type as this class, but running in a new Lua thread.
Lua threading is cooperative multithreading: It is non-preemptive, and as such requires that you
"yield" to pause processing.
Returns:
A TScript-derived class constructed with similar parameters as the host class.

void TScript::DoLuaString (str luaCommand, int32_t length = -1, int nresults = 0)

Execute a string in the Lua interpreter.


Is not executed as a thread, so will not interfere with an existing thread that has yielded.
Parameters:
luaCommand Command to execute.
length Optional length, for binary buffers.
nresults Optional number of results.

virtual bool TScript::InjectFunction ()

Inject a function into a running Lua script. Default implementation is empty, but the TWindow-
Manager::GetScript() (p. 525) script has a derived implementation.
Attempts to inject the function on the top of the Lua stack into the current coroutine.
The Lua function can take parameters, but is assumed to not return any results.
Returns:
True on success, false on failure.
See also:
TScript::RunScript (opposite)

int32_t TScript::Resume (int32_t narg = 0)

Resume a thread that has been suspended by a coroutine yield.


Parameters:
narg Number of arguments being passed in on the stack; these arguments are returned as the
results of the previous yield.
Returns:
0 if there are no errors running the coroutine, or an error code. See http://www.lua.org/
manual/5.0/manual.html#lua_pcall for error codes.

Playground 4.0.17.1
394 Class and File Reference

bool TScript::CoroutineActive (int32_t narg = 0)


Test to see if a coroutine can currently be successfully resumed.
Parameters:
narg Number of arguments you were planning to pass in to the coroutine.
Returns:
True if a coroutine exists and is ready to be resumed. False otherwise.

str TScript::GetGlobalString (str name)


Get a string from a global Lua variable.
Parameters:
name Name of the Lua variable.
Returns:
The string, if found. An empty string otherwise.

str TScript::GetGlobalTableString (str name, int32_t index)


Get a string from a global Lua table.
Parameters:
name Name of the Lua table.
index Index of item to extract.
Returns:
The string, if table and index found. An empty string otherwise.

TLuaTable∗ TScript::GetGlobalTable (str name)


Get a global table from a Lua state. The table is created with new, and must be deleted when you
are done with it.
Parameters:
name Name of table to retrieve.
Returns:
A TLuaTable (p. 269) wrapping the global table.

void TScript::SetGlobalString (str name, str value)


Set a string global in a Lua environment.
Parameters:
name Name of the string variable.

Navigating the Playground SDK


15.55 TScript Class Reference 395

value Value to set the string variable.

void TScript::SetGlobalNumber (str name, lua_Number value)


Set a numeric global in a Lua environment.
Parameters:
name Name of the lua_Number variable.
value Value to set the variable.

lua_Number TScript::GetGlobalNumber (str name)


Get a number from a global Lua variable.
Parameters:
name Name of the Lua variable.
Returns:
The corresponding number, or 0 if not found.

virtual bool TScript::Animate ()


This function is called when it’s time to execute this task.
Returns:
True to keep the task alive. False to destroy the task.

Implements TAnimTask (p. 192).

static str TScript::GetLuaPath ()


Get the global Lua search path.

void TScript::SetLuaPath (str luaPath)


Set the global Lua search path.
Parameters:
luaPath New path for Lua.

int32_t TScript::RunFunction (int32_t nargs = 0, int32_t nresults = 1)


Run the function with parameters on the Lua stack.
This is different than the Lua APIs lua_call and lua_pcall in that it relies on InjectFunction to pass a
function into a currently paused coroutine. InjectFunction is implemented in the TWindowMan-
ager (p. 519) script, but not in the base class. See Implementation Details below.
Example usage:

Playground 4.0.17.1
396 Class and File Reference

TScript * s = TWindowManager::GetInstance()->GetScript(); C++


// Push the function on the stack.
lua_getglobal( s->GetState(), "MyLuaFunction" );
// Run the function with no parameters or results.
s->RunFunction(0,0);

The above will call MyLuaFunction() in Lua with no parameters.


Example with parameters and a return value:

TScript * s = TWindowManager::GetInstance()->GetScript(); C++


// Push the function on the stack.
lua_getglobal( s->GetState(), "StopGame" );
// Push the number 25 onto the stack.
lua_pushnumber( s->GetState(), 25 );
// Run the function with one parameter and one result.
s->RunFunction(1,1);
// Get the return value from the top of the stack.
int32_t result = (int32_t)lua_tonumber( s->GetState(), -1 );

See Lua API documentation from http://www.lua.org for more information on lua_getglobal,
lua_pushnumber, and the rest of the internal Lua API.
Warning:

If you need more than one return value from your function, it cannot yield control, nor call
any function that yields control of the coroutine. A single return value is supported by the
current API.

15.55.4 Details
When Lua has paused a script using the "coroutine.yield" function or the C call lua_yield, it re-
mains in a suspended state until one calls lua_resume or coroutine.resume. In this state you can
actually still use the same interpreter to execute Lua functions, but those functions may not them-
selves yield, nor can a Lua function that was called via C resume the previous Lua coroutine.
To allow arbitrary function execution from C, the Playground Lua "message loop" takes an extra
parameter which is a function to call. In other words, whenever the Lua message loop has yielded
to wait for a message, you can pass it in a message and/or a command to execute. The TWin-
dowManager (p. 519) version of InjectFunction calls Resume with that command as a parameter,
and it’s executed as part of the main thread–so it can therefore enter its own wait loops, call other
script functions, etc. However, that function that’s passed in as a parameter can take no parame-
ters of its own; RunFunction uses a Playground Lua call GetClosure to wrap your function plus
any parameters in a Lua closure, and then passes that closure in to be executed.
In the case that a coroutine is not currently active, RunFunction does the trivial thing and calls
lua_pcall with the standard error handler.
Note that the base class implementation of InjectFunction does nothing, and it’s only the derived
window UI script that InjectFunction will work.
This is not to hide the implementation, but instead because the injection relies on how the Lua
script that yielded treats the return values of the yield statement. We can’t make any assumptions
about how your own custom scripts will process yield results; if you want to create your own

Navigating the Playground SDK


15.55 TScript Class Reference 397

version of InjectFunction, derive from TScript (p. 389) and add your own implementation. As an
example:

bool InjectFunction() C++


{
return Resume(1)==0;
}

This would assume that your Lua code interpreted the first return value from yield as a function,
and then ran the function:

f = yield(); Lua
if (f) then
f();
end

That way, the function is executed as part of your thread, rather than outside of it. If you need
multiple threads, see TScript::NewThread() (p. 393).
Parameters:
nargs Number of arguments.
nresults Number of results. If there’s a chance your function will be executed during a paused
coroutine, and your function needs to be able to yield, then this number should be zero
or one.
Returns:
0 on success. Lua error code otherwise.

Playground 4.0.17.1
398 Class and File Reference

15.56 TScriptCode Class Reference


#include <pf/script.h>
Inheritance diagram for TScriptCode:

TAsset

TScriptCode

15.56.1 Detailed Description

An encapsulation of a compiled Lua source file.

Public Member Functions

• str GetCode ()
• uint32_t GetCodeLength ()

Static Public Member Functions

• static TScriptCodeRef Get (str handle, str luaPath="", str ∗error=NULL)

15.56.2 Member Function Documentation

static TScriptCodeRef TScriptCode::Get (str handle, str luaPath = "", str ∗ error = NULL)
Accessor function for Lua script-code asset.
Internally, when loading a Lua script from a file, the internal routines use TScriptCode::Get()
(this page) to load it. If you keep a reference to the TScriptCode (this page), then when the routine
calls TScriptCode::Get() (this page), it will retrieve the cached (and precompiled) copy rather than
reloading it from disk.
Parameters:
handle File handle to load.
luaPath Any additional Lua search path necessary.
error An optional str (p. 161) that gets set with an error string.
Returns:
A reference to the compiled code object.

Navigating the Playground SDK


15.56 TScriptCode Class Reference 399

str TScriptCode::GetCode ()
Get the (compiled) script code.
Returns:
A pre-compiled Lua block. Can have embedded null characters; use TScript-
Code::GetCodeLength() (this page) to determine the length.

uint32_t TScriptCode::GetCodeLength ()
Get the length of the compiled code block.
Returns:
Code block length.

Playground 4.0.17.1
400 Class and File Reference

15.57 TSimpleHttp Class Reference


#include <pf/simplehttp.h>

15.57.1 Detailed Description


The TSimpleHttp (this page) class implements a basic HTTP connection.

Public Types

• enum ERequestFlags { eNoFlag, eDoNotWriteCache, eIgnoreCNInvalid }


• enum EStatus { eNetWait, eNetDone, eNetError, eFileError }

Public Member Functions

• TSimpleHttp ()
• virtual ∼TSimpleHttp ()
• void Init (const char ∗url, bool bPost=false, const char ∗path=NULL)
• void AddArg (const char ∗name, const char ∗value)
• void AddArg (const char ∗name, int32_t value)
• void DoRequest (int32_t flags)
• EStatus GetStatus ()
• unsigned long GetContentLengthHeader ()
• unsigned long GetBytesReceived ()
• char ∗ GetContents ()

Static Public Member Functions

• static str HttpSafeString (const char ∗unsafeString)

15.57.2 Member Enumeration Documentation


enum TSimpleHttp::ERequestFlags
Request modifiers.
Enumerator:
eNoFlag No modifier.
eDoNotWriteCache Do not write the request to the cache.
eIgnoreCNInvalid Ignore an invalid certificate.

Navigating the Playground SDK


15.57 TSimpleHttp Class Reference 401

enum TSimpleHttp::EStatus
Status enumeration.
Enumerator:
eNetWait Waiting for a reply.
eNetDone Reply complete and successful.
eNetError Error communicating with server.
eFileError Error writing file.

15.57.3 Constructor & Destructor Documentation


TSimpleHttp::TSimpleHttp ()
Construction.

virtual TSimpleHttp::∼TSimpleHttp ()
Destruction.

15.57.4 Member Function Documentation


void TSimpleHttp::Init (const char ∗ url, bool bPost = false, const char ∗ path = NULL)
Initialize TSimpleHttp (opposite).
Parameters:
url The URL to connect with. The underlying library will not accept extremely long URLs, so
use POST requests if the request will be more than about 800 characters long.
bPost True for a POST request; otherwise GET.
path Specify path name to download to; otherwise the data is kept in an internal buffer and
retrieved using TSimpleHttp::GetContents() (p. 403).

void TSimpleHttp::AddArg (const char ∗ name, const char ∗ value)


Add a POST or GET argument to the query.
Parameters:
name Name of argument.
value Value of argument.

void TSimpleHttp::AddArg (const char ∗ name, int32_t value)


Add a POST or GET argument to the query.
Parameters:
name Name of argument.
value Value of argument.

Playground 4.0.17.1
402 Class and File Reference

static str TSimpleHttp::HttpSafeString (const char ∗ unsafeString)


HTTP cleanup.
Parameters:
unsafeString String to clean.
Returns:
Newly cleaned string.

void TSimpleHttp::DoRequest (int32_t flags)


Start the request.
Parameters:
flags One or more ERequestFlags bitwise-ORed together.

EStatus TSimpleHttp::GetStatus ()
Get the current status.
Returns:
The status.

unsigned long TSimpleHttp::GetContentLengthHeader ()


Returns the "content-length" field of the HTTP header, if available.
This value is the expected total download size.
Returns:
Expected size of the content.
See also:
GetBytesReceived() (this page)

unsigned long TSimpleHttp::GetBytesReceived ()


Get the total number of bytes received. If the download is complete, this is the same as GetCon-
tentLengthHeader() (this page); if the download is still in progress, this will be a lower number
that you can use to display a progress bar.
Returns:
Bytes received.
See also:
GetContentLengthHeader() (this page)

Navigating the Playground SDK


15.57 TSimpleHttp Class Reference 403

char∗ TSimpleHttp::GetContents ()
Get the content of the reply.
Available only if downloading to memory: Will fail until status is eNetDone.

Playground 4.0.17.1
404 Class and File Reference

15.58 TSlider Class Reference


#include <pf/slider.h>
Inheritance diagram for TSlider:

TWindow

TSlider

15.58.1 Detailed Description


Slider class.
A class that implements a UI slider that is scalable. It consists of two parts, the rail and the slider.
The rail consists of three graphics, the top, middle, and bottom. The middle is stretched to be as
long as it needs to match the height or width of the slider. You can set the width or height of the
slider to be the long dimension, and the other dimension will be taken from the width of the rail
images.
Attributes:

• railtop - Top of the rail. Rail graphics are vertical.

• railmid - Middle of the rail. This part gets stretched.

• railbot - Bottom of the rail.

• sliderimage - Image to use as the slider handle.

• sliderrollimage - Image to use as the rollover for the slider handle.

• yoffset - An offset to use to adjust the centering of the slider handle.

Public Types
• enum ESliderState { eIdle, eMoving }

Public Member Functions


• void ShowHandle (bool show)
• virtual void Draw ()
• void SetRailTexture (TTextureRef top, TTextureRef mid, TTextureRef bot)
• void SetSliderTexture (TTextureRef texture, TTextureRef rollover)
• TReal GetValue ()

Navigating the Playground SDK


15.58 TSlider Class Reference 405

• void SetValue (TReal value, bool silent=false)


• void SetScale (TReal scale)
• TReal GetScale ()
• void SetAlpha (TReal alpha)
• TReal GetAlpha ()
• virtual bool OnMouseDown (const TPoint &point)
• virtual bool OnMouseUp (const TPoint &point)
• virtual bool OnMouseMove (const TPoint &point)
• virtual bool OnMouseLeave ()
• virtual void Init (TWindowStyle &style)
• ESliderState GetState ()

Static Public Member Functions


• static void Register ()

15.58.2 Member Enumeration Documentation


enum TSlider::ESliderState
The current state of the slider.

15.58.3 Member Function Documentation


void TSlider::ShowHandle (bool show)
Show the slider widget. Defaults to being visible.
Parameters:
show True to show handle.

virtual void TSlider::Draw ()


Draw the window. Derived classes will override this function and provide the draw functionality.
Optionally only redraw portions that have been invalidated since the previous draw.
Reimplemented from TWindow (p. 503).

void TSlider::SetRailTexture (TTextureRef top, TTextureRef mid, TTextureRef bot)


Set the textures for the rail. The textures are oriented vertically, as if for a vertical slider, and will
be rotated counter-clockwise for horizontal sliders.
To ensure compatiblity across renderers, the height each texture should be a power of two and
greater than its width.

Playground 4.0.17.1
406 Class and File Reference

Parameters:
top Top of the slider.
mid Middle of the slider. This one gets stretched out to make the slider the right height or
width.
bot Bottom of the slider.

void TSlider::SetSliderTexture (TTextureRef texture, TTextureRef rollover)


Set the textures for the slider knobs.
Parameters:
texture Normal state slider knob.
rollover Rollover state slider knob.

TReal TSlider::GetValue ()
Get the current slider handle position.
Returns:
The position as a value from 0 to 1.

void TSlider::SetValue (TReal value, bool silent = false)


Set the current slider handle position.
Parameters:
value Position from 0 to 1 inclusive.
silent True to prevent a "slider-changed" message from being sent.

void TSlider::SetScale (TReal scale)


Set the slider scale.
Parameters:
scale The scale of the slider.

TReal TSlider::GetScale ()
Get the current slider scale.
Returns:
Slider scale.

void TSlider::SetAlpha (TReal alpha)


Set the current slider alpha.

Navigating the Playground SDK


15.58 TSlider Class Reference 407

Parameters:
alpha Alpha of the slider.

TReal TSlider::GetAlpha ()
Get the current slider alpha.
Returns:
The slider alpha.

virtual bool TSlider::OnMouseDown (const TPoint & point)


Mouse handler.
Parameters:
point Mouse position.
Returns:
True if handled.

Reimplemented from TWindow (p. 512).

virtual bool TSlider::OnMouseUp (const TPoint & point)


Mouse handler.
Parameters:
point Mouse position.
Returns:
True if handled.

Reimplemented from TWindow (p. 512).

virtual bool TSlider::OnMouseMove (const TPoint & point)


Mouse handler.
Parameters:
point Mouse position.
Returns:
True if handled.

Reimplemented from TWindow (p. 512).

Playground 4.0.17.1
408 Class and File Reference

virtual bool TSlider::OnMouseLeave ()


Mouse handler.
Returns:
True if handled.

Reimplemented from TWindow (p. 513).

static void TSlider::Register ()


Register TSlider (p. 404) with the windowing system.

virtual void TSlider::Init (TWindowStyle & style)


Window initialization handler.
Parameters:
style Window style.

Reimplemented from TWindow (p. 501).

ESliderState TSlider::GetState ()
Get the current slider state (whether it’s moving or idle).
Returns:
The state of the slider.

Navigating the Playground SDK


15.59 TSound Class Reference 409

15.59 TSound Class Reference


#include <pf/sound.h>
Inheritance diagram for TSound:

TAsset

TSound

15.59.1 Detailed Description


The TSound (this page) class represents an object that can play a sound asset.
By default, TSound (this page) only knows how to load Ogg/Vorbis files, but Playground sup-
ports the loading of Ogg/Speex files as well. The Speex compression format is optimized for voice
compression. For the fullest Playground support of Ogg/Speex files, you must use the encoder
that ships with Playground, bin/speexenc.exe.
To activate Speex decoding, you need to add the following code to main.cpp:

#include <pf/speex.h> C++


...

// In PlaygroundInit()
TSpeex::Register();

This will cause TSound::Get() (next page) to handle .spx files correctly. Speex files only support
streamed playback, and do not support seeking to an arbitrary offset. You can, however, pause,
resume, and reset a Speex sound to the beginning, and you can loop a Speex sound.

Factory Methods
• static TSoundRef Get (str filename, bool bInMemory=true, int32_t type=-1)

Public Types
• enum { kButtonSound, kUserSoundBase }

Public Member Functions


• TSoundInstanceRef Play (bool bLoop=false)
• bool Pause (bool bPause)

Playground 4.0.17.1
410 Class and File Reference

• bool Kill ()
• TReal GetSoundLength ()
• TSoundRef GetRef ()
• str GetName ()

Friends
• class TSoundInstance

15.59.2 Member Function Documentation


static TSoundRef TSound::Get (str filename, bool bInMemory = true, int32_t type = -1)
Get a sound from a name, associating it with a particular sound group.
You can also specify the sound group by appending "?group=###" to the filename instead of pass-
ing the group number as the third parameter. This allows you to specify a group number when
referencing a sound in Lua (in the TButton (p. 202) sound tags, for example), or when add a group
of files using TAssetMap::AddAssets() (p. 197).
Parameters:
filename Name of the sound file.
bInMemory True to load entire sound into memory, false to stream it
type Type of sound, or -1 to be part of a global group. Sounds with the same type will all play
at the same volume. User defined groups should start at kUserSoundBase. Anything
below that value is reserved for internal library use.
Returns:
A TSoundRef to the sound.

TSoundInstanceRef TSound::Play (bool bLoop = false)


Play a sound
Parameters:
bLoop Whether or not to loop a sound
Returns:
A reference to the spawned instance of the sound. To modify or update that instance once it’s
spawned, keep a reference to the TSoundInstance (p. 413) and use it to modify the instance.

bool TSound::Pause (bool bPause)


Pause all instances of this sound.
Parameters:
bPause True to pause, false to unpause

Navigating the Playground SDK


15.59 TSound Class Reference 411

Returns:
true on success, false on failure

bool TSound::Kill ()
Kill all instances of this sound - once a sound is killed it must be restarted with Play() (opposite),
it cannot be unpaused.
If a sound is set as a "continuation" of a sound that is killed, it will also be killed, even if it hasn’t
started yet.
Returns:
true if any sounds were killed, false otherwise.

TReal TSound::GetSoundLength ()
Get the length of the sound in seconds.
Returns:
Number of seconds.

TSoundRef TSound::GetRef ()
Get a reference to this sound.
Returns:
A reference to this.

Reimplemented from TAsset (p. 195).

str TSound::GetName ()
Get the file handle used to create the sound.
Returns:
The sound file handle.

Playground 4.0.17.1
412 Class and File Reference

15.60 TSoundCallBack Class Reference


#include <pf/sound.h>

15.60.1 Detailed Description


TSoundCallBack (this page) –a class that you override and attach to a TSound (p. 409) if you want
to know when the sound has finished playing.

Public Member Functions


• TSoundCallBack ()
• virtual ∼TSoundCallBack ()
• virtual void OnComplete (TSoundInstanceRef soundInstance, TSoundRef nextSound)=0

Friends
• class TSound
• class TSoundData

15.60.2 Constructor & Destructor Documentation


TSoundCallBack::TSoundCallBack ()
Constructor.

virtual TSoundCallBack::∼TSoundCallBack ()
Destructor.

15.60.3 Member Function Documentation


virtual void TSoundCallBack::OnComplete (TSoundInstanceRef soundInstance, TSoundRef
nextSound)
Function called when a sound has finished playing. This function is guaranteed to be called during
the main thread, but may be called up to one second later due to buffering.
Parameters:
soundInstance TSoundInstanceRef of sound that just finished
nextSound TSoundRef of sound that has been queued up to play next with
TSound::SetCompleteAction

Navigating the Playground SDK


15.61 TSoundInstance Class Reference 413

15.61 TSoundInstance Class Reference


#include <pf/soundinstance.h>

15.61.1 Detailed Description


An instance of a sound. Returned as a TSoundInstanceRef from TSound::Play() (p. 410), you can
then control the playback of that instance using this class.
See also:
TSound (p. 409)

Public Member Functions


• virtual ∼TSoundInstance ()
• void Play ()
• void Pause (bool bPause)
• void Kill ()
• void SetPosition (TReal seconds)
• void SetVolume (float volume)
• int GetGroupId ()
• void SetCompleteAction (TSoundCallBack ∗pCallback, TSoundRef
playNext=TSoundRef())
• TSoundRef GetSound ()
• TSoundRef GetNextSound ()

Friends
• class TSound
• class TSoundData
• class TSoundStream

15.61.2 Constructor & Destructor Documentation


virtual TSoundInstance::∼TSoundInstance ()
Destructor.

15.61.3 Member Function Documentation


void TSoundInstance::Play ()
Play the sound!

Playground 4.0.17.1
414 Class and File Reference

void TSoundInstance::Pause (bool bPause)


Pause the sound!
Parameters:
bPause True to pause the sound; false to resume.

void TSoundInstance::Kill ()
Kill the sound instance. Sound instances normally live until they complete or until they are killed.
Simply releasing the TSoundInstanceRef will not itself kill a sound.

void TSoundInstance::SetPosition (TReal seconds)


Set a sound to a specific play position
Parameters:
seconds The position, in seconds, to set the play position of the sound.

void TSoundInstance::SetVolume (float volume)


Set the volume of the sound.
Parameters:
volume Volume level 0.0-1.0f

int TSoundInstance::GetGroupId ()
Get the group this stream belongs to.
Returns:
The current group id.

void TSoundInstance::SetCompleteAction (TSoundCallBack ∗ pCallback, TSoundRef


playNext = TSoundRef())
Setup a sound callback - the sound will call the passed in callback class when the sound has fin-
ished playing. The client maintains ownership of the callback, and it is their responsibility to
delete it when no longer needed. Deleting the callback automatically unregisters it. A TSound-
CallBack (p. 412) contains references to the current sound and the playNext sound. Therefore,
you do not need to keep a reference around to a sound used in a sound callback, and the sound
can be killed by deleting the sound callback (However - in practice it is wise to keep around your
own sound reference so you can pause it, kill it, etc.) This call can also be used to setup a sound to
play immediately after this sound is done. Note that because a callback is called during the main
thread, in order to play a sound seamlessly, it is better to setup a 2nd sound with playNext instead
of having the pCallback play another sound.

Navigating the Playground SDK


15.61 TSoundInstance Class Reference 415

Warning:

When queueing up sounds with the next parameter, the sound must be of the same number
of channels (i.e. mono or stereo).

If you queue up a sound with a different number of channels, an ASSERT will trigger in a debug
build. In a release build, the resulting sound will likely be incorrect.
Parameters:
pCallback Pointer to callback object that will be called when the sound is done. This param-
eter can be NULL if the client just wants to setup a playNext sound.
playNext - what sound to play after the current sound finishes. Default is a NULL
TSoundRef() (p. 548). (See note above about playNext restrictions)

TSoundRef TSoundInstance::GetSound ()
Get a reference to the original sound that spawned this instance.
Returns:
A sound reference, or NULL if the sound has been deleted.

TSoundRef TSoundInstance::GetNextSound ()
Get a reference to the next sound to be streamed after the current one completes.

Playground 4.0.17.1
416 Class and File Reference

15.62 TSoundManager Class Reference


#include <pf/soundmanager.h>

15.62.1 Detailed Description


The TSoundManager (this page) class controls access to the sound subsystem.

Public Member Functions


• void SetVolume (float volume)
• void SetTypeVolume (int32_t type, float volume)
• void PauseAllSounds (bool bPause, int32_t type=-1)
• void KillAllSounds (int32_t type=-1)

Friends
• class TSoundStream
• class TLockSoundMutex

15.62.2 Member Function Documentation


void TSoundManager::SetVolume (float volume)
Set the global sound volume.
Parameters:
volume Global sound volume. 0.0 is off, 1.0 is full volume.

void TSoundManager::SetTypeVolume (int32_t type, float volume)


Set the volume for a specific group of sounds. This is multiplied with the global volume setting.
Parameters:
type id of sound group to set.
volume Volume to set. 0.0 is off, 1.0 is full volume.

void TSoundManager::PauseAllSounds (bool bPause, int32_t type = -1)


Pause or unpause all sounds.
Parameters:
bPause true to pause, false to resume.
type Pass -1 to pause all sounds, or specify a specific sound group ID

Navigating the Playground SDK


15.62 TSoundManager Class Reference 417

void TSoundManager::KillAllSounds (int32_t type = -1)


Kill all sounds.
Parameters:
type Pass -1 to kill all sounds, or specify a specific sound group ID.

Playground 4.0.17.1
418 Class and File Reference

15.63 TSpeex Class Reference


#include <pf/speex.h>

15.63.1 Detailed Description


Interface for class TSpeex (this page) A class that wraps the registration of Speex support with the
sound engine. Once you call TSpeex::Register() (this page), TSound::Get() (p. 410) will properly
load a TSound (p. 409) object that streams an Ogg/Speex file, assuming the file has the expected
.spx extension.
See more important information in the TSound (p. 409) documentation.

Static Public Member Functions


• static void Register ()

15.63.2 Member Function Documentation


static void TSpeex::Register ()
Register the Speex decoder with the sound engine.

Navigating the Playground SDK


15.64 TSprite Class Reference 419

15.64 TSprite Class Reference


#include <pf/sprite.h>
Inheritance diagram for TSprite:

TSprite

TAnimatedSprite TTextSprite

15.64.1 Detailed Description


A 2d sprite object. A TSprite (this page) functions both as an individual display object and a
container for child TSprite (this page) objects. Typically a TSprite (this page) with no TTexture
(p. 463) is used as a container for all of the TSprites in one screen of a game.
TSprite References

A TSprite (this page) is always stored in the client as a TSpriteRef—it’s a reference counted
object. To destroy a TSprite (this page), simply call reset() on the last TSpriteRef that refers to
that sprite.

It’s worth noting that a TSprite (this page) holds a reference to any of its children, so you don’t
need to worry about keeping an external reference to a child sprite that can be passively attached
to an object. An example of this usage would be a shadow that stays at a constant offset from the
parent sprite. To make the shadow appear behind the parent you can give it a negative "layer"
when you create it.
Design Concerns

Because it’s convenient, many people tend to want to use TSprite (this page) as a game object.
It’s not designed that way, however, and you’ll quickly run into limitations if you try. For
instance, there’s no way to enumerate children of a TSprite (this page). There’s also no way
to name a TSprite (this page), and then look up a child by name.

This is intentional. TSprite (this page) was designed as a very light class, and adding strings and
the ability to iterate would weigh it down.
Another option you might consider is deriving your own class from TSprite (this page). It has been
requested by developers so often, that it’s used as an example in the docs. I’ve come to believe that
creating a game object that way is categorically a bad idea. As Playground has grown, new child
classes of TSprite (this page) have been created, so if you derive a game object from TSprite (this
page), you won’t be able to have a game object that is, say, a TFxSprite or a TTextSprite (p. 454).
Aside from that, a TSprite (this page) really is all about rendering a TTexture (p. 463), and mixing
game code with your rendering code is poor design when it can be avoided.
If your game objects exist in their own hierarchy, however, and they just own a reference to the
TSprite (this page) that represents them in the game, then your game objects can be represented
by whatever TSprite-derived object we (or you) devise, and the design of your game will now be

Playground 4.0.17.1
420 Class and File Reference

cleaner, since the details of the rendering of your game objects will be properly encapsulated in its
own class and not mixed willy-nilly in the game object behavior classes.
So that’s why you should create your own hierarchy of game objects distinct from the TSprite (pre-
vious page) hierarchy. Having two parallel hierarchies is not ideal, but weighing down TSprite
(previous page) with the plumbing required to promote it to a full-fledged game object is even less
desirable.
How Sprites are Drawn

A TSprite (previous page) has a concept of a layer which indicates how it will be rendered
relative to its siblings. For the top sprite in a hierarchy (the one you’re calling Draw on your-
self), the layer parameter is meaningless—it only applies to sprites with siblings or a parent.
The layer determines the relative order of drawing of a sprite with its siblings and parent.

Here are the rules that determine the order of drawing:

• When siblings have the same layer, they will render in an arbitrary order—it is assumed not
to matter what order they’re in.

• When siblings have different layers, the higher layered siblings will be rendered above the
lower layered siblings.

• When a child sprite has a negative layer, it will be rendered behind its parent; otherwise it
will be rendered in front of its parent.

Changing the layer of a sprite requires that the parent’s child list be resorted. In other words, it’s
a relatively heavy operation if there are a lot of siblings, so try not to do it frequently.
See also:
TAnimatedSprite (p. 175)

Initialization/Destruction
• static TSpriteRef Create (int32_t layer=0, TTextureRef texture=TTextureRef())
• virtual ∼TSprite ()

Drawing and Layers


• virtual void Draw (const TDrawSpec &environmentSpec=TDrawSpec(), int32_t depth=-1)
• void SetLayer (int32_t layer)
• int32_t GetLayer ()

Parent/Child Access and Management


• void AddChild (TSpriteRef child)
• virtual bool RemoveChild (TSpriteRef sprite)
• void RemoveChildren ()

Navigating the Playground SDK


15.64 TSprite Class Reference 421

Bounding Rectangles and Hit Tests.

• virtual TRect GetRect (const TDrawSpec &parentContext, int32_t depth=-1)


• virtual bool HitTest (const TPoint &at, const TDrawSpec &parentContext, int32_t opacity=-
1, int32_t depth=-1)

Public Types

• typedef std::list< TSpriteRef > SpriteList

Public Member Functions

• virtual void SetTexture (TTextureRef texture)


• TTextureRef GetTexture ()
• TDrawSpec & GetDrawSpec ()
• const TDrawSpec & GetDrawSpec () const
• void SetVisible (bool visible)
• bool IsVisible ()
• TSprite ∗ GetParent ()

Protected Member Functions

• TSprite (int32_t layer)


• virtual void ResortSprites ()

Protected Attributes

• SpriteList mChildren

Friends

• class TSpriteManager
• bool operator< (TSpriteRef first, TSpriteRef second)

15.64.2 Member Typedef Documentation

typedef std::list<TSpriteRef> TSprite::SpriteList


A list of sprites.

Playground 4.0.17.1
422 Class and File Reference

15.64.3 Constructor & Destructor Documentation


TSprite::TSprite (int32_t layer) [protected]
Internal Constructor. Use TSprite::Create() (this page) to get a new sprite.

virtual TSprite::∼TSprite ()
Destructor.

15.64.4 Member Function Documentation


static TSpriteRef TSprite::Create (int32_t layer = 0, TTextureRef texture = TTextureRef())
Allocation of a new sprite. Construction is restricted to help "encourage" the use of TSpriteRefs to
hold your TSprites (as well as to encapsulate the TSpriteRef creation pattern).
Parameters:
layer Initial sprite layer.
texture Initial sprite texture.
Returns:
A newly allocated TSprite (p. 419) wrapped in a TSpriteRef.
See also:
SetLayer (opposite)
SetTexture (p. 424)

virtual void TSprite::Draw (const TDrawSpec & environmentSpec = TDrawSpec(), int32_t


depth = -1)
Draw the sprite and its children.
A common mistake is to assume that the incoming TDrawSpec (p. 223) here is what you use
to position and configure this sprite. The way to position a sprite is to modify its internal
TDrawSpec (p. 223), which you retrieve with GetDrawSpec() (p. 425). The environment pa-
rameter is combined with the local TDrawSpec (p. 223) to determine the actual position of the
sprite, though it only inherits those features marked in TDrawSpec (p. 223) as inheritable. See
TDrawSpec::GetRelative() (p. 224) for more details.
Parameters:
environmentSpec The ’parent’ or environment drawspec—the frame of reference that this
sprite is to be rendered in. In general you shouldn’t pass anything in for this parame-
ter and instead should modify the position of the sprite using its GetDrawSpec() (p. 425)
member.

Defaults to a default-constructed TDrawSpec (p. 223). See TDrawSpec (p. 223) for more details
on what is inherited.

Navigating the Playground SDK


15.64 TSprite Class Reference 423

Parameters:
depth How many generations of children to draw; -1 means all children.
See also:
TDrawSpec (p. 223)

Reimplemented in TAnimatedSprite (p. 178), and TTextSprite (p. 457).

void TSprite::SetLayer (int32_t layer)


Set the layer of the sprite. A relatively expensive call; use with care.
The sprite’s layer determines the order in which it will be rendered relative to its immediate parent
and siblings. A negative layer will be rendered behind its parent, while a positive layer will be
rendered in front. Higher layer numbers are rendered in front of lower layer numbers.
Parameters:
layer New sprite layer.

int32_t TSprite::GetLayer ()
Get the current sprite layer.

void TSprite::AddChild (TSpriteRef child)


Add a child sprite. Children are drawn relative to the parent sprite: When you set the position, it
will be added to the position of the parent.
The child should not be added independently to the sprite manager.
Children with a negative sprite layer are drawn behind the parent sprite. Zero or positive layers
are drawn after the parent sprite.
Parameters:
child The sprite to add as a child of this sprite.

virtual bool TSprite::RemoveChild (TSpriteRef sprite)


Remove a child sprite. Returns true if child found.
Parameters:
sprite Child to remove.
Returns:
True if child found.

void TSprite::RemoveChildren ()
Release all children of the sprite.

Playground 4.0.17.1
424 Class and File Reference

"If you love them, set them free."

virtual TRect TSprite::GetRect (const TDrawSpec & parentContext, int32_t depth = -1)

Get the bounding rectangle of this sprite.


Parameters:
parentContext The parent context to test within—where is this sprite being drawn, and with
what matrix? Alpha and color information is ignored.
depth Depth of children to test
Returns:
Rectangle that includes this sprite.

Reimplemented in TAnimatedSprite (p. 177), and TTextSprite (p. 458).

virtual bool TSprite::HitTest (const TPoint & at, const TDrawSpec & parentContext, int32_t
opacity = -1, int32_t depth = -1)

Test to see if a point is within our sprite. Will test children as well, unless depth is set to zero.
By default will not test children unless the TPlatform (p. 336) setting TPlat-
form::kSpriteAlwaysTestChildren (p. 349) is enabled with TPlatform::SetConfig() (p. 340).
Parameters:
at Point to test.
parentContext The parent context to test within—where is this sprite being drawn, and with
what matrix? Alpha and color information is ignored.
opacity Level of opacity to test for; -1 for a simple bounding box test, or 0-255 for alpha color
value, where 0 is transparent (and will therefore always succeed).
depth Depth of children to test. Zero means only test this sprite. -1 means recurse children as
deep as they go.
Returns:
true if point hits us.

Reimplemented in TAnimatedSprite (p. 177), and TTextSprite (p. 458).

virtual void TSprite::SetTexture (TTextureRef texture)

Set the texture of the sprite object.


Parameters:
texture Texture to use.

Reimplemented in TAnimatedSprite (p. 180).

Navigating the Playground SDK


15.64 TSprite Class Reference 425

TTextureRef TSprite::GetTexture ()
Get the current texture.
Returns:
A reference to the current texture.

TDrawSpec& TSprite::GetDrawSpec ()
Get the associated TDrawSpec (p. 223).
Returns:
A modifiable reference to the TDrawSpec (p. 223) associated with this sprite.

const TDrawSpec& TSprite::GetDrawSpec () const


Get a const reference to the associated TDrawSpec (p. 223).
Returns:
A non-modifiable reference to the TDrawSpec (p. 223) associated with this sprite.

void TSprite::SetVisible (bool visible)


Set a sprite to be visible and enabled. Sprites are initially visible.
Parameters:
visible True to set visible.

bool TSprite::IsVisible ()
Is the sprite visible/enabled?
Returns:
True if it’s enabled.

TSprite∗ TSprite::GetParent ()
Get the current parent of this sprite.
Returns:
A pointer to the current parent, or NULL if this sprite is free.

virtual void TSprite::ResortSprites () [protected]


Resort my children because one of them has changed layer (priority).

Playground 4.0.17.1
426 Class and File Reference

15.64.5 Friends And Related Function Documentation


bool operator< (TSpriteRef first, TSpriteRef second) [friend]
Comparison operator for layer sorting.
Parameters:
first Left hand item to compare.
second Right hand item to compare.
Returns:
True if first sprite has a lower layer than the second.

15.64.6 Member Data Documentation


SpriteList TSprite::mChildren [protected]
Sprite children.

Navigating the Playground SDK


15.65 TStringTable Class Reference 427

15.65 TStringTable Class Reference


#include <pf/stringtable.h>

15.65.1 Detailed Description


The interface class for a string table.
The global string table contains a mapping of string identifiers to localized strings. When each
string is requested at run time using GetString() (this page), the parameters passed into Get-
String() (this page) are substituted into slots specified by %1%, %2%, %3%... etc.
You can also use ’s to reference other lookups, such as "Today’s date is %date%", where date is
another string to look up in the table.
To create "%" in a string, use "%%".
Each string supports up to 9 parameters.
A string can contain formatting information as described in the documentation for TTextGraphic
(p. 447).
See Translation Issues and the String Table (p. 65) for a general description of the string table
requirements.

Public Member Functions


• str GetString (str id, str param1=str(), str param2=str(), str param3=str(), str param4=str(),
str param5=str())
• str GetString (str id, uint32_t numStr, str ∗strArray)
• bool SetSilent (bool silent)

15.65.2 Member Function Documentation


str TStringTable::GetString (str id, str param1 = str(), str param2 = str(), str param3 = str(),
str param4 = str(), str param5 = str())
Get a string - get a string from the string table, filling in the string with passed in strings
Parameters:
id id of string to look up in the string table.
param1-param5 Optional strings used to fill in the placeholders in the string returned from
the string table. If you want a parameter to be looked up in the string table as well,
enclose it with %param% to signify that it should be looked up in the string table (use
"%%" to just output a "%").
Returns:
a formatted str (p. 161) that is the result of looking up the id in the string table and adding
in all the optional parameters. If any of the ids do not exist in the str (p. 161) table, the string
returned will be "#####" to signify an invalid lookup.

Playground 4.0.17.1
428 Class and File Reference

str TStringTable::GetString (str id, uint32_t numStr, str ∗ strArray)


Get a string - get a string from the string table, filling in the string with passed in array of strings
Parameters:
id id of string to look up in the string table.
numStr number of Str in the str (p. 161) array
strArray Pointer to array of strings used to fill in the placeholders in the string returned from
the string table. If you want a parameter to be looked up in the string table as well,
enclose it with %param% to signify that it should be looked up in the string table (use
"%%" to just output a "%").
Returns:
a formatted str (p. 161) that is the result of looking up the id in the string table and adding
in all the optional parameters. If any of the ids do not exist in the str (p. 161) table, the string
returned will be "#####" to signify an invalid lookup.

bool TStringTable::SetSilent (bool silent)


Set the string table to not write errors for missing strings.
Parameters:
silent True to suppress errors.
Returns:
Old value of silent.

Navigating the Playground SDK


15.66 TTask Class Reference 429

15.66 TTask Class Reference


#include <pf/task.h>
Inheritance diagram for TTask:

TTask

TAnimTask

TScript

15.66.1 Detailed Description


The task interface. Used as a "callback" for events and periodic tasks.

Public Types
• enum ETaskContext { eNormal, eOnDraw }

Public Member Functions


• virtual ∼TTask ()
• virtual bool Ready (ETaskContext context=eNormal)
• virtual bool DoTask ()=0

15.66.2 Member Enumeration Documentation


enum TTask::ETaskContext
Task context.
Enumerator:
eNormal Normal update context.
eOnDraw Immediately prior to the next screen draw context.

15.66.3 Constructor & Destructor Documentation


virtual TTask::∼TTask ()
Virtual Destructor.

Playground 4.0.17.1
430 Class and File Reference

15.66.4 Member Function Documentation


virtual bool TTask::Ready (ETaskContext context = eNormal)
Is this task ready?
A virtual function that returns whether this task is ready to be executed. Derived classes should
override this function to provide more control over when a task is executed.
Parameters:
context The context in which we’re being called.
Returns:
eReady if it’s ready, eNotReady to wait, or eOnDraw to execute prior to the next screen draw.
Default implementation returns eReady.

virtual bool TTask::DoTask ()


This function is called when it’s time to execute this task.
Returns:
True to keep the task alive. False to destroy the task.

Navigating the Playground SDK


15.67 TTaskList Class Reference 431

15.67 TTaskList Class Reference


#include <pf/tasklist.h>

15.67.1 Detailed Description


A list of TTask-derived objects.

Public Types
• typedef std::list< TTask ∗ > TaskList

Public Member Functions


• ∼TTaskList ()
• bool OrphanTask (TTask ∗task)
• void AdoptTask (TTask ∗task)
• void DoAll (TTask::ETaskContext context=TTask::eNormal)
• void DestroyAll ()

15.67.2 Member Typedef Documentation


typedef std::list<TTask∗> TTaskList::TaskList
The internal task list type.

15.67.3 Constructor & Destructor Documentation


TTaskList::∼TTaskList ()
Destructor

15.67.4 Member Function Documentation


bool TTaskList::OrphanTask (TTask ∗ task)
Remove a task from the task list. Does not delete the task, but rather releases ownership; calling
function now owns task.
Parameters:
task Task to remove.
Returns:
true if task was removed, false if task was not found

Playground 4.0.17.1
432 Class and File Reference

void TTaskList::AdoptTask (TTask ∗ task)


Add a task to the task list. Task list takes ownership of the task and will delete it when the task
notifies that it is complete.
Parameters:
task Task to add.

void TTaskList::DoAll (TTask::ETaskContext context = TTask::eNormal)


Perform all of the tasks in the task list.
Parameters:
context A calling context, if any. Used to trigger tasks when drawing, for example.

void TTaskList::DestroyAll ()
Destroy all the tasks in the list.

Navigating the Playground SDK


15.68 TText Class Reference 433

15.68 TText Class Reference


#include <pf/text.h>
Inheritance diagram for TText:

TWindow

TText

TTextEdit

15.68.1 Detailed Description


A text window. Contains a TTextGraphic (p. 447) and renders it transparently.
See also:
TTextGraphic (p. 447)

Public Types
• enum EFlags { kHAlignLeft, kHAlignCenter, kHAlignRight, kVAlignTop, kVAlignCen-
ter, kVAlignBottom }

Public Member Functions


• TText (bool staticText=false)
• ∼TText ()
• bool Create (str text, uint32_t w, uint32_t h, uint32_t flags, const char ∗fontFilename, uint32_t
lineHeight, const TColor &textColor)
• virtual void Draw ()
• uint32_t GetLineCount ()
• void SetStartLine (TReal startLine=0)
• void GetTextBounds (TRect ∗pBounds)
• virtual void SetText (str text)
• virtual str GetText ()
• TTextGraphic ∗ GetTextGraphic ()
• void SetColor (const TColor &color)
• void SetAlpha (TReal alpha)
• void SetScale (TReal scale)

Playground 4.0.17.1
434 Class and File Reference

• void SetLinePadding (int32_t linePadding)


• virtual bool OnMouseUp (const TPoint &point)
• virtual bool OnMouseDown (const TPoint &point)
• virtual bool OnMouseMove (const TPoint &point)
• virtual bool OnMouseLeave ()
• void SetRotation (TReal degrees, int32_t originX, int32_t originY)
• uint32_t GetMaxScroll ()
• virtual void SetScroll (TReal vScroll, TReal hScroll=0)
• void SetScrollPadding (TReal pad)
• virtual void Init (TWindowStyle &style)

15.68.2 Member Enumeration Documentation


enum TText::EFlags
TText (previous page) window child flags.
Enumerator:
kHAlignLeft Align horizontally with the left edge.
kHAlignCenter Align horizontally with the center.
kHAlignRight Align horizontally with the right edge.
kVAlignTop Align vertically with the top.
kVAlignCenter Align vertically with the center.
kVAlignBottom Align vertically with the bottom.

15.68.3 Constructor & Destructor Documentation


TText::TText (bool staticText = false)
Constructor.
Parameters:
staticText True if this is a static text field.

TText::∼TText ()
Destructor.

15.68.4 Member Function Documentation


bool TText::Create (str text, uint32_t w, uint32_t h, uint32_t flags, const char ∗ fontFilename,
uint32_t lineHeight, const TColor & textColor)
Create a TText (previous page) window.

Navigating the Playground SDK


15.68 TText Class Reference 435

Parameters:
text Initial text for window.
w Width of client rectangle.
h Height of client rectangle.
flags Flags from TText::EFlags (opposite)
fontFilename Font name.
lineHeight Font size.
textColor Font color.
Returns:
True on success.

virtual void TText::Draw ()


TWindow::Draw (p. 503) handler.
Reimplemented from TWindow (p. 503).
Reimplemented in TTextEdit (p. 445).

uint32_t TText::GetLineCount ()
Get the number of lines in the text output.
Returns:
Number of lines.

void TText::SetStartLine (TReal startLine = 0)


Set the first line in the text output. Lines are 0 -> linecount-1.
Parameters:
startLine Line to display as the first line of text.

void TText::GetTextBounds (TRect ∗ pBounds)


Get the actual boundary of the rendered text.
Parameters:
pBounds A rectangle in client coordinates.

virtual void TText::SetText (str text)


Set the current text content
Parameters:
text Text to set.

Reimplemented in TTextEdit (p. 445).

Playground 4.0.17.1
436 Class and File Reference

virtual str TText::GetText ()


Get the current text content.
Returns:
A string containing the current text.

Reimplemented in TTextEdit (p. 445).

TTextGraphic∗ TText::GetTextGraphic ()
Get the associated TTextGraphic (p. 447) object.
Returns:
The TTextGraphic (p. 447) that draws this window’s text.

void TText::SetColor (const TColor & color)


Set the current text color.
Parameters:
color New text color.

void TText::SetAlpha (TReal alpha)


Set the text alpha.
Parameters:
alpha Opacity of text. 1.0==opaque. Multiplied by alpha component of color.

void TText::SetScale (TReal scale)


Set the current text scale. Default is 1.0. Useful for zooming effects.
Parameters:
scale New text scale.

void TText::SetLinePadding (int32_t linePadding)


Set the current line padding. Default is 0. Can be positive or negative - extends/compresses a
fonts natural line spacing
Parameters:
linePadding New Line Padding.

virtual bool TText::OnMouseUp (const TPoint & point)


Mouse up handler.

Navigating the Playground SDK


15.68 TText Class Reference 437

Used to detect clicks on embedded text links. Returns false if no text link was previously clicked
on.
Parameters:
point Location of mouse release in client coordinates.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented from TWindow (p. 512).

virtual bool TText::OnMouseDown (const TPoint & point)


Mouse down handler.
Used to detect clicks on embedded text links. Returns false if no text link is found.
Parameters:
point Location of mouse press in client coordinates.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented from TWindow (p. 512).

virtual bool TText::OnMouseMove (const TPoint & point)


Mouse motion handler.
Parameters:
point Location of mouse in client coordinates.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented from TWindow (p. 512).

virtual bool TText::OnMouseLeave ()


Notification that the mouse has left the window.
Warning:

This message is only sent if TWindowManager::AddMouseListener() (p. 524) has been called
for this window previously.
Returns:
True if handled.

Reimplemented from TWindow (p. 513).

Playground 4.0.17.1
438 Class and File Reference

void TText::SetRotation (TReal degrees, int32_t originX, int32_t originY)


Change the rotation - default is 0 degrees, 0,0 origin
Parameters:
degrees rotation angle in degress (not radians because degress are friendlier)
originX offset from left of text rect to use as center point of rotation
originY offset from top of text rect to use as center point of rotation

uint32_t TText::GetMaxScroll ()
Get the maximum line you need to scroll the text to in order to display the last line of text.
Returns:
The highest integer you need to set the top line to.

virtual void TText::SetScroll (TReal vScroll, TReal hScroll = 0)


A virtual function to override if your window can scroll.
Parameters:
vScroll Vertical scroll percentage (0.0-1.0).
hScroll Horizontal scroll percentage (0.0-1.0).

Reimplemented from TWindow (p. 509).

void TText::SetScrollPadding (TReal pad)


This value controls how far past (in lines) the end of the text the scroll can go. The default value is
0.5f, so this means that if you called SetScroll(1.0f), then the text would scroll so it was 0.5 lines up
off the bottom of the window.
Parameters:
pad How many lines to pad the scrolling text

virtual void TText::Init (TWindowStyle & style)


Initialize the Window. Called by the system only in Lua initialization.
When you create your own custom window, this is where you put your own custom initialization
that needs to happen before children are created. Fundamental window initialization is handled
in every class by this function, so when you override this function you almost always want to
call your base class to handle base class initialization.
Parameters:
style The Lua style that was in effect when this window was created. This style contains
all parameters specified explicitly for the window as well as parameters defined in the
current style. Parameters set locally override ones in the style.

Navigating the Playground SDK


15.68 TText Class Reference 439

Reimplemented from TWindow (p. 501).


Reimplemented in TTextEdit (p. 443).

Playground 4.0.17.1
440 Class and File Reference

15.69 TTextEdit Class Reference


#include <pf/textedit.h>
Inheritance diagram for TTextEdit:

TWindow

TText

TTextEdit

15.69.1 Detailed Description


The TTextEdit (this page) class represents an editable text TWindow (p. 496).
When creating from Lua, in addition to the TWindow (p. 496) tags, you can specify the following
tags:
Warning:

Once this class finds an ancestor modal window, it will register itself with the modal and link
itself to any other TTextEdit (this page) windows it finds under that modal window. If you
then remove it (or a parent) from the hierarchy without destroying it or calling Unregister()
(p. 444), the resulting behavior is undefined.

Public Types
• enum eKeyType { kKeyChar, kKeyMove, kKeyEnter, kKeyTab, kKeyPaste, kKeyIllegal }

Public Member Functions


• TTextEdit ()
• virtual ∼TTextEdit ()
• virtual bool KeyHit (eKeyType type, char key=0)
• virtual bool KeyHitUTF8 (eKeyType type, uint32_t key=0)
• virtual bool OnNewParent ()
• virtual bool OnKeyDown (char key, uint32_t flags)
• virtual void Init (TWindowStyle &style)
• virtual bool OnChar (char key)
• virtual bool OnUTF8Char (str key)
• void Unregister ()

Navigating the Playground SDK


15.69 TTextEdit Class Reference 441

• void SetPassword (bool bPassword)


• void SetEditable (bool bEditable)
• bool GetEditable ()
• void UpdateText ()
• void Backspace ()
• void SetIgnoreChars (str ignoreStr)
• str GetIgnoreChars ()
• virtual str GetText ()
• virtual void SetText (str newText)
• virtual void Draw ()
• void SetMaxLength (uint32_t maxLength)
• void SetUTF8Mode (bool utf8mode)

Static Public Attributes


• static const int kCursorFlashMS
• static const int kDefaultMaxLength

Protected Member Functions


• virtual bool OnTaskAnimate ()
• uint32_t GetCursor ()
• void SetCursor (uint32_t cursor)

Protected Attributes
• uint32_t mMaxLength

Friends
• class TextSpider

15.69.2 Member Enumeration Documentation


enum TTextEdit::eKeyType
Key category.
Enumerator:
kKeyChar Key is a normal character.
kKeyMove Key is a cursor or backspace character.
kKeyEnter Key is enter or return.
kKeyTab Key is the tab character.

Playground 4.0.17.1
442 Class and File Reference

kKeyPaste Key is the "Paste" character.


kKeyIllegal Key is illegal.

15.69.3 Constructor & Destructor Documentation

TTextEdit::TTextEdit ()
Default Constructor.

virtual TTextEdit::∼TTextEdit ()
Destructor.

15.69.4 Member Function Documentation

virtual bool TTextEdit::KeyHit (eKeyType type, char key = 0)


Virtual function to notify child that a key was pressed.
Parameters:
type key type
key key that was hit when appropriate
Returns:
True to accept the key. False to ignore.

virtual bool TTextEdit::KeyHitUTF8 (eKeyType type, uint32_t key = 0)


New virtual function that supports UTF-8 characters. Will return false for any UTF-8 character
that is not in the current font.
Parameters:
type Type of key event.
key Actual key hit.
Returns:
True to accept the key. False to ignore.

virtual bool TTextEdit::OnNewParent ()


Handle any initialization or setup that is required when this window is assigned to a new parent.
No initialization of the window has happened prior to this call.
Returns:
True on success; false on failure.

Navigating the Playground SDK


15.69 TTextEdit Class Reference 443

See also:
Init (this page)
PostChildrenInit (p. 502)

Reimplemented from TWindow (p. 501).

virtual bool TTextEdit::OnKeyDown (char key, uint32_t flags)


Raw key hit on keyboard.
Parameters:
key Key pressed on keyboard. Returns either a (low-ASCII) key name, or one of the constants
defined in the Key Codes (p. 229) section.
flags TEvent::EKeyFlags (p. 230) mask representing the state of other keys on the keyboard
when this key was hit.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented from TWindow (p. 514).

virtual void TTextEdit::Init (TWindowStyle & style)


Initialize the Window. Called by the system only in Lua initialization.
When you create your own custom window, this is where you put your own custom initialization
that needs to happen before children are created. Fundamental window initialization is handled
in every class by this function, so when you override this function you almost always want to
call your base class to handle base class initialization.
Parameters:
style The Lua style that was in effect when this window was created. This style contains
all parameters specified explicitly for the window as well as parameters defined in the
current style. Parameters set locally override ones in the style.

Reimplemented from TText (p. 438).

virtual bool TTextEdit::OnChar (char key)


Translated character handler.
In UTF-8 mode, this function will only be called if OnUTF8Char() (next page) returns false, or
there is no OnUTF8Char() (next page) handler.
Parameters:
key Key hit on keyboard, along with shift translations.
Returns:
true if message was handled, false to keep searching for a handler.

Playground 4.0.17.1
444 Class and File Reference

See also:
TPlatform::kUTF8Mode (p. 348)

Reimplemented from TWindow (p. 513).

virtual bool TTextEdit::OnUTF8Char (str key)


UTF-8 Translated character handler.
This function is ONLY active when UTF-8 support has been enabled.
Parameters:
key Key hit on keyboard, along with shift translations.
Returns:
true if message was handled, false to keep searching for a handler.
See also:
TPlatform::kUTF8Mode (p. 348)

Reimplemented from TWindow (p. 514).

void TTextEdit::Unregister ()
Tell this TTextEdit (p. 440) that it should unlink itself from its parent modal window and any
related TTextEdit (p. 440) windows in its tab ring.

void TTextEdit::SetPassword (bool bPassword)


Sets the textedit field into password mode, meaning that the displayed text will be all asterisks.
Parameters:
bPassword - true to enable, false to disable

void TTextEdit::SetEditable (bool bEditable)


Set this field to be editable. Enables the cursor, which will display when the TTextEdit (p. 440) is
focused.
Parameters:
bEditable True to make the field editable.

bool TTextEdit::GetEditable ()
Query as to whether this TTextEdit (p. 440) is currently editable.
Returns:
True if editable.

Navigating the Playground SDK


15.69 TTextEdit Class Reference 445

void TTextEdit::UpdateText ()
Update the text in the text field.

void TTextEdit::Backspace ()
Call this function to simulate pressing "Backspace" in the text field.

void TTextEdit::SetIgnoreChars (str ignoreStr)


Any character in ignoreStr will be ignored and not entered into the textedit field.
Parameters:
ignoreStr A string of characters to ignore.

str TTextEdit::GetIgnoreChars ()
Get the characters this TTextEdit (p. 440) is ignoring.
Returns:
A string that contains the characters to ignore.

virtual str TTextEdit::GetText ()


Get the current editable text.
Returns:
The text in the edit box.

Reimplemented from TText (p. 436).

virtual void TTextEdit::SetText (str newText)


Set the current editable text.
Parameters:
newText Text to set to.

Reimplemented from TText (p. 435).

virtual void TTextEdit::Draw ()


Function to draw dynamic elements.
Reimplemented from TText (p. 435).

void TTextEdit::SetMaxLength (uint32_t maxLength)


Set the maximum length of the input field. Current field is not evaluated to test the new length.

Playground 4.0.17.1
446 Class and File Reference

Parameters:
maxLength Maximum number of characters you can type.

void TTextEdit::SetUTF8Mode (bool utf8mode)


Turn on UTF-8 key entry mode. This allows the TTextEdit (p. 440) field to take any arbitrary UTF-8
character. At present only characters that have glyphs will be displayed.
Parameters:
utf8mode True to enable UTF-8 mode.

virtual bool TTextEdit::OnTaskAnimate () [protected]


Animate the cursor flashing.
Returns:
True to continue animating. False to stop.

Reimplemented from TWindow (p. 512).

uint32_t TTextEdit::GetCursor () [protected]


Retrieve the current cursor position.

void TTextEdit::SetCursor (uint32_t cursor) [protected]


Set the current cursor position.
Parameters:
cursor New cursor position.

15.69.5 Member Data Documentation


const int TTextEdit::kCursorFlashMS
Speed of the cursor flash.

const int TTextEdit::kDefaultMaxLength


Default length if none given.

uint32_t TTextEdit::mMaxLength [protected]


Maximum number of characters in a string.

Navigating the Playground SDK


15.70 TTextGraphic Class Reference 447

15.70 TTextGraphic Class Reference


#include <pf/textgraphic.h>

15.70.1 Detailed Description


Formatted text class.
A class that allows you to format text using the following tags:

• <br> Line break

• <p></p> Paragraph

• <b></b> Bold

• <i></i> Italic

• <u></u> Underline

• <center></center> Center

• <left></left> Left Justify

• <right></right> Right Justify

• <tab pos="100"> Move the cursor to a specific offset, in pixels.

• <outline color="ff0000" size=2> Outline text

• <font size="10" color="ff0000"></font> Font characteristics

• <a id=’buttonname’></a> Trigger a button named ’buttonname’ when clicking this text.

• <cursor> Cursor icon

Text can be rendered directly to screen. For text that is automatically rendered in a window, use
the TText (p. 433) class.
Use the static function TTextGraphic::Create (p. 449) to create a new instance of a TTextGraphic
(this page).
See also:
TText (p. 433)

Public Types

• enum EFlags { kHAlignLeft, kHAlignCenter, kHAlignRight, kVAlignTop, kVAlignCen-


ter, kVAlignBottom }

Playground 4.0.17.1
448 Class and File Reference

Public Member Functions


• void SetSpriteRender (bool activate=true)
• void Destroy ()
• void Draw (const TRect &destRect, TReal scale=1.0, int32_t linePadding=0, TReal al-
pha=1.0, TTextureRef target=TTextureRef())
• void Draw (const TVec2 &at, uint32_t height, TReal scale=1.0, int32_t linePadding=0, TReal
alpha=1.0, TTextureRef target=TTextureRef())
• void SetNoBlend ()
• void SetAlphaBlend ()
• uint32_t GetLineCount ()
• void SetStartLine (TReal startLine=0)
• TReal GetStartLine ()
• void GetTextBounds (TRect ∗bounds, TReal scale=1.0F)
• void SetText (str text)
• str GetText () const
• void SetColor (const TColor &color)
• void SetLineHeight (uint32_t newHeight)
• void SetFont (const char ∗fontFilename)
• str GetFont ()
• void SetFlags (uint32_t flags)
• void SetTextRect (uint32_t w, uint32_t h)
• void SetRotation (TReal degrees, uint32_t originX, uint32_t originY)
• const TColor & GetColor () const
• str Pick (const TPoint &point, int32_t linePadding=0)
• bool Rollover (const TPoint ∗pPoint, int32_t linePadding=0)
• uint32_t GetMaxScroll (TReal scale, int32_t linePadding) const

Static Public Member Functions


• static TTextGraphic ∗ Create (str text, uint32_t w, uint32_t h, uint32_t flags=0, const char
∗fontFilename="", uint32_t lineHeight=10, const TColor &textColor=TColor(0, 0, 0, 1))

15.70.2 Member Enumeration Documentation


enum TTextGraphic::EFlags
TTextGraphic (previous page) window child flags.
Enumerator:
kHAlignLeft Align horizontally with the left edge.
kHAlignCenter Align horizontally with the center.
kHAlignRight Align horizontally with the right edge.
kVAlignTop Align vertically with the top.
kVAlignCenter Align vertically with the center.
kVAlignBottom Align vertically with the bottom.

Navigating the Playground SDK


15.70 TTextGraphic Class Reference 449

15.70.3 Member Function Documentation


void TTextGraphic::SetSpriteRender (bool activate = true)
Activate the sprite-render style for TTextGraphic (p. 447). The legacy style for TTextGraphic
(p. 447) is for it to render as if the text surface is a texture, and all alignment happens relative to
this "virtual" texture surface.
In the newer "sprite" render mode, which was created to help support the new TTextSprite (p. 454)
class, rendering is done as if to a constant virtual surface size. This has no effect on left and top
justified text, but centered and right or bottom justified text are drawn relative to the original
surface offsets rather than scaling those offsets along with the text size.
Parameters:
activate True to activate sprite rendering for this TTextGraphic (p. 447).
See also:
TPlatform::kTextGraphicSpriteRender (p. 347)

static TTextGraphic∗ TTextGraphic::Create (str text, uint32_t w, uint32_t h, uint32_t flags


= 0, const char ∗ fontFilename = "", uint32_t lineHeight = 10, const TColor & textColor =
TColor(0, 0, 0, 1))
Create a TTextGraphic (p. 447).
Parameters:
text Initial text for graphic. Can be empty.
w Width of client rectangle. Must be non-zero.
h Height of client rectangle. Must be non-zero.
flags Flags from TTextGraphic::EFlags (opposite)
fontFilename Font name.
lineHeight Font size.
textColor Font color.
Returns:
True on success.

void TTextGraphic::Destroy ()
Call to destroy a TTextGraphic (p. 447). Deletes the object and releases all resources.

void TTextGraphic::Draw (const TRect & destRect, TReal scale = 1.0, int32_t linePadding = 0,
TReal alpha = 1.0, TTextureRef target = TTextureRef())
Draw the text to a rectangle on the screen.
Deprecated

This overload uses an older, more confusing, syntax, and doesn’t allow for sub-pixel place-
ment.

Playground 4.0.17.1
450 Class and File Reference

Must be called between a TRenderer::Begin2d (p. 380)/TRendererEnd2d pair.


Parameters:
destRect Destination rectangle in screen coordinates.
scale Scale factor - useful for zooming effects.
linePadding Additional spacing between text lines.
alpha Alpha multiplier. 1.0 is opaque.
target [optional] Target texture to draw to. Leave as default to draw to current context.

References TRect::GetHeight(), TRect::x1, and TRect::y1.

void TTextGraphic::Draw (const TVec2 & at, uint32_t height, TReal scale = 1.0, int32_t
linePadding = 0, TReal alpha = 1.0, TTextureRef target = TTextureRef())
Draw the text to the screen.
Must be called between a TRenderer::Begin2d (p. 380)/TRendererEnd2d pair.
Parameters:
at Location to draw the text.
height Height of text region in pixels. Used to determine how many lines of text to draw.
scale Scale factor - useful for zooming effects.
linePadding Additional spacing between text lines.
alpha Alpha multiplier. 1.0 is opaque.
target [optional] Target texture to draw to. Leave as default to draw to current context.

void TTextGraphic::SetNoBlend ()
When drawing to an offscreen texture, copy pixels to the texture, instead of alpha blending them.
Does not work with text outlines, since the text and outline need to be blended with each other.
The default state is to blend the pixels into the destination texture, leaving alpha alone. If you call
SetNoBlend() (this page), then pixels will be set directly to the colors and alpha values, so that the
texture can then be used blended with an arbitrary background. TTextGraphic::SetAlphaBlend()
(this page) is similar, but uses a more complex (i.e., slower) blend algorithm that supports text
outlines.
This setting has no effect when drawing to the screen.
See also:
TTextGraphic::SetAlphaBlend() (this page)

void TTextGraphic::SetAlphaBlend ()
When drawing to an offscreen texture, blend pixels into the texture and accumulate alpha. Se-
tAlphaBlend() (this page) uses a more sophisticated (and slower) blend algorithm than TText-
Graphic::SetNoBlend() (this page) that causes it to work correctly with text outlines, as well as
blending the text in with other translucent layers.
This setting has no effect when drawing to the screen.

Navigating the Playground SDK


15.70 TTextGraphic Class Reference 451

See also:
TTextGraphic::SetNoBlend() (opposite)

uint32_t TTextGraphic::GetLineCount ()
Get the number of lines in the text output.
Returns:
Number of lines.

void TTextGraphic::SetStartLine (TReal startLine = 0)


Set the first line in the text output.
Parameters:
startLine Line to display as the first line of text. First line is 0.

TReal TTextGraphic::GetStartLine ()
Get the index of the first line of text output.
Returns:
An index between 0 and GetLineCount() (this page)-1.

void TTextGraphic::GetTextBounds (TRect ∗ bounds, TReal scale = 1.0F)


Get the actual boundary of the rendered text.
Parameters:
bounds A rectangle in client coordinates.
scale The scale you want the text to be at when you query the bounds.

void TTextGraphic::SetText (str text)


Set the current text content. Will return immediately if the text hasn’t changed.
Parameters:
text Text to set.

str TTextGraphic::GetText () const


Get the current text content.
Returns:
A string containing the current text.

Playground 4.0.17.1
452 Class and File Reference

void TTextGraphic::SetColor (const TColor & color)


Set the current text color.
Parameters:
color New text color.

void TTextGraphic::SetLineHeight (uint32_t newHeight)


Set a new line height for this text. Text is re-calculated as to line wraps and tags based on new
height value.
Parameters:
newHeight New text height.

void TTextGraphic::SetFont (const char ∗ fontFilename)


Set the font to be used to draw this text. Can change text bounds.
Parameters:
fontFilename Font to use.

str TTextGraphic::GetFont ()
Get the current font.
Returns:
The current font name.

void TTextGraphic::SetFlags (uint32_t flags)


Set the flags used to render this text.
Parameters:
flags Font alignment flags.

void TTextGraphic::SetTextRect (uint32_t w, uint32_t h)


Change the text rectangle
Parameters:
w Width of client rectangle. Must be non-zero.
h Height of client rectangle. Must be non-zero.

void TTextGraphic::SetRotation (TReal degrees, uint32_t originX, uint32_t originY)


Change the rotation - default is 0 degrees, 0,0 origin

Navigating the Playground SDK


15.70 TTextGraphic Class Reference 453

Parameters:
degrees rotation angle in degrees (not radians because degrees are friendlier)
originX offset from left of text rect to use as center point of rotation
originY offset from top of text rect to use as center point of rotation

const TColor& TTextGraphic::GetColor () const


Get the current text color
Returns:
The current default text color. Note this can be changed by the text markup.

str TTextGraphic::Pick (const TPoint & point, int32_t linePadding = 0)


Pick an anchor record within text. ( <a id="buttonname">link</a> )
Parameters:
point Point to test within text.
linePadding Line padding to use when Picking.
Returns:
A button name to trigger, if one is found. An empty string if no button is found.

bool TTextGraphic::Rollover (const TPoint ∗ pPoint, int32_t linePadding = 0)


Handle rollover state for links.
Parameters:
pPoint Point to test within text, or NULL to clear the state.
linePadding Line padding to use when handling roll-over.
Returns:
True if a rollover link was triggered.

uint32_t TTextGraphic::GetMaxScroll (TReal scale, int32_t linePadding) const


Get the number of lines this text needs to be scrolled to fit in the current text region.
Parameters:
scale Scale of text.
linePadding Line padding.
Returns:
Number of lines to scroll to get to bottom.

Playground 4.0.17.1
454 Class and File Reference

15.71 TTextSprite Class Reference


#include <pf/textsprite.h>
Inheritance diagram for TTextSprite:

TSprite

TTextSprite

15.71.1 Detailed Description


A 2d text sprite object. A sprite that’s primary purpose is to draw text at the sprite’s location. Will
also respect simple rotation and scaling from its matrix, and from the parent’s sprite context. Any
skew or non-symmetric scaling will be ignored, however.
TTextSprites are always stored in the client as TTextSpriteRef–reference counted objects. To de-
stroy a TTextSprite (this page), simply call reset() on the last TTextSpriteRef that refers to that
sprite.
See also:
TSprite (p. 419)

Initialization/Destruction
• static TTextSpriteRef Create (uint32_t width, uint32_t height, uint32_t justify=0, const
char ∗fontFilename="", uint32_t lineHeight=10, const TColor &textColor=TColor(0, 0, 0, 1),
int32_t layer=0)
• virtual ∼TTextSprite ()

Drawing
• virtual void Draw (const TDrawSpec &environmentSpec=TDrawSpec(), int32_t depth=-1)
• void SetNoBlend ()
• void SetAlphaBlend ()

Bounding Rectangles and Hit Tests.


• virtual TRect GetRect (const TDrawSpec &parentContext, int32_t depth=-1)
• const TVec2 & GetOrigin ()
• virtual bool HitTest (const TPoint &at, const TDrawSpec &parentContext, int32_t opacity=-
1, int32_t depth=-1)

Navigating the Playground SDK


15.71 TTextSprite Class Reference 455

Embedded Links
• str Pick (const TPoint &point)
• bool Rollover (const TPoint ∗pPoint)

Text Parameters
• void SetTextRect (uint32_t w, uint32_t h)
• void SetFont (const char ∗fontFilename)
• void SetFlags (uint32_t flags)
• uint32_t GetFlags ()
• void SetColor (const TColor &color)
• const TColor & GetColor () const
• str GetText () const
• void SetText (str text)
• void SetLineHeight (uint32_t newHeight)
• uint32_t GetTextHeight () const
• uint32_t GetTextWidth () const
• TRect GetTextBounds (const TDrawSpec &environmentSpec=TDrawSpec()) const
• uint32_t GetMaxScroll (const TDrawSpec &environmentSpec=TDrawSpec()) const
• uint32_t GetLineCount () const
• void SetStartLine (TReal startLine)
• TReal GetStartLine () const
• void SetLinePadding (int32_t padding)
• void SetDrawingOrigin (const TVec2 &origin)

Public Types
• enum EFlags { kHAlignLeft, kHAlignCenter, kHAlignRight, kVAlignTop, kVAlignCen-
ter, kVAlignBottom }

Protected Member Functions


• TTextSprite (uint32_t w, uint32_t h, int32_t layer)

15.71.2 Member Enumeration Documentation


enum TTextSprite::EFlags
TTextSprite (opposite) text alignment flags.
Enumerator:
kHAlignLeft Align text horizontally with the left edge of the virtual space; text will "grow"
to the right from the drawing location.

Playground 4.0.17.1
456 Class and File Reference

kHAlignCenter Align text horizontally with the center the virtual space; text will be centered
on the drawing location horizontally.
kHAlignRight Align text horizontally with the right edge of the virtual space; text will
"grow" to the left from the drawing location.
kVAlignTop Align text vertically with the top edge of the virtual space; text will "grow" down
from the drawing location.
kVAlignCenter Align text vertically with the center the virtual space; text will be centered on
the drawing location vertically.
kVAlignBottom Align text vertically with the bottom of the virtual space; text will "grow" up
from the drawing location.

15.71.3 Constructor & Destructor Documentation

TTextSprite::TTextSprite (uint32_t w, uint32_t h, int32_t layer) [protected]


Internal Constructor. Use TTextSprite::Create() (this page) to get a new sprite.

virtual TTextSprite::∼TTextSprite ()
Destructor.

15.71.4 Member Function Documentation

static TTextSpriteRef TTextSprite::Create (uint32_t width, uint32_t height, uint32_t justify


= 0, const char ∗ fontFilename = "", uint32_t lineHeight = 10, const TColor & textColor =
TColor(0, 0, 0, 1), int32_t layer = 0)
Allocation of a new text sprite. Construction is restricted to help "encourage" the use of
TTextSpriteRefs to hold your TTextSprites (as well as to encapsulate the TTextSpriteRef creation
pattern).
Parameters:
width The logical width of the text region, in pixels; determines text wrapping.
height The logical height of the text region, in pixels. Determines the maximum height of
drawn text.
justify The alignment of the text; see EFlags (previous page).
fontFilename The handle of the font to use.
lineHeight The initial line height.
textColor The initial color of the text.
layer Initial sprite layer.
Returns:
A newly allocated TTextSprite (p. 454) wrapped in a TTextSpriteRef.
See also:
TSprite::SetLayer (p. 423)

Navigating the Playground SDK


15.71 TTextSprite Class Reference 457

virtual void TTextSprite::Draw (const TDrawSpec & environmentSpec = TDrawSpec(), int32_t


depth = -1)
Draw the sprite and its children.
A common mistake is to assume that the incoming TDrawSpec (p. 223) here is what you use
to position and configure this sprite. The way to position a sprite is to modify its internal
TDrawSpec (p. 223), which you retrieve with GetDrawSpec() (p. 425). The environment pa-
rameter is combined with the local TDrawSpec (p. 223) to determine the actual position of the
sprite, though it only inherits those features marked in TDrawSpec (p. 223) as inheritable. See
TDrawSpec::GetRelative() (p. 224) for more details.
Parameters:
environmentSpec The ’parent’ or environment drawspec–the frame of reference that this
sprite is to be rendered in. In general you shouldn’t pass anything in for this parame-
ter and instead should modify the position of the sprite using its GetDrawSpec() (p. 425)
member.

Defaults to a default-constructed TDrawSpec (p. 223). See TDrawSpec (p. 223) for more details
on what is inherited.
Parameters:
depth How many generations of children to draw; -1 means all children.
See also:
TDrawSpec (p. 223)

Reimplemented from TSprite (p. 422).

void TTextSprite::SetNoBlend ()
When drawing to an offscreen texture, copy pixels to the texture, instead of alpha blending them.
Does not work with text outlines, since the text and outline need to be blended with each other.
The default state is to blend the pixels into the destination texture, leaving alpha alone. If you call
SetNoBlend() (this page), then pixels will be set directly to the colors and alpha values, so that the
texture can then be used blended with an arbitrary background. TTextGraphic::SetAlphaBlend()
(p. 450) is similar, but uses a more complex (i.e., slower) blend algorithm that supports text out-
lines.
This setting has no effect when drawing to the screen.
See also:
TTextSprite::SetAlphaBlend() (this page)

void TTextSprite::SetAlphaBlend ()
When drawing to an offscreen texture, blend pixels into the texture and accumulate alpha. Se-
tAlphaBlend() (this page) uses a more sophisticated (and slower) blend algorithm than TText-
Graphic::SetNoBlend() (p. 450) that causes it to work correctly with text outlines, as well as blend-

Playground 4.0.17.1
458 Class and File Reference

ing the text in with other translucent layers.


This setting has no effect when drawing to the screen.
See also:
TTextSprite::SetNoBlend() (previous page)

virtual TRect TTextSprite::GetRect (const TDrawSpec & parentContext, int32_t depth = -1)
Get the bounding rectangle of this sprite.
Parameters:
parentContext The parent context to test within—where is this sprite being drawn, and with
what matrix? Alpha and color information is ignored.
depth Depth of children to test
Returns:
Rectangle that includes this sprite.

Reimplemented from TSprite (p. 424).

const TVec2& TTextSprite::GetOrigin ()


Get the logical origin of the text in the virtual text area.
Returns:
The point in the virtual text rectangle relative to which text will grow.

virtual bool TTextSprite::HitTest (const TPoint & at, const TDrawSpec & parentContext,
int32_t opacity = -1, int32_t depth = -1)
Test to see if a point is within our sprite.
Parameters:
at Point to test.
parentContext The parent context to test within–where is this sprite being drawn, and with
what matrix? Alpha and color information is ignored.
opacity Level of opacity to test for; -1 for a simple bounding box test, or 0-255 for alpha color
value, where 0 is transparent (and will therefore always succeed).
depth Depth of children to test. Zero means only test this sprite. -1 means test
Returns:
true if point hits us.

Reimplemented from TSprite (p. 424).

str TTextSprite::Pick (const TPoint & point)


Pick an anchor record within text. ( <a id="buttonname">link</a> )

Navigating the Playground SDK


15.71 TTextSprite Class Reference 459

Parameters:
point Point to test within text.
Returns:
A button name to trigger, if one is found. An empty string if no button is found.

bool TTextSprite::Rollover (const TPoint ∗ pPoint)


Handle rollover state for links.
Parameters:
pPoint Point to test within text, or NULL to clear the state.
Returns:
True if a rollover link was triggered.

void TTextSprite::SetTextRect (uint32_t w, uint32_t h)


Set the virtual text rectangle; used for determining text wrapping and vertical alignment.
Parameters:
w Width of virtual text region, in pixels.
h Height of virtual text region, in pixels.

void TTextSprite::SetFont (const char ∗ fontFilename)


Set the font to be used to draw this text. Can change text bounds.
Parameters:
fontFilename Font to use.

void TTextSprite::SetFlags (uint32_t flags)


Set the flags used to render this text.
Parameters:
flags Font alignment flags.

uint32_t TTextSprite::GetFlags ()
Get the current sprite flags.
Returns:
Current flags.

Playground 4.0.17.1
460 Class and File Reference

void TTextSprite::SetColor (const TColor & color)


Set the default text color.
Parameters:
color New text color.

const TColor& TTextSprite::GetColor () const


Get the default text color.
Returns:
Text color.

str TTextSprite::GetText () const


Get the current text of the sprite.
Returns:
Current text.

void TTextSprite::SetText (str text)


Set the current text of the sprite. Will return immediately if the text hasn’t changed.
Parameters:
text New text.

void TTextSprite::SetLineHeight (uint32_t newHeight)


Set the rendered height of a line of text in pixels; this changes the font size. Text line wraps are
re-calculated, and tag locations are adjusted, based on the new size of the font.
Parameters:
newHeight New height in pixels.

uint32_t TTextSprite::GetTextHeight () const


Query the height of the virtual text region.
Returns:
The height text region width.

uint32_t TTextSprite::GetTextWidth () const


Query the width of the virtual text region.

Navigating the Playground SDK


15.71 TTextSprite Class Reference 461

Returns:
The virtual text region width.

uint32_t TTextSprite::GetMaxScroll (const TDrawSpec & environmentSpec = TDrawSpec())


const
Get the number of lines this text needs to be scrolled so that the final line fits in the current text
region.
Parameters:
environmentSpec The parent environment of this sprite; typically empty. Only relevant if a
parent sprite contains any scaling.
Returns:
Number of lines to scroll to get to bottom.

uint32_t TTextSprite::GetLineCount () const


Get the number of lines in the text output.
Returns:
Number of lines.

void TTextSprite::SetStartLine (TReal startLine)


Set the first line in the text output.
Parameters:
startLine Line to display as the first line of text. First line is 0.

TReal TTextSprite::GetStartLine () const


Get the index of the first line of text output.
Returns:
An index between 0 and GetLineCount() (this page)-1.

void TTextSprite::SetLinePadding (int32_t padding)


Set any additional padding between text lines. If you want "double spaced" text, you’d put the
line height in this field.
Parameters:
padding The number of pixels to add between lines. Can be negative to squeeze text lines
together.

Playground 4.0.17.1
462 Class and File Reference

void TTextSprite::SetDrawingOrigin (const TVec2 & origin)


Set the current drawing origin. This value is overwritten internally if you call SetTextRect() (p. 459)
or SetFlags() (p. 459).
Rotation is performed around this point, and scaling is performed relative to this point.
The default value for the origin depends on the horizontal and vertical alignment flags. When
"center" is used, it defaults to the center on that axis; when one side or the other is used, the origin
will be aligned with that side.
So left-top justified text will default to an origin of (0,0), while right-bottom justified text will
default to (width,height). Fully centered text will default to (width/2,height/2).
Parameters:
origin The point on the virtual text surface to draw relative to. Typically this point is between
0,0 and width,height of your virtual drawing surface, but that isn’t required.

Navigating the Playground SDK


15.72 TTexture Class Reference 463

15.72 TTexture Class Reference


#include <pf/texture.h>
Inheritance diagram for TTexture:

TAsset

TTexture

TAnimatedTexture

15.72.1 Detailed Description

This class encapsulates the concept of a texture.


A TTexture (this page) can be used to:

• Texture a 3d object on the screen

• Draw a sprite

• Draw a screen widget (background, button, etc.)

• Be a target for 3d rendering (which will restrict it to being a 2d blit source)

Texture size is limited to 1024x1024 for textures that are in video RAM (i.e., any texture that isn’t
created as "slow").
Additionally, some textures are created from bitmaps, and those bitmaps can be dynamically
MIPMAPped. Bitmaps can be read from JPG or PNG files, and the PNG files will correctly read
the transparency information, if present.
The image extension can be omitted to allow the decision between JPG and PNG to be made on a
an image-by-image basis without needing to change code.

Drawing Methods

• virtual void DrawSprite (TReal x, TReal y, TReal alpha=1, TReal scale=1, TReal rotRad=0,
uint32_t flags=0)
• virtual void DrawSprite (const TDrawSpec &drawSpec)
• virtual void CopyPixels (int32_t x, int32_t y, const TRect ∗sourceRect=NULL, TTextureRef
_dst=TTextureRef())

Playground 4.0.17.1
464 Class and File Reference

Surface access.

• bool Lock (TColor32 ∗∗data, uint32_t ∗pixelPitch)


• void Unlock ()

Information Query.

• virtual uint32_t GetWidth ()


• virtual uint32_t GetHeight ()
• TPoint GetInternalSize ()
• str GetName ()
• bool IsSimple ()
• bool IsSlow ()
• bool HasAlpha ()
• void Clear ()
• bool Save (str fileName, TReal quality=1.0f)
• TTextureRef GetRef ()

Factory Methods

• static TTextureRef Get (str assetName, uint32_t flags=eDefaultAlpha)


• static TTextureRef GetMerged (str colorAssetName, str alphaAssetName, uint32_t
flags=eDefaultAlpha)
• static TTextureRef Create (uint32_t width, uint32_t height, bool alpha)
• static TTextureRef GetSimple (str assetName)
• static TTextureRef CreateSimple (uint32_t width, uint32_t height, bool slow=false, bool al-
pha=false)

Public Types

• enum ETextureCreateFlags { eDefaultAlpha, eGenerateMipmaps, eForceAlpha,


eForceNoAlpha }

Public Attributes

• TTextureData ∗ mData

Static Protected Member Functions

• static TTextureRef InternalNew (str handle="")

Navigating the Playground SDK


15.72 TTexture Class Reference 465

15.72.2 Member Enumeration Documentation


enum TTexture::ETextureCreateFlags
Texture loading flags used with TTexture::Get (this page) and TTexture::GetMerged (this page).
Enumerator:
eDefaultAlpha Select alpha based on the image content. In the case of a PNG image that
contains alpha information, alpha will be enabled; otherwise it will be disabled.
eGenerateMipmaps Generate MIPMAPs for the image.
eForceAlpha Force the image to have an alpha channel.
eForceNoAlpha Force the image to not have an alpha channel.

15.72.3 Member Function Documentation


static TTextureRef TTexture::Get (str assetName, uint32_t flags = eDefaultAlpha)
Get a texture from a handle with optional alpha information and optional auto-generated
mipmaps. The handle refers to a file in the assets folder.
When passing in an assetName, flags can be passed following a "?" and seperated by commas.
Example "texture.png?slow"
Maximum texture size for non-slow textures is 1024x1024.
Available flags are:

• slow - Load this texture into slow system RAM. Allows for non-square, non-power-of-two
textures, as well as textures larger than 1024x1024. This flag implies "simple"–no direct draw-
ing from this surface is allowed.

• simple - Create this texture as a simple surface. See GetSimple() (next page) for an explana-
tion.

• alpha - Create this texture with an alpha layer.

• mipmap - Create this texture with mipmaps.


Parameters:
assetName Name of the asset. File extension (.jpg, .png) is not necessary.
flags ETextureCreateFlags
Returns:
A TTextureRef to the texture.

static TTextureRef TTexture::GetMerged (str colorAssetName, str alphaAssetName, uint32_t


flags = eDefaultAlpha)
Get a texture from 2 assets, one which specifies the color map and one which specifies the alpha
map. So that the alpha map can be a highly compressed image, the alpha value will be pulled
from the "red" channel of the alpha asset.

Playground 4.0.17.1
466 Class and File Reference

See TTexture::Get() (previous page) for information on passing flags inside of asset names.
Note that eForceNoAlpha has no effect, since the point of this function is to add an alpha channel.
Warning:

The two assets must be the same dimensions, or the alpha map will not show up correctly.
Parameters:
colorAssetName Name of the asset used for the color map.File extension (.jpg, .png) is not
necessary. Supports "?" flags like TTexture::Get() (previous page), but only include those
options on the colorAssetName parameter.
alphaAssetName Name of the asset used for the alpha map. File extension (.jpg, .png) is not
necessary. Do not use "?" flags on alphaAssetName.
flags ETextureCreateFlags
Returns:
A TTextureRef to the texture.

static TTextureRef TTexture::Create (uint32_t width, uint32_t height, bool alpha)


Create a texture at a particular size.
Maximum texture size for a created texture is 1024x1024.
Warning:

Cannot be called within a BeginDraw/EndDraw or BeginRenderTarget/EndRenderTarget


block.
Parameters:
width Width
height Height
alpha Create with alpha channel
Returns:
A TTextureRef to the texture.

static TTextureRef TTexture::GetSimple (str assetName)


Get a simple texture from an asset name
Simple textures are not usable as 3d textures, and in fact can only be copied with CopyPixels()
(p. 468). Advantages include speed and decreased memory usage: A "Simple" texture can be
created without the common restrictions of 3d textures, which often need to be powers of two in
size and square.
Maximum texture size for non-slow textures is 1024x1024; slow textures have problems with either
dimension larger than 4096.
Look in the documentation for TTexture::Get (previous page) for information on flags that can be
appended to the asset name.

Navigating the Playground SDK


15.72 TTexture Class Reference 467

Parameters:
assetName Name of the asset to load or acquire a reference to. File extension (.jpg, .png) is
not necessary.
See also:
TTexture::Get() (p. 465)
Returns:
A TTextureRef to the texture.

static TTextureRef TTexture::CreateSimple (uint32_t width, uint32_t height, bool slow =


false, bool alpha = false)
Create a simple texture surface. See GetSimple for more information on "simple" textures.
Maximum texture size for non-slow textures is 1024x1024; slow textures have problems with either
dimension larger than 4096.
Warning:

Cannot be called within a BeginDraw/EndDraw or BeginRenderTarget/EndRenderTarget


block.
Parameters:
width Width
height Height
slow True to create a slow (RAM based) texture.
alpha True to have this texture include alpha.
See also:
TTexture::GetSimple (opposite)
Returns:
A TTextureRef to the created texture.

virtual void TTexture::DrawSprite (TReal x, TReal y, TReal alpha = 1, TReal scale = 1, TReal
rotRad = 0, uint32_t flags = 0)
Draw a normal texture to a render target surface as a sprite. This draws a texture with optional
rotation and scaling. Only capable of drawing an entire surface–not a sub-rectangle. See TTex-
ture::DrawSprite(const TDrawSpec&) (next page) for more drawing control.
Will draw the sprite within the currently active viewport. X and Y are relative to the upper left
corner of the current viewport.
DrawSprite can be called inside TWindow::Draw() (p. 503) or a BeginRenderTarget/EndRender-
Target block.
Parameters:
x X of Center.

Playground 4.0.17.1
468 Class and File Reference

y Y of Center.
alpha Alpha to apply to the entire texture. Set to a negative value to entirely disable alpha
during blit, including alpha within the source TTexture (p. 463).
scale Scaling to apply to the texture. 1.0 is no scaling.
rotRad Rotation in radians around center point.
flags Define how textures are drawn. Use ETextureDrawFlags for the flags. Default behavior
is eDefaultDraw.

Reimplemented in TAnimatedTexture (p. 185).

virtual void TTexture::DrawSprite (const TDrawSpec & drawSpec)

Draw a normal texture to a render target surface or backbuffer as a sprite. Uses the TDrawSpec to
decide where to put the texture and how to draw it. See TDrawSpec (p. 223) for details.
Will draw the sprite within the currently active viewport. TDrawSpec position is relative to the
upper left corner of the current viewport.
DrawSprite can be called inside TWindow::Draw() (p. 503) or a TRenderer::BeginRenderTarget()
(p. 379)/EndRenderTarget block.
Parameters:
drawSpec The TDrawSpec to use to draw the sprite.

Reimplemented in TAnimatedTexture (p. 186).

virtual void TTexture::CopyPixels (int32_t x, int32_t y, const TRect ∗ sourceRect = NULL,


TTextureRef _dst = TTextureRef())

Draw a normal or simple texture to any target TTexture (p. 463) surface with the same alpha as
this surface. In other words, CopyPixels can go from an alpha surface to another alpha surface, or
to a non-alpha to another non-alpha surface, but not between the two.
There are no restrictions on the blit source rectangle or the destination of the blit within the target
surface.
CopyPixels() (this page) does not respect alpha in its copy; it performs a bitwise, opaque copy
only.
Unlike the other texture calls, CopyPixels() (this page) can be called outside of a TWin-
dow::Draw() (p. 503) or a BeginRenderTarget/EndRenderTarget block.
Parameters:
x Left side of resulting rectangle.
y Top edge of resulting rectangle.
sourceRect Source rectangle to blit. NULL to blit the entire surface.
_dst Destination texture. NULL to draw to back buffer.

Reimplemented in TAnimatedTexture (p. 185).

Navigating the Playground SDK


15.72 TTexture Class Reference 469

bool TTexture::Lock (TColor32 ∗∗ data, uint32_t ∗ pixelPitch)


Lock a surface for reading and writing pixel data.
Surface will be stored in 32 bit pixels, in the binary order defined by TColor32 (p. 218).
Parameters:
data [out] Receives a pointer to the locked data.
pixelPitch Number of pixels to add to a pointer to advance one row.
Returns:
True on success.

void TTexture::Unlock ()
Unlock a surface

virtual uint32_t TTexture::GetWidth ()


Get the width of the texture. This gets the width of the texture as requested at creation or load;
the actual internal width of the texture may vary. If you’re using this texture as a source for
TRenderer::DrawVertices (p. 376), see GetInternalSize() (this page).
Returns:
Width of the texture in pixels.

Reimplemented in TAnimatedTexture (p. 189).

virtual uint32_t TTexture::GetHeight ()


Get the height of the texture. This gets the height of the texture as requested at creation or load;
the actual internal height of the texture may vary. If you’re using this texture as a source for
TRenderer::DrawVertices (p. 376), see GetInternalSize() (this page).
Returns:
Height of the texture in pixels.

Reimplemented in TAnimatedTexture (p. 189).

TPoint TTexture::GetInternalSize ()
Gets the internal width and height of the texture in pixels, rather than the requested width and
height. Relevant if you’re using the texture as a texture source for TRenderer::DrawVertices
(p. 376).
The texture coordinates that you set in vertices that refer to this texture need to be calculated
based on the internal representation size, and not the "logical" size that GetWidth() (this page)
and GetHeight() (this page) return. In other words, if the original width is 800, and the internal
width is 1024, then your U coordinate for the right edge would be 800.0F/1024.0F.

Playground 4.0.17.1
470 Class and File Reference

If your textures are always powers of two and square in size (equal width and height), GetInter-
nalSize should always return the same values as GetWidth() (previous page) and GetHeight()
(previous page).
Returns:
A point with width and height of the internal texture size, in pixels.

str TTexture::GetName ()
Get the name of the texture.
Returns:
The handle of the image used to create the texture, along with any alpha texture handle.

bool TTexture::IsSimple ()
Query whether this texture is a "simple" type; simple textures can not be used in DrawSprite()
(p. 467), but can be locked and can be used in CopyPixels() (p. 468).
See also:
TTexture::GetSimple (p. 466)
Returns:
True if simple

bool TTexture::IsSlow ()
Query whether this texture is a "slow" texture, i.e. one that’s been allocated in system RAM.
Returns:
True if slow.

bool TTexture::HasAlpha ()
Query whether this texture has an alpha channel.
Returns:
True if the texture has an alpha channel, false otherwise.

void TTexture::Clear ()
Clear the texture to black and transparent alpha.

bool TTexture::Save (str fileName, TReal quality = 1.0f)


Save the texture to a file.

Navigating the Playground SDK


15.72 TTexture Class Reference 471

Parameters:
fileName path of file to create including extension that defines what format to save the file as.
Currently supported file extensions are: ".jpg" and ".png".
quality For file formats that use image compression, this specifies what level of compression
to use (1.0 means highest quality, 0.0 means lowest quality) .png files currently ignore
the quality parameterT
Returns:
true if file was successfully saved, false otherwise.

TTextureRef TTexture::GetRef ()
Get a shared pointer (TTextureRef) to this texture.
Returns:
A TTextureRef that shares ownership with other Refs to this texture.

Reimplemented from TAsset (p. 195).


Reimplemented in TAnimatedTexture (p. 189).

static TTextureRef TTexture::InternalNew (str handle = "") [protected]


Internal function to create a TTexture (p. 463).
Parameters:
handle (optional) Handle of asset to add to asset manager. Empty to create a unique TTexture
(p. 463).
Returns:
A TTextureRef to the new texture.

15.72.4 Member Data Documentation


TTextureData∗ TTexture::mData
Internal implementation data.

Playground 4.0.17.1
472 Class and File Reference

15.73 TTransformedLitVert Struct Reference


#include <pf/vertexset.h>

15.73.1 Detailed Description


Transformed and lit vertex.

Public Attributes
• TVec3 pos
• TReal rhw
• TColor32 color
• TColor32 specular
• TVec2 uv

15.73.2 Member Data Documentation


TVec3 TTransformedLitVert::pos
Position in screen coordinates.

TReal TTransformedLitVert::rhw
RESERVED; must set to 0.5F.

TColor32 TTransformedLitVert::color
Vertex color.

TColor32 TTransformedLitVert::specular
Vertex specular component.

TVec2 TTransformedLitVert::uv
Vertex texture coordinate.

Navigating the Playground SDK


15.74 TURect Class Reference 473

15.74 TURect Class Reference


#include <pf/rect.h>
Inheritance diagram for TURect:

TRect

TURect

15.74.1 Detailed Description


A TRect (p. 364) that’s forced to be unsigned at all times.
Will ASSERT in debug builds if you construct a TURect (this page) with a TRect (p. 364) that has
negative values.
See also:
TRect (p. 364)

Public Member Functions


• TURect ()
• TURect (uint32_t X1, uint32_t Y1, uint32_t X2, uint32_t Y2)
• TURect (const TRect &rect)
• TURect & operator= (const TRect &rect)
• TURect & operator= (const TURect &rect)
• TURect (const TPoint &topLeft, const TPoint &bottomRight)

15.74.2 Constructor & Destructor Documentation


TURect::TURect ()
Default constructor.

TURect::TURect (uint32_t X1, uint32_t Y1, uint32_t X2, uint32_t Y2)


Construct from four values.
Parameters:
X1 Left edge.
Y1 Top edge.
X2 One past right edge.
Y2 One past bottom edge.

Playground 4.0.17.1
474 Class and File Reference

TURect::TURect (const TRect & rect)


Construct from a TRect (p. 364)
Parameters:
rect Source TRect (p. 364) to construct from.

TURect::TURect (const TPoint & topLeft, const TPoint & bottomRight)


Construct a TRect (p. 364) from two points.
Parameters:
topLeft Upper left corner of the TRect (p. 364).
bottomRight Lower right corner of the TRect (p. 364).
See also:
TPoint (p. 350)

15.74.3 Member Function Documentation


TURect& TURect::operator= (const TRect & rect)
Assign from a TRect (p. 364).
Parameters:
rect Source rectangle.

TURect& TURect::operator= (const TURect & rect)


Assign from a TURect (previous page).
Parameters:
rect Source rectangle.

Navigating the Playground SDK


15.75 TVec2 Class Reference 475

15.75 TVec2 Class Reference


#include <pf/vec.h>

15.75.1 Detailed Description


A 2d vector class.
This class is a POD (plain-old-data) type with public member data.

Public Member Functions


• TVec2 ()
• TVec2 (TReal X, TReal Y)
• TVec2 (const TVec2 &rhs)
• TVec2 (const TVec3 &rhs)
• TVec2 & operator= (const TVec2 &rhs)
• TReal & operator[ ] (TIndex i)
• const TReal & operator[ ] (TIndex i) const
• TIndex Dim () const
• TReal LengthSquared () const
• TReal Length () const
• TVec2 & operator+= (const TVec2 &rhs)
• TVec2 & operator-= (const TVec2 &rhs)
• TVec2 & operator∗= (TReal s)
• TVec2 & operator/= (TReal s)
• TVec2 & Normalize ()
• TVec2 operator- () const

Public Attributes
• TReal x
• TReal y

Related Functions
(Note that these are not member functions.)

• bool operator== (const TVec2 &lhs, const TVec2 &rhs)


• bool operator!= (const TVec2 &lhs, const TVec2 &rhs)
• TVec2 operator+ (const TVec2 &lhs, const TVec2 &rhs)
• TVec2 operator- (const TVec2 &lhs, const TVec2 &rhs)
• TVec2 operator∗ (const TVec2 &lhs, TReal s)

Playground 4.0.17.1
476 Class and File Reference

• TVec2 operator∗ (TReal s, const TVec2 &rhs)


• TVec2 operator/ (const TVec2 &lhs, TReal s)
• TReal DotProduct (const TVec2 &lhs, const TVec2 &rhs)

15.75.2 Constructor & Destructor Documentation


TVec2::TVec2 ()
Constructor.

TVec2::TVec2 (TReal X, TReal Y)


Initializing constructor.
Parameters:
X X value
Y Y value

TVec2::TVec2 (const TVec2 & rhs)


Copy construction.

TVec2::TVec2 (const TVec3 & rhs) [explicit]


Conversion from a TVec3 (p. 481).
Parameters:
rhs Source TVec3 (p. 481). Constructor drops the z parameter.

15.75.3 Member Function Documentation


TVec2& TVec2::operator= (const TVec2 & rhs)
Assignment.
Returns:
A reference to this.

TReal& TVec2::operator[ ] (TIndex i)


Member accessor.
Parameters:
i Zero-based index.
Returns:
A reference to the i’th member.

Navigating the Playground SDK


15.75 TVec2 Class Reference 477

const TReal& TVec2::operator[ ] (TIndex i) const


Member accessor.
Parameters:
i Zero-based index.
Returns:
A reference to the i’th member.

TIndex TVec2::Dim () const


The dimension of this vector (2).
Returns:
2

TReal TVec2::LengthSquared () const


The length of this vector squared.
Returns:
x2 + y2

TReal TVec2::Length () const


The length of this vector.
Returns:
p
x2 + y2

TVec2& TVec2::operator+= (const TVec2 & rhs)


Addition-assignment operator.
Returns:
A reference to this.

TVec2& TVec2::operator-= (const TVec2 & rhs)


Subtraction-assignment operator.
Returns:
A reference to this.

TVec2& TVec2::operator∗= (TReal s)


Scaling operator.

Playground 4.0.17.1
478 Class and File Reference

Parameters:
s Scale factor.
Returns:
A reference to this, scaled as (x ∗ s, y ∗ s)

TVec2& TVec2::operator/= (TReal s)


Scaling operator.
Parameters:
s Scale divisor.
Returns:
A reference to this, scaled as (x/s, y/s)

TVec2& TVec2::Normalize ()
Normalize this vector.
Changes this vector to (x/Length(), y/Length())
Returns:
A reference to this.

TVec2 TVec2::operator- () const


Unary negation.
Returns:
(−x, −y)

15.75.4 Friends And Related Function Documentation


bool operator== (const TVec2 & lhs, const TVec2 & rhs) [related]
Equality operator.
Returns:
True if equal.

bool operator!= (const TVec2 & lhs, const TVec2 & rhs) [related]
Inequality operator.
Returns:
True if not equal.

Navigating the Playground SDK


15.75 TVec2 Class Reference 479

TVec2 operator+ (const TVec2 & lhs, const TVec2 & rhs) [related]
Addition operator.
Returns:
(x1 + x2 , y1 + y2 )

TVec2 operator- (const TVec2 & lhs, const TVec2 & rhs) [related]
Subtraction operator.
Returns:
(x1 − x2 , y1 − y2 )

TVec2 operator∗ (const TVec2 & lhs, TReal s) [related]


Scaling operator.
Returns:
(x ∗ s, y ∗ s)

TVec2 operator∗ (TReal s, const TVec2 & rhs) [related]


Scaling operator.
Returns:
(x ∗ s, y ∗ s)

TVec2 operator/ (const TVec2 & lhs, TReal s) [related]


Scaling operator.
Returns:
(x/s, y/s)

TReal DotProduct (const TVec2 & lhs, const TVec2 & rhs) [related]
Dot product function.
Parameters:
lhs Left-hand side of the dot product.
rhs Right-hand side of the dot product.
Returns:
The dot product of the two vectors: (x1 ∗ x2 + y1 ∗ y2).

Playground 4.0.17.1
480 Class and File Reference

15.75.5 Member Data Documentation


TReal TVec2::x
Public X dimension.

TReal TVec2::y
Public Y dimension.

Navigating the Playground SDK


15.76 TVec3 Class Reference 481

15.76 TVec3 Class Reference


#include <pf/vec.h>

15.76.1 Detailed Description


A 3d vector class.
This class is a POD (plain-old-data) type with public member data.

Public Member Functions


• TVec3 ()
• TVec3 (TReal X, TReal Y, TReal Z)
• TVec3 (const TVec2 &rhs, TReal z=0)
• TVec3 (const TVec4 &rhs)
• TVec3 (const TVec3 &rhs)
• TVec3 & operator= (const TVec3 &rhs)
• TReal & operator[ ] (TIndex i)
• const TReal & operator[ ] (TIndex i) const
• TIndex Dim () const
• TReal LengthSquared () const
• TReal Length () const
• TVec3 & Normalize ()
• TVec3 & operator+= (const TVec3 &rhs)
• TVec3 & operator-= (const TVec3 &rhs)
• TVec3 & operator∗= (TReal s)
• TVec3 & operator/= (TReal rhs)
• TVec3 operator- () const

Public Attributes
• TReal x
• TReal y
• TReal z

Related Functions
(Note that these are not member functions.)

• bool operator== (const TVec3 &lhs, const TVec3 &rhs)


• bool operator!= (const TVec3 &lhs, const TVec3 &rhs)
• TVec3 operator+ (const TVec3 &lhs, const TVec3 &rhs)

Playground 4.0.17.1
482 Class and File Reference

• TVec3 operator- (const TVec3 &lhs, const TVec3 &rhs)


• TVec3 operator∗ (const TVec3 &lhs, TReal s)
• TVec3 operator∗ (TReal s, const TVec3 &rhs)
• TVec3 operator/ (const TVec3 &lhs, TReal s)
• TReal DotProduct (const TVec3 &lhs, const TVec3 &rhs)
• TVec3 CrossProduct (const TVec3 &lhs, const TVec3 &rhs)
• bool IntersectTriangle (const TVec3 &pvOrig, const TVec3 &pvDir, const TVec3 &pv0, const
TVec3 &pv1, const TVec3 &pv2, TReal ∗pfDist, TVec3 ∗pvHit)

15.76.2 Constructor & Destructor Documentation

TVec3::TVec3 ()
Constructor.

TVec3::TVec3 (TReal X, TReal Y, TReal Z)


Initializing constructor.
Parameters:
X X value.
Y Y value.
Z Z value.

TVec3::TVec3 (const TVec2 & rhs, TReal z = 0) [explicit]


Conversion constructor.
Parameters:
rhs TVec2 (p. 475) to convert from.
z Additional z component to add; defaults to zero.

TVec3::TVec3 (const TVec4 & rhs) [explicit]


Conversion constructor.
Parameters:
rhs TVec4 (p. 487) to convert from. Drops the w component.

TVec3::TVec3 (const TVec3 & rhs)


Copy construction.

Navigating the Playground SDK


15.76 TVec3 Class Reference 483

15.76.3 Member Function Documentation


TVec3& TVec3::operator= (const TVec3 & rhs)
Assignment.
Returns:
A reference to this.

TReal& TVec3::operator[ ] (TIndex i)


Member accessor.
Parameters:
i Zero-based index.
Returns:
A reference to the i’th member.

const TReal& TVec3::operator[ ] (TIndex i) const


Member accessor.
Parameters:
i Zero-based index.
Returns:
A reference to the i’th member.

TIndex TVec3::Dim () const


The dimension of this vector (3).
Returns:
3

TReal TVec3::LengthSquared () const


The length of this vector squared.
Returns:
x2 + y2 + z2

TReal TVec3::Length () const


The length of this vector.
Returns:
p
x2 + y2 + z2

Playground 4.0.17.1
484 Class and File Reference

TVec3& TVec3::Normalize ()
Normalize this vector.
Changes this vector to (x/Length(), y/Length(), z/Length())
Returns:
A reference to this.

TVec3& TVec3::operator+= (const TVec3 & rhs)


Addition-assignment operator.
Returns:
A reference to this.

TVec3& TVec3::operator-= (const TVec3 & rhs)


Subtraction-assignment operator.
Returns:
A reference to this.

TVec3& TVec3::operator∗= (TReal s)


Scaling operator.
Parameters:
s Scale factor.
Returns:
A reference to this, scaled as (x ∗ s, y ∗ s, z ∗ s)

TVec3& TVec3::operator/= (TReal rhs)


Scaling operator.
Parameters:
s Scale divisor.
Returns:
A reference to this, scaled as (x/s, y/s, z/s)

TVec3 TVec3::operator- () const


Unary negation.
Returns:
(−x, −y, −z)

Navigating the Playground SDK


15.76 TVec3 Class Reference 485

15.76.4 Friends And Related Function Documentation


bool operator== (const TVec3 & lhs, const TVec3 & rhs) [related]
Equality operator.
Returns:
True if equal.

bool operator!= (const TVec3 & lhs, const TVec3 & rhs) [related]
Inequality operator.
Returns:
True if not equal.

TVec3 operator+ (const TVec3 & lhs, const TVec3 & rhs) [related]
Addition operator.
Returns:
(x1 + x2 , y1 + y2 , z1 + z2 )

TVec3 operator- (const TVec3 & lhs, const TVec3 & rhs) [related]
Subtraction operator.
Returns:
(x1 − x2 , y1 − y2 , z1 − z2 )

TVec3 operator∗ (const TVec3 & lhs, TReal s) [related]


Scaling operator.
Returns:
(x ∗ s, y ∗ s, z ∗ s)

TVec3 operator∗ (TReal s, const TVec3 & rhs) [related]


Scaling operator.
Returns:
(x ∗ s, y ∗ s, z ∗ s)

TVec3 operator/ (const TVec3 & lhs, TReal s) [related]


Scaling operator.

Playground 4.0.17.1
486 Class and File Reference

Returns:
(x/s, y/s, z/s)

TReal DotProduct (const TVec3 & lhs, const TVec3 & rhs) [related]
Dot product function.
Returns:
The dot product of the two vectors: (x1 ∗ x2 + y1 ∗ y2 + z1 ∗ z2 ).

TVec3 CrossProduct (const TVec3 & lhs, const TVec3 & rhs) [related]
Cross product function.
Returns:
The cross product of the two vectors.

bool IntersectTriangle (const TVec3 & pvOrig, const TVec3 & pvDir, const TVec3 & pv0, const
TVec3 & pv1, const TVec3 & pv2, TReal ∗ pfDist, TVec3 ∗ pvHit) [related]
Detects if a ray intersects a triangle.
Parameters:
← pvOrig Points to ray origin.
← pvDir Points to ray direction from origin.
← pv0 Points to triangle vertex0.
← pv1 Points to triangle vertex1.
← pv2 Points to triangle vertex2.
→ pfDist Points to where the distance from vOrig to the point of intersection gets stored.
→ pvHit Points to where the actual point of intersection gets stored.
Returns:
true if ray intersects triangle.

15.76.5 Member Data Documentation


TReal TVec3::x
X dimension.

TReal TVec3::y
Y dimension.

TReal TVec3::z
Z dimension.

Navigating the Playground SDK


15.77 TVec4 Class Reference 487

15.77 TVec4 Class Reference


#include <pf/vec.h>

15.77.1 Detailed Description


A 4d vector class.
This class is a POD with public member data.

Public Member Functions


• TVec4 ()
• TVec4 (TReal X, TReal Y, TReal Z, TReal W)
• TVec4 (const TVec3 &rhs, TReal W=0.0)
• TVec4 (const TVec4 &rhs)
• TVec4 & operator= (const TVec4 &rhs)
• TReal & operator[ ] (TIndex i)
• const TReal & operator[ ] (TIndex i) const
• TIndex Dim () const
• TReal LengthSquared () const
• TReal Length () const
• TVec4 & Normalize ()
• TVec4 & operator+= (const TVec4 &rhs)
• TVec4 & operator-= (const TVec4 &rhs)
• TVec4 & operator∗= (TReal rhs)
• TVec4 & operator/= (TReal rhs)
• TVec4 operator- () const

Public Attributes
• TReal x
• TReal y
• TReal z
• TReal w

Related Functions
(Note that these are not member functions.)

• bool operator== (const TVec4 &lhs, const TVec4 &rhs)


• bool operator!= (const TVec4 &lhs, const TVec4 &rhs)
• TVec4 operator+ (const TVec4 &lhs, const TVec4 &rhs)

Playground 4.0.17.1
488 Class and File Reference

• TVec4 operator- (const TVec4 &lhs, const TVec4 &rhs)


• TVec4 operator∗ (const TVec4 &lhs, TReal s)
• TVec4 operator∗ (TReal s, const TVec4 &rhs)
• TVec4 operator/ (const TVec4 &lhs, TReal rhs)
• TReal DotProduct (const TVec4 &lhs, const TVec4 &rhs)
• TVec4 CrossProduct (const TVec4 &a, const TVec4 &b, const TVec4 &c)

15.77.2 Constructor & Destructor Documentation

TVec4::TVec4 ()
Constructor.

TVec4::TVec4 (TReal X, TReal Y, TReal Z, TReal W)


Initializing constructor.
Parameters:
X X value (v[0]).
Y Y value (v[1]).
Z Z value (v[2]).
W W value (v[3]).

TVec4::TVec4 (const TVec3 & rhs, TReal W = 0.0) [explicit]


Conversion from a TVec3 (p. 481).
Parameters:
rhs Source TVec3 (p. 481).
W W component to add. Defaults to zero.

TVec4::TVec4 (const TVec4 & rhs)


Copy construction.

15.77.3 Member Function Documentation

TVec4& TVec4::operator= (const TVec4 & rhs)


Assignment.
Returns:
A reference to this.

Navigating the Playground SDK


15.77 TVec4 Class Reference 489

TReal& TVec4::operator[ ] (TIndex i)


Member accessor.
Parameters:
i Zero-based index.
Returns:
A reference to the i’th member.

const TReal& TVec4::operator[ ] (TIndex i) const


Member accessor.
Parameters:
i Zero-based index.
Returns:
A reference to the i’th member.

TIndex TVec4::Dim () const


The dimension of this vector (4).
Returns:
4

TReal TVec4::LengthSquared () const


The length of this vector squared.
Returns:
x2 + y2 + z2 + w2

TReal TVec4::Length () const


The length of this vector.
Returns:
p
x2 + y2 + z2 + w2

TVec4& TVec4::Normalize ()
Normalize this vector. Changes vector to (x/Length(), y/Length(), z/Length(), w/Length())
Returns:
A reference to this.

Playground 4.0.17.1
490 Class and File Reference

TVec4& TVec4::operator+= (const TVec4 & rhs)


Addition-assignment operator.
Returns:
A reference to this.

TVec4& TVec4::operator-= (const TVec4 & rhs)


Subtraction-assignment operator.
Returns:
A reference to this.

TVec4& TVec4::operator∗= (TReal rhs)


Scaling operator.
Parameters:
s Scale factor.
Returns:
A reference to this, scaled as (x ∗ s, y ∗ s)

TVec4& TVec4::operator/= (TReal rhs)


Scaling operator.
Parameters:
s Scale divisor.
Returns:
A reference to this, scaled as (x/s, y/s)

TVec4 TVec4::operator- () const


Unary negation.
Returns:
(−x, −y, −z, −w)

15.77.4 Friends And Related Function Documentation

bool operator== (const TVec4 & lhs, const TVec4 & rhs) [related]
Equality operator.

Navigating the Playground SDK


15.77 TVec4 Class Reference 491

Returns:
True if equal.

bool operator!= (const TVec4 & lhs, const TVec4 & rhs) [related]
Inequality operator.
Returns:
True if not equal.

TVec4 operator+ (const TVec4 & lhs, const TVec4 & rhs) [related]
Addition operator.
Returns:
(x1 + x2 , y1 + y2 , z1 + z2 , w1 + w2 )

TVec4 operator- (const TVec4 & lhs, const TVec4 & rhs) [related]
Subtraction operator.
Returns:
(x1 − x2 , y1 − y2 , z1 − z2 , w1 − w2 )

TVec4 operator∗ (const TVec4 & lhs, TReal s) [related]


Scaling operator.
Returns:
(x ∗ s, y ∗ s)

TVec4 operator∗ (TReal s, const TVec4 & rhs) [related]


Scaling operator.
Returns:
(x ∗ s, y ∗ s)

TVec4 operator/ (const TVec4 & lhs, TReal rhs) [related]


Scaling operator.
Returns:
(x/s, y/s, z/s, w/s)

Playground 4.0.17.1
492 Class and File Reference

TReal DotProduct (const TVec4 & lhs, const TVec4 & rhs) [related]
Dot product function.
Returns:
The dot product of the two vectors: (x1 ∗ x2 + y1 ∗ y2 + z1 ∗ z2 + w1 ∗ w ∗ 2).

TVec4 CrossProduct (const TVec4 & a, const TVec4 & b, const TVec4 & c) [related]
Cross product function.
Returns:
The cross product of the two vectors.

15.77.5 Member Data Documentation


TReal TVec4::x
X dimension.

TReal TVec4::y
Y dimension.

TReal TVec4::z
Z dimension.

TReal TVec4::w
W dimension.

Navigating the Playground SDK


15.78 TVert Struct Reference 493

15.78 TVert Struct Reference


#include <pf/vertexset.h>

15.78.1 Detailed Description


3d untransformed, unlit vertex.

Public Attributes
• TVec3 pos
• TVec3 normal
• TVec2 uv

15.78.2 Member Data Documentation


TVec3 TVert::pos
Position in 3d space.

TVec3 TVert::normal
Vertex normal. Must not be (0,0,0), and must be normalized.

TVec2 TVert::uv
Vertex texture coordinate.

Playground 4.0.17.1
494 Class and File Reference

15.79 TVertexSet Class Reference


#include <pf/vertexset.h>

15.79.1 Detailed Description


A helper/wrapper for the Vertex Types (p. 155) which allows TRenderer::DrawVertices (p. 376)
to identify the vertex type being passed in without making the vertex types polymorphic.

Public Member Functions

• TVertexSet (TTransformedLitVert ∗v, uint32_t count)


• TVertexSet (TLitVert ∗v, uint32_t count)
• TVertexSet (TVert ∗v, uint32_t count)
• TVertexSet (const TVertexSet &)
• TVertexSet & operator= (const TVertexSet &)
• ∼TVertexSet ()
• void SetCount (uint32_t count)

Static Public Attributes

• static const uint32_t kMaxVertices

15.79.2 Constructor & Destructor Documentation


TVertexSet::TVertexSet (TTransformedLitVert ∗ v, uint32_t count)
Create a vertex set from an existing external array of TTransformedLitVerts. Does NOT copy the
vertices–only keeps a pointer to them.
Parameters:
v Pointer to array of vertices.
count Number of vertices in array. Must not be more than kMaxVertices.

TVertexSet::TVertexSet (TLitVert ∗ v, uint32_t count)


Create a vertex set from an existing external array of TLitVerts. Does NOT copy the vertices–only
keeps a pointer to them.
Parameters:
v Pointer to array of vertices.
count Number of vertices in array. Must not be more than kMaxVertices.

Navigating the Playground SDK


15.79 TVertexSet Class Reference 495

TVertexSet::TVertexSet (TVert ∗ v, uint32_t count)


Create a vertex set from an existing, external array of TVerts. Does NOT copy the vertices–only
keeps a pointer to them.
Parameters:
v Pointer to array of vertices.
count Number of vertices in array. Must not be more than kMaxVertices.

TVertexSet::TVertexSet (const TVertexSet &)


Copy construction: Needs to be implemented because of an inane rule in the ISO standard.
See https://developer.playfirst.com/node/158 for details.

TVertexSet::∼TVertexSet ()
Destructor.

15.79.3 Member Function Documentation


TVertexSet& TVertexSet::operator= (const TVertexSet &)
Assignment
Returns:
A reference to this

void TVertexSet::SetCount (uint32_t count)


Change the vertex count. This allows you to create a single TVertexSet (opposite) and reuse its
data repeatedly without reconstructing it.
Maximum count is kMaxVertices.
Parameters:
count Number of vertices in the set.

15.79.4 Member Data Documentation


const uint32_t TVertexSet::kMaxVertices
A hard limit on the number of vertices that you can specify.

Playground 4.0.17.1
496 Class and File Reference

15.80 TWindow Class Reference


#include <pf/window.h>
Inheritance diagram for TWindow:

TWindow

TImage TLayeredWindow TModalWindow TSlider TText

TButton TDialog TScreen TTextEdit

15.80.1 Detailed Description


The TWindow (this page) class is the base class of any object that needs to draw to the screen.
As you create your own custom TWindow-derived classes, you should be aware that a TWindow
(this page) "owns" its children: When a TWindow (this page) is destroyed, it expects to be able
to delete its children. Therefore a TWindow (this page) should never be allocated on the stack. If
you want a window to persist longer than its parent, you need to ensure that it is removed from
the parent prior to the parent’s destruction.

Locally Defined Types


Types defined in the TWindow (this page) scope.

• enum ETypeFlags { kModal, kFocusTarget, kInfrequentChanges, kStartGroup, kType-


Mask }
• enum EDepth { kBackMost, kFrontMost, kOneHigher, kOneLower, kDepthCount }
• enum EStateFlags { kEnabled, kChecked, kCached, kOpaque, kStateMask }
• enum EDrawMode { eAll, eCached, eDynamic }
• typedef std::list< TWindow ∗ > WindowList
• typedef std::list< TRect > RectList

Child and Parent Window Functions.


Functions to find child windows and to retreive and set parent windows.

• virtual bool AdoptChild (TWindow ∗child, bool initWindow=true)

Navigating the Playground SDK


15.80 TWindow Class Reference 497

• virtual void OrphanChild (TWindow ∗child)


• void DestroyAllChildren ()
• void FitToChildren ()
• TWindow ∗ ChildWindowFromPoint (const TPoint &point, int32_t depth=1)
• TModalWindow ∗ FindParentModal ()
• virtual void OnParentModalPopped ()
• void ForEachChild (TWindowSpider ∗spider, bool reverse=false)
• bool HasChildren ()
• TWindow ∗ GetChildWindow (str name, int32_t depth=-1)
• TWindow ∗ GetParent ()
• void SetWindowDepth (TWindow ∗inFrontOf=NULL)
• void SetWindowDepth (EDepth depth)

Construction and Initialization


• TWindow ()
• virtual ∼TWindow ()
• virtual bool OnNewParent ()
• virtual void Init (TWindowStyle &style)
• virtual void PostChildrenInit (TWindowStyle &style)
• void SizeAndPositionFromStyle (TWindowStyle &style)

Type Information and Casting


• PFClassId ClassId ()
• virtual bool IsKindOf (PFClassId type)
• template<class TO>
TO ∗ GetCast ()

Update Functions
Functions related to the drawing of windows.

• virtual void Draw ()


• virtual void PostDraw ()

Window Coordinates and Rectangles.


Functions to calculate window point conversions relative to two windows, and to acquire the
window and client rectangles.

• void GetWindowRect (TRect ∗rect)

Playground 4.0.17.1
498 Class and File Reference

• void SetWindowPos (const TPoint &point)


• void SetWindowPos (int32_t x, int32_t y)
• const TPoint & GetWindowPos ()
• void SetWindowSize (uint32_t width, uint32_t height)
• void GetClientRect (TRect ∗rect)
• uint32_t GetWindowWidth ()
• uint32_t GetWindowHeight ()
• void ScreenToClient (TPoint ∗point)
• void ScreenToClient (TRect ∗rect)
• void ClientToScreen (TPoint ∗point)
• void ClientToScreen (TRect ∗rect)
• void ParentToClient (TPoint ∗point) const
• void ParentToClient (TRect ∗rect) const
• void ClientToParent (TPoint ∗point)
• void ClientToParent (TRect ∗rect)
• void GetParentRelativeRect (TRect ∗rect)
• const TRect & GetParentRelativeRect ()

Window Information Accessors.


Functions to get or set information about a window.

• virtual void SetScroll (float vScroll, float hScroll=0)


• uint32_t GetFlags () const
• void SetFlags (uint32_t flags)
• str GetName ()
• void SetName (str name)
• bool IsOpaque ()
• bool IsModal ()
• bool IsEnabled ()

Event Handlers
Functions to override to handle events in a window, and functions to trigger events on a window.

• void SendWindowMessage (TMessage ∗message)


• void StartWindowAnimation (int32_t delay, bool autoRepeat=true, bool resetTime=true,
bool forceFrequency=false)
• void StopWindowAnimation ()
• virtual bool OnMessage (TMessage ∗message)
• virtual bool OnTaskAnimate ()
• virtual bool OnMouseDown (const TPoint &point)

Navigating the Playground SDK


15.80 TWindow Class Reference 499

• virtual bool OnExtendedMouseEvent (const TPoint &point, TPlat-


form::ExtendedMouseEvents event)
• virtual bool OnMouseUp (const TPoint &point)
• virtual bool OnMouseMove (const TPoint &point)
• virtual bool OnMouseLeave ()
• virtual bool CanAcceptFocus ()
• virtual bool OnChar (char key)
• virtual bool OnUTF8Char (str key)
• virtual bool OnKeyDown (char key, uint32_t flags)
• virtual bool OnKeyUp (char key)
• virtual bool OnMouseHover (const TPoint &point)
• virtual void OnSetFocus (TWindow ∗previous)
• virtual void OnKillFocus (TWindow ∗newFocus)

Internal Utility Functions


Functions that are only called internally by the library.

• bool HandleEvent (const TEvent ∗eIn, bool focusChanged=false)


• str GetID ()
• TWindow ∗ SetParent (TWindow ∗newParent)

Protected Member Functions


• bool IsEnabledSimple ()
• void AddWindowType (uint32_t type)
• TAnimTask ∗ GetWindowAnim ()

Protected Attributes
• WindowList mChildren

Friends
• class TWindowAnim

15.80.2 Member Typedef Documentation


typedef std::list<TWindow∗> TWindow::WindowList
A list of owned windows. Used for children.

Playground 4.0.17.1
500 Class and File Reference

typedef std::list<TRect> TWindow::RectList


List of rectangles

15.80.3 Member Enumeration Documentation


enum TWindow::ETypeFlags
Static Window Types
Flags that define what type and/or class a window is. These do not change after window cre-
ation.
Enumerator:
kModal Flag that this window is modal.
kFocusTarget Flag that this window can accept focus.
kInfrequentChanges Hint that we could cache this window. Only works if all ancestors are
also flagged.
kStartGroup This window is the start of a group of siblings (i.e. for radio buttons).
kTypeMask A flag mask that isolates the window types.

enum TWindow::EDepth
Position constants for SetWindowDepth
See also:
TWindow::SetWindowDepth (p. 506)
Enumerator:
kBackMost Set this window to be the backmost window.
kFrontMost Set this window to be the frontmost window.
kOneHigher Set this window to be one higher than its current position.
kOneLower Set this window to be one lower than its current position.
kDepthCount Number of depth options.

enum TWindow::EStateFlags
Dynamic Window States
States that may change frequently after window creation.
Enumerator:
kEnabled This window is enabled, and therefore can be rendered to and clicked upon.
kChecked This window is in its "selected" or "checked" state.
kCached This window is rendered to the cache.
kOpaque This window uses no alpha blending when it draws itself, and covers its rectangle
completely. It’s important to set this flag on a window when it’s full screen and should
completely obscure the windows behind it–this will allow Playground to prevent the
deeper window from drawing.
kStateMask A flag mask that isolates the window states.

Navigating the Playground SDK


15.80 TWindow Class Reference 501

enum TWindow::EDrawMode
Window drawing mode.
Enumerator:
eAll Draw all layers.
eCached Draw only cacheable layers.
eDynamic Draw only dynamic layers.

15.80.4 Constructor & Destructor Documentation


TWindow::TWindow ()
Default Constructor.

virtual TWindow::∼TWindow ()
Destructor.

15.80.5 Member Function Documentation


virtual bool TWindow::OnNewParent ()
Handle any initialization or setup that is required when this window is assigned to a new parent.
No initialization of the window has happened prior to this call.
Returns:
True on success; false on failure.
See also:
Init (this page)
PostChildrenInit (next page)

Reimplemented in TButton (p. 209), TDialog (p. 222), TModalWindow (p. 302), and TTextEdit
(p. 442).

virtual void TWindow::Init (TWindowStyle & style)


Initialize the Window. Called by the system only in Lua initialization.
When you create your own custom window, this is where you put your own custom initialization
that needs to happen before children are created. Fundamental window initialization is handled
in every class by this function, so when you override this function you almost always want to
call your base class to handle base class initialization.
Parameters:
style The Lua style that was in effect when this window was created. This style contains
all parameters specified explicitly for the window as well as parameters defined in the
current style. Parameters set locally override ones in the style.

Playground 4.0.17.1
502 Class and File Reference

Reimplemented in TButton (p. 208), TImage (p. 251), TSlider (p. 408), TText (p. 438), and TTextE-
dit (p. 443).

virtual void TWindow::PostChildrenInit (TWindowStyle & style)


Do post-children-added initialization when being created from Lua.
Any initialization that needs to happen after a window’s children have been added can be placed
in a derived version of this function.
Warning:

Remember to always call the base class if you’re overriding this function.
Parameters:
style Current style environment that this window was created in.

Reimplemented in TButton (p. 209), and TModalWindow (p. 303).

void TWindow::SizeAndPositionFromStyle (TWindowStyle & style) [protected]


A function that takes the default window parameters and applies them to the window’s position
and size.
Note:
This function is for advanced users only.

Called by TWindow::Init() and by TWindow::PostChildrenInit() (this page).


Has no effect if it can’t calculate the position and size based on current information available: If
a position is set to kCenter, or a size set to kMax, but the parent window size hasn’t yet been
calculated, this function won’t do anything.
Note:
Implementation details.

Since some windows set their size based on their calculated children’s sizes (using TWin-
dow::FitToChildren (p. 504)), TWindow::PostChildrenInit() (this page) needs to call this to adjust
the position after the size has been calculated. Since other windows must have their full position
and size specified in order to properly initialize, TWindow::Init() needs to call this function.
Parameters:
style The style of the window to apply.

PFClassId TWindow::ClassId ()
Get the ClassId.
Returns:
A ClassId that can be passed to IsKindOf.

Navigating the Playground SDK


15.80 TWindow Class Reference 503

See also:
Type Information and Casting (p. 25)

bool TWindow::IsKindOf (PFClassId type)


Determine whether this window is derived from type.
Parameters:
type ClassId() (opposite) of type to test.
See also:
Type Information and Casting (p. 25)

template<class TO> template< class TO > TO ∗ TWindow::GetCast ()


Safely cast this window to another type.
Returns:
A cast pointer, or an empty reference.
See also:
Type Information and Casting (p. 25)

virtual void TWindow::Draw ()


Draw the window. Derived classes will override this function and provide the draw functionality.
Reimplemented in TImage (p. 250), TSlider (p. 405), TText (p. 435), and TTextEdit (p. 445).

virtual void TWindow::PostDraw ()


Draw any overlays that should appear on top of this window’s children.

virtual bool TWindow::AdoptChild (TWindow ∗ child, bool initWindow = true)


Add a child to this window
Warning:

If you override this in a derived class, be sure to call the base class to actually add the child
from the list of children.
Parameters:
child Child that’s being added.
initWindow True to call OnNewParent() (p. 501).
Returns:
True if successful. On false, the window has NOT been adopted and the calling class still has
responsibility for destruction.

Playground 4.0.17.1
504 Class and File Reference

Reimplemented in TLayeredWindow (p. 253).

virtual void TWindow::OrphanChild (TWindow ∗ child)


Remove a child from this window.
Warning:

If you override this in a derived class, be sure to call the base class to actually remove the child
from the list of children.
Parameters:
child Child that’s being removed.

Reimplemented in TLayeredWindow (p. 253).

void TWindow::DestroyAllChildren ()
Destroy (delete) all child windows. Those windows will destroy their own children. Actual dele-
tion is deferred using TWindowManager::SafeDestroyWindow() (p. 527), so the windows will be
actually deleted in the next event loop.

void TWindow::FitToChildren ()
Fit this window to its childrens’ sizes.

TWindow∗ TWindow::ChildWindowFromPoint (const TPoint & point, int32_t depth = 1)


Recursively find a child window from the given point. The point is assumed to be inside this
window.
When searching for children, ChildWindowFromPoint() (this page) will ignore any windows that
are disabled (kEnabled is not set).
Parameters:
point Point to test in client coordinates.
depth The number of times to recurse. 1 gives you only immediate children. -1 gives you the
deepest child. Defaults to 1.
Returns:
A pointer to the window containing the point. If the point is not inside any of the child
windows, the function will return this.

TModalWindow∗ TWindow::FindParentModal ()
Find the nearest direct-ancestor modal window.
Returns:
A pointer to a modal window, or NULL if none is found.

Navigating the Playground SDK


15.80 TWindow Class Reference 505

virtual void TWindow::OnParentModalPopped ()


This method is called when this window’s parent modal has been removed from the window
stack. Because window deletion is delayed until it is safe to delete the window, this method can
be used to detect immediately when a window has been removed from the stack, whereas the
destructor will only be called when the window is actually deleted.

void TWindow::ForEachChild (TWindowSpider ∗ spider, bool reverse = false)


Iterate through all children and call the Process() member function of TWindowSpider (p. 528).
Iteration happens in front-to-back order by default, or back-to-front if reverse is true
Parameters:
spider The derived class which contains a Process() function to be called on each child win-
dow.
reverse If this is true, back-to-front order is used, default is false

bool TWindow::HasChildren ()
Return true if this window has children.
Returns:
True if we’re parents; false otherwise.

TWindow∗ TWindow::GetChildWindow (str name, int32_t depth = -1)


Return the descendant window with the given name, if one exists.
Parameters:
name Window name to search for.
depth Number of levels deep to look. Set to -1 for no limit. Defaults to -1.
Returns:
A TWindow (p. 496) to the descendant with the given name. Children are searched recur-
sively up to the level indicated in depth.

TWindow∗ TWindow::GetParent ()
Get the current window parent
Returns:
A shared pointer to the current parent window.
Note:
This will return NULL if the current window has no parent.

Referenced by IsEnabled(), and IsEnabledSimple().

Playground 4.0.17.1
506 Class and File Reference

void TWindow::SetWindowDepth (TWindow ∗ inFrontOf = NULL)


Reposition this window to be immediately in front of a given sibling.
Pass the results of GetParent() (previous page)->GetFirstChild() to bring this window to the front.
Parameters:
inFrontOf Sibling we should be visually in front of. If NULL, will place this window in the
back.

void TWindow::SetWindowDepth (EDepth depth)


Reposition this window to be in the position specified by the given constant.
Parameters:
depth Enumeration that specifies a logical window depth.
See also:
EDepth (p. 500)

void TWindow::GetWindowRect (TRect ∗ rect)


Get the rectangle that specifies the current window in top-level TScreen (p. 387) coordinates.
Parameters:
rect TRect (p. 364) to fill with resulting rectangle.

void TWindow::SetWindowPos (const TPoint & point)


Set the position of the upper left corner of the window in parent client coordinates.
Parameters:
point New window position.
See also:
SetWindowSize (opposite)
SetWindowDepth (this page)

void TWindow::SetWindowPos (int32_t x, int32_t y)


Set the position of the upper left corner of the window in parent client coordinates.
Parameters:
x New window x coordinate.
y New window y coordinate.
See also:
SetWindowSize (opposite)

Navigating the Playground SDK


15.80 TWindow Class Reference 507

SetWindowDepth (opposite)

const TPoint& TWindow::GetWindowPos ()


Get the current window position.
Returns:
The current window position relative to its parent.

void TWindow::SetWindowSize (uint32_t width, uint32_t height)


Set the size of the window.
Parameters:
width New window width.
height New window height.

void TWindow::GetClientRect (TRect ∗ rect)


Get the "client" rectangle of the current window. This mimics the Windows functionality of getting
a rect that has top and left set to 0, with right and bottom set to width and height, respectively.
Parameters:
rect The TRect (p. 364) to fill with the client rectangle.

uint32_t TWindow::GetWindowWidth ()
Get the width of the client area of this window.
Returns:
Window client width in pixels.

uint32_t TWindow::GetWindowHeight ()
Get the height of the client area of this window.
Returns:
Window client height in pixels.

void TWindow::ScreenToClient (TPoint ∗ point)


Convert between top-level screen and client coordinates.
Parameters:
point in: Screen coordinates, out:client coordinates.

Playground 4.0.17.1
508 Class and File Reference

void TWindow::ScreenToClient (TRect ∗ rect)


Convert between top-level screen and client coordinates.
Parameters:
rect in: Screen coordinates, out:client coordinates.

References TRect::GetBottomRight(), and TRect::GetTopLeft().

void TWindow::ClientToScreen (TPoint ∗ point)


Convert between client and top-level screen coordinates.
Parameters:
point in: client coordinates, out: screen coorditates.

void TWindow::ClientToScreen (TRect ∗ rect)


Convert between client and top-level screen coordinates.
Parameters:
rect in: client coordinates, out: screen coorditates.

References TRect::GetBottomRight(), and TRect::GetTopLeft().

void TWindow::ParentToClient (TPoint ∗ point) const


Convert between parent and client coordinates.
Parameters:
point in: a point in parent’s coordinate system, out:client coordinates

void TWindow::ParentToClient (TRect ∗ rect) const


Convert between parent and client coordinates.
Parameters:
rect in: a rect in parent’s coordinate system, out:client coordinates

References TRect::GetBottomRight(), and TRect::GetTopLeft().

void TWindow::ClientToParent (TPoint ∗ point)


Convert between client and parent coordinates.
Parameters:
point in: client coordinates, out:a point in parent’s coordinate system.

Navigating the Playground SDK


15.80 TWindow Class Reference 509

void TWindow::ClientToParent (TRect ∗ rect)


Convert between parent and client coordinates.
Parameters:
rect in: a rect in parent’s coordinate system, out:client coordinates

References TRect::GetBottomRight(), and TRect::GetTopLeft().

void TWindow::GetParentRelativeRect (TRect ∗ rect)


Get the rectangle that represents this window in the client space of its parent window.
Parameters:
rect A rectangle to fill with the window’s rectangle in it’s parent’s coordinate system.

const TRect& TWindow::GetParentRelativeRect ()


Get the rectangle that represents this window in the client space of its parent window.
Returns:
A reference to a TRect (p. 364) that describes this window in its parents coordinates.

virtual void TWindow::SetScroll (float vScroll, float hScroll = 0)


A virtual function to override if your window can scroll.
Parameters:
vScroll Vertical scroll ratio (0.0-1.0).
hScroll Horizontal scroll percentage (0.0-1.0).

Reimplemented in TText (p. 438).

uint32_t TWindow::GetFlags () const


Get the window’s state and style flags.
Returns:
Current state and style of the window.

void TWindow::SetFlags (uint32_t flags)


Set the state flags of the window. Does not change the "type" or style flags of the window.
Parameters:
flags Complete set of flags to update.

Playground 4.0.17.1
510 Class and File Reference

str TWindow::GetName ()
Get the window name, if any.
Returns:
A str (p. 161) containing the window’s name.

void TWindow::SetName (str name)


Set the window name.
Parameters:
name New name for the window.

bool TWindow::IsOpaque ()
Query this window’s opacity.
Returns:
true if the window is "opaque": When it draws, none of the background will show through. If
any part of the window is transparent, it should not have the kOpaque style set.

bool TWindow::IsModal ()
Query this window’s modal status.
A modal window blocks further event handling by its parent and receives DoModalProcess() calls.
Returns:
Return true if this is a modal window, false if it is not.

Referenced by IsEnabled(), and IsEnabledSimple().

bool TWindow::IsEnabled ()
Return whether this window and all of its ancestors are enabled.
Returns:
True if this window is really enabled and (eventual) child of a TModalWindow (p. 298).

References GetParent(), IsModal(), and mFlags.

void TWindow::SendWindowMessage (TMessage ∗ message)


Send a message to a window (or its ancestor). Takes ownership of message and will delete it after
it has been delivered.
Calls OnMessage for this window and its parents until one returns "true", indicating the message
has been handled. Stops searching at the first modal window.

Navigating the Playground SDK


15.80 TWindow Class Reference 511

Parameters:
message Message to send, including potential payload. Will be deleted after delivery.

void TWindow::StartWindowAnimation (int32_t delay, bool autoRepeat = true, bool


resetTime = true, bool forceFrequency = false)

Start a window animation. Can be called to reset an animation delay. The virtual function On-
TaskAnimate() (next page) will be called at the frequency given by the parameters to StartWin-
dowAnimation until StopWindowAnimation is called or this window is destroyed.
This window must already be in a hierarchy and have a parent TModalWindow (p. 298) to attach
its animation to, or StartWindowAnimation() (this page) will ASSERT (or crash in release build).
In other words, you cannot call this function in a constructor.
Parameters:
delay Delay, in ms., before OnTaskAnimate will be called.
autoRepeat True to cause delay to be auto-reset, i.e., to call OnTaskAnimate every delay ms.
instead of just once.
resetTime Reset the time after each call. See TAnimTask::SetDelay (p. 192) for details.
forceFrequency Force the animation frequency. See TAnimTask::SetDelay (p. 192) for details.
See also:
TWindow::StopWindowAnimation (this page)
TWindow::OnTaskAnimate (next page)

void TWindow::StopWindowAnimation ()

Stop a window from receiving OnTaskAnimate calls.


See also:
TWindow::StartWindowAnimation (this page)
TWindow::OnTaskAnimate (next page)

virtual bool TWindow::OnMessage (TMessage ∗ message)

Handle a message.
Parameters:
message Payload of message.
Returns:
True if message handled; false otherwise.

Reimplemented in TDialog (p. 222), and TModalWindow (p. 302).

Playground 4.0.17.1
512 Class and File Reference

virtual bool TWindow::OnTaskAnimate ()


Called if you have initiated a window animation with TWindow::StartWindowAnimation (pre-
vious page).
Returns:
True to continue animating. False to stop.

Reimplemented in TTextEdit (p. 446).

virtual bool TWindow::OnMouseDown (const TPoint & point)


Mouse down handler.
Parameters:
point Location of mouse press in client coordinates.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented in TButton (p. 207), TSlider (p. 407), and TText (p. 437).

virtual bool TWindow::OnExtendedMouseEvent (const TPoint & point,


TPlatform::ExtendedMouseEvents event)
Extended mouse button handler.
Parameters:
point Location of mouse event in client coordinates.
event Event that happened.
Returns:
true if message was handled, false to keep searching for a handler.

virtual bool TWindow::OnMouseUp (const TPoint & point)


Mouse up handler.
Parameters:
point Location of mouse release in client coordinates.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented in TButton (p. 206), TSlider (p. 407), and TText (p. 436).

virtual bool TWindow::OnMouseMove (const TPoint & point)


Mouse motion handler.

Navigating the Playground SDK


15.80 TWindow Class Reference 513

Parameters:
point Location of mouse in client coordinates.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented in TButton (p. 207), TSlider (p. 407), and TText (p. 437).

virtual bool TWindow::OnMouseLeave ()


Notification that the mouse has left the window.
Warning:

This message is only sent if TWindowManager::AddMouseListener() (p. 524) has been called
for this window previously.
Returns:
True if handled.

Reimplemented in TButton (p. 206), TSlider (p. 408), and TText (p. 437).

virtual bool TWindow::CanAcceptFocus ()


Returns true if this window can accept the keyboard focus.
Override to return true if your derived window can accept focus.
Returns:
Return true if this window can accept keyboard focus. If it can accept keyboard focus, it
should respond to the On∗Focus() message to update its appearance when its focus state
changes.

virtual bool TWindow::OnChar (char key)


Translated character handler.
In UTF-8 mode, this function will only be called if OnUTF8Char() (next page) returns false, or
there is no OnUTF8Char() (next page) handler.
Parameters:
key Key hit on keyboard, along with shift translations.
Returns:
true if message was handled, false to keep searching for a handler.
See also:
TPlatform::kUTF8Mode (p. 348)

Reimplemented in TModalWindow (p. 302), and TTextEdit (p. 443).

Playground 4.0.17.1
514 Class and File Reference

virtual bool TWindow::OnUTF8Char (str key)


UTF-8 Translated character handler.
This function is ONLY active when UTF-8 support has been enabled.
Parameters:
key Key hit on keyboard, along with shift translations.
Returns:
true if message was handled, false to keep searching for a handler.
See also:
TPlatform::kUTF8Mode (p. 348)

Reimplemented in TTextEdit (p. 444).

virtual bool TWindow::OnKeyDown (char key, uint32_t flags)


Raw key hit on keyboard.
Parameters:
key Key pressed on keyboard. Returns either a (low-ASCII) key name, or one of the constants
defined in the Key Codes (p. 229) section.
flags TEvent::EKeyFlags (p. 230) mask representing the state of other keys on the keyboard
when this key was hit.
Returns:
true if message was handled, false to keep searching for a handler.

Reimplemented in TModalWindow (p. 301), and TTextEdit (p. 443).

virtual bool TWindow::OnKeyUp (char key)


Raw key released on keyboard.
Parameters:
key Key released.
Returns:
true if message was handled, false to keep searching for a handler.

virtual bool TWindow::OnMouseHover (const TPoint & point)


Called if the mouse hovers over a point on the window.
Parameters:
point Point the mouse was last hovering over.

Navigating the Playground SDK


15.80 TWindow Class Reference 515

Returns:
True if processed; false to keep looking.

virtual void TWindow::OnSetFocus (TWindow ∗ previous)


This window is receiving the keyboard focus.
Parameters:
previous The window that was previously focused. Can be NULL.

Reimplemented in TModalWindow (p. 301).


Referenced by TWindowManager::SetFocus().

virtual void TWindow::OnKillFocus (TWindow ∗ newFocus)


This window is losing the keyboard focus.
Parameters:
newFocus The window that’s receiving focus.

bool TWindow::HandleEvent (const TEvent ∗ eIn, bool focusChanged = false)


Internal event handling function.
Warning:

This function should normally only be called by the library.


NOTE it’s currently not virtual. If it’s ever made virtual, it will likely be VERY important for
derived classes to call the base class function.
Parameters:
eIn Event to process.
focusChanged true if this event has already caused a focus change, so that this event will only
cause one focus change total.
Returns:
True if the event is handled; false otherwise.

str TWindow::GetID ()
Get a unique window identifier.
Returns:
The ID of the window.

References str::getFormatted().

Playground 4.0.17.1
516 Class and File Reference

TWindow∗ TWindow::SetParent (TWindow ∗ newParent) [protected]


Set the current parent window.
Parameters:
newParent A TWindow (p. 496) ∗ to the new parent window.
Returns:
A TWindow (p. 496) ∗ to the old parent window.

bool TWindow::IsEnabledSimple () [protected]


Return whether this window is enabled, looking at parents, but ignoring whether it descends from
a TModalWindow (p. 298).
Returns:
True if enabled.

References GetParent(), IsModal(), and mFlags.

void TWindow::AddWindowType (uint32_t type) [protected]

Function that allows a derived window to add type flags to the TWindow (p. 496). This isn’t
public because in most circumstances a window’s type should be invariant once created.
Parameters:
type Flags to add.

TAnimTask∗ TWindow::GetWindowAnim () [protected]


Get the associated TAnimTask (p. 191). A TAnimTask (p. 191) is associated with this TWindow
(p. 496) when StartWindowAnimation() (p. 511) is called.
Returns:
A pointer to a TAnimTask (p. 191), or NULL if none exists.
See also:
StartWindowAnimation (p. 511)

15.80.6 Friends And Related Function Documentation

friend class TWindowAnim [friend]

A TWindowAnim can poke inside us.

Navigating the Playground SDK


15.80 TWindow Class Reference 517

15.80.7 Member Data Documentation


WindowList TWindow::mChildren [protected]
We own our children. Our descendants can play with our children, though.

Playground 4.0.17.1
518 Class and File Reference

15.81 TWindowHoverHandler Class Reference


#include <pf/windowmanager.h>

15.81.1 Detailed Description


A callback that receives notification that a window has had the mouse hover over it.
See also:
TWindowManager::AdoptHoverHandler (p. 523)

Public Member Functions


• virtual bool Handle (TWindow ∗window, const TPoint &point)=0

15.81.2 Member Function Documentation


virtual bool TWindowHoverHandler::Handle (TWindow ∗ window, const TPoint & point)
Abstract virtual function for handling hover events.
Parameters:
window Window that mouse is hovering over.
point Point in window client coordinates.
Returns:
True if event handled; false to continue processing.

Navigating the Playground SDK


15.82 TWindowManager Class Reference 519

15.82 TWindowManager Class Reference


#include <pf/windowmanager.h>

15.82.1 Detailed Description


The TWindowManager (this page) class manages, controls, and delegates messages to the win-
dow system.
TWindowManager (this page) contains a stack of TModalWindows, the top of which is considered
to be the active window in the system. If the a TModalWindow (p. 298) covers the entire viewable
area and is flagged as opaque, only the top modal window and its children are drawn.
The main message pump hands messages to TWindowManager (this page) using TWindowMan-
ager::HandleEvent() (p. 524), which then dispatches the event to the appropriate listener(s).

Construction, Destruction, and Singleton Access


• TWindowManager ()
• virtual ∼TWindowManager ()
• static TWindowManager ∗ GetInstance ()

Message handling.
• void PostWindowMessage (TMessage ∗message)
• void AdoptMessageListener (TMessageListener ∗messageListener)
• bool OrphanMessageListener (TMessageListener ∗messageListener)

Top-level Screen Related Functions


• class TScreen ∗ GetScreen ()
• void InvalidateScreen ()
• void SetScreen (TScreen ∗screen)

Modal window handling and supporting functions.


• void PushModal (TModalWindow ∗w)
• void PopModal (str windowName)
• str GetModalReturnStr ()
• int32_t GetModalReturnInt ()
• class TDialog ∗ DisplayDialog (str dialogSpec, str body, str title, str name="")
• class TModalWindow ∗ GetTopModalWindow ()
• void SetTopModalOnly (bool enable)

Playground 4.0.17.1
520 Class and File Reference

Pop-up help handling


Customize the default pop-up help features of your application.

• void AdoptHoverHandler (TWindowHoverHandler ∗handler)


• TWindowHoverHandler ∗ GetHoverHandler ()

Overlay Window management.


An overlay window allows you to draw to a window that lives "on top" of the hierarchy.

• void AdoptOverlayWindow (TWindow ∗overlay)


• bool OrphanOverlayWindow (TWindow ∗overlay)

Event Management and Routing


Member functions that manipulate how messages our routed through the system.

• void HandleEvent (TEvent ∗e)


• void AddMouseListener (TWindow ∗window)
• void RemoveMouseListener (TWindow ∗window)
• void SetFocus (TWindow ∗focus)
• TWindow ∗ GetFocus ()

Lua GUI Script Access


Functions that access and manipulate the Lua GUI script supplied by TWindowManager (previ-
ous page).

• TScript ∗ GetScript ()
• void RunScript (TWindow ∗window, const char ∗filename)
• void DoLuaString (TWindow ∗window, str script)
• void OnScriptMessage (TMessage ∗message, TLuaFunction ∗command=NULL)
• void AddWindowType (str command, PFClassId classId)
• bool EnableStringTable (bool bEnable)

Utility Functions
• void AddText (TWindow ∗window, str bodyText, str style)
• void SafeDestroyWindow (TWindow ∗window)

Friends
• class TPlatform

Navigating the Playground SDK


15.82 TWindowManager Class Reference 521

15.82.2 Constructor & Destructor Documentation


TWindowManager::TWindowManager ()
Default Constructor.

virtual TWindowManager::∼TWindowManager ()
Destructor.

15.82.3 Member Function Documentation


static TWindowManager∗ TWindowManager::GetInstance ()
Get the global TWindowManager (p. 519) instance.
Returns:
A pointer to the TWindowManager (p. 519).

void TWindowManager::PostWindowMessage (TMessage ∗ message)


Post a message to the queue. Takes ownership of the message, and will expect to be able to delete
the message when it has been delivered.
Parameters:
message Message to post.

void TWindowManager::AdoptMessageListener (TMessageListener ∗ messageListener)


Add a message listener that will be able to receive messages that aren’t targeted at a specific win-
dow.
Parameters:
messageListener Listener to adopt. Will be destroyed by TWindowManager (p. 519) unless
it is orphaned prior to the destruction of the TWindowManager (p. 519).

bool TWindowManager::OrphanMessageListener (TMessageListener ∗ messageListener)


Remove a message listener from the TWindowManager (p. 519).
Parameters:
messageListener Listener to remove.
Returns:
True if it was found and removed; false otherwise. If true it’s safe to delete, otherwise it’s been
deleted already.

Playground 4.0.17.1
522 Class and File Reference

class TScreen∗ TWindowManager::GetScreen ()


Get the global screen object (the top level application TWindow (p. 496)).
Returns:
A pointer to the application TScreen (p. 387).

void TWindowManager::InvalidateScreen ()
Mark the current screen as needing to be redrawn.

void TWindowManager::SetScreen (TScreen ∗ screen)


Set the screen to a particular TScreen (p. 387) and initializes it to be the correct size. Also calls Init()
on the screen, since no one will be calling AdoptChild() with the TScreen (p. 387) as a parameter.
This function can only be called once in a Playground game. It is called internally by the library
when you first call TPlatform::SetDisplay() (p. 342), so if you want to create a custom-derived
TScreen (p. 387) then you need to add it before you call SetDisplay() the first time.
Parameters:
screen Screen to set to be the one-and-only top level screen class.

void TWindowManager::PushModal (TModalWindow ∗ w)


Push a modal window onto the modal window stack.
Parameters:
w Window to push.

void TWindowManager::PopModal (str windowName)


Pop a modal window off the modal window stack. Safe to do at any time–window will be deleted
at next event.
Parameters:
windowName Name of the window to pop. Will pop that window and any of its descendents
from the stack, if found.

str TWindowManager::GetModalReturnStr ()
Get the return value from a modal window.
Returns:
A string return value.

int32_t TWindowManager::GetModalReturnInt ()
Get the return value from a modal window.

Navigating the Playground SDK


15.82 TWindowManager Class Reference 523

Returns:
An integer return value.

class TDialog∗ TWindowManager::DisplayDialog (str dialogSpec, str body, str title, str name
= "")
Display a modal dialog box.
Parameters:
dialogSpec Handle to a Lua dialog specification file.
body String to be placed in the dialog body. Selects style DialogBodyText and sets gDi-
alogTable.body to the given body. The Lua dialog specification can then use gDi-
alogTable.body to set the text of the body of the dialog.
title Title of dialog. Selects style DialogTitleText and adds the text to the dialog as gDi-
alogTable.title.
name The name to be given to the resulting dialog window.
Returns:
A pointer to the dialog. The dialog will already have been pushed as the top modal window,
but you may need this pointer to set additional fields.

class TModalWindow∗ TWindowManager::GetTopModalWindow ()


Get the current top-most modal window. Note that this window may have some number of
children–this is just the modal window that is currently receiving the processing.
Returns:
A reference to the top-most modal window.

void TWindowManager::SetTopModalOnly (bool enable)


Enable "Draw Top Modal Window Only" mode. Only the top layer will be drawn when true.
Parameters:
enable True to enable.

void TWindowManager::AdoptHoverHandler (TWindowHoverHandler ∗ handler)


Set the current pop-up default help handler.
To add pop-up help to your application, you can either override individual TWin-
dow::OnMouseHover (p. 514) handlers, or you can allow TWindow (p. 496) to call the default
handler, which you can set using this function.
The previous handler, if any, is deleted when you call this function.
Parameters:
handler A handler to add.

Playground 4.0.17.1
524 Class and File Reference

TWindowHoverHandler∗ TWindowManager::GetHoverHandler ()
Get the current pop-up help handler.
Returns:
A pointer to the current handler, if any.

void TWindowManager::AdoptOverlayWindow (TWindow ∗ overlay)


Add an overlay window to the TWindowManager (p. 519). As always, the "Adopt" semantics
implies ownership, so when TWindowManager (p. 519) is destroyed, it will attempt to delete this
window. To prevent this behavior, call OrphanOverlayWindow to release it from TWindowMan-
ager (p. 519).
An overlay window allows you to draw to a window that lives "on top" of the hierarchy. Set the
window rectangle to the area that should be redrawn next frame.
If you want your overlay window to be able to process mouse messages, you need to globally
enable the feature by calling:

TPlatform::SetConfig(TPlatform::kOverlayWindowMouseEvents,"1"); C++

...in your program initialization code.


Parameters:
overlay An overlay window to add.

bool TWindowManager::OrphanOverlayWindow (TWindow ∗ overlay)


Release an overlay window from the TWindowManager (p. 519).
Parameters:
overlay Window to release.
Returns:
True if it was found and released. False if it was not found.

void TWindowManager::HandleEvent (TEvent ∗ e)


Handle a system event. Processes the event and passes it along as a message or a callback to the
appropriate window. Typically called in the main loop message pump.
Parameters:
e Event.

void TWindowManager::AddMouseListener (TWindow ∗ window)


Capture the mouse and other input events.

Navigating the Playground SDK


15.82 TWindowManager Class Reference 525

Implemenation is low-overhead, and so can be safely called in OnMouseMove(). If you request


capture a second time with the same window pointer, the new window will not be added to the
list of listeners, so a window that wants capture does not need to remember whether it has called
AddMouseListener() (opposite) already–it can just add itself again.
Events are dispatched to all registered mouse listeners, regardless of return values from handled
functions.
Parameters:
window Window that wants to receive all mouse events.

void TWindowManager::RemoveMouseListener (TWindow ∗ window)


Stop listening to all mouse messages.
Parameters:
window Window to release from capturing the mouse. Silently fails if window is not cur-
rently a mouse listener.

void TWindowManager::SetFocus (TWindow ∗ focus)


Set the window that is to receive the keyboard focus.
Note that the window will lose the focus if someone clicks unless it has the style kFocusTarget. On
construction of a window that is to receive the focus, call

AddWindowType( kFocusTarget ); C++

...and this will flag that window as being able to accept focus when clicked. Otherwise focus goes
it its nearest kFocusTarget ancestor, or is delegated to the default-focus defined by the window’s
parent modal.
Parameters:
focus New focus window.

References TWindow::OnSetFocus().

TWindow∗ TWindowManager::GetFocus ()
Get the window that is currently receiving keyboard events.
Returns:
A reference to the current focused window.

TScript∗ TWindowManager::GetScript ()
Get the current TWindowManager (p. 519) GUI script.

Playground 4.0.17.1
526 Class and File Reference

Returns:
A pointer to the current script.

void TWindowManager::RunScript (TWindow ∗ window, const char ∗ filename)


Use a Lua Script in an external resource to populate a Window.
Parameters:
window Window to apply script to.
filename Name of Lua file.

void TWindowManager::DoLuaString (TWindow ∗ window, str script)


Use a Lua Script in a str (p. 161) to populate a Window.
Parameters:
window Window to apply script to.
script Lua commands to run.

void TWindowManager::OnScriptMessage (TMessage ∗ message, TLuaFunction ∗ command =


NULL)
Dispatch a message to the GUI script.
Parameters:
message Message to pass to Lua.
command Command to pass to Lua to execute in GUI thread.

void TWindowManager::AddWindowType (str command, PFClassId classId)


Add a custom-defined window type to the script context.
Parameters:
command Window type name.
classId The TWindow::ClassId() (p. 502) of the custom defined window. Note that the win-
dow needs to have PFTYPEDEF_DC() (p. 543) in the header and PFTYPEIMPL_DC()
(p. 543) in the implementation file for this to work.

bool TWindowManager::EnableStringTable (bool bEnable)


Toggle on/off using the string table to convert labels found in LUA to properly localized strings
(see TStringTable (p. 427) for more information).
Parameters:
bEnable true to use the table, false to not use the table

Navigating the Playground SDK


15.82 TWindowManager Class Reference 527

Returns:
returns true if string table was previously enabled, false otherwise

void TWindowManager::AddText (TWindow ∗ window, str bodyText, str style)


Convenience function that creates a TText (p. 433) child of the given window, using the given
bodyText, in the given Lua style.
Parameters:
window The window to add a new TText (p. 433) child to.
bodyText Text to add.
style Name of the Lua style to use (must already be loaded in the TWindowMan-
ager::GetScript() (p. 525) Lua script), or a style definition in curly brackets.

void TWindowManager::SafeDestroyWindow (TWindow ∗ window)


Safely destroy a window at the beginning of an event loop. Allows you to mark a window for
destruction when processing an event that may need to continue accessing the window.
Parameters:
window Window to destroy.

Playground 4.0.17.1
528 Class and File Reference

15.83 TWindowSpider Class Reference


#include <pf/window.h>

15.83.1 Detailed Description


A class used with TWindow::ForEachChild (p. 505) to iterate over the children of a window with
a single "callback" function.

Public Member Functions


• virtual ∼TWindowSpider ()
• virtual bool Process (TWindow ∗window)=0

15.83.2 Constructor & Destructor Documentation


virtual TWindowSpider::∼TWindowSpider ()
Virtual destructor

15.83.3 Member Function Documentation


virtual bool TWindowSpider::Process (TWindow ∗ window)
The function called once for each window.
Parameters:
window The window being iterated.
Returns:
True to continue the traversal.

Navigating the Playground SDK


15.84 TWindowStyle Class Reference 529

15.84 TWindowStyle Class Reference


#include <pf/windowstyle.h>

15.84.1 Detailed Description


An encapsulation of a Lua window style.

Local Types

• enum { kCenter, kMax, kHAlignLeft, kHAlignCenter, kHAlignRight, kVAlignTop,


kVAlignCenter, kVAlignBottom, kDefault, kPushButtonAlignment, kRadioButtonAlign-
ment, kToggleButtonAlignment }

Public Member Functions

• TWindowStyle (TLuaTable ∗table)


• virtual ∼TWindowStyle ()
• str GetString (str key, str defaultValue="") const
• double GetNumber (str key, double defaultValue=0) const
• bool GetBool (str key, bool defaultValue=false) const
• TColor GetColor (str key, TColor defaultValue=TColor(0, 0, 0, 1)) const
• TLuaFunction ∗ GetFunction (str key) const
• TLuaTable ∗ GetTable (str key)
• int32_t GetInt (str key, int32_t defaultValue=0) const

15.84.2 Member Enumeration Documentation


anonymous enum
Various window constants
Enumerator:
kCenter Select center for a coordinate.
kMax Select max for a width or height
kHAlignLeft Align text to the left.
kHAlignCenter Align text to the center.
kHAlignRight Align text to the right.
kVAlignTop Align text to the top.
kVAlignCenter Align text vertically to the center.
kVAlignBottom Align text to the bottom.
kDefault Default text alignment.

Playground 4.0.17.1
530 Class and File Reference

15.84.3 Constructor & Destructor Documentation


TWindowStyle::TWindowStyle (TLuaTable ∗ table)
Construction.

virtual TWindowStyle::∼TWindowStyle ()
Destructor.

15.84.4 Member Function Documentation


str TWindowStyle::GetString (str key, str defaultValue = "") const
Get a string parameter from the style.
Parameters:
key Name of the parameter to query.
defaultValue Default if parameter value not found.
Returns:
Value if found; defaultValue otherwise.

double TWindowStyle::GetNumber (str key, double defaultValue = 0) const


Get a numeric parameter from the style.
Parameters:
key Name of the parameter to query.
defaultValue Default if parameter value not found.
Returns:
Value if found; defaultValue otherwise.

bool TWindowStyle::GetBool (str key, bool defaultValue = false) const


Get a boolean parameter from the style.
Parameters:
key Name of the parameter to query.
defaultValue Default if parameter value not found.
Returns:
Value if found; defaultValue otherwise.

TColor TWindowStyle::GetColor (str key, TColor defaultValue = TColor(0, 0, 0, 1)) const


Get a color parameter from the style.

Navigating the Playground SDK


15.84 TWindowStyle Class Reference 531

Parameters:
key Name of the parameter to query.
defaultValue Default if parameter value not found.
Returns:
Value if found; defaultValue otherwise.

TLuaFunction∗ TWindowStyle::GetFunction (str key) const


Get a Lua function closure from the style.
You will need to delete the function when you’re done with it.
Parameters:
key Name of the parameter to query.
Returns:
Function if found; NULL otherwise.

TLuaTable∗ TWindowStyle::GetTable (str key)


Get a Lua table from the style.
You will need to delete the table when you’re done with it.
Parameters:
key Name of the parameter to query.
Returns:
Table if found; NULL otherwise.

int32_t TWindowStyle::GetInt (str key, int32_t defaultValue = 0) const


Get an integer parameter from the style.
Parameters:
key Name of the parameter to query.
defaultValue Default if parameter value not found.
Returns:
Value if found; defaultValue otherwise.

Playground 4.0.17.1
532 Class and File Reference

15.85 TXmlNode Class Reference


#include <pf/simplexml.h>

15.85.1 Detailed Description


The TXmlNode (this page) class is a limited XML parser. It does not support comments with
nested tags, nor most non-trivial XML extensions.
Any XML files in your assets folder will be obfuscated by default (in addition to being included
in the flat file) in a production build, so if you need them to remain human-readable, let your
producer know.

Public Member Functions

• TXmlNode ()
• TXmlNode (const char ∗name)
• virtual ∼TXmlNode ()
• uint32_t ParseStream (const char ∗data, uint32_t len, bool bOneTag=false)
• void ParseString (const char ∗data)
• void ParseFile (const char ∗filename)
• void Clear ()
• bool HasChildren () const
• TXmlNode ∗ GetChild (const char ∗name)
• void OrphanChild (TXmlNode ∗child)
• void DeleteChild (TXmlNode ∗child)
• void ResetChildren ()
• bool GetNextChild (str ∗pName, TXmlNode ∗∗pChild)
• TXmlNode ∗ CreateChild (const char ∗name)
• void SetName (const char ∗name)
• str GetName () const
• str GetContent ()
• void SetContent (const char ∗content)
• str GetAttribute (const char ∗name, bool ∗pbQuoted=NULL)
• void SetAttribute (const char ∗name, const char ∗value)
• void SetAttribute (const char ∗name, int32_t value)
• void ResetAttributes ()
• bool GetNextAttribute (str ∗pName, str ∗pValue)
• str GetChildContent (const char ∗name)
• str AsString ()

Navigating the Playground SDK


15.85 TXmlNode Class Reference 533

15.85.2 Constructor & Destructor Documentation

TXmlNode::TXmlNode ()
Default constructor.

TXmlNode::TXmlNode (const char ∗ name)


Create this node with a name.
Parameters:
name Initial name for the node.

virtual TXmlNode::∼TXmlNode ()
Destructor.

15.85.3 Member Function Documentation

uint32_t TXmlNode::ParseStream (const char ∗ data, uint32_t len, bool bOneTag = false)
Parse a stream as XML, loading contents as children of this node. Does not consume all data.
Consumes a balanced open/close tag (and everything in between)
Parameters:
data buffer to parse
len length of buffer
bOneTag normally false, set to true to consume just one tag, not a balanced open/close
Returns:
Number of Characters consumed from the buffer - will be 0, if not enough data available

void TXmlNode::ParseString (const char ∗ data)


Parse a string as XML, loading contents as children of this node.
Parameters:
data String to parse.

void TXmlNode::ParseFile (const char ∗ filename)


Parse a file as XML, loading contents as children of this node.
Parameters:
filename File to read.

Playground 4.0.17.1
534 Class and File Reference

void TXmlNode::Clear ()
Remove all children and attributes.

bool TXmlNode::HasChildren () const


Query whether this node has children
Returns:
True if has children.

TXmlNode∗ TXmlNode::GetChild (const char ∗ name)


Get a pointer to a child of the node.
Parameters:
name The name of the child to find.
Returns:
A pointer to the child. The child is still owned by the parent, so this pointer will become
invalid when the parent is deleted.

void TXmlNode::OrphanChild (TXmlNode ∗ child)


Remove a child from the parent and take ownership.
Parameters:
child A pointer to the child.

void TXmlNode::DeleteChild (TXmlNode ∗ child)


Delete a child from this node.
Parameters:
child Child to delete.

void TXmlNode::ResetChildren ()
Reset internal child iterator.
See also:
GetNextChild (this page)

bool TXmlNode::GetNextChild (str ∗ pName, TXmlNode ∗∗ pChild)


Iterate through children. MUST call ResetChildren() (this page) to start iteration.

Navigating the Playground SDK


15.85 TXmlNode Class Reference 535

Parameters:
pName Pointer to str (p. 161) to receive name of child that was found
pChild Pointer to receive next child in iteration.
Returns:

TXmlNode∗ TXmlNode::CreateChild (const char ∗ name)


Create a new child and add it to our list of children.
Parameters:
name Name of the new child.
Returns:
A pointer to the new child.

void TXmlNode::SetName (const char ∗ name)


Set the name of this node.
Parameters:
name New name.

str TXmlNode::GetName () const


Get the name of this node.
Returns:
The node’s name.

str TXmlNode::GetContent ()
Get the content of this node (the part between the opening and closing tags).
Returns:
The node content.

void TXmlNode::SetContent (const char ∗ content)


Set the content of this node.
Parameters:
content New content.

str TXmlNode::GetAttribute (const char ∗ name, bool ∗ pbQuoted = NULL)


Get an attribute of this node’s tag.

Playground 4.0.17.1
536 Class and File Reference

Parameters:
name Name of attribute to query.
pbQuoted Whether the attribute’s value is surrounded by quotes.
Returns:
The value of the attribute, if found. Otherwise an empty string.

void TXmlNode::SetAttribute (const char ∗ name, const char ∗ value)


Set an attribute to a particular value.
Parameters:
name Name of the attribute to set.
value New value for that attribute.

void TXmlNode::SetAttribute (const char ∗ name, int32_t value)


Set an attribute to a particular value.
Parameters:
name Name of the attribute to set.
value New value for that attribute.

void TXmlNode::ResetAttributes ()
Reset the internal attribute iterator.

bool TXmlNode::GetNextAttribute (str ∗ pName, str ∗ pValue)


Get the next attribute in an iteration. Call ResetAttributes() (this page) to reset the iteration.
Parameters:
pName [return] Name of the attribute.
pValue [return] Value of the attribute.
Returns:
True if another attribute was found.

str TXmlNode::GetChildContent (const char ∗ name)


Get the content of a child node.
Parameters:
name Node of child to find.
Returns:
Child content.

Navigating the Playground SDK


15.85 TXmlNode Class Reference 537

str TXmlNode::AsString ()
Parse the XML tree into an XML formatted string that can be written to a file.
Returns:
The data as a string.

Playground 4.0.17.1
538 Class and File Reference

15.86 debug.h File Reference

15.86.1 Detailed Description


Playground debug and error utility routines.

Defines

• #define ERROR_WRITE(OUT_STATEMENT)
• #define TRACE_WRITE()
• #define ASSERT(STATEMENT)
• #define VERIFY(STATEMENT)
• #define DEBUG_WRITE(OUT_STATEMENT)
• #define VERBOSE_ERROR(X)
• #define VERBOSE_DEBUG(X)
• #define VERBOSE_TRACE()

15.86.2 Define Documentation


#define ASSERT(STATEMENT)
ASSERT that a statement is returning non-zero.
In builds with INCLUDE_DEBUG_STATEMENTS set to zero (by default any non-debug build),
STATEMENT is NOT executed.
Parameters:
STATEMENT Statement to test.

Referenced by TParticleState::GetReal(), TParticleMachineState::GetSize(), TParticleMachineS-


tate::Param(), TScript::PopBool(), TParamSet::ResetPartial(), and TLuaTable::TLuaTable().

#define DEBUG_WRITE(OUT_STATEMENT)
In debug builds (when _DEBUG is 1), this function will send the contained printf-style string and
parameters to the debug log, and to the debug monitor.

DEBUG_WRITE(("Format String %d",5)); C++

All printf format codes are supported.


Note you need to enclose the parameters in a second pair of parenthesis:

DEBUG_WRITE(("Format String %d",5)); C++

All printf format codes are supported.

Navigating the Playground SDK


15.86 debug.h File Reference 539

#define ERROR_WRITE(OUT_STATEMENT)
In all builds, this function will write the contained printf-style string and parameters to the debug
log, and also to the debug monitor in debug builds.
Note you need to enclose the parameters in a second pair of parenthesis:

ERROR_WRITE(("Format String %d",5)); C++

All printf format codes are supported.


Referenced by TScript::PopBool().

#define TRACE_WRITE()
When INCLUDE_TRACE_STATEMENTS in debug.h (opposite) is set to 1, this function will out-
put the name of the function, file, and line to the debug log.

#define VERBOSE_DEBUG(X)
This macro will write an error string to the debug log in debug builds if you enable verbose de-
bugging by calling TPlatform::SetConfig( TPlatform::kVerboseDebug );
See also:
DEBUG_WRITE (opposite)

#define VERBOSE_ERROR(X)
This macro will write an error string to the debug log in debug and release builds if you enable
verbose debugging by calling TPlatform::SetConfig( TPlatform::kVerboseDebug );
See also:
DEBUG_WRITE (opposite)

#define VERBOSE_TRACE()
This macro will write an error string to the debug log in debug builds indicating the name of
the function, file, and line to the debug log if you enable verbose debugging by calling TPlat-
form::SetConfig( TPlatform::kVerboseDebug );
See also:
DEBUG_WRITE (opposite)

#define VERIFY(STATEMENT)
Verify that a statement is returning non-zero.
Acts like ASSERT, only STATEMENT is always included in the program.

Playground 4.0.17.1
540 Class and File Reference

Parameters:
STATEMENT Statement to test.

Navigating the Playground SDK


15.87 pftypeinfo.h File Reference 541

15.87 pftypeinfo.h File Reference

15.87.1 Detailed Description


Runtime type information handling support macros. This file contains a number of macros that
add a more flexible runtime-type information facility than is supported natively by C++. For any
class you want to decorate with additional runtime information, you’ll need one call in the class
definition, with a corresponding call in the implementation file. The base class definition has its
own call as well.
The basic form is PFTYPEDEF() (next page) in the class, PFTYPEIMPL() (p. 543) in the implemen-
tation file, with the base class using PFTYPEDEFBASE() (p. 543). This set would be used in classes
that do not need dynamic creation or to be stored in shared pointers.
The PFSHAREDTYPEDEF() (this page) variation is used in classes that will be held in shared
pointers. It requires that you use PFSHAREDTYPEDEFBASE() (next page) in the base class, and
that the base class be derived from enable_shared_from_this<BASECLASS>. In the implemen-
tation files you can use PFTYPEIMPL() (p. 543) with PFSHAREDTYPEDEF() (this page) or PF-
SHAREDTYPEDEFBASE() (next page).
The _DC variations are similar to the ones described above, only they also support dynamic
creation by defining a function CreateFromId() that takes the ClassId() of a class and creates a
new instance of the class. PFTYPEDEF_DC() (p. 543) matches PFTYPEIMPL_DC() (p. 543). The
PFTYPEIMPL_DCA() (p. 543) variation needs to be used for any abstract class.
See also:
Type Information and Casting (p. 25)

Defines
• #define PFTYPEDEF(THISCLASS, BASECLASS)
• #define PFTYPEDEF_DC(THISCLASS, BASECLASS)
• #define PFSHAREDTYPEDEF(BASECLASS)
• #define PFSHAREDTYPEDEF_DC(THISCLASS, BASECLASS)
• #define PFTYPEDEFBASE()
• #define PFTYPEDEFBASE_DC(THISCLASS)
• #define PFSHAREDTYPEDEFBASE(THISCLASS)
• #define PFSHAREDTYPEDEFBASE_DC(THISCLASS)
• #define PFTYPEIMPL(THISCLASS)
• #define PFTYPEIMPL_DC(THISCLASS)
• #define PFTYPEIMPL_DCA(THISCLASS)

15.87.2 Define Documentation


#define PFSHAREDTYPEDEF(BASECLASS)
Additional definitions for a class that needs run time type information, and that is controlled
through shared pointers.

Playground 4.0.17.1
542 Class and File Reference

Putting this macro in a class will declare and define IsKindOf(), GetCast() and ClassId() for that
class.
Parameters:
BASECLASS Our base class.
See also:
Type Information and Casting (p. 25)

#define PFSHAREDTYPEDEF_DC(THISCLASS, BASECLASS)


Additional definitions for a class that needs run time type information and dynamic creation, and
that is controlled through shared pointers.
Putting this macro in a class will declare and define DynamicCreate(), IsKindOf(), GetCast() and
ClassId() for that class.
Parameters:
THISCLASS The class we’re defining.
BASECLASS The (single) base class.
See also:
Type Information and Casting (p. 25)

#define PFSHAREDTYPEDEFBASE(THISCLASS)
Additional definitions for the base class of a polymorphic type that needs run time type informa-
tion, and that will be stored in shared pointers (reference counted, like TTextureRef).
Putting this macro in a class will declare and define IsKindOf(), GetCast() and ClassId() for that
class.
Parameters:
THISCLASS The current class to declare.

#define PFSHAREDTYPEDEFBASE_DC(THISCLASS)
Additional definitions for the base class of a polymorphic type that needs run time type infor-
mation and dynamic creation, and that will be stored in shared pointers (reference counted, like
TTextureRef).
Putting this macro in a class will declare and define IsKindOf(), GetCast() and ClassId() for that
class.

#define PFTYPEDEF(THISCLASS, BASECLASS)


Additional definitions for a class that needs run time type information.
Putting this macro in a class will declare and define IsKindOf(), GetCast() and ClassId() for that
class.

Navigating the Playground SDK


15.87 pftypeinfo.h File Reference 543

See also:
Type Information and Casting (p. 25)

#define PFTYPEDEF_DC(THISCLASS, BASECLASS)


Additional definitions for a class that needs run time type information and dynamic creation.
Putting this macro in a class will declare and define DynamicCreate(), IsKindOf(), GetCast() and
ClassId() for that class.
See also:
Type Information and Casting (p. 25)

#define PFTYPEDEFBASE()
Additional definitions for the base class of a polymorphic type that needs run time type informa-
tion.
Putting this macro in a class will declare and define IsKindOf(), GetCast() and ClassId() for that
class.

#define PFTYPEDEFBASE_DC(THISCLASS)
Additional definitions for the base class of a polymorphic type that needs run time type informa-
tion and dynamic creation.
Putting this macro in a class definition file will declare and define IsKindOf(), GetCast() and Clas-
sId() for that class.
Parameters:
THISCLASS The current class to declare.

#define PFTYPEIMPL(THISCLASS)
Implementation for run time type information.
Use this macro in the implementation file.

#define PFTYPEIMPL_DC(THISCLASS)
Implementation for run time type information for a class with dynamic creation.
Use this macro in the implementation file.

#define PFTYPEIMPL_DCA(THISCLASS)
Implementation for run time type information for an abstract class, descendents of which will
require dynamic creation.
Use this macro in the implementation file.

Playground 4.0.17.1
544 Class and File Reference

15.88 pflibcore.h File Reference

15.88.1 Detailed Description


Include file that PFLIB requires you load before anything else.

Functions
• void PlaygroundInit ()

15.88.2 Function Documentation


void PlaygroundInit ()
A user-defined function that will be called by Playground before TPlatform (p. 336) is initialized.
No non-static calls on TPlatform (p. 336) are allowed.
In order for this function to be called, you must define PLAYGROUND_INIT in the file where
you’re defining PLAYFIRST_MAIN, before you include pflibcore.h (this page).
This function is really designed only for setting up values with TPlatform::SetConfig() (p. 340)
that TPlatform (p. 336) will need during initialization; most application initialization still belongs
in Main().

Navigating the Playground SDK


Part III

Appendix
Appendix A

Forward Declarations

A.1 forward.h File Reference

A.1.1 Detailed Description


Forward declarations for Playground.

Typedefs
• typedef shared_ptr< TTexture > TTextureRef
• typedef shared_ptr< TAnimatedTexture > TAnimatedTextureRef
• typedef shared_ptr< TSprite > TSpriteRef
• typedef shared_ptr< TTextSprite > TTextSpriteRef
• typedef shared_ptr< TAnimatedSprite > TAnimatedSpriteRef
• typedef shared_ptr< TScriptCode > TScriptCodeRef
• typedef shared_ptr< TSound > TSoundRef
• typedef shared_ptr< TSoundInstance > TSoundInstanceRef
• typedef shared_ptr< TModel > TModelRef
• typedef shared_ptr< TAsset > TAssetRef

A.1.2 Typedef Documentation


typedef shared_ptr<TAnimatedSprite> TAnimatedSpriteRef
A reference to a TAnimatedSprite (p. 175).

typedef shared_ptr<TAnimatedTexture> TAnimatedTextureRef


A reference to a TAnimatedTexture (p. 182).
548 Forward Declarations

typedef shared_ptr<TAsset> TAssetRef


A reference to a TAsset (p. 194).

typedef shared_ptr<TModel> TModelRef


A reference to a TModel (p. 304).

typedef shared_ptr<TScriptCode> TScriptCodeRef


A reference to a TScriptCode (p. 398) object.

typedef shared_ptr<TSoundInstance> TSoundInstanceRef


A reference to a TSoundInstance (p. 413).

typedef shared_ptr<TSound> TSoundRef


A reference to a TSound (p. 409).

typedef shared_ptr<TSprite> TSpriteRef


A reference to a TSprite (p. 419).

typedef shared_ptr<TTextSprite> TTextSpriteRef


A reference to a TTextSprite (p. 454).

typedef shared_ptr<TTexture> TTextureRef


A reference to a TTexture (p. 463).

Navigating the Playground SDK


Appendix B

Annotated Class Listing

B.1 Class List


Here are the classes, structs, unions and interfaces with brief descriptions:
ParticleMember . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
T2dParticle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
T2dParticleRenderer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
TAnimatedSprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
TAnimatedTexture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
TAnimTask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
TAsset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
TAssetMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
TBegin2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
TBegin3d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
TButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
TButton::Action (An abstract action class for button actions ) . . . . . . . . . . . . . . . . . 210
TButton::LuaAction (A class that wraps a Lua command in an action ) . . . . . . . . . . . 211
TClock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
TColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
TColor32 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
TDialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
TDrawSpec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
TEncrypt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
TEvent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
TFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
TFlashHost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
TGameState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
TGameStateHandler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
TImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
TLayeredWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
TLight (A 3d light ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
550 Annotated Class Listing

TLitVert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
TLuaFunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
TLuaObjectWrapper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
TLuaParticleSystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
TLuaTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
TMat3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
TMat4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
TMaterial (A rendering material ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
TMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
TMessageListener . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
TModalWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
TModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
TParamSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
TParticleFunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
TParticleMachineState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
TParticleRenderer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
TParticleState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
TPfHiscores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
TPlatform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
TPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
TPrefs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
TPrefsDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
TRandom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
TRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
TRenderer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
TScreen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
TScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
TScriptCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
TSimpleHttp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
TSlider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
TSound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
TSoundCallBack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
TSoundInstance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
TSoundManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
TSpeex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
TSprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
TStringTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
TTask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
TTaskList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
TText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
TTextEdit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
TTextGraphic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
TTextSprite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
TTexture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
TTransformedLitVert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
TURect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
TVec2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
TVec3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481

Navigating the Playground SDK


B.1 Class List 551

TVec4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
TVert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
TVertexSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
TWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
TWindowHoverHandler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
TWindowManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
TWindowSpider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
TWindowStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
TXmlNode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532

Playground 4.0.17.1
552

Navigating the Playground SDK


553

About the Author


Tim Mensch has honed his library-design skills over more than 20 years in the games industry,
working with companies such as Lucasfilm Games, Disney Interactive, Sega, Maxis, Velocity, Has-
bro Interactive, Digital Eclipse, 3d6 Games, and Activision, and also running his own development
house. Now he is the lead architect of the Playground SDK™. Tim has a degree in cognitive sci-
ence from the University of California at San Diego, and now lives in Boulder, Colorado, with
his wife and their daughter. In his free time he enjoys his family, seeks technological solutions to
the world’s problems, works on his digital photography skills, and plays badminton and ultimate
frisbee.

Playground 4.0.17.1

You might also like