C++ Game Development By Example - Siddharth Shekar - E-Book

C++ Game Development By Example E-Book

Siddharth Shekar

0,0
32,36 €

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

Mehr erfahren.
Beschreibung

Explore modern game programming and rendering techniques to build games using C++ programming language and its popular libraries




Key Features



  • Learn how you can build basic 2D and complex 3D games with C++


  • Understand shadows, texturing, lighting, and rendering in 3D game development using OpenGL


  • Uncover modern graphics programming techniques and GPU compute methods using the Vulkan API





Book Description



Although numerous languages are currently being used to develop games, C++ remains the standard for fabricating expert libraries and tool chains for game development. This book introduces you to the world of game development with C++.






C++ Game Development By Example starts by touching upon the basic concepts of math, programming, and computer graphics and creating a simple side-scrolling action 2D game. You'll build a solid foundation by studying basic game concepts such as creating game loops, rendering 2D game scenes using SFML, 2D sprite creation and animation, and collision detection. The book will help you advance to creating a 3D physics puzzle game using modern OpenGL and the Bullet physics engine. You'll understand the graphics pipeline, which entails creating 3D objects using vertex and index buffers and rendering them to the scene using vertex and fragment shaders. Finally, you'll create a basic project using the Vulkan library that'll help you get to grips with creating swap chains, image views, render passes, and frame buffers for building high-performance graphics in your games.






By the end of this book, you'll be ready with 3 compelling projects created with SFML, the Vulkan API, and OpenGL, and you'll be able take your game and graphics programming skills to the next level.





What you will learn



  • Understand shaders and how to write a basic vertex and fragment shader


  • Build a Visual Studio project and add SFML to it


  • Discover how to create sprite animations and a game character class


  • Add sound effects and background music to your game


  • Grasp how to integrate Vulkan into Visual Studio


  • Create shaders and convert them to the SPIR-V binary format





Who this book is for



If you're a developer keen to learn game development with C++ or get up to date with game development, this book is for you. Some knowledge of C++ programming is assumed.

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

EPUB
MOBI

Seitenzahl: 405

Veröffentlichungsjahr: 2019

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



C++ Game Development By Example

 

Learn to build games and graphics with SFML, OpenGL, and Vulkan using C++ programming

 

 

 

 

 

 

 

 

 

 

Siddharth Shekar

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

C++ Game Development By Example

Copyright © 2019 Packt Publishing

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

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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.

 

Commissioning Editor: Kunal ChoudhariAcquisition Editor:Trusha ShriyanContent Development Editor:Keagan CarneiroTechnical Editor:Leena PatilCopy Editor: Safis EditingLanguage Support Editor: Storm MannProject Coordinator:Kinjal BariProofreader: Safis EditingIndexer: Pratik ShirodkarGraphics:Alishon MendonsaProduction Coordinator: Shraddha Falebhai

First published: May 2019

Production reference: 2131219

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78953-530-3

www.packtpub.com

 

To my loving mother, Shanti Shekar, and my caring father, Shekar Rangarajan, for their sacrifices and for exemplifying the power of determination.
                                                                                                – Siddharth Shekar
 

Packt.com

Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Fully searchable for easy access to vital information

Copy and paste, print, and bookmark content

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.packt.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.packt.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. 

Contributors

About the author

Siddharth Shekar is a game developer and teacher with over 6 years' industry experience and 12 years' experience in C++ and other programming languages. He is adept at graphics libraries such as OpenGL and Vulkan, and game engines such as Unity and Unreal.

He has published games on the iOS and Android app stores. He has also authored books including Swift Game Development, Mastering Android Game Development with Unity, and Learning iOS 8 Game Development Using Swift, all published by Packt Publishing.

He currently lives in Auckland, New Zealand, and is a lecturer in the games department at Media Design School. He teaches advanced computer graphics programming, PlayStation 4 native game development, and mentors final year production students.

 

 

About the reviewers

