alien_fx_fiend

Mario-SideScroller D2D-Platformer-Demo

May 30th, 2025
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.85 KB | Source Code | 0 0
  1. ++== Here's the full source code for (file 1/1) of "D2d-Platform-Demo.cpp"::: ++==
  2. ```D2d-Platform-Demo.cpp
  3. // ------------------------------------------------------------------
  4. // Super-Tiny Side-Scroller Demo  (Win32 + Direct2D + Memory-DC)
  5. //   cl main.cpp /EHsc /DUNICODE /DWIN32_LEAN_AND_MEAN /Zi /MD
  6. //       d2d1.lib windowscodecs.lib
  7. // ------------------------------------------------------------------
  8. #define NOMINMAX
  9. #include <windows.h>
  10. #include <d2d1.h>
  11. #include <cmath>
  12. #include <algorithm>
  13.  
  14. #pragma comment(lib, "d2d1.lib")
  15.  
  16. template<class T> inline void SafeRelease(T*& p) { if (p) { p->Release(); p = nullptr; } }
  17.  
  18. constexpr float GRAVITY = 2000.0f;
  19. constexpr float JUMP_VELOCITY = -700.0f;
  20. constexpr float MOVE_SPEED = 300.0f;
  21. constexpr UINT  TIMER_ID = 1;            // ~60 Hz
  22.  
  23. struct Entity
  24. {
  25.    float x{}, y{}, w{}, h{}, vx{}, vy{};
  26.    bool  alive{ true };
  27.    D2D1_RECT_F RectF() const { return D2D1::RectF(x, y, x + w, y + h); }
  28. };
  29.  
  30. Entity player{ 50, 200, 30, 30 };
  31. Entity platform{ 200, 300,180, 20 };
  32. Entity enemy{ 550, 270, 30, 30, 60, 0 };
  33.  
  34. float cameraX = 0.f;
  35. bool  keyLeft = false, keyRight = false, keyJump = false;
  36.  
  37. // current bottom-of-world (client-height) – initialised to default 480,
  38. // updated each time the window is resized
  39. float g_worldH = 480.0f;
  40.  
  41. // ------------------------------------------------------------------
  42. // D2D / GDI globals
  43. // ------------------------------------------------------------------
  44. ID2D1Factory* g_pFactory = nullptr;
  45. ID2D1DCRenderTarget* g_pRT = nullptr;
  46. ID2D1SolidColorBrush* g_pBrush = nullptr;
  47.  
  48. HDC     g_hMemDC = nullptr;
  49. HBITMAP g_hMemBmp = nullptr;
  50. SIZE    g_back{};
  51.  
  52. // ------------------------------------------------------------------
  53. // Back-buffer + render target
  54. // ------------------------------------------------------------------
  55. void CreateBackBuffer(HDC wndDC, int w, int h)
  56. {
  57.    if (w == 0 || h == 0) return;
  58.  
  59.    if (g_hMemBmp) DeleteObject(g_hMemBmp);
  60.    if (!g_hMemDC) g_hMemDC = CreateCompatibleDC(wndDC);
  61.  
  62.    BITMAPINFO bi{};
  63.    bi.bmiHeader.biSize = sizeof(bi.bmiHeader);
  64.    bi.bmiHeader.biWidth = w;
  65.    bi.bmiHeader.biHeight = -h;        // top-down
  66.    bi.bmiHeader.biPlanes = 1;
  67.    bi.bmiHeader.biBitCount = 32;
  68.    bi.bmiHeader.biCompression = BI_RGB;
  69.  
  70.    g_hMemBmp = CreateDIBSection(wndDC, &bi, DIB_RGB_COLORS, nullptr, nullptr, 0);
  71.    SelectObject(g_hMemDC, g_hMemBmp);
  72.    g_back = { w,h };
  73.  
  74.    if (!g_pRT)                                   // first creation
  75.    {
  76.        D2D1_RENDER_TARGET_PROPERTIES props =
  77.            D2D1::RenderTargetProperties(
  78.                D2D1_RENDER_TARGET_TYPE_DEFAULT,
  79.                // *** EXPLICIT BGRA 32-bit format (fix) ***
  80.                D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,
  81.                    D2D1_ALPHA_MODE_PREMULTIPLIED));
  82.        if (SUCCEEDED(g_pFactory->CreateDCRenderTarget(&props, &g_pRT)))
  83.            g_pRT->CreateSolidColorBrush(
  84.                D2D1::ColorF(D2D1::ColorF::White), &g_pBrush);
  85.    }
  86. }
  87.  
  88. // ------------------------------------------------------------------
  89. // Physics / game update
  90. // ------------------------------------------------------------------
  91. inline bool Intersect(const Entity& a, const Entity& b)
  92. {
  93.    return a.x<b.x + b.w && a.x + a.w>b.x &&
  94.        a.y<b.y + b.h && a.y + a.h>b.y;
  95. }
  96.  
  97. void GameUpdate(float dt)
  98. {
  99.    player.vx = 0;
  100.    if (keyLeft)  player.vx -= MOVE_SPEED;
  101.    if (keyRight) player.vx += MOVE_SPEED;
  102.  
  103.    static bool prevJump = false;
  104.    if (keyJump && !prevJump &&
  105.        std::abs(player.vy) < 0.01f &&
  106.        player.y + player.h >= platform.y - 1)
  107.        player.vy = JUMP_VELOCITY;
  108.    prevJump = keyJump;
  109.  
  110.    player.vy += GRAVITY * dt;
  111.    player.x += player.vx * dt;
  112.    player.y += player.vy * dt;
  113.  
  114.    if (player.vy > 0 &&
  115.        player.y + player.h >= platform.y &&
  116.        player.x + player.w > platform.x &&
  117.        player.x < platform.x + platform.w)
  118.    {
  119.        player.y = platform.y - player.h; player.vy = 0;
  120.    }
  121.  
  122.    //if (player.y + player.h > 480) { player.y = 480 - player.h; player.vy = 0; }
  123.        // collide with *current* bottom of the window
  124.        if (player.y + player.h > g_worldH)
  125.         {
  126.        player.y = g_worldH - player.h;
  127.        player.vy = 0;
  128.        }
  129.  
  130.    if (enemy.alive)
  131.    {
  132.        enemy.x += enemy.vx * dt;
  133.        if (enemy.x < 530) { enemy.x = 530; enemy.vx = std::abs(enemy.vx); }
  134.        if (enemy.x > 650) { enemy.x = 650; enemy.vx = -std::abs(enemy.vx); }
  135.    }
  136.  
  137.    if (enemy.alive && Intersect(player, enemy))
  138.    {
  139.        bool stomp = player.vy > 0 && player.y + player.h - enemy.y < 15;
  140.        if (stomp) { enemy.alive = false; player.vy = JUMP_VELOCITY * 0.75f; }
  141.        else { player = { 50,200,30,30 }; }
  142.    }
  143.  
  144.    cameraX = std::max(0.f, player.x - 320.f);
  145. }
  146.  
  147. // ------------------------------------------------------------------
  148. // Rendering
  149. // ------------------------------------------------------------------
  150. void GameRender()
  151. {
  152.    if (!g_pRT) return;                   // guard
  153.  
  154.    RECT rc = { 0,0,g_back.cx,g_back.cy };
  155.    g_pRT->BindDC(g_hMemDC, &rc);
  156.  
  157.    g_pRT->BeginDraw();
  158.    g_pRT->Clear(D2D1::ColorF(0.08f, 0.10f, 0.15f));
  159.  
  160.    auto draw = [&](const Entity& e, D2D1::ColorF c)
  161.    {
  162.        g_pBrush->SetColor(c);
  163.        g_pRT->FillRectangle(
  164.            D2D1::RectF(e.x - cameraX, e.y,
  165.                e.x - cameraX + e.w, e.y + e.h),
  166.            g_pBrush);
  167.    };
  168.  
  169.    draw(platform, D2D1::ColorF(0.6f, 0.4f, 0.2f));
  170.    if (enemy.alive) draw(enemy, D2D1::ColorF(0.9f, 0.2f, 0.2f));
  171.    draw(player, D2D1::ColorF(0.2f, 0.7f, 1.0f));
  172.  
  173.    // ---------- handle device-loss / recreate-target ----------
  174.    HRESULT hr = g_pRT->EndDraw();
  175.    if (hr == D2DERR_RECREATE_TARGET)
  176.    {
  177.        SafeRelease(g_pRT);
  178.        SafeRelease(g_pBrush);
  179.    }
  180. }
  181.  
  182. // ------------------------------------------------------------------
  183. // Window procedure
  184. // ------------------------------------------------------------------
  185. LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM w, LPARAM l)
  186. {
  187.    switch (msg)
  188.    {
  189.    case WM_CREATE:
  190.        D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &g_pFactory);
  191.        return 0;
  192.  
  193.    case WM_SIZE:
  194.    {
  195.        int wdt = LOWORD(l), hgt = HIWORD(l);
  196.        HDC hdc = GetDC(hWnd);
  197.        CreateBackBuffer(hdc, wdt, hgt);
  198.        ReleaseDC(hWnd, hdc);
  199.  
  200.        static bool timerStarted = false;
  201.        if (!timerStarted && g_pRT)
  202.        {
  203.            SetTimer(hWnd, TIMER_ID, 16, nullptr); timerStarted = true;
  204.        }        
  205.            // update game-world height so the player can't fall below view
  206.             g_worldH = static_cast<float>(hgt);
  207.     } return 0;
  208.  
  209.     case WM_KEYDOWN: case WM_KEYUP:
  210.     {
  211.         bool down = (msg == WM_KEYDOWN);
  212.         switch (w)
  213.         {
  214.         case VK_LEFT:  keyLeft = down; break;
  215.         case VK_RIGHT: keyRight = down; break;
  216.         case VK_SPACE: keyJump = down; break;
  217.         }
  218.     } return 0;
  219.  
  220.     case WM_TIMER:
  221.     {
  222.         static LARGE_INTEGER fq{}, prev{};
  223.         if (!fq.QuadPart)
  224.         {
  225.             QueryPerformanceFrequency(&fq); QueryPerformanceCounter(&prev);
  226.         }
  227.  
  228.         LARGE_INTEGER now; QueryPerformanceCounter(&now);
  229.         float dt = float(now.QuadPart - prev.QuadPart) / fq.QuadPart;
  230.         prev = now;
  231.  
  232.         GameUpdate(dt);
  233.         InvalidateRect(hWnd, nullptr, FALSE);
  234.     } return 0;
  235.  
  236.     case WM_PAINT:
  237.     {
  238.         PAINTSTRUCT ps;
  239.         HDC hdc = BeginPaint(hWnd, &ps);
  240.         GameRender();
  241.         if (g_hMemDC)
  242.             BitBlt(hdc, 0, 0, g_back.cx, g_back.cy,
  243.                 g_hMemDC, 0, 0, SRCCOPY);
  244.         EndPaint(hWnd, &ps);
  245.     } return 0;
  246.  
  247.     case WM_DESTROY:
  248.         KillTimer(hWnd, TIMER_ID);
  249.         PostQuitMessage(0);
  250.         return 0;
  251.     }
  252.     return DefWindowProc(hWnd, msg, w, l);
  253. }
  254.  
  255. // ------------------------------------------------------------------
  256. // Entry point
  257. // ------------------------------------------------------------------
  258. int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmd)
  259. {
  260.     WNDCLASSEX wc{ sizeof wc };
  261.     wc.hInstance = hInst;
  262.     wc.lpfnWndProc = WndProc;
  263.     wc.lpszClassName = L"SideScrollerWnd";
  264.     wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
  265.     RegisterClassEx(&wc);
  266.  
  267.     HWND hWnd = CreateWindowEx(0, L"SideScrollerWnd",
  268.         L"Mini Side-Scroller (D2D + GDI)",
  269.         WS_OVERLAPPEDWINDOW,
  270.         CW_USEDEFAULT, CW_USEDEFAULT, 800, 480,
  271.         nullptr, nullptr, hInst, nullptr);
  272.  
  273.     ShowWindow(hWnd, nCmd);
  274.     UpdateWindow(hWnd);
  275.  
  276.     MSG msg;
  277.     while (GetMessage(&msg, nullptr, 0, 0) > 0)
  278.     {
  279.         TranslateMessage(&msg); DispatchMessage(&msg);
  280.     }
  281.  
  282.     SafeRelease(g_pBrush);
  283.     SafeRelease(g_pRT);
  284.     SafeRelease(g_pFactory);
  285.     if (g_hMemBmp) DeleteObject(g_hMemBmp);
  286.     if (g_hMemDC)  DeleteDC(g_hMemDC);
  287.     return 0;
  288. }
  289. ```
Advertisement
Add Comment
Please, Sign In to add comment