SFML draws nothing from another thread, and can SFML coexist with GDI? - c++

I'm writing a SFML test application with MFC. The following code runs inside an infinite loop in another thread started by AfxBeginThread() function. (Because I want to use SFML like it's in a pure WinAPI application)
// SFML Window and View were initialized using CView's HWND
// Use SFML to draw
sf::Color back(255, 255, 0); // a yellow background
_psfwnd->clear(back);
_psfwnd->display();
// Then use MFC GDI functions to draw
CWnd* pwnd;
pwnd = CWnd::FromHandle(_psfwnd->getSystemHandle()); // It seems that the HWND is valid
CPaintDC dc(pwnd);
CRect r(10, 10, 100, 100);
CBrush b(0xFF000000);
dc.FillRect(&r, &b); // draw a black rectangle
The result is a white background with a black rectangle. It seems that SFML draws nothing but MFC does.
Same code above. Now I put it into a MFC command handler (so the above code draws one frame when I click a button once).
This time the window background is yellow and MFC black rectangle is gone.
Now I am quite confused. I have two questions:
Why SFML doesn't draw the first time? It's because of threading, or initialization?
Why MFC doesn't draw when SFML does?

Don't use CPaintDC. It is specialized for use only in a WM_PAINT message handler. You can use CClientDC instead.

Related

MFC Draw Stuff Outside OnPaint in a Dialog-based App

I'm currently trying to draw something outside OnPaint function. I know there are many duplicate questions on the internet, however, I failed to get any of them to work. This is entirely because of my lack of understanding of MFC.
What works inside OnPaint:
CDC* pDC = GetDC();
HDC hDC = pDC->GetSafeHdc();
CRect lDisplayRect;
GetDlgItem(IDC_DISPLAYPOS)->GetClientRect(&lDisplayRect);
GetDlgItem(IDC_DISPLAYPOS)->ClientToScreen(&lDisplayRect);
ScreenToClient(&lDisplayRect);
pDC->FillSolidRect(&lDisplayRect, GetSysColor(COLOR_3DDKSHADOW));
pDC->TextOutW(300, 300, TEXT("test"));
It fills the area of the button control I have with a defined colour.
And it prints out the "test" string without any issue.
But it won't work outside OnPaint.
I've seen numerous suggestions such as using CmemDC,CPaintDC, etc
But none of them worked outside OnPaint.
For example,
CClientDC dc(this);
dc.rectangle( ....);
does not work.
Please note that this is a temporary test code and what I am eventually trying to do is draw incoming frames from a frame grabber within my display thread (a separate thread from the main UI thread) on the DisplayPos area and my dlg object(the dialog) owns an instance of the DisplayThread class. And I'm passing HWND and displayrect upon creating the member mDisplayThread so I can draw stuff within the display thread and that's the reason why I need to be able to draw to DC outside OnPaint (DisplayThread class does not have OnPaint or inherit any class that has it).
I'm in dire need of help...Please help!
Added: I have overridden PreTranslateMessage(MSG* pMsg) and made it return without calling the default function just in case WM_ERASE msg is erasing everything, but this approach didn't work either.
For example:
void CMFCApplicationDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
HDC hdc = ::GetDC(m_hWnd);
Ellipse(hdc, point.x - 10, point.y - 10, point.x + 10, point.y + 10);
::ReleaseDC(m_hWnd, hdc);
CDialogEx::OnLButtonDown(nFlags, point);
}
Two important suggestions:
Do not draw outside of OnPaint. The content may be erased or painted over at the direction of OS.
Do not draw on the dialog surface. First, it is not designed for that. It may be affected by other controls or by theming, skinning, etc. Just create a window with your own window procedure, so you are in control.
I would store the information needed for drawing in you frame grabber, and cause an immediate window painting by calling RedrawWindow

Draw button on top of ImageList videos in C++ with winapi

