SFML 2 drawing does not work when connected with OGRE - c++

I am currently working on connecting OGRE and SFML.
SFML should be used for 2D drawing, network stuff and input.
OGRE is for the 3d Graphics.
Currently the whole thing is on Linux.
What works: Connecting OGRE and SFML. First I create a SFML Render Window, then I grab the handle of this window and give it to the OGRE Render WIndow while creating it. I can use the SFML Events now. Did not test the Network stuff, but I am sure this will work too.
What does not work: Drawing in the SFML window.
Case 1: SFML and OGRE are not connected. OGRE does not have the SFML window handle and has its own window. SFML still can't draw in its own window! The main loop executes a maximum of 3 times and then just stops. Nothing more happens. A few seconds later (about 20 or so) I get a Memory Access violation and the program ends.
Case 2: SFML and OGRE are connected. A similar thing happens: The main loop executes exectly 53 times, nothing gets drawn and then the program stops with the terminal message "aborted" (actually its "Abgebrochen", because it's in German)
The strange behaviour also happens, when I let SFML draw into a sf::RenderTexture instead of the sfml_window.
Here is my code:
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <iostream>
#include <OGRE/Ogre.h>
#include <vector>
#include <stdio.h>
int main(int argc, char * argv[])
{
if(argc == 1)
return -1;
// start with "1" and you get 1 window, start with "0" and you get two
bool together = atoi(argv[1]);
// create the SFML window
sf::RenderWindow sfml_window(sf::VideoMode(800, 600), "test");
sf::WindowHandle sfml_system_handle = sfml_window.getSystemHandle();
sfml_window.setVerticalSyncEnabled(true);
std::cout<<sfml_system_handle<<std::endl;
// init ogre
Ogre::Root * ogre_root = new Ogre::Root("", "", "");
std::vector<Ogre::String> plugins;
plugins.push_back("/usr/lib/x86_64-linux-gnu/OGRE-1.8.0/RenderSystem_GL");
for(auto p : plugins)
{
ogre_root->loadPlugin(p);
}
const Ogre::RenderSystemList& render_systems = ogre_root->getAvailableRenderers();
if(render_systems.size() == 0)
{
std::cerr<<"no rendersystem found"<<std::endl;
return -1;
}
Ogre::RenderSystem * render_system = render_systems[0];
ogre_root->setRenderSystem(render_system);
ogre_root->initialise( false, "", "");
// create the ogre window
Ogre::RenderWindow * ogre_window= NULL;
{
Ogre::NameValuePairList parameters;
parameters["FSAA"] = "0";
parameters["vsync"] = "true";
// if started with 1, connect the windows
if(together) parameters["externalWindowHandle"] = std::to_string(sfml_system_handle);
ogre_window = ogre_root->createRenderWindow("ogre window", 800, 600, false, &parameters);
}
// ogre stuff
Ogre::SceneManager * scene = ogre_root->createSceneManager(Ogre::ST_GENERIC, "Scene");
Ogre::SceneNode * root_node = scene->getRootSceneNode();
Ogre::Camera * cam = scene->createCamera("Cam");
Ogre::SceneNode * cam_node = root_node->createChildSceneNode("cam_node");
cam_node->attachObject(cam);
Ogre::Viewport * vp = ogre_window->addViewport(cam);
vp->setAutoUpdated(false);
vp->setBackgroundColour(Ogre::ColourValue(0, 1, 1));
ogre_window->setAutoUpdated(false);
ogre_root->clearEventTimes();
//sfml image loading
sf::Texture ring;
std::cout<<"ring loading: "<<ring.loadFromFile("ring.png")<<std::endl;
sf::Sprite sprite;
sprite.setTexture(ring);
// main loop
int counter = 0;
while(!ogre_window->isClosed() && sfml_window.isOpen())
{
std::cout<<counter<<std::endl;
counter++;
std::cout<<"a"<<std::endl;
// sfml events
sf::Event event;
while(sfml_window.pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
sfml_window.close();
}
}
std::cout<<"b"<<std::endl;
std::cout<<"c"<<std::endl;
ogre_root->renderOneFrame();
std::cout<<"d"<<std::endl;
// here the strange behaviour happens
// if this line (draw) isn't present, everything works
sfml_window.pushGLStates();
sfml_window.draw(sprite);
sfml_window.popGLStates();
vp->update();
std::cout<<"e"<<std::endl;
sfml_window.display();
// only needs to be done for separated windows
// sfml display updates otherwise, both use double buffering
if(!together) ogre_window->update(true);
}
return 0;
}
Help would be really appreciated.
EDIT: I added the pushGLStates(); and popGLStates(); commands, forgot those earlier!

