Failed to load font in SFML C++ on other computers - c++

I am making an SFML project using Visual Studio, and I have an error when sharing it with other people (works fine on my computer).
Basically they get the error
Failed to load font "../fonts/BalooPaaji2.ttf" (failed to create the font face)
So I tried to uninstall the font in my OS fonts and only keep it in the project itself, and everything still works fine for me.
I though it was maybe a directory problem but if so why would the .exe file work fine for me and not other people ?
Here is the code of my write function:
void write(sf::RenderWindow& window, std::string t1, sf::IntRect rect) {
//load font
sf::Font font;
font.loadFromFile("../fonts/BalooPaaji2.ttf");
//create the text element
sf::Text text(t1, font);
text.setStyle(sf::Text::Bold);
text.setFillColor(sf::Color(0,0,0,150));
//size and place the text element according to the space available, this is specific of my project (and probably could be optimized) so you can skip this part
text.setCharacterSize(rect.height/2);
sf::FloatRect textRect = text.getLocalBounds();
text.setOrigin(textRect.left + textRect.width / 2.0f, textRect.top + textRect.height / 2.0f);
text.setPosition(sf::Vector2f(rect.left + rect.width/2, rect.top + rect.height / 2));
if (t1 == "Play") {
text.setPosition(sf::Vector2f(rect.left + rect.width / 2, rect.top + rect.height / 1.8));
}
window.draw(text);
}
My structure looks like that:
I don't have any clues of where this problem could come from, any help will be appreciated and feel free to ask for more information you could need.

Related

Alt+Enter in Win32 apps, manage resizing and resolution

I'm struggling with resizing and full screen mode of my project. This is what I'm working on Mandelbrot in a Pixel Shader and here on GIT https://github.com/ShamanLKG/Mandelbrot
The app crashes when Alt+Enter is pressed and I don't understand why.
case WM_SIZE:
{
int width = LOWORD(lParam); // Macro to get the low-order word.
int height = HIWORD(lParam); // Macro to get the high-order word.
pThis->D3D->OnResize(width, height);
pThis->D3D = std::shared_ptr<Direct3D>(new Direct3D(hWnd, width, height));
pThis->D2D = std::shared_ptr<Direct2D>(new Direct2D(hWnd, pThis->D3D));
break;
}
I recreated the Direct3d and Direct2 objects on resize to solve issues with the navigation and to adjust the resolution of the window. But impossible so far to get the full screen working. The full screen works without recreating the D3D and D2D object but then I'm stucked with the original resolution and the navigation does not work properly. I use the OnResize() function from MSDN (https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/d3d10-graphics-programming-guide-dxgi#handling-window-resizing). I tried passing on a BOOL argument to InitD3D to tell the program if the swapchain is full screen or not from swapchain->GetFullScreenState but it did not help.
The navigation works as long at the window size is not changed, then it's not precise. Adjusting the yDelta with the change in screen ratio helps, but only when the window width is changed. It becomes again unstable when the window height is changed. So as workaround I recreated the D3D and D2D object to start with fresh parameters and having a function navigation. But as a result the full screen now crashes.
void Direct3D::CenterScreen(int xPos, int yPos)
{
//float ratio = startRatio / currentRatio;
int xDelta = xPos - width / 2;
int yDelta = (yPos - height / 2); //could divide by ratio to capture window width change
realStart += (float)xDelta / (float)width * 2 * mandelWidth;
imagStart += (float)yDelta / (float)height * 2 * mandelHeight;
}
Any clue how I could solve these issues? Many thanks in advance.
Found the error, the Direct2D resources were not released causing the ResizeBuffers to fail with code 0x887A0001. The tutorial from https://bell0bytes.eu/fullscreen/ has been very helpful.
hr = swapchain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
Lesson of the day, have a robust error handling system.

Has SDL2.0 SetRenderDrawColor and TTF_RenderUNICODE_Blended memory issues?