I'm having trouble drawing a button on top of a video with WinAPI. I am grabbing frames from the webcam and drawing those frames as soon as I get them. The problem is that whenever I draw an image the button disappears under it.
I tried using SetWindowPos(button, HWND_TOPMOST, 50, 50, 50, 50, SWP_SHOWWINDOW); to place the button at the topmost of the z-order but it still doesn't work.
The image is drawn on top of the button and this is a required behavior. I want the image to be as big as possible (taking the whole monitor).
I thought maybe I should make a part of the image transparent (the part over the button). Is that an easy solution and how should I go about doing that.
You can add WS_CLIPSIBLINGS style to the button ,
Clips child windows relative to each other; that is, when a particular
child window receives a WM_PAINT message, the WS_CLIPSIBLINGS style
clips all other overlapping child windows out of the region of the
child window to be updated. If WS_CLIPSIBLINGS is not specified and
child windows overlap, it is possible, when drawing within the client
area of a child window, to draw within the client area of a
neighboring child window.
Refer this case: https://stackoverflow.com/a/56470706/11128312

How can I draw around a rectangle?

I'm using openGL to draw some animation.
I want to draw the animation in an area around a rectangle.
That rectangle are should be transparent, to show whatever windows happen to be there, and leave that to regular windows MFC drawings.
I know there should be away to do it with clipping. But since whatever is in that rectangle isn't drawn with the openGL I'm not sure that will work well.
I'm using openGL with c++.
Solution:
If you are drawing over unrelated windows, you should use Stencil buffer.
This can be used as a masking layer to decide where you want to draw.
If you have an MFC window with a child window, you can create the "father" window with the following style: WS_CLIPCHILDREN

How do I clear a Direct2D render target to fully transparent

I'm trying to draw semi-transparent rectangles on an invisible HWND. However, clearing the window with ID2D1HwndRenderTarget::Clear just makes the entire window black, so when I draw rectangles on top, they look semi-black.
If I don't Clear() and don't draw, then the window is invisible, as it should be. Clear() is the culprit here; however if I don't use it then painting messes up pretty badly.
Here's the code I'm using in my WindowProc:
case WM_PAINT:
// Begin drawing
pRenderTarget->BeginDraw();
pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
// Clear the window
pRenderTarget->Clear();
// Paint the panel and its children
D2DSurface()->StartPainting();
{
D2DSurface()->PaintTraverse(panel);
}
D2DSurface()->FinishPainting();
// Finish drawing
HRESULT hr = plat->pRenderTarget->EndDraw();
Thanks in advance!
Transparency is a problem. The only window that support per-pixel transparency are WS_EX_LAYERED windows. These windows were designed for uses like drag-drop icons, and that leads to problems in every other usage.
Using D2D with WS_EX_LAYERED windows requires that you use a DXGI render target. To EndDraw, you get a DC out of the render target then pass that into the layered window and tell the layered window to update itself. (Try this with a HWNDRenderTarget - it will probably crash the device driver).
I suspect your window appears transparent because it's not drawing at all.
Another gotcha you may run into... if the window is sufficiently transparent, mouse clicks will go through it to the underlying window.
Use ID2D1DCRenderTarget instead of ID2D1HwndRendTarget, then bind the device context (DC) of your window before drawing begins.
Of course, you will need to set the WS_EX_LAYERED for your window and then call SetLayeredWindowAttributes to set the transparent color:
SetLayeredWindowAttributes(hWnd, RGB(0, 0, 0), 0, LWA_COLORKEY);
Screenshot:
When creating your RenderTarget, you'll have to tell D2D that you want to use alpha (in premultiplied mode) in the pixel format:
HRESULT hr = mD2DFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat( DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED ) ),
D2D1::HwndRenderTargetProperties( mWindow, size ),
&mRenderTarget );
After this, calling Clear() with an alpha value of zero works just fine.

Transparent child control

