glutWarpPointer crash - c++

I'm following these tutorials on modern OpenGL. I've done them up to number 15 "Camera Control - Part 2". The tutorial suggests using glutWarpPointer(). The problem is, my program crashes at that call. This is my code:
c_camera::c_camera(int width, int height, const c_vector3f& Pos, const c_vector3f& Target, const c_vector3f& Up){
m_windowWidth = width;
m_windowHeight = height;
m_pos = Pos;
m_target = Target;
m_target.Normalize();
m_up = Up;
m_up.Normalize();
Init();
}
void c_camera::Init(){
c_vector3f HTarget(m_target.x, 0.0, m_target.z);
HTarget.Normalize();
if (HTarget.z >= 0.0f){
if (HTarget.x >= 0.0f){
m_AngleH = 360.0f - (asin(HTarget.z) TO_DEG);
} else {
m_AngleH = 180.0f + (asin(HTarget.z) TO_DEG);
}
} else {
if (HTarget.x >= 0.0f){
m_AngleH = (asin(-HTarget.z) TO_DEG);
} else {
m_AngleH = 90.0f + (asin(-HTarget.z) TO_DEG);
}
}
m_AngleV = -(asin(m_target.y) TO_DEG);
m_OnUpperEdge = false;
m_OnLowerEdge = false;
m_OnLeftEdge = false;
m_OnRightEdge = false;
m_mousePos.x = m_windowWidth / 2;
m_mousePos.y = m_windowHeight / 2;
cout << "this gets printed just fine" << endl;
glutWarpPointer(500,400); //program crashes
cout << "this doesn't get printed" << endl;
}
I'm not sure if I'm doing something weird here, or if I just have a bad glut version (seems unlikely to me) or if the tutorial is just wrong... Do I need to set up something glut specific before I can call glutWarpPointer()? I am new to glut, and new to modern OpenGL (I learned immediate mode first).
A quick google search didn't help me much. Any help would be appreciated.
Edit: I am on windows, and I'm using mingw 4.5
Edit2: These are the details windows gives me about the crash:
Problem Event Name: APPCRASH
Application Name: modern_opengl.exe
Application Version: 0.0.0.0
Application Timestamp: 51044575
Fault Module Name: glut32.dll
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 3bea4ff3
Exception Code: c0000005
Exception Offset: 0000a879
OS Version: 6.2.9200.2.0.0.256.48
Locale ID: 1043
Additional Information 1: 5861
Additional Information 2: 5861822e1919d7c014bbb064c64908b2
Additional Information 3: f3d5
Additional Information 4: f3d5be0cad2787556264647dc02181c3
Edit3: This is my call stack:
0 1000A879 glutWarpPointer() (C:\Windows\system\glut32.dll:??)
1 004033FB c_camera::Init(this=0x4aa0e0) (C:\CodeBlocks\projects\modern_opengl\c_camera.cpp:50)
2 00403164 c_camera::c_camera(this=0x4aa0e0, width=800, height=600, Pos=..., Target=..., Up=...) (C:\CodeBlocks\projects\modern_opengl\c_camera.cpp:18)
3 00402F4B __static_initialization_and_destruction_0(__initialize_p=1, __priority=65535) (C:\CodeBlocks\projects\modern_opengl\main.cpp:55)
4 00403004 GLOBAL_sub_I_vertices() (C:\CodeBlocks\projects\modern_opengl\main.cpp:177)
5 0043595B __do_global_ctors() (../mingw/gccmain.c:59)
6 00401098 __mingw_CRTStartup() (../mingw/crt1.c:236)
7 00401284 mainCRTStartup() (../mingw/crt1.c:264)

Your function seems to be in c_camera::Init, which seems to be called before main probably due to it being instantiated as a global object (globals are constructed before main is entered). You should delay glut calls till after you enter main and called glutInit is called.

Related

ImGui sample code/basic initialisation not working (Windows and Linux)

