Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Game Programming Using Qt
PREMIUM
Số trang
512
Kích thước
5.1 MB
Định dạng
PDF
Lượt xem
1646

Game Programming Using Qt

Nội dung xem thử

Mô tả chi tiết

[ 1 ]

Game Programming Using Qt

A complete guide to designing and building fun games

with Qt and Qt Quick 2 using their associated toolsets

Witold Wysota

Lorenz Haas

BIRMINGHAM - MUMBAI

Game Programming Using Qt

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system,

or transmitted in any form or by any means, without the prior written permission of the

publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the

information presented. However, the information contained in this book is sold without

warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers

and distributors will be held liable for any damages caused or alleged to be caused directly or

indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the

companies and products mentioned in this book by the appropriate use of capitals. However,

Packt Publishing cannot guarantee the accuracy of this information.

First published: January 2016

Production Reference: 1210116

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78216-887-4

www.packtpub.com

Credits

Authors

Witold Wysota

Lorenz Haas

Reviewers

Simone Angeloni

Rahul De

Pooya Eimandar

Shaveen Kumar

M. Cihan Özer

Acquisition Editor

Vinay Argekar

Content Development Editor

Pooja Mhapsekar

Technical Editor

Mrunmayee Patil

Copy Editor

Neha Vyas

Project Coordinator

Sanjeet Rao

Proofreader

Safis Editing

Indexer

Monica Ajmera Mehta

Graphics

Disha Haria

Jason Monterio

Production Coordinator

Conidon Miranda

Cover Work

Conidon Miranda

About the Authors

Witold Wysota is a software architect and developer living in Poland. He started his

adventure with Qt in 2004 when he joined QtForum.org and started answering questions

about programming with Qt. Shortly afterwards, he became part of the moderator group of

the forum. In 2006, together with the moderator team, he established QtCentre.org, which

quickly became the largest community-driven support site devoted to Qt. For a number of

years, he conducted commercial, academic, and public trainings and workshops and has

been giving lectures on Qt, Qt Quick, and related technologies. He is a certified Qt developer

and was a member of Qt Education Advisory Board with Nokia, where he helped prepare

materials in order to use Qt in educational activities.

Witold was also a technical reviewer for Foundations of Qt Development, Johan Thelin,

Apress Publishing, a book about Qt 4, and an author of a couple of articles on programming

with Qt.

In real life, he is a passionate adept of Seven Star Praying Mantis, a traditional style of

Chinese martial arts.

I would like to thank all the people who have worked on Qt's development

over the years for creating such a great programming framework, which

was the main force that helped me to shape my programming career.

I would also like to thank Lorenz for helping me with the book as well as

the team at Packt Publishing for having a magnitude of patience for me

during the process of the creation of this book.

Lorenz Haas is a passionate programmer who started his Qt career with Qt 3. Thrilled

by Qt's great community, especially the one at QtCentre.org, he immersed himself in this

framework, became one of the first certified Qt developers and specialists, and turned his

love for Qt into his profession.

Lorenz is now working at a medium-sized IT company based in Erlangen, Germany, as a lead

software architect. He mainly develops machine controls and their user interfaces as well

as general solutions for the industry sector. Additionally, he runs his own small consultancy