I'm writing a control that may have some of its parts transparent or semitransparent. Basically this control shows a png image (with alpha channel). The control's parent window has some graphics on it. Therefore, to make the png control render correctly it needs to get image of what the parent window would draw beneath it. Parent dialog might have WS_CLIPCHILDREN flag set, that means that the the parent window won't draw anything under the the png control and in this case png control won't work properly.
This control has to work on Windows Mobile also, so it can't have WS_EX_TRANSPARENT
Funny you should ask. I just wrote code to do this yesterday. It's in the code base for Project Resistance. Look at how ResistorView (which has a PNG with transparency) interacts with MainForm (which has the background image).
I'm not doing c#, so I don't think that could be helpful. I tried to look into your code and I don't see anything that can solve my problem even though you accomplish the same task as me.
To give more details, my control also supports gif animation and I also used the same IImage load from stream as you do in your project. From my experience, that IImage load from stream is unbelievable junk code, it's extremely slow. I have no idea how that possibly could be so slow. Loading 32x32 gif with 31 frames takes like 1.5secods using that junk IImage stuff. I wrote my own loader (using some opensource gif library) and without any optimization entire decoding/loading of the gif frames takes less than 100ms. I'm using TouchPro2... I can't imagine how badly this code would perform on a low end device.
As a quick alternative here's a possible solution to my question:
in the WM_PAINT handler of the child control that draws images (gif or png) I do the following:
first, I call SetRedraw(false) on self and on parent window.
then I hide the child control, and send WM_PAINT to parent window with optional HDC (as wParam). The parent window renders everything to the offscreen bitmap (passed via hdc to WM_PAINT) and after WM_PAINT successfully returns I take relevant part of the offscreen bitmap.
Then I enable show the child window and call SetRedraw(true) on both child and the parent window. That trick works but has some disadvantages obviously (I need to createa huge offscreen bitmap to capture entire screen area even though I need 32x32 pixel from the middle of parent window).
the code is below:
bool pic_control::get_parent_bg(MyBitmap & bg)
{
CWindow parent = GetParent();
CClientDC dc(parent);
bool is_visible = IsWindowVisible() && parent.IsWindowVisible();
if(!is_visible){
return false;
}
parent.SetRedraw(false);
SetRedraw(false);
CRect rect;
parent.GetClientRect(rect);
MyBitmap bmp;
bmp.create(rect.Width(), rect.Height());
ShowWindow(SW_HIDE);
parent.SendMessage(WM_PAINT, (WPARAM)(HDC)bmp.dc());
ShowWindow(SW_SHOW);
GetWindowRect(rect);
parent.ScreenToClient(rect);
bg.create(rect.Width(), rect.Height());
bg.dc().BitBlt(0, 0, rect.Width(), rect.Height(), bmp.dc(), rect.left, rect.top, SRCCOPY);
IF_DEBUG SAL::saveHBITMAPToJpeg(bg.GetBitmap(), "frames/BG.jpg", 100);
SetRedraw(true);
parent.SetRedraw(true);
return true;
}
WS_CLIPCHILDREN is forced on in WinCe, you cannot toggle it. I dont know why, maybe it is done for performance reasons.
From my experience what i did in this situation.
1) If the parent window bacgkround is dynamic (for instance window that contains map, which can be moved), then it is painted to memory canvas first, then to the screen, and memory canvas is saved and used for painting transparent childs. Memory canvas would not contain holes in place of child windows, so it can be used for futher pixel merge. The disadvantage here is memory consumption to hold canvas in memory.
2) If parent window background is static (dialog box, menu, etc) then you can make non-window childs.
class CImageButton
{
public:
bool IsPointInside(POINT pt);
void OnPaint(HDC canvas);
void OnClick();
void SetRect(RECT& rc);
private:
RECT m_rc;
};
Your parent window will contain an array of such objects and redirect WM_PAINT and
mouse clicks to them.
The disavantage is additional code needed to be added to parent window, but you can make a base class for all your parent windows, which would handle issues with non-windowed controls.