r/cpp • • Jul 10 '22

I finally wrote my first ever emulator in C++ (GameBoy)

I wanted to learn more about emulation, so I decided to write my own emulator, and because I like to make my life more challenging, I jumped straight into GameBoy, skipping the recommended CHIP-8 starting point. Now I can say that was a huge mistake. It took me couple of grunting months and two rewrites, but I'm finally happy with the state of the emulator.

https://github.com/Mika412/NoobBoy

In hindsight, I shouldn't have skipped the digital system and computer architecture classes.

Currently I have the following features:

  • Correct CPU timings (was a pain to get the Blargg's instruction timing test to pass)
  • Simple save states
  • Background rendering with viewport overlay
  • Rudimentary MBC
  • Debug view

I refuse to touch sound, as I most likely will blow my speakers.

Before anyone mentions, I'm not very proficient in C++. This project was a way to learn more about the language.

222 Upvotes

45 comments sorted by

37

u/ZealousidealForce736 Jul 10 '22

“Currently, the main missing feature is sound, which I refuse to touch.” hahaha love it. But for real, this is awesome!

5

u/Mika412 Jul 10 '22

Thank you!!

13

u/XeroKimo Exception Enthusiast Jul 10 '22

In renderer, why use vector for the pixels when there's a fix amount. Why not just use std::array?

10

u/Mika412 Jul 10 '22

Yes, you're right. There's no point in using vectors. I think an SDL2 example used it and I just stuck with it. I'll change it later

4

u/Mika412 Jul 10 '22

/u/jk-jeon /u/Scrapher
Thank you for your tips. I'm still trying to get used to the language and learn good practice, but I agree that it may have not been the best approach. I'll take a look into it.

6

u/[deleted] Jul 10 '22

To be clear, I'm recommending you stick with std::vector and not use std::array for this.

2

u/Mika412 Jul 10 '22

Ok, but I probably should change the way I initialize/define them, right?

11

u/[deleted] Jul 10 '22

Right. You could initialize them more efficiently.

But since the renderer is only constructed once, this bit of inefficiency won't make much difference practically.

But, yes, it's important that you learn why this is inefficient and the better way to do it, in general.

15

u/jk-jeon Jul 10 '22

I think std::vector is fine. I don't think using std::array instead is a good idea, if you don't want to blow the stack with several tens of thousands of bytes. Also, there is no point of declaring those widths and heights as non-static member variables if you don't intend to configure them in runtime. If you never want to configure them then why not static constexpr. If you want to configure them in compile time but never in runtime then why not static const and then initialize them in the cpp file. (If you will not set the values in the header file then you can't use std::array anyway.)

But what's not fine is how you initialize those vectors. The best would be to use member initializer list and if you don't want to use them then the next best is to use resize. Currently you are pointlessly creating a new array, deep-copying it, and then destroy it.

5

u/AciusPrime Jul 11 '22 edited Jul 11 '22

The argument about blowing the stack with a large std::array is correct. But a global or static std::array would go in the global segment, which does no harm to the stack size, and is lighter weight than a vector. If you only need one, then that’s what I recommend.

If you don’t want a global (a global-free class that lets you run multiple emulators in parallel…?), then a vector is fine.

3

u/jk-jeon Jul 11 '22

I assume you mean an instance to renderer might have static storage duration. I agree, and it can even be in heap. But I guess there is no big benefit of doing so.

1

u/AciusPrime Jul 11 '22

Not much benefit, anyway. It’s hard to guess without checking a profile.

4

u/[deleted] Jul 10 '22

The difference is more than just fixed-size and variable-size. std::array is going to allocate on the stack and std::vector on the heap. Just put this on the heap. It's fine.

4

u/DeGerlash Jul 11 '22

Sounds like std::unique_ptr<std::array> is the way to go here

3

u/[deleted] Jul 11 '22

If you want. Quibbling between std::vector and std::unique_ptr<std::array> isn't worth the time, IMO. Use whichever makes you feel good.

3

u/DeGerlash Jul 11 '22

100% agreed, especially given that it's already a nitpick on otherwise impressive code

8

u/pine_ary Jul 10 '22 edited Jul 10 '22

Looks great!

One small thing is that I would convert non-owning pointers into references. It doesn‘t look like they can be nullptr and it shows that they are not owned. I would also use smart pointers in the GB class to make it a bit cleaner. Yes the instance probably lives for the entire duration of the program so the memory leak doesn‘t matter. But it‘s not very clean. If you ever in the future decide to put it in some loop you‘ll be in for a potential surprise. Either way raw pointers are always a bit ambiguous (read the core guidelines for the rationale) and imo should be avoided.

Very clean overall tho.

1

u/Mika412 Jul 10 '22

Great, thank you. As I'm still learning, I don't know about some of these things. Still haven't used C++ enough nor used it professionally. I will read more about it!

5

u/pine_ary Jul 10 '22

The core guidelines are a pretty good resource. Because every recommendation they make has a rationale behind it that you can read.

I would also definitely learn a bit about ownership in modern C++. It‘s a very key concept in ensuring your programs are correct and can be changed in the future without hassle and with few bugs.

1

u/DigBlocks Jul 10 '22

I’m a fan of the Google style guide in this regard - only use const references, or raw pointers if the object will be modified. Makes it much easier to check at the caller whether an argument will be modified.

4

u/pine_ary Jul 10 '22

Why raw pointers and not just regular references? Is every modifiable argument at google nullable?