I am trying to setup ImGui to make some apps in, however I can't get it working. I installed the .h and .cpp files from the GitHub, https://github.com/ocornut/imgui, and followed the instructions to allow the project to compile, which it does. But on Windows and Linux (i've tried both), it spits out a runtime error, (stopped responding Windows, segmentation fault (core dumped) Linux). This is the sample code that was published,
#include "imgui.h"
int main()
{
// Create a window called "My First Tool", with a menu bar.
ImGui::Begin("My First Tool", &my_tool_active, ImGuiWindowFlags_MenuBar);
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Open..", "Ctrl+O")) { /* Do stuff */ }
if (ImGui::MenuItem("Save", "Ctrl+S")) { /* Do stuff */ }
if (ImGui::MenuItem("Close", "Ctrl+W")) { my_tool_active = false; }
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
// Edit a color (stored as ~4 floats)
ImGui::ColorEdit4("Color", my_color);
// Plot some values
const float my_values[] = { 0.2f, 0.1f, 1.0f, 0.5f, 0.9f, 2.2f };
ImGui::PlotLines("Frame Times", my_values, IM_ARRAYSIZE(my_values));
// Display contents in a scrolling region
ImGui::TextColored(ImVec4(1,1,0,1), "Important Stuff");
ImGui::BeginChild("Scrolling");
for (int n = 0; n < 50; n++)
ImGui::Text("%04d: Some text", n);
ImGui::EndChild();
ImGui::End();
return 0;
}
Now this code doesn't compile due to my_tool_active and my_color, so I added these 2 lines to the code before the ImGui::Begin():
bool my_tool_active = true;
float my_color[4] = {0.5, 0.5, 0.5, 1};
So now when I compile and run, it gets to the ImGui::Begin() and then crashes at that stage. I have tried it in a much smaller example where it is just the ImGui::Begin() and ImGui::End() and placed print statements around it, and it showed that it never finished executing the Begin().
Imgui doesn't provide a graphics backend, neither it creates a window or a graphics API context. You have to provide it by yourself (using OpenGL/DirectX/Vulkan ecc...) or use a library that creates one for you (SDL/glfw ecc...).
Refer to the sample directory to a more complete sample.
This one is using sdl+openGl.
https://github.com/ocornut/imgui/blob/master/examples/example_sdl_opengl3/main.cpp

How to use QueryPerformanceCounter to test performance of existing code?

I have an existing project in Visual Studio, with a main file that calls a function file. I also created a CodeTimer.cpp following the steps from the Microsoft guide, and I placed it along with the necessary headers in the same directory as my code and function.
The issue is, I don't know how to link them. The solution builds fine, all three files combine with no errors. But when I CTRL-F5 it, I just see the output of my main, for obvious reasons (I didn't link the CodeTimer to the main).
This is my CodeTimer:
#include "stdafx.h"
#include <tchar.h>
#include <windows.h>
using namespace System;
int _tmain(int argc, _TCHAR* argv[])
{
__int64 ctr1 = 0, ctr2 = 0, freq = 0;
int acc = 0, i = 0;
// Start timing the code.
if (QueryPerformanceCounter((LARGE_INTEGER *)&ctr1) != 0)
{
// Code segment is being timed.
for (i = 0; i<100; i++) acc++;
// Finish timing the code.
QueryPerformanceCounter((LARGE_INTEGER *)&ctr2);
Console::WriteLine("Start Value: {0}", ctr1.ToString());
Console::WriteLine("End Value: {0}", ctr2.ToString());
QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
Console::WriteLine("QueryPerformanceFrequency : {0} per Seconds.", freq.ToString());
Console::WriteLine("QueryPerformanceCounter minimum resolution: 1/{0} Seconds.", freq.ToString());
Console::WriteLine("ctr2 - ctr1: {0} counts.", ((ctr2 - ctr1) * 1.0 / 1.0).ToString());
Console::WriteLine("65536 Increments by 1 computation time: {0} seconds.", ((ctr2 - ctr1) * 1.0 / freq).ToString());
}
else
{
DWORD dwError = GetLastError();
Console::WriteLine("Error value = {0}", dwError.ToString());
}
// Make the console window wait.
Console::WriteLine();
Console::Write("Press ENTER to finish.");
Console::Read();
return 0;
}
NVM fixed it. Just had to add the body of _tmain() in main() function under my code, and get ride of the CodeTimer.cpp file completely. It was a conflict of mains (multiple mains in one project, the compiler automatically outputted the one with the highest priority in the project).

Abort() error encountered when adding points from input PointCloud to OctreePointCloud in PCL

