int main() running constantly - c++

I am brand new to c++ so I apologize if this is a stupid question but I can't seem to find the answer to it.
I have been using Processing for a while now and would like to start using c++ because I heard it is faster and a program I made is too long/dense for Processing to run at a reasonable speed.
In Processing there is a setup void which runs once and then the draw void which runs continuously after that. This is what I am used to and I need it to make remake a program in c++ (a chess AI).
Is there a way to get int main to run continuously? If not can I have it call a function that will run continuously?
Also is there a way to make a window pop up when you run the program which you can draw geometry to? (I will need to make pieces that can be manipulated by a mouse ideally)
I'm using Xcode by the way

main() should typically do your setup and then start the main message-processing loop provided by your toolkit. The message processing loop will run continuously until the user requests your application to quit (or you ask the toolkit to shut down your app).
Your toolkit will call your draw function whenever your window needs to be painted. It will call other functions when user input such as keypresses or mouse clicks happen.
For example, if you were using the GLUT toolkit (for OpenGL, a very popular drawing API supported on Mac, Windows, Linux, and many mobile devices), your main function might look like this (complete tutorial here):
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(500,500);
glutCreateWindow("My First openGL Program");
glutDisplayFunc(render);
glutMainLoop();
}
For Cocoa, the OSX native API, it might look like this (more information and links here):
#import <Cocoa/Cocoa.h>
int main(int argc, const char** argv)
{
return NSApplicationMain(argc, argv);
}

May I suggest that instead of asking very rudimentary questions like this on StackOverflow, you go and invest your time reading one of the thousands of introductory C++ tutorials that are scattered all over the web.
After a couple of hours of reading you'll find that questions like this are answered faster via a Google search.
Good luck with your learning.

You should not try to get main() to run continuously.
You may instead do something like this:
int main() {
while (true) {
//call functions here
}
return 1;
}

In C++, each function is defined by it's call and it's return. For example:
void foo()
{
cout << "hello world!";
return;
}
int main()
{
foo();
return 0;
}
When foo() is called, it runs until the return statement. If we want foo to run for some indeterminate amount of time, we could, for example:
void foo()
{
bool isExiting = false;
char input;
while( isExiting != true )
{
cout << "Exit? ";
cin >> input;
if ( input == 'y' )
{
isExiting = true;
}
return;
}
}
int main()
{
foo();
return 0;
}
This is a kind of ugly example - using cin to a char and whatnot - but it gets the idea across. The while loop will run forever and the innards of it (well, it's logic, anyway) could be replaced with whatever your program needed to do.
Make sense?

There are plenty of options as far as graphics libraries go; you can use SDL, GLUT/OpenGL, DirectX, even good ol' Win32. However, for someone who is relatively new to things as rudimentary as while loops, I suggest that you stay off the C++ for a while, as there are many peculiarities that might prove to be enormous roadblocks. If you really need every ounce of speed, I recommend that you make a DLL with your time-critical algorithms and use it in conjunction with a simpler language that supports DLL's, and provides a relatively developer-friendly interface. Game Maker comes immediately to mind, although I'm sure there are many options out there.
Best of luck.

I'd recommend having a look at Cinder or OpenFrameworks as a neat transition from Processing.org - especially if you're planning on doing multimedia applications (which, if you were using Processing, is likely)
They both provide a very similar layer to that of Processing, and will ease your journey somewhat.
You could also implement your own basic framework on top of SDL if you feel up to it.
As a more general answer to your question, the main() function is basically the same as the setup() function in Processing.org - with the main distinction being that it has to call a (user-provided) draw() function or equivalent.
So a rudimentary equivalent would be:
bool quit = FALSE;
void setup() {
// initialise the screen and so forth
}
void draw() {
// perform some drawing and update tasks
}
int main(int argc, char *argv[]) {
setup();
while (!quit) {
draw();
}
shutdown();
return 0;
}
NB: the above will probably compile, but it would do nothing except loop and potentially bog up your machine since it's not connected to any graphics library and is getting no user input to modify the quit boolean.
finally, I'll quote a section from the Cinder faq:
I’m experienced with Processing, but I
think I’m ready to try something new.
Is Cinder right for me?
Very possibly.
First though, be sure you really need
to move on to Cinder. Have you already
experimented with using an external
IDE like Eclipse? Are you using native
OpenGL calls instead of PGraphics?
What about experimenting with Toxi’s
excellent libraries? You’ll learn some
things that will make an eventual
transition to Cinder much easier, and
as much as we’re into C++, it’s easy
to underestimate how far Processing
can take you. All that said, don’t let
us talk you out of this either — if
you’re excited about learning Cinder,
we’re excited to have you, and we bet
you’ll find it’s easier to get started
than you might imagine.

Related

Replacement for QTextCodec::setCodecforCStrings in Qt5

I have a lot of legacy that was making use of QTextCodec::setCodecForCStrings to handle other languages such as portuguese, swedish and italian. I know of this solution:
QTextCodec::setCodecForCStrings is GONE in Qt5
And have also read that blog
http://www.macieira.org/blog/2012/05/source-code-must-be-utf-8-and-qstring-wants-it/
but it does not help at all. The fact that this function is gone really is a dealbreaker for me.
I have considered writing my own QString class or copying the source code for SetCodecForCStrings and adapting it for Qt5. I will deal with cross-platform issues (it was already dealt with anyway).
Has anyone tried this ? If so what problem did you encounter ? Is there anything already made that could be used instead (library, wrapper, adapter) ? I do not mind paying for it if I need to. Or maybe I just have to stick with qt4 but I really like the new connect syntax...
Edit :
int main(int argv, char** args)
{
// Create test application.
QApplication application(argv, args);
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("GB18030-0"));
//My main form shown here
return application.exec();
}

