I have a problem with my sfml project in c++. After compiling and running this simple code, i start using my mouse in the window (the code is a very simple pathfinding algorithm, in which, where i click, that's where the "ch" texture goes) and after aprox. 10 or so seconds the window stops responding. The only time when the program doesn't crash is when i run it in debug mode. i had this problem some time ago with a bigger project, but because of this problem i gave up on it. I believe that the program crashing has somthing to do with using the mouse, because in the bigger project i once started and crashed in the same way I also used the sfml mouse functions, and when compiled and ran in debug mode, it didn't crash. I'm programming in Code::Blocks version:13.12, and the SFML library i'm not sure what version. I have no idea why this happens, so ask you for help whith this problem. Thanks:D
The code:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
using namespace sf;
int main()
{
RenderWindow win(VideoMode(700,700),"test");
float x=10,y=10;
int mx=x,my=y;
int mxo,myo;
Texture t;
t.loadFromFile("char.png");
Sprite ch;
ch.setTexture(t);
ch.setPosition(x,y);
while(win.isOpen())
{
win.clear();
if(Mouse::isButtonPressed(Mouse::Left))
{
mx=Mouse::getPosition(win).x;
my=Mouse::getPosition(win).y;
}
if(x!=mx)
{
if(mx>x)
{
x++;
}
if(mx<x)
{
x--;
}
Sleep(2);
}
if(y!=my)
{
if(my>y)
{
y++;
}
if(my<y)
{
y--;
}
Sleep(2);
}
ch.setPosition(x,y);
win.draw(ch);
win.display();
}
return 0;
}
You have blocking sleeps in the main event loop, and are not handling events.
This makes the OS think that the program is unresponsive, and it tells you that.
It didn't actually crash.
Related
I'm currently new to programming and don't know, how to let the program process while the loading bar is running.
I wanted to display the loading bar and check, wether the program is finished processing. If not, then the processing bar should simply begin to fill again.
My code now is just showing the loading bar once and begins to process after that. This is pretty useless.
I researched on Google and here on stack overflow, but i only got the loading bar from that, not the useful integration in my program.
I just need a simple way to check, wether there would be an output besides the loading bar and i need to run the rest of the program at the same time as the loading bar, just to save time.
#include <iostream>
#include <windows.h>
#include <unistd.h>
#include <string>
#include <thread>
using namespace std;
static void loading(){
system("Color 0A");
cout<<"\t\n\n";
char a=177, b=219;
cout<<"\t";
for (int i=0;i<=50;i++)
cout<<a;
cout<<"\r";
cout<<"\t";
for (int i=0;i<=50;i++){
cout<<b;
for (int j=0;j<=2e7;j++);
}
cout << "\n\n";
}
int main(){
//ProjectEuler Problem___
loading();
int j=0;
do{
j++;
}while(j<=1e9); //just an example to see when it is processing
cout << "hi" << endl;
return 0;
}
I'm grateful for any help.
The typical pattern you're looking for would look something like:
void do_expensive_work(std::atomic<bool>& done) {
... something expensive goes here...
done = true;
}
int main() {
std::atomic<bool> done = false;
auto t = std::thread(do_expensive_work, std::ref(done));
while (!done) {
... update your progress bar ...
... sleep a bit ...
}
t.join();
return 0;
}
The specifics of how you communicate the result of your computation back to the calling thread etc are up to you. Similarly, you could in theory use a global atomic for the done status, or wrap up the computation in a class that keeps track of state and manages the execution of the thread. Code above is greatly simplified but gives a general pattern.
I'm trying to create an application with the SDL, and would like the window to be resized.
For now, if I try to maximize the window, it works, if I place it in the left or right half of the screen, it works and take the right size.
But, when I resize the window by dragging one of it sides (vertical or horizontal), something really strange happen : the height grow until it's equal to the height of the screen.
When it grows, I can see that it's not instantaneous, in fact it takes many times times, growing each time of 37 pixels.
It's really strange, and I really don't know what to do.
I created a minimalist code to test if the problem was due to something special in my code, but it doesn't change anything, the problem is still the same.
Here is my minimalist code :
#include <SDL/SDL.h>
using namespace std;
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* surface=SDL_SetVideoMode(100, 100, 32, SDL_HWSURFACE|SDL_RESIZABLE);
SDL_Event event;
while (true)
{
SDL_Flip(surface);
SDL_PollEvent(&event);
if (event.type==SDL_QUIT) break;
else if (event.type==SDL_VIDEORESIZE)
{
surface=SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_HWSURFACE|SDL_RESIZABLE);
}
SDL_Delay(30);
}
}
So the problem don't seem to be in my code. (To verify that, I installed a game that use the SDL (Briquolo), and it has the same problem)
I searched on the web, but it seems that I'm the only person who got this problem (or it's maybe that I don't use the good keywords), so it seems that it's not the SDL.
The problem is probably caused by my system.
For information, got Ubuntu 16.10 64-bit, with the Gnome desktop.
How can I solve this problem, without having side effects ?
Finally found a way to avoid this (but I don't really understand why the first way didn't work) :
If I store the new sizes, process all events, and then resize, it works. Here's the working code :
#include <SDL/SDL.h>
#include <iostream>
using namespace std;
int main()
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* surface=SDL_SetVideoMode(100, 100, 32, SDL_HWSURFACE|SDL_RESIZABLE);
SDL_Event event;
bool resized=false;
int newW, newH;
while (true)
{
while (SDL_PollEvent(&event))
{
if (event.type==SDL_QUIT) return 0;
else if (event.type==SDL_VIDEORESIZE)
{
resized=true;
newW=event.resize.w;
newH=event.resize.h;
}
}
}
if (resized)
{
resized=false;
surface=SDL_SetVideoMode(newW, newH, 32, SDL_HWSURFACE|SDL_RESIZABLE);
}
SDL_Flip(surface);
}
I have made this program in Turbo C++ wherein when the user clicks inside the square that comes on screen, the program should exit. The program works fine if I run it once. But when I run it again, it exits as soon as mouse is inside the square. It does not wait for the click. I think it is something to do with resetting the mouse.
#include<process.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
union REGS in,out;
void main()
{
int gdriver = DETECT,gmode;
int xp,yp,cl=0;
int x,y;
initgraph(&gdriver,&gmode,"C:\\Turboc3\\BGI");
x=getmaxx()/2;
y=getmaxy()/2;
in.x.ax=4;
in.x.cx=10;
in.x.dx=10;
int86(51,&in,&out);
in.x.ax=1;
int86(51,&in,&out);
setcolor(RED);
rectangle((x-100),(y-100),x,y);
in.x.ax=3;
while(1)
{
int86(51,&in,&out);
cl=out.x.bx;
xp=out.x.cx;
yp=out.x.dx;
if(((xp>=x-100)&&(xp<=x))&&((yp>=y-100)&&(yp<=y)))
if(cl==1)
{
cl=0;
exit(1);
}
}
}
OUTPUT
P.S. I already know that Turbo C++ is an "ancient compiler" and I am well aware of the existence of other modern compilers, but I am forced to use this compiler.
Ok I have figured out the problem. When I start the program again, instead of dragging the mouse inside the square button straight away, if I click outside the square button first and then move towards the square button, the problem doesn't happen.
Basically, when the program starts for the 2nd time, the mouse starts with click=1 instead of click=0. I can't find out how to fix this though..
I've found this, dunno if that would help any. Depending what your OS you're running... or is that DosBox? It uses BGI to set graphic mode which may not work if you run it from x64 windows, should work from DosBox(at least, Turbo Pascal's version does). It is curious, that program does one dummy reading of mouse status after making cursor visible, to flush the registers. Is that the gotcha you're hit by?
#include<graphics.h>
#include<conio.h>
#include<dos.h>
union REGS i, o;
int initmouse()
{
i.x.ax = 0;
int86(0X33,&i,&o);
return ( o.x.ax );
}
void showmouseptr()
{
i.x.ax = 1;
int86(0X33,&i,&o);
}
void getmousepos(int *button, int *x, int *y)
{
i.x.ax = 3;
int86(0X33,&i,&o);
*button = o.x.bx;
*x = o.x.cx;
*y = o.x.dx;
}
main()
{
int gd = DETECT, gm, status, button, x, y;
char array[50];
initgraph(&gd,&gm,"C:\\TC\\BGI");
settextstyle(DEFAULT_FONT,0,2);
status = initmouse();
if ( status == 0 )
printf("Mouse support not available.\n");
else
{
showmouseptr();
getmousepos(&button,&x,&y);
while(!kbhit())
{
getmousepos(&button,&x,&y);
if( button == 1 )
{
button = -1;
cleardevice();
sprintf(array,"Left Button clicked x = %d y = %d",x,y);
outtext(array);
}
else if( button == 2 )
{
button = -1;
cleardevice();
sprintf(array,"Right Button clicked x = %d y = %d",x,y);
outtext(array);
}
}
}
getch();
return 0;
}
You're doing what my boss called jokingly "Computer necrophilia". Those old systems had all kind of quirks. There were reasons why programmers of old where maniacal about initializing variables. You could run into issue that if you declare a long int variable, then assigning to it a long value, then a short value, then only lower word will be set in second case - all because compiler wasn't "casting" short to long implicitly, it was just copying binary image to the same address.
I have faced the same problem recently and the cause is DOSBox, more precisely Turbo C++ IDE running in DOSBox. Try exiting the IDE and runnning your compiled program from the command line, it will work fine. Or try a virtualbox MS-DOS machine, it will work fine even from the IDE.
So I am making a game, an ASCII dungeon explorer and I had a plan to get the window size and scale the display the inventory beside the dungeon. I went on google to find a function that would return the window size so I can print the inv on the side... The parts that are commented out is the code that I found and so I tried to put it in my main.cpp just to try it out. I planned to use other functions that I found to get the max size of the window and to set the size. This code that I pasted into my code was giving me loads of errors when I went to run the game, somewhere around 180 errors from a header file called wingdi.h. I googled a bit more and found people changing some definitions in the project properties which I tried and it gave me about 130 errors from different headers included in . Someone said that one of the variables is already declared in windows.h and the person that asked that question should change it to something else so I changed csbi to my_csbi, both didn't work. Some people also said it was a problem with the code so I decided to just leave it for now, and go back to my old code and do something else for now (I was getting frustrated, lol). I commented it all out, hoping to come back to it later. When I tried to run my game with all of that code gone, it gave me the same errors. Do I have to reinstall Visual Studio 2015? Starting my code from scratch or changing some definitions?
#include <iostream>
#include <conio.h>
//#include <Windows.h>
#include "GameSystem.h"
using namespace std;
int main()
{
//int x = 0;
//int y = 0;
//CONSOLE_SCREEN_BUFFER_INFO my_csbi;
//GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &my_csbi);
//x = my_csbi.srWindow.Right -my_csbi.srWindow.Left + 1;
//y = my_csbi.srWindow.Bottom -my_csbi.srWindow.Top + 1;
//printf("columns: %d\n", x);
//printf("rows: %d\n", y);
GameSystem gameSystem("level1.txt");
gameSystem.playGame();
printf("Enter any key to exit...\n");
int tmp;
cin >> tmp;
return 0;
}
I am fairly new to programming so I'm sorry if my question is stupid or "simple" and if that offended you in some shape or form. :)
Thanks, Bulky.
EDIT: All the "solutions" others got didn't work for me and I decided to ask this because after I commented out all that code, my old code didn't even run (it was perfect before).
You never include <WinGdi.h> directly. You always include <Windows.h>, which pulls in the required headers implicitly.
The GDI functions (from <WinGdi.h>) aren't going to do you any good if you are writing a console application. The GetConsoleScreenBufferInfo function is probably what you want to be using, but it is not a GDI function. It is a kernel function. Again, although it is technically declared in <WinCon.h>, you are not supposed to include that header directly. Just include <Windows.h>.
The following code works fine for me
(other than the fact that std::cin doesn't actually work for "enter any key to exit..."):
#include <iostream>
#include <conio.h>
#include <Windows.h>
using namespace std;
int main()
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
int x = csbi.srWindow.Right - csbi.srWindow.Left + 1;
int y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
printf("columns: %d\n", x);
printf("rows: %d\n", y);
printf("Enter any key to exit...\n");
int tmp;
cin >> tmp;
return 0;
}
Output:
columns: 90
rows: 33
Enter any key to exit...
If it does not work for you, one of the following must be true:
1. The problem resides in "GameSystem.h", which you have not shown us.
(It is fineāin the future, please post code as text, not pictures.)
2. You have created the wrong type of project (recreate a new project using the Win32 Console Application template).
3. There is something wrong with your installation of Visual Studio (try reinstalling).
Some background: I am trying to track a bug which is causing me major headaches. After many dead ends (see this question) I finally ended up with this code:
#include <thread>
#include <vector>
#include <iosfwd>
#include <sstream>
#include <string>
#include <windows.h>
int main()
{
SRWLOCK srwl;
InitializeSRWLock(&srwl);
for(size_t i=0;i<1000;++i)
{
std::vector<std::thread>threads;
for(size_t j=0;j<100;++j)
{
OutputDebugString(".");
threads.emplace_back([&](){
AcquireSRWLockExclusive(&srwl);
//Code below modifies the probability to see the bug.
std::this_thread::sleep_for(std::chrono::microseconds(1));
std::wstringstream wss;
wss<<std::this_thread::get_id();
wss.str();
//Code above modifies the probability to see the bug.
ReleaseSRWLockExclusive(&srwl);});
}
for(auto&t:threads){t.join();}
OutputDebugString((std::to_string(i)+"\n").data());
}
return 0;
}
When I run this code inside VS 2013 debugger the program hangs with an output like this one:
....................................................................................................0
....................................................................................................1
....................................................................................................2
...........................
Strangely enough, If I pause the debugger and inspect what is going on, one of the threads is inside AcquireSRWLockExclusive (in NtWaitForAlertByThreadId) apparently there is no reason why the program is hanging. When I click resume, the program happily continues and print some more stuff until it is blocked again.
Do you have any Idea what is going on here ?
Some more info:
As far as I can tell, this bug only exists on Windows 8.1.
I tried VS2013.4 and VS2015 RC.
I could reproduce it on two different computers under Windows 8.1.
One of the machine was formatted, the RAM, CPU and Disk tested (I thought of a malfunction because at first I could only observe the bug on this particular machine)
I could never reproduce it on Windows 7.
It may be useful to modify the code between the comments to observe the bug. When I added the microsecond sleep, I could at last reproduce the bug on another computer.
With VS2015 RC I could reproduce the same behavior with a simple std::mutex. On VS2013 however the SRWLOCK seems mandatory to observe the bug.
This issue is caused by an OS scheduler bug introduced in the spring 2014 update to Windows 8.1. A hotfix for this problem was released in May 2015 and available at https://support.microsoft.com/en-us/kb/3036169.
For me it looks like a bug in windows OS, I have different code variants that hangs using new Vista primitives under debugger in Win 8.1 / Server 2012R2 after April 2014 update. Also some thread pool wait function hangs too. Looks like it mostly tied to other thread finished execution at the moment of wait/lock. Here is the simple code that always hangs under debugger in NtWaitForAlertByThreadId() :
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma optimize("",off)
VOID CALLBACK _WorkCallback(PTP_CALLBACK_INSTANCE Instance, PVOID pUser, PTP_WORK Work)
{
for (int i = 0; i < INT_MAX / 256; i++) {}
}
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
for (int i = 0; i < INT_MAX / 256; i++) {}
return 0;
}
#pragma optimize("",on)
int _tmain(int argc, _TCHAR* argv[])
{
LONGLONG c = 0;
while(!_kbhit())
{
PTP_WORK ptpw = CreateThreadpoolWork(&_WorkCallback, NULL, NULL);
if (ptpw != NULL)
{
for(long i = 0; i < 3; i++) SubmitThreadpoolWork(ptpw);
CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
WaitForThreadpoolWorkCallbacks(ptpw, FALSE);
CloseThreadpoolWork(ptpw);
}
printf("%I64d \r", c++);
}
_getch();
return 0;
}
Unfortunately I have no idea where to report it to the Microsoft.