Welcome, Guest. Please login or register. Did you miss your activation email?

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Topics - Ant

Pages: [1]
1
Network / Nonblocking Tcp Socket Status is Never sf::Socket::Done
« on: August 19, 2021, 09:56:30 am »
I'm running into problems with nonblocking Tcp sockets where the client is unable to receive the sf::Socket::Done status despite that the server accepting the connection. After the server accepts the connection, the client's socket status becomes NotReady.

Server minimal example:
#include <chrono>
#include <iostream>
#include <SFML/Network.hpp>
#include <thread>

int main()
{
        std::cout << "Starting server\n";

        unsigned long updateRate = 30;

        sf::TcpListener listen;
        listen.setBlocking(false);
        if (listen.listen(2011) != sf::Socket::Done)
        {
                std::cout << "Failed to listen at port 2011\n";
                return -1;
        }

        std::cout << "Listening on port 2011\n";

        sf::TcpSocket client;
        client.setBlocking(false);
        while (true)
        {
                if (listen.accept(client) == sf::Socket::Done)
                {
                        break;
                }

                //simulate work
                std::this_thread::sleep_for(std::chrono::milliseconds(updateRate));
        }

        std::cout << "Connected... waiting for packet\n";
        sf::Packet packet;
        while (true)
        {
                sf::Socket::Status status = client.receive(packet);
                if (status == sf::Socket::Done)
                {
                        int num;
                        packet >> num;
                        std::cout << "Received data. " << num << " \n";
                        break; //TODO: loop a couple times to check if receiving multiple data.
                }
               
                //Simulate work
                std::this_thread::sleep_for(std::chrono::milliseconds(updateRate));
        }

        std::cout << "Disconnecting server.\n";
        client.disconnect();
        return 0;
}

Server output:
Starting server
Listening on port 2011
Connected... waiting for packet
 


Client minimal example:
#include <chrono>
#include <iostream>
#include <SFML/Network.hpp>
#include <thread>

int main()
{
        std::cout << "Starting client\n";

        unsigned long updateRate = 30;
        sf::TcpSocket client;
        client.setBlocking(false);

        while (true)
        {
                sf::Socket::Status status = client.connect(sf::IpAddress("127.0.0.1"), 2011);
                if (status == sf::Socket::Done)
                {
                        break;
                }

                //Simulate work
                std::this_thread::sleep_for(std::chrono::milliseconds(updateRate));
        }

        std::cout << "Connected... sending packet\n";
        sf::Packet packet;
        while (true)
        {
                int num = 456;
                packet << num;

                sf::Socket::Status status = client.send(packet);
                if (status == sf::Socket::Done)
                {
                        std::cout << "Sent data. " << num << " \n";
                        break;
                }
               
                //Simulate work
                std::this_thread::sleep_for(std::chrono::milliseconds(updateRate));
        }

        std::cout << "Disconnecting client.\n";
        client.disconnect();
        return 0;
}

Client output:
Starting client

When I set the client's socket to blocking (server remains unblocking), then it proceeds as expected.
Server output
Starting server
Listening on port 2011
Connected... waiting for packet
Received data. 456
Disconnecting server.

Client output
Starting client
Connected... sending packet
Sent data. 456
Disconnecting client.

This is tested on Windows 10.
I'm using SFML version 2.5.1.

I will continue looking into this, and I'll post anything I identified in my investigation.

2
Window / Hitching and Crashing with multiple sf::Window handles
« on: June 05, 2020, 11:17:58 pm »
I've been experiencing hitches with sf::Window::pollEvents function. Most of the time, the application can run smoothly (over 100 fps). But every few seconds, the app hitches on this function.

    Stopwatch pollEventsStopwatch;

    int counter = 0;

    sf::Event sfEvent;
    while (Resource != nullptr && Resource->pollEvent(sfEvent))
    {
        counter++;

        //Do stuff in this loop, but this loop is never iterating since there aren't any events.
    }

    FLOAT elapsedTime = pollEventsStopwatch.GetElapsedTime();
    if (elapsedTime > 50)
    {
        int breakHere = 0; //<----  I'm hitting this breakpoint since elapsed time is usually above 150 milliseconds even when counter is 0.
    }
 

I've been struggling with this for awhile. The best theory I have is maybe because there many window handles in this application. The application I have is basically runs multiple unit tests so it pops up about five windows on a thread. And to test this theory, I closed all but one of the windows. And it seems to never hit that break point when it's down to one window handle.

