SFML Game Development By Example - Raimondas Pupius - E-Book

SFML Game Development By Example E-Book

Raimondas Pupius

0,0
39,59 €

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

Mehr erfahren.
Beschreibung

Simple and Fast Multimedia Library (SFML) is a simple interface comprising five modules, namely, the audio, graphics, network, system, and window modules, which help to develop cross-platform media applications. By utilizing the SFML library, you are provided with the ability to craft games quickly and easily, without going through an extensive learning curve. This effectively serves as a confidence booster, as well as a way to delve into the game development process itself, before having to worry about more advanced topics such as “rendering pipelines” or “shaders.”

With just an investment of moderate C++ knowledge, this book will guide you all the way through the journey of game development.

The book starts by building a clone of the classical snake game where you will learn how to open a window and render a basic sprite, write well-structured code to implement the design of the game, and use the AABB bounding box collision concept.
The next game is a simple platformer with enemies, obstacles and a few different stages. Here, we will be creating states that will provide custom application flow and explore the most common yet often overlooked design patterns used in game development.
Last but not the least, we will create a small RPG game where we will be using common game design patterns, multiple GUI. elements, advanced graphical features, and sounds and music features. We will also be implementing networking features that will allow other players to join and play together.
By the end of the book, you will be an expert in using the SFML library to its full potential.

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

EPUB
MOBI

Seitenzahl: 593

Veröffentlichungsjahr: 2015

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



Table of Contents

SFML Game Development By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. It's Alive! It's Alive! – Setup and First Program
What is SFML?
SFML licensing
Resources and installation
Setting up a Microsoft Visual Studio project
Opening a window
Basics of SFML drawing
Drawing images in SFML
What is a sprite?
Common mistakes
Summary
2. Give It Some Structure – Building the Game Framework
Graduating to ravioli
Implementing the window class
Building the game class
Putting our code to work
Hardware and execution time
Controlling the frame-rate
Using the SFML clock
Fixed time-step
Common mistakes
Summary
3. Get Your Hands Dirty – What You Need to Know
Introducing snake
Game design decisions
Implementing the snake structure
The snake class
The World class
Time to integrate
Hunting bugs
Fixing bugs
Going the extra mile
Common mistakes
Summary
4. Grab That Joystick – Input and Event Management
Retrieving peripheral input
Checking for mouse input
Plug in your controller
Understanding the sf::Event
Introducing the event manager
Standard function wrapper
Building the event manager
Implementing the event manager
Integrating the Event Manager class
Moving a sprite revisited
Principles of use
Common mistakes
Summary
5. Can I Pause This? – Application States
What is a state?
The most simplistic approach
Introducing the state pattern
Defining common types
The state manager class
Defining the state manager class
Implementing the state manager
Improving the Event Manager class
Incorporating the state manager
Creating the intro state
Implementing the intro state
The main menu state
A sample game state
The means to pause
Common mistakes
Summary
6. Set It in Motion! – Animating and Moving around Your World
Use of copyrighted resources
Finding and using the current directory
Using the SFML views
Preparing application states for views
Automated resource management
Designing a resource manager
Implementing the texture manager
Introducing sprite sheets
Implementing a sprite sheet class
The base animation class
Implementing the base animation class
Directional animation
Loading the sprite sheet files
Summary
7. Rediscovering Fire – Common Game Design Elements
The game map
What is a tile?
Building the game world
The flyweight pattern
Designing the map class
The parent of all world objects
Creating the base entity class
Collisions and bounding boxes
Implementing the base entity class
Entity-on-tile collisions
Entity storage and management
Implementing the entity manager
Using entities to build characters
Implementing the character class
Creating the player
Adding enemies
Loading entities from the map file
Final editions to our code base
Changes to the shared context
Putting all the pieces together
Summary
8. The More You Know – Common Game Programming Patterns
Use of copyrighted resources
What is a programming pattern?
The entity component system
What is a component?
The position component
The bitmask
Managing entities
Implementing the entity manager
The factory pattern
Designing the systems
Entity events
Entity event queue
The base system
Implementing the base system
Handling messages
The observer pattern
The message handler class
Managing systems
Implementing the system manager
Implementing the rendering system
The sprite sheet component
The renderer
Putting the ECS to work
The new and improved map
Adjusting the Map class
Summary
9. A Breath of Fresh Air – Entity Component System Continued
Adding entity movement
The movement system
Implementing states
The state system
The entity controller
Animating the entities
Handling collisions
The collision system
Implementing the collision system
Summary
10. Can I Click This? – GUI Fundamentals
Use of copyrighted resources
What is a GUI?
GUI style
Expansion of utility functions
Font management
The core of all elements
Implementing the GUI element class
Defining GUI events
The interface class
Implementing the interface class
Summary
11. Don't Touch the Red Button! – Implementing the GUI
The GUI manager
Implementing the GUI manager
The label element
The text field element
The scrollbar element
Integrating the GUI system
Expanding the event manager
Re-implementing the main menu
Summary
12. Can You Hear Me Now? – Sound and Music
Use of copyrighted resources
Preparing the project for sound
Basics of SFML sound
Playing sounds
Playing music
Sound spatialization
Placing sounds in space
Audio manager
Defining sound properties
Managing sounds
Implementing the sound manager
Adding support for sound
Animation system hooks
Entity component system expansion
The sound emitter component
The sound listener component
Implementing the sound system
Integrating our code
Summary
13. We Have Contact! – Networking Basics
Basics of networking
SFML networking
TCP sockets
Handling multiple connections
TCP protocol specifics
User datagram protocol
Alternative to sending raw data
SFML packets
Non-blocking sockets
Letting the traffic flow
Multi-threading
Shared data protection
Creating a simple communication protocol
Keeping a UDP connection alive
Designing the client class
Implementing the client
The server class
Implementing server
A simple chat application
The chat client
Summary
14. Come Play with Us! – Multiplayer Subtleties
Use of copyrighted resources
Shared code
Additional components
Building our game server
Additions to the entity component system
Implementing combat
Server action timing
Server network system
Implementing the network system
Server entity and system management
Main server class
Implementing the world class
Server entry point
Developing the game client
Entity component system expansions
Network class and interpolation
Implementing the client network class
Client entity and system management
Putting the pieces into place
Main menu adjustments
Summary
Index

