Created with Sketch.
Take Up Code
12 minutes | Sep 24, 2019
261: CppCon: Interview With Conor Hoekstra About C++ Algorithms And Ranges.
This is an interview with Conor Hoekstra about C++ algorithms and ranges. Conor presented my favorite talk at CppCon 2019 called Algorithm Intuition. I asked him to talk about algorithms on this podcast and he agreed. This just proves again why CppCon is the best place to be when you want to improve your C++ skills. The presenters were all going beyond just getting up on stage and answering a few questions. They’re real people who are willing to talk and mingle and generally help out in many ways. If you’d like to improve your coding skills, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. Most of the ideas discussed in this episode will only come in C++20 and there are no books that I know of yet that focus on C++20. You can learn about the existing STL algorithms which will help you be prepared when C++20 is generally available. Listen to the episode for more details or read the summary below. Summary Have you given talks on algorithms at other conferences besides CppCon? Conor gave versions of Algorithm Intuition at meetups in the Bay Area and in San Fransisco and then at conferences at CppCon 2019 and C++ Now in 2019. What’s coming in C++ involving algorithms? Conor is on the Canadian national body for ISO and he’s working on ranges in C++20 including 12 range adapters such as transform and reverse. There will be more range adapters being added in the future from the range-v3 library. Conor works with other languages beyond C++ and there are range adapters included in these other languages. So it’s important to get the naming correct in C++ so people will know what to expect. We should follow precedence if possible that’s already been established. Conor hopes to influence C++23, C++26, and C++29. Yes, C++29 comes up in committee meetings. This is because certain additions are optimistically targeting C++26 but might not arrive until C++29. ISO is definitely working towards a long term future. What are the major changes coming in C++ algorithms? There are two different things coming with ranges. The changes are more than updated algorithms that take data structures instead of iterator pairs. The new range based algorithms let you pass collections directly instead of begin() and end(). The second part is a new piping syntax that lets you send the output from one algorithm into the next algorithm. This comes currently with adapters and potentially in the future with actions. There will be more range adapters coming that will work with both of these changes. What is piping syntax? Most Linux systems let you pipe the output from one command and send it to another command. This lets you compose commands by chaining them together. The same syntax is used for algorithms. The pipe is the vertical bar symbol on your keyboard. For US based keyboards, this is right above the enter key. As an example consider the need to calculate the number of unique words in a list. Ignoring for a moment the std::unique algorithm, how could this be done by composing other algorithms together? First sort the list, then group the result, then take the head, and finally count the result. For example, if you start with the collection a b c a b c a b c, then sorting will give you a a a b b b c c c. Going into the group algorithm will split the collection into a list of separate lists a a a, followed by b b b and then c c c. And then taking the head of each sublist gives you a collection with just a, b, and c. You can then count the items in the last result to get the answer. This is difficult to do today without using std::unique. With the new range-v3, it’s easy to take the initial list, pipe it to sort, pipe it to group, pipe it to transform_head, and then pipe it to length. If you need to learn just a handful of C++ algorithms, what would they be? There’s one algorithm that’s most under appreciated. And that’s the algorithm std::accumulate. Ben Deane gave a talk previously at CppCon 2016 called “std::accumulate: Exploring an Algorithmic Empire”. In this talk, Ben showed that almost all the standard algorithms can be implemented using std::accumulate. In other languages, this might be known as a fold or a reduce operation. This takes a list of items and reduces it down to a single item. For example, std::max_element and std::min_element are both reducing algorithms. The default operation for std::accumulate is std::plus. But if you replace this default operator with std::max or std::min, then you get the same result as std::max_element and std::min_element. What final recommendations do you have? Conor recommends learning a new programming language each year. You don’t need to become an expert. A little knowledge will help you to write better C++ code.
12 minutes | Sep 24, 2019
260: CppCon: Interview With Josh Lospinoso About The Book C++ Crash Course.
Josh Lospinoso discusses his new book C++ Crash Course. This is a book with a focus on C++17 written with a desire to simplify and make it easy for you to learn C++. I got this book during the CppCon conference and have to say, this is a fun book. It’s got lots of examples, diagrams, and tables but they’re not boring. Josh does a great job of making them blend in and support the book. Well done! I want to apologize for mispronouncing Josh’s name the first time I said it in the interview. I was so focused on pronouncing his last name correctly that I got it mixed up. Sorry, Josh! If you’d like to improve your coding skills, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. And, yes, the C++ Crash Course is listed on this page. Listen to the episode for more details or read the summary below. Summary Why write a book about C++? Josh had a difficult time learning C++ about 5 years ago. He found that it was hard for beginners to separate parts of C++ because they all fit together. He tried books, classes, and asking people. He wanted a book that didn’t put things off for a long time and wanted something that presented the material in a more linear order. Josh used the word humbling correctly in his presentation at CppCon. I don’t think this presentation was recorded. It was a lunch hour talk about writing a book. He realizes how many things we think we know until we try to teach something or write about it. He always makes sure to truly master the material so that readers can understand it better. Josh’s favorite chapter is the one about object lifecycles. The biggest single problem he’s seen is because students are not clear about when objects start and end their valid lifetimes. He explores all the various ways objects can be constructed and then destroyed. What’s the best way to make the lifecycle more relatable? Josh tries to find real world examples that are close enough to the topic without being too distracting. He tries to make the examples a bit funny by including some references to sci-fi when possible. What’s coming next? Josh will be taking a break for a short while and plans to be back for C++ 20. The current book focuses directly on C++ 17. This helps readers focus too. But C++ 20 should make it easier to teach and learn C++. Things like modules eliminate discussions around the preprocessor. And templates become easier to understand with the upcoming feature called concepts. And ranges help clean up algorithms. Any new book or updated version will likely be about 2 years out.
13 minutes | Sep 23, 2019
259: CppCon: Interview With Asad Naweed About Augmented Reality.
This is an interview with Asad Naweed about augmented reality. I met Asad at CppCon in 2019 when he asked some questions at one of the presentations I also attended. We started talking at first about teaching coding. He has taught others how to code through education programs at Google. I especially liked his business card that I recognized immediately as being related to Google Cardboard. You can find more information at https://vr.google.com/cardboard I asked him to come on the podcast to talk to you about augmented reality. If you’d like to improve your coding skills so that you can apply augmented reality in your code, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. Listen to the episode for more details or read the summary below. Summary What is augmented reality? Augmented reality, or AR for short, puts a layer over the physical world so you can use your smart phone to view additional information or images. The initial version of Pokemon Go loses the illusion of reality when you move around. This might be changing with more advanced versions that can anchor the images in the real world. Can you walk around and view images from behind? Augmented reality is inherently 3D, so, yes you should be able to do this. The application needs to be aware of anchor points and planes and use modern libraries. What about shadows and lighting in an augmented reality scene? A lot depends on the inertial measurement unit on your phone. Asad works with technology that will let you estimate where the light is coming from and create realistic looking experiences. He’s also working to lower the bar so that developers can come up with realistic images easily. How easy is it to use a Google library instead of writing something yourself? Motion tracking is a big part of this. It’s challenging to keep track of 6 degrees of freedom and has taken years of research to get this working. We still rely on the developers to specify where the anchor points will be located. The future has even more advances that will help. Google makes it easy for developers to use Unity and C#. Other options are to use Java or the C API. C++ developers can use the C API. There’s feature parity between all the APIs so you can do the same things with each of the APIs. What types of skills are needed to get into 3D augmented reality? Asad recommends using Android and having a solid knowledge of 3D math, such as matrix math and transformations. That’s because we’re dealing with 6 degrees of freedom, rigid body transformations, and animations. CppCon is an awesome experience that’s not just for advanced programmers. The conference is very beginner friendly. Also check out the #include C++ channel on Discord.
14 minutes | Sep 23, 2019
258: CppCon: Interview With Nicolai Josuttis About How The C++ Standardization Has Changed Over The Years.
This is an interview with Nicolai Josuttis about how the C++ standardization process has changed over the years. You can find more information about Nicolai at his website http://www.josuttis.com I first came to know about Nicolai through his book “The C++ Standard Library – A Tutorial and Reference” and recently started reading his new book “C++ 17 – The Complete Guide” If you’d like to improve your coding skills and deepen your knowledge too, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. I keep copies of Nicolai’s books within reach at home because I keep coming back to them. His new book is already proving just as useful. Even after programming for 30 years, I learned something new within the first 5 minutes of reading Nicolai’s new book! That’s the type of value you’ll get from his books and talks. Listen to the episode for more details or read the summary below. Summary Nicolai Josuttis has been involved in all the standards since about 1996. He talks about a time in the beginning when the chief architect, Bjarne Stroustrup, along with a few others could make decisions. There were no laptops, no internet, and no HTML. The early standards meetings were done with paper and Andrew Koenig would run samples on a PDP-11 to try things out. The Java language actually helped because a lot of people left C++ who were more interested in politics. Only the most committed remained. I had never thought about it like this but it makes sense. The standardization committee started with a core language group and a library group. Now we have a core group and a core evolution group and a library group and a library evolution group. In addition to these four main groups, there’s enough other groups to need 10 different parallel tracks for the meetings. The language changed a lot with C++11 and both Nicolai and I came back to the language. C++ is in many ways a victim of its own success. It’s not possible for any one person to understand everything. This leads to problems because there are no generalists who can see everything. We make more mistakes such as mutexes and locks. We now have many different solutions. We couldn’t change the lock classes to use templates and had to introduce a new class with variatic arguments and now we have 3 different lock classes. We also can’t consolidate because of backward compatibility. We now have 40 years of backward compatibility. It’s not all problems though. Nicolai is most excited about having a new generation getting involved. There’s a lot of young people that make a good mix. It’s a good sign. CppCon is an amazing conference that gives people access to other people that can help you. We are a C++ community. Working with 200 people in the standardization committee is a good example of dealing effectively with people. If there’s a mistake or a bug in the standard, just remember, that you might have been able to prevent it by getting involved. So please help contribute.
16 minutes | Sep 22, 2019
257: CppCon: Interview With Sean Hale About Becoming A Software Developer Without A Degree In Computer Science.
This is an interview with Sean Hale about how he got into computers and then turned a degree in literature into a job as a software development engineer. I met Sean at CppCon in 2019 and asked him to be on the podcast because of his experience. You can become a software development engineer without a college degree. This is something I mention all the time. Sean has a degree in literature. But what gave him the skills to become a software engineer was a combination of a really amazing opportunity and a lot of hard work. The opportunity didn’t just land with Sean by accident either. He made it happen by taking responsibility for his future and deciding to improve his skills. Then when he got the opportunity to learn directly from another engineer, Sean didn’t waste it. He worked his current job and took on extra duties at the same time. It was like working two jobs at once. If you’d like to improve your coding skills and deepen your knowledge too, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. Listen to the episode for more details or read the summary below. Summary Sean got into programming in high school. He enjoyed it but was worried about working with computers in a full time job. At this point, working with computers was more of a hobby for Sean. He found a customer support role that made use of his skills with computer networking and building computers. He later interviewed for a QA role and was qualified because of the product knowledge he gained while in customer support. The interview was looking for things like: Can you reason well? Can you work well with others? Sean started learning programming on his own and then worked with a team member on building a game. He was also applying his skills to automate tasks. About how long did the process take until Sean felt he was ready for a development role? After a year and a half, he interviewed but did not get the job. They needed a deeper knowledge of programming and reasoning. This showed Sean where he needed to improve. Sean was presented an opportunity to work with a software engineer over a summer to improve his skills. He was pair programming to make Monopoly in Java over lunch each day for 3 months. Then Sean started working side-by-side with other developers. All this was done while still doing his normal QA duties. This was like working two jobs at once. After another year or two, Sean went through another interview even more technical than the first and this time, he got the position. The most important lesson to learn from Sean is this: Look for opportunities and be ready to work hard when you get them.
5 minutes | Sep 22, 2019
256: What Is Hurting Your Effort To Learn Coding? How To Improve Your Learning With One Simple Trick I Discovered By Accident.
Is there something you can do that will help you learn coding? When learning something new, it helps to focus on associations, especially opposites. It’s hard to learn separate facts and ideas. Linking them together lets them reinforce each other. Instead of being more work, they will lend support. This will improve your memory too. Then, use what you learn for another link. I first discovered this helped me learn languages. But it can also help you to learn anything new. This is the advice I gave to my son to help him learn how to code. If you’d like to improve your coding skills, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. Listen to the episode for more details or read the full transcript below. This started when I asked my son what was his biggest frustration with learning how to code? Transcript I asked my son this question recently and he said that his biggest frustration was syntax. If you share this same frustration, then I have something to help. It’s a way of learning that I’ve found effective and that I use in my classes. But I’m also going to start highlighting it more because it’s a small thing that’s easily overlooked. I discovered this technique on my own many years ago when learning to speak another language. And I’ve naturally included it in my programming classes without even thinking about it. The whole technique is based on opposites. What do I mean by that? Well, we learn best when we can associate new ideas with something we already know. Just look at a common and effective way that memory experts use to remember long sequences of unrelated items. They start with a framework of things they already know very well. This could be rooms in your house and going through those rooms, you pick out certain features or aspects of each room that stand out in your mind when you think of that room. All you need to do is get these room features in a certain order. Maybe you can start with the room you first enter each day after coming home and visit each room and feature in order. Once you have this order, it’s easy to remember it. Because it’s something we’re familiar with and are exposed to every day, it’s almost impossible to forget. Then to remember other things, you just take the first thing you want to remember and associate it somehow with the first thing from your house. By making the association clear, vivid, and hopefully strange or outlandish, then it will also stand out in your memory. The whole point is that it really helps when you have something to associate a new idea with. If you just try to learn a bunch of new ideas in isolation, then you’ll quickly forget. It takes a lot of time and effort to learn by dry memorization only. Now, I’m not suggesting that you learn how to program by linking programming topics to things in your house. Although, maybe that’s not such a bad idea after all. What I encourage you to do is to learn by pairing things together into opposites. I found that when I was learning a new language, it helped to remember the word for “up” by also remembering the word for “down”. In a way, what I was doing was grouping things together so they had their own associations. I found that you can do the same thing with programming. Take syntax for example. He said something as simple as when to use parenthesis vs. curly braces can be confusing. Especially during written tests when there’s no computer to help. My advice when you find yourself in this situation is to try learning the confusing parts together. Compare them and learn how they relate to each other. I think this leads to better results than learning topics in isolation. It gives you hooks that will improve your memory because you can let the topics reinforce each other instead of fighting with each other. The C++ language uses and reuses symbols such as parenthesis for different purposes. For example, you can use parenthesis to declare a method and to call a method, to group expressions, and to initialize variables. Let’s say that you already know how to use parenthesis to call methods when you learn that they can be used to initialize variables. One thing that will help right away is to think about how this is already similar to calling a method. You’re calling a constructor in the new usage. Then it might seem like it adds complexity, but I say it helps to jump right into using curly braces to initialize variables too. This is the opposite aspect that I mentioned. Start by comparing them and what are the advantages and disadvantages of each. What can you do with one that can’t be done with another? Where are they the same? It’s these types of comparison questions that will lead to a better understanding. And when you discover a new use, go back and review the other uses. Make sure to firmly fit the new use together with the earlier uses and you’ll find better reinforcement of ideas. The next step is to put your new skills into use. Write some code. Use the new syntax in your code. This will give you another association because you’ll remember using the syntax in your program and where you used it. The more you put it to use, the stronger your associations will become.
7 minutes | Sep 22, 2019
255: How To Avoid Small Choices And Design Your Application To Scale Big.
How do you design your application so it scales well to a big size? Scaling needs to be verified early in the design to prevent costly mistakes that usually appear later. You can scale in many ways. The number of users, amount of data, and code size are common. Avoid hard limits in the code and leave room to grow. Test large amounts of data and users even if they’re not real. This episode describes some design decisions I made recently to let my game handle a large number of game objects. If you’d like to improve your coding skills, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. Listen to the episode for more details or read the full transcript below. Transcript By the time you notice that your program will not scale, it might be too late for simple fixes. There’s a balance here that will come with experience. But we usually only learn from experience when we fail. What kinds of failures am I talking about and how can you notice them before they become bigger? When we’re in school learning how to program or reading a book or even watching an online video, the goal is usually to teach some specific concept that you can use later. There’s lots of little things you should be considering but these would only get in the way of learning the main idea. So they’re left out of the topic. There’s just too many opportunities to get lost in the details when learning something new. The problems you’ll be learning about and solving will be very specific to the idea and small. Let’s say that you’re first learning how to count. It might be okay to use your fingers at first. The problems you’ll be working with are designed for this. Things like 2 plus 3 are easy to visualize with fingers. Even some subtraction can be done with fingers. But try to scale the problems so they’re bigger with sums in the thousands or millions and you run into difficulty. The same thing happens in programming. If you need to keep track of items, then you might want to use a vector. It’s easy to push new items on to a vector. And you have simple ways to find things and remove them from vectors. But you need to know when to use a vector in any type of real software application. There are times when it’s the absolute best choice. And I’m not just talking about when the sizes are small. It can scale very well to large solutions when used properly. Because it’s so simple, it’s like using your fingers. So a lot of books and classroom lectures and videos will use it when explaining another topic. I have a book right now that I’m using to get ideas for the game library that I’m working on. Finding something in an unsorted vector means that you have to examine each item one by one to see if it’s the one you want. So this book came up with the idea to use a bitmask first just to know if a particular item exists in the vector. A bitmask lets you quickly test if a binary bit is set to one and if so, then use that as a signal that the item you want is somewhere in the vector. This helps to avoid searching through the whole vector only to end up empty-handed. It’s better to know quickly and avoid the search if it’s not there. What happens if the bitmask says the item should exist in the vector? Then the code will have to start visiting each item to see if it matches. Beyond the time needed to check each item, there’s another scalability problem with this design. Because the book doesn’t use an expandable bitmask, the design has a limited number of items it can support. This number can be either 32 or 64 items. To me, this is a bigger limitation that will prevent an application from growing bigger. A vector can always be changed with a different data structure. But the use of this bitmask has a broader impact on the overall design of an application. It requires that each item have a known bit in the bitmask. It makes it harder to add new items because each new item needs to become well known to all the other items. I decided to take a different approach and register new items instead. The registered items will not have a bit to go in a bitmask. So this design allows for many more items. However many are needed. This changes how the code is designed because there’s a whole process around registration now. It’s the type of change that can be done easy early on. But would require a lot of effort later. I mentioned at the beginning that this is a balance. I’ve also seen it taken too far. I remember one response I saw several years ago to an interview coding question. The candidate was working with text and needed to be able to tell the difference between vowels and consonants. The proposed solution used a full hash table to hold the five vowels, a, e, i, o, and u. Nevermind that it left out y. This is a bigger and more elaborate solution than required. It’s not like the English language gets new vowels. I don’t remember the vowels ever changing. Now I used a hash table to quickly find items in the game library I’m working on. This is what I meant by being able to change a vector for a hash table. The effect on the design is small when just considering the vector vs. hash table but bigger when you consider the other changes this small change allows. Getting rid of the bitmask and taking a registration approach should allow the game library to grow and expand much bigger than a bitmask would allow. It also simplifies the complexity of the overall solution. Sure a hash table is a little harder and more complicated to use than a simple vector. And a bitmask is easier and simpler than registering items. But the biggest advantage I think will be in how new items can be added with no knowledge of other items. And I don’t have to go back to older items to make them aware of new items. So when you’re designing your solutions, look for hard limits and look for places where code knows about other code. If you find yourself creating a constant to track the maximum number of something. Ask yourself what will happen if you eventually need more? And as you write or change code in one place, if you find that you have to visit several other places to make allowances, then stop to look for ways that you can shift things around so that these changes can be done separately. Do this even when you think it’s no big deal and still easy to manage. Because eventually, the problem will get bigger and then you’ll feel stuck in a design that’s starting to feel like a lot of work. And when you try scaling even bigger yet, you might really wish you had made a change way back when it was a minor inconvenience.
11 minutes | Sep 2, 2019
254: GameDev: How To Use Noise To Procedurally Generate Maps And Landscape.
How do you create unique and random game worlds and maps? Unique and random game maps and worlds can be created procedurally in code using noise. The noise is good for simulating nature because it produces values that change randomly in small amounts with no abrupt changes and provides realistic curves to rivers or hills. Noise is not good for straight or square items. What does noise look like? We normally think of noise as something we hear. Something is noisy or loud. That’s not the type of noise I’m talking about. This noise is sometimes called Perlin Noise after Ken Perlin who created a computer algorithm to generate the noise. The noise is really a map of values that gradually change. It’s possible to assign colors to the values and then they form an image that looks a lot like wispy clouds. This is a picture of noise that I posted on Facebook. But we don’t use the noise directly by drawing it to the screen. The values are used to control other things such as the height of the world map or the boundaries of a forest. Anything that needs to look random with no noticeable pattern is a good choice for noise. If you’d like to improve your coding skills, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. Listen to the full episode for more details or read the full transcript below. Transcript This episode explains how I started creating game worlds by hand and now plan to generate them in code instead. When I started teaching programming, I knew that I needed to make it fun and interesting in order for you to get the most benefit. So I decided to use games. I taught the first few students how to build simple text-based games that we could build in just a few hours. By text-based, I mean a game that only needs text output to display and a keyboard for a player to type. Something like Tic-Tac-Toe is a perfect example. The board can be drawn over several lines using dashes and vertical lines to draw the borders. And letters to show the occupied squares. These were simple and allowed students to focus on the language and what it means to program. I still use these types of games in my classes. But now, I do have something a little more exciting and that’s a racing game. It still uses simple text such as dots for the outline of the race track and the letter V for the race car. The idea is to move the car left or right to stay on the road as the dots scroll by to make it look like the car is moving. But I know you want more than this. So I started building a two dimensional or 2D side scroller game that uses graphics. It has a character that animates so it looks like it’s walking, running and jumping. When it jumps, it waves its arms to keep balance. A side scroller game lets you move the character left or right and the background shifts to make it seem like the character is moving. The character can also jump onto floating platforms or fall into pits where the game ends. I decided to use a 2D game mainly to keep things simple so you could focus more on the programming instead of learning all the details of a full three dimensional or 3D game engine. It’s a bit old school but sure looks a lot better than a black text screen with some dots and a few letters. A side scroller game like this needs to know where the ground is and where the floating platforms are and where the pits are. It needs a map. It’s a simple map because everything can be built using square tiles. There’s a tile for grass with a bit of dirt showing under the grass. Or maybe it could be a stone tile that looks like bricks. Or ice. The tiles can be anything as long as they’re square so they can be placed next to each other to build a ground for the player to walk on and jump onto. The game usually has multiple levels that get harder. Each level is very wide and normally just as high as a single screen will show. It’s called a side-scroller because the maps is so wide that the whole level can’t be shown at once and needs to scroll left or right as the player walks or runs. For a game like this, it’s possible to place the tiles by hand. By that, I mean that you as the programmer can decide how big each level is and specify in the code or in some text file that the code reads that there should be a grass tile over here, another grass tile over there, a stone tile placed just above them, etc. You design each level by placing enough tiles until the level is filled up exactly the way you want it. Building a game like this lets you craft unique experiences for each level. If there’s a special challenge you want the players to solve, then you can design the level with this in mind. It’s a lot of work and each level needs to be built one at a time. If you want a bigger game with more levels, then you need to build bigger and more levels. What I found though was that even a 2D game introduced a lot of new concepts to new programmers. Concepts that distracted them from learning how to code. It wasn’t nearly as overwhelming as 3D but still was a bit too much for some students. So I went back to text. But I wanted something more exciting than Tic-Tac-Toe. I decided to focus on building a top-down Rogue-style game. This is a game where you move your character around a game world and explore and fight monsters. The view is always from the top looking down. I figured that I could use the same idea of maybe dots for walls and letters for other things. The letter T could be used to show there’s a tree at some spot. Stuff like that. Now all I needed was a way to place all the trees, walls, bushes, roads, rivers, bridges, etc. that would make up the game world. This type of game is more open. So instead of individual levels, there’s a bigger world map. By world, most games usually mean a small section of a world. And not a full globe. Games like this also have an idea of zooming out to get the full view of the whole world map or zooming in to see the details of what’s currently around the player. Anyway, I thought about how I could achieve this for quite some time. Placing individual trees and other terrain over the whole map was too much for this type of game. I mean, it could work. If you play some popular online or big game studio games that have a detailed world that never changes, then it was probably built by hand. Every house, tree, car, bridge, etc. was put in a specific spot for a reason. Somebody had to look at the map and say, “I think we need a delivery truck here. Oh, and let’s put the mailbox for this house right here.” This was too much work for too little benefit for what I was trying to do. I needed something different. One idea that I came up with was to start at the zoomed out level and create a map that would show forests and lakes and rivers and other large terrain features. Then I’d fill in the details as the player zoomed in. By randomly shifting from a forest to individual trees, this seemed like it might work. But there were problems. The details started making the code harder to understand. What if the map needed to shift from a forest to a lake? I didn’t want random trees sticking up from the lake. But shifting from a forest to grassland was okay to have a few trees in the grass. And going from a forest to a marsh was okay to have dead trees in the water. I started to look around to see how other programmers have solved this type of challenge. One of the creators that I found on Patreon has some YouTube videos on how to generate planets. This was exactly the type of thing I needed. I started watching the videos and learned about something called noise. The video just showed how to include some code and then use the noise to generate a planet. I took this a bit further and investigated exactly how the noise was generated. That’s probably a topic for another episode. For now, I’ll just describe how noise can help solve the problem of shifting from one terrain type to another. The first thing is that this solution can be made entirely in code. There’s no need, unless you want to, to hand place anything. What noise gives you is a value based on coordinates you pas to it. The value might be somewhere between 0 and 1. Or it could be between -1 and 1. It’s not hard to switch between these ranges. The important point is that you pass in coordinates based on the location in the map and get back a value. If you pass in two coordinates near each other, then you’ll get back two noise values that are also close to the same value. This means that as you slowly move through the map, then the noise value will slowly change. There are no abrupt changes. This helps to mimic the way a landscape will have rolling hills that gradually go up and down. The noise values might shift gradually, but they do so in a random manner. So over larger distances, you can find the noise values to be very different. This mimics that way those rolling hills can turn into mountains in the distance. Now that we have a noise value that shifts slowly, we can multiply it to make the change larger. It wouldn’t be much of a change even for mountains if the entire landscape only changed an inch or so up or down. So we need to multiply the noise to make it more noticeable. Then we can start with a perfectly flat world and add the noise to that. This will cause the world to shift up and down based on the amplified noise level. All we need to do is pick a certain level for sea level. This can be anything we want based on how much water we want in the world. Anything below this water level will be cut off and replaced with a flat value again for the surface of the water. The same thing can be done for lakes. Once we have the elevation of the land set and water levels figured out, we
7 minutes | Sep 2, 2019
253: Creative Ways To Use C++ Curly Braces Beyond Just Functions And Loops.
This episode will explain how you can use curly braces in C++ to create a new scope. You can use this ability to control name visibility and reduce name conflicts. And you can also use curly braces to control exactly when object constructors and destructors are run. This is possible because C++ has very specific rules about when objects are constructed and destructed. Other languages that use garbage collection can’t give you this level of control. If you’d like to improve your coding skills, then browse the recommended books and resources at the Resources page. You can find all my favorite books and resources at this page to help you create better software designs. Listen to the full episode for more details or read the full transcript below. Transcript Did you know that you can use curly braces for more than just function and loop bodies? When writing a function, or a class, or an if statement, or a loop, C++ uses an opening curly brace to begin the body of the function, class, if/else statement, or loop. Then you put all the normal statements and close it all with a matching closing curly brace. We get so used to this that we don’t usually notice the curly braces anymore. At least until we miss one and have to hunt through the code to find where it’s missing. It helps to keep your braces aligned and your indentation consistent. It makes it easy to spot a missing curly brace. This is one of the reasons that I put curly braces on their own lines. I like mine unindented from the class, method, or loop and then indent the code inside them. That’s just my personal preference. A lot of books place the opening curly brace at the end of the previous line which saves vertical space. This is important in books. And I think a lot of people become used to see code written this way and then write their own code the same. This episode is not about where to put your curly braces though. The only thing I’ll suggest is that whatever style you like, at least be consistent. This episode is about something else. Something so obvious that many people are not even aware of it. You see, not only are braces used to define the body of a class, method, or loop, they also define a scope. If you declare a local variable inside a method, then that variable is scoped to that method. This means the compiler will only let you refer to the variable by name from within that method. When the method begins, the variable is constructed. And when the method ends, the variable is destructed. And you can do the same thing inside a loop. Only this time, the variable will be constructed and destructed on each pass through the loop. And you can declare member variables inside a class definition which then get constructed whenever you create instances of the class and get destructed when the class instances get destructed. The curly braces define the scope and how they’re used, either as part of a class, or a method, or a loop defines the lifetime of that scope. The interesting thing is that you don’t need to write a new method or loop in order to get a new scope. As long as you’re writing code inside a method, you can put matching opening and closing curly braces anywhere you want. They don’t have to be attached to an “if” statement or a “for” loop. The real question is why would you want to do this? The C++ language is very specific about when and in what order constructors and destructors will be called. When you need to adjust this order, then adding a new pair of curly braces might be just what you need. The nice thing is that you’re not limited to using only the variables declared inside the curly braces. You just need to be aware that any variables you declare inside the curly braces won’t be available anymore once you leave. Let’s say you declare an int type called count at the beginning of a method. You can use count from that point forward until the end of the method. You can pass it to other methods. You can use it inside if statements. And you can use it inside extra curly braces. The only thing you can’t do is use any variables declared inside the curly braces once you leave the curly braces. What happens if you declare another variable of any type within the curly braces also called count? This is also okay as long as you’re aware that count within the curly braces refers to the new one and not the one declared outside. You can use this to your advantage if you ever need to declare a macro that needs its own variable. By defining the macro to use its own scope with curly braces, then the variable name is guaranteed to not conflict with any other variable names. Or maybe you want to use the same variable name multiple places within your method for different purposes and maybe with different types? I’d normally suggest not doing this but maybe you have a good reason. You can use separate scopes defined with curly braces to do this. Maybe you’re writing code that will be used to generate more code. This sounds like computers programming themselves. But we’re not that advanced yet. You just want to write some routine code based on input that’s well understood. The problem is this code is tedious and easy to make mistakes. That’s a perfect job for a program to handle. This is the solution I created when designing a Google Protocol Buffers implementation. I needed a program that would read a message definition and create code that could serialize that message. Don’t worry if this part doesn’t make sense right now. The point is that I had C++ code that read an input file and generated more C++ code as output. This generated code can then be included in your projects to allow it to send messages to other applications. Other than managing name collisions, you’ll be more likely to use curly braces to manage variable lifetimes like I started explaining before getting sidetracked. This is not very interesting for integral types but can get interesting for complex types. Especially your own classes. If your class does some extra work during construction and maybe cleans up, or prints a message, or logs a time, etc. during destruction, then by declaring and using this class as a variable inside curly braces, you can control when all this work happens.
5 minutes | Sep 1, 2019
252: How To Handle Frustration When Learning To Code.
What’s the best way to handle frustration when learning to code? Knowing that all developers face frustration at times is a big help. You’re not alone. And it doesn’t mean that coding is not for you. Treat it as a learning opportunity and stick with it until you solve the problem. Keep trying ideas until one works. Remember the satisfaction waiting for you when your code works. This episode describes how we try many things before we finally find a solution. And why is that solution the last thing we would have thought of? It happens to us in other situations too. When you can’t find your keys and you’ve searched everywhere, what do you do? You keep looking and eventually find them where? In the last place you would have thought of. This happened to me once. I could not find the key to my tractor. Yes, I used to have a tractor. It was a single key and was nowhere to be found. I finally gave up and just didn’t use my tractor for several weeks. I didn’t really give up. I would look for that key sometimes but it was nowhere to be found. One day, I was moving my boots and saw the key inside one of the boots! I must have dropped it and it fell into my boot. Who would have guessed that’s where the key was? It really was the last place I would have suspected. Or was it? Listen to the episode or read the full transcript to understand what I mean. Transcript That’s the last thing I would have thought of! You’ve probably heard some people say things like this before. And maybe you use this expression too. What does it mean? Well, we usually say something like this when we try something for a long time before finally succeeding. Maybe you lost something and after searching for an hour, you find it where? In the last place you would have expected. I read a book once where the main character was looking for a guru to help with his quest. He was searching when he came across a person sitting on a rock. He asked the person if he knew where the guru could be found. The person on the rock told him to keep looking because this will be the last place the guru will be found. Most people take this to mean that they should look somewhere else. But the main character sat down in front of the rock and waited. When the other person asked why he hadn’t left yet, he answered that he was in the right location. After all, if this really was the last place the guru will be found, then why would he continue looking after he had already found the guru. I always like this example because it applies so much to programming. You will encounter problems that need to be solved when programming. These are like puzzles sometimes. There’s not always a single correct answer to programming challenges and many times, we’ll be glad to find any solution that meets our needs. Now, when you’re looking for a solution, where do you start? Do you go straight for the most unlikely or difficult solution? No. We start first with simple attempts and work our way to more elaborate solutions. What do you do when you find something that works? You complete that task and move on to the next challenge. In other words, it doesn’t matter if the problem is simple or hard. We always stop at the last thing we think of. Okay, maybe that’s not entirely true for simple problems. I can usually think of several approaches to solving something and if I decide to start with the second of three possible solutions and it works, then technically, I didn’t stop at the last thing that I thought of. But we tend to forget about simple problems and remember only the big ones. The ones that take a week to solve or more. In those cases, you quickly go through all your initial ideas and reject them for one reason or another. This is when frustration sets in. We’ve tried everything we can think of and so far nothing has worked well enough. Now, when a new idea comes to mind, we try it right away. And if it works, and if the problem was difficult enough, then we remember that it was the last thing we would have thought of. The important thing to remember is that these problems will arise. Especially when you’re starting to learn how to program. Treat them as learning opportunities because that’s when your skills will improve. Don’t think that just because you struggle quite often with programming challenges that you’re not meant to be a programmer. Or that you’re not cut out to be a programmer. Or that surely somebody with more experience never needs to struggle anymore. We all face challenges that are difficult. And if you ever find something is no longer challenging, then that’s a sure sign that you’ve stopped growing. I remember when I was in grade school, and we had this concept of a reading level. We were told to select books that were in our reading level so they wouldn’t be either too easy or too difficult. I forget when exactly, but it wasn’t until much later that I came across a better gauge of a proper reading level. When you’re reading a book, you can tell if it’s at your reading level if there’s about 2-3 new words on every page. That’s actually a bit of a challenge for most people and they tend to stay with books where they already know what all the words mean. These people are no longer advancing. They’re stuck. The same thing applies to programming in a slightly modified way. The way I see it, you should be encountering new ideas and ways to express yourself for every few pages of code that you write. And at least once a week, encounter something that makes you think that was the the last thing you would have thought of.
8 minutes | Sep 1, 2019
251: What Happens When Code Has Undefined Behavior?
What happens when code has undefined behavior? There’s hundreds of ways code can have undefined behavior. What happens is completely up to the compiler. You should not depend on undefined behavior because compilers can completely change or delete sections of code. Since the behavior is undefined, then compilers can optimize code in ways you never intended. I’ve known about undefined behavior for a long time. But this episode describes something that surprised me. I was not fully aware of the magnitude of the problem and the drastic steps that compilers can take. You really can’t depend on anything in your code once you enter undefined behavior. And because compilers are getting better all the time, something that used to go undetected can suddenly change on you as the compiler decides to rewrite your code. Since it’s already undefined, then who’s to say that the compiler is wrong? There’s a lot of really great videos online at cppcon.org about undefined behavior if you want to learn more. Just search for “cppcon undefined behavior” and you’ll find lots more information. If you’d like to improve your coding skills even more, then you can find all my favorite books and resources at the Resources page. Listen to the full episode for more details or read the full transcript below. Transcript Undefined means that we don’t know what will happen. I’ve been programming for a long time and have known about undefined behavior. But I just learned something new about undefined behavior that I want to share with you. This surprised me. Let’s first recap what is undefined behavior and what causes it. You can get into this situation in a lot of ways. I recently found out that the C language has about 200 documented cases leading to undefined behavior in your code. C++ has even more but they’re not documented all in one place. None of this includes your own code or that of some library you’re using. I’ve always known that you can’t rely on undefined behavior but what surprised me was that the compiler can decide to do whatever it wants when it detects undefined behavior. Since the behavior is already undefined, the compiler writers viewpoint is that the compiler can’t make things any worse. So what happens is the compiler can optimize your code. In other words, they actually use undefined behavior. And compilers don’t just use undefined behavior in the same way, they’re getting better at it. Code that used to work even though it relied on undefined behavior can sometimes stop when you upgrade your compiler. A new compiler can detect the undefined behavior and decide to reorder your code, skip function calls completely, exit out of your loops early, and who knows what else. The exact code generated by the compiler can change from one version to the next or even with different options. Compilers are able to detect undefined behavior based on possible misuse even if other factors would normally cause nothing bad to happen. For example, there’s a method called memcpy, usually pronounced as “memcopy”, that copies data from one place in memory to another. It takes two pointers and an integer. One pointer points to the source of the data. Another pointer points to the destination. And the integer lets you control how much data will be copied. Now, if you call this method with the size set to zero, then it doesn’t matter what the source and destination point to. You’re saying don’t copy anything from over there to over here. But just the fact that the compiler notices you using null pointers means you’ve already entered undefined behavior. To put this in terms of something from real life, let’s say that you visit an ice cream shop and tell the clerk that you’d like to purchase nothing. Does it really matter if you wanted to pay with fake monopoly money? No. Because you’re not really buying anything. But if this was a compiler, it might decide that because you’re using fake money, then your behavior is undefined and it’s free to do whatever it wants. Maybe you walk away from the shop with all your real money mysteriously gone from your wallet. Or the secret service is waiting for you outside the shop for using counterfeit money. They arrest you even though you explain that you never actually tried to buy anything. When writing code, it might seem like a good idea to make calls like this in a loop or during recursion. Maybe you know that the first time through the loop, everything will be okay and it simplifies your code so you don’t have to write special cases. The compiler might see this and decide to do whatever it wants. It might remove all this code as if you never wrote it at all. Maybe you do notice that your program isn’t behaving like you thought it would. What do you do? Well, you start debugging. One way to debug is to add code that will print messages to a log file. You think that you can trust that if your code reaches some log statement, then it will print the message to a file. But if the bug is caused by undefined behavior, then the compiler might just decide to skip everything. Including your log statement. You’re looking through your log file and getting even more confused because it doesn’t make sense. That’s the thing with undefined behavior. Once you get into this situation, anything is possible. You can’t even rely on warning messages from your compiler. What would that message look like? “Hi, this is your compiler speaking and I noticed that this code might sometimes not behave correctly. So I decided to make it better by changing it for you.” Here’s one specific case of undefined behavior. This is actually the case that I found out about and was surprised by. It turns out that C++ says it’s undefined to take the address of a class member method in the std namespace. Why would you ever want to do that? Well, maybe you learn about something called bind that lets you store away some arguments to pass to a method and then call the bind object later with the remaining arguments. The bind object will take the arguments it already has plus the arguments you provide when you call the bind object and call the method with all the parameters it expects. In order to use bind, you need to give it the address of the method to call. This means if you try to bind the method push_back in a vector, you’ve just entered undefined behavior. The compiler is then free to do whatever it wants including deleting all that code and pretending it was never written. How will your program react to gaping holes in the code? That’s for you to worry about. The compiler did its job. While researching this episode, I watched some really good videos from cppcon. Just search for cppcon undefined behavior. That’s c p p c o n. One talk describes code that tries to use an initialized variable as a source for random numbers. We know that we can’t rely on memory containing any specific value unless we own that memory and have already written something there. To read a value from memory when nothing was ever written will return whatever value happens to already exist. Well, the compiler can detect this case. And it might decide to remove all your code that deals with the uninitialized memory and replace it with something that’s constant. Why not? Since you can’t rely on any specific value, why not just give your code the same value without reading the memory? The compiler can generate smaller and faster code whenever your code tries to do something that it’s not supposed to.
8 minutes | Dec 9, 2018
250: GameDev: Design Patterns: Entity Component System.
This design pattern will help you make sense of your game design as it gets bigger. You can listen to episodes 77, 86, 87, and 88 for more information and background. This episode will start tying things together. I didn’t originally describe this because it really is a merging of many patterns. But as I started coding this myself, I’ve realized that there’s more to it than just sticking a few design patterns together. Enough that you can benefit from a description. Here’s the big picture. Your game will likely have many characters and objects in it. The characters can be directly controlled by one or more players or be controlled by the game as either direct opponents or just background characters. And the objects can be almost anything that your character interacts with. This could be a weapon, or an apple, or a door or table. All of these characters and objects share certain abilities and behaviors. That’s normally a good sign to use inheritance in your design. But if you go that way, you’ll find that inheritance leads to large and complicated hierarchies of classes that are difficult to change. Listen to the full episode to learn more about how the patterns work together to keep your game design understandable as it gets bigger. Or, you can read the transcript below. Transcript This is something I’ve been working on for the last three months in the game development sessions. You can listen to episodes 86, 87, and 88 for more information and background. This episode will start tying things together. And if you’d like to participate in these game development sessions, you can really learn a lot more than what I can describe here. Listen to episode 248 for a full description of a special offer now through the middle of January. And in that episode, you’ll also hear about a specific example of a template design that I was working on. The best way to participate in the game development sessions is to become a patron. You can get extra podcast episodes, videos, and free game development sessions. Okay, on to the topic for today. This brings together several design patterns. I didn’t originally describe this because it really is a merging of many patterns. But as I started coding this myself, I’ve realized that there’s more to it than just sticking a few design patterns together. Enough that you can benefit from a description. You can also listen to episode 77 about the observer pattern. That forms a big part of this as well. Here’s the big picture. Your game will likely have many characters and objects in it. The characters can be directly controlled by one or more players or be controlled by the game as either direct opponents or just background characters. And the objects can be almost anything that your character interacts with. This could be a weapon, or an apple, or a door or table. All of these characters and objects share certain abilities and behaviors. That’s normally a good sign to use inheritance in your design. But if you go that way, you’ll find that inheritance leads to large and complicated hierarchies of classes that are difficult to change. And I mean they’re difficult to change both at design time and at run time. You might want to change something about how an object looks or behaves and doing so affects other things in the game because they all inherit from the same base classes. This causes problems and increases the work and time needed to write your code. And it also causes problems when you want something in your game to change how it works during the game. Maybe you want the character to be able to move through walls like a ghost for a short while and then go back to being solid. You’ll have a really hard time designing such a game if you’ve relied too much on inheritance. Episode 86 describes the Component design pattern which can be used to attach behavior to characters and game objects by having them contain this behavior instead of inheriting this behavior. Want a different behavior? Just swap out one component for another. It’s like being able to rearrange your inheritance hierarchy whenever you want. Because you’ll have code separated into components, you’ll need some way for them to communicate. Episode 87 describes the event queue and episode 77 describes the observer pattern. Each of these has a place. Sometimes, you’ll want to place events in a queue and process them later and sometimes you’ll want a more targeted approach that lets interested code know about something happening right away. A other way to think about this is that a queue lets you stack up work to be done by almost any other code. This is work that needs to be done maybe to finalize something that’s already happened in the game. While an observer lets only that code which has previously shown an interest to get involved right away. Maybe the observer will let that other code change things before they become settled. Or even cancel something sort of like a veto power. I’ve been talking about characters and game objects as if they were different things in a game. And they are. But I also said that they can have many of the same needs and share behavior. If you throw a chair against a wall, it should bounce off and possibly break just like how a character will fall back after hitting a wall and maybe take damage too. The entity component system tries to treat as much as possible as just a game entity. Whether this is the hero of the game or a rock laying alongside a road that can be picked up and thrown, they’re all entities. Or game objects if you prefer. What makes one game object different from another is the components attached to each and the values of properties that these components have. You’ll need another aspect of all this and that’s systems. Think of a system as something to manage various game objects and their components. You might have a system that just deals with movement. In order for this system to actually move a game object, then the game object will need to have a moveable component with properties to remember the current position. With all these components and systems, you’ll need to sometimes find one or another one. That’s where episode 88 helps by describing a pattern you can use. It’s a flexible way to describe what you want instead of looking for a component or system directly. You might find a component or system that you weren’t expecting but it should do what you need and that’s what’s important. Hopefully, you can see the need for an entity component system for large games. Actually implementing one is a very different story. I’m almost done with the implementation for the game I’m working on and will go into more details in the next episode. I’ll end with one final thought. And it has to do with what I’ve found to be a good way to develop software. You see, I started out without an entity component system and got the game to a point where you can move the character around on the screen. Then I switched focus to building an entity component system and for the last several months have been working on just that. The only way I know it’s working has been through unit tests. But before going too far, I switched back to the game and modified it to start using the entity component system. There were some changes that I realized were needed to make the new entity component system easier to use. This is an agile approach. Get something working that actually has value. But don’t take it too far just yet. Eventually, something else will become important and working on that might change your thinking about earlier designs. That’s okay and leads to a better overall design that stays focused on the current and evolving needs of your customer. In this case, I’m not just trying to build a fun game, but I’m doing it a way that will help you to learn how to program better.
6 minutes | Nov 25, 2018
249: GameDev: Floating Point: Zero, Infinity, NaN.
There’s some special floating point values that you should be aware of. Zero, infinity, and not a number are three cases that might surprise you. Let’s get started. First of all, do you know the sign of zero? Is it positive or negative? Depending on your country and traditions, zero might either have no sign or be both positive and negative. I think it’s standard for most places that zero has no sign at all. It can be important when a value approaches zero to consider what direction it’s approaching from. In other words, is a value shrinking from a positive value towards zero? Or is it increasing from a negative value towards zero? Once a value reaches zero, then it loses it’s sign. Or it gains both signs if you prefer. The main point is that zero behaves slightly differently than all other values. This difference is most important when dividing. Listen to the full episode for more information about how dividing by a floating point 0.0 is very different than dividing by an integer 0 value. Floating point division can lead to infinity while integer division can lead to almost anything. And from there, it’s not too hard to get into “not a number” values. Or you can read the full transcript below. Transcript Because you’ll be likely to use a lot of floating point numbers when building a game, this episode will explain some special values. Zero, infinity, and not a number are three cases you should be aware of. You probably already know about zero and infinity, but even these might surprise you. And not a numbers which are usually referred to as NaNs are even more peculiar. Let’s get started. First of all, do you know the sign of zero? Is it positive or negative? Depending on your country and traditions, zero might either have no sign or be both positive and negative. I think it’s standard for most places that zero has no sign at all. It can be important when a value approaches zero to consider what direction it’s approaching from. In other words, is a value shrinking from a positive value towards zero? Or is it increasing from a negative value towards zero? Once a value reaches zero, then it loses it’s sign. Or it gains both signs if you prefer. The main point is that zero behaves slightly differently than all other values. This is most important when dividing. If you ever try to divide by zero, you get, well, you don’t really get anything. This is just not allowed. I remember a proof once when I was in high school that showed through a series of steps that 1 was equal to 2. It was obviously wrong. But why? Every algebra step along the way looked correct. But hidden in one of the steps was a divide by zero. This broke the entire proof and led to a bad result. In programming, dividing by zero using integer arithmetic is undefined. I wrote a small program for this episode to see what the result would be. I just printed the output of dividing 1 by 0. The first thing I noticed was a compiler warning that said this operation was undefined. The compiler was able to tell this because I was using the literal values 1 and 0 directly. It’s more likely in your programs that the values you’ll be dividing won’t be known until runtime. They’ll be variables. The compiler can’t warn you for things like this. Anyway, it was a warning and the program compiled. So I ran it. And it said that 1 divided by 0 was 73,896. Once you get into undefined behavior in your program, the results could be anything. Your program could crash or give you wild results that don’t make any sense. Dividing by zero is something you always need to be careful to avoid. But that’s for integer numbers. Those are whole numbers. What about dividing by zero with floating point numbers? This turns out to have a definite answer. And it depends on whether the zero is positive or negative. That’s right, in floating point format, the number zero can be either positive or negative. It’s all controlled by the single sign bit in the floating point standard. This sign bit exists and is used for the number 0.0 just like all the other numbers. So what is 1.0 divided by 0.0? The answer leads us to the next special floating point number type. Infinity. And in this case, positive infinity. If you divide 1.0 by -0.0, then you end up with negative infinity. This is not just a really big number that can be either positive or negative. According to the floating point standard, there are specific bit patterns reserved for the special values. This is also why you can’t just compare floating point bits to figure out what they mean. You can’t just write code that checks if all the bits in a floating point value are zero and assume then that the value must be zero. Because negative zero and positive zero both represent the value zero and differ by a single bit. If you take any positive floating point value and divide by positive infinity, then you end up with positive zero. Dividing by negative infinity will give you negative zero. What happens if you divide 0.0 by 0.0 though? Now we end up with a problem again. This doesn’t make sense and floating point has the answer. You get something that’s no longer a number. It’s actually called not a number. And this is written NaN with capital N, lowercase a, and another capital N. You get the same not a number if you try subtracting infinity from infinity. Although, I always wondered why this doesn’t just result in zero? There’s a few other things you can do to end up with not a number. But the important thing to note is that once you do get not a number, then anything you do with that in your calculation will also result in not a number. And if you ever try comparing anything with a not a number, you’ll get false. They’re not equal to anything and not a numbers spread through your results like a cold in winter.
10 minutes | Nov 18, 2018
248: GameDev: Special Offer: Free Advanced Game Building Bonus.
Looking for more advanced training to help you better understand how to actually build something in C++? Want to go beyond example snippets that don’t really teach you anything? How about being able to ask questions or get feedback on a suggestion? You can get all these things by attending a live game development session. This is where you get to watch and participate as I work on building a game. This is real code and unscripted. And now through the middle of January 2019, you can get a free game development session bonus when you sign up to be a patron of Take Up Code. This bonus is normally only for those patrons who choose the $10 per month game development session tier. You can get a free game development session bonus when you sign up to be a patron at any tier, now through the middle of January 2019. Just $1 a month is enough to become a patron. And for that $1, you also get access to a special podcast just for patrons. There’s already a whole series that you can listen to that will explain databases, how to use them, what they are, the differences between SQL and NoSQL databases, and even my number one suggestion for avoiding security attacks in your data. What can you learn in a game development session? Well, for one, the project I’m working on is starting to get big. Not as big as what you might find working in a large software company like Microsoft. But definitely big for what one person can create over several years. You can see and learn for yourself how to manage a large project. But more than that, you get to understand all the work that goes into the project even between commits. I try to commit regularly but even that leaves out all the small things that I try and then change my mind about. This is super important for you to understand because it’s how software actually gets written. When you read a book or watch a tutorial online, you’re getting an edited account that makes it look like the developer knew exactly how to proceed and just started writing the final code. Sure, sometimes it does work out like that. But not often. And this can leave you feeling lost and confused and maybe even thinking that you’re no good at writing code because your own attempts don’t turn out anything like what you read or watch. For a specific example, I was recently working on a hashing class. You can create a hash of different lengths. I mean a different number of bits. But the hash algorithm I was implementing only works with a couple fixed sizes. You can listen to the full episode or read the transcript below as I describe in about two minutes what actually took me several hours to create. All you have to do is visit takeupcode.com and click the Patron link at the top to get started. This will take you to a site called Patreon that I use to manage and coordinate patron registration and bonuses. While you’re there, check out some of the other creators that I support. It’s a great way to help creators such as myself and get valuable rewards at the same time for yourself. Transcript You can get all these things by attending a live game development session. This is where you get to watch and participate as I work on building a game. This is real code and unscripted. And now through the middle of January 2019, you can get a free game development session bonus when you sign up to be a patron of Take Up Code. This bonus is normally only for those patrons who choose the $10 per month game development session tier. You can get a free game development session bonus when you sign up to be a patron at any tier, now through the middle of January 2019. Just $1 a month is enough to become a patron. And for that $1, you also get access to a special podcast just for patrons. There’s already a whole series that you can listen to that will explain databases, how to use them, what they are, the differences between SQL and NoSQL databases, and even my number one suggestion for avoiding security attacks in your data. If you want to attend regular game development sessions, then $10 per month will already give you a free game development session each month. So if you choose this option, don’t worry, I’ve got an even bigger offer for you. Now through the middle of January 2019, when you sign up to be a patron at the $10 per month game development tier, you’ll get four extra game development sessions to use whenever you want throughout 2019. That’s a $100 dollar value of extra bonuses on top of your already free game development session each month. What can you learn in a game development session? Well, for one, the project I’m working on is starting to get big. Not as big as what you might find working in a large software company like Microsoft. But definitely big for what one person can create over several years. You can see and learn for yourself how to manage a large project. But more than that, you get to understand all the work that goes into the project even between commits. I try to commit regularly but even that leaves out all the small things that I try and then change my mind about. This is super important for you to understand because it’s how software actually gets written. When you read a book or watch a tutorial online, you’re getting an edited account that makes it look like the developer knew exactly how to proceed and just started writing the final code. Sure, sometimes it does work out like that. But not often. And this can leave you feeling lost and confused and maybe even thinking that you’re no good at writing code because your own attempts don’t turn out anything like what you read or watch. You also don’t get to ask questions in real time. It’s all after the fact if even then. You definitely get no chance for your question or suggestion to change the development. Maybe while participating, you think you would have done something in a different way. Just mention it, and you’ll get a conversation going that will help you understand the differences between the solutions. You might even have a better solution. You’ll learn either way. It does take time to learn how to code. One way to speed up this process is to incorporate different learning methods. If you only watch YouTube videos, that’s not enough. If you only read books, that’s not enough. If you only attend lectures and presentations, that’s not enough. You need to do as many different activities as you can. There’s nothing quite like attending a live session to bring you back to reality and see firsthand how software really gets written. The code that I’m working on uses some advanced C++ techniques. And it’s all modern C++ too. My main development tool doesn’t yet support all the modern C++ features that I’d like to include. So this is well past C++11. And of course, this is a video presentation. It’s not an audio podcast anymore. You get to see the code from anywhere in the world. All you need to join is a computer with a decent internet connection. I recommend headphones with a mic just like you might use for playing an online game. We’ll talk about more than just C++ features. You’ll be exposed to design patterns, creating your own template and specializations, custom data structures, algorithms, and well, pretty much everything, really. All you have to do is visit takeupcode.com and click the Patron link at the top to get started. This will take you to a site called Patreon that I use to manage and coordinate patron registration and bonuses. While you’re there, check out some of the other creators that I support. It’s a great way to help creators such as myself and get valuable rewards at the same time for yourself. For a specific example, I was recently working on a hashing class. You can create a hash of different lengths. I mean a different number of bits. But the hash algorithm I was implementing only works with a couple fixed sizes. So I first created a template class called HashSize with an int value template parameter. This is one of C++’s greatest strengths, the ability to create templates based on not just types but values too. If you look at a language like C#, it has the ability to create generic classes that can change based on types. But the C# language creators never included the ability to create generic classes based on values. The HashSize template that I created needs an integer value in order to construct it. You can create a HashSize instance with a value of 5, or 105, or anything you want and these become different and distinct types. They’re not just the same class type with a different member value. The value becomes part of the type itself and doesn’t need a data member variable to hold the value. This is a good start but isn’t exactly what I wanted. I wanted to limit the values that could be used in the hash algorithm to just 32 or 64. You might think an enumeration would be good for this. And that could work. But an enumeration can hold other values. Plus I eventually wanted a method like getHash that would either return a 32 bit value or a 64 bit value and have different implementations for each. That means I needed something that could change the return type of a method. In other words, I wanted to start out with a value such as 32 or 64 and then use that value to control the return type as well as the entire algorithm of the getHash method. For this, a value itself like an enumeration just wouldn’t work. What I eventually did was to create two full template specializations of the HashSize class. And in each template specialization, I declared a using statement called HashValue to be either a 32 bit integer or a 64 bit integer. Then in another class called the HashGenerator, I made it also a template based on an int value. And inside this class, I declared another using stateme
9 minutes | Nov 11, 2018
247: GameDev: 1.1 Plus 2.2 Is Not 3.3. What?
Be careful with floating point numbers when building games. You could be in for some big surprises if you don’t understand how computers work with fractional values. You might be able to write an app to keep track of your friend’s addresses without using any floating point numbers. But most games will need math that uses fractional values. That is if you want any kind of game with smooth motion. If your game consist of typing letters in words, then maybe you won’t have to worry about this. But if you want those letters to move slowly across the screen as the user drags them into place, then you’ll need to use fractional values. You might think that you can get away from this by just having really small whole numbers. Maybe you track individual pixels. The problem is that computers are really fast these days and can do a lot of work even between pixels. You might find that the computer tries to move the image by 1 thousandth of a pixel. If you only work with whole numbers, then this becomes zero. And your image will be stuck without moving at all because the computer is so fast that it’s always trying to move it by a tiny amount. Instead of limiting yourself to whole numbers, you’ll need to understand how to use fractional values. And that means you need to understand how to use floating point numbers. You should also listen to episode #112 about the float data type, or you can read the full transcript below. I try not to repeat information between episodes so you’ll find both this episode and the earlier one have something for you. Transcript You could be in for some big surprises if you don’t understand how computers work with fractional values. You might be able to write an app to keep track of your friend’s addresses without using any floating point numbers. But most games will need math that uses fractional values. That is if you want any kind of game with smooth motion. If your game consist of typing letters in words, then maybe you won’t have to worry about this. But if you want those letters to move slowly across the screen as the user drags them into place, then you’ll need to use fractional values. You might think that you can get away from this by just having really small whole numbers. Maybe you track individual pixels. The problem is that computers are really fast these days and can do a lot of work even between pixels. You might find that the computer tries to move the image by 1 thousandth of a pixel. If you only work with whole numbers, then this becomes zero. And your image will be stuck without moving at all because the computer is so fast that it’s always trying to move it by a tiny amount. Instead of limiting yourself to whole numbers, you’ll need to understand how to use fractional values. And that means you need to understand how to use floating point numbers. They’re called floating point because the decimal point that separates the whole number portion from the fractional number portion can move around as needed. Actually, I completely made up that last part. It seems reasonable to me and this is how I’ve always thought of floating point numbers. But I really have no idea where the name comes from. So I don’t repeat earlier content, you’ll want to listen to episode #112 where I described the float data type. In this episode, I just wanted to bring the topic to your attention again. Especially, since I’m describing game development topics and some of the math you’ll need to use. Early computers were really good with adding, subtracting, multiplying, and dividing whole numbers. They still are. You can represent all the values 0 up through the maximum value without missing any numbers. I mean, it would be really bad if computers, say, had trouble with 8. To a computer, all the numbers are just a series of binary 1’s and 0’s. They can even represent negative numbers through something called two’s compliment. This is where you flip all the bits and then add 1. So if you start out with the value 1 and want to make it negative, then you first flip all the bits. This gives you all 1’s except for the least significant bit which started out as one and is now 0. Then when you add one, even that last zero becomes a one. You end up with the value -1 being all 1’s. You need a different system to represent fractional values. And early computers didn’t agree on how this should be done. The computer engineers of that time, and I’m talking about sometime around the 1970’s, decided that a standard was needed. So the IEEE 754 standard was created to describe how floating point values would be represented in computers. These early computers had a standard now, but working with floating point numbers was slow. Any operation required the main processor to break up the floating point number into pieces and calculate them separately and then put everything back into the standard format for the answer. It wasn’t anything like flipping some bits. Although, one nice thing about floating point values is there’s a single bit that holds the sign of the number. So something as simple as changing the number 1.0 into -1.0 and back again can now be done by turning a single bit on and off. Let me also sidestep here for a moment. The number 1 is a whole number. It’s an int. The number 1.0 is a floating point number. Just because the values after the decimal point are all zeros doesn’t turn it into a whole number. Sure, you can always convert between whole numbers and their floating point equivalents. But going back to whole numbers might cause you to lose some bits. Going from 1.0 to 1 won’t lose anything. But those are specific examples. In general, a language like C++ won’t let you convert from a floating point value into an int value unless you tell it that it’s okay to do so. Back to the early computers. We have a standard but it’s still slower to work with floating point numbers than it is to work with integer numbers. Unless your computer had extra hardware that also understood the IEEE 754 standard. By the time I was buying my first computer in the 1980’s, there was an empty socket in the computer motherboard where an additional chip could be place to help speed things up a bit. This was called a numeric co-processor. For Intel processors, if your computer had an 8086 processor, then you could buy an 8087 math co-processor and plug it into the empty socket. If you had a 80186 processor, then there was a 80187 math co-processor. Intel keep this pattern going for some time. I’m not sure exactly how long. Eventually, they stopped selling separate math co-processors and started putting everything on a single chip. Now, we don’t even think about the extra work needed to understand and operate on floating point values. We just know that computers are really fast with working with any type of number. The math co-processors that are built into modern computer CPUs are able to work with floating point values much faster than ever. But they still have to treat some values as approximate. In other words, a value like 1.1 which we can represent exactly in decimal is slightly off from the exact value of 1.1. It’s close but not exact. This is just like how we can’t express 1/3 as a decimal value of 0.3333 exactly either. The three’s need to keep going forever. Computers don’t have forever. And the IEEE standard defines a fixed number of bits available. Once the bits run out, the value stops being as precise as we might expect. Now, we’re already familiar with values like 1/3 being imprecise. We work with base 10 or decimal. It turns out that having ten fingers for our counting is actually very fortunate. Because what are the factors of 10? By that, I mean, what whole numbers can be multiplied together to get 10? Well, 1 times 10 equals 10. And so does 2 times 5. Three doesn’t go into ten evenly. And that’s why one third can’t be represented easily in base 10. Even though four is not a factor, it’s a multiple of 2. So one fourth is no problem. One fifth is no problem because five is a factor of ten. One sixth, one seventh, and one ninth will all give problems. Because 1, 2, 5, and 10 are all factors of 10, then any fractions based on these values can be represented exactly in base 10. So a value like 1.1 is really 1 and 1 tenth. That 1 tenth part is what I mean about going into ten evenly. What about 1.2? Well, this is 1 and 2 tenths, or you can also say it’s 1 and 1 fifth. Again, it goes into ten evenly. But binary is base two. What are the factors of 2? Just 1 and 2. We no longer have evenly representable values of tenths available as exact numbers in binary. All we can really do in binary with exact precision is divide by 2. For the most part, this is okay. The IEEE standard gives us enough bits that 1.1 can be represented by a number that’s really, really close. Just be aware that it’s not exact.
9 minutes | Oct 28, 2018
246: GameDev: Points Vs. Vectors. Which Should You Use?
Do you know the differences between points and vectors? You might be surprised. I learned a few things myself recently when I implemented points and vectors in the TUCUT library. Listen to episode 240 to learn more about TUCUT. As to which you should use, that’s sort of a trick question. You’ll most likely use whatever your game engine provides. Unless you’re writing your own library like I’m doing, the idea of a point and a vector are very basic concepts that would be provided for you. Any type of drawing needs to know where to do the drawing. Animations need to know which directions to move. Game items need to know where they exist in the world. Listen to the full episode to learn what you can do with points and vectors, how they can interact, and why many game engines provide only vectors. You can also read the full transcript below. Transcript You might be surprised. I learned a few things myself recently when I implemented points and vectors in the TUCUT library. Listen to episode 240 to learn more about TUCUT. As to which you should use, that’s sort of a trick question. You’ll most likely use whatever your game engine provides. Unless you’re writing your own library like I’m doing, the idea of a point and a vector are very basic concepts that would be provided for you. Any type of drawing needs to know where to do the drawing. Animations need to know which directions to move. Game items need to know where they exist in the world. And because game engines provide these features, they need a way for you to specify points and vectors. Traditionally, points have been mostly a geometry topic and vectors an algebra topic. I see them as very close concepts and the differences between them can sometimes be a matter of preference. One of the strange things I found in my research was the idea that points have no coordinates. They exist at some location and the reason they have no coordinates is because there could be multiple coordinates that end up in the same location. For example, if you have a sphere like earth and a point is some city. Then you can pick an origin and go to the city. But you can also keep going and come all the way around the sphere until you reach the same city again. Depending on how your points exist in the universe, they might have many different coordinates. Or maybe you have multiple origins or an origin that moves around. This would cause the coordinates to change. Think of it like this, if you live near the border of a city and the city border changes, then you might get a new mailing address. It’s not like your house suddenly changed its location. But the origin changed and now your address is relative to a different city or county. Or maybe you have different ways of measuring distance. It could be millimeters or inches. The same point will have different coordinates if you use different measurement systems. To me, these are not good reasons for saying that points have no coordinates. I’m okay with the idea that coordinates need to be matched with a specific origin and measurement system. If the origin changes, then the coordinates will change. And if there’s different ways to get to the same point, then to me that’s okay too. A vector is more flexible in this sense. Because vectors have no origin. Let’s take an example in a single dimension. Imagine a point at coordinate 8 and another point at 10. A vector will tell you how to get from 8 to 10. Just move two unit positions to the right. That’s all a vector is. Just a magnitude and a direction. In this example, the magnitude is 2 and the direction is towards the right. What if you want to go from point 5 to point 7? You get the same vector, two units to the right. Now, the points themselves are based on the origin. So you get to a point at position 5 by starting at the origin and moving five units to the right. This is where the differences between points and vectors start to become blurred. Because a points coordinates define the location of a point from the origin and because a vector also defines how to get from one location to another, then it’s easy to see how everything can be thought of as a vector. A lot of game engines may only have a vector class. And vectors are used to represent both points and vectors. Let’s say we have two dimensions. If we move in the positive x direction by 2 units and then in the positive y direction by 2 units, then we arrive at the point at 2, 2. Now, I mentioned moving first in x and then in y. That was just to help explain the position. The point at 2, 2 really has nothing to do with moving. It just exists at that location. A vector is about moving. And a 2, 2 vector starting at the origin would also arrive at the same 2, 2 point. You can think of any point as the result of starting at the origin and moving along a vector with the same axis components as the point coordinates. You can also think of the origin as a point with all zero coordinates. And adding a vector to the origin point is what takes you to another point. A vector can be added to any point which will cause you to arrive at another point. Unless, of course, the vector zero is used. Then you don’t really go anywhere and stay on the starting point. Now, you could, I suppose, add a one dimensional vector to a 2 dimensional point. Or even add a 2 dimensional vector to a 3 dimensional point. But that’s stretching things a bit too far, I think. Let’s stick with the vectors and the points all having the same number of dimensions. At least I’m not aware of any practical uses for adding vectors and points with different number of dimensions. If anybody knows of a use for this, then please let me know. I should also say that when adding vectors, it doesn’t always mean that the result will be positive numbers or even bigger than what we started with. You could have a -1, 0 vector that if you add it to the 2, 2 point, then you’ll end up at the point 1, 2. Notice that you can have a vector with components set to zero. That’s another reason that I don’t think there’s any value in considering vectors and points interacting with different number of dimensions. If you really only want to move along a single axis, then just set everything else to zero. Before ending, let’s think about some other operations we might want to perform on points and vectors. I mentioned already that you can add a vector to a point. You then get another point. You can also subtract a vector from a point. That’s just like changing the sign of the vector components before adding it. When you start out with a point, you can add or subtract a vector and you end up with another point. I mentioned earlier that you can think of a vector as telling you how to move from a point at position 8 to a point at position 10. This is what you get when you subtract points. So taking the point at 10 and subtracting the point at 8 gives you a vector of 2. What about adding points? We can add vectors. But adding points doesn’t make any sense. What about multiplying points or dividing points? Again, these don’t really make any sense. But you can multiply and divide vectors by a fixed number. This just means that you multiply or divide each component of the vector by the same number. This has the effect of making the vector longer or shorter without changing its direction. Unless you multiply by a negative number. That’ll reverse a vector. But multiplying or dividing won’t cause a vector to change its direction slightly. It can grow and shrink, continue to point in the same direction or turn it completely around to point in the opposite direction. It’s because of these differences between what you can do with vectors vs. points that I decided to keep the concepts separate in the TUCUT library. Anytime the library needs a fixed position, it uses a point. And anytime it needs a direction, it uses a vector. I might later change my mind and use only vectors for everything. But until I find a reason otherwise, I’d like to keep these two ideas separate. I didn’t go into what it means to multiply vectors in this episode. That’s a whole different topic.
12 minutes | Oct 14, 2018
245: GameDev: Points, Lines, Planes, Dimensions, and Normals.
You don’t need a lot of math to program. What you do need is usually simple. But you do need some. Don’t worry, it’s not that hard and I’ll explain it so you can understand. Game development probably needs a bit more math than you might guess. Let’s start with a point. It’s a simple concept that really just represents a position. A point has no dimensions itself. In other words, it has no length, width, or height. It just exist at some location. It’s the location that has dimensions. If we’re talking about a point in a one dimensional world, then there’s only two directions, left or right. Or, depending on how you want to view the line, it could be up or down. Or, if you can imagine that you are inside the line itself looking down it’s length, then you really have forwards and backwards as the two directions you can go. Once you know the directions, you have to decide how far you want to travel. We normally think of a line divided into equal measures like a ruler. If you start out at position zero and move forward one unit, then you can say that you’re now at position one. Moving backward from there by two units will take you back to position negative one. Everything is relative. We think of a ruler as having a specific beginning at one end that we call zero. But if you were inside that line that extends forward and backward in infinite amounts, then where is zero? Well, it’s wherever you want, really. The main thing is to be consistent. Once you pick a spot that you consider to be zero, then stick with that. Everything else will be based on that point. Listen to the full episode to learn about 2D planes and 3D and even 4D spaces. You’ll also learn why the indices are drawn 90 degrees apart from each other and what this really means. Or you can read the full transcript below. Transcript But you do need some. Don’t worry, it’s not that hard and I’ll explain it so you can understand. Game development probably needs a bit more math than you might guess. There’s a lot of things that get thrown in a game, sure, that you need to calculate where or what it’ll hit. But there’s math involved in just drawing the game objects so they look good. Things such as cloth billowing in the wind or reflections in the gentle waves of a pool of water are details that are harder to get right. They’re also things we notice if they look wrong or fake. It’s always a struggle with programming to decide how detailed you need to be. More detail either means more data or more computations. Less detail means flat surfaces that should be curved, or trees that all tend to move in the same direction at the same time, or just skipping things completely like deciding to not bother with shadows. There’s lots of tricks and shortcuts that have been developed over the years. And then there’s that fact that computers have gotten faster so games can consider it possible to include details that would have been impossible years ago. It’s harder to do these calculation in a game than it is in a motion picture. A game has a game loop that’s very sensitive to timing. A movie can take all the time you need to draw each image. It might take years to record and edit a major motion picture. But it takes you exactly 1 minute to play a game for 1 minute. And in that 1 minute of game time are 60 seconds that need 60 frames in order to look good. That’s 3600 frames that need to be drawn in 1 minute. Then there are games that simplify things on purpose. I mean, if the whole world is made out of squares, then it really simplifies a lot of calculations. I’ve always said that if you can’t get something perfect, then people will notice. Unless you make it so obviously imperfect that you can say you did it that way on purpose. Okay, I’m getting a bit off topic here. I wanted to explain some math terms today that will help you understand how to program games. Even if you use a library where all these things are already taken care of for you, a basic understanding will still help you build better and more believable software. Let’s start with a point. It’s a simple concept that really just represents a position. A point has no dimensions itself. In other words, it has no length, width, or height. It just exist at some location. It’s the location that has dimensions. If we’re talking about a point in a one dimensional world, then there’s only two directions, left or right. Or, depending on how you want to view the line, it could be up or down. Or, if you can imagine that you are inside the line itself looking down it’s length, then you really have forwards and backwards as the two directions you can go. Once you know the directions, you have to decide how far you want to travel. We normally think of a line divided into equal measures like a ruler. If you start out at position zero and move forward one unit, then you can say that you’re now at position one. Moving backward from there by two units will take you back to position negative one. Everything is relative. We think of a ruler as having a specific beginning at one end that we call zero. But if you were inside that line that extends forward and backward in infinite amounts, then where is zero? Well, it’s wherever you want, really. The main thing is to be consistent. Once you pick a spot that you consider to be zero, then stick with that. Everything else will be based on that point. That’s fine if you’re all by yourself. The moment you have two people living in the line, either they both have to agree on where is point zero or they have to always map between one person’s viewpoint and the other. It gets more complicated if the units of measurement are also different. I mean who got to say that an inch was to be as long as it is. Or that a meter is as long as it is. How you represent your dimensions is very important. No matter how many dimension you have. The metric system is much better organized around 10s just like the way we count. And it sticks to that factor of ten. Not at all like how there are 12 inches in a foot and 3 feet in a yard. And do you remember how many yards are in a mile. I don’t. And I grew up using miles my whole life. It’s just not the sort of information that I want sitting around cluttering up my mind. But I know there’s a thousand meters in a kilometer. Another thing to consider that will be important soon is to think about what would happen if the line that you’re imagining is your home was really a thread. And that thread was tangled up and twisted all around. We can picture this. But try for a moment to imagine that your whole world exists inside the line. The only directions you know are forward and backward. If your world is actually curved because the thread spins in a loop for a while, you don’t see this. Inside the line, it’s still straight ahead or straight back. Just keep this thought in mind. To make things simple, we’ll stick to lines really being straight and unbendable. Alright, let’s move on to two dimensions. This is a plane. A flat surface. At least it’s flat to anybody living in the plane. We normally think of the ground as being flat but that’s just because the earth is so much bigger than our viewpoint typically allows us to see. So it’s possible to stretch and twist a plane so it’s no longer perfectly flat. Just like the line, we’ll stick to planes being perfectly flat. Now we have two dimensions to work with. Typically called x and y. How are these dimensions related to each other? We normally look at the axis lines. These are lines like the one dimension ruler that mark off the distances. The lines are drawn so the y axis passes through the x six zero point. And the x axis passes through the y axis zero point. Both zero points meet at the origin of the dimensions. The axis lines are also drawn so they’re perpendicular to each other. This means the lines make a 90 degree angle. But don’t focus so much on the angle. The most important point is that if you move along one axis only, then you shouldn’t be moving along the other axis. The best way to show this is to draw the axis lines at 90 degrees. We’re used to this kind of arrangement. From graph paper to maps, we use this arrangement all the time. You can get to any point from the origin with a straight line. But we usually represent the location of this point by giving both the x component and the y component. It doesn’t mean that you have to travel along the x axis and then along the y axis to get to the point. The coordinates are there just to identify the location of the point. While we’re talking about planes, let me explain what a normal is and what it’s used for. The normal will extend into the third dimension but that’s okay. I’ll explain it now. If the plane is flat like the ground, then a normal is like a flagpole sticking straight up into the sky. It doesn’t matter how tall the flagpole is. You’ll usually find normals will be one unit long. That makes a short flagpole, I know. What a normal does is point straight out from the plane so that your program will know which direction the plane is facing. This direction is used to figure out how to color a flat surface. Light can behave differently to our eyes when it reflects off a surface as that surface changes its direction. And a normal is a good way to keep track of the direction. That’s why the length of the normal is not important. It’s easier to keep track of and specify the direction of a line to figure out which way a surface is facing than track the surface itself. And normals are even more important when we get to curved surfaces. What about 3 dimensions? Again, we
8 minutes | Oct 1, 2018
244: CppCon: What Did I Learn? And What Will Help You?
I just got back from CppCon 2018 in Bellevue Washington. And since this is a podcast where I teach you how to program, I thought I’d share something that I learned at the conference. It was a great conference with full days that went from 8 in the morning to usually 10:30 at night for five straight days. And then there were classes before and after the conference. There were so many choices for presentations to attend that it was tough to choose. It was packed with people. I think there were over 1,200 people attending. But at the same time, it was as smooth as you can imagine. The organizers deserve amazing credits. Even with all the people, I never had trouble finding a good spot. Sometimes I would sit up front. And sometimes I would sit at a table in the back of the room. One of my favorite talks was from Nicolai Josuttis. This is something that I’ve been aware of since I first started programming C++. There’s a lot of different ways to declare a variable and initialize that variable so it has a value. This explanation really needs text for you to be able to see the actual code. So I won’t be able to describe everything from the presentation. I’ll stick to the big ideas. In a couple weeks, more or less, you should be able to watch the full presentation on YouTube. It’s called “The Nightmare of Initialization in C++”. Probably the main thing to understand is that in C++ if you have a method that declares an int variable and gives that variable a name, then the value of that variable is undefined until you write a value first. If you just declare a variable and read from it without first providing a value, then you’re in undefined behavior. The value could be anything. The rules are changing all the time. Some of the things I learned from this talk were about how things change in C++17 vs. earlier versions of the language. You’ll also gain insight into some changes that might take effect in C++20. Listen to the full episode or read the full transcript below to learn more and make sure to watch the video once it’s published. Transcript And since this is a podcast where I teach you how to program, I thought I’d share something that I learned at the conference. It was a great conference with full days that went from 8 in the morning to usually 10:30 at night for five straight days. And then there were classes before and after the conference. There were so many choices for presentations to attend that it was tough to choose. Everything will be posted on YouTube later for you to watch. Which is good because unlike Hermione in Harry Potter, I didn’t have a time turner so that I could attend multiple talks at the same time. It took me over an hour just to plan out which talks I wanted to attend. I don’t know how many talks there were in total but the conference sometimes had about eight different talks going at the same time in different rooms. It was packed with people. I think there were over 1,200 people attending. But at the same time, it was as smooth as you can imagine. The organizers deserve amazing credits. Even with all the people, I never had trouble finding a good spot. Sometimes I would sit up front. And sometimes I would sit at a table in the back of the room. The largest meeting room was big enough to hold everybody at once with extra seats to spare. And I didn’t need binoculars to see the presentation. There were multiple projection screens available to watch from any seat in any of the rooms. All in all, it was an amazing conference and I’m still processing the things I learned. Which brings me to the topic of this episode. This podcast is all about teaching you how to code. It’s not just news and it doesn’t focus on interviews. There actually hasn’t been a single interview yet on this podcast. Not that I’m against interviews. But my list of things that I want to explain to you doesn’t seem to be getting shorter. So what’s one thing that I learned in this conference? Let’s see. I might have to split this into multiple episodes. For today, I’d like to explain some things about variable initialization. One of my favorite talks was from Nicolai Josuttis. This is something that I’ve been aware of since I first started programming C++. There’s a lot of different ways to declare a variable and initialize that variable so it has a value. This explanation really needs text for you to be able to see the actual code. So I won’t be able to describe everything from the presentation. I’ll stick to the big ideas. In a couple weeks, more or less, you should be able to watch the full presentation on YouTube. It’s called “The Nightmare of Initialization in C++” Probably the main thing to understand is that in C++ if you have a method that declares an int variable and gives that variable a name, then the value of that variable is undefined until you write a value first. If you just declare a variable and read from it without first providing a value, then you’re in undefined behavior. The value could be anything. And because it could be anything, the compiler doesn’t even have to give you a real value. It might decide to make up a value for you. After all, if you have no idea what to expect, then who’s to say that a value the compiler gives you isn’t the correct value? You shouldn’t rely on this behavior for some strange reason. Trying to read uninitialized variables is always a bug. If you really want a random value, then there’s better ways to do this. It’s easy to provide an initial value though. that is if you ignore all the different ways to do this. You might just write int i = 2. And you now have a fully defined integer variable with an initial value of 2. Now why would C++ even let you define uninitialized variables if reading them is undefined? Because C++ lets you write code as you need to. There’s nothing wrong with declaring a variable with no initial value. As long as you make sure to write a value to the variable before you try reading from it. Maybe you want to declare several variables together in one spot and you don’t yet have an initial value. C++ doesn’t make you provide a fake initial value. It doesn’t make you store a zero in the variable. I would recommend that you declare variables at the moment they’re needed. It’s a habit from the C language where all the method variables would be declared at the beginning of a method. Even if some of those variables don’t appear in the code until later in the method. C++ lets you declare variables at any point in your method. And declaring them at the point they’re first needed makes your code easier to read. But there could be times where you have several similar variables and you want to declare them together. You might not yet have values to go into those variables. C++ is okay with this. Just don’t read from them until you’ve written something to them. All of this was basic information to me. And I’ve also already been aware of many different ways to declare and initialize variables. But this talk really brought everything together. I liked how it described clearly all the ways a variable can be declared and what the effects will be. For example, if you declare a char called c and give it an initial value of the letter a, then it’s an error to declare another char called c1 and give it the value c + 1 inside of curly braces. But if you declare a char called c2 and give it the same value of c + 1 without using any braces at all, then this is okay. Or you can declare a char called c3 and give it the value c + 1 inside of parenthesis and this is also okay. The reason the first one fails with an error is because the compiler will perform the addition of 1 using integer arithmetic and then try to assign the integer result back to a char. Since an integer can hold more information than a char, this is a narrowing operation and could result in the compiler needing to chop some bits off of the integer. It won’t do this unless you tell it that it’s okay. The whole point is that there’s often subtle differences between using parenthesis and curly braces. The rules are not always easy to understand especially if you’re not aware of the possible problems. And when you include auto in the mix, it gets even more complicated. Now, it’s possible that just using an equal sign or no equal sign in the variable declaration can affect not only the value but the basic type of the variable being declared. I hope I’ve given you enough motivation to watch the video once it becomes available. It’s about an hour long and unless you do this sort of detailed work everyday writing your own compiler or something, I can say that you’ll definitely learn something from the video. The rules are changing all the time. Some of the things I learned from this talk were about how things change in C++17 vs. earlier versions of the language. You’ll also gain insight into some changes that might take effect in C++20.
11 minutes | Sep 16, 2018
243: How To Install Linux, GCC, GDB, Git, CMake, LLVM, Clang, Boost, SFML, CodeLite, Sublime Text 3, And Dropbox On a $140 Lenovo ideapad 120S.
Installing Linux, GCC, GDB, Git, CMake, LLVM, Clang, Boost, SFML, CodeLite, Sublime Text 3, And Dropbox On a $140 Lenovo ideapad 120S makes an ultra portable C++ programming laptop. Listen to the audio podcast to hear my story about how and why I decided to buy an 11 inch Lenovo ideapad 120S. This is the show notes page and here you’ll find the detailed step-by-step instructions that I promised in the podcast. I spent over a week researching and documenting everything I did to get this computer ready so that you can follow along and learn from what I’ve discovered. Maybe some of the instructions could be made similar or simplified more. I tried to make them as simple as possible. Most of these instructions came from other websites, from questions and answers in online forums, and from the product web pages. There were too many sources to keep track of. Some gave conflicting or wrong instructions. And some might have worked by themselves but had trouble with other steps I was doing. Here, you’ll find a full listing of all the steps and commands that I found to work well. And they should all work well together on this computer. Please let me know if I missed anything or if anything needs further explanation. Ready? Okay. Follow along and install Linux and all the development tools you’ll need to get started programming. Remove Windows 10 and install Linux instead Go through initial Windows setup and use the installed updating tools to update the computer BIOS. Download Kubuntu from https://kubuntu.org Create bootable USB drive Download UNetbootin from http://unetbootin.github.io Run UNetbootin and select the downloaded Kubuntu and the USB drive and make it bootable. Insert USB drive, restart the Lenovo ideapad, and press Fn-F2 repeatedly while the computer starts up until the BIOS screen appears. Change the boot order so that the computer will try booting from the USB drive first. Save changes and continue restarting the computer. Wait for Kubuntu to start and choose the option to install. Answer the basic setup questions and for the page where it asks how to format and partition the drive, select the guided option that uses the full drive. Useful configuration changes Open the Konsole terminal. Protect root folder from accidental deletion alias rm=’rm -preserve-root’ Setup nano as the default editor export editor=nano Install basic build tools and libraries Open the Konsole terminal. Install basic development tools. Allow apt-get to find and install additional software packages. sudo nano /etc/apt/sources.list remove the leading “# ” from near the end where it says to uncomment the following lines to enable partner content. Just uncomment the deb line so it looks like this: deb http://archive.canonical.com/ubuntu bionic partner sudo apt-get update sudo apt-get install build-essential ccache Install CMake sudo apt-get install cmake cmake-gui Install Git sudo apt-get install git gitg Install glogg log file viewer sudo apt-get install glogg Install Boost sudo apt-get install libboost-all-dev This installs the Boost header files to: /usr/include/boost And the Boost libraries to: /usr/lib/x86_64-linux-gnu Install SFML Install prerequisites. SFML installs okay without these but from what I’ve been able to tell, it might not be fully functional without these. These were already installed for me. Installing them directly marked them as a manual install sudo apt-get install libpthread-stubs0-dev sudo apt-get install libgl1-mesa-dev sudo apt-get install libx11-dev sudo apt-get install libxrandr-dev sudo apt-get install libfreetype6-dev sudo apt-get install libglew1.5-dev sudo apt-get install libjpeg8-dev sudo apt-get install libsndfile1-dev sudo apt-get install libopenal-dev sudo apt-get install libsfml-dev This installs the SFML header files to: /usr/include/SFML And the SFML libraries to: /usr/lib/x86_64-linux-gnu Add more storage space for about $25 (Optional) Buy a 32 GB Micro SD card. Make sure it really is Micro. It will probably come with a bigger SD card adapter. You only need the smaller Micro SD card. Run the Dolphin file explorer and create in home folder a new folder called Storage. Insert the drive into the slot in the side of the computer. Open KDE Partition Manager. Select the drive at /dev/mmcblk1 Right-click the existing FAT32 partition and choose to delete. If the partition is already ext4, then you probably have the wrong drive selected. Choose the Partition menu and select New. Fill in the options to use the full disk, make a primary partition, select the ext4 filesystem, and give it a label. Click the Apply button at the top to make the changes. Right-click on the ext4 partition at /dev/mmcblk1p1 and Unmount. Right-click on the ext4 partition at /dev/mmcblk1p1 and Edit Mount Point Choose the Storage folder you created in the home folder. Right-click on the ext4 partition at /dev/mmcblk1p1 and Mount. Take ownership of the newly formatted drive. Replace “user” below with your user name. Open the Konsole terminal cd ~ sudo chown -R user:user Storage Use the Dolphin file explorer to create or move the following folders from your home folder into the Storage folder. You can recreate the folder icons by viewing the folder properties and clicking the folder icon in the properties dialog. Documents Downloads Music Videos Configure Git. Use your own name and email below. Open the Konsole terminal. git config –global –add user.name ‘Your Name In Quotes’ git config –global –add user.email email@example.com git config –global –add core.editor nano git config –global –add push.default simple git config –global credential.helper cache git config –global credential.helper ‘cache –timeout=3600’ Install Clang and LLVM Open the Konsole terminal. sudo apt-add-repository “deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-6.0 main” wget -O – https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add – sudo apt-get update sudo apt-get install clang llvm Install CodeLite Open the Konsole terminal. echo “deb https://repos.codelite.org/ubuntu/ bionic universe” | sudo tee /etc/apt/sources.list.d/codelite.list sudo apt-key adv –fetch-keys http://repos.codelite.org/CodeLite.asc sudo apt-get update sudo apt-get install codelite wxcrafter Install Dropbox Open the Konsole terminal. echo “deb [arch=i386,amd64] http://linux.dropbox.com/ubuntu xenial main” | sudo tee /etc/apt/sources.list.d/dropbox.list sudo apt-key adv –keyserver keyserver.ubuntu.com –recv-keys 1C61A2656FB57B7E4DE0F4C1FC918B335044912E sudo apt-get update sudo apt-get install python-gpg dropbox Install Sublime Text 3 Open the Konsole terminal. wget -qO – https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add – echo “deb https://download.sublimetext.com/ apt/stable/” | sudo tee /etc/apt/sources.list.d/sublime-text.list sudo apt-get update sudo apt-get install sublime-text Install OBS (Open Broadcaster Software) Open the Konsole terminal. sudo add-apt-repository ppa:obsproject/obs-studio sudo apt-get update sudo apt-get install obs-studio
5 minutes | Sep 2, 2018
242: In The End, It’s You Vs. You.
In the end, it’s you vs. you. Is this about living or dying? It seems that this is a common inspirational quote used a lot in fitness clubs and weight loss programs. But I first saw it on a t-shirt this weekend. I was at one of my favorite places to eat, Aria Kabab in Queens, New York. I told the person that the quote was very true and he asked me how I interpreted the quote. He had a different interpretation. And it was interesting enough that I left thinking that I was going to discuss it with you for this week’s episode. Now, you might also see variations of this quote that tell you to make sure that you’re the winner. To me, this is misleading and goes against the basic message. The only way to lose is when we forget the basic message and start comparing ourselves to others or start thinking about ourselves as a different person. My interpretation is that life is all about improving ourselves and helping others improve as well. And the only true way to measure our progress is to look back and see how much we’ve each improved. You can’t measure progress against somebody else’s current status or even against another person’s improvement. The only thing that matters is that you’re getting better each day. Even a little bit of a gradual improvement will result in big changes over time. My friend at Aria said that I was the first person to comment on his shirt and had a different meaning in mind. While I took the phrase, in the end, figuratively, he took it to mean exactly what it implied. He said that when we die, everything we did up to that point is what we have to rely on. There’s no asking for help from anybody. Not our parents. Not our friends. We have only ourselves and our preparation. Listen to the full episode to hear my comments on how these two interpretations work together and some advice on how to structure your goals so they have the most meaning. Or you can read the full transcript below. Transcript It seems that this is a common inspirational quote used a lot in fitness clubs and weight loss programs. But I first saw it on a t-shirt this weekend. I was at one of my favorite places to eat, Aria Kabab in Queens, New York. I told the person that the quote was very true and he asked me how I interpreted the quote. He had a different interpretation. And it was interesting enough that I left thinking that I was going to discuss it with you for this week’s episode. Now, you might also see variations of this quote that tell you to make sure that you’re the winner. To me, this is misleading and goes against the basic message. The only way to lose is when we forget the basic message and start comparing ourselves to others or start thinking about ourselves as a different person. My interpretation is that life is all about improving ourselves and helping others improve as well. And the only true way to measure our progress is to look back and see how much we’ve each improved. You can’t measure progress against somebody else’s current status or even against another person’s improvement. The only thing that matters is that you’re getting better each day. Even a little bit of a gradual improvement will result in big changes over time. My friend at Aria said that I was the first person to comment on his shirt and had a different meaning in mind. While I took the phrase, in the end, figuratively, he took it to mean exactly what it implied. He said that when we die, everything we did up to that point is what we have to rely on. There’s no asking for help from anybody. Not our parents. Not our friends. We have only ourselves and our preparation. As I got to thinking about this, I realized the two meanings fit together well. There’s no winner or loser here. What it means is that we each have to keep a bigger goal in mind. We need to improve and measure our improvement against ourselves and at the same time, we need to make sure that we’re improving good things. Things that will help us now and later. You see, life is a race. It’s a race to do as much good in this world as we can and that means we need to keep getting better so we can take on bigger and more meaningful projects. I’m not going to turn this episode into a religious talk. That’s why I’m sticking to things that we can all agree on. The need to improve ourselves and do good for the short time we have available. Just think of it like this. There’s 365 days each year. And if you live to be 80 years old, then that means you have just 29,200 days. Since most of us spend the first 20 years getting through school, that leaves 21,900 days. If you use one M&M candy for each day, and there’s about 500 M&M’s per pound, then the remaining days fill about 45 bags. And if you’re in you’re 40 years old already, then you’re down to just 30 bags. I encourage you to make each day count. Don’t let a single day pass by without improving something about yourself that will help you now while you still have time and later when your record is all you have left to you. Aim high and set big goals full of lasting meaning that will help you later. And set smaller goals that you can measure your progress on that will help you now. By keeping your smaller goals aligned with your bigger goals, you’ll be making progress and heading in the right direction. And if it’s been a while since you listened to episode #1 of this podcast, I encourage you to back and listen now. Keep what I’ve just mentioned in mind. I’m referring to the second episode since the first was episode #0. As programmers, it’s actually natural to start counting from 0 instead of 1.
Terms of Service
Do Not Sell My Personal Information
© Stitcher 2021