Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
SFML Game Development
SFML Game Development

SFML Game Development: If you've got a firm grasp of C++ with a secret hankering to create a great game, this book is for you. Every practical aspect of programming an interactive game world is here – the only real limit is your imagination.

Arrow left icon
Profile Icon Henrik Valter Vogelius Profile Icon Jan Haller Profile Icon Artur Moreira Profile Icon Henrik Vogelius Hansson Profile Icon SFML +1 more Show less
Arrow right icon
₹800 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (31 Ratings)
Paperback Jun 2013 296 pages 1st Edition
eBook
₹799 ₹2919.99
Paperback
₹3649.99
Subscription
Free Trial
Renews at ₹800p/m
Arrow left icon
Profile Icon Henrik Valter Vogelius Profile Icon Jan Haller Profile Icon Artur Moreira Profile Icon Henrik Vogelius Hansson Profile Icon SFML +1 more Show less
Arrow right icon
₹800 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8 (31 Ratings)
Paperback Jun 2013 296 pages 1st Edition
eBook
₹799 ₹2919.99
Paperback
₹3649.99
Subscription
Free Trial
Renews at ₹800p/m
eBook
₹799 ₹2919.99
Paperback
₹3649.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

SFML Game Development

Chapter 2. Keeping Track of Your Textures – Resource Management

In the previous chapter, you have learned how to load a texture, and display a sprite that uses the texture. During the process of game development, you encounter such situations again and again: you need to load data from the hard disk, be it images, fonts, or sounds. This chapter intends to give you a broader understanding of the following points:

  • What is the motivation behind external resources

  • Which classes for resource handling and manipulation does Simple and Fast Multimedia Library (SFML) provide

  • What might a typical use case in a game look like

  • How do we cope with the constantly recurring need to manage resources in a simple way

Defining resources


In game development, the term resource denotes an external component, which the application loads during runtime. Another often-used term for a resource is asset.

Mostly, resources are heavyweight multimedia items, such as images, music themes, or fonts. "Heavyweight" refers to the fact that those objects occupy a lot of memory, and that operations on them, especially copying, perform slowly. This affects the way we use them in our application, as we try to restrict slow operations on them to a minimum.

Non-multimedia items such as scripts that describe the in-game world, menu content, or artificial intelligence are also considered resources. Configuration files containing user settings such as the screen resolution and the music volume are good examples of resources as well. However, when we mention resources in the book, we mostly refer to multimedia resources.

Resources are usually loaded from a file on the hard disk. Although being the most common approach, it is not...

Resources in SFML


SFML offers classes to deal with a wide variety of resources. Often, the resource classes are not directly used to output multimedia on the periphery. Instead, there is an intermediate front-end class, which refers to the resource. In contrast to the resource class which holds all the data, the front-end class is lightweight and can be copied without severe performance impacts.

All resource classes contain member functions to load from different places. Depending on the exact resource type, there may be slight deviations. A typical method to load a resource from a file has the following signature:

bool loadFromFile(const std::string& filename);

The function parameter contains the path to the file, where the resource is stored, and the return value is a bool, which is true if loading was successful, and false if it failed. It is important to check return values in order to react to possible errors, such as invalid file paths.

SFML resources also provide methods to load resources...

A typical use case


Now we have seen what kinds of different resources there are, but we do not know yet how to apply this knowledge to our game. While the approach you have seen in Chapter 1, Making a Game Tick, may work for simple examples, it does not scale well to a bigger project. As our game grows, we have to reflect about how the resources are going to be used. This is explained in the next sections.

Graphics

In our game, a crucial part will be the visual representation of the world and different objects in it. We need to think about how we get from an image on the hard disk to its visualization on the screen.

  • Game entities such as the player's airplane, enemies, or the landscape are represented with sprites and possibly texts. They do not own the heavy textures and fonts; instead they use the front-end classes to refer to them.

  • As a consequence, the resources (textures and fonts) need to be accessible by the entities. We must make sure that the resource objects stay alive as long as any...

An automated approach


Our goal is to encapsulate the just mentioned functionality into a class that relieves us from managing resources again and again. For resource management, the C++ idiom Resource Acquisition Is Initialization (RAII) comes in handy.

Note

RAII describes the principle that resources are acquired in a class' constructor and released in its destructor. Since both constructor and destructor are invoked automatically when the object is created or goes out of scope, there is no need to track resources manually. RAII is mostly used for automatic memory management (as in smart pointers), but it can be applied to any kind of resources. A great advantage of RAII over manual allocation and deallocation (such as new/delete pairs) is that deallocation is guaranteed to take place, even when there are multiple return statements or exceptions in a function. To achieve the same safety with manual memory management, every possible path would have to be protected with a delete operator. As...

Error handling