SFML Game Development By Example

SFML Game Development By Example

Copyright © 2015 Packt Publishing

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

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

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

First published: December 2015

Production reference: 1181215

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-734-3

www.packtpub.com

Credits

Author

Raimondas Pupius

Reviewers

Tom Ivanyo

Vittorio Romeo

Richa Sachdeva

Commissioning Editor

Dipika Gaonkar

Acquisition Editors

Prachi Bisht

Usha Iyer

Content Development Editor

Mamata Walker

Technical Editor

Pramod Kumavat

Copy Editors

Ting Baker

Kevin McGowan

Project Coordinator

Sanjeet Rao

Proofreader

Safis Editing

Indexer

Priya Sane

Graphics

Kirk D'Penha

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Author

Raimondas Pupius is a game development enthusiast from Lithuania. He is currently working towards getting a degree in software engineering as well as working on a few projects of his own. Starting his unofficial education in this field at the age of 9, and having been introduced to video games even prior to that, helped narrow down his decision regarding a career choice. His ultimate dream is, of course, starting his own company and creating professional games for a living. "It beats my previous choice of being a plumber when I was four years old!" he says jokingly.

His other interests include web development, which was his primary interest before game development, music, and linguistics.

First, I would like to express my deepest thanks to Usha Iyer for offering me the opportunity to write this book and bringing me on board. In addition to that, I would like to thank Prachi Bisht, Mamata Walkar, and Pramod Kumavat for being great to work with and handling the production duties.

