Load OpenGL function pointers using glad withing a QOpenGLWidget - c++

So I am reading up on some OpenGL and I want to use the QOpenGLWidget for drawing to maybe create some other helpful UI elements later. I am using glad for resolving the function pointers to OpenGL but I have no idea how to use Qt's getProcAddress function!
Inside my QOpenGLWidget subclass' initializeGL() function I have tried:
if(gladLoadGLloader((GLADloadproc) currentContext()->getProcAddress) {}
but that did not work out since Qt's function is overloaded. When I use
if(gladLoadGL()) {}
it doesn't work either. My includes are:
#include <glad\glad.h>
#include "OpenGLViewport.h"
#include <QDebug>
#include <QOpenGLContext>
I have searched Mr. Google and I've had a diligent look through the Qt documentation and found nothing. I want to use GLAD just so my rendering code is not bound to Qt too tightly, in case I want to switch later.
EDIT: I am aiming to use the noninstanced OpenGL functions with Qt (though the documentation recommends otherwise if I recall correctly). Because then I'd be able to seemlessly switch to GLFW for providing a window etc.

Moved solution from question to answer:
ANSWER: So it turns out I just had some things mixed up, this is how I got it to work, in case anyone has the same problem:
add glad.c in your project
add the necessary headers to your include directory
the .cpp file of your QOpenGLWidget subclass should have following components:
// Subclass.cpp
#include <glad/glad.h>
// important, subclass header file after glad!!
// otherwise glad won't "hook"
#include "Subclass.h"
void Subclass::initializeGL()
{
if(gladLoadGL()) initialized = true; // initialized is a class member here
else; // handle errors
}
void Subclass::paintGL()
{
if(initialized); // render here
}

Related

Unable to compile Qt project using qlogvalueaxis.h

I am currently working on a C++ application for controlling an instrument. The instrument output should be displayed using a QChart. For the display I created a Qt user interface with a QChartView widget.
Here is the header file for the display class:
#pragma once
#include <QWidget>
#include "QtCharts\qchart.h"
#include <QtCharts\qchartview.h>
#include <QtCharts\qscatterseries.h>
#include <QtCharts\qlineseries.h>
#include "ui_ChartsDisplay.h"
#include <qthread.h>
using namespace QtCharts;
class ChartsDisplay : public QWidget
{
Q_OBJECT
public:
ChartsDisplay(QWidget *parent = Q_NULLPTR);
~ChartsDisplay();
private:
Ui::ChartsDisplay ui;
QLineSeries *trace,*retrace,*arbitrarySeriesX,*arbitrarySeriesY;
QChart *chart;
//QLogValueAxis *axisX, *axisY;
void rescaleChart();
public slots:
void SLUpdateChart(float *newValues);
void SLSetupChartDisplay(int type);
void SLResetChart();
void SLUpdateNoise(float** newValues, int size);
};
I need two instances of the ChartDisplay class. One with linear and one with logarithmmic scaling for displaying different data types.
I found a Qt tutorial on using logarithmic axis scaling here:
https://doc.qt.io/qt-5/qtcharts-logvalueaxis-example.html
However, once I include "qlogvalueaxis.h" my programm will no longer compile. I get a long list of syntax errors originating in "qlogvalueaxis.h".
I created a new Qt project and implemented a simple chart with logarithmic scaling using qlogvalueaxis which worked fine.
Also I cleaned the whole project and removed all qt generated files before compiling. The problem still remained.
All necessary libraries are linked and up to date as are the header files.
Some information about the environment:
-Visual Studio 2015, community edition
-Qt framework 5.8
-Operating system is Win 7
Any would appreciate any advice.
Best regards,
T. Krastev
I had a similar (or perhaps the same) problem. I got compile errors indicating that the min() and max() function prototypes were already declared elsewhere, so if this is the case for you simply omit the min and max macros by adding the following before including the QtCharts headers:
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif

Exit a gtkmm application properly

I am creating a GUI using Glade, and am able to connect signals to it properly. I am trying to have a button that simply quit the application.
The doc is not very clear on how to do so. On some forums you should do:
Gtk::Main::quit();
Which does exit my application, but with a Segmentation Fault. Apparently I am supposed to call quit() directly from my application, like so:
p_application->quit();
But this returns me the resulting error at compile time:
error: invalid use of member ‘GUI::p_application’ in static member function
Glib::RefPtr<Gtk::Application> p_application;
^
error: from this location
p_application->quit();
^
I created the application using this:
p_application = Gtk::Application::create(argc, argv, "org.app.app");
How should I proceed ?
It looks like you are trying to access the p_application member of your GUI class from a static member function of GUI.
You can't access members from static functions, since there is no instance. Change the function to not be static, or get hold of an instance and access the member on that.
Warning: All the online documentation I could find is for gtkmm-4. If you are stuck using gtkmm-3.0 for Ubuntu, download your own docs from the repository (see below). I've included links to gtkmm-4 documentation in the hopes that they are helpful; use at your own risk.
Here is a working solution for gtkmm-3.0. Compile with:
g++ helloworld.cc -o main `pkg-config --cflags --libs gtkmm-3.0`
Code:
// In file helloworld.cc
// sigc::mem_fun is the important part:
// it lets you turn a member function into a static one (or something).
// I don't really get it.
// I got most of the code here from https://www.gtk.org/docs/language-bindings/cpp
#include <iostream>
#include <sigc++/sigc++.h> // Unnecessary, because the gtkmm modules also include mem_fun.
#include <glibmm/refptr.h> // The wrapper object that Application::create returns.
#include <gtkmm/application.h> // C++ wrapper for C's gtk_main.
#include <gtkmm/button.h>
#include <gtkmm/window.h>
class HelloWorld : public Gtk::Window
{
public:
HelloWorld(Glib::RefPtr<Gtk::Application>);
protected:
void on_button_clicked();
Gtk::Button m_button;
Glib::RefPtr<Gtk::Application> app;
};
// Constructor for window class. app should be a pointer to the Application instance you made in main.
HelloWorld::HelloWorld(Glib::RefPtr<Gtk::Application> app)
: m_button("Quit this program") // Sets button label. I have no idea what this syntax is. C++ be whack, yo
{
this->app = app;
// mem_fun does most of the magic. How does it work? idk lol
m_button.signal_clicked().connect(sigc::mem_fun(*this,
&HelloWorld::on_button_clicked));
add(m_button);
m_button.show();
}
void HelloWorld::on_button_clicked()
{
std::cout << "Exiting the program now." << std::endl;
this->app->quit();
std::cout << "Note: Program doesn't actually end until this function finishes." << std::endl;
}
int main (int argc, char *argv[])
{
Glib::RefPtr<Gtk::Application> app = Gtk::Application::create(argc, argv, "org.gtkmm.example");
HelloWorld helloworld(app);
return app->run(helloworld);
}
My thoughts: I don't really get it?
Gtk::Button.signal_clicked() (reference) returns a Glib::SignalProxy<void()>. SignalProxy (reference) has template <R(T...)>, which I think describes the kind of functions that can be connected--in this case, with a return type void and an empty list () of arguments. SignalProxy.connect() returns something I'll ignore, and accepts either a SlotType& or a SlotType&& (I have no idea what the difference is) where SlotType is sigc::slot<R(T...)>, or in this case sigc::slot<void()>.
sigc::slot<R(T...)> (reference) seems pretty fundamental. It looks like it's just a wrapper that holds a function (presumably, so SignalProxy can store it to be called later when the button is clicked). Up until now, it all makes sense.
The notes on sigc::mem_fun (reference) say that it returns a sigc::mem_functor, which sounds reasonable but mem_functor does not seem to fulfill what SignalProxy.connect() wants: sigc::slot and sigc::mem_functor do not inherit from each other. Baffling. I guess there's some kind of undocumented type coercion going on here? Maybe? The other lead is that mem_fun apparently returns an object of type decltype(auto)? Which I tried reading documentation on, and then they started talking about lvalues and unparenthesized id-expressions, and that's when my eyes glazed over. Looking at the old documentation, there used to be like 70 overloaded versions of mem_fun to do what one version can do now, so I guess decltype is doing its job. But the point is, that's where I gave up.
decltype(auto) and mem_functors are C++ deep-magic. mem_fun does the thing SignalProxy.connect() needs, and that's all I know.
References:
gtkmm-4.0 documentation
glibmm documentation
sigc++ documentation
gdk documentation in c << gtkmm refers to stuff like "GdkEventKey" and enumerations from the header <gdk/gdkkeysyms.h>. I couldn't find a c++ reference for this, or anything like "gdkmm". I think maybe gtkmm just uses the C structs for events directly?
Installing documentation: I'm on Ubuntu, 20.04.3 LTS. You can install html documentation for gtk 3.0 from the repository. Do sudo apt install libgtkmm-3.0-doc libglibmm-2.4-doc libsigc++-2.0-doc. To find out where the index file is for, for example, gtkmm, do dpkg -L libgtkmm-3.0-doc | grep index. sigc++ has multiple index files, two of which are traps. I could not figure out where the documentation for GDK is, possibly because there isn't any in the repository. Use the online stuff instead.

AActor *UactorComponent::GetOwner const - pointer to incomplete class type is not allowed

I'm new to UE4 development and I've followed Udemy's Unreal Engine Development course. I have created a new Component on an Actor, named PositionReporter with header PositionReporter.h
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "PositionReporter.generated.h"
UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) )
class BUILDINGESCAPE_API UPositionReporter : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
UPositionReporter();
protected:
// Called when the game starts
virtual void BeginPlay() override;
public:
// Called every frame
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
};
and code in PositionReporter.cpp being
#include "PositionReporter.h"
// Sets default values for this component's properties
UPositionReporter::UPositionReporter()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = true;
// ...
}
// Called when the game starts
void UPositionReporter::BeginPlay()
{
Super::BeginPlay();
FString t = GetOwner()->GetActorLabel();
UE_LOG(LogTemp, Warning, TEXT("Position Reporter reporting for duty on %s"), *t);
}
// Called every frame
void UPositionReporter::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
As you can see, I am now trying to call the GetName function on the Pointer to the AActor retrieved through GetObject().
However, as soon as I type "GetObject()->" no autocomplete pops up (as it does in the video) and when I add "GetName()" manually, I get the compiler error "pointer to incomplete class type is not allowed".
What am doing wrong? Am I missing an import or so? I already compared my code to Ben's git repo but can't find any differences. I am on unreal editor 4.16.0!
I noticed another strange thing: When I compile everything from Unreal Engine Editor, it compiles and runs fine. But when I compile it with VS 2017 I get the error, and I also dont get the Autocomplete, which is a real bummer. What am I missing?
Including Engine.h on PositionReporter.h fixes the issue.
#pragma once
#include "Engine.h" // <- This
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "PositionReporter.generated.h"
You'll need to give Intellisense some time... As a matter of fact I closed and reopened the solution for it to stop showing the non existing errors and give autocomplete functionality.
NOTE: As is mentioned in other posts, this solution is good to get intellisense autocompleting but isn't the best as it will include a ton of stuff and greatly increase compilation times.
Including the specific .h file would be better, but you need to know what .h to include, and probably you don't know it.
Best solution I found is ditching Intellisense and use Resharper for code autocompletion, it works fast, autocompletes correctly and you don't need to include any extra file.
I would like to point out that including "Engine.h" is going against the IWYU rationale from Unreal 4.15 onwards, because Engine.h is huge and slows down compile time. See the Unreal Documentation for more information on the matter. So although it solves the problem, and there is nothing particularly 'wrong' with doing it - it may not be the best idea.
Another option which is more in line with IWYU would be to include Actor.h in PositionReport.cpp since GetOwner is in the AActor class.
#include "PositionReport.h"
#include "GameFramework/Actor.h" //This is the change in PositionReport.cpp