The basic steps are done, the main functionality is implemented. However, there may be errors which we have to recognize and handle meaningfully. The first error can occur during the loading of the texture. For example, the specified file might not exist, or the file might have an invalid image format, or be too big for the video memory of the graphics card. To handle such errors, the method sf::Texture::loadFromFile() returns a Boolean value that is true in case of success, and false in case of failure.

There are several strategies to react to resource loading errors. In our case, we have to consider that the texture is later needed by sprites that are rendered on the screen—if such a sprite requests the texture, we must give something back. One possibility would be to provide a default texture (for example, plain white), so the sprites are just drawn as a white rectangle. However, we do not want the player of our game to fiddle around with rectangles; he should either have...

Generalizing the approach


We have implemented everything we need for textures, but we would like to handle other resources such as fonts and sound buffers too. As the implementation looks extremely similar for them, it would be a bad idea to write new classes FontHolder and SoundBufferHolder with exactly the same functionality. Instead, we write a class template, which we instantiate for different resource classes.

We call our template ResourceHolder and equip it with two template parameters:

  • Resource: The type of resource, for example, sf::Texture. We design the class template to work the SFML classes, but if you have your own resource class which conforms to the required interface (providing loadFromFile() methods), nothing keeps you from using it together with ResourceHolder.

  • Identifier: The ID type for resource access, for example, Textures::ID. This will usually be an enum, but the type is not restricted to enumerations. Any type that supports an operator< can be used as identifier...

Summary


In this chapter, we have learned the important points about resource management. By now, we know the ideas behind resources and the facilities SFML provides to work with them. We have taken a look at a possible way resources are used in a bigger project, and implemented a generic resource holder that helps us with passing resources to different parts of the application. We also investigated possible error sources as well as techniques to handle them appropriately.

In the next chapter, we are going to develop the game world with a variety of objects in it. Most of these objects require different resources, which is a good opportunity to show our resource holder in a real-world example.

Left arrow icon Right arrow icon

Key benefits

  • Develop a complete game throughout the book
  • Learn how to use modern C++11 style to create a full featured game and support for all major operating systems
  • Fully network your game for awesome multiplayer action
  • Step-by-step guide to developing your game using C++ and SFML
  • You can find the updated code files here

Description

Game development comprises the combination of many different aspects such as game logics, graphics, audio, user input, physics and much more. SFML is an Open Source C++ library designed to make game development more accessible, exposing multimedia components to the user through a simple, yet powerful interface. If you are a C++ programmer with a stack of ideas in your head and seeking a platform for implementation, your search ends here.Starting with nothing more than a blank screen, SFML Game Development will provide you with all the guidance you need to create your first fully featured 2D game using SFML 2.0. By the end, you'll have learned the basic principles of game development, including advanced topics such as how to network your game, how to utilize particle systems and much more.SFML Game Development starts with an overview of windows, graphics, and user inputs. After this brief introduction, you will start to get to grips with SFML by building up a world of different game objects, and implementing more and more gameplay features. Eventually, you'll be handling advanced visual effects, audio effects and network programming like an old pro. New concepts are discussed, while the code steadily develops.SFML Game Development will get you started with animations, particle effects and shaders. As well as these fundamental game aspects, we're also covering network programming to the extent where you'll be able to support the game running from two different machines. The most important part, the gameplay implementation with enemies and missiles, will make up the core of our top-scrolling airplane shoot' em-up game!You will learn everything you need in SFML Game Development in order to start with game development and come closer to creating your own game.

Who is this book for?

SFML Game Development addresses ambitious C++ programmers who want to develop their own game. If you have plenty of ideas for an awesome and unique game, but don't know how to start implementing them, then this book is for you. The book assumes no knowledge about SFML or game development, but a solid understanding of C++ is required.

What you will learn

  • Learn the basics of SFML and render an airplane to the screen.
  • Create a game world to play in using entities and handle input from the player
  • Make your game richer with menus, settings, and other states
  • Implement the foundation for a GUI library
  • Populate the world with enemies and let them interact
  • Load resources like textures from the hard drive and learn about resource management
  • Animate the game object, build a particle system and look behind the scenes of rendering
  • Add music and sound effects to your game to create an immersive gaming experience
  • Implement multiplayer over a network to indulge in gameplay over the Internet

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 24, 2013
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781849696845
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. ₹800 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 24, 2013
Length: 296 pages
Edition : 1st
Language : English
ISBN-13 : 9781849696845
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 11,023.97
SFML Game Development
₹3649.99
SFML Blueprints
₹3276.99
SFML Game Development By Example
₹4096.99
Total 11,023.97 Stars icon
Banner background image

Table of Contents

