std::cerr can't print float variable - c++

I am writing a program that is supposed to operate with matrices and to use OpenGL framework for drawing them. Honestly, it's just for practice. Anyway, I tried to compile it and, of course, it didn't run well. Inserting as many logging as I could, I found out that my std::cerr can't print float values. I really got no idea how that may stop working. I have made some deep researches on my little code like replacing variables with their values, coding external programs using same functions and so on; and found even more unbelievable thing that there's absolutely no reason for this.
Useful details
OS X 10.9.
No bugs regarding to precompilation may occur other than ones caused by #pragma once.
Compiler
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn).
g++ -std=c++11 -framework OpenGL -framework GLUT
main.cpp
#include <GLUT/glut.h>
#include <cstdlib>
#include "Window.hpp"
Window *black_screen;
void Display () { black_screen->Display (); }
void Reshape (int NEW_WIDTH, int NEW_HEIGHT) { black_screen->Reshape (NEW_WIDTH, NEW_HEIGHT); }
void Keyboard (unsigned char key, int x, int y) { black_screen->Keyboard (key, x, y); }
void Special (int key, int x, int y) { black_screen->Special (key, x, y); }
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
Window *black_screen = new Window(800, 800);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glutDisplayFunc ( Display );
glutReshapeFunc ( Reshape );
glutKeyboardFunc ( Keyboard );
glutSpecialFunc ( Special );
black_screen->AddMatrix(Matrix(5));
Display();
glutMainLoop();
}
WINDOW.hpp
#pragma once
#include <GLUT/glut.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include "Matrix.hpp"
class Window {
std::vector <Matrix> matrices_;
float WIDTH_, HEIGHT_,
SIZE_X_, SIZE_Y_;
const char *NAME_;
public:
Window (const float WIDTH, const float HEIGHT);
private:
void Type (const float x, const float y, const char *string) const;
public:
void AddMatrix (const Matrix &A);
void Write (const std::string &message);
void Display ();
void Reshape (int NEW_WIDTH, int NEW_HEIGHT);
void Keyboard (unsigned char key, int x, int y);
void Special (int key, int x, int y);
};
WINDOW.cpp
// --- THIS IS CONSTRUCTOR --- --- --- --- ---
Window::Window (const float WIDTH, const float HEIGHT) :
WIDTH_(WIDTH), HEIGHT_(HEIGHT),
SIZE_X_(800), SIZE_Y_(800),
NAME_("MATRIX") {
...
}
// --- THIS IS DISPLAY FUNCTION CALLED FROM MAIN::Display() ---
void Window::Display () {
glLoadIdentity(); Write("glLoadIdentity();");
glClear(GL_COLOR_BUFFER_BIT); Write("glClear(GL_COLOR_BUFFER_BIT);");
glMatrixMode(GL_PROJECTION); Write("glMatrixMode(GL_PROJECTION);");
Write("\tNOW i WILL TRY TO OUTPUT HEIGHT_ :");
std::cerr << HEIGHT_ << std::endl;
glOrtho(0, WIDTH_, 0, HEIGHT_, 1, -1); //Write("glOrtho(0, WIDTH_, 0, HEIGHT_, 1, -1);");
...
}
output
[ glutInitWindowSize(SIZE_X_, SIZE_Y_); :
[ SIZE_X_ 800.000000
[ SIZE_Y_ 800.000000
[ glutCreateWindow(NAME_); :
[ NAME_ MATRIX
[ glLoadIdentity();
[ glClear(GL_COLOR_BUFFER_BIT);
[ glMatrixMode(GL_PROJECTION);
[ NOW i WILL TRY TO OUTPUT HEIGHT_ :
make: *** [run] Segmentation fault: 11

You don't show this in the code posted, but it appears you have two different definitions for black_screen, one global and one inside the main function. The one inside main has been initialized properly, but the global one is a bad pointer. The segmentation fault is the result of undefined behavior from dereferencing the bad pointer.

Related

FLTK flickering animation

I'm trying to make a simple animation using FLTK(a circle with increasing and decreasing radius). I've managed to write a simple program that seems to work, but the animation flickers. The circle disappears for a couple of milliseconds and then gets back. I've changed Fl_Window class to Fl_Double_Window, but that didn't fix this problem.
class Painting : public Fl_Widget {
public:
Painting(int x, int y, int w, int h) : Fl_Widget(x, y, w, h, 0) {}
private:
void draw()
{
static double inc = 0;
inc += 0.2;
double radius = 50 + 10*sin(inc);
fl_begin_polygon();
fl_arc(100, 100, radius, 0, 360);
fl_end_polygon();
}
};
void redraw_cb(void *data)
{
Fl_Widget *w = (Fl_Widget*)data;
w->redraw();
Fl::repeat_timeout(0.01, redraw_cb, data);
}
int main(int argc, char **argv)
{
Fl_Double_Window *win = new Fl_Double_Window(1000, 500, "hello");
Painting *painting = new Painting(0, 0, 1000, 500);
Fl::add_timeout(1, redraw_cb, painting);
Fl::visual(FL_DOUBLE|FL_INDEX);
win->resizable(painting);
win->end();
win->show();
return Fl::run();
}

Visual Studio Dynamic Library: OpenGL don't create window

I have a problem. I decided to make an interface so that I can override functions for OpenGL, DirectX and so on ..
The problem is that opengl window is not being created in my dynamic project. But when I create a window without a dynamic library, then the window is created without problems.
Why, when I try to create a window through a dynamic library, it is not created?
Below I will briefly provide the project structure
My visual studio solution consists of two projects: GLRenderSystem and MeshEditor
GLRenderSystem - dynamic library. Here I have two classes declared, GLRenderSystem.h, GLWindow.h which will inherit from the IRenderSystem and IWindow interfaces:
GLWindow.h:
#pragma once
#ifndef _GL_WINDOW_
#define _GL_WINDOW_
#include "../Interfaces/IWindow.h"
#include <glfw\glfw3.h>
class GLWindow : public IWindow
{
public:
GLWindow(const std::string& title, uint32_t width, uint32_t height);// Window is not creating.
~GLWindow();
uint32_t getWidth() const;
uint32_t getHeight() const;
GLFWwindow* getGLFWHandle() const;
private:
GLFWwindow* glfwHandle;
};
#endif
GLWindow.cpp:
#include "pch.h"
#include "GLWindow.h"
#include<iostream>
GLWindow::GLWindow(const std::string & title, uint32_t width, uint32_t height)
{
glfwHandle = glfwCreateWindow(width, height, title.data(), nullptr, nullptr); // ALWAYS NULL POINTER RETURNS
glfwMakeContextCurrent(glfwHandle);
static bool initGLAD = false;
if (!initGLAD)
{
initGLAD = true;
gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
}
......
Also Exports.h and Exports.cpp with functions neede to create IRenderSystem and IWindow in the main MeshEditor
Exports.h:
#pragma once
#include <string>
#ifdef OGL_RENDER_SYSTEM_EXPORT
#define OGL_RENDER_SYSTEM_API __declspec(dllexport)
#else
#define OGL_RENDER_SYSTEM_API __declspec(dllimport)
#endif
class IRenderSystem;
class IWindow;
extern "C" OGL_RENDER_SYSTEM_API IRenderSystem* createRenderSystem();
extern "C" OGL_RENDER_SYSTEM_API IWindow* createWindow(const std::string& title, uint32_t width, uint32_t height);
...
Exports.cpp:
#include "pch.h"
#include "Exports.h"
#include "GLWindow.h"
#include "GLRenderSystem.h"
#include<iostream>
OGL_RENDER_SYSTEM_API IRenderSystem * createRenderSystem()
{
return new GLRenderSystem;
}
OGL_RENDER_SYSTEM_API IWindow * createWindow(const std::string & title, uint32_t width, uint32_t height)
{
return new GLWindow(title, width, height);
}
...
And finally, the MeshEditor project, where from main.cpp I try to create a window using a dynamic library
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "../Interfaces/IWindow.h"
#include "../Interfaces/IRenderSystem.h"
#include "DynamicLibrary.h"
#include<iostream>
int main()
{
DynamicLibrary dll("GLRenderSystem.dll");
auto createRenderSystem = dll.getSymbol<IRenderSystem* (*)()>("createRenderSystem");
auto createWindow = dll.getSymbol<IWindow* (*)(const std::string& title, uint32_t width, uint32_t height)>("createWindow");
auto waitEvents = dll.getSymbol<void(*)()>("waitEvents");
auto swapDisplayBuffers = dll.getSymbol<void(*)(IWindow* window)>("swapDisplayBuffers");
auto windowShouldClose = dll.getSymbol<bool(*)(IWindow* window)>("windowShouldClose");
IRenderSystem* rs = createRenderSystem();
IWindow* window = createWindow("myWindow", 640, 480); // ALWAYS NULL POINTER RETURNS
rs->init();
rs->setupLight(0, glm::vec3{ 0,5,0 }, glm::vec3{ 1,0,0 }, glm::vec3{ 0,1,0 }, glm::vec3{ 0,0,1 });
rs->turnLight(0, true);
while (!windowShouldClose(window))
{
rs->setViewport(0, 0, window->getWidth(), window->getHeight());
rs->clearDisplay(0.5f, 0.5f, 0.5f);
renderScene(*rs);
swapDisplayBuffers(window);
waitEvents();
}
delete window;
delete rs;
return 0;
}
The problem is that the createWindow function in main.cpp always returns nullptr, that is, window is not created.

Ifstream doesn't work with OpenGL/freeglut

A program crashes if I try to use ifstream while having OpenGL/freeglut. My code:
#include <fstream>
#include <windows.h>
#include <GL/freeglut.h>
double x, y;
std::ifstream read("coordinates.txt");
void display() {
glBegin(GL_LINE_STRIP);
while (read >> x) //Crashes here
{
read >> y;
glVertex2d(x, y);
}
glEnd();
glFlush();
}
void key(unsigned char mychar, int x, int y) {
if (mychar == 27) {
exit(0);
}
}
void initialize()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-27, 27, -27, 27);
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowSize(1920, 1080);
glutInitWindowPosition(0, 0);
glutCreateWindow("Lorenz Attractor");
initialize();
glutDisplayFunc(display);
glutKeyboardFunc(key);
glColor3d(0, 0, 1);
glutFullScreen();
glutMainLoopEvent();
Sleep(60000);
}
coordinates.txt:
1.1 1.03
2.5 2
3 5.3
I don't even need to include freeglut, I checked out an older project that was working perfectly before and now it crashes as well. Using Code::Blocks with MinGW. Why would this happen? Thanks!
display will be called more than one time. It's called whenever the display needs to be redrawn, such as when the window comes into view, another window is moved over top of it, the window is resized, etc.
display reads a file. Well, after the first time it reads the file, the file will be empty. After all, you opened the file in a global variable (FYI: never do that), and you kept reading until the file was empty.
Don't read files while you're drawing. Read the file into a data structure (say, a vector<float>). Do that before the rendering loop. Then, use the data structure to draw from.

Sierpinski gasket

i was writing a code in C/C++ and i face an error .
#include "glut.h"
#include <random>
// Classes and structs //
struct GLPoint {
GLfloat x, y;
};
// Method(s) Declration //
void drawDot(GLfloat, GLfloat);
void serpinski_render(void);
void myInti(void);
// Method(s) Implementation //
void drawDot(GLfloat x, GLfloat y){
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
void serpinski_render(void)
{
glClear(GL_COLOR_BUFFER_BIT); // Clear the screen from anything is displayed on it
GLPoint T[3] = { { 10, 10 }, { 600, 10 }, { 300, 600 } }; // the three points of parent triangle
int index = rand() % 3; // this mean i will choose a random number between 0 , 3
GLPoint point = T[index];
drawDot(point.x, point.y);
for (unsigned int i = 0; i < 5500; i++) // a loop that going to run 5500 ( a very big number )
{
index = rand() % 3;
point.x = (point.x + T[index].x) / 2;
point.y = (point.y + T[index].y) / 2;
drawDot(point.x, point.y);
}
glFlush();
}
void myInti(void)
{
glClearColor(1, 1, 1, 0); // a white background
glColor3f(0, 0, 0); // black points
glPointSize(3); // 3 pixel point size
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 640, 0, 480);
}
// Main Method //
void main(int argc ,char ** argv )
{
glutInit(&argc, argv); // intilize toolkit
glutInitWindowPosition(100, 150);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640, 480); // windows size is 640 x 480
glutDisplayFunc(serpinski_render);
myInti();
glutMainLoop();
}
i dont know if it will work fine but this code should produce me Sierpinski triangle .
and i face every time i use C++ library in this case the random lib this problem in the stdlib.h making me confused never face something like it before
Error 1 error C2381: 'exit' : redefinition; __declspec(noreturn) differs c:\program files (x86)\microsoft visual studio 12.0\vc\include\stdlib.h 376
There is an incompatibility between glut.h and Visual Studio .NET, which is the usage of both "glut.h" and in your case.
You can solve it by just declaring:
#include <random>
#include "glut.h"
instead of:
#include "glut.h"
#include <random>
Please read this description for further information and for an another solution. ("Header (.h) files" section)
Also your code will possibly fail because of not creating window. You can use glutCreateWindow to create a window. You can also solve this issue by arranging your main like below:
void main(int argc ,char ** argv )
{
glutInit(&argc, argv); // intilize toolkit
glutInitWindowPosition(100, 150);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(640, 480); // windows size is 640 x 480
glutCreateWindow("A title");
myInti();
glutDisplayFunc(serpinski_render);
glutMainLoop();
}
Please also read this information for glutCreateWindow function.
You probably have this code in glut.h:
# ifndef GLUT_BUILDING_LIB
extern _CRTIMP void __cdecl exit(int);
# endif
The glut.h header is quite old. This was probably a workaround for an old VC deficiency. Visual C now seems to have a declaration that conflicts with this one. The easy solution is to just delete these lines from the header, since there is a valid definition in stdlib.h.
By the way, all the glVertex, glBegin, glEnd, matrix stack, and many other OpenGL calls are deprecated in favor of shaders.
Perhaps there is also a newer/better glut available. I'd check that out.

Can't draw in opengl in visual studio 2012

I am trying to figure out how to make opengl work in Windows 8.1 using Visual Studio 2012.
My program compiles and runs, but nothing happens in the windows which is created, I can't even change background color or see the mouse.
My program looks as follows:
main.cpp
#include <cstdio>
#include <iostream>
#include "simpleViewer.h"
using namespace std;
int main(int argc, char **argv){
simpleViewer Viewer;
Viewer.initOpenGL(argc, argv);
Viewer.run();
}
simpleViewer.h
#pragma once
#ifndef _SIMPLEVIEWER_H_
#define _SIMPLEVIEWER_H_
#include "GL\GL\glut.h"
#include <iostream>
enum DisplayModes {
DISPLAY_MODE_OVERLAY,
DISPLAY_MODE_DEPTH,
DISPLAY_MODE_IMAGE
};
class simpleViewer
{
public:
simpleViewer(void);
~simpleViewer(void);
virtual void run();
virtual void initOpenGL(int argc, char **argv);
virtual void initOpenGLHooks();
virtual void display();
virtual void displayPostDraw(){};
DisplayModes m_eViewState;
private:
static simpleViewer* ms_self;
static void glutIdle();
static void glutDisplay();
};
#endif
and simpleViewer.cpp
#include "simpleViewer.h"
#define GL_WIN_SIZE_X 1280
#define GL_WIN_SIZE_Y 1024
// Undeprecate CRT functions
#ifndef _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_DEPRECATE 1
#endif
simpleViewer* simpleViewer::ms_self;
simpleViewer::simpleViewer(void)
{
ms_self = this;
}
simpleViewer::~simpleViewer(void)
{
}
void simpleViewer::initOpenGL(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitWindowSize(GL_WIN_SIZE_X, GL_WIN_SIZE_Y);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow ("Test");
// glutFullScreen();
glutSetCursor(GLUT_CURSOR_NONE);
initOpenGLHooks();
glDisable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glClearColor(1.0f,0.0f,0.0f,1.0f);
}
void simpleViewer::initOpenGLHooks()
{
glutDisplayFunc(glutDisplay);
glutIdleFunc(glutIdle);
}
void simpleViewer::run(){
glutMainLoop();
}
void simpleViewer::display(){
glBegin(GL_TRIANGLES);
glColor3f(1.0,0,0);
glVertex3f(0.1,0,0);
glVertex3f(0,0,0);
glVertex3f(0,0,0.1);
glEnd();
glFlush();
}
void simpleViewer::glutIdle(){
glutPostRedisplay();
}
void simpleViewer::glutDisplay(){
simpleViewer::ms_self->display();
}
I have checked so that it really goes into display(), but nothing happens. The background is totally white even if it should be red.
You've requested double-buffering via GLUT_DOUBLE.
Use glutSwapBuffers() instead of glFlush() at the end of simpleViewer::display().
glClearColor() only latches some state. glClear() actually does the clear. Add a glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) at the top of simpleViewer::display().
That triangle is wonky for the default projection/modelview matrices. Try this instead:
glBegin( GL_TRIANGLES );
glVertex2i( 0, 0 );
glVertex2i( 1, 0 );
glVertex2i( 1, 1 );
glEnd();
You'll probably want to change the triangle color too. Red on red is pretty hard to see :)