Simone Angeloni is a software engineer with over 14 years' experience in C/C++. His skill set includes cross-platform development, network communications, embedded systems, multithreading, databases, web applications, low-latency architectures, user interfaces, game development, and visual design. At present, he is the principal software engineer of the R&D department of MRMC, a subsidiary company of Nikon Corporation, where he develops robotic motion control solutions used for live broadcasts, film productions, and photography.

 

 

Andreas Oehlke is a professional full-stack software engineer. He holds a bachelor's degree in computer science and loves to experiment with software and hardware. His trademark has always been his enthusiasm and affinity for electronics and computers. His hobbies include game development, building embedded systems, sports, and making music. He currently works full-time as a senior software engineer for a German financial institution. Furthermore, he has worked as a consultant and game developer in San Francisco, CA. He is also the author of LearningLibGDX Game Development, published by Packt Publishing.

 

 

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

C++ Game Development By Example

Dedication

About Packt

Why subscribe?

Contributors

About the author

About the reviewers

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Section 1: Basic Concepts

C++ Concepts

Program basics

Variables

Strings

Operators

Statements

Iteration

Jump statements

Switch statement

Functions

Scope of variables

Arrays

Pointers

Structs

Enums

Classes

Inheritance

Summary

Mathematics and Graphics Concepts

3D coordinate systems

Points

Vectors

Vector operations

Vector magnitude

Unit vectors

The dot product

The cross product

Matrices

Matrix addition and subtraction

Matrix multiplication

Identity matrix

Matrix transpose

Matrix inverse

GLM OpenGL mathematics

OpenGL data types

Space transformations

Local/object space

World space

View space

Projection space

Screen space

Render pipeline

Vertex specification

Vertex shader

Vertex post-processing

Primitive assembly

Rasterization

Fragment shader

Per-sample operation

Framebuffer

Summary

Section 2: SFML 2D Game Development

Setting Up Your Game

An overview of SFML

Downloading SFML and configuring Visual Studio

Creating a window

Drawing shapes

Adding sprites

Keyboard input

Handing player movement

Summary

Creating Your Game

Starting afresh

Creating the Hero class

Creating the Enemy class

Adding enemies

Creating the Rocket class

Adding rockets

Collision detection

Summary

Finalizing Your Game

Finishing the Gameloop and adding scoring

Adding text

Adding audio

Adding player animations

Summary

Section 3: Modern OpenGL 3D Game Development

Getting Started with OpenGL

What is OpenGL?

Creating our first OpenGL project

Creating a window and ClearScreen

Creating a Mesh class

Creating a Camera class

The ShaderLoader class

The Light Renderer class

Drawing the object

Summary

Building on the Game Objects

Creating the MeshRenderer class

Creating the TextureLoader class

Adding Bullet Physics

Adding rigid bodies

Summary

Enhancing Your Game with Collision, Loops, and Lighting

Adding a RigidBody name

Adding an enemy

Moving the enemy

Checking collision

Adding keyboard controls

Game loop and scoring

Text rendering

Adding lighting

Summary

Section 4: Rendering 3D Objects with Vulkan

Getting Started with Vulkan

About Vulkan

Configuring Visual Studio

Vulkan validation layers and extensions

Vulkan instances

The Vulkan Context class

Creating the window surface

Picking a physical device and creating a logical device

Summary

Preparing the Clear Screen

Creating SwapChain

Creating Renderpass

Using render targets and framebuffers

Creating CommandBuffer

Beginning and ending Renderpass

Creating the clear screen

Summary

Creating Object Resources

Updating the Mesh class for Vulkan

Creating the ObjectBuffers class

Creating the Descriptor class

Creating the SPIR-V shader binary

Summary

Drawing Vulkan Objects

Preparing the GraphicsPipeline class

ShaderStageCreateInfo

VertexInputStateCreateInfo

InputAssemblyStateCreateInfo

RasterizationStateCreateInfo

MultisampleStateCreateInfo

Depth and stencil create info

ColorBlendStateCreateInfo

Dynamic state info

ViewportStateCreateInfo

GraphicsPipelineCreateInfo

The ObjectRenderer class

Changes to the VulkanContext class

The Camera class

Drawing the object

Synchronizing the object

Summary