I tried moving one of the tests to its own thread, but by doing so, I'm running into a new issue where creating a new window handle on the separate thread causes an infinite recursion crash.

//Other stuff here. Let me know if you want me to post the full context of this function.

PrimaryWindow = Window::CreateObject();
PrimaryWindow->SetResource(new sf::RenderWindow(sf::VideoMode(800, 600), PROJECT_NAME)); //<---- crashes here
 

Callstack crash:
....
        sfml-window-d-2.dll!`anonymous namespace'::getInternalContext() Line 159        C++
        sfml-window-d-2.dll!sf::priv::GlContext::ensureContext() Line 217       C++
        sfml-window-d-2.dll!sf::GlResource::GlResource() Line 61        C++
        sfml-window-d-2.dll!sf::Context::Context() Line 61      C++
        sfml-window-d-2.dll!`anonymous namespace'::getInternalContext() Line 159        C++
        sfml-window-d-2.dll!sf::priv::GlContext::ensureContext() Line 217       C++
        sfml-window-d-2.dll!sf::GlResource::GlResource() Line 61        C++
        sfml-window-d-2.dll!sf::Context::Context() Line 61      C++
        sfml-window-d-2.dll!`anonymous namespace'::getInternalContext() Line 159        C++
        sfml-window-d-2.dll!sf::priv::GlContext::ensureContext() Line 217       C++
        sfml-window-d-2.dll!sf::GlResource::GlResource() Line 61        C++
        sfml-window-d-2.dll!sf::Context::Context() Line 61      C++
....
 

While reading through docs and forums, I learned about sf::Window::setActive. Although I call setActive(true) during the draw/render stage, it did not seem to make a difference. Then I started calling setActive(false) everywhere (after creating sf::RenderWindow, before render calls, before pollEvents, etc...). I know that's not the right way of doing things, but I was hoping it would at least 'lock' the windows instead of crashing whenever I create a window handle on a different thread.

I've did this for sf::RenderTextures, too. And I'm still crashing whenever I create a window handler on the other thread.


And here I am currently stuck. I'm running SFML version 2.4.0. I suppose I can upgrade it to a later version in case there was a bug fix for this.


Questions I have are:
1. Any idea why polling events sometimes take over 150 milliseconds even though there aren't any events?

2. When do I need to call setActive on a window handle? Can it only be activated before calling clear, draw, display functions? Or do I need to activate the window handles when polling events, too? I presume the same should be done for sf::RenderTextures, too.

3. Any idea what could be causing the infinite recursion crash? If the windows are self contained in their own threads, is it possible to handle windows and render textures in multiple threads if setActive is called appropriately?

3
Graphics / Transformation Order Problem
« on: June 16, 2018, 03:33:47 am »
I apologies for the long winded topic.  I got stuck on a problem for a few days, and I think what would help me is to write the situation somewhere to straighten my thoughts.


The problem is that I misinterpreted the origin attribute for transformable objects.

I interpreted that the origin was the spot where whenever you call setPosition, the origin will be placed at that pixel location.
By default, it's the top left corner.  Setting the origin would shift the rendered object.  This would allow the dev to easily center a sprite over a specified position.
Scale and rotation by seems to work fine, too.  It rotates about the origin, and it scales relative to the origin.


My issue is introduced when I tried to apply all three transforms for a test game (Solitaire).
I'm setting a card's origin to the middle to allow it to spin around its center.
I'm setting the center's position equal to the center of a specific spot.
Lastly, the sprite is scaled by 50%.  Here I'm expecting the card's borders to squeeze closer to the origin equally.

Although the card gets smaller, the position is 'shifted' from desired location.  I've attached a screenshot to help visualize the scenario.  I've also disabled spinning to simplify the problem.
Looking at the 9 of spades, there's a card outline to the top left of it.  That's the desired location.
CardSize.X = 90
Pivot = CardSize * 0.5  (Pivot.X = 90/2 => 45)
Position.X = 8 + Pivot   (53) <--- The intention is to place the center of the card at the center of the outline.
Size = 0.5
Result Position of top left corner of card (X-axis) = 31     ((-Pivot.X*0.5) + Position.X)  <-- The 0.5 is coming from size
Expected Position of top left corner of card (X-axis) = 8   (-Pivot.X + Position.X)

The easiest solution is to simply adjust the position, but that would weaken my internal usage behind origin where the origin is always at the location where setPosition is specified.
My objective is that when I call SetPosition on an object, the origin of that object is found at that location regardless of scale and rotation.

I've considered a handful of hacky solutions, but I'm too embarrassed to bring them up.

-----------------------------------

Edit:  I sat on my post for a few hours before publishing it.  Writing it down did help me understand the problem.  It's an order of operation error.  It's applying origin shift, scaling, then translating when I need to scale, shift it, then translate it.

For the example above (looking at left border X coordinate of sprite):
Actual:
Absolute Pos = 0
Apply Origin Shift (45)
Absolute Pos = -45
Apply scaling (0.5)
Absolute Pos = -22.5
Apply translation (53)
Absolute Pos = 31

Needed:
Absolute Pos = 0
Apply scale (0.5)
Absolute Pos = 0   <--- but the card is half size
Apply translation (53)
Absolute Pos = 53
Apply Origin Shift (45)
Absolute Pos = 8

Perhaps changing my setPosition setOrigin setSize calls with using a sf::Transform object may help resolve my issue.  I'll give this a try, and I'll post again.  I decided to make this post anyways in case others are running into similar problems.

4
System / basic_string<Unsigned Char> to basic_string<char> for UTF-8
« on: January 07, 2017, 07:13:58 am »
Ever since Microsoft announced that they added support Unicode literals in Visual Studio 2015, I've been slowly replacing my wide strings with UTF-8 basic strings.
https://msdn.microsoft.com/en-us/library/hh409293.aspx

I ran into an issue with std::basic_string<unsigned char>
With std::basic_string<unsigned char> (instead of  std::basic_string<char>) I lose some functionality to interact with std.  For example, I can't do this:
std::basic_string<unsigned char> something;
std::cout << something << std::endl; //error here
 

The sf::String::toUtf8 function returns std::basic_string<Uint8> which is results to std::basic_string<unsigned char>

Here's an example of an issue I'm running into:
void LogIt (const std::string& log)
{
        std::cout << log;
        OutputDebugString(log.c_str());
}

void LogIt (const std::basic_string<unsigned char>& log)
{
        //Need to convert basic_string<sf::Uint8> to string<char>
}

void DoStringTest ()
{
        //Value of string copied from:  http://en.cppreference.com/w/cpp/locale/wstring_convert/from_bytes
        std::string utf8String = u8"z\u00df\u6c34\U0001d10b \n";
        std::string normalString = "z\u00df\u6c34\U0001d10b \n"; //invalid chars and compiler warnings
        std::basic_string<char> utf8Basic = u8"z\u00df\u6c34\U0001d10b \n";
        std::basic_string<char> normalBasic = "z\u00df\u6c34\U0001d10b \n"; //invalid chars and compiler warnings

        sf::String sfString = utf8String;
        //std::string something = sfString.toUtf8(); //error
        std::basic_string<sf::Uint8> fromSF = sfString.toUtf8();

        LogIt(utf8String); //produces "zÃ...." The remaining characters cannot be displayed in this forum post.
        LogIt(utf8Basic); //produces "zÃ...." The remaining characters cannot be displayed in this forum post.
        LogIt(sfString); //produces "zÃ...." The remaining characters cannot be displayed in this forum post.
        LogIt(fromSF); //Goes to overloaded function with param std::basic_string<unsigned char>
}
 
Compiled in Microsoft Visual Studio 2015 Update 1
Using SFML version 2.4.0.

I'm not sure if I should have created a feature request to have that function return a std::basic_string<char> instead, or I should look at this problem at a different angle.

Thanks for your help.

5
SFML website / Custom Avatar Is Not Accepted
« on: December 18, 2016, 11:20:34 am »
I've been trying to change my avatar to use an image from my Dropbox account.  However when I hit 'Change Profile' button in the profile settings I receive a 'Your profile has been updated successfully.' message at the top, but the avatar radio button reset back to 'No Avatar'.

I've tried the following resolutions in jpg:
596x357
512x512
128x128
32x32


What are the rules for a custom avatar via URL?
Is there a min/max size?
Is there an enforced aspect ratio?

Thanks for your help in advance.

6
Feature requests / Check if Shader Parameter Exists
« on: July 08, 2016, 10:12:45 am »
I think having the capability to check which uniform(s) exists on a Shader may help reduce the amount of micromanagement.  For example, I can create a wrapper of sf::Shader, and that wrapper can check for specific uniform names and act accordingly.  If the uniform named 'GlobalTime' or 'DeltaTime' exists on shader, I can have the shader wrapper automatically update those variables every frame.  It gets trickier when I need to associate a texture mask that's based on the current animation frame.  Having this functionality implemented in a wrapper class may reduce the need of external objects updating every shader they instanced.

I'm requesting for a bool CheckParamExists function defined in the sf::Shader class.

7
Feature requests / Friendly string mapping to Keyboard::Key
« on: October 23, 2015, 07:10:32 am »
This is a minor request, and is not urgent at all.

I think it'll be beneficial to have a vector of strings or char* that corresponds to the Keyboard::Key enumerator.  I don't plan to use this for comparison but rather for presentation.

Having this will allow me to log more meaningful debugging messages (rather than logging indices), and this could also be used to present to the user when binding controls.

8
Window / Get Window Position
« on: April 03, 2015, 08:29:54 pm »
Hello,

I feel like I'm overlooking something.  I need a way to get the window's position without the title bar.

The Window::getPosition function returns the upper left corner of the window's title bar, but I need the upper left corner of the rendered content within the window.

9
Graphics / Text character size documentation
« on: March 08, 2015, 07:39:48 pm »
Hello,

I would like to request for further information on the Text class's character size.  I've read up the documentation from:
http://www.sfml-dev.org/documentation/2.0/classsf_1_1Text.php

Unfortunately, the description of the character size functions did not provide the answer I was searching for.  What is the character size measuring?  Vertical length of a character (if so, what's the difference between font's line spacing and this)?  Horizontal length of a character (if so, how does it handle characters such as "l" and "M")?

Thanks for your consideration.

10
Graphics / Highlighting Text
« on: January 02, 2015, 03:25:45 am »
Hello,

I'm designing a text field where the user can position a cursor in a middle of a text field, and select chunks of text to copy or overwrite the selected text.

One of my concerns with my plans is rendering the highlighted text.  A solution I thought of is having 3 instanced sf::Text (One Text contains the text before the highlight, the second contains the highlighted text with inverted colors, and the third is the text after the highlighted part).  Then I'll was thinking about drawing rectangles (one for each selected line) to represent the highlighted part.

This method sounds slower than it needs to be, and it seems strange to pass characters from one Text instance to another whenever the user is dragging the mouse.  I was curious if there was a better way of doing this.  Does this seem to be the right approach?

11
General / Error Handling
« on: September 10, 2014, 07:08:23 am »
I was curious about the error handling system for SFML.  For example, SFML may be unable to import an image if an artist specifies incorrect parameters.  When that happens, I would like to display a meaningful message to them.  I did read an old post about this topic...
http://en.sfml-dev.org/forums/index.php?topic=4643.0

I am curious if there are any news about error handling since that post.  If not, are there any plans for displaying error messages?

Thanks for the support!

-Ant

12
Graphics / sf::Text::getText Heap Crash
« on: July 17, 2014, 05:57:04 am »
Hello,

I've spent the last few days investigating this crash, but I'm finding myself traveling in circles now.
I'm running into a heap crash when I call sf::Text::getText()
std::string stdString = text.getString();

Here's the crash message I'm running into:
Quote
Program: ...s\visual studio 2013\Projects\TextTest\x64\Debug\TextTest.exe
File: f:\dd\vctools\crt\crtw32\misc\dbgheap.c
Line: 1424

Expression: _pFirstBlock == pHead

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

(Press Retry to debug the application)

I'm using Visual Studio 2013 Express.
This crash only occurs in debug.
This happens in 32bit and 64bit.
I'm using the latest stable version SFML 2.1 for Visual Studio 2012 64bit.


#include <SFML/Graphics.hpp>

int main()
{
        sf::Font font;
        if (!font.loadFromFile("TheanoModern-Regular.ttf"))
        {
                return 0;
        }

    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");

        sf::Text text;
       
        text.setFont(font);
        text.setString(L"Hello World.\0");
        std::string stdString = text.getString(); //crashes here

    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }

        window.clear();
        window.draw(text);
        window.display();
    }

    return 0;
}

Let me know if you need any further information.
Thank you in advance for your help!

Pages: [1]
anything