I've been trying to make a game using ncurses.
However, I am stumped with how to make the timing part of my main loop work.
Would someone be able to add some insight into how I could add framerate code to my main loop, while keeping portability and not compromising speed.
Thanks in advance!
The normal way to handle this type of problem I believe is to pass in the duration since the last loop (often called delta) as a parameter to the system. This allows you to update the progress of entities in the game based on the amount of real world time that has passed. For example:
new_position = old_position + delta*speed
This allows entities in your game to move at a constant speed independent of the frame rate of your program.
Assuming you have functionality to update your gamestate after a small period of time, next you need to be able to poll the user for input. If you do not specify otherwise, ncurses will block when you ask for input. To prevent this, look up the init functions here. In particular, the halfdelay() function may be of use of you (it implements a sort of framerate).
Just remember to check for ERR on the return value of getch() when using this mode.
Related
I've seen a lot of answers to very similar questions, but they all seem to resort to using something like a sleep(1/n) call at the end of a function or in some cases timing the function and calling sleep((1/n) - functionTime). Surely there is a better way to do this? Modern hardware has access to precise hardware timers that can send an interrupt to the CPU some known number of times per second, is there no way to take advantage of these timers to run a function such as a physics engine update a known, fixed number of times per second from user space code? What I would like to do in particular is, preferably in C or C++, define some function, let's call it foo(), and designate it to be called N times per second. I would want to be able to know that if M seconds have passed, foo will have been called N*M times assuming foo() ran in less than 1/N seconds on average.
There is no standard C API for scheduling calls.
You probably want to have a separate thread that runs every 1/Nth of a second.
In the pthreads world, this can be done with pthread_cond_timedwait. This function expects the absolute time to wake up. In addition, some other thread can wake it up using the condition variable if some unplanned update needs to be made.
In the Windows world you probably need one of the WaitFor<whatever> functions. They expect a relative timeout, so you want to convert absolute time to relative time-interval-from-now yourself. In this case, too, another thread is able to wake you up to perform an urgent update.
The absolute time you need is just the absolute time the previous call was scheduled for, plus 1/Nth of a second. The very first one can be set to the current time just before the call.
I'm porting some code from C# to C. In the C# code there are three timers that fire if particular events take too long and they set flags that are checked next time a thread runs a bit of housekeeping.
The C is pure C, not C++, and will eventually be used on both Linux and in embedded targets, so I can't use any OS oriented stuff- simple soft timers. I started off using just an "enabled" flag and a due time for each timer, in ms, and when I call the housekeeping function I'll pass the current ms timer value to it. Then I started thinking of the wraparound issue and decided I wanted the start time as well, so if the present time isn't between the start time and the due time I know it's expired. And I want the default duration to be there as well, so it ends up being worth making a structure to represent a timer. And then making functions that work with pointers to these structures. And then it started me thinking I may be reinventing the wheel.
I don't see anything in the standard libraries that looks like this. Am I missing something? Is this just something that's just easier to do than to look for? :)
Ta for commenting. That's the way I went, just wanted to make sure I wasn't wasting work. Yeah embedded stuff tends to have a timer interrupt, but three is probably asking a bit much and adds hardware dependencies- I'm just passing the current ms timer value to my code and then it doesn't have to care about where that value's coming from. – Craig Graham
I have a GTK window with an image inside of it. I want this image to change. Let's say I have two images, "sun.png" and "moon.png". Once every second, I want to receieve the output of "date -f%l" to get the current hour. If the hour is between 7-19 (7 AM to 7 PM), I want to display sun.png. Else, I want to display moon.png.
Is it possible to have a seperate thread with a while loop in it, that changes the image as the program's running? How would I go about doing this?
I'm writing in C, by the way.
This isn't going to be a complete answer, but it's too long for a comment and it's important.
You definitely do not implement something like this by going into a loop sleeping for one second at a time and calling the external date command and parsing its output to determine what to do next. Not only is this a lot more work than is necessary; more importantly, it will eat your users' batteries for dinner.
Instead, you call gettimeofday or clock_gettime to determine the current time, then compute the next time in the future that the sun/moon image will need to be changed. Then, you sleep the whole interval until that time, i.e. up to 12 hours in a single sleep. If your thread wakes up early (perhaps from signals, etc.) then you just determine, on calling gettimeofday again, that it's not yet time to change, and compute a new duration of time to go back to sleep. This way, the CPU remains completely idle (and can go into powersaving mode) except when there's actually work to be done.
As for whether you can do this with a thread at all in GTK+, I'm pretty sure you can, but I'm not familiar with the GTK+ API.
I am planning to write a Pacman game in C language, right from scratch. The most basic challenge that I am facing is how to maintain multiple flows of control at the same time.
I mean how does the Pacman move, the ghosts move, the score being updated -- all at the same time. In general it is very common for all games. Is any kind of threading involved here?
If so can anyone please tell as to how to make your program do many things at the same time (it will be helpful if you tell for C language).
Thanks in advance
One of the fundamental principle in real time game development is the game tick. It represents a small unit of time for things to happen in. So you might have a tick every 0.100 seconds. The smaller the tick, the finer control you have.
You can think of them as really fast turns with a time limit on them. If you don't do anything on that turn you forfeit the turn.
I think it's pretty unlikely that the original version of Pac-Man was multithreaded in the sense we use the term today. It was more likely implemented as a simple loop with some kind of interrupt support. You can do the same to implement rudimentary multithreading - write your program in a while (1) or for (;;) loop, and set up a timer to interrupt your loop at regular intervals to perform the screen updates.
I have an image generator which would benefit from running in threads. I am intending to use POSIX threads, and have written some mock up code based on https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal to test things out.
In the intended program, when the GUI is in use, I want the generated lines to appear from the top to the bottom one by one (the image generation can be very slow).
It should also be noted, the data generated in the threads is not the actual image data. The thread data is read and transformed into RGB data and placed into the actual image buffer. And within the GUI, the way the thread generated data is translated to RGB data can be changed during image generation without stopping image generation.
However, there is no guarantee from the thread scheduler that the threads will run in the order I want, which unfortunately makes the transformations of the thread generated data trickier, implying the undesirable solution of keeping an array to hold a bool value to indicate which lines are done.
How should I deal with this?
Currently I have a watcher thread to report when the image is complete (which really should be for a progress bar but I've not got that far yet, it instead uses pthread_cond_wait). And several render threads doing while(next_line());
next_line() does a mutex lock, and gets the value of img_next_line before incrementing it and unlocking the mutex. it then renders the line and does a mutex lock (different to first) to get lines_done checks against height, signals if complete, unlocks and returns 0 if complete or 1 if not.
Given that threads may well be executing in parallel on different cores it's pretty much inevitable that the results will arrive out of order. I think your appraoch of tracking what's complete with a set of flags is quite reasonable.
It's possible that the overall effect might be nicer if used threads in a different granularity. Say give each thread (say) 20 lines to work on rather than one. Then on completion you'd have bigger blocks available to draw, and maybe drawing stripes would look ok?
Just accept that the rows will be done in a non-deterministic order; it sounds like that is happening because they take different lengths of time to render, in which case forcing a completion order will waste CPU time.
This may sound silly but as a user I don't want to see one line rendered slowly from top to bottom. It makes a slow process seem even slower because the user already has completely predicted what will happen next. Better to just render when ready even if it is scattered over the place (either as single lines or better yet as blocks as some have suggested). It makes it look more random and therefore more captivating and less boring to a user like me.