Lastly, I would like to thank my mom, grandmother, my beautiful wife, as well as her entire family for showing me endless love and support throughout this entire ordeal. I wouldn't be where I am today without your kindness, understanding, and patience during my late-night binge writing. This book is dedicated to you!

About the Reviewers

Tom Ivanyo is an aspiring game and software developer. After learning Visual Basic, he picked up several other languages, from Assembly to C#. Currently, he is working as a software developer and spending his free time creating games along with his friend, Doug Madden. Together, they started their small gaming studio named S2D Games (http://s2dgames.com).

Vittorio Romeo is a computer science student at the University of Messina and a C++ enthusiast. Since childhood, he has been interested in computers, gaming, and programming. He learned to develop games and applications as an autodidact at a very young age. He started with the VB/C# and the .NET environment, and moved on to C++ and native cross-platform programming. He works on his open source general-purpose C++14 libraries in his spare time and develops open source free games using SFML2. The evolution of C++ is something that greatly interests him. He has also spoken about game development with the latest standard features at CppCon 2014.

Richa Sachdeva is an avid programmer. She believes in designing games that are high on educational content as well as entertainment and is giving her two cents towards creating and exploring different dimensions in the field of game programming. She is a physics graduate who somewhere along the line found her true calling in computers and has ever since been amazed by this strange pixilated world. When not thinking about games or deciding on which movie to watch, she finds solace in writing.

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.

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 PacktCopy and paste, print, and bookmark contentOn 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.

Preface

Game development is one of the most interesting career choices to date. Apart from the many other fields that are incorporated in this process, it's also a realm where pure imagination comes to life. Even during the times when one may think that there's nothing new under the sun, ground-breaking ideas are still cemented in this medium, both as revolutionary milestones and exciting adventures that will make us feel child-like excitement yet again.

Getting started with game programming is easier now than ever before! Documentation and tutorials aside, there even exist enthusiasts out there who actually put together libraries of code that can be used to eliminate the redundant or difficult parts of building different types of applications. As it so happens, one of these libraries is titled "Simple and Fast Multimedia Library", and it is the focal point of this publication.

Throughout the course of this book, three projects are built from scratch, with each one having increased complexity compared to its preceding project. We will start with a basic clone of the classical arcade game—Snake, which introduces the basics of SFML and some of the framework that is going to persist until the very end. As difficult subjects are addressed, we will begin to cobble the second project together, turning it into a side-scrolling platformer. The remaining chapters of this book focus on building and polishing an online RPG-style game that can be played with your friends! No detail of any of these projects will remain undiscussed, as you will be guided through the entire process of planning and implementing every single aspect of these projects.

If the vast array of features that need to be worked on hasn't scared you away yet, congratulations! You are about to embark on a journey of tremendous proportions. So don't let the odds intimidate you. We hope to see you at the finish line!

What this book covers

Chapter 1, It's Alive! It's Alive! – Setup and First Program, covers the fundamentals that are necessary in order to build basic SFML applications.

Chapter 2, Give It Some Structure – Building the Game Framework, introduces a better framework for the applications that will be used throughout the book. It also covers the basics of timing in video games.

Chapter 3, Get Your Hands Dirty – What You Need to Know, helps solidify all the information from the previous chapters by finishing our first game project.

Chapter 4, Grab That Joystick – Input and Event Management, elaborates on the process of obtaining a window event and peripheral information as well as using it in an automated way.

Chapter 5, Can I Pause This? – Application States, addresses the issue of state switching and blending using a state machine.

Chapter 6, Set It in Motion! – Animating and Moving around Your World, deals with the issues of screen scrolling and resource management as well as the usage and animation of sprite sheets.

Chapter 7, Rediscovering Fire – Common Game Design Elements, wraps up the second project of the book by dealing with entity management, tile-maps, and collision.

Chapter 8, The More You Know – Common Game Programming Patterns, introduces the third project of the book by covering the fundamentals of a few common programming patterns, including the entity component system.