I have a work-related C/C++ SDL 2.0 project - originally developed and compiled on Win7 computer for x86 platform (With MS Visual Studio) that was working fine for the whole time. Since the program was meant to run also at newer Win10 x64 devices, I moved the entire solution to a newer Win10 x64 computer, changed all SDL2 libraries, header files etc. for the x64 version and rebuilt the solution for x64 architecture.
The program is basically an advanced diagnostic screen with dials, icons and text information, so it uses variety of colors, fonts, geometry etc.
After the recompilation for x64 platform, I noticed that the colors of some elements are absolutely off. For example - a rectangle that should be grey (used SDL_SetRenderDrawColor one step before drawing the rect.) is suddenly green, despite its given grey RGB numbers as input arguments. Even the function SDL_GetRenderDrawColor called before and/or after drawing of the rectangle returns values 195, 195, 195, but the rectangle is shown green.
Rectangle drawing function:
void DrawRectangle(SDL_Color color, int pozX, int pozY, int width, int height)
{
SDL_Rect Proportions = { pozX, pozY, width, height };
SDL_SetRenderDrawColor(gRenderer, color.r, color.g, color.b, 0xFF);
SDL_RenderFillRect(gRenderer, &Proportions);
}
Rectangle drawing call:
DrawRectangle(grey, pocpozX, 182, width, height);
Later I have noticed that this rectangle inherits its color from a text rendered a few steps earlier. If I change the color of this text, it for some strange reason applies also for the rectangle.
Text drawing function:
void DrawText(std::wstring text, TTF_Font *font, int pozX, int pozY, SDL_Color color)
{
typedef std::basic_string<Uint16, std::char_traits<Uint16>, std::allocator<Uint16> > u16string;
std::wstring text_sf_str = text;
u16string utext_sf_str(text_sf_str.begin(), text_sf_str.end());
SDL_Surface* text_sf = TTF_RenderUNICODE_Blended(font, utext_sf_str.c_str(), color);
SDL_Texture* text_Tx = SDL_CreateTextureFromSurface(gRenderer, text_sf);
int text_TxW;
int text_TxH;
SDL_QueryTexture(text_Tx, NULL, NULL, &text_TxW, &text_TxH);
SDL_Rect textrect = { pozX, pozY, text_TxW, text_TxH };
SDL_RenderCopy(gRenderer, text_Tx, NULL, &textrect);
SDL_FreeSurface(text_sf);
SDL_DestroyTexture(text_Tx);
}
Notice all these conversions needed to display a wstring text with some uncommonly used UNICODE characters. I don't quite understand why SDL needs to be passed each character as Uint16 number, this could have been done better. I also don't understand the need of using SDL_QueryTexture just in order to display the text proportions right. I would expect the user to want to display the text not anyhow stretched by default. This all seems to me unnecessarily complicated.
Funny thing is, that if I remove SDL_DestroyTexture tag, there is of course a huge memory leak, but the problem disappears.
Text drawing call - in a for loop, this draws numeric labels onto speedometer axis:
if (i % 20 == 0)
{
if (i <= 160)
{
DrawText(str2, font, posX, posY, grey);
}
else
{
DrawText(str2, font, posX, posY, green);
}
}
... And this very "green" as the last argument of the call is what causes the rectangle to be green also - despite the fact that more elements are drawn between this text and rectangle so SDL_SetRenderDrawColor is called multiple times.
I have also noticed that some shown numbers are for a little while glitching some senseless values every n-th second, so I guess this is a memory-related problem. Of course there are more color problems, this was just for an example. Due to company policy, I cannot be more specific or post the full code here.
If I switch back to x86 configuration (with the right libraries of course), the problem now remains the same.

Why do I get a different behviour in Codename One simulator than on a real Android device?