Integrating C++ OpenGL project with another C++ project

I was working with a project that reads a data file, performs some calculations, and show results on standard output. Later i wanted to give a 3D graphical view to the results, so I made a new OpenGL project that shows data as 3D object.
Now the problem is, I can not figure out a way to integrate these two independent projects, because the main() in my OpenGL project goes in a non terminating glutMainLoop() loop, and I am unable to figure out where to put the loop in main() of my first project !
/**** Proj1 ****/
int main()
{
while(ESC key not pressed)
{
// read data file
// do some processing
// show results on standard output
}
}
/**** Proj2 ****/
int main()
{
glutInit(&argc, argv);
Init();
glutDisplayFunc(Display);
glutKeyboardFunc(Keyboard);
glutMouseFunc(Mouse);
glutIdleFunc(Idle);
glutMainLoop();
}
Least mixing of codes between Proj1 & Proj2 is requested.
Is it possible to do something like:
/**** Proj1 ****/
#include <filesFromProj2>
int main()
{
while(ESC key not pressed)
{
// read data file
// do some processing
proj2.showResult(result) // how to do this ?
}
}
The most simple solution would be to ditch GLUT and use a OpenGL windowing framework that lets you implement the event loop. GLFW would be the immediate choice. Then instead of having an opaque glutMainLoop that never returns you instead call glfwPollEvents beside your your stdio processing.
GLUT decouples your event handling code from your display code. It feels strange if you're used to the paradigm where you have full control over the loop, but it's not really hard to deal with. Basically, you need to maintain a state that your glutDisplayFunc will react to, and update that state in your glutKeyboardFunc. So in pseudocode (it seems like you have the C++ down):
displayFunc:
if state.showProj1
proj1.showResult
else if state.showProj2
proj2.showResult
keyboardFunc
if keyPressed(esc)
state.showProj1 = false
state.showProj2 = true
glutPostRedisplay()
Ok, so that is some pretty naive code there, but it should get the idea of how to make changes to your state in response to user input which in turn affects what you are rendering.
As mentioned in the previous answer, if you want explicit control of the program loop (as opposed to the event-based paradigm), you have some good options in GLFW and SDL, but of course there will be some ramp-up with those since GLUT does things in a pretty different way.
Found a solution so answering it myself for everyone's reference:
I desperately needed a workaround without having to change my existing glut base code into GLFW and SDF etc.
Digging more on internet I found that freeglut supports a function glutMainLoopEvent() that "causes freeglut to process one iteration’s worth of events in its event loop. This allows the application to control its own event loop and still use the freeglut windowing system."
Also, freeglut supported all the functions of glut (or atleast supported all the glut functions used in my prog). So,i didn't have to change my glut base code.
The pseudo-code for the workaround is as below. I welcome your comments.
#include <gl/freeglut.h>
#include <filesFromProj2>
int main()
{
glutInit(&argc, argv);
Init();
glutDisplayFunc(Display);
glutKeyboardFunc(Keyboard);
glutMouseFunc(Mouse);
glutIdleFunc(Idle);
// glutMainLoop(); // Do not use this
while(ESC key not pressed)
{
// read data file
// do some processing
proj2.showresults(results)
glutMainLoopEvent(); // One iteration only
Display(); // Call the func used with glutDisplayFunc()
}
glutLeaveMainLoop();
}
I also thought that multi-threading, may also solve this problem. One thread for glutMainLoop() and another for data processing !!