Further Reading

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Computer graphics programming is considered to be one of the hardest subjects to cover, as it involves complex mathematics, programming, and graphics concepts that are intimidating to the average developer. Also, with alternative game engines available, such as Unity and Unreal, it is important to understand graphics programming, as it is a lot easier to make 2D or 3D games using these more sophisticated game engines. These engines also use some rendering APIs, such as OpenGL, Vulkan, Direct3D, and Metal, to draw objects in a scene, and the graphics engine in a game engine constitutes more than 50% of it. Therefore, it is imperative to have some knowledge about graphics programming and graphics APIs.

The objective of this book is to break down this complex subject into bite-sized chunks to make it easy to understand. So, we will start with the basic concepts that are required to understand the math, programming, and graphics basics. 

In the next section of the book, we will create a 2D game, initially with Simple and Fast Multimedia Library (SFML), which covers the basics that are required to create any game, and with which you can make any game with the utmost ease, without worrying about how a game object is drawn. We will be using SFML just to draw our game objects.

In the next part of the book, we will see how game objects get presented onscreen using OpenGL. OpenGL is a high-level Graphics API that enables us to get something rendered to a scene quickly. A simple sprite created in SFML goes through a lot of steps before actually getting drawn on the screen. We will see how a simple image gets loaded and gets displayed on the screen and what steps are required to do so. But that is just the start. We will see how to add 3D physics to the game and develop a physics-based game from the ground up. Finally, we will add some lighting to make the scene a little more interesting.

With that knowledge of OpenGL, we will dive further into graphics programming and see how Vulkan works. Vulkan is the successor to OpenGL and is a low-level, verbose graphics API. OpenGL is a high-level graphics API that hides a lot of inner workings. With Vulkan, you have complete access to the GPU, and with the Vulkan graphics API, we will learn how to render our game objects.

Who this book is for

This book is targeted at game developers keen to learn game development with C++ and graphics programming using OpenGL or the Vulkan graphics API. This book is also for those looking to update their existing knowledge of those subjects. Some prior knowledge of C++ programming is assumed.

What this book covers

Chapter 1, C++ Concepts, covers the basics of C++ programming, which are essential to understand and code the chapters in this book. 

Chapter 2, Mathematics and Graphics Concepts, In this chapter we cover the basic topics of maths such as vector calculations and knowledge on matrices. These are essential for graphics programming and basic physics programming. We then move on to the basics of graphics programming, starting with how a bunch of vertices is sent to the graphics pipeline and how they are converted into shapes and rendered on the screen.

Chapter 3, Setting Up Your Game, introduces the SFML framework, its uses, and its limitations. It also covers creating a Visual Studio project and adding SFML to it, creating a basic window with the basic framework of the game to initialize, update, render, and close it. We will also learn how to draw different shapes and learn how to add a textured sprite to the scene and add keyboard input.

Chapter 4, Creating Your Game, covers the creation of the character class and adding functionality to a character to make them move and jump. We will also create the enemy class to populate enemies for the game. We will add a rockets class so the player can spawn rockets when they fire. Finally, we will add collision detection to detect collisions between two sprites.

Chapter 5, Finalizing Your Game, covers finishing the game and adding some polishing touches by adding scoring, text, and audio. We'll also add some animation to the player character to make the game more lively.

Chapter 6, Getting Started with OpenGL, looks at what OpenGL is, its advantages, and its shortcomings. We'll integrate OpenGL into the Visual Studio project and use GLFW to create a window. We'll create a basic game loop and render our first 3D object using Vertex and fragment shaders.

Chapter 7, Building on the Game Objects, covers adding textures to an object. We'll include the Bullet Physics library in the project to add physics to the scene. We will see how to integrate physics with our 3D OpenGL rendered object. Finally, we will create a basic level to test out the physics.

Chapter 8, Enhancing Your Game with Collision, Loop, and Lighting, covers adding a game-over condition and finishing the game loop. We will add some finishing touches to the game by adding some basic 3D lighting and text to display the score and game-over condition.