I am trying to figure out why I get a different behaviour in the simulator (iPhone, Nexus, Nexus5, ... skins ) VS on an Android real device with the following code (my goal is to draw a text over a background image and save the whole in background image resolution) :
Please note that the GUI was done with the Designer.
protected void beforeMain(Form f) {
// The drawing label will contain the whole photo montage
f.setLayout(new LayeredLayout());
final Label drawing = new Label();
f.addComponent(drawing);
String nom = "Hello World";
// Image mutable dans laquelle on va dessiner (fond blancpar défaut)
// synthe is an Image
Image mutableImage = Image.createImage(synthe.getWidth(), synthe.getHeight());
drawing.getUnselectedStyle().setBgImage(mutableImage);
drawing.getUnselectedStyle().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);
// Draws over the background image and put all together on the mutable image.
paintSyntheOnBackground(mutableImage.getGraphics(),
synthe,
nom,
synthe.getWidth(),
synthe.getHeight());
long time = new Date().getTime();
OutputStream os;
try {
os = Storage.getInstance().createOutputStream("screenshot_" + Long.toString(time) + ".png");
ImageIO.getImageIO().save(mutableImage, os, ImageIO.FORMAT_PNG, 1.0f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // end of beforeMain
And here is the method I call to draw a text over an image
public void paintSyntheOnBackground(Graphics g,
Image synthe,
final String pNom,
int width, int height) {
Font myFont = g.getFont();
g.setFont(myFont);
int w = myFont.stringWidth(pNom);
int h = myFont.getHeight();
// Added just to see the background
g.setColor(0x0000FF);
g.fillRect(0, 0, width, height);
g.setColor(0xff0000);
int x = g.getTranslateX() + width / 2 - w / 2;
int y = g.getTranslateY() + height / 2 - h / 2;
g.drawRect(x, y, w, h);
g.drawString(pNom, x, y);
} // end of paintSyntheOnBackground
Here is the outcome on the simulator (GoogleNexus7) :
And here is the outcome on the device (Android 4.4) :
My development system features Eclipse on Linux with Codename One V3-4.
I know the simulator cannot reproduce specific case, but here there is nothing special isn't it ? What can I do to make the behaviour on the simulator reflect the real behaviour since it would be much handier to test in the simulator ?
EDIT : After upgrading each of my CN1 project libs from version 114 to 115 (see this question for details on how to do the upgrade), I am now able to get the same behaviour in both simulator and device! Great bug fixing job CN1 team!
Please note : In my case (Eclipse - Linux) I had to upgrade the project libs in each and every Codename One project.
Any help would be greatly appreciated!
Cheers,
This was a really annoying bug that we just fixed now so it can make it to today's release.
The problem only occurs when drawing on a mutable image in a case where the simulator is in scale mode both of which we don't do often as scale mode is less accurate and mutable images are generally slower.
Thanks for keeping up with this.

Window resizing and scaling images / Redeclaring back buffer size / C++ / DIRECTX 9.0

C++ / Windows 8 / Win api / DirectX 9.0
I am having real big issues with this:
https://github.com/jimmyt1988/TheGame/tree/master/TheGame
Problem is that I have defined some adjust coordinate functions. They are for when a window is resized and I need to offset all of my coordinates so that my mouse cooridnates are working out the correct collisions and also to scale and yet keep ratio locked for the images I am drawing to the screen.
For example, If I had a screen at 1920 x 1080 and then resized to 1376 x 768, I need to make sure that the bounding boxes for my objects (for when my mouse hovers over them) is adjusted on the mouse coordinates I use to use to check if the mouse was in the bounding box.
I found out that I originally had problems because when I resized my window, directX was automatically scaling everything.. and on top of that, I too was rescaling things, so they would get utterly screwed... I was told by someone that I need to re-declare my screen buffer width and height, which I have done keeping in mind there is a border to my window and also a menu at the top.
Can anyone see why... regardless of doing all this stuff, I am still getting the incorrect results.
If you manage to run my application: Pressing the 1 key will make the resolution 1920 x 1080, pressing the 2 key will make it 1376 x 768. The resize is entirely wrong: https://github.com/jimmyt1988/TheGame/blob/master/TheGame/D3DGraphics.cpp
float D3DGraphics::ResizeByPercentageChangeX( float point )
{
float lastScreenWidth = screen.GetOldWindowWidth();
float currentScreenWidth = screen.GetWindowWidth();
if( lastScreenWidth > currentScreenWidth + screen.GetWidthOffsetOfBorder() )
{
float percentageMoved = currentScreenWidth / lastScreenWidth;
point = point * percentageMoved;
}
return point;
}
float D3DGraphics::ResizeByPercentageChangeY( float point )
{
float lastScreenHeight = screen.GetOldWindowHeight();
float currentScreenHeight = screen.GetWindowHeight();
if( lastScreenHeight > currentScreenHeight + screen.GetHeightOffsetOfBorderAndMenu() )
{
float percentageMoved = currentScreenHeight / lastScreenHeight;
point = point * percentageMoved;
}
return point;
}
and yet if you put the return point above this block of code and just do nothing to it, it scales perfectly because of blooming directX regardless of this which is being called correctly (presparams are previously declared in the D3DGraphics construct and a reference held in the class its self:
void D3DGraphics::ResizeSequence()
{
presParams.BackBufferWidth = screen.GetWindowWidth() - screen.GetWidthOffsetOfBorder();
presParams.BackBufferHeight = screen.GetWindowHeight() - screen.GetHeightOffsetOfBorderAndMenu();
d3dDevice->Reset( &presParams );
}
This is the problem at hand:
Here is the code that makes this abomination of a rectangle:
void Game::ComposeFrame()
{
gfx.DrawRectangle( 50, 50, screen.GetWindowWidth() - screen.GetWidthOffsetOfBorder() - 100, screen.GetWindowHeight() - screen.GetHeightOffsetOfBorderAndMenu() - 100, 255, 0, 0 );
}
EDIT::::::::::::::::
I noticed that On MSDN it says:
Before calling the IDirect3DDevice9::Reset method for a device, an
application should release any explicit render targets, depth stencil
surfaces, additional swap chains, state blocks, and D3DPOOL_DEFAULT
resources associated with the device.
I have now released the vbuffer and reinstantiated it after the presparams and device are reset.
EDIT::::::::::::
I placed an HRESULT on my reset in which I now manage to trigger an error... But, well.. it doesn't really help me! : http://i.stack.imgur.com/lqQ5K.jpg
Basically, the issue was I was being a complete derp. I was putting into my rectangle the window width and then readjusting that size based on the oldwidth / newwidth.. well the new width was already the screen size... GRRRRRRR.

GLFW get screen height/width?

Playing around with OpenGL for a while, using the freeglut library, I decided that I will use GLFW for my next training project instead, since I was told that GLUT was only designed for learning purposes and should not be used professionally. I had no problems with linking the lib to my NetBeans project and it compiles just fine, using mingw32 4.6.2.
However, I am running into difficulties trying to position the window at the center of the screen.
Under freeglut, I previously used:
glutInitWindowPosition (
(glutGet(GLUT_SCREEN_WIDTH)-RES_X) / 2,
(glutGet(GLUT_SCREEN_HEIGHT)-RES_Y) / 2
);
I can't find any glfw function that would return the screen size or width. Is such a function simply not implemented?
How about glfwGetDesktopMode, I think this is what you want.
Example:
GLFWvidmode return_struct;
glfwGetDesktopMode( &return_struct );
int height = return_struct.Height;
For GLFW they use glfwGetVideoMode, which has a different call but the return structure can be used in the same way.
first you need two variables to store your width and height.
int width, height;
then as described on page 14 of the reference.
glfwSetWindowPos(width / 2, height / 2);
and as a bonus you can then call
glfwGetWindowSize(&width, &height);
this a void function and does not return any value however it will update the two previously declared variables.. so place it in the mainloop or the window reshape callback function.
you can verify this in the official manual here on page 15.
This might help somebody...
void Window::CenterTheWindow(){
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
glfwSetWindowPos(m_Window, (mode->width - m_Width) / 2, (mode->height - m_Height) / 2);
}
m_Width and m_Height are variables that have the width and the height of the window.
Reference: http://www.glfw.org/docs/latest/monitor.html