How to use wrapper class? - c++

I have a QgraphicsScene which contains many QGraphicsItem. I am reading line, arc and circle's co-ordinates from a file and storing them in a map and when time comes to draw them, I iterate over that map and give those co-ordinates to respective Qt's Api.
But the problem is that, the symbol which is getting generated is not fully selectable.
Means if a symbol is created by let's say 4 lines, 1 arc and 1 circle. Then if I click on a particular line, then only that line gets selected. Or that particular arc gets selected.
But I am expecting, on clicking, the full symbol should be selected.
For that I was suggested to use wrapper class. But not understanding
how to use that ?
Here is my structure:
class mySymbol
{
struct Line {
std::tuple<int, int, int, int> line;
};
struct Arc {
std::tuple<int, int, int, int, int, int> arc;
};
struct Circle {
std::tuple<int, int, int> circle;
};
struct Rect
{
std::vector<Line> allLines;
std::vector<Arc> allArcs;
std::vector<Circle> allCircles;
}
std::map<std::string, Rect> allShapes;
}
DrawShapes.h
class DrawShapes
{
void createSymbol(map<std::string, Rect>);
}
DrawShapes.cpp
void DrawShapes :: createSymbol(map<std::string, Rect> allShapes)
{
QGraphicsItemGroup * parentGroup = new QGraphicsItemGroup;
for (auto iter = allShapes.begin(); iter != allShapes.end(); ++iter)
{
if (iter->second.allLines.size() > 0)
{
for (unsigned int i = 0; i < iter->second.allLines.size(); i++)
{
// getting 4 co-ordinates of line as first,second,third and fourth
myLine* line = new myLine(first,second,third,fourth);
line->DrawLine();
parentGroup->addToGroup(line);
scene->addItem(static_cast<QGraphicsLineItem*>(line));
}
}
// same logic for arc and circle
}
myLine.h
class myLine: public QGraphicsLineItem
{
public:
myLine();
myLine(int x1,int y1,int x2 ,int y2,QGraphicsItem *parent = nullptr)
: QGraphicsLineItem(x1,y1,x2,y2,parent)
{}
void DrawLine();
};
myLine.cpp
void myLine::DrawLine()
{
this->setPen(QPen(QColor("blue"), 1));
this->setFlag(QGraphicsItem::ItemIsSelectable);
}

Related

C++ Struct Members not Updating in Funtion

Firstly, while not new to programming, I am very new to C++, so please bear with me.
I am using the Raylib library to attempt making a particle system for a game.
This consists of a struct with a few private members and public functions:
struct Particle {
Particle() {
mPosVector = {(float)GetMouseX(), (float)GetMouseY()};
mVelVector = {(float)GetRandomValue(15, 70)/100, (float)GetRandomValue(15, 70)/100};
mSize = GetRandomValue(5, 15);
}
void update(double deltaTime) {
mPosVector.x += mVelVector.x;
mPosVector.y += mVelVector.y;
}
void draw() {
DrawRectangleV(mPosVector, {(float)mSize, (float)mSize}, WHITE);
}
private:
Vector2 mPosVector;
Vector2 mVelVector;
int mSize;
};
The Vector2 type is defined by Raylib:
struct Vector2 {
float x;
float y;
};
In my main function I have an std::vector storing Particles. A particle gets added when the left mouse button is pressed. I loop through the Particles vector twice, once for updating position based on velocity and once for drawing. I was originally doing these both in one loop, but was still getting the problem that I will get onto, so tried it this way.
This is the current code:
std::vector<Particle> particles = {Particle()};
while (!WindowShouldClose()) {
deltaTime = GetFrameTime();
if (IsMouseButtonDown(0)) {
particles.push_back(Particle());
}
for (Particle part : particles) {
part.update(deltaTime);
}
BeginDrawing();
ClearBackground(BLACK);
DrawFPS(10, 10);
DrawText((numToString<double>(deltaTime*1000).substr(0, 5) + "ms").c_str(), 10, 40, 20, WHITE);
for (Particle part : particles) {
part.draw();
}
EndDrawing();
So, my problem: While particles are being instantiated as expected while pressing the left mouse button and being drawn, for some reason their positions are not being updated by their velocity. I have tried printing debug information to the console, such as the velocity, and it is as expected, but for some unknown reason to me (probably just me being stupid) their positions aren't being updated.
Any help would be greatly appreciated.
for (Particle part : particles) {
part.update(deltaTime);
}
this is making a copy of each entry , you need
for (Particle &part : particles) {
part.update(deltaTime);
}
to get a reference to the object in the vector to update it in place
To understand, think that the ranged for is just short hand for this
for(int i = 0; i < particles.size(); i++)
{
// this line copies the value
particle p = particles[i];
}
whereas the one with & in it does
for(int i = 0; i < particles.size9); i++)
{
// this line gets a reference to the ith entry
particle &p = particles[i];
}
Its nothing special to do with the ranged for loop.

Write text input on the screen in SFML

So I'm creating a graphing calculator. I have an input string s. From the string, I can graph it using SFML. I start from the a MIN x-coordinate to a MAX x-coordinate, get the corresponding y from a EvaluateString() method, and all the coordinates to a VertexArray v. I wrote my method and the graphing method already and it all worked well.
However, I have a small issue. I want to input my string on the screen, such as "sin(cos(tan(x)))" like this. I'm struggling to find a way to do it. I kinda figured out it has to do with the event TextEntered, but still I can't find anything completely.
Please suggest me a way.
class Calculator{
public:
void main();
private:
WindowSize DefaultWindow;
sf::RenderWindow window;
Cartesian vertexX[2],vertexY[2];
sf::Vertex axis[4];
const double MAX = 10;
const double MIN = -10;
const double INCREMENT = 0.001;
};
int main(){
DefaultWindow.Max = Cartesian(10,10);
DefaultWindow.Min = Cartesian(-10,-10);
DefaultWindow.plane.width=1500;
DefaultWindow.plane.height=1500;
// Set up x and y-axis
vertexX[0] = Cartesian(-100,0);
vertexX[1] = Cartesian(100, 0);
vertexY[0] = Cartesian(0,-100);
vertexY[1] = Cartesian(0,100);
axis[0] = sf::Vertex(convertCartesiantoWindow(vertexX[0],DefaultWindow));
axis[1] = sf::Vertex(convertCartesiantoWindow(vertexX[1],DefaultWindow));
axis[2] = sf::Vertex(convertCartesiantoWindow(vertexY[0],DefaultWindow));
axis[3] = sf::Vertex(convertCartesiantoWindow(vertexY[1],DefaultWindow));
// Set up the window
window.create(sf::VideoMode(1500, 1500), "Graphing calculator");
// Input string
string s = "sin(cos(tan(x)))";
// Stack c contains all the Cartesian coordinate vertices
// Cartesian is a struct which contains x and y coordinates
Stack<Cartesian> c;
sf::VertexArray v;
// For a certain function in string s, I evaluate it
// and return the y_coordinate from the function EvaluateString (s, i)
// Push each (x,y) evaluated in the Stack c
for (double i = MIN; i <= MAX; i+= INCREMENT)
c.Push(Cartesian(i,EvaluateString(s,i)));
// v is VertexArray which contains all the vertices (x,y)
v = plot(DefaultWindow, c);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
}
}
}
// Draw the graph
window.clear(sf::Color::Black);
window.draw(axis,4,sf::Lines);
window.draw(v);
window.display();
}
As #super suggest, use a library would be a nice solution, and surely better than mine, but just in case this satisfies your needs, I implemented a super basic TextField class.
It may be plenty of errors, but it can gives you an idea on how to achieve that functionality.
A TextField is nothing more than a rectangle which contains a text. Since it will have a sf::Text, it must have a sf::Font. Additionally, I limit the number of characters that it will contain. In order for us to write inside the TextField, we have to know if it's selected, i.e. if it has the focus. So, a first approach could be:
class TextField : public sf::Transformable, public sf::Drawable{
private:
unsigned int m_size;
sf::Font m_font;
std::string m_text;
sf::RectangleShape m_rect;
bool m_hasfocus;
};
We need a constructor for this class:
class TextField : public sf::Transformable, public sf::Drawable{
public:
TextField(unsigned int maxChars) :
m_size(maxChars),
m_rect(sf::Vector2f(15 * m_size, 20)), // 15 pixels per char, 20 pixels height, you can tweak
m_hasfocus(false)
{
m_font.loadFromFile("C:/Windows/Fonts/Arial.ttf"); // I'm working on Windows, you can put your own font instead
m_rect.setOutlineThickness(2);
m_rect.setFillColor(sf::Color::White);
m_rect.setOutlineColor(sf::Color(127,127,127));
m_rect.setPosition(this->getPosition());
}
private:
unsigned int m_size;
sf::Font m_font;
std::string m_text;
sf::RectangleShape m_rect;
bool m_hasfocus;
};
We also need some basic methods, we want to get the text inside:
const std::string sf::TextField::getText() const{
return m_text;
}
and move it, placing it somewhere inside our window:
void sf::TextField::setPosition(float x, float y){
sf::Transformable::setPosition(x, y);
m_rect.setPosition(x, y);
}
this is a tricky one. We are overwritting setPosition method of sf::Transformable because we need to update our own m_rect.
Also, we need to know if a point is inside of the box:
bool sf::TextField::contains(sf::Vector2f point) const{
return m_rect.getGlobalBounds().contains(point);
}
pretty simple, we use cointains method of sf::RectangleShape, already in sfml.
Set (or unset) focus on the TextField:
void sf::TextField::setFocus(bool focus){
m_hasfocus = focus;
if (focus){
m_rect.setOutlineColor(sf::Color::Blue);
}
else{
m_rect.setOutlineColor(sf::Color(127, 127, 127)); // Gray color
}
}
easy one. For aesthetics, we also change the outline color of the box when focused.
And last, but not least, our TextField has to behave some way when input (aka an sf::Event) is received:
void sf::TextField::handleInput(sf::Event e){
if (!m_hasfocus || e.type != sf::Event::TextEntered)
return;
if (e.text.unicode == 8){ // Delete key
m_text = m_text.substr(0, m_text.size() - 1);
}
else if (m_text.size() < m_size){
m_text += e.text.unicode;
}
}
That delete key check is little dirty, I know. Maybe you can find better solution.
That's all! Now main looks like:
int main()
{
RenderWindow window({ 500, 500 }, "SFML", Style::Close);
sf::TextField tf(20);
tf.setPosition(30, 30);
while (window.isOpen())
{
for (Event event; window.pollEvent(event);)
if (event.type == Event::Closed)
window.close();
else if (event.type == Event::MouseButtonReleased){
auto pos = sf::Mouse::getPosition(window);
tf.setFocus(false);
if (tf.contains(sf::Vector2f(pos))){
tf.setFocus(true);
}
}
else{
tf.handleInput(event);
}
window.clear();
window.draw(tf);
window.display();
}
return 0;
}
Proof of concept:
std::string str;
sf::String text;
// In event loop...
if (event.Type == sf::Event::TextEntered)
{
// Handle ASCII characters only
if (event.Text.Unicode < 128)
{
str += static_cast<char>(event.Text.Unicode);
text.SetText(str);
}
}
// In main loop...
window.Draw(text);
This should create an sf::Event::TextEntered for input, and sf::String for output