How can I initialize glut without the main line arugments?

In c++, we are used to see that opengl is installed in main function.Such as-
int main(int argv,char **argc){
glutInit(&argv,argc);
glutInitDisplayMode(GLUT_DOUBLE| GLUT_RGB|GLUT_DEPTH);
..............................
}
But without this main function,how can we declare opengl in other sub functions?
Such as-
int main(){
...........}
int installopengl(int argv,char **argc){
glutInit(&argv,argc);
glutInitDisplayMode(GLUT_DOUBLE| GLUT_RGB|GLUT_DEPTH);
..............................
}
Maybe I misunderstood - why cant you directly call the function like below ?
int main(int argv,char **argc) {
installopengl(argv, argc);
...........
}
int installopengl(int argv,char **argc) {
glutInit(&argv,argc);
glutInitDisplayMode(GLUT_DOUBLE| GLUT_RGB|GLUT_DEPTH);
..............................
}
Please get your terminology right. OpenGL is not installed in a program. It get's initialized.
Also the pattern you quoted is GLUT initialization. GLUT is not OpenGL, but a simple windowing framework, that creates a OpenGL context for you to use to draw to the window. But there are several other frameworks as well.
Then you seem to completely misunderstand what the main function does. main is the program entry point, the very first function that gets called in a process after the runtime environment has been set up. main can call any function, and you can simply call a dedicated framework initialization there. If it needs parameters from main you simply pass them along.
While it is defiantly not recommended, you can always do this:
int i = 0;
glutInit(&i, NULL);
The issue with doing it this way is that you won't be able to pass any information to the glut library from the command line.

Simple sound (.wav) playing application in QT (C++)