10 Chapters
Making a Game Tick Chevron down icon Chevron up icon
Keeping Track of Your Textures – Resource Management Chevron down icon Chevron up icon
Forge of the Gods – Shaping Our World Chevron down icon Chevron up icon
Command and Control – Input Handling Chevron down icon Chevron up icon
Diverting the Game Flow – State Stack Chevron down icon Chevron up icon
Waiting and Maintenance Area – Menus Chevron down icon Chevron up icon
Warfare Unleashed – Implementing Gameplay Chevron down icon Chevron up icon
Every Pixel Counts – Adding Visual Effects Chevron down icon Chevron up icon
Cranking Up the Bass – Music and Sound Effects Chevron down icon Chevron up icon
Company Atop the Clouds – Co-op Multiplayer Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.8
(31 Ratings)
5 star 29%
4 star 35.5%
3 star 19.4%
2 star 16.1%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Fredrickson Aug 03, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I had written a pong game in one file. This book helped me to use a time stamp, not delta time, and using a boolean value to create smooth movement based on keys. I look forward to continuing reading.
Amazon Verified review Amazon
Thiago J. A. Maranhao May 22, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book! My recommendatio is that people first develop a game without reading this book, just to get familiarized with SFML... And then read this book to modularize their code in an excellent model...
Amazon Verified review Amazon
JMR Jul 18, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Perfecto para aprender SFML desde cero, y en general, muy bueno para introducirse en el mundo del desarrollo de video juegos. A lo largo del libro el lector desarrolla un video juego mientras se va introduciendo en los los conceptos y en la biblioteca SFML. El libro supone que el lector cuenta ya experiencia previa con C++ aunque explica algunas características introducidas en C++11.
Amazon Verified review Amazon
Willi Nov 15, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A while ago I was contacted by Packt Publishing. They were looking for “SFML professionals” to review a book they had published and I assume my activity on the SFML forums and bug tracker convinced them I fit the bill. So I got a free sample and a request to review it. I don’t get anything except the ebook out of this.With that out of the way, let’s talk about the book! It’s aptly called SFML Game Development and is about exactly that. So, what is SFML? It’s the cross-platform Simple and Fast Multimedia Library for C++ that lets you easily create windows, handle their events, do 2D graphics (while allowing you to do 3D graphics using OpenGL), sound, networking and multithreading. I’ve used it in numerous small projects and some medium-sized ones and would recommend anyone starting out making games in C++ to use it. I may personally be switching over to Qt because it’s more powerful, but it’s hardly as Simple and Fast so I don’t recommend it to beginners.So that’s SFML. You may want to use it. The book aims to teach you how. What it does not teach you is C++, and rightly so, because that’s a topic worthy of its own book, and sure enough there are plenty. (I don’t know any beginner’s books on C++ though since I’ve mostly learned through mentors so I can’t recommend any. Once you’re intermediate check out Scott Meyers.) Well, that’s not entirely true. C++ recently received a much appreciated makeover, C++11 (as in 2011). A lot of cool new features were added and the book introduces some of them where it makes sense, explaining what they do and why they’re useful. I really liked that since I had not previously looked into C++11 in depth.But I liked the rest of the book as well. It iteratively adds onto the same game (a Shmup), resulting in a playable prototype at the end of each chapter. All of SFML’s major components are used and explained, but you could just read the API documentation to learn about those. No, the important thing is that you learn how to build a game with them: Yes, just loading a texture is fairly simple, but how do you manage all the textures in your level? Drawing a sprite is easy, but what’s a reasonable way of storing them for easy manipulation? How do you make the keys customizable? How do you manage multiple states like menus, the game itself and a pause screen? The book’s so helpful because it answers these questions in addition to teaching SFML.One thing to keep in mind is that there are often multiple solutions to a given problem. When the book presented Entity hierarchies as the way to go I thought to myself: “Yes, they work for simple games like this one, but once the hierarchy grows you run into all kinds of trouble. A component-based system might be better in some cases.” But then sure enough the next paragraph explained that hierarchies aren’t the only way and mentioned component-based systems as one alternative. And that’s not the only place where the book mentions alternatives, there are multiple links to further material for those interested. Being aware of ones limits is important and this book certainly is aware of them and makes you aware, too. Take shaders, for example: It explains them on a high level but does not go into explaining the rendering pipeline, that’s simply outside of the book’s scope, and that’s okay since it’s open about it.So in conclusion what makes this book valuable is not that it teaches you how to use SFML, but how to program a game with it. And it’s also a nice introduction to some of C++11. If you know C++ and want to make games with it, this is probably the book for you.
Amazon Verified review Amazon
B. W. Jun 20, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Das Framework wird gut erklärt und mit ausführlichen Beispielen vorgestellt. Der Rahmen des Buches ist gut gewählt; es sollte nach der Lektüre kein Problem sein, mit dem Wissen aus dem Buch eigene Spiele zu schreiben. Vor allem gibt der Autor auch einen gutes Beispiel dafür, wie ein Spiel von der Architektur her aufgebaut werden kann, sodass diese aus dem Buch für andere Spiele nachgebaut und wiederverwendet werden kann.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.