MegaSteve/Graphics.cpp

114 lines
2.6 KiB
C++

module;
#include <d2d1.h>
#include <wrl/client.h>
#include <wincodec.h>
#include <cassert>
module Graphics;
using namespace D2D1;
using namespace ::Microsoft::WRL;
constexpr D2D1_RECT_F SteveRect{ 1678,2,1766,96 };
ComPtr<ID2D1HwndRenderTarget> Graphics::RT = nullptr;
ComPtr<IWICImagingFactory> Graphics::wic_factory = nullptr;
Vector2 Graphics::RtSize{};
//ComPtr<IWICImagingFactory> Graphics::wic_factory = nullptr;
void Graphics::Init(HWND hwnd)
{
ComPtr<ID2D1Factory> Factory = nullptr;
auto hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, Factory.GetAddressOf());
assert(hr == S_OK);
RECT rc;
GetClientRect(hwnd, &rc);
hr = Factory->CreateHwndRenderTarget(
RenderTargetProperties(),
HwndRenderTargetProperties(hwnd, SizeU(rc.right-rc.left, rc.bottom-rc.top)),
&RT
);
assert(hr == S_OK);
RtSize = { (FLOAT)(rc.right - rc.left), (FLOAT)(rc.bottom - rc.top) };
hr = CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&wic_factory)
);
assert(hr == S_OK);
}
void Graphics::BeginDraw()
{
RT->BeginDraw();
}
void Graphics::Clear()
{
RT->Clear({ .r = 0.96862745f, .g = 0.96862745f, .b = 0.96862745f, .a = 1.0f });
}
void Graphics::Present()
{
RT->EndDraw();
}
void Graphics::Finalize()
{
}
void Graphics::DrawBitMap(const ComPtr<ID2D1Bitmap>& bitmap, D2D_RECT_F dst, D2D_RECT_F src)
{
if (!bitmap) return;
dst.top = RtSize.y - dst.top;
dst.bottom = RtSize.y - dst.bottom;
RT->DrawBitmap(bitmap.Get(), dst, 1.0f, D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, src);
}
ComPtr<ID2D1Bitmap> Graphics::LoadImageFromFile(LPCWSTR uri)
{
ComPtr<ID2D1Bitmap> img = nullptr;
ComPtr<IWICBitmapDecoder> decoder = nullptr;
ComPtr<IWICBitmapFrameDecode> source = nullptr;
ComPtr<IWICFormatConverter> converter = nullptr;
auto hr = wic_factory->CreateDecoderFromFilename(
uri,
nullptr,
GENERIC_READ,
WICDecodeMetadataCacheOnLoad,
&decoder
);
assert(hr == S_OK);
hr = decoder->GetFrame(0, &source);
assert(hr == S_OK);
hr = wic_factory->CreateFormatConverter(&converter);
assert(hr == S_OK);
hr = converter->Initialize(
source.Get(),
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
assert(hr == S_OK);
hr = RT->CreateBitmapFromWicBitmap(
converter.Get(),
nullptr,
&img
);
assert(hr == S_OK);
return img;
}