Chapter 9, A Breath of Fresh Air – Entity Component System Continued, focuses on building common game functionality by breaking it down to its components and systems.

Chapter 10, Can I Click This? – GUI Fundamentals, breaks down how a graphical user interface can be implemented using the fundamental data types.

Chapter 11, Don't Touch the Red Button! – Implementing the GUI, picks up where the previous chapter left off and wraps up the implementation of a GUI system. We also discuss three basic element types.

Chapter 12, Can You Hear Me Now? – Sound and Music, livens up the third project of the book by bringing entity sounds and music to the table.

Chapter 13, We Have Contact! – Networking Basics, covers all the basics that are required in order to implement networking in our final project.

Chapter 14, Come Play with Us! – Multiplayer Subtleties, transforms the final project of the book into a multiplayer RPG-style death match with the application of a client-server network model as well as a combat system.

What you need for this book

Given that this book covers the SFML library, it's necessary to have it downloaded and set up. Chapter 1, It's Alive! It's Alive! – Setup and First Program covers this process step by step.

Additionally, a compiler or an IDE that supports C++11 is needed in order to compile the code that we're about to write. The code for the book has been written on and compiled with the Microsoft Visual Studio 2013 IDE on a system that runs Windows 7.

Who this book is for

This book is intended for game development enthusiasts who have at least a decent knowledge of the C++ programming language and an optional background in game design.

Conventions

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

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

#include <SFML/Graphics.hpp> void main(int argc, char** argv[]){ }

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

#include <SFML/Graphics.hpp> void main(int argc, char** argv[]){ }

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Navigate to the VC++ Directories underneath Configuration Properties by right clicking on our project and selecting Properties."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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

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

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

Customer support

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

Downloading the example code

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

Errata

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

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

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

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

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

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. It's Alive! It's Alive! – Setup and First Program

The proud feeling of building something is a powerful one. Coupled with the thrill of exploration, it hardly makes it difficult to narrow down why most of our fellow game developers do what they do. Although creation is a major force in this process, failure governs it, much like any other subject. Sooner or later, all of us will be placed in a situation where a brick wall not only derails the development of a given project, but maybe even kills the motivation to work on it. Having a good resource to fall back on is crucial during those times, especially for new developers who are just now getting their hands dirty, and that's where we come in. Our goal is to pass on the experience in the most hands-on approach by developing real projects during the course of this book.

In this chapter, we're going to be covering:

Setting up SFML on your machine and IDEFlow of an average SFML applicationOpening and managing windowsBasics of rendering

The purpose of this chapter is to ease you into the process of developing games using Simple and Fast Multimedia Library (SFML). Let's get started by first tackling the setup process!

What is SFML?

Before we start throwing terms and code your way, it's only fair we talk a little bit about the choice library for this book. As its title clearly states, SFML is a library, which speeds up and eases the process of developing applications that rely on extensive use of media content, such as video, text, still images, audio, and animation for interactivity, and we will be focusing on a specific category of those applications, that is, video games. It provides an easy to use application programming interface (API), compiles and runs out of the box on Windows, Linux, and Mac OS X, and is supported by multiple languages, such as C, .NET, C++, Java, Ruby, Python, and Go, just to name a few. Unofficial ports for certain mobile devices do exist out there, however official releases for mobile platforms are still in the works. It's also open source, so one can always go and look at the source code if one is so inclined. In this book, we will be focusing solely on development for the Windows platform using C++11.

For convenience, SFML is split into five modules, which are independent of one another and can be included on a need-to-use basis:

System: A core module, which defines most basic data structures, provides access to threads, clocks, user data streams, and other essentials.Window: This module provides a means of creating and managing a window, gathering user input and events, as well as using SFML alongside OpenGL.Graphics: Everything left to be desired graphically after fully utilizing the window module falls back on the graphics module. It deals with everything concerning two-dimensional rendering.Audio: Anything to do with playing music, sounds, audio streams, or recording audio is handled by this module.Network: The last but definitely not the least interesting module that covers sending data to other computers as well as working with a few networking protocols.

