23,99 €
Learn OpenGL is your one-stop reference guide to get started with OpenGL and C++ for game development. From setting up the development environment to getting started with basics of drawing and shaders, along with concepts such as lighting, model loading, and cube mapping, this book will get you up to speed with the fundamentals.
You begin by setting up your development environment to use OpenGL on Windows and macOS. With GLFW and GLEW set up using absolute and relative linking done, you are ready to setup SDL and SFML for both the operating systems.
Now that your development environment is set up, you'll learn to draw using simple shaders as well as make the shader more adaptable and reusable. Then we move on to more advanced topics like texturing your objects with images and transforming your objects using translate, rotate and scale.
With these concepts covered, we'll move on to topics like lighting to enable you to incorporate amazing dynamic lights in your game world.
By the end of the book, you'll learn about model loading, right from setting up ASSIMP to learning about the model class and loading a model in your game environment. We will conclude by understanding cube mapping to bring advance worlds to your game.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 242
Veröffentlichungsjahr: 2018
Copyright © 2018 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 ChaudhariAcquisition Editor:Shweta PantContent Development Editor: Onkar WaniTechnical Editor: Sachin SunilkumarCopy Editor:Safis EditingProofreader: Safis EditingIndexer:Pratik ShirodkarGraphics:Jason MonteiroProduction Coordinator:Arvindkumar Gupta
First published: August 2018
Production reference: 1310818
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78934-036-5
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,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.
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
Mapt is fully searchable
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.
Frahaan Hussain is the CEO of Sonar Systems which is the world leader in educational material for the game engine Cocos2d-x, one of the best and the most popular game engines in the world. With years of experience in programming and running an online education platform (Sonar Learning), he enjoys to help and support new programmers like you. He is also a University Lecturer teaching a variety of topics in Games Programming from Games Design to OpenGL Shader Programming.
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.
Title Page
Copyright and Credits
Learn OpenGL
Packt Upsell
Why subscribe?
Packt.com
Contributors
About the author
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
Disclaimer
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Setting Up OpenGL
Setting up OpenGL using GLFW and GLEW on Windows
Downloading the essential libraries
Linking GLFW and GLEW libraries with absolute linking
Linking GLFW and GLEW libraries with relative linking
Adding a dynamic link library to the project
Setting up OpenGL using GLFW on a Mac
Downloading the GLFW and GLEW libraries for a Mac
Setting up Xcode for OpenGL
Creating the OpenGL rendering window using GLFW
Setting up OpenGL using SDL on Windows
Downloading the SDL library
Setting up OpenGL using SDL and GLEW with absolute linking
Setting up OpenGL using SDL and GLEW with relative linking
Adding a DLL file to the project
Setting up OpenGL using SDL on a Mac
Downloading the SDL and GLEW libraries
Setting up Xcode for OpenGL using SDL
Creating the OpenGL rendering window using SDL
Setting up OpenGL using SFML on Windows
Downloading the SFML library
Linking the SFML and GLEW libraries to the project
Adding a DLL file to the project
Setting up OpenGL using SFML on a Mac
Creating the OpenGL rendering window using SFML
Summary
Drawing Shapes and Applying Textures
Drawing a triangle
Adding code to draw the shape
Abstracting the shaders
Creating the shader files
Creating the Shader.h header file
Making changes to the draw triangle code
Loading and applying textures to the shape
Setting up a project to use SOIL on Windows
Setting up a project to use SOIL on Mac
Applying texture to our shape
Modifying the while loop
Updating the shader files to integrate texture coordinates
Summary
Transformations, Projections, and Camera
Transformations using GLM
Setting up a project to use GLM on Windows / Mac
Updating shader files
Applying transformations to the objects
Projections and coordinate systems
Modifications to the code
Making modifications to the shader files
Modifications to the main code
View Frustum
Modifications to while loop
Orthgraphic projection
Adding a Camera class to the project
Creating a Camera.h header file
Making modifications to main.cpp
Summary
Effects of lighting , Materials and Lightmaps
Adding an object and a light source
Creating lighting and lamp shader files
Creating shader files for the lamp
Modifying the main code to implement a cube and a light source
Modifications to the while loop
Lighting up objects
Updating the shaders
What are normals ?
Updating the lighting.frag shader
Ambient lighting
Diffuse lighting
Specular lighting
Minor change in Camera.h
Making changes to the main code
Materials
Updating shader files for Materials
Making changes to the main code to add materials to our object
Lightmaps
Making modifications to shader files
Changes to the main code to implement lightmaps
Modifying while loop
Summary
Types of light sources and combining of lights
Directional light
Directional lights
Making changes to main code to integrate directional light in our world
Point lights
The point light concept
The diffuse section
The specular section
The attenuation section
Time for changes in main.cpp
Spotlight
Making changes to shader files
Minor modification to Camera.h
Making changes to the main code
Combining light
Getting the shader files ready
Making modifications void main of lighting.frag
Changes to the main code
Summary
Implementing a Skybox Using a Cubemap
Creating shaders for the skybox
Modifications to the main.cpp file
Creating the Texture.h file
Adding cube mapping code to Texture.h
Drawing the skybox
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
OpenGL is the most popular graphics library in the world; most mobile games use OpenGL and many other applications. In this book, you'll get to learn about the fundamentals that make the awesome games we play and the game engines behind them. A step-by-step process is used to show everything, from setting up OpenGL to its essential modern features. You'll gain a good understanding of the following concepts: setting up on Windows and Mac using GLFW, SDL, and SFML, 2D drawing, 3D drawing, texturing, lighting, 3D rendering, Shaders/GLSL, model loading, and cube mapping.
Learn OpenGL is for anyone and everyone who is interested in creating games, learning how game engines work, and most importantly for anyone who is interested in learning OpenGL. The ideal reader for this book would be anyone with a passion for learning game development or looking out for an OpenGL reference guide. The skills that you'll learn in this book will be applicable to all your game development needs. You'll require a strong foundation in C++ to understand and apply the concepts of this book.
Chapter 1, Setting Up OpenGL, In this chapter, you'll get to learn how to set up OpenGL using various libraries: GLFW, GLEW, SDL, and SFML. We'll learn how to set up our OpenGL projects on Windows and Mac. We also discuss how to link the libraries to your projects using absolute or relative linking, and eventually create the rendering windows to display OpenGL graphics.
Chapter 2, Drawing Shapes and Applying Textures, takes you through drawing various shapes using shaders. We'll begin by drawing a triangle and learn to add color to it. Then, we'll use the triangle concept to draw our quadrilateral and also learn how to add texture to it.
Chapter 3, Transformations, Projections, and Camera, This chapter further builds on the previous chapter. You'll get to grips with applying transformations such as rotation and translation to our shapes, and learn to draw a cube and apply a texture to it. Then, we explore the concepts of projections (perspective and orthographic) and implement those concepts in our game world.
Chapter 4, Effects of lighting, Materials, and Lightmaps, In this chapter we'll learn to apply colors to our objects and how to create a light source such as a lamp in our game world. We'll then look at the effects of light on the objects. You'll understand different types of lighting techniques: ambient, diffused, specular lighting. We'll also explore the various real worl materials and observe the effects of light on the materials. You'll also get to learn about lightmaps in this chapter.
Chapter 5, Types of light sources and combining of lights, This chapter will discuss the different types of light sources such as directional lights, point lights, and spotlights. We'll also learn to combine the lighting effects and the light sources for our game world.
Chapter 6, Implementing a Skybox Using a Cubemap, In this chapter, you'll generate a skybox using a cubemap. You'll learn how to apply textures to the skybox and then create a separate texture file to make loading of textures in the code easier. You'll also learn to draw the skybox and create our game world using it.
Online Chapter, Model Loading, This is a bonus chapter available at https://www.packtpub.com/sites/default/files/downloads/ModelLoading.pdf. In this chapter, you'll learn how to setup Assimp (Open Asset Import Library) on Windows using CMake for all our Model Loading needs. We'll also cover setting up Assimp on Mac OS X and creating a cross-platform Mesh Class. Then we'll explore how to load a 3D model into our game. You'll also get to learn how to create a Model Class to handle loading of our model.
For this book, it's really important that you have a good foundation in C++ as in this book you will be using OpenGL with C++. It's not the easiest thing, OpenGL. If this is your first time coding or you haven't been coding for long, it is recommended you get a good grasp of C++ and then continue with the book.
The illustrations used in this book are for illustrative purposes only. We do not recommend you to misuse these in any way. For more information please consult the terms and conditions of the publishers mentioned here.
Nintendo : https://www.nintendo.com/terms-of-use
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.packt.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 & Errata
.
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 athttps://github.com/PacktPublishing/Learn-OpenGL. 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 athttps://github.com/PacktPublishing/. Check them out!
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/LearnOpenGL_ColorImages.pdf.
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: "Extract the library files for GLEW and GLFW inExternal Libraries folder. "
A block of code is set as follows:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
Any command-line input or output is written as follows:
brew install glfw3
brew install glew
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: "Open up Xcode and click on the Create a new Xcode project option."
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.packt.com/submit-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.
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.
Welcome to the world of modern OpenGL. Open Graphics Library (OpenGL) is an API that provides developers with various sets of functions that enable them to manipulate graphics and images. It is the core framework of most games today, whether it's mobile games for iOS or Android, or for other platforms, such as desktops and consoles as well. OpenGL just speaks for itself. Take a look at any sort of game you can think of, and it is doable in OpenGL. It's not just restricted to 3D; you can create 2D games as well. The 2D and 3D game engines are created using OpenGL, so it is more than capable of anything that you can think of. In this book, we will learn all the concepts necessary for 3D game development.
In this chapter, we'll take a look at how to set up OpenGL on Windows and Mac, using various libraries, such as GLFW, GLEW, SDL, and SFML. Our main focus for this chapter will be to understand how to download the libraries and set up OpenGL using those. While we are learning about how to set up our projects, we will also take a look at how to link these libraries to our project using absolute and relative linking.
The following topics will be covered in this chapter:
Downloading the essential libraries
Setting up a project on different platforms to use the libraries
Creating an OpenGL rendering window using the libraries
In this section, we'll learn how to set up OpenGL using GLFW and GLEW on your Windows system, by using Visual Studio. But, first let's understand what GLFW and GLEW are. GLFW is an OpenGL framework. It's a very lightweight framework that allows us to detect events such as keyboard input, mouse input, and other sort of inputs, but more importantly, it allows you to create a render window in which you can render your code, as OpenGL doesn't have a way of creating a rendering window, and it needs something like GLFW to create it.
GLEW is the OpenGL Extension Wrangler, which basically allows you to use OpenGL functions that are new, or more precisely, non-core. It provides systematic mechanisms during runtime to determine which OpenGL extensions are supported on the target platform. For any new functions, you essentiallyrequire something like OpenGL Extension Wrangler to initialize extensions and to write portable applications.
Let's begin our setup process by downloading the GLFW and GLEW libraries.
Let's get started with the setup, by performing below mentioned steps:
First of all, we will need Visual Studio. You might
have
already installed it. If you did, it's fantastic. If not, go to
https://visualstudio.microsoft.com/
, go to
Downloads
, and then click to download the
Visual Studio Community 2017
v
ersion. Then, follow the instructions and install Visual Studio onto your system. Once you've got that installed, you just want to make sure it's set up for the C++ environment.
Next, we will download the
OpenGL Extension Wrangler
library. Visit
http://glew.sourceforge.net/
, and then click on the
Binaries
option to download the 32-bit or 64-bit version files, as per your system requirements:
After downloading, just unzip the file and put it somewhere you find feasible to access, because for this project, and any other projects that you create, it will reference that directory. So, you don't want to be moving it around because then you will have to redo the settings for your project. For this project, it's recommended that you create a folder called OpenGL in your C: drive and place all the downloaded libraries in it. This will help you with easy access to the libraries while you are linking those to your project.
Once you have done that, we will move on to downloading
OpenGL framework
library files
.
Go to
http://www.glfw.org/
and click on the
Download
menu. We will want to download the precompiled binaries for Windows. As seen in the following screenshot, select and click to download either the 32-bit or 64-bit version as per your system requirements:
Once you've downloaded the file, unzip it and, as mentioned before, place it in the GLFW folder inside the OpenGL folder.
After we have downloaded all the necessary files, we will set up the environment in Visual Studio for OpenGL using the GLFW and GLEW libraries. Follow these steps:
Open Visual Studio, and then click on
Create new Project...:
Then, go to
Visual C++ | Windows Desktop | Windows Console Application
and name your project
GLFWOpenGL
, as seen in the following screenshot, and then click
OK:
Now, right-click on the project in the
Solution Explorer
window. Go to
Add | New Item
, and you will get an
Add New Item
window. Select
C++ File
, as this will be our main file, and let's name it
main.cpp
and then click on the
Add
button.
Next, right-click on the project in the
Solution Explorer
window
.
Click on
Properties
.
A
Property Pages
window will pop up; click on
C/C++
|
General
and then go to
Additional Include Directories
. Click on the dropdown, then click on
<Edit>
, and you will get a pop up window as follows:
As highlighted in the preceding screenshot, click on the new button and then click on the three dots. And now, browse to the
GLEW
folder inside the
OpenGL
folder. Select the
include
folder and then click on the
Select Folder
button. Next, we repeat the same process to add the GLFW library to our project. Once we have included both the libraries, click on the
OK
button.
Now, again in the
Property Pages
window, we'll go to
Linker | General
, and then go to
Additional Library Directories
. Click on the dropdown, then click on
<Edit>
, and you will get a pop-up window, as follows:
As highlighted in the preceding screenshot, click on the new button and then click on the three dots. Now, browse to the
OpenGL
folder where you have downloaded the GLEW files. Open the
lib
folder inside the
GLEW
folder, then double-click on the
Release
folder, select
Win32
, and then click on the
Select Folder
button.
Repeat the same process to include GLFW libraries. But for GLFW, you've got a bunch of different libraries that you could choose from. For our project, it's best that we select the
lib-vc2015
folder. Once you have added both the libraries, click on the
OK
button.
Next, we'll go to
Linker
|
Input
, and then go to
Additional Dependencies
.
Click on the dropdown, and then click on
Edit.
What we'll do here is type
opengl32.lib
in the textbox, as seen highlighted in the following screenshot.
opengl32.lib
is the library built into the operating system. Next, we'll type
glew32s.lib
. This is the static library and it will be statically linked to your project. If you don't want to statically link it, you can just remove the
s
from the suffix; it is up to you. Next, we'll type
glfw3.lib
, and then click on the
OK
button:
Then, click on the
Apply
button.
In the preceding section, we discussed how to download the essential libraries and how to link them up to our project with absolute linking.
In the following section, we'll study how to link these libraries to our project with relative linking, and we'll also learn about how relative linking is beneficial for us. You can use either one of them to link the libraries to your project; it's your choice.
In this section, we'll take a look at how to set up OpenGL using GLFW as the provider to create a render window with relative linking. In the previous section, we discussed absolute linking, So, let's just have a quick overview of what absolute and relative linking actually are.
Absolute linking is a process where you specifically link your libraries to the project. For example, if you create a project and you are linking up libraries like GLFW and GLEW, while linking them up, you specifically put in the paths of the directory they are in. If they're in the C: drive, you would actually put the explicit directory. But, if you move the library files to any other location, then you would have to update your Visual Studio project with the changed path.
With relative linking, the libraries are actually linked, but relative to the project. So, you don't say libraries are in the C: drive; rather, you say those relatively link to your project from a particular folder. So even if you move your libraries, it won't affect your project. It is a great method for transporting the project from one machine to an other. This method of development is preferable when you're working on a platform that doesn't really have a good visual editor; for example, platforms, such as Unity or Unreal.
So, let's get started with relatively linking our libraries and creating an OpenGL render window. Let's open up Visual Studio and follow these steps:
Click on
Create new project...
and go to
Visual C++
|
Windows Desktop
|
Windows Console Application
. Name the project
GLApp
(since we are learning how to relatively link the libraries, we've created a different project).
Then, in the
New Project
window, click on the
Browse...
button. Go to the
OpenGL
folder that we've created on the desktop (we are using this folder structure format to understand relative linking). Just select the folder and then click
OK
.
One more thing you need to do before starting the project is to create a folder called
External Libraries
within the
OpenGL
folder on desktop where you have saved your project. Extract the library files for GLEW and GLFW in the
External Libraries
folder
.
Now, we'll right-click on the project in the
Solution Explorer
window. Go to
Add | New Item
. Select
C++ File
and name it
main.cpp
, and then click on the
Add
button.
Next, right-click on the project in the
Solution Explorer
window and go to
Properties
.
A
Property Pages
window will pop up; click on
C/C++
|
General
and then go to
Additional Include Directories
. In it, click on the dropdown and then click on
<Edit>
:
Then, click on the new button. As we are doing relative linking in this section, we won't click on the three dots. Clicking on them is for absolute linking only, as we have to browse to the directory where we have stored the libraries.
In the textbox highlighted in the preceding screenshot, type
$(SolutionDir)
; this command refers to the folder that contains our
.sln