Settings errors in Qt project with OpenGL

In the project that use OpenGL in Qt I use in protected method initializeGL() the statement
qglClearColor(qtPurple.dark());
Follows errors occurs in the building project:
‘qtPurple’ was not declared in this scope
‘qglClearColor’ was not declared in this scope
The files that is included is:
#include <QtGui>
#include <QtOpenGL>
#include <QtGui/QColor>
In the .pro file is present
QT += core gui, opengl
Where are the mistakes that cause these errors?
QGLClearColor is a non-static member of QGLWidget. So first you must include <QGLWidget> to your widget header file and inherit your widget from QGLWidget. Then you will be able to call it in methods of your widget. You get was not declared in this scope error because qglClearColor is in QGLWidget scope.
Alternatively, you can call it as regular method of your widget object.
And what is qtPurple? It seems that it's not a part of Qt.
Add #include <QtOpenGL/QGLWidget> in your head file.And Your class should inherit QGLWidget.
It seems that you have not declared the variable qtPurple,so check
your head file,if not exist,just declare it[like this:QColor qtPurple;].

Organization of code for a game using SDL

I've been using SDL for some days now, and I decided after following some tutorials to start developing my own clone of Galaga. However, I had some difficulty trying to find a proper layout for my code.
For example, I have a Spaceship class defined as follows:
class Spaceship : public Sprite
{
public:
Spaceship(SDL_Surface *surface);
Spaceship(const char *filename);
void handleEvent(SDL_Event *event);
};
where Sprite is a base class that holds the position on the screen and so on.
My constructor would be something like:
Spaceship::Spaceship(SDL_Surface *surface) :
Sprite(surface)
{
m_y = Game::screenHeight() - m_surface->h; //positions the ship at the bottom
}
From what I've seen it's not possible to use Game::screenWidth() [static class] because I'd need to include "game.h", which is basically the main game class and includes "spaceship.h", creating basically an infinite loop (I've tried using #ifndef etc. with no success).
Is it possible to achieve this kind of result?
EDIT: I found a way to overcome the problem (I just added the "game.h" include in the cpp file and not in the header file).
If you only want to store pointers or references to those objects, then you can forward-declare one or both of the classes with class Game; or class Spaceship;. This is also fine if they take these objects as parameters or return them (with some exceptions, afaik).
If you actually want both to have a member of the other, then this is not possible, as each object would then have a copy of itself inside it.
You need to break a cycle in your dependency graph.
For example, one can add a field to your Spaceship class which saves a screen height.