I've encountered an error I'm having some difficulty solving in my current PCL c++ program. My original code is much larger and part of a classification project so I have tested using the following code and am still encountering my issue. When calling addPointsFromInputCloud() from my octree the function is running once for the first point, then appears to be unable to read the memory in which the defined input cloud is located. It throws the following error: R6010 - abort() has been called. I'm using PCL 1.8 with Visual Studio 2012. I have had PCL up and running in this project but started to have this issue yesterday after changing some binary reading code in an unrelated part of the project. In my header file I include:
#include <pcl\point_types.h>
#include <pcl\point_cloud.h>
#include <pcl\octree\octree.h>
In my function in the corresponding class I attempt to implement the code from the basic PCL octree tutorial (http://www.pointclouds.org/documentation/tutorials/octree.php):
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
// Generate pointcloud data
cloud->width = 1000;
cloud->height = 1;
cloud->points.resize (cloud->width * cloud->height);
for (size_t i = 0; i < cloud->points.size (); ++i) {
cloud->points[i].x = 1024.0f * rand () / (RAND_MAX + 1.0f);
cloud->points[i].y = 1024.0f * rand () / (RAND_MAX + 1.0f);
cloud->points[i].z = 1024.0f * rand () / (RAND_MAX + 1.0f);
}
float resolution = 128.0f;
pcl::octree::OctreePointCloudSearch<pcl::PointXYZ> octree (resolution);
octree.setInputCloud(cloud);
octree.addPointsFromInputCloud();
This throws the error above when attempting to execute the final line.
This is the code from octree_poointcloud.hpp wherein the failure occurs:
//////////////////////////////////////////////////////////////////////////////////////////////
template<typename PointT, typename LeafContainerT, typename BranchContainerT, typename OctreeT> void
pcl::octree::OctreePointCloud<PointT, LeafContainerT, BranchContainerT, OctreeT>::addPointsFromInputCloud ()
{
size_t i;
if (indices_)
{
for (std::vector<int>::const_iterator current = indices_->begin (); current != indices_->end (); ++current)
{
assert( (*current>=0) && (*current < static_cast<int> (input_->points.size ())));
if (isFinite (input_->points[*current]))
{
// add points to octree
this->addPointIdx (*current);
}
}
}
else
{
for (i = 0; i < input_->points.size (); i++)
{
if (isFinite (input_->points[i]))
{
// add points to octree
this->addPointIdx (static_cast<unsigned int> (i));
}
}
}
}
The first execution of the loop under the else statement is successful but it then appears to be unable to read from _input and errors.
Answered my own question and figured I'd let everyone know what my issue was. In the reading section of my program I had altered the packing to ensure there was no padding when I was casting the read bytes to my struct. Simply changing '#pragma pack(1)' to #pragma pack(push,1) before the declaration of my struct and '#pragma pack(pop)' after the declaration brought PCL back to life. Of course that wasn't until recompiling PCL from scratch...lesson learned though!

Unresolved Externals in Irrlicht

I am currently coding in Visual Studio 2010, using C++ and the Irrlicht game engine. I have tried asking this question on their forum, however I haven't had any response.
I am using the tutorials on the Irrlicht website:
http://irrlicht.sourceforge.net/docu/example002.html
The error I am getting is: "unresolved external symbol _imp_createDevice referenced in function _main"
I have added linked the Irrlicht library and include files already, but I am still getting this error.
// Tutorial2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <irrlicht.h>
#include <iostream>
using namespace irr;
#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif
int main()
{
// ask user for driver
video::E_DRIVER_TYPE driverType;
printf("Please select the driver you want for this example:\n"\
" (a) OpenGL 1.5\n (b) Direct3D 9.0c\n (c) Direct3D 8.1\n"\
" (d) Burning's Software Renderer\n (e) Software Renderer\n"\
" (f) NullDevice\n (otherKey) exit\n\n");
char i;
std::cin >> i;
switch(i)
{
case 'a':driverType = video::EDT_OPENGL; break;
case 'b':driverType = video::EDT_DIRECT3D9; break;
case 'c':driverType = video::EDT_DIRECT3D8; break;
case 'd':driverType = video::EDT_BURNINGSVIDEO; break;
case 'e':driverType = video::EDT_SOFTWARE; break;
case 'f':driverType = video::EDT_NULL; break;
default: return 1;
}
// create device and exit if creation failed
IrrlichtDevice *device =
createDevice(driverType, core::dimension2d<u32>(640, 480));
if (device == 0)
return 1; // could not create selected driver.
video::IVideoDriver* driver = device->getVideoDriver();
scene::ISceneManager* smgr = device->getSceneManager();
device->getFileSystem()->addFileArchive("../../media/map-20kdm2.pk3");
scene::IAnimatedMesh* mesh = smgr->getMesh("20kdm2.bsp");
scene::ISceneNode* node = 0;
if (mesh)
node = smgr->addOctreeSceneNode(mesh->getMesh(0), 0, -1, 1024);
// node = smgr->addmeshSceneNode(mesh->getMesh(0));
if (node)
node->setPosition(core::vector3df(-1300,-144,-1249));
smgr->addCameraSceneNodeFPS();
device->getCursorControl()->setVisible(false);
int lastFPS = -1;
while(device->run())
{
if(device->isWindowActive())
{
driver->beginScene(true, true, video::SColor(255, 200, 200, 200));
smgr->drawAll();
driver->endScene();
int fps = driver->getFPS();
if (lastFPS != fps)
{
core::stringw str = L"Irrlicht Engine - Quake 3 Map example[";
str += driver->getName();
str += "] FPS:";
str += fps;
device->setWindowCaption(str.c_str());
lastFPS = fps;
}
}
else
device->yield();
}
device->drop();
return 0;
}
I've managed to build the sample, no problem.
The only way to get your error is to mix the 32 and 64bit lib files.
Rename the 64bit library Irrlicht_x64.lib and try building again.

SDL Video Init causes Exception on Mac OS X 10.8

I have just ported my C++ game to OS X and the first time it ran I get the following exception when trying to call SDL_SetVideoMode.
2012-09-28 15:01:05.437 SCRAsteroids[28595:707] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error (1000) creating CGSWindow on line 259'
* First throw call stack:
(
0 CoreFoundation 0x00007fff8b53b716 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff90e30470 objc_exception_throw + 43
2 CoreFoundation 0x00007fff8b53b4ec +[NSException raise:format:] + 204
3 AppKit 0x00007fff8a26a579 _NSCreateWindowWithOpaqueShape2 + 655
4 AppKit 0x00007fff8a268d70 -[NSWindow _commonAwake] + 2002
5 AppKit 0x00007fff8a2277e2 -[NSWindow _commonInitFrame:styleMask:backing:defer:] + 1763
6 AppKit 0x00007fff8a22692f -[NSWindow _initContent:styleMask:backing:defer:contentView:] + 1568
7 AppKit 0x00007fff8a2262ff -[NSWindow initWithContentRect:styleMask:backing:defer:] + 45
8 libSDL-1.2.0.dylib 0x0000000107c228f6 -[SDL_QuartzWindow initWithContentRect:styleMask:backing:defer:] + 294
9 libSDL-1.2.0.dylib 0x0000000107c20505 QZ_SetVideoMode + 2837
10 libSDL-1.2.0.dylib 0x0000000107c17af5 SDL_SetVideoMode + 917
11 SCRAsteroids 0x0000000107be60fb _ZN11SDLGraphics4initEP6IWorldii + 291
)
libc++abi.dylib: terminate called throwing an exception
Abort trap: 6
My init code looks like this:
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
return false;
const SDL_VideoInfo *videoInfo = SDL_GetVideoInfo();
if (!videoInfo) {
fprintf(stderr, "Video query failed: %s\n",
SDL_GetError());
return false;
}
/* the flags to pass to SDL_SetVideoMode */
videoFlags = SDL_OPENGL; /* Enable OpenGL in SDL */
videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */
videoFlags |= SDL_HWPALETTE; /* Store the palette in hardware */
/* This checks to see if surfaces can be stored in memory */
if (videoInfo->hw_available)
videoFlags |= SDL_HWSURFACE;
else
videoFlags |= SDL_SWSURFACE;
if (w == 0) {
widthViewport = videoInfo->current_w;
heightViewport = videoInfo->current_h;
cout << "Will use full screen resolution of ";
videoFlags |= SDL_FULLSCREEN;
} else {
cout << "Will use full user supplied resolution of ";
widthViewport = w;
heightViewport = h;
videoFlags |= SDL_RESIZABLE; /* Enable window resizing */
}
cout << widthViewport << "x" << heightViewport << "\n";
/* This checks if hardware blits can be done */
if (videoInfo->blit_hw)
videoFlags |= SDL_HWACCEL;
/* Sets up OpenGL double buffering */
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
/* get a SDL surface */
surface = SDL_SetVideoMode(widthViewport, heightViewport,
SCREEN_BPP, videoFlags);
It gets into that last SDL call and throws the exception above. I have tried it in both full screen and resizable window mode, same thing.
I build my app old school, on the command line, as opposed to using Xcode.
SDL_main was yet again the culprit. My C++ main routine was in a file that does not include SDL.h, so it was not being redefined to SDL_main. The code that includes SDL is instead in a reusable static library, no main routine you see. I manually changed the name of my function to SDL_main and this means that SDL provides the essential main routine. I don't like doing this, but for the moment, on SDL 1.2.15 for Mac, it is necessary.
On Windows, the same new code causes linker conflicts. That's a new problem.
There are problems with calling the videocard in cocoa. So you need to initalize it before calling SDL_Setvideomode
Add the following method, and call it first in your main method
#include <dlfcn.h> //To make it work on mac
//This must be called before playing with SDL, else it won't work on osx.
void pre_init()
{
void* cocoa_lib;
cocoa_lib = dlopen( "/System/Library/Frameworks/Cocoa.framework/Cocoa", RTLD_LAZY );
void (*nsappload)(void);
nsappload = (void(*)()) dlsym( cocoa_lib, "NSApplicationLoad");
nsappload();
}
`
Same issue, but solved by linking libSDLmain (as well as libSDL). This in turn requires two frameworks: Foundation and Cocoa.
I didn't rename the main function.