Each one of these modules is compiled in a separate library (.lib) with specific postfixes that signify whether the library is being linked statically or dynamically, as well as if it's being built in debug or release mode. Linking a library statically simply means that it gets included in the executable, as opposed to dynamic linking, where .dll files are required to be present in order for the application to run. The latter situation reduces the overall size of the application by relying on the library being present on the machine that runs it. It also means that the library can be upgraded without the need to alter the application, which can be useful when fixing bugs. Static linking, on the other hand, allows your code to be executed in environments that are more limited.

It's also important to make sure that your application is being built in a mode that's suitable for the situation. Debug mode applications are bloated with additional information that is useful when you're hunting down flaws in your programs. This makes the application run considerably slower and shouldn't be used for any other purposes than testing. When building your project in release mode, tons of different optimizations are also turned on, which not only provides a smaller executable footprint, but also a much faster running speed. This should be the mode an application is compiled in, if it is to be released for any kind of use other than debugging.

Each module is named according to the format sfml-module[-s][-d].lib. For example, the file name of a graphics library that is being linked statically and compiled in debug mode would look like this: sfml-graphics-s-d.lib. When linking dynamically or compiling in release mode, the postfixes need to be omitted. SFML also requires the SFML_STATIC macro to be defined when linking statically, which we will cover shortly when setting up our first project.

An important thing to keep in mind about the separate libraries is that they still have dependencies. Window, graphics, audio, and network libraries are dependent on the system library, which has to be linked to for any SFML application to compile and run. The graphics library is also dependent on the window library, so all three have to be linked to if an application does any drawing. The audio and networking libraries only depend on the system library.

Note

Since version 2.2, when linking SFML statically, its dependencies must also be linked to the project. These dependencies vary between major versions 2.2 and 2.3, so we're going to stick with the newest version, that is, 2.3. The graphics library requires opengl32.lib, freetype.lib, and jpeg.lib libraries. The window library depends on opengl32.lib, winmm.lib, and gdi32.lib. Linking to the system library only requires the winmm.lib library, while sfml-network-s.lib relies on ws2_32.lib in order to work. Lastly, the sound library depends on openal32.lib, flac.lib, vorbisenc.lib, vorbisfile.lib, vorbis.lib, and ogg.lib.

Each one of these five modules has a corresponding header that must be included to utilize its functionality. For example, including the graphics header would look like this:

#include <SFML/Graphics.hpp>

It is also possible to avoid including the entire module header by specifying the actual header that is desired within a module:

#include <SFML/Graphics/Color.hpp>

This gives you a chance to include only the parts that are absolutely necessary.

Note

It's best practice to use forward slashes when including libraries. Different operating systems do not recognize paths that have a backslash in them.

SFML licensing

Whenever you're utilizing a library of any sorts for your project, it's important to know what you can and cannot use it for. SFML is licensed under the zlib/libpng license, which is far from being restrictive. It allows anyone to use SFML for any purposes, even commercial applications, as well as alter and re-distribute it, given that the credit for writing the original software is left unchanged and the product is marked as an altered source. Giving credit for using the original software isn't required, but it would be appreciated. For more information, visit: http://opensource.org/licenses/Zlib.

Resources and installation

You can download the latest stable pre-built version of the library at: http://www.sfml-dev.org/download.php. It is also possible for you to get the latest Git revision and compile it yourself from here: https://github.com/LaurentGomila/SFML. The former option is easier and recommended for beginners. You have to wait for major versions to be released, however they're more stable. To build SFML yourself, you will need to use CMake, which is a tool used to generate solutions or g++ Makefiles, depending on the software that will be used to compile it. The official SFML website provides tutorials on building it yourself at: http://www.sfml-dev.org/tutorials.