How to use of "new" for polygons in C++

The definitions of Circle and Polygon are here in Graph.h and graph.cpp.
For some exercise I need to have some unnamed shapes which are made using the new keyword. Both Circle and polygon are kinds of Shape.
For example if I have a vector_ref<Circle> vc; I can using this statement add an unnamed Circle into that vector: vc.push_back(new Circle (Point (p), 50)); because I can supply parameters (which are a point and a radius) of a circle when defining it.
But for polygons the subject is different.
For having a polygon I must declare it first, e.g., Polygon poly; then add points to it, this way, poly.add(Point(p));. Now it has caused a problem for me.
Consider I have a vector of polygons, Vector_ref<Polygon> vp; Now how to add (that is push back) a polygon using the new keyword just like I did for circle please?
My code is this:
#include <GUI.h>
using namespace Graph_lib;
//---------------------------------
class Math_shapes : public Window {
public:
Math_shapes(Point, int, int, const string&);
private:
//Widgets
Menu menu;
Button quit_button;
In_box x_coor;
In_box y_coor;
Vector_ref<Circle> vc;
Vector_ref<Graph_lib::Rectangle> vr;
Vector_ref<Graph_lib::Polygon> vt;
Vector_ref<Graph_lib::Polygon> vh;
//Action fucntions
void circle_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
vc.push_back(new Circle (Point(x,y), 50));
attach(vc[vc.size()-1]);
redraw();
}
void square_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
vr.push_back(new Graph_lib::Rectangle (Point(x,y), Point(x+100,y+100)));
attach(vr[vr.size()-1]);
redraw();
}
void triangle_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
vt.push_back(new Graph_lib::Polygon); // Problem is here!!
attach(vt[vt.size()-1]);
redraw();
}
void hexagon_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
Graph_lib::Polygon h;
h.add(Point(x,y)); h.add(Point(x+50,y+50)); h.add(Point(x+50,y+80));
h.add(Point(x,y+100)); h.add(Point(x-50,y+80)); h.add(Point(x-50,y+50));
vh.push_back(h);
attach(vh[vh.size()-1]);
redraw();
}
void quit() { hide(); }
// Call-back functions
static void cb_circle (Address, Address pw) { reference_to<Math_shapes>(pw).circle_pressed(); }
static void cb_square (Address, Address pw) { reference_to<Math_shapes>(pw).square_pressed(); }
static void cb_triangle (Address, Address pw) { reference_to<Math_shapes>(pw).triangle_pressed(); }
static void cb_hexagon (Address, Address pw) { reference_to<Math_shapes>(pw).hexagon_pressed(); }
static void cb_quit (Address, Address pw) { reference_to<Math_shapes>(pw).quit(); }
};
//----------------------------------------------------------------------------------
Math_shapes::Math_shapes(Point xy, int w, int h, const string& title):
Window(xy, w, h, title),
menu (Point(x_max()-150,70),120,30,Menu::vertical, "MathShapes"),
quit_button (Point(x_max()-100, 20), 70,20, "Quit", cb_quit),
x_coor(Point(x_max()-450,30),50,20,"x coordinate: "),
y_coor(Point(x_max()-250,30),50,20,"y coordinate: ")
{
attach(x_coor);
attach(y_coor);
attach(quit_button);
menu.attach(new Button(Point(0,0),0,0,"Circle",cb_circle));
menu.attach(new Button(Point(0,0),0,0,"Square",cb_square));
menu.attach(new Button(Point(0,0),0,0,"Equilateral triangle",cb_triangle));
menu.attach(new Button(Point(0,0),0,0,"Hexagon",cb_hexagon));
attach(menu);
}
//-------------------------------------------
int main()
try {
Math_shapes M_s(Point(100,100), 800, 600, "Math Shapes");
return gui_main();
}
catch(...)
{
return 0;
}
You simply need to hold a pointer to your polygon until you've put it in the conatiner:
Circle* pPoly = new Polygon();
// ...
pPoly->add(Point(p1));
// ...
pPoly->add(Point(p2));
// ...
vc.push_back(pPoly);
you probably want to use smart pointers rather than raw ones as above but this is where you can start.
Have you tried this
void triangle_pressed() {
int x = x_coor.get_int();
int y = y_coor.get_int();
Polygon *poly = new Polygon();
poly.add(Point(x));// add your points, I don't know if these are the right points
poly.add(Point(y));// but have you tried this way? creating it, adding, then calling
vt.push_back(poly); // push back without the move
attach(vt[vt.size()-1]);
redraw();
Well, in order to use the new operator, you would need to create a Polygon constructor that takes vector<Point> or initializer_list<Point> as an argument.
The other way around would be to create a helper function, e.g.
-- note that this is really suboptimal, there may be much better solution using move semantics, etc. (or even variadic template function for the matter)
Polygon* make_polygon(initializer_list<Point>& points)
{
Polygon* poly = new Polygon();
for (auto point : points)
poly->Add(point);
return poly;
}
And then just call vp.push_back(make_polygon({p1, p2, ...});
Obviously you could change the function to work without pointers simply by removing them alongside with the new operator call, but then it wouldn't work with your vector_ref<Polygon> type. You would need to use vector<Polygon> instead, as I assume that vector_ref<T> is just a typedef for vector<T*>

c++ Find all values of all objects in a class

I'm making a simple 2d platformer and I need to find all the values of all objects created, these objects would represent the in game collidables. So I would need all of the x/y co-ordinates, width and height so that I can check if any of them are colliding with the player.
Class Looks like:
class CollidableObject
{
public:
CollidableObject();
virtual ~CollidableObject();
int Height;
int Width;
DirectX::SimpleMath::Vector2 position;
bool collidable;
};
It's obviously a very simple class and I just need a way to find out if the player position collides with any of the collidable objects values, I don't need collision code just a way to get at all of the collidable objects values at once. Hope I've made it clear.
class CollisionPred(
public:
CollisionPred( Player p) : p_(p) {}
bool operator()(const ColiidableObject& o) {
// process object and return true if there is a collision, i.e:
return o.Height*o.Height + o.Width*o.Width > p_.distance;
}
private:
Player p_;
;
int main() {
//...
std::vector<CollidableObject> v(100);
std::vector<CollidableObject>::iterator it =
std::find_if(v.begin(), v.end(), CollisionPred());
//...
}
The simplest and yet, the most popular way of doing it is to just iterate through a collection of collidables to check if any collides with a player.
vector<CollidableObject> objects;
for(CollidableObject& obj: objects)
{
if (obj.position.x - obj.width < player.position.x + player.radius
&& obj.position.x + obj.width > player.position.x - player.radius
&& obj.position.y - obj.height < player.position.y + player.radius
&& obj.position.y + obj.height > player.position.y - player.radius
)
// collision happened
}

How to create an object inside another class with a constructor?

So I was working on my code, which is designed in a modular way. Now, one of my classes; called Splash has to create a object of another class which is called Emitter. Normally you would just create the object and be done with it, but that doesn't work here, as the Emitter class has a custom constructor. But when I try to create an object, it doesn't work.
As an example;
Emitter has a constructor like so: Emitter::Emitter(int x, int y, int amount); and needs to be created so it can be accessed in the Splash class.
I tried to do this, but it didn't work:
class Splash{
private:
Emitter ps(100, 200, 400, "firstimage.png", "secondimage.png"); // Try to create object, doesn't work.
public:
// Other splash class functions.
}
I also tried this, which didn't work either:
class Splash{
private:
Emitter ps; // Try to create object, doesn't work.
public:
Splash() : ps(100, 200, 400, "firstimage.png", "secondimage.png")
{};
}
Edit: I know the second way is supposed to work, however it doesn't. If I remove the Emitter Section, the code works. but when I do it the second way, no window opens, no application is executed.
So how can I create my Emitter object for use in Splash?
Edit:
Here is my code for the emitter class and header:
Header
// Particle engine for the project
#ifndef _PARTICLE_H_
#define _PARTICLE_H_
#include <vector>
#include <string>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "image.h"
extern SDL_Surface* gameScreen;
class Particle{
private: // Particle settings
int x, y;
int lifetime;
private: // Particle surface that shall be applied
SDL_Surface* particleScreen;
public: // Constructor and destructor
Particle(int xA, int yA, string particleSprite);
~Particle(){};
public: // Various functions
void show();
bool isDead();
};
class Emitter{
private: // Emitter settings
int x, y;
int xVel, yVel;
private: // The particles for a dot
vector<Particle> particles;
SDL_Surface* emitterScreen;
string particleImg;
public: // Constructor and destructor
Emitter(int amount, int x, int y, string particleImage, string emitterImage);
~Emitter();
public: // Helper functions
void move();
void show();
void showParticles();
};
#endif
and here is the emitter functions:
#include "particle.h"
// The particle class stuff
Particle::Particle(int xA, int yA, string particleSprite){
// Draw the particle in a random location about the emitter within 25 pixels
x = xA - 5 + (rand() % 25);
y = yA - 5 + (rand() % 25);
lifetime = rand() % 6;
particleScreen = Image::loadImage(particleSprite);
}
void Particle::show(){
// Apply surface and age particle
Image::applySurface(x, y, particleScreen, gameScreen);
++lifetime;
}
bool Particle::isDead(){
if(lifetime > 11)
return true;
return false;
}
// The emitter class stuff
Emitter::Emitter(int amount, int x, int y, string particleImage, string emitterImage){
// Seed the time for random emitter
srand(SDL_GetTicks());
// Set up the variables and create the particles
x = y = xVel = yVel = 0;
particles.resize(amount, Particle(x, y, particleImage));
emitterScreen = Image::loadImage(emitterImage);
particleImg = particleImage;
}
Emitter::~Emitter(){
particles.clear();
}
void Emitter::move(){
}
void Emitter::show(){
// Show the dot image.
Image::applySurface(x, y, emitterScreen, gameScreen);
}
void Emitter::showParticles(){
// Go through all the particles
for(vector<Particle>::size_type i = 0; i != particles.size(); i++){
if(particles[i].isDead() == true){
particles.erase(particles.begin() + i);
particles.insert(particles.begin() + i, Particle(x, y, particleImg));
}
}
// And show all the particles
for(vector<Particle>::size_type i = 0; i != particles.size(); i++){
particles[i].show();
}
}
Also here is the Splash Class and the Splash Header.
The second option should work, and I would start looking at compilation errors to see why it doesn't. In fact, please post any compilation errors you have related to this code.
In the meantime, you can do something like this:
class Splash{
private:
Emitter* ps;
public:
Splash() { ps = new Emitter(100,200,400); }
Splash(const Splash& copy_from_me) { //you are now responsible for this }
Splash & operator= (const Splash & other) { //you are now responsible for this}
~Splash() { delete ps; }
};
Well, I managed to fix it, in a hackish way though. What I did was create a default constructor, and move my normal Constructor code into a new function. Then I created the object and called the the new init function to set everything up.