Not an answer really, but too long for a comment:
ogre_window = ogre_root->createRenderWindow("ogre window", 800, 600, false, &parameters);
Are you sure that it's okay to pass the address of an object you destroy the very next line here with &parameters?

Related

How to bounce a QWidget around the desktop

I am trying to bounce a QWidget around the screen. This is the code i tried.
class Window : public QMainWindow {
public:
void moveEvent(QMoveEvent* aEvent) override;
};
void Window::moveEvent(QMoveEvent* aEvent) {
QSizeF screenSize = QGuiApplication::primaryScreen()->screenSize();
QRect oldRect = this->geometry();
QRect newRect = oldRect;
QPoint offset;
if (newRect.left() == 0) {
offset.setX(1);
}
else if (newRect.right() == screenSize.width()) {
offset.setX(-1);
}
if (newRect.top() == 0) {
offset.setX(1);
}
else if (newRect.bottom() == screenSize.height()) {
offset.setX(-1);
}
newRect.setTopLeft(newRect.topLeft() + offset);
newRect.setBottomRight(newRect.bottomRight() + offset);
QTimer::singleShot(1, [this, newRect]() {
setGeometry(newRect);
});
}
int main(int argc, char** argv) {
QApplication app{argc, argv};
Window* w = new Window();
w->show();
w->setGeometry(w->geometry());
return app.exec();
}
However, the window does not move around the screen, but somewhat jitters in place. When i move the window with the mouse and let go. It moves sporadically around the desktop, which is also not what i want.
Does anyone know if this is possible? If so, does anyone know the right way to do this?
There are several problems with the posted code, including:
The Window class doesn't have any member-variable to keep track of its current direction of motion. Without keeping that state, it's impossible to correctly calculate the next position along that direction of motion.
Driving the animation from within moveEvent() is a bit tricky, since moveEvent() gets called in response to setGeometry() as well as in response to the user actually moving the window with the mouse; that makes unexpected feedback loops possible, resulting in unexpected behavior.
The code assumes that the screen's usable surface area starts at (0,0) and ends at (screenSize.width(),screenSize.height()), which isn't necessarily a valid assumption. The actual usable area of the screen is a rectangle given by availableGeometry().
When calling setGeometry(), you are setting the new location of the area of the window that the Qt program can actually draw into. However that's only a 99% subset of the actual on-screen area taken up by the window, because the window also includes the non-Qt-controlled regions like the title bar and the window-borders. Those parts need to fit into the availableGeometry() also, otherwise the window won't be positioned quite where you wanted it to be, which can lead to anomalies (like the window getting "stuck" on the top-edge of the screen)
In any case, here's my attempt at rewriting the code to implement a closer-to-correct "bouncing window". Note that it's still a bit glitchy if you try to mouse-drag the window around while the window is also trying to move itself around; ideally the Qt program could detect the mouse-down-event on the title bar and use that to disable its self-animation until after the corresponding mouse-up-event occurs, but AFAICT that isn't possible without resorting to OS-specific hackery, because the window-title-bar-dragging is handled by the OS, not by Qt. Therefore, I'm leaving that logic unimplemented here.
#include <QApplication>
#include <QMainWindow>
#include <QMoveEvent>
#include <QShowEvent>
#include <QScreen>
#include <QTimer>
class Window : public QMainWindow {
public:
Window() : pixelsPerStep(5), moveDelta(pixelsPerStep, pixelsPerStep)
{
updatePosition(); // this will get the QTimer-loop started
}
private:
void updatePosition()
{
const QRect windowFrameRect = frameGeometry(); // our on-screen area including window manager's decorations
const QRect windowRect = geometry(); // our on-screen area including ONLY the Qt-drawable sub-area
// Since setGeometry() sets the area not including the window manager's window-decorations, it
// can end up trying to set the window (including the window-decorations) slightly "out of bounds",
// causing the window to "stick to the top of the screen". To avoid that, we'll adjust (screenRect)
// to be slightly smaller than it really is.
QRect screenRect = QGuiApplication::primaryScreen()->availableGeometry();
screenRect.setTop( screenRect.top() + windowRect.top() - windowFrameRect.top());
screenRect.setBottom( screenRect.bottom() + windowRect.bottom() - windowFrameRect.bottom());
screenRect.setLeft( screenRect.left() + windowRect.left() - windowFrameRect.left());
screenRect.setRight( screenRect.right() + windowRect.right() - windowFrameRect.right());
// Calculate where our window should be positioned next, assuming it continues in a straight line
QRect nextRect = geometry().translated(moveDelta);
// If the window is going to be "off the edge", set it to be exactly on the edge, and reverse our direction
if (nextRect.left() <= screenRect.left()) {nextRect.moveLeft( screenRect.left()); moveDelta.setX( pixelsPerStep);}
if (nextRect.right() >= screenRect.right()) {nextRect.moveRight( screenRect.right()); moveDelta.setX(-pixelsPerStep);}
if (nextRect.top() <= screenRect.top()) {nextRect.moveTop( screenRect.top()); moveDelta.setY( pixelsPerStep);}
if (nextRect.bottom() >= screenRect.bottom()) {nextRect.moveBottom(screenRect.bottom()); moveDelta.setY(-pixelsPerStep);}
setGeometry(nextRect);
QTimer::singleShot(20, [this]() {updatePosition();});
}
const int pixelsPerStep;
QPoint moveDelta; // our current positional-offset-per-step in both X and Y direction
};
int main(int argc, char** argv) {
QApplication app{argc, argv};
Window* w = new Window();
w->show();
return app.exec();
}