After either obtaining the pre-built version of SFML or compiling it yourself, it's a good idea to move it somewhere more permanent, hopefully with a short path. It's not unusual to dedicate a directory somewhere on your local drive that will hold SFML and potentially other libraries, which can be linked to quickly and at all times. This becomes useful when dealing with several versions of the same library as well. For the rest of this book, we will assume the location of our SFML library and header directories to be at C:\libs\SFML-2.3, consequently being C:\libs\SFML-2.3\lib and C:\libs\SFML-2.3\include. These directories have to be set up correctly in your compiler of choice for the project to build. We will be using Microsoft Visual Studio 2013 throughout the course of this book, however instructions on setting up projects for Code::Blocks can be found in the tutorials section of the SFML website.

Setting up a Microsoft Visual Studio project

Create a new solution in your IDE. It can be a Win32 application or a console application, which is not really relevant, although a nice console window is often useful for debug purposes. I always go with the Empty Project option to avoid any auto-generated code. After that's done, let's prepare our project to use SFML:

Navigate to the VC++ Directories underneath Configuration Properties by right clicking on our project and selecting Properties.Only two fields are of any concern to us, the Include Directories and Library Directories. Make sure the paths to the SFML library and include directories are provided for both Debug and Release configurations.When linking SFML statically, the Preprocessor section underneath C/C++ is where you need to define the SFML_STATIC macro.Next is the Additional Library Directories in General underneath Linker. Make sure that it also points to the SFML library directory in both debug and release configurations.Lastly, we need to set up the project dependencies by editing the Additional Dependencies field in the Input section underneath Linker. It would look something like this for the debug configuration when using statically linked libraries: sfml-graphics-s-d.lib; sfml-window-s-d.lib; sfml-system-s-d.lib; opengl32.lib; freetype.lib; jpeg.lib; winmm.lib; gdi32.lib;

Remember that we need to include the system library because of library dependencies. Also note the use of -s and -d postfixes. Make sure both debug and release configurations are set up and that the release configuration omits the -d postfix.

Common mistakes

Oftentimes, new users of SFML attempt to do something like this:

sf::Sprite CreateSprite(std::string l_path){ sf::Texture texture; texture.loadFromFile(l_path); . . . return sf::Sprite(texture); }

When attempting to draw the returned sprite, a white square pops out where the sprite is supposed to be located. What happened? Well, take a look back at the section where we covered textures. The texture needs to be within scope as long as it's being used by a sprite because it stores a pointer to the texture instance. From the example above, we can see that it is statically allocated, so when the function returns, the texture that got allocated on the stack is now out of scope and gets popped. Poof. Gone. Now the sprite is pointing to an invalid resource that it cannot use and instead draws a white rectangle. Now this is not to say that you can't just allocate memory on the heap instead by making a new call, but that's not the point of this example. The point to take away from this is that proper resource management is paramount when it comes to any application, so pay attention to the life span of your resources. In Chapter 6, Set It in Motion! – Animating and Moving around Your World, we will cover designing your own resource manager and automatically dealing with situations like this.

Another common mistake is keeping too many texture instances around. A single texture can be used by as many sprites as one's heart desires. sf::Texture is not a lightweight object at all, where it's possible to keep tons of sf::Sprite instances using the same texture and still achieve great performance. Reloading textures is also expensive for the graphics card, so keeping as few textures as possible is one of the things you really need to remember if you want your application to run fast. That's the idea behind using tile sheets, which are just large textures with small images packed within them. This grants better performance, since instead of keeping around hundreds of texture instances and loading files one by one, we get to simply load a single texture and access any desired tile by specifying the area to read from. That will also receive more attention in later chapters.

Using unsupported image formats or format options is another fairly common issue. It's always best to consult the official website for the most up to date information on file format support. A short list can be found here: http://www.sfml-dev.org/documentation/2.2/classsf_1_1Image.php#a9e4f2aa8e36d0cabde5ed5a4ef80290b

Finally, the LNK2019 errors deserve a mention. It doesn't matter how many times a guide, tutorial, or book mentions how to properly set up and link your project to any given library. Nothing is perfect in this world, especially not a human being. Your IDE output may get flooded by messages that look something like this when trying to compile your project:

error LNK2019: unresolved external symbol. . .

Do not panic, and please, don't make a new forum post somewhere posting hundreds of lines of code. You simply forgot to include all the required additional dependencies in the linker input. Revisit the part where we covered setting up the project for use with SFML and make sure that everything is correct there. Also, remember that you need to include libraries that other libraries are dependent on. For example, the system library always has to be included, the window library has to be included if the graphics module is being used, and so on. Statically linked libraries require their dependencies to be linked as well.

Summary

A lot of ground has been covered in this chapter. Some of it may be a little bit difficult to grasp at first if you're just starting, but don't be discouraged just yet. Applying this knowledge practically is the key to understanding it better. It's important that you are competent with everything that has been introduced so far before proceeding onto the next chapter.

If you can truly look throughout this chapter and say with utmost confidence that you're ready to move forward, we would like to congratulate you on taking your first major step towards becoming a successful SFML game developer! Why stop there? In the next chapter, we will be covering a better way to structure code for our first game project. On top of that, time management will be introduced and we'll practically apply everything covered so far by building a major chunk of your first, fully functional game. There's a lot of work ahead of us, so get the lead out! Your software isn't going to write itself.

Chapter 2. Give It Some Structure – Building the Game Framework

Working on a project with poor structure is much like building a house with no foundation: it's difficult to maintain, extremely unstable, and will probably cause you to abandon it shortly. While the code we worked on in Chapter 1, It's Alive! It's Alive! – Setup and First Program, is functional and can be managed on a very small scale, expanding it without first building a solid framework would most likely result in tons of spaghetti code (not to be confused with ravioli code or lasagna code) being present. Although it sounds delicious, this pejorative term describes the pain of a new feature being exponentially more difficult to implement within the source code that is unstructured and executes in a "tangled" manner, which is something we'll be focusing on avoiding.

In this chapter we will cover:

Designing a window class, along with a main game classCode restructuring and proper architectureThe importance of proper time management in applicationsUsing sf::Clock and sf::Time classesFixed and variable time-steps

Graduating to ravioli

Let's start small. Every game needs to have a window, and as you already know from Chapter 1, It's Alive! It's Alive! – Setup and First Program, it needs to be created, destroyed, and its events need to be processed. It also needs to be able to clear the screen and update itself to show anything drawn after the screen was cleared. Additionally, keeping track of whether the window is being closed and if it's in full-screen mode, as well as having a method to toggle the latter would be quite useful. Lastly, we will, of course, need to draw to the window. Knowing all of that, the header of our window class will predictably look something like this:

class Window{ public: Window(); Window(const std::string& l_title,const sf::Vector2u& l_size); ~Window(); void BeginDraw(); // Clear the window. void EndDraw(); // Display the changes. void Update(); bool IsDone(); bool IsFullscreen(); sf::Vector2u GetWindowSize(); void ToggleFullscreen(); void Draw(sf::Drawable& l_drawable); private: void Setup(const std::string& l_title, const sf::Vector2u& l_size); void Destroy(); void Create(); sf::RenderWindow m_window; sf::Vector2u m_windowSize; std::string m_windowTitle; bool m_isDone; bool m_isFullscreen; };

Because we want to handle setting up our window internally, the setup method is made private, as well as the destroy and create methods. Think of these as just helper methods that the user of this class doesn't need to know about. It's a good idea to keep certain information around after the setup is done, such as the window size or the title that's being displayed above it. Lastly, we keep around two Boolean variables to keep track of the window being closed and its state regarding full screen.

Tip

The naming convention that's being employed in our window class is referred to as the Hungarian notation. Using it is, of course, not required, but it can prove useful when dealing with lots of code, trying to track down bugs, and working in larger groups of people. We'll be utilizing it throughout this book. More information about it can be found here: http://en.wikipedia.org/wiki/Hungarian_notation