I am new to Qt and was trying to write a simple qt class that can plan a wav file.
After some reading and looking around I wrote the class and the code is as below. Questions follow after code
#include <QtGui/QApplication>
#include "playsound.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
playSound w;
int ch = 2;
int ready = 1;
cout<<"ready"<<ready<<endl;
// w.show();
w.playwav(ch);
return a.exec();
}
Source code for playsound.cpp
#include "playsound.h"
playSound::playSound(QWidget *parent): QWidget(parent) {}
playSound::~playSound() {}
void playSound::playwav(int ch)
{
switch (ch)
{
case 1: {QSound::play("/home/alok/qtworkspace/sounds/abc.wav"); break;}
case 2: {QSound::play("/home/alok/qtworkspace/sounds/xyz.wav"); break;}
case 3: {QSound::play("/home/alok/qtworkspace/sounds/abc.wav"); break;}
case 4: {QSound::play("/home/alok/qtworkspace/sounds/aaa.wav"); break;}
case 5: {QSound::play("/home/alok/qtworkspace/sounds/nnn.wav"); break;}
}
}
Problems and questions:
1) I want to close the application once the sound is played.As of now it says program running and I have to forcefully close it using the red button in the "Application Output" area in Qt creator. I tried using close() from Qwidget and quit() from QApplication but probably I am doing it wrong. How to go abt this?
2) Can there be a simpler implementation for this functionality? You know something that does not involve event loops. I was trying to do it in old school C++ style where I call a function when I need to play a sound and be done with it but could not get it done. Suggestions most welcome on this one.
Thanks
I can offer an answer using PyQt4 (since I'm a python coder), but the idea is the same.
1) QSound is a very basic interface for playing sounds. It doesn't have any useful signals (though I think it really should). In order to know when the QSound is complete, you have to keep checking its isFinished() method. You could either do this in a loop in your main thread, or get more advanced and create a QThread which will play your sound, go into the loop, and then emit its own custom signal when its complete. The QThread is preferred because you should never block your main thread. You would then be able to connect this custom soundIsFinished() SIGNAL to say the close() SLOT of your widget, or any other handler.
If you want more advanced options, you can use the phonon module, which does have all of these various signals built in. Its a litte more annoying to set up, but then you won't need a QThread.
2) Event loops are the core concept of how Qt functions. Your main application always enters an event loop so that widgets can post their events and have them processed. You could technically use Qt without an event loop, but then its really pointless because you are just fighting against the framework and losing everything that its capable of.
To exit from an application, you have to close the top level widget (if you're App has the property verbosely named quitOnLastWindowClosed set to true, but this is default so you don't have to worry with it) or emit a quit signal to the QCoreApplication you've created.
In the example below, I've taken the easy way: emit a close signal.
As stated by jdi, it would be better to create a Thread, but I've understood that you're only learning Qt and wrote this as an example, so busy waiting for isFinished is good enough. Below an example of how it should go:
#include "playsound.h"
playSound::playSound(QWidget *parent): QWidget(parent) {}
playSound::~playSound() {}
void playSound::playwav(int ch)
{
QSound *player = 0; // Creates an object so that you can call player.isFinished()
// the isFinished function is not static.
switch (ch)
{
case 1: {player = new QSound("/home/alok/qtworkspace/sounds/abc.wav"); break;}
// other cases
}
if(!player)
this->close();
while(!player->isFinished()); // waits until the player has finished playing
delete player;
this->close(); // closes this widget, and
// as this Widget has no parent, i.e. it's the "top-level" widget,
// it'll close the app.
}
edit: Shame on me for not reading the docs how I should have. QSound does not have a default constructor, I've edited the code.
A few notes: as this is only a test for you to learn how to use Qt, I've created a pointer to QSound and deleted it afterward. This is not a good approach, you should not play with pointers as I did there, a much better solution would be only instantiating the object you would use. Having to delete things manually is not good, and it's really better to rely on the good ol' stack for that.

Best Way C++ Eventing Handling on iPhone and other mobile devices

I am writing a C++ library that will need to do some eventing handling. I intend to call this in and Android environment using JNI, and I also intend to call it from a iPhone application as well. So I want to know the best C++ library or solution for event handling? I want MIT or BSD type license. Or maybe I could write it in objective C and distribute on both types of devices? I don't have a mac so no XCode right now. I need a simple solution, no threading issues, and no GPL etc licenses.Or is there a way to do this in Native C++ easily without a library. I am looking for recommendations on this. One thing it will probably also do is connect to SQLite. Thanks
You can cook up something extremely simple using std::tr1::function. An event could just be a function wrapper:
#include <tr1/functional>
typedef std::tr1::function<void ()> event;
void my_event_handler()
{
// handler code here
}
class C {
public:
void my_method_handler()
{
// handler code here
}
};
int main(int argc, char* argv[])
{
event ev;
ev = &::handler; // assign an event handler
ev(); // fire an event
// same thing, but using a method as a handler
C c;
ev = std::tr1::bind(&C::my_method_handler, &c);
ev();
}
The code above is very portable, I run something like this on iOS, Android, OSX, Windows and cygwin.