and programming business called Histomatics (http://www.histomatics.de).

A few years ago, he started contributing to Qt Creator. He added a couple of refactoring

options that you probably rely on a regular basis if you use Qt Creator. He is also the author

of the Beautifier plugin.

I would like to thank Witold who guided me through my first steps into the

Qt world back in the days and who still assists me with any problems that

arise. I am also very grateful to him for taking me on board for this book

writing project. He's an excellent teacher and tutor!

Secondly, I would like to thank the team at Packt Publishing, who helped

and guided us through the entire process of writing this book.

About the Reviewers

Simone Angeloni is a software developer and consultant with over a decade of experience

in C++ and scripting languages. He is a passionate gamer, but an even more passionate

modder and game designer.

He is currently working for Crytek GmbH and developing the UI of the free-to-play, award￾winning video game Warface. Before this, he was realizing configuration systems for railway

signaling and creating standalone applications with Qt. Later, he worked with universities

and the National Institute of Nuclear Physics to realize fast data acquisition for particle

accelerators.

Recently, he founded Clockwise Interactive, a game company that is currently working on the

production of its first title.

Rahul De is a 23-year-old systems and server-side engineer from Kolkata, India. He recently

graduated from the Vellore Institute of Technology with a bachelor of technology degree

in computer science and now works with ThoughtWorks. Being a tech and open source

enthusiast and a proper "geeks geek", Rahul took up programming at a very young age and

quickly matured from developing small-time native applications for desktops to maintaining

servers, writing compilers, building IDEs, and enhancing Qt. His latest pet projects involve

Medusa—a JIT compiler for Python using Qt, which aims to provide up to a 1500 percent

boost for Python projects.

Being an avid gamer, he has already dabbled quite a bit with various engines such as Unreal

and Cry. He likes to play and develop games in his spare time.

Pooya Eimandar was born on 7th January 1986. He graduated in computer science and

has a hardware engineering degree from Shomal University. He is also the author of DirectX

11.1 Game Programming, Packt Publishing.

He began his career working on various 3D simulation applications. In 2010, he founded

BaziPardaz Game Studio, and since then, he has been leading an open source game engine

(https://persianengine.codeplex.com/) at Bazipardaz.

He is currently working on a playout and CG editor tool for Alalam News Network. You can

find more information about him at http://PooyaEimandar.com/.

Shaveen Kumar is a computer scientist and engineer. He graduated from Carnegie Mellon

University in 2013 with a master's degree in entertainment technology and is working at

Google. He works there as a graphics engineer and technical artist. His main interests are in

GPU programming, parallel computing, game engine development, robotics, and computer

vision.

More information about his work can be found at http://www.shaveenk.com.

M. Cihan Özer is a game developer and researcher in computer graphics. He started his

career in game development and worked for several mobile and game companies.

He got his bachelor's degree from Ankara University, Turkey, and he is currently an MS

student at Université de Montréal, Canada. Cihan's work focuses on realistic rendering and

interactive techniques.

I would like to thank the authors of this book. It will help a lot of people

who want to learn Qt and work with it. Also, I would like to thank the great

people at Packt Publishing for giving me the opportunity to review this

book.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub

files available? You can upgrade to the eBook version at www.PacktPub.com and as a print

book customer, you are entitled to a discount on the eBook copy. Get in touch with us at

[email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for

a range of free newsletters and receive exclusive discounts and offers on Packt books and

eBooks.

TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book

library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

‹ Fully searchable across every book published by Packt

‹ Copy and paste, print, and bookmark content

‹ On demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib

today and view 9 entirely free books. Simply use your login credentials for immediate access.

[ i ]

Table of Contents

Preface xi

Chapter 1: Introduction to Qt 1

The cross-platform programming 1

Qt Platform Abstraction 2

Supported platforms 3

A journey through time 3

New in Qt 5 5

Restructured codebase 5

Qt Essentials 6

Qt Add-ons 7

Qt Quick 2.0 7

Meta-objects 8

C++11 support 8

Choosing the right license 8

An open source license 8

A commercial license 9

Summary 9

Chapter 2: Installation 11

Installing the Qt SDK 11

Time for action – installing Qt using an online installer 12

Setting up Qt Creator 15

Time for action – loading an example project 16

Time for action – running the Affine Transformations project 17

Building Qt from sources 20

Time for action – setting up Qt sources using Git 20

Time for action – configuring and building Qt 21

Summary 22

Table of Contents

[ ii ]

Chapter 3: Qt GUI Programming 23

Windows and dialogs 23

Creating a Qt project 23

Time for action – creating a Qt Desktop project 24

Adding child widgets to a window 27

Managing widget content 28

Time for action – implementing a tic-tac-toe game board 30

Qt meta-objects 33

Signals and slots 34

Time for action – functionality of a tic-tac-toe board 38

Properties 41

Declaring a property 41

Using a property 42

Time for action – adding properties to the board class 42

Designing GUIs 43

Time for action – designing the game configuration dialog 46

Time for action – polishing the dialog 48

Accelerators and label buddies 48

The tab order 49

Signals and slots 50

Using designer forms 53

Direct approach 53

The multiple-inheritance approach 54

The single inheritance approach 54

Time for action – the logic of the dialog 55

An application's main window 57

The Qt resource system 58

Time for action – the main window of the application 58

Time for action – adding a pull-down menu 61

Time for action – creating a toolbar 62

Time for action – filling in the central widget 62

Time for action – putting it all together 64

Summary 67

Chapter 4: Qt Core Essentials 69

Text handling 69

Manipulating strings 70

Encoding and decoding text 70

Basic string operations 71

The string search and lookup 72

Dissecting strings 73

Converting between numbers and strings 74

Using arguments in strings 75

Regular expressions 75

Table of Contents

[ iii ]

Time for action – a simple quiz game 76

Extracting information out of a string 78

Finding all pattern occurrences 80

Data storage 81

Files and devices 81

Traversing directories 81

Getting access to the basic file 83

Devices 84

Time for action – implementing a device to encrypt data 85

Text streams 88

Data serialization 90

Binary streams 91

Time for action – serialization of a custom structure 91

XML streams 92

Time for action – implementing an XML parser for player data 93

JSON files 99

Time for action – the player data JSON serializer 100

Time for action – implementing a JSON parser 102

QSettings 104

Summary 106

Chapter 5: Graphics with Qt 107

Raster painting 107

Painter attributes 108

Widget painting 114

Time for action – custom-painted widgets 115

Time for action – transforming the viewport 117

Time for action – drawing an oscillogram 118

Input events 120

Time for action – making oscillograms selectable 120

Working with images 123

Loading 124

Modifying 125

Painting 126

Painting text 126

Static text 127

Rich text 128

Optimized drawing 129

Time for action – optimizing oscillogram drawing 129

Time for action – developing the game architecture 131

Time for action – implementing the game board class 135

Time for action – understanding the ChessView class 139

Time for action – rendering the pieces 145

Time for action – making the chess game interactive 148

Table of Contents

[ iv ]

Time for action – connecting the game algorithm 156

OpenGL 163

Introduction to OpenGL with Qt 164

Time for action – drawing a triangle using Qt and OpenGL 165

Time for action – scene-based rendering 167

Time for action – drawing a textured cube 168

Modern OpenGL with Qt 173

Shaders 173

Time for action – shaded objects 175

GL buffers 181

Off-screen rendering 183

Summary 183

Chapter 6: Graphics View 185

Graphics View architecture 185

Items 187

Parent child relationship 187

Appearance 189

Time for action – creating a black, rectangular item 189

Time for action – reacting to an item's selection state 191

Time for action – making the item's size definable 192

Standard items 193

Coordinate system of the items 195

Time for action – creating items with different origins 196

Time for action – rotating an item 197

Scenes 198

Adding items to the scene 198

Time for action – adding an item to a scene 199

Interacting with items on the scene 200

Rendering 203

Time for action – rendering the scene's content to an image 203

Coordinate system of the scene 204

Time for action – transforming parent items and child items 206

View 208

Time for action – putting it all together! 209

Showing specific areas of the scene 211

Transforming the scene 213

Time for action – creating an item where transformations can easily be seen 213

Time for action – implementing the ability to scale the scene 214

Time for action – implementing the ability to move the scene 215

Time for action – taking the zoom level into account 217

Questions you should keep in mind 218

Table of Contents

[ v ]

The jumping elephant or how to animate the scene 218

The game play 218

The player item 219

Time for action – creating an item for Benjamin 219

The playing field 221

The scene 222

Time for action – making Benjamin move 222

Parallax scrolling 227

Time for action – moving the background 228

QObject and items 229

Time for action – using properties, signals, and slots with items 229

Property animations 230

Time for action – using animations to move items smoothly 230

Time for action – keeping multiple animations in sync 232

Item collision detection 233

Time for action – making the coins explode 233

Setting up the playing field 235

A third way of animation 236

Widgets inside Graphics View 236

Optimization 238

A binary space partition tree 238

Caching the item's paint function 239

Optimizing the view 239

Summary 241

Chapter 7: Networking 243

QNetworkAccessManager 243

Downloading files over HTTP 244

Time for action – downloading a file 245

Error handling 247

Time for action – displaying a proper error message 248

Downloading files over FTP 250

Downloading files in parallel 250

The finished signal 251

Time for action – writing the OOP conform code using QSignalMapper 252

The error signal 253

The readyRead signal 253

The downloadProgress method 254

Time for action – showing the download progress 254

Using a proxy 255

Table of Contents

[ vi ]

Connecting to Google, Facebook, Twitter, and co. 256

Time for action – using Google's Distance Matrix API 256

Time for action – constructing the query 257

Time for action – parsing the server's reply 259

Controlling the connectivity state 264

QNetworkConfigurationManager 264

QNetworkConfiguration 266

QNetworkSession 266

QNetworkInterface 268

Communicating between games 268

Time for action – realizing a simple chat program 268

The server – QTcpServer 269

Time for action – setting up the server 269

Time for action – reacting on a new pending connection 270

Time for action – forwarding a new message 271

Time for action – detecting a disconnect 273

The client 274

Time for action – setting up the client 274

Time for action – receiving text messages 275

Time for action – sending text messages 276

Improvements 277

Using UDP 278

Time for action – sending a text via UDP 278

Summary 280

Chapter 8: Scripting 281

Why script? 281

The basics of Qt Script 282

Evaluating JavaScript expressions 282

Time for action – creating a Qt Script editor 284

Time for action – sandboxed script evaluation 289

Integrating Qt and Qt Script 290

Exposing objects 290

Time for action – employing scripting for npc AI 291

Exposing functions 297

Exposing C++ functions to scripts 297

Exposing script functions to C++ 300

Time for action – storing the script 300

Time for action – providing an initialization function 302

Time for action – implementing the heartbeat event 303

Using signals and slots in scripts 304

Tải ngay đi em, còn do dự, trời tối mất!