Generating multiple amounts of the same sprite broken

I have just started working on a 2d game of mine. I'm currently experiencing a problem where I am trying to make some land with a grass block texture by spawning the same sprites multiple times with the same grass texture. However, instead of getting a row of the same texture, I am getting the row being stretched for some reason.
Let me show you:
Normal grass texture:
Current grass output:
This is the code:
#include <iostream>
#include <vector>
#include <random>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
int main() {
RenderWindow window(VideoMode(1920, 1080), "Treko");
Color bg(0, 205, 255);
Font errorFont;
Texture grass;
Texture dirt;
if (!errorFont.loadFromFile("font/Arial/Arial.ttf")) {
RenderWindow error(VideoMode(600, 500), "Error!");
Text errorText;
errorText.setFont(errorFont);
errorText.setString("Unfortunaetly, we are unable to find Arial.ttf.\nPlease reinstall the application and report the error. Thank you.");
errorText.setCharacterSize(18);
errorText.setFillColor(Color::White);
while (error.isOpen()) {
Event errorEvent;
while (error.pollEvent(errorEvent)) {
if (errorEvent.type == Event::Closed) {
error.close();
}
}
error.clear();
error.draw(errorText);
error.display();
}
}
if (!dirt.loadFromFile("img/Dirt.png")) {
RenderWindow error(VideoMode(600, 500), "Error!");
Text errorText;
errorText.setFont(errorFont);
errorText.setString("Unfortunaetly, we are unable to find Dirt.png.\nPlease reinstall the application and report the error. Thank you.");
errorText.setCharacterSize(18);
while (error.isOpen()) {
Event errorEvent;
while (error.pollEvent(errorEvent)) {
if (errorEvent.type == Event::Closed) {
error.close();
}
}
error.clear();
error.draw(errorText);
error.display();
}
}
if (!grass.loadFromFile("img/Grass.png")) {
RenderWindow error(VideoMode(600, 500), "Error!");
Text errorText;
errorText.setFont(errorFont);
errorText.setString("Unfortunaetly, we are unable to find Grass.png.\nPlease reinstall the application and report the error. Thank you.");
errorText.setCharacterSize(18);
errorText.setFillColor(Color::White);
while (error.isOpen()) {
Event errorEvent;
while (error.pollEvent(errorEvent)) {
if (errorEvent.type == Event::Closed) {
error.close();
}
}
error.clear();
error.draw(errorText);
error.display();
}
}
Sprite grassBlock;
grassBlock.setTexture(grass);
Sprite dirtBlock;
dirtBlock.setTexture(dirt);
vector<Sprite> grassM;
/* This is a work in progress. I'm trying to add height to the land using random y axis generation. Any of you know how to do this it would be great to let me know!
std::uniform_int_distribution<int> randomColorRange(680, 720);
std::random_device rd;
std::mt19937 RandYPos(rd());
*/
//THE PROBLEM PART 1
for (int i = 0; i <= 1918; i++) {
grassBlock.setPosition(Vector2f(i + 1, 690));
grassBlock.setScale(Vector2f(0.5f, 0.5f));
grassM.push_back(Sprite(grassBlock));
}
while (window.isOpen()) {
Event event;
while (window.pollEvent(event)) {
if (event.type == Event::Closed) {
window.close();
}
}
window.clear(bg);
//THE PROBLEM PART 2
for (int i = 0; i < grassM.size(); i++) {
window.draw(grassM[i]);
}
window.display();
}
return 0;
}
If anyone knows how to do this, that would be great!
While I didn't try to run the code, to me it looks like everything is working. Your problem is, that you're just moving the sprites one pixel apart:
grassBlock.setPosition(Vector2f(i + 1, 690));
Since all show the same texture with the same origin, this will result in all the sprites essentially showing the first column of your texture (since the rest is overlapped by the next tile).
While I think you should rework your whole code structure (it feels really messy and I wouldn't recommend to create new SFML windows if you encounter errors, since that might fail as well), all you have to do is move your sprites apart by multiplying the index used for your coordinate by the desired tile width:
grassBlock.setPosition(Vector2f(i * tile_width, 690));

Using window.draw() outside of main SFML

I am using SFML and this is the first time I have really used a library but I have a decent knowledge in C++. How do I access my window functions outside of main? e.g.
void checkWin()
{
if (iFilled[0] == 1 && iFilled[1] == 1 && iFilled[2] == 1) {
RectangleShape line(Vector2f(150, 5));
line.setPosition(10, 450);
window.draw(line); //error window is inside of main()
}
}
int main()
{
RenderWindow window;
window.create(VideoMode(800, 600), "Red vs. Green Peppers", Style::Close);
//more code
return 0;
}
First, you need to check those tutorials from SFML's site: http://www.sfml-dev.org/tutorials/2.1/ .
If you have decent knowledge in C++ you could use pointers and reference parameters:
void checkWin( sf::RenderWindow &window) { ... }
Anyway, to show an image to the screen you need to do that in a while, because, how you wrote that, you will show that image only for 1 frame, or less, because you don't know if window is still open.

SFML 2.0 Targeting a player by a single turret

At the beginning - sorry for my english (i'm still learning).
I've created a turret which targets player. It works fine but when i'm moving around within the range of tower, turret no longer targets me. Just take a look at this code and run this in your compilator.
int detection (sf::Sprite statek,sf::RectangleShape linia,sf::Texture textstatku)
{
sf::FloatRect rect, rect2;
rect = linia.getGlobalBounds();
rect2 = statek.getGlobalBounds();
if(rect2.intersects(rect))
return 1;
else
return 2;
}
int _tmain(int argc, _TCHAR* argv[])
{
sf::Event evente;
sf::RenderWindow okno ( sf::VideoMode(500,500,32)," TURRET TEST ");
sf::Texture textturreta;
textturreta.loadFromFile ("C:\\Users\\Darono\\C++\\Projekty\\IN PROGGRES\\Single turret\\Debug\\turret.png");
sf::CircleShape turret (20.0,100);
turret.setTexture((sf::Texture *)&textturreta);
turret.setPosition (240,240);
sf::Texture Lufatext;
Lufatext.loadFromFile("C:\\Users\\Darono\\C++\\Projekty\\IN PROGGRES\\Single turret\\Debug\\Lufa.png");
sf::Sprite lufa;
lufa.setTexture(Lufatext);
sf::Texture gracztext;
gracztext.loadFromFile("C:\\Users\\Darono\\C++\\Projekty\\IN PROGGRES\\Single turret\\Debug\\gracz.png");
sf::Sprite gracz(gracztext);
int orginY=turret.getPosition().y+20;
int orginX=turret.getPosition().x+20;
lufa.setPosition(turret.getPosition().x+20,turret.getPosition().y+20);
lufa.setOrigin (2,-20);
sf::RectangleShape liniastrzalu(sf::Vector2f(1,200));
liniastrzalu.setOrigin(0,-20);
liniastrzalu.setPosition(turret.getPosition().x+20,turret.getPosition().y+20);
int a =0;
while (okno.isOpen())
{
if (gracz.getPosition().y >= turret.getPosition().y-240||gracz.getPosition().y <= turret.getPosition().y+280)
{
if (detection(gracz,liniastrzalu,textturreta)== 1)
{
std::cout <<"lol";
}
if (detection(gracz,liniastrzalu,textturreta)==2)
{
lufa.rotate(1);
liniastrzalu.rotate(1);
}
}
while (okno.pollEvent(evente))
{
//lufa obraca się razem z kołem
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
gracz.move(-2,0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
gracz.move(2,0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
{
gracz.move(0,2);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
gracz.move(0,-2);
}
}
okno.display();
okno.clear();
okno.draw(turret);
okno.draw(lufa);
okno.draw(gracz);
//okno.draw(liniastrzalu);
}
return 0;
}
You should follow a few best practices:
Your game loop consists of 3 main parts: handling user input, updating your game world and drawing your game world. Although you do this, you have the order mixed up. You seem to update your game world before handling user input.
Drawing in SFML consists of cleaning the surface, drawing and presenting in that order.
okno.clear();
okno.draw(turret);
okno.draw(lufa);
okno.draw(gracz);
okno.display();
Notice how I put the display call to the end.
You don't need to call your detection method twice. Call it once and store the result in a variable, then use that variable.
Fix those things first, because they will cause a lot of problems that may hide your real problem or cause problems when your code is fine.

C++ Allegro: Program Crashes when I move the window

I Have built a C++ Allegro Map Editor. One of the requests was to have a log so I've put it in the console window for every move that is made... Problem now is that the console window is under the main window (Used GFX_AUTODETECT_WINDOWED), But whenever I try to move that window, it simply crashes the program.. I need to be able to move it and to move the console window to and come back to the map editor. Anybody has any ideas???
Here's the main of my code.
#include <allegro.h>
#include <string>
#include <sstream>
#include "Layout.h"
#include "System.h"
#include "Map.h"
#include <iostream>
#include <fstream>
using namespace std;
// Allegro Functions to stabilize speed
volatile long speed_counter = 0;
void increment_speed_counter() // A function to increment the speed counter
{speed_counter++; }
END_OF_FUNCTION(increment_speed_counter);
int main()
{
System system; // Initialising Allegro
system.Setup();
Map map1; // Creating default map
map1.createMap();
BITMAP *buffer = create_bitmap(24,45); // Double buffering
LOCK_VARIABLE(speed_counter); //Used to set the timer - which regulates the game's
LOCK_FUNCTION(increment_speed_counter);//speed.
install_int_ex(increment_speed_counter, BPS_TO_TIMER(8));//Set our BP
/*game looop */
while( !key[KEY_ESC] )
{
clear_bitmap(buffer); // Clear the contents of the buffer bitmap
while(speed_counter > 0)
{
if(mouse_b &1 ){ // On mouse click
map1.catchMouseEvent(mouse_x, mouse_y);
while(mouse_b & 1){}
}
speed_counter --;
}
rectfill(buffer,0,0,25,45,makecol(135,206,250));
textprintf_ex(buffer, map1.getLayout().getFont(), 0, 0, makecol(255, 255, 255), -1,"%d", map1.getRowVal());
textprintf_ex(buffer, map1.getLayout().getFont(), 0, 20, makecol(255, 255, 255), -1,"%d", map1.getColVal());
blit(buffer, screen, 0, 0, 970, 50, 100, 50);
}
/*Free memory after */
destroy_bitmap( buffer );
return 0;
allegro_exit();
}
END_OF_MAIN();
Also, it does happen that it randomly crashes by itself without moving the window. There is not a specific reason, it just crashes at random times.
Any ideas someone?
Without seeing all of the code, it's impossible to know why or where it's crashing. If you use a debugger it should be obvious what's happening. You should be responding to return codes. e.g., When you load or create a bitmap, make sure it's not NULL.
I'm not really sure what you are trying to do with such a smaller double buffer. Typically you create a single buffer the same size as the window. Note that Allegro 4 will only work properly if the screen width is a multiple of four. Also, you should call set_color_depth(desktop_color_depth()) (before setting the graphics mode) for maximum compatibility.