Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ==++ Here is the full source code (file 1/1) of "bow and arrow.cpp":: ++==
- ```bow and arrow.cpp
- // BowAndArrow.cpp
- // Simple Win32 / Direct2D demo - "wireframe longbow"
- // Build: cl /EHsc /DUNICODE /D_UNICODE BowAndArrow.cpp d2d1.lib user32.lib gdi32.lib
- #include <windows.h>
- #include <d2d1.h>
- #include <chrono>
- #include <cmath>
- #include <algorithm>
- #pragma comment(lib, "d2d1")
- // -------------------------------------------------
- // Small RAII helper to release COM objects
- // -------------------------------------------------
- template<class T> void SafeRelease(T** pp)
- {
- if (*pp) { (*pp)->Release(); *pp = nullptr; }
- }
- // -------------------------------------------------
- // Animation constants
- // -------------------------------------------------
- constexpr float COCK_TIME = 1.0f; // seconds
- constexpr float HOLD_TIME = 0.5f; // seconds
- constexpr float FIRE_TIME = 1.0f; // seconds
- constexpr UINT TIMER_ID = 1;
- constexpr UINT TIMER_MS = 16; // ~60 FPS
- enum class AnimStage { Cocking, Hold, Firing, Done };
- constexpr float ARROW_REST_OFFSET = 500.0f; // pixels in-front of bow ( > 0 )
- // String pull distance (pixels) and bow X center
- constexpr float STRING_MAX_PULL = 180.0f;
- constexpr float CX_BOW = 220.0f;
- // -------------------------------------------------
- // Global state (kept simple for a demo)
- // -------------------------------------------------
- HWND g_hWnd = nullptr;
- ID2D1Factory* g_pFactory = nullptr;
- ID2D1HwndRenderTarget* g_pRenderTarget = nullptr;
- ID2D1SolidColorBrush* g_pBrush = nullptr;
- float g_windowW = 1280.0f;
- float g_windowH = 720.0f;
- // Modify g_arrowPosX initialization to start off-screen at the top
- float g_arrowPosX = CX_BOW; // Will be properly positioned in animation update
- // Add these with other global variables
- float g_arrowPosY = 0.0f; // Variable for arrow's vertical position
- float g_arrowRotation = 0.0f; // Rotation angle in radians
- // Geometry helpers (depend on window height, so they are updated in WM_SIZE)
- float cx = CX_BOW;
- float topY = 120.0f;
- float bottomY = 600.0f; // will be overwritten in WM_SIZE
- float midY = 360.0f;
- float halfHeight = 240.0f;
- // Animation variables
- AnimStage g_stage = AnimStage::Cocking;
- float g_timeInStage = 0.0f; // seconds
- auto g_prevTick = std::chrono::high_resolution_clock::now();
- float g_stringOffset = 0.0f; // 0 = relaxed, 1 = fully drawn
- //float g_arrowPosX = 0.0f; // head position
- // -------------------------------------------------
- // Helpers
- // -------------------------------------------------
- float Lerp(float a, float b, float t) { return a + (b - a) * t; }
- // Create or re-create render target
- HRESULT CreateDeviceResources()
- {
- if (g_pRenderTarget) return S_OK;
- RECT rc; GetClientRect(g_hWnd, &rc);
- D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left,
- rc.bottom - rc.top);
- HRESULT hr = g_pFactory->CreateHwndRenderTarget(
- D2D1::RenderTargetProperties(),
- D2D1::HwndRenderTargetProperties(g_hWnd, size),
- &g_pRenderTarget);
- if (SUCCEEDED(hr))
- hr = g_pRenderTarget->CreateSolidColorBrush(
- D2D1::ColorF(D2D1::ColorF::White), &g_pBrush);
- return hr;
- }
- void DiscardDeviceResources()
- {
- SafeRelease(&g_pBrush);
- SafeRelease(&g_pRenderTarget);
- }
- // -------------------------------------------------
- // Core rendering
- // -------------------------------------------------
- void OnRender()
- {
- if (FAILED(CreateDeviceResources()))
- return;
- g_pRenderTarget->BeginDraw();
- g_pRenderTarget->Clear(D2D1::ColorF(0x202020)); // dark bg
- // -------------------------------------------------
- // 1. Draw Bow limbs (two quadratic curves)
- // -------------------------------------------------
- ID2D1PathGeometry* pGeom = nullptr;
- ID2D1GeometrySink* pSink = nullptr;
- if (SUCCEEDED(g_pFactory->CreatePathGeometry(&pGeom)))
- {
- pGeom->Open(&pSink);
- //--------------------------------------------------------------
- // One continuous ")"-shaped limb with a slightly pointy tip.
- // End-points stay on the string ( (cx, topY) & (cx, bottomY) )
- //--------------------------------------------------------------
- constexpr float NOSE = 35.0f; // how far the tips stick out
- const float BULGE = halfHeight * 0.5f; // max belly distance (x)
- pSink->BeginFigure(D2D1::Point2F(cx, topY), D2D1_FIGURE_BEGIN_HOLLOW);
- // Draw semicircle bow with pointy tip at middle
- // First quarter - top to middle-top
- pSink->AddBezier(
- D2D1::BezierSegment(
- D2D1::Point2F(cx + NOSE, topY + halfHeight * 0.1f), // slight curve at top
- D2D1::Point2F(cx + BULGE, topY + halfHeight * 0.5f), // first quarter curve
- D2D1::Point2F(cx + BULGE + NOSE, midY - NOSE))); // approaching tip
- // Middle part with pointy tip
- pSink->AddBezier(
- D2D1::BezierSegment(
- D2D1::Point2F(cx + BULGE + NOSE * 1.2f, midY - NOSE * 0.5f), // curve to tip
- D2D1::Point2F(cx + BULGE + NOSE * 1.5f, midY), // pointy tip
- D2D1::Point2F(cx + BULGE + NOSE * 1.2f, midY + NOSE * 0.5f))); // curve from tip
- // Last quarter - middle-bottom to bottom
- pSink->AddBezier(
- D2D1::BezierSegment(
- D2D1::Point2F(cx + BULGE + NOSE, midY + NOSE), // after tip
- D2D1::Point2F(cx + BULGE, bottomY - halfHeight * 0.5f), // last quarter curve
- D2D1::Point2F(cx + NOSE, bottomY - halfHeight * 0.1f))); // approaching bottom
- // Connect back to string
- pSink->AddBezier(
- D2D1::BezierSegment(
- D2D1::Point2F(cx + NOSE * 0.5f, bottomY - NOSE * 0.25f), // curve to bottom
- D2D1::Point2F(cx, bottomY), // bottom endpoint
- D2D1::Point2F(cx, bottomY))); // dummy point (required)
- pSink->EndFigure(D2D1_FIGURE_END_OPEN);
- pSink->Close();
- g_pRenderTarget->DrawGeometry(pGeom, g_pBrush, 2.0f);
- SafeRelease(&pSink);
- SafeRelease(&pGeom);
- }
- // -------------------------------------------------
- // 2. Draw Bow string
- // -------------------------------------------------
- float pull = g_stringOffset * STRING_MAX_PULL;
- D2D1_POINT_2F p1 = D2D1::Point2F(cx, topY);
- D2D1_POINT_2F pm = D2D1::Point2F(cx - pull, midY);
- D2D1_POINT_2F p2 = D2D1::Point2F(cx, bottomY);
- g_pRenderTarget->DrawLine(p1, pm, g_pBrush, 2.0f);
- g_pRenderTarget->DrawLine(pm, p2, g_pBrush, 2.0f);
- // Replace the OnRender arrow drawing section with this to use variable Y position
- // Replace the OnRender arrow drawing section with this to use variable Y position and rotation
- // Replace the OnRender arrow drawing section with this to use variable Y position and rotation
- // -------------------------------------------------
- // 3. Draw Arrow (simple shaft + head + tail)
- // -------------------------------------------------
- float arrowLen = 240.0f;
- float arrowHead = 18.0f;
- // Apply rotation to the arrow
- g_pRenderTarget->SetTransform(
- D2D1::Matrix3x2F::Rotation(
- g_arrowRotation * (180.0f / 3.14159f), // Convert radians to degrees
- D2D1::Point2F(g_arrowPosX, g_arrowPosY)
- )
- );
- // Shaft
- g_pRenderTarget->DrawLine(
- D2D1::Point2F(g_arrowPosX, g_arrowPosY),
- D2D1::Point2F(g_arrowPosX - arrowLen, g_arrowPosY),
- g_pBrush, 2.0f);
- // Arrow head (small triangle)
- D2D1_POINT_2F headPts[3] = {
- D2D1::Point2F(g_arrowPosX, g_arrowPosY),
- D2D1::Point2F(g_arrowPosX - arrowHead, g_arrowPosY - arrowHead * 0.5f),
- D2D1::Point2F(g_arrowPosX - arrowHead, g_arrowPosY + arrowHead * 0.5f)
- };
- g_pRenderTarget->DrawLine(headPts[0], headPts[1], g_pBrush, 2.0f);
- g_pRenderTarget->DrawLine(headPts[0], headPts[2], g_pBrush, 2.0f);
- // Fletching (3 short diagonal lines)
- const float fletch = 20.0f;
- const float step = 5.0f;
- // Top fletching
- for (int i = 0; i < 6; ++i)
- {
- float x = g_arrowPosX - arrowLen + i * step;
- g_pRenderTarget->DrawLine(
- D2D1::Point2F(x, g_arrowPosY),
- D2D1::Point2F(x - fletch, g_arrowPosY - fletch * 0.4f + i * 3.0f),
- g_pBrush, 2.0f);
- }
- // Bottom fletching
- for (int i = 0; i < 6; ++i)
- {
- float x = g_arrowPosX - arrowLen + i * step;
- g_pRenderTarget->DrawLine(
- D2D1::Point2F(x, g_arrowPosY),
- D2D1::Point2F(x - fletch, g_arrowPosY + fletch * 0.4f - i * 3.0f),
- g_pBrush, 2.0f);
- }
- // Reset transform for other drawing operations
- g_pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity());
- // Present
- HRESULT hr = g_pRenderTarget->EndDraw();
- if (hr == D2DERR_RECREATE_TARGET)
- DiscardDeviceResources();
- }
- // -------------------------------------------------
- // Animation tick (called from WM_TIMER)
- // -------------------------------------------------
- // Replace the UpdateAnimation function with this updated version
- // Replace the UpdateAnimation function with this updated version
- void UpdateAnimation()
- {
- // Compute delta time
- auto now = std::chrono::high_resolution_clock::now();
- float dt = std::chrono::duration<float>(now - g_prevTick).count();
- g_prevTick = now;
- g_timeInStage += dt;
- switch (g_stage)
- {
- case AnimStage::Cocking:
- {
- float t = min(g_timeInStage / COCK_TIME, 1.0f);
- if (t < 0.6f) {
- // First part: arrow dropping from top with tail pointing down
- float arcT = t / 0.6f; // Normalize to 0-1 for just this part
- // Starting position at top, end at bow position
- float startX = cx + 100.0f; // Start slightly right of bow
- float startY = 0.0f; // Start at top of screen
- float endX = cx + 50.0f; // End to the right of bow
- float endY = midY - 50.0f; // End slightly above midpoint
- // Calculate curved path
- g_arrowPosX = Lerp(startX, endX, arcT);
- g_arrowPosY = Lerp(startY, endY, arcT * arcT); // Accelerate down
- // Arrow has tail pointing down (pointing up = -90 degrees = -PI/2)
- g_arrowRotation = -1.57079f + arcT * 1.07079f; // -PI/2 to close to 0
- }
- else if (t < 0.8f) {
- // Second part: arrow rotates to horizontal and moves into position
- float alignT = (t - 0.6f) / 0.2f; // Normalize to 0-1 for just this part
- // Move arrow into position horizontally
- float startX = cx + 50.0f;
- float startY = midY - 50.0f;
- float endX = cx + 50.0f; // Position just right of the bow
- float endY = midY; // At the midpoint height
- g_arrowPosX = Lerp(startX, endX, alignT);
- g_arrowPosY = Lerp(startY, endY, alignT);
- // Complete the rotation to horizontal
- g_arrowRotation = Lerp(-0.5f, 0.0f, alignT); // Finish rotating to horizontal
- }
- else {
- // Third part: arrow attaches to string and string gets pulled
- float stringT = (t - 0.8f) / 0.2f; // Normalize to 0-1 for just this part
- // Move arrow with string as it's drawn back
- float startX = cx + 50.0f;
- float endX = cx - STRING_MAX_PULL + 50.0f;
- g_arrowPosX = Lerp(startX, endX, stringT);
- g_arrowPosY = midY;
- g_arrowRotation = 0.0f; // Keep horizontal
- // Pull string back gradually
- g_stringOffset = stringT;
- }
- if (t >= 1.0f) { g_stage = AnimStage::Hold; g_timeInStage = 0.f; }
- } break;
- case AnimStage::Hold:
- // Arrow is now at the correct position
- g_arrowPosY = midY;
- g_arrowRotation = 0.0f; // Ensure arrow is horizontal
- if (g_timeInStage >= HOLD_TIME)
- {
- g_stage = AnimStage::Firing; g_timeInStage = 0.f;
- }
- break;
- case AnimStage::Firing:
- {
- float t = min(g_timeInStage / FIRE_TIME, 1.0f);
- g_stringOffset = 1.0f - t; // 1 -> 0 (same)
- float startX = cx - STRING_MAX_PULL + 50.0f;
- float endX = g_windowW + 100.0f;
- g_arrowPosX = Lerp(startX, endX, t);
- g_arrowPosY = midY; // Keep arrow on straight horizontal path
- g_arrowRotation = 0.0f; // Keep arrow horizontal
- if (t >= 1.0f)
- {
- g_stage = AnimStage::Cocking; g_timeInStage = 0.f;
- // Reset arrow to starting position for next animation cycle
- g_arrowPosX = cx + 100.0f;
- g_arrowPosY = 0.0f;
- g_arrowRotation = -1.57079f; // Start with tail pointing down (arrow pointing up)
- }
- } break;
- case AnimStage::Done:
- // Not used anymore, but kept for completeness
- break;
- }
- // Request redraw
- InvalidateRect(g_hWnd, nullptr, FALSE);
- }
- // -------------------------------------------------
- // Window procedure
- // -------------------------------------------------
- LRESULT CALLBACK WndProc(HWND hWnd, UINT msg,
- WPARAM wParam, LPARAM lParam)
- {
- switch (msg)
- {
- // Add this initialization in WM_CREATE or before animation starts
- // Add to WM_CREATE case or main initialization
- // Add this initialization in WM_CREATE case
- case WM_CREATE:
- if (FAILED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED,
- &g_pFactory)))
- return -1; // abort window creation
- SetTimer(hWnd, TIMER_ID, TIMER_MS, nullptr);
- g_prevTick = std::chrono::high_resolution_clock::now();
- g_arrowPosX = cx + 100.0f; // Initialize right of bow
- g_arrowPosY = 0.0f; // Initialize at top of screen
- g_arrowRotation = -1.57079f; // Start with tail pointing down (arrow pointing up)
- return 0;
- case WM_SIZE:
- {
- g_windowW = static_cast<float>(LOWORD(lParam));
- g_windowH = static_cast<float>(HIWORD(lParam));
- // Update dependent geometry values
- topY = 120.0f;
- bottomY = g_windowH - 120.0f;
- midY = (topY + bottomY) * 0.5f;
- halfHeight = (bottomY - topY) * 0.5f;
- if (g_pRenderTarget)
- g_pRenderTarget->Resize(
- D2D1::SizeU(static_cast<UINT>(g_windowW),
- static_cast<UINT>(g_windowH)));
- }
- return 0;
- case WM_TIMER:
- if (wParam == TIMER_ID)
- UpdateAnimation();
- return 0;
- case WM_PAINT:
- {
- PAINTSTRUCT ps;
- BeginPaint(hWnd, &ps);
- OnRender();
- EndPaint(hWnd, &ps);
- } return 0;
- case WM_DESTROY:
- KillTimer(hWnd, TIMER_ID);
- DiscardDeviceResources();
- SafeRelease(&g_pFactory);
- PostQuitMessage(0);
- return 0;
- }
- return DefWindowProc(hWnd, msg, wParam, lParam);
- }
- // -------------------------------------------------
- // WinMain - entry point
- // -------------------------------------------------
- int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmdShow)
- {
- const wchar_t CLASS_NAME[] = L"BowWindow";
- WNDCLASS wc = {};
- wc.lpfnWndProc = WndProc;
- wc.hInstance = hInst;
- wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
- wc.lpszClassName = CLASS_NAME;
- RegisterClass(&wc);
- g_hWnd = CreateWindowEx(0, CLASS_NAME, L"Direct2D - Longbow Demo",
- WS_OVERLAPPEDWINDOW,
- CW_USEDEFAULT, CW_USEDEFAULT,
- static_cast<int>(g_windowW),
- static_cast<int>(g_windowH),
- nullptr, nullptr, hInst, nullptr);
- ShowWindow(g_hWnd, nCmdShow);
- // Main message loop
- MSG msg;
- while (GetMessage(&msg, nullptr, 0, 0))
- {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
- return 0;
- }
- ```
Advertisement
Add Comment
Please, Sign In to add comment