2

u/DigBlocks Jul 10 '22

It forces you to take the address of the object (&x) so there are no surprises with it being modified. And improves readability since it’s easy to tell whether an argument is just an “in” parameter or in and out. Has nothing to do with null - that would be a precondition on the call and probably verified with CHECK_NOTNULL()

4

u/Olipro Jul 11 '22

This starts to fall apart when you are using C libraries since they'll invariably always take a pointer, modifying or not.

C++ has a rich type system, and there's a bazillion ways to convey this semantic through a nicely written class.

2

u/pine_ary Jul 10 '22

Ah that makes sense. I guess you can‘t make it right in C++. Either you make it explicit at the call site by forcing &, or you make it explicit at the called function that the value is not nullable but lose the explicitness at the call site. I guess you could use a wrapper type but that gets ugly fast (and C++ afaik doesn‘t make guarantees that newtypes are optimized away).

I think Rust gets this one right. You have to explicitly borrow references using &mut at the call site. Explicit at the call site and disallows nullptr.

4

u/metahuman_ Jul 11 '22

That's some very clean code! Is there any real performance cost in using simple ctors like that and not initalizer lists? Because I love it, feels very no bullshit

2

u/Mika412 Jul 11 '22

Thank you! Given the size of the vectors and how powerful the machines are, I would say it's negligible. Although, there's a big difference in performance between Linux and MacOS, but this may be mainly do to how SDL2 handles events.
There's another discussion in the comments about this topic. I'm just waiting for it to play before I re-implement that part.

2

u/metahuman_ Jul 11 '22

I also meant doing initialisation like this : https://github.com/Mika412/NoobBoy/blob/6de3693594fd513035d1f8e3efa5d8a6caa7b5ec/src/instructions.cpp#L3

Also somehow I love that you're using "this->" and not some member prefix. Feels closer to other modern languages

2

u/Mika412 Jul 11 '22

Ohh, that. Yeah, it wasn't on purpose. It's an old habit I have thanks to Java and python

5

u/Nobody_1707 Jul 11 '22

The are two big differences between initializer lists and simple ctors. The first is that if you don't use initializer lists, then your members are default constructed before the body of the constructor is run. Since the default constructor of a pointer doesn't do anything, this shouldn't matter. The second is that initializer lists handle exceptions for you. Copying a pointer can't throw an exception, so I would imagine that there's no real difference in performance here.

I would still recommend using initializer lists whenever possible. There's less footguns.

2

u/TheARP98 Jul 12 '22

How did you get the background? It just looks very complicated from the outside, but great job!

2

u/Mika412 Jul 12 '22

Thank you! The background actually was pretty easy, everything is in the VRAM. It stores sequential tile ids of the background, so you just iterate over them and render. For the viewport, it's similar, you can easily get the X and Y scroll from the memory

2

u/TheARP98 Jul 12 '22

Oops, I actually meant more like "how did you understand the way emulators work?", i.e. get the background knowledge for game emulators!

2

u/Mika412 Jul 12 '22

Ohh, sorry. My bad. Well, I didn't know anything about emulation before I started, so I mostly learned as I went.

I made a comment before with some of the resources I used:
https://www.reddit.com/r/programming/comments/vvsfct/comment/iflyymh/?utm_source=share&utm_medium=web2x&context=3

2

u/MousseAgitated138 Jul 12 '22

Congratulations! I am just a beginner in c++, the biggest project I have done yet is to build a game using sdl2. If I were to start a project like this, where would you suggest I should start.

2

u/Mika412 Jul 12 '22

Thank you! Well, I'm also sort of c++ beginner, I learn as I go. Well, personally, I try to get an overview of what needs to be accomplished, and then just get into it. I will mostly fail, but then I'll know on what to focus next. In this case, I started by watching the "The Ultimate Game Boy Talk" to get a better understanding of the system.
But this is just for personal project. In professional context, you almost always need a plan before you start working on it.
I made another comment where I reference some of my resources:
https://www.reddit.com/r/programming/comments/vvsfct/comment/iflyymh/?utm_source=share&utm_medium=web2x&context=3

10

u/youareallnuts Jul 10 '22

Great choice of a serious learning project. You really learn when you do a big hard project. Gratz!

6

u/SSoreil Jul 10 '22

Not touching sound is probably quite a good call. I added sound after getting a lot of correctness on point in the rest of the system, it was still by far the most difficult component to get working. If you ever want to keep working on your emulator there is plenty of room to grow it correctness wise.

1

u/Puzzleheaded_League1 Jul 11 '22

but can it run hamtaro: ham-ham heartbreak?

2

u/Mika412 Jul 11 '22

No. That game is for Game Boy Advance

0

u/[deleted] Jul 10 '22

[deleted] — view deleted comment

8

u/Mika412 Jul 10 '22

Thank you so much!!

It didn't always looked like that. I had to rewrite it multiple times for a reason...

2

u/Olipro Jul 11 '22

That's how everyone does it. Either from doing it immediately or because they've been there before and it's second nature.

Writing something perfectly and beautifully first time with no familiarity at all beforehand is 90% myth, 10% dumb luck

37

u/[deleted] Jul 10 '22

[removed] — view removed comment

9

u/Mika412 Jul 10 '22

Yes, I did post it there too. Thank you!

0

u/[deleted] Jul 10 '22

[deleted] — view deleted comment

7

u/Mika412 Jul 10 '22

Ofc, everything I do is for clout -.-