Chapter 9, Getting Started with Vulkan, looks at the need for Vulkan and how it is different from OpenGL. We'll look at the advantages and disadvantages of Vulkan, integrate it into the Visual Studio project, and add GLFW to create a window for the project. We will create an app and a Vulkan instance, and add validation layers to check whether Vulkan is running as required. We'll also get physical device properties and create a logical device.

Chapter 10, Preparing the Clear Screen, covers the creation of a window surface to which we can render the scene. We also need to create a swap chain so that we can ping-pong between the front buffer and back buffer, and create image views and frame buffers to which the views are attached. We will create the draw command buffer to record and submit graphics commands and create a renderpass clear screen. 

Chapter 11, Creating Object Resources, covers creating the resources required to draw the geometry. This includes adding a mesh class that has all the geometry information, including vertex and index data. We'll create object buffers to store the vertex, index, and uniform buffers. We'll also create DescriptorSetLayout and Descriptor Sets, and finally, we'll create shaders and convert them to SPIR-V binary format.

Chapter 12, Drawing Vulkan Objects, covers creating the graphics pipeline, in which we set the vertices and enable viewports, multisampling, and depth and stencil testing. We'll also create an object class, which will help create the object buffers, descriptor set, and graphics pipeline for the object. We will create a camera class to view the world through, and then finally render the object. At the end of the chapter, we will also see how to synchronize information being sent.

To get the most out of this book

The book is designed to be read from the start, chapter by chapter. If you have prior knowledge of the contents of a chapter, then please feel free to skip ahead instead.

It is good to have some prior programming experience with C++, but if not, then there is a chapter on C++ programming, which covers the basics. No prior knowledge of graphics programming is assumed.

To run OpenGL and Vulkan projects, make sure your hardware supports the current version of the API. The book uses OpenGL 4.5 and Vulkan 1.1. Most GPU vendors support OpenGL and Vulkan, but for a full list of supported GPUs, please refer to the GPU manufacturer or to the wiki, at https://en.wikipedia.org/wiki/Vulkan_(API).

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

 

www.packt.com

.

Select the

 

Support

 

tab.

Click on

 

Code Downloads

.

Enter the name of the book in the

 

Search

 

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/CPP-Game-Development-By-Example. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here:

https://www.packtpub.com/sites/default/files/downloads/9781789535303_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Here, the printing ofHello, Worldis tasked to the main function."

A block of code is set as follows:

#include <iostream>// Program prints out "Hello, World" to screenint main(){std::cout<< "Hello, World."<<std::endl;return 0;}

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

int main() { //init game objects while (window.isOpen()) { // Handle Keyboard events // Update Game Objects in the scene

window.clear(sf::Color::Red);

// Render Game Objects

window.display();

} return 0; }

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "In Input and underLinker, type the following.libfiles."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

Section 1: Basic Concepts

This section covers some basic concepts of C++ game development. We need to have a good understanding of math, programming, and computer graphics to get ready for the later sections in the book.

The following chapters are in this section:

Chapter 1, C++ Concepts

Chapter 2, Mathematics and Graphics Concepts

C++ Concepts

In this chapter, we will explore the basics of writing a C++ program. Here, we will cover just enough to wrap our heads around the capabilities of the C++ programming language. This will be required to understand the code used in this book.

To run the examples, use Visual Studio 2017. You can download the community version for free at https://visualstudio.microsoft.com/vs/:

The topics covered in this chapter are as follows:

Program basics

Variables

Operators

Statements

Iteration

Functions

Arrays and pointers

Struct

and

Enum

Classes and inheritance

Program basics

C++ is a programming language, but what exactly is a program? A program is a set of instructions executed in sequence to give a desired output.

Let's look at our first program:

#include <iostream> // Program prints out "Hello, World" to screen int main() { std::cout<< "Hello, World."<<std::endl; return 0; }

We can look at this code line by line.

The hash (#) include is used when we want to include anything that is using valid C++ syntax. In this case, we are including a standard C++ library in our program. The file we want to include is then specified inside the <> angle brackets. Here, we are including a file called iostream.h. This file handles the input and output of data to the console/screen.

On the second line, the // double slash marks the initiation of a code comment. Comments in code are not executed by the program. They are mainly to tell the person looking at the code what the code is currently doing. It is good practice to comment your code so that when you look at code you wrote a year ago, you will know what the code does.

Basically, main() is a function. We will cover functions shortly, but a main function is the first function that is executed in a program, also called the entry point. A function is used to perform a certain task. Here, the printing of Hello, World is tasked to the main function. The contents that need to be executed must be enclosed in the curly brackets of the function. The int preceding the main() keyword suggests that the function will return an integer. This is why we have returned 0 at the end of the main function, suggesting that the program can be executed and can terminate without errors.

When we want to print out something to the console/screen, we use the std::cout (console out) C++ command to send something to the screen. Whatever we want to send out should start and end with the output operator, <<. Furthermore, <<std::endl is another C++ command, which specifies the end of a era line and that nothing else should be printed on the line afterward. We have to use the prefix before std:: to tell C++ that we are using the standard namespace with the std namespace. But why are namespaces necessary? We need namespaces because anyone can declare a variable name with std. How would the compiler differentiate between the two types of std? For this, we have namespaces to differentiate between the two.

Note that the two lines of code we have written in the main function have a semicolon (;) at the end of each line. The semicolon tells the compiler that this is the end of the instructions for that line of code so that the program can stop reading when it gets to the semicolon and go to the next line of instruction. Consequently, it is important to add a semicolon at the end of each line of instruction as it is mandatory.

The two lines of code we wrote before can be written in one line as follows:

std::cout<< "Hello, World."<<std::endl;return 0;

Even though it is written in a single line, for the compiler, there are two instructions with both instructions ending with a semicolon.

The first instruction is to print out Hello, World to the console, and the second instruction is to terminate the program without any errors.

It is a very common mistake to forget semicolons, and it happens to beginners as well as experienced programmers every now and then. So it's good to keep this in mind, for when you encounter your first set of compiler errors.

Let's run this code in Visual Studio using the following steps:

Open up Visual Studio and create a new project by going to

File

 

|

 

New 

|

 

Project

.

On the left-hand side, select

Visual C++

and then 

Other

. For the

Project Type

, select

Empty Project

. Give this project a 

Name

. Visual Studio automatically names the first project 

MyFirstProject

. You can name it whatever you like.

Select the 

Location

that you want the project to be saved in:

Once the project is created, in

Solution Explorer

, right-click and select

Add 

|

 

New Item

:

Create a new

.cpp

file, called the 

Source

file:

Copy the code at the start of the section into the

Source.cpp

file.

Now press the

F5

key on the keyboard or press the

Local Window Debugger

button at the top of the window to run the application.

A popup of the console should appear upon running the program. To make the console stay so that we can see what is happening, add the following highlighted lines to the code:

#include <iostream> #include <conio.h>// Program prints out "Hello, World" to screen int main() { std::cout << "Hello, World." << std::endl; _getch(); return 0; }

What _getch() does is it stalls the program and waits for a character input to the console without printing the character to the console. So, the program will wait for some input and then close the console.

To see what is printed to the console, we just add it for convenience. To use this function, we need to include the conio.h header.

When you run the project again, you will see the following output:

Now that we know how to run a basic program, let's look at the different data types that are included in C++.

Functions

So far, we have written all of our code in the main function. This is fine if you are doing a single task, but once you start doing more with a program, the code will become bigger and over a period of time everything will be in the main function, which will look very confusing.

With functions, you can break your code up into smaller, manageable chunks. This will enable you to structure your program better.

A function has the following syntax:

type function name (parameter1, parameter2) {statements;}

Going from left to right, type here is the return type. After performing a statement, a function is capable of returning a value. This value could be of any type, so we specify a type here. A function has only one variable at a time.

The function name is the name of the function itself.

Then, inside brackets, you will pass in parameters. These parameters are variables of a certain type that are passed into the function to perform a certain function.

Here is an example: two parameters are passed in but you can pass as many parameters you want. You can pass in more than one parameter per function, and each parameter is separated by a comma.