TERMINAL GAME ENGINE! // Code Review
Вставка
- Опубліковано 24 лис 2024
- Try Code Rabbit for FREE now ► coderabbit.ai
Patreon ► / thecherno
Instagram ► / thecherno
Twitter ► / thecherno
Discord ► / discord
Hazel ► hazelengine.com
🕹️ Play the latest Hazel game FREE ► studiocherno.i...
Code ► github.com/ura...
🌏 Need web hosting? ► hostinger.com/...
Send an email to chernoreview@gmail.com with your source code, a brief explanation, and what you need help with/want me to review and you could be in the next episode of my Code Review series! Also let me know if you would like to remain anonymous.
💰 Links to stuff I use:
⌨ Keyboard ► geni.us/T2J7
🐭 Mouse ► geni.us/BuY7
💻 Monitors ► geni.us/wZFSwSK
This video is sponsored by Code Rabbit.
Thanks for watching! Video I mentioned at 1:05 if coming tomorrow! ❤
Also definitely try Code Rabbit's AI code reviews! Free for open-source projects ► coderabbit.ai
Sir I have completed your course of C++ and I want to study the C++ more in deep from you because you are teaching good so where should I get these course.
How do I submit game for a game review ? But, my game is only partially done.
@@abacaabaca8131check the video description.
Hey Cherno! Thanks for reviewing my game engine :)). And video was fantastic and very helpful for me. I'm really learning from you a lot. About solution files, for some reason I couldn't make it work with cmake. I'm using Windows and Linux PC back and forth so I decided to leave it there. And for scene deletion: I wanted to implement a scene change but I would do that later.
When I saw it I thought that's amazing! It's really cool! Never thought it was possible to do such great games with terminal! And that's amazing that is done by someone just for hobby, and whose main job is being a vet not a programmer. Really well done!
I'm very impressed with your engine having been self taught. I noticed that you are calculating milliseconds from seconds, but you are using std::chrono, so no calculations are required. You can simply assign a seconds variable to a milliseconds variable, and the milliseconds variable will hold the value you were calculating manually.
for scene management i would definitely suggest having an array of std::unique_ptr
I am really inspired by you!! This is the start of coding journey as well... and seeing a fellow who is learning and making such a cool project is such a delight!
12:45 Terminals usually don't have a refresh rate, but more like a rate of characters or write operations per second limit. If you only ever update parts of the screen, it can go much faster than if you update the entire screen at once. Also, the Windows Terminal is ridiculously slow compared to common Linux terminals with Bash. That's likely why the demo game had some severe flickering when you tried it. I recently played with cellular automata and rendered them in the terminal. On Linux, I could fully update the full-screen, zoomed-out terminal upwards of 100x per second without flickering. The difference is crazy.
interestin, so thats why
I don't see what your shell should have anything to do with your terminal emulator's speed
I didn't know it was called defensive programming, I've always called it anxiety programming
Heh, thats a good name for it.
Its good to have a strong contract on an API, and 'this assumes non-null s' is a perfectly fine contractual item. And for fast low level stuff, likely necessary.
I usually try to assert on contractual items, as well as document them for the API. If I could get away with it (ie, it was fast enough), Id build the contract into types.
Have you seen the One Lone Coder console game engine?
Ye
**laughs in Spyro hub world rendered in console**
I think it's no longer in development and he switched entirely to his pixel game engine.
@@TheLordoftheDarkness yep. I follow his community. the pixelgameengine has grown to be quite impressive.
I was about to say the exact same thing!! OLC Console Game Engine is such a gem when it comes to learning c++ and programming in general
I've written a fair bit of terminal-based renderers for GUI and animation and there's definitely an art to making it performant, especially on older terminal emulators, but some "modern" ones like Windows Terminal are still quite slow. This is because the rate of updates is determined by the speed of I/O operations and the terminal's ability to render characters, which is bound by its internal implementation details.
Rather than working with pixels, you instead work with a buffer of characters that is made up of unicode/ASCII (what you usually see on screen) and control escape codes that is used to control terminal but doesn't render on screen. Both of which takes up space in the buffer. This means you are working with a buffer size that can vary, depending on your needs.
Some techniques we can use to optimize things is similar to what a GPU would do but at CPU level. For example having a virtual screen buffer that can be used to diff between cells and only update the 'dirty' ones, portion off a section of the screen buffer, rather than dealing with an entire screen at once and much more.
The most prominent and still often text-based user interface API is ncurses, which is also used by vim. It can be fast, but is very low level compared to, say a game engine. It's more akin to working with something like OpenGL directly.
DIdnt Casey's terminal rant encourage the windows terminal folks to speed up theirs? I thought I had read that they boosted large portions of it.
Regarding the vector of vectors a cool new feature in c++23 is that you can define multi-dimensional subscript (array access) operators, so you could create your own wrapper around a single-dimensional data-structure (or use mdspan for access) and access the values like a multi-dimensional array (tho with commas instead of chained [][]) e.g.: sprite[0, 1] => sprite of the 2nd column in the 1st row
I think you are talking about std::mdspan?
@@peternimmo74 not only. std::mdspan is just the library feature, which I also mentioned briefly. But the multi-dimensional subscript operator is the language feature which allows mdspan to work which it didn't (not like that at least) before C++23
The 2d -> 1d array mapping was something I learned with CUDA programming. Totally blew my mind and it’s a super clever way of storing multidimensional arrays. The indexing ends up being something like [row_width * row + col] for a 2d array where row_width is a fixed value and row/col are the “indices” you would normally use in a multidimensional array.
std::mdspan is going to make it even cleaner too!
Bonus points if row_width is a power of two because then it’s just a bit shift operation
Its better when you learn to reduce this to only additions when there are repeated operations taking place
Thanks for the video @TheCherno;
Knowing how to access the memory in an optimal way is one of the most important / first things a game engine developer should know! Glad you always bring this up into your reviews.
This "be aware of what value it might have" is the best feature about Rust. I don't care about their memory model per se, but the ability to force you to deal with the "possibly null"-like scenarios is golden.
Null… the billion dollar mistake
This is actually a pretty cool project idea because if they do it right they can extrapolate this functionality into a 2D and later 3D game engine extending their prior work. One suggestion I would offer is that if they're associating names of objects or file system paths to objects or a combination of both, say as a mapping of strings to them, then a flat hash table would be preferable to a map since you can store everything in a contiguous array and have nearly instantaneous jumps to individual elements. You might need to write one yourself or use a third party library, depending on whether the STL implementation for your system is good enough.
TBH about 22-25 yars ago when I still did my secondary I've got the idea to do an "Imperium Galactica II" inspired game in Turbo Pascal using DOS and 80x25 console. I had a book about VGA card programming which had a floppy with assembly codes. There was one example to replace the standard font table with custom one. I even managed to do animated planets to replace the font table periodically.
Bruh, the codes was shipped on a 5.25" floppy, I even had to find a friend who could copy those examples to a 3,5" disk. Good old memories.
I'm gonna wager this is the work of the new video editor. Great job! And if not, Great job!
My best video series in this channel. I learn so much things whenever I watch this videos.
Dang it I'm a decent C++ programmer and thought I'd catch everything you did but I immediately missed clearing the scenes vector at 6:08. It's really obvious to devs like me that your videos give us insight into what a senior engineer sees, which is incredibly valuable to those of us trying to push past the intermediate 3-4 years of experience stage
I would not use the raw pointer in the vector at all, but make it a unique ptr.
Looping through the destruction yourself is utterly unnecessary and error prone.
Oh good, someone mentioned this. I searched through once, and missed this comment. Glad I searched again.
unique_ptr is really solid for sure
Hey Cherno, I have a video idea: Why should you use pointers in some cases?
For example at 6:00 the Scene is a raw pointer, but why. You have to do cleanup etc. Wouldn't it be better to not use a pointer here and if this needs to be shared using a reference instead of sharing the pointer?
Good Job Ural! You've done a fantastic job, as expected of you.
Thanks görkem 😊
How nice to see not one but two fellow Turkish code enthusiasts here😁
Delete scenes in the same place where they were created. Either move the "new" to the "Engine" class (template "AddScene" method) or create and destroy ("new" and "delete") the scene in the "Run" method.
I'd say older Dwarf Fortress would be a terminal game engine. People used to play it over telnet. Same for a lot of older roguelikes. Nethack still has the ability to run in a terminal.
dll can just be updated/compiled separately from the main executable. if thats what you want. same for java, just compile what has changed. maybe the runtime stays the same, only the dll program changes. sometimes making a project for some IDE takes ages. avoid not-integrated make tools with all costs.
The idea of having one single long vector of all the sprites is the same concept of a sprite atlas. Not sure if they used the same term back in the day, but it's reminiscent of how they packed all the sprites to old games. Take Gameboy's Pokemon for example: when you go outside the range of expected sprite memory addresses, you get fun glitches like Missingno
Actual curses based engines aren't really common, but there's a ton of pseudo terminal libraries available for several languages for making traditional Roguelikes. Most of them also have utilities for a* and fov algorithms like recursive shadowcasting.
08:42 does assert not crash program?
What a cool project 🎉
Just found this channel and I already like it; especially how much enphasis you put on memory safety. What is your stance on Rust? Sorry if you already have a video on it, I didn't find.
The scene vector is problematic, but don’t leave the dangling pointers by deleting in place. Either remove then delete, or swap the entire vector out to a local var and delete from that.
Thanks for the video! I would have to disagree about the usage of dll, there is a reason for, namely, you plan to load this in several processes, you'll save RAM in the amount which correlates with the size of the library*Nproc. So, maybe that's what he had in mind. As for inlining, it would still work as you have to define those functions in headers to allow this behaviour in the first place.
THE THREE AMIGOS
THE THREE BROTHERS
THE THREE MUSKETEERS
Having a vector as a public member seems like a mistake too... Who gets to modify that vector and when? Answer (apparently): anyone at any time. How the scenes are stored should be an implementation detail, and what you can do with them should be tightly controlled.
It really depends on what you are doing even on a terminal game engine you could need ECS. Your problem is you are thinking purely what is being shown on the screen. But you could be doing far more in the background. Consider a game like dwarf fortress the original was terminal based. If you wanted all the entities in the game to continually do stuff even when not visible and depending on how many you have ECS would be a very good option.
Really nice review. As your other reviews, the video gets better the later in the video. Of course, it would be even better if that would be of a game where the author especially asked for a performance tips 😀. (Also, the next logical conclusion would be to go into optimizing the icache and put all the code for the same types of "GameObject" together. And that would nicely lead into my main objection to the code base: Does OOP really gives benefits here at all?
One remark: 6:44 "scene" is likely NOT nullptr here. it comes from the scenes[0] before, trying to read past the scene vector. so.. uninitialized memory or already an access violation. Also, although the fact that you _could_ call a non-virtual member function on a nullptr, anyone who actually consciously does this REALLY has to clearly comment it as a hack he HAD to do because he was with his back against a wall with a big shotgun at his face.
I am making my own graphics API for the terminal.
Sir I have completed your course of C++ and I want to study the C++ more in deep from you because you are teaching good so where should I get these course.
thanks for this video! i recognise in my game engine that i could have ALOT of guards sitting behind macros using asserts. i currently just use if() to check if things are null in the setup stage but just assume everything is fine in the render stage.
I have seen a terminal game engine before, even kind of made one before for a uni project, this is far beyond what I made though.
Hey Cherno, a question for you. Do you only take C++ code in your code reviews? I have a project in C and another in Rust that I would love to get checked out by you, but I won't send it in if you don't do other programming languages 😅.
I guess C should be fine if you already review C++ though...
17:19 Dwarf Fortress would probably be one of the only examples
I think you mean that with a huge buffer with all the sprites memory, the cpu will make less case heaps and that is cool but how can I know what part of this buffer is not used when random game objects are destroyed during the game loop?
Smart pointer move semantics should have been used. Better yet, have the engine call the constructors.
mmm u suggested iterating through the std::map of the gameobjects cuz iterating the extra std::vector of gameobjs is over optimized. but then u challenged his vector of vectors over some cache misses? i dont think flattening the vector would make any noticeable difference performance wise tbh
Cherno, would defensive programming warrant its own video? Sounds very interesting and extremely useful.
About the vector of vectors, isn't each member of a vector stored contiguously with the previous member?
up until you it needs to expand the vector.
@@ea_naseer Then it allocates a new block of memory big enough to hold the new size and copies all the existing members to the new block of memory. That's why if you need a collection that's going to change size a lot, you should use one based on a linked-list and not an array.
But each vector member is a pointer to another vector.
With the default allocator, a vector is just a wrapper around a dynamically-allocated array. So the vector objects are allocated contiguously, but the arrays backing them are not.
Thanks , i love these code reviews, i have a question : isn't the 2d array faster in the reallocation than the continuous approach because when it needs to add to the outer vector it only has to reallocate the main (outer) array, instead of reallocate the whole thing?
The problem is in this case iteration occurs much more often than reallocation. When the CPU fetches data from memory, it fetches a chunk at a time (not a single value at a time) so if all of your data is next to each other it can grab chunks much more effectively when iterating through it.
Another problem is that when the data is in different places, the memory access is much less predictable. When the code is predictable the CPU can fetch what it thinks it will need ahead of time (branch prediction). This is why sorting an array before using it can actually *improve* performance if the resulting logic is more predictable.
Reallocation occurs every so often, when the capacity is exceeded. Having lots of small allocations can fragment your memory and make future allocations slower - there can be gaps made by the smaller allocations that are harder to fill up. Also, each allocation requires a separate search for available space, so reducing the number of allocations is also an important thing.
So in general, keep the memory contiguous and don't use linked-lists.
@@BoardGameMaker4108 thanks for the explanation
to be fair, flattening the vector was a micro optimization in this case. doubt it changed much
The thing is, forcing yourself to limit yourself in this way can lead to more interesting optimizations.
It might depend on other factors, but if all you need is to know the location of something in a 2d grid you might only need one int per column.
0 nothing
1 something
So in this example you could have a 4x4 (or 4xn) sprite with only 5 int.
First int declares the column count. Second, third, etc hold the column data.
Only works if they really only need to store 1/0. Would get more complicated if they're doing more than just a position map.
Heyy cherno! I've been following you for 3 years now. Thanks for everything. You're the reason I landed my first Job.
Honest Criticism:
While I understand why you spend time on things like vectors of vectors and memory leaks, it would be really amazing if you actually review stuff that is interesting. You could probably look at a grass renderer or water renderer and talk about how these things work and can be improved.
In this case I was really looking forward to seeing how the console sprite rendering was managed but that was barely shown.
It would be really awesome to see how some actual amazing game features like GI, Volumetrics or Terrain from the perspective of an experienced engine dev - like the video that you did on asset packs. That was really useful !
Anyways I do understand that you might not have time to do both YT and Hazel at the same time but it would be really amazing to see some new content !
P.S - Editing is better these days! I guess the new editor does know his stuff.
the vector of vector thing felt like such a nitpick to me tbh. i understand theyre bad, but like making the change wont improve performance by any noticeable amount here
Nice idea
I have a little question. Since we have smart ptrs we should use only them instead of raw ptrs or we should even use raw ptrs for some efficiency critical apps to avoid overhead of smart ptrs or this overhead is neglible and doesn't matter? I watch sometimes some cpp talks and they always talk about memory safety above efficiency. I'm a little bit confused.
I think the main idea is that smart pointers deal with ownership. If that's not what you're dealing with in some code, than raw pointers should be fine
The cpp talks talk about memory safety because that’s the whole point of smart pointers. If your pointer only points to memory but doesn’t own it then use a raw pointer. There is no point avoiding smart pointers to squeeze out a bit of performance if you introduce a bunch of memory leaks and hard to track down bugs imo, especially if you didn’t actually measure and profile the performance increase.
If you are interested in cpp talks that discuss the overhead of smart pointers try chandler caruth’s “There Are No Zero-cost Abstractions” or Nicolai Josuttis’ “The real price of shared pointers”
Would you review my (or others) game engine written in c?
You really spend a lot of time on the simplest issues and never have enough time to get too deep in these projects. Like you could mention that he didn't handle the case where no scenes were added, but you don't have to spend 5 minutes exploring different options to handle that imo, just one ot two to prove the point is fine. For me it would be way more interesting to see more parts of the code rather than insisting on a few parts unnecessarily long
You should review Mike Acton's ncurses Unity game port.
≠ I am using this from now on
I love vulkan->I hate vulkan->I love vulkan->I hate vulkan->...
I hate vulkan -> I hate vulkan even more
I learned the other day dlls can be optimized at linker time
pretty sure this video is sped up a tiny bit?
Hi Cherno. Are Macros still wise?
The preprocessor - including macros - is a tool. It is a tool that is error-prone and easy to misuse, but there are legitimate uses for it. If you can’t find a sane alternative, using the preprocessor is fine.
Justin Debug? He back?
cool vid
i was just making a terminal game engine
I am sure this was inspired by Javidx9's Console game engine
Nope. I am seeing lots of people talking about this engine all the time. I've checked it myself after I see in the comments. And I've seen his code. And if you check his code, you will see there is no relation. He makes it single file and he is focusing more on rendering. While my focus is not rendering but making game engine related classes and architecture
@jgsw563 he made it portable but yeah, structural separation in classes is better. The principle, though, is the same if you use windows api for reading and writing to console(stdin and stdout)
@@radoslavdimitrov7505 yeah, because probably the best approach for multiplatform
If you didn’t do delta time, terminals like alacrity would have a field day with their 12mil fps 😂
can you send me your vs settings ? only for colors no time for make it self
Yeah, I keep noticing his bright yellow font for the keyword in the find box. Not sure how that's done. So would love his font settings.
This stuff in so hard to understand for a regular guy. I must be too dumb to even think about understanding it. Interesting though 👍👍
It is way simpler than it looks, you are probably just lacking critical information.
arrays of arrays are bad??? Don't tell any lua developers that... i think they might faint.
fwiw I use a terminal called Kitty which renders with a separate GPU accelerated thread for performance and feature enhancement :)
It's a shame you are not aware of javidx9's Console Game Engine
Lol
Newbs should write c not cxx
I think for someone new to programming in general both are difficult to write correctly. You need to already know what you are doing for both b/c they definitely won’t do anything for you lol.
let beginners learn what they want
Much too unstructured to be a good tutorial.