Advertisement
alien_fx_fiend

Infinite Doodle Canvas Direct2D MultiVariant BrushSizes Fixed

Mar 27th, 2025 (edited)
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 32.54 KB | Source Code | 0 0
  1. Next fixes will include following Speed Optimizations (Stay Tuned !):
  2. Performance Boost: Scene graph optimizations, bitmap caching, and dirty region optimizations. AND ALSO True Infinite Canvas: No fixed size limits, supports seamless scrolling. AND ALSO Optimized Panning: Uses Direct2D transformation matrices for smooth, hardware-accelerated panning. AND ALSO Faster Panning: Optimized with scene graph transformations instead of pixel shifting.
  3.  
  4. ==++ Here's the full source code for (file 1/1) "D2D-Doodle.cpp"::: ++==
  5. ```D2D-Doodle.cpp
  6. #define NOMINMAX
  7. #define WIN32_LEAN_AND_MEAN
  8.  
  9. #include <windows.h>
  10. #include <windowsx.h>
  11. #include <commctrl.h>
  12. #include <commdlg.h>
  13. #include <d2d1.h>
  14. #include <dwrite.h>
  15. #include <string>  // add if not already included
  16. #include <cmath>
  17. #include <vector>
  18. #include <mutex>
  19. #include <fstream>
  20. #include <thread>
  21. #include <algorithm>
  22. #include "resource.h"
  23.  
  24. #pragma comment(lib, "d2d1.lib")
  25. #pragma comment(lib, "comctl32.lib")
  26.  
  27. //----------------------------------------------------------------
  28. // Data Structures and Globals
  29. //----------------------------------------------------------------
  30.  
  31. struct DrawPoint {
  32.    int x, y;
  33.    DWORD timestamp;
  34.    DrawPoint() : x(0), y(0), timestamp(0) {}
  35.    DrawPoint(int px, int py) : x(px), y(py), timestamp(GetTickCount()) {}
  36. };
  37.  
  38. struct SerializedStroke {
  39.    std::vector<DrawPoint> points;
  40.    COLORREF color;
  41.    int brushSize;
  42.    bool isEraser;
  43. };
  44.  
  45. std::mutex strokeMutex;
  46. std::vector<SerializedStroke> strokeHistory;
  47. std::vector<DrawPoint> strokeBuffer;
  48. const double MIN_DISTANCE = 2.0;
  49.  
  50. COLORREF currentBrushColor = RGB(24, 123, 205);
  51. int brushSize = 10;
  52. int currentStrokeBrushSize = 10;
  53. bool isDrawing = false;
  54. bool isEraserMode = false;
  55. bool isPaintbrushSelected = true;
  56. bool isSpacePressed = false;
  57. POINT lastMousePos = { 0, 0 };
  58.  
  59. int scrollX = 0;
  60. int scrollY = 0;
  61. float gridZoomFactor = 1.0f;
  62. bool showGrid = true;
  63. bool useAlphaGrid = false;
  64. int gridOpacity = 255;
  65. const int GRID_SIZE = 100;
  66.  
  67. HINSTANCE hInst;
  68. HWND hWnd;
  69. //HWND hStatusBar = NULL;
  70. // Global DirectWrite objects:
  71. IDWriteFactory* pDWriteFactory = nullptr;
  72. IDWriteTextFormat* pTextFormat = nullptr;
  73. std::wstring g_statusText = L"";
  74. // Add DirectWrite globals and a global status string:
  75. //IDWriteFactory* pDWriteFactory = nullptr;
  76. //IDWriteTextFormat* pTextFormat = nullptr;
  77. DWORD lastStatusUpdateTime = 0;
  78. const DWORD STATUS_UPDATE_INTERVAL = 50;
  79. HDC hStatusBufferDC = NULL;
  80. HBITMAP hStatusBufferBitmap = NULL;
  81.  
  82. // Serialization globals
  83. const wchar_t* STATE_FILE = L"canvas_state2.bin";
  84. bool isLoading = false;
  85. bool sessionDirty = false;
  86.  
  87. // For Direct2D
  88. ID2D1Factory* pFactory = nullptr;
  89. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  90. ID2D1BitmapRenderTarget* pOffscreenRT = nullptr;
  91. bool offscreenDirty = true;
  92. int lastOffscreenScrollX = 0;
  93. int lastOffscreenScrollY = 0;
  94.  
  95. //----------------------------------------------------------------
  96. // Function Declarations
  97. //----------------------------------------------------------------
  98.  
  99. void SaveCanvasState();
  100. void LoadCanvasStateAsync(HWND hwnd);
  101. void UpdateStatus(HWND hwnd);
  102. void InitializeStatusBuffer(HWND hStatus);
  103. void UpdateOffscreenBuffer(HWND hwnd);
  104. HRESULT CreateDeviceResources(HWND hwnd);
  105. void DiscardDeviceResources();
  106. void DrawSmoothStroke(ID2D1RenderTarget* pRT, const std::vector<DrawPoint>& points, bool isEraser, COLORREF strokeColor, int strokeSize, int offsetX, int offsetY);
  107. void DrawGrid(ID2D1RenderTarget* pRT, const D2D1_RECT_F& rect);
  108.  
  109. //----------------------------------------------------------------
  110. // Serialization Functions
  111. //----------------------------------------------------------------
  112.  
  113. void SaveCanvasState() {
  114.    std::ofstream file(STATE_FILE, std::ios::binary | std::ios::out);
  115.    if (!file)
  116.        return;
  117.    file.write(reinterpret_cast<const char*>(&gridZoomFactor), sizeof(float));
  118.    file.write(reinterpret_cast<const char*>(&showGrid), sizeof(bool));
  119.    file.write(reinterpret_cast<const char*>(&useAlphaGrid), sizeof(bool));
  120.    file.write(reinterpret_cast<const char*>(&gridOpacity), sizeof(int));
  121.    file.write(reinterpret_cast<const char*>(&currentBrushColor), sizeof(COLORREF));
  122.    file.write(reinterpret_cast<const char*>(&brushSize), sizeof(int));
  123.    {
  124.        std::lock_guard<std::mutex> lock(strokeMutex);
  125.        size_t strokeCount = strokeHistory.size();
  126.        file.write(reinterpret_cast<const char*>(&strokeCount), sizeof(size_t));
  127.        for (const auto& stroke : strokeHistory) {
  128.            std::vector<DrawPoint> optimizedPoints;
  129.            if (!stroke.points.empty()) {
  130.                optimizedPoints.push_back(stroke.points[0]);
  131.                for (size_t i = 1; i < stroke.points.size(); ++i) {
  132.                    const DrawPoint& prev = optimizedPoints.back();
  133.                    const DrawPoint& curr = stroke.points[i];
  134.                    double dx = curr.x - prev.x;
  135.                    double dy = curr.y - prev.y;
  136.                    double distance = sqrt(dx * dx + dy * dy);
  137.                    if (distance >= MIN_DISTANCE)
  138.                        optimizedPoints.push_back(curr);
  139.                }
  140.            }
  141.            size_t pointCount = optimizedPoints.size();
  142.            file.write(reinterpret_cast<const char*>(&pointCount), sizeof(size_t));
  143.            if (pointCount > 0)
  144.                file.write(reinterpret_cast<const char*>(optimizedPoints.data()), pointCount * sizeof(DrawPoint));
  145.            file.write(reinterpret_cast<const char*>(&stroke.color), sizeof(COLORREF));
  146.            file.write(reinterpret_cast<const char*>(&stroke.brushSize), sizeof(int));
  147.            file.write(reinterpret_cast<const char*>(&stroke.isEraser), sizeof(bool));
  148.        }
  149.    }
  150.    file.close();
  151. }
  152.  
  153. void LoadCanvasStateAsync(HWND hwnd) {
  154.    isLoading = true;
  155.    std::thread([hwnd]() {
  156.        std::ifstream file(STATE_FILE, std::ios::binary | std::ios::in);
  157.        if (!file) {
  158.            isLoading = false;
  159.            return;
  160.        }
  161.        try {
  162.            file.read(reinterpret_cast<char*>(&gridZoomFactor), sizeof(float));
  163.            file.read(reinterpret_cast<char*>(&showGrid), sizeof(bool));
  164.            file.read(reinterpret_cast<char*>(&useAlphaGrid), sizeof(bool));
  165.            file.read(reinterpret_cast<char*>(&gridOpacity), sizeof(int));
  166.            file.read(reinterpret_cast<char*>(&currentBrushColor), sizeof(COLORREF));
  167.            file.read(reinterpret_cast<char*>(&brushSize), sizeof(int));
  168.            size_t strokeCount = 0;
  169.            file.read(reinterpret_cast<char*>(&strokeCount), sizeof(size_t));
  170.            std::vector<SerializedStroke> loadedStrokes;
  171.            for (size_t i = 0; i < strokeCount && file.good(); ++i) {
  172.                SerializedStroke stroke;
  173.                size_t pointCount = 0;
  174.                file.read(reinterpret_cast<char*>(&pointCount), sizeof(size_t));
  175.                if (pointCount > 0 && pointCount < 1000000) {
  176.                    for (size_t j = 0; j < pointCount; ++j) {
  177.                        DrawPoint point;
  178.                        file.read(reinterpret_cast<char*>(&point.x), sizeof(int));
  179.                        file.read(reinterpret_cast<char*>(&point.y), sizeof(int));
  180.                        file.read(reinterpret_cast<char*>(&point.timestamp), sizeof(DWORD));
  181.                        stroke.points.push_back(point);
  182.                    }
  183.                    file.read(reinterpret_cast<char*>(&stroke.color), sizeof(COLORREF));
  184.                    file.read(reinterpret_cast<char*>(&stroke.brushSize), sizeof(int));
  185.                    file.read(reinterpret_cast<char*>(&stroke.isEraser), sizeof(bool));
  186.                    loadedStrokes.push_back(stroke);
  187.                }
  188.            }
  189.            {
  190.                std::lock_guard<std::mutex> lock(strokeMutex);
  191.                strokeHistory = std::move(loadedStrokes);
  192.            }
  193.        }
  194.        catch (...) {
  195.            isLoading = false;
  196.            return;
  197.        }
  198.        file.close();
  199.        isLoading = false;
  200.        // Post a message to update offscreen buffer after loading
  201.        PostMessage(hwnd, WM_USER + 1, 0, 0);
  202.        }).detach();
  203. }
  204.  
  205. //----------------------------------------------------------------
  206. // Direct2D Initialization and Resource Management
  207. //----------------------------------------------------------------
  208.  
  209. HRESULT CreateDeviceResources(HWND hwnd) {
  210.    if (pRenderTarget)
  211.        return S_OK;
  212.    RECT rc;
  213.    GetClientRect(hwnd, &rc);
  214.    D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);
  215.  
  216.    HRESULT hr = pFactory->CreateHwndRenderTarget(
  217.        D2D1::RenderTargetProperties(),
  218.        D2D1::HwndRenderTargetProperties(hwnd, size),
  219.        &pRenderTarget
  220.    );
  221.    if (SUCCEEDED(hr)) {
  222.        // Create an offscreen compatible render target for persistent drawing.
  223.        hr = pRenderTarget->CreateCompatibleRenderTarget(
  224.            D2D1::SizeF((FLOAT)rc.right, (FLOAT)rc.bottom),
  225.            &pOffscreenRT
  226.        );
  227.        if (SUCCEEDED(hr)) {
  228.            // Mark offscreen as dirty so it is initially updated.
  229.            offscreenDirty = true;
  230.            lastOffscreenScrollX = scrollX;
  231.            lastOffscreenScrollY = scrollY;
  232.        }
  233.    }
  234.    return hr;
  235. }
  236.  
  237. void DiscardDeviceResources() {
  238.    if (pOffscreenRT) {
  239.        pOffscreenRT->Release();
  240.        pOffscreenRT = nullptr;
  241.    }
  242.    if (pRenderTarget) {
  243.        pRenderTarget->Release();
  244.        pRenderTarget = nullptr;
  245.    }
  246. }
  247.  
  248. //----------------------------------------------------------------
  249. // Drawing Functions (Direct2D versions)
  250. //----------------------------------------------------------------
  251.  
  252. void DrawSmoothStroke(ID2D1RenderTarget* pRT, const std::vector<DrawPoint>& points, bool isEraser, COLORREF strokeColor, int strokeSize, int offsetX, int offsetY) {
  253.    if (points.empty())
  254.        return;
  255.  
  256.    // Determine color; for eraser use white.
  257.    D2D1_COLOR_F color = isEraser ? D2D1::ColorF(D2D1::ColorF::White) :
  258.        D2D1::ColorF(
  259.            GetRValue(strokeColor) / 255.0f,
  260.            GetGValue(strokeColor) / 255.0f,
  261.            GetBValue(strokeColor) / 255.0f
  262.        );
  263.  
  264.    ID2D1SolidColorBrush* pBrush = nullptr;
  265.    if (FAILED(pRT->CreateSolidColorBrush(color, &pBrush)))
  266.        return;
  267.  
  268.    if (points.size() == 1) {
  269.        const DrawPoint& pt = points[0];
  270.        D2D1_ELLIPSE ellipse = D2D1::Ellipse(
  271.            D2D1::Point2F((FLOAT)(pt.x - offsetX), (FLOAT)(pt.y - offsetY)),
  272.            (FLOAT)strokeSize, (FLOAT)strokeSize);
  273.        pRT->FillEllipse(ellipse, pBrush);
  274.    }
  275.    else {
  276.        for (size_t i = 1; i < points.size(); ++i) {
  277.            const DrawPoint& prev = points[i - 1];
  278.            const DrawPoint& curr = points[i];
  279.            double dx = curr.x - prev.x;
  280.            double dy = curr.y - prev.y;
  281.            double distance = sqrt(dx * dx + dy * dy);
  282.            if (distance > 0) {
  283.                int steps = std::max(1, (int)(distance / 2));
  284.                for (int step = 0; step <= steps; ++step) {
  285.                    double t = step / (double)steps;
  286.                    int x = (int)(prev.x + dx * t);
  287.                    int y = (int)(prev.y + dy * t);
  288.                    D2D1_ELLIPSE ellipse = D2D1::Ellipse(
  289.                        D2D1::Point2F((FLOAT)(x - offsetX), (FLOAT)(y - offsetY)),
  290.                        (FLOAT)strokeSize, (FLOAT)strokeSize);
  291.                    pRT->FillEllipse(ellipse, pBrush);
  292.                }
  293.            }
  294.        }
  295.    }
  296.    pBrush->Release();
  297. }
  298.  
  299. void DrawGrid(ID2D1RenderTarget* pRT, const D2D1_RECT_F& rect) {
  300.    // Use a solid orange color for grid lines.
  301.    ID2D1SolidColorBrush* pGridBrush = nullptr;
  302.    pRT->CreateSolidColorBrush(D2D1::ColorF(1.0f, 0.55f, 0.0f), &pGridBrush);
  303.    int scaledGridSize = (int)(GRID_SIZE * gridZoomFactor);
  304.    // Compute starting positions based on scroll offsets.
  305.    int modX = scrollX % scaledGridSize;
  306.    if (modX < 0)
  307.        modX += scaledGridSize;
  308.    float startX = -modX;
  309.    for (float x = startX; x < rect.right; x += scaledGridSize) {
  310.        pRT->DrawLine(D2D1::Point2F(x, rect.top), D2D1::Point2F(x, rect.bottom), pGridBrush, 1.0f);
  311.    }
  312.    int modY = scrollY % scaledGridSize;
  313.    if (modY < 0)
  314.        modY += scaledGridSize;
  315.    float startY = -modY;
  316.    for (float y = startY; y < rect.bottom; y += scaledGridSize) {
  317.        pRT->DrawLine(D2D1::Point2F(rect.left, y), D2D1::Point2F(rect.right, y), pGridBrush, 1.0f);
  318.    }
  319.    pGridBrush->Release();
  320. }
  321.  
  322. //----------------------------------------------------------------
  323. // Offscreen Buffer Update (using pOffscreenRT)
  324. //----------------------------------------------------------------
  325.  
  326. void UpdateOffscreenBuffer(HWND hwnd) {
  327.    if (!pOffscreenRT)
  328.        return;
  329.    pOffscreenRT->BeginDraw();
  330.    // Clear offscreen render target to white.
  331.    pOffscreenRT->Clear(D2D1::ColorF(D2D1::ColorF::White));
  332.    // Redraw all strokes.
  333.    {
  334.        std::lock_guard<std::mutex> lock(strokeMutex);
  335.        for (const auto& stroke : strokeHistory) {
  336.            DrawSmoothStroke(pOffscreenRT, stroke.points, stroke.isEraser, stroke.color, stroke.brushSize, scrollX, scrollY);
  337.        }
  338.    }
  339.    HRESULT hr = pOffscreenRT->EndDraw();
  340.    // Mark offscreen as clean.
  341.    offscreenDirty = false;
  342.    lastOffscreenScrollX = scrollX;
  343.    lastOffscreenScrollY = scrollY;
  344. }
  345.  
  346. //----------------------------------------------------------------
  347. // Status Bar Functions (GDI remains unchanged)
  348. //----------------------------------------------------------------
  349.  
  350. void InitializeStatusBuffer(HWND hStatus) {
  351.    if (hStatusBufferDC) {
  352.        DeleteDC(hStatusBufferDC);
  353.        DeleteObject(hStatusBufferBitmap);
  354.    }
  355.    HDC hdc = GetDC(hStatus);
  356.    RECT rect;
  357.    GetClientRect(hStatus, &rect);
  358.    hStatusBufferDC = CreateCompatibleDC(hdc);
  359.    hStatusBufferBitmap = CreateCompatibleBitmap(hdc, rect.right, rect.bottom);
  360.    SelectObject(hStatusBufferDC, hStatusBufferBitmap);
  361.    ReleaseDC(hStatus, hdc);
  362. }
  363.  
  364. void UpdateStatus(HWND hwnd) {
  365.    DWORD currentTime = GetTickCount();
  366.    if (currentTime - lastStatusUpdateTime < STATUS_UPDATE_INTERVAL)
  367.        return;
  368.    lastStatusUpdateTime = currentTime;
  369.    wchar_t status[512];
  370.    BYTE r = GetRValue(currentBrushColor);
  371.    BYTE g = GetGValue(currentBrushColor);
  372.    BYTE b = GetBValue(currentBrushColor);
  373.    swprintf_s(status, 512,
  374.        L"Mode: %s | Brush: %d | Color: RGB(%d,%d,%d) | Grid: %s%s | Zoom: %.1fx | Opacity: %d%% | Canvas Pos: (%d,%d)",
  375.        isEraserMode ? L"Eraser" : L"Draw",
  376.        brushSize,
  377.        r, g, b,
  378.        showGrid ? L"On" : L"Off",
  379.        useAlphaGrid ? L"(Alpha)" : L"",
  380.        gridZoomFactor,
  381.        (gridOpacity * 100) / 255,
  382.        scrollX, scrollY
  383.    );
  384.    g_statusText = status;
  385. }
  386.  
  387. /* void UpdateStatus(HWND hwnd) {
  388.    DWORD currentTime = GetTickCount();
  389.    if (currentTime - lastStatusUpdateTime < STATUS_UPDATE_INTERVAL)
  390.        return;
  391.    lastStatusUpdateTime = currentTime;
  392.    if (!hStatusBar)
  393.        return;
  394.    if (!hStatusBufferDC) {
  395.        InitializeStatusBuffer(hStatusBar);
  396.    }
  397.    RECT statusRect;
  398.    GetClientRect(hStatusBar, &statusRect);
  399.    wchar_t status[512];
  400.    BYTE r = GetRValue(currentBrushColor);
  401.    BYTE g = GetGValue(currentBrushColor);
  402.    BYTE b = GetBValue(currentBrushColor);
  403.    swprintf_s(status, 512,
  404.        L"Mode: %s | Brush: %d | Color: RGB(%d,%d,%d) | Grid: %s%s | Zoom: %.1fx | Opacity: %d%% | Canvas Pos: (%d,%d)",
  405.        isEraserMode ? L"Eraser" : L"Draw",
  406.        brushSize,
  407.        r, g, b,
  408.        showGrid ? L"On" : L"Off",
  409.        useAlphaGrid ? L"(Alpha)" : L"",
  410.        gridZoomFactor,
  411.        (gridOpacity * 100) / 255,
  412.        scrollX, scrollY
  413.    );
  414.    SendMessage(hStatusBar, SB_SETTEXT, 0, (LPARAM)status);
  415. } */
  416.  
  417. //----------------------------------------------------------------
  418. // Window Procedure
  419. //----------------------------------------------------------------
  420.  
  421. LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  422.    HRESULT hr;
  423.    switch (uMsg) {
  424.    case WM_CREATE:
  425.    {
  426.        // Initialize Direct2D Factory
  427.        HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  428.        if (FAILED(hr))
  429.            return -1;
  430.  
  431.        // Initialize DirectWrite Factory and Text Format for the status text.
  432.        HRESULT hrDWrite = DWriteCreateFactory(
  433.            DWRITE_FACTORY_TYPE_SHARED,
  434.            __uuidof(IDWriteFactory),
  435.            reinterpret_cast<IUnknown**>(&pDWriteFactory)
  436.        );
  437.        if (SUCCEEDED(hrDWrite))
  438.        {
  439.            hrDWrite = pDWriteFactory->CreateTextFormat(
  440.                L"Segoe UI",                // Font family name.
  441.                NULL,                       // Use system font collection.
  442.                DWRITE_FONT_WEIGHT_NORMAL,
  443.                DWRITE_FONT_STYLE_NORMAL,
  444.                DWRITE_FONT_STRETCH_NORMAL,
  445.                14.0f,                      // Font size.
  446.                L"",                        // Locale.
  447.                &pTextFormat
  448.            );
  449.            if (SUCCEEDED(hrDWrite))
  450.            {
  451.                pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  452.                pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  453.            }
  454.        }
  455.  
  456.        // (Remove GDI status bar creation; status will be rendered via Direct2D.)
  457.  
  458.        // Device resources (pRenderTarget and pOffscreenRT) will be created in WM_SIZE.
  459.        LoadCanvasStateAsync(hwnd);
  460.        return 0;
  461.    }
  462.    case WM_SIZE:
  463.    {
  464.        RECT rcClient;
  465.        GetClientRect(hwnd, &rcClient);
  466.  
  467.        // Resize (or create) the main render target.
  468.        if (pRenderTarget)
  469.        {
  470.            pRenderTarget->Resize(D2D1::SizeU(rcClient.right, rcClient.bottom));
  471.        }
  472.        else
  473.        {
  474.            HRESULT hr = CreateDeviceResources(hwnd);
  475.            if (FAILED(hr))
  476.                return -1;
  477.        }
  478.  
  479.        // Recreate the offscreen render target.
  480.        if (pOffscreenRT)
  481.        {
  482.            pOffscreenRT->Release();
  483.            pOffscreenRT = nullptr;
  484.        }
  485.        HRESULT hr = pRenderTarget->CreateCompatibleRenderTarget(
  486.            D2D1::SizeF((FLOAT)rcClient.right, (FLOAT)rcClient.bottom),
  487.            &pOffscreenRT
  488.        );
  489.        if (SUCCEEDED(hr))
  490.        {
  491.            offscreenDirty = true;               // Force update of the offscreen buffer.
  492.            lastOffscreenScrollX = scrollX;
  493.            lastOffscreenScrollY = scrollY;
  494.            UpdateOffscreenBuffer(hwnd);         // Rebuild the offscreen content.
  495.        }
  496.  
  497.        // Update status (which now contains the grid state) and force a full redraw.
  498.        UpdateStatus(hwnd);
  499.        InvalidateRect(hwnd, NULL, TRUE);
  500.        return 0;
  501.    }
  502.        case WM_KEYDOWN:
  503.    {
  504.        if (GetKeyState(VK_MENU) & 0x8000)
  505.            return DefWindowProc(hwnd, uMsg, wParam, lParam);
  506.        // Panning using Space + Drag is handled in WM_MOUSEMOVE.
  507.        // Additionally, allow arrow keys for panning.
  508.        if (wParam == VK_LEFT) {
  509.            scrollX -= 20;
  510.            offscreenDirty = true;
  511.            InvalidateRect(hwnd, NULL, FALSE);
  512.        }
  513.        else if (wParam == VK_RIGHT) {
  514.            scrollX += 20;
  515.            offscreenDirty = true;
  516.            InvalidateRect(hwnd, NULL, FALSE);
  517.        }
  518.        else if (wParam == VK_UP) {
  519.            scrollY -= 20;
  520.            offscreenDirty = true;
  521.            InvalidateRect(hwnd, NULL, FALSE);
  522.        }
  523.        else if (wParam == VK_DOWN) {
  524.            scrollY += 20;
  525.            offscreenDirty = true;
  526.            InvalidateRect(hwnd, NULL, FALSE);
  527.        }
  528.        else if (wParam == VK_SPACE && !isSpacePressed) {
  529.            isSpacePressed = true;
  530.            GetCursorPos(&lastMousePos);
  531.            ScreenToClient(hwnd, &lastMousePos);
  532.            SetCursor(LoadCursor(NULL, IDC_SIZEALL));
  533.            SetCapture(hwnd);
  534.        }
  535.        else if (wParam == 0x50) {
  536.            isPaintbrushSelected = true;
  537.            isEraserMode = false;
  538.            UpdateStatus(hwnd);
  539.            InvalidateRect(hwnd, NULL, TRUE);
  540.        }
  541.        else if (wParam == 0x45) {
  542.            isPaintbrushSelected = false;
  543.            isEraserMode = true;
  544.            UpdateStatus(hwnd);
  545.            InvalidateRect(hwnd, NULL, TRUE);
  546.        }
  547.        else if (wParam == 'Q') {
  548.            CHOOSECOLOR cc = { sizeof(CHOOSECOLOR) };
  549.            static COLORREF customColors[16] = { 0 };
  550.            cc.hwndOwner = hwnd;
  551.            cc.rgbResult = currentBrushColor;
  552.            cc.lpCustColors = customColors;
  553.            cc.Flags = CC_FULLOPEN | CC_RGBINIT;
  554.            if (ChooseColor(&cc))
  555.                currentBrushColor = cc.rgbResult;
  556.            UpdateStatus(hwnd);
  557.            offscreenDirty = true;
  558.            InvalidateRect(hwnd, NULL, TRUE);
  559.        }
  560.        else if (wParam == VK_ADD || wParam == VK_OEM_PLUS) {
  561.            brushSize = std::min(50, brushSize + 5);
  562.            offscreenDirty = true;  // Ensure new brush size is applied in drawing.
  563.            UpdateStatus(hwnd);
  564.            InvalidateRect(hwnd, NULL, TRUE);
  565.        }
  566.        else if (wParam == VK_SUBTRACT || wParam == VK_OEM_MINUS) {
  567.            brushSize = std::max(5, brushSize - 5);
  568.            offscreenDirty = true;
  569.            UpdateStatus(hwnd);
  570.            InvalidateRect(hwnd, NULL, TRUE);
  571.        }
  572.        else if (wParam == 0x43) {
  573.            std::lock_guard<std::mutex> lock(strokeMutex);
  574.            strokeHistory.clear();
  575.            sessionDirty = true;  // Mark session as changed.
  576.            offscreenDirty = true;
  577.            InvalidateRect(hwnd, NULL, TRUE);
  578.        }
  579.        else if (wParam == VK_HOME) {
  580.            scrollX = 0;
  581.            scrollY = 0;
  582.            lastOffscreenScrollX = 0;
  583.            lastOffscreenScrollY = 0;
  584.            offscreenDirty = true;
  585.            UpdateOffscreenBuffer(hwnd);
  586.            UpdateStatus(hwnd);
  587.            InvalidateRect(hwnd, NULL, TRUE);
  588.        }
  589.        else if (wParam == 'G') {
  590.            showGrid = !showGrid;
  591.            offscreenDirty = true;  // Mark offscreen dirty so grid redraws.
  592.            UpdateStatus(hwnd);
  593.            InvalidateRect(hwnd, NULL, TRUE);
  594.        }
  595.        else if (wParam == 'A') {
  596.            useAlphaGrid = !useAlphaGrid;
  597.            UpdateStatus(hwnd);
  598.            InvalidateRect(hwnd, NULL, FALSE);
  599.        }
  600.        else if (wParam == VK_PRIOR) {
  601.            gridZoomFactor *= 1.1f;
  602.            offscreenDirty = true;
  603.            UpdateStatus(hwnd);
  604.            InvalidateRect(hwnd, NULL, FALSE);
  605.        }
  606.        else if (wParam == VK_NEXT) {
  607.            gridZoomFactor *= 0.9f;
  608.            if (gridZoomFactor < 0.1f)
  609.                gridZoomFactor = 0.1f;
  610.            offscreenDirty = true;
  611.            UpdateStatus(hwnd);
  612.            InvalidateRect(hwnd, NULL, FALSE);
  613.        }
  614.        else if (wParam == VK_OEM_6 && useAlphaGrid) {
  615.            gridOpacity = std::min(255, gridOpacity + 15);
  616.            offscreenDirty = true;
  617.            UpdateStatus(hwnd);
  618.            InvalidateRect(hwnd, NULL, FALSE);
  619.        }
  620.        else if (wParam == VK_OEM_4 && useAlphaGrid) {
  621.            gridOpacity = std::max(0, gridOpacity - 15);
  622.            offscreenDirty = true;
  623.            UpdateStatus(hwnd);
  624.            InvalidateRect(hwnd, NULL, FALSE);
  625.        }
  626.        else if (wParam == VK_ESCAPE) {
  627.            if (isSpacePressed) {
  628.                isSpacePressed = false;
  629.                ReleaseCapture();
  630.            }
  631.            if (sessionDirty) {
  632.                SaveCanvasState();
  633.                sessionDirty = false;
  634.            }
  635.            PostQuitMessage(0);
  636.            return 0;
  637.        }
  638.        else if (wParam == VK_F1) {
  639.            MessageBox(hwnd,
  640.                L"Infinite Canvas Doodle App (Direct2D Accelerated)\n"
  641.                L"P=Brush, E=Eraser, C=Clear, +/-=BrushSize, Space+Drag/Arrow Keys=Panning, Home=Reset, Q=Color, G=Grid, A=Alpha, PgUp=ZoomIn, PgDn=ZoomOut, F1=About",
  642.                L"Information", MB_OK | MB_ICONINFORMATION);
  643.            return 0;
  644.        }
  645.        return 0;
  646.    }
  647.    case WM_KEYUP:
  648.    {
  649.        if (wParam == VK_SPACE) {
  650.            isSpacePressed = false;
  651.            SetCursor(LoadCursor(NULL, IDC_ARROW));
  652.            ReleaseCapture();
  653.            return 0;
  654.        }
  655.        return 0;
  656.    }
  657.    case WM_LBUTTONDOWN:
  658.    {
  659.        isDrawing = true;
  660.        currentStrokeBrushSize = brushSize;
  661.        int worldX = GET_X_LPARAM(lParam) + scrollX;
  662.        int worldY = GET_Y_LPARAM(lParam) + scrollY;
  663.        strokeBuffer.clear();
  664.        strokeBuffer.push_back(DrawPoint(worldX, worldY));
  665.        SetCapture(hwnd);
  666.        InvalidateRect(hwnd, NULL, FALSE);
  667.        return 0;
  668.    }
  669.    case WM_LBUTTONUP:
  670.    {
  671.        if (isDrawing) {
  672.            isDrawing = false;
  673.            SerializedStroke stroke;
  674.            stroke.points = strokeBuffer;
  675.            stroke.color = currentBrushColor;
  676.            stroke.brushSize = brushSize;
  677.            stroke.isEraser = isEraserMode;
  678.            {
  679.                std::lock_guard<std::mutex> lock(strokeMutex);
  680.                strokeHistory.push_back(stroke);
  681.            }
  682.            strokeBuffer.clear();
  683.            ReleaseCapture();
  684.            InvalidateRect(hwnd, NULL, FALSE);
  685.            sessionDirty = true;
  686.            if (sessionDirty) {
  687.                SaveCanvasState();
  688.                sessionDirty = false;
  689.            }
  690.            offscreenDirty = true;
  691.            UpdateOffscreenBuffer(hwnd);
  692.            UpdateStatus(hwnd);
  693.        }
  694.        return 0;
  695.    }
  696.    case WM_MOUSEMOVE:
  697.    {
  698.        int x = GET_X_LPARAM(lParam);
  699.        int y = GET_Y_LPARAM(lParam);
  700.        if (isSpacePressed) {
  701.            RECT clientRect;
  702.            GetClientRect(hwnd, &clientRect);
  703.            int deltaX = x - lastMousePos.x;
  704.            int deltaY = y - lastMousePos.y;
  705.            scrollX -= deltaX;
  706.            scrollY -= deltaY;
  707.            lastMousePos.x = x;
  708.            lastMousePos.y = y;
  709.            if (scrollX != lastOffscreenScrollX || scrollY != lastOffscreenScrollY)
  710.                offscreenDirty = true;
  711.            UpdateStatus(hwnd);
  712.            InvalidateRect(hwnd, NULL, FALSE);
  713.        }
  714.        else if (isDrawing && (wParam & MK_LBUTTON)) {
  715.            int worldX = x + scrollX;
  716.            int worldY = y + scrollY;
  717.            if (strokeBuffer.empty())
  718.                strokeBuffer.push_back(DrawPoint(worldX, worldY));
  719.            else {
  720.                const DrawPoint& lastPt = strokeBuffer.back();
  721.                double dx = worldX - lastPt.x;
  722.                double dy = worldY - lastPt.y;
  723.                double distance = sqrt(dx * dx + dy * dy);
  724.                if (distance >= MIN_DISTANCE)
  725.                    strokeBuffer.push_back(DrawPoint(worldX, worldY));
  726.            }
  727.            // Compute dirty rectangle for the new segment (optional, for partial redraw)
  728.            RECT dirty;
  729.            int clientPrevX = strokeBuffer.back().x - scrollX;
  730.            int clientPrevY = strokeBuffer.back().y - scrollY;
  731.            int clientNewX = x;
  732.            int clientNewY = y;
  733.            dirty.left = std::min(clientPrevX, clientNewX) - brushSize;
  734.            dirty.top = std::min(clientPrevY, clientNewY) - brushSize;
  735.            dirty.right = std::max(clientPrevX, clientNewX) + brushSize;
  736.            dirty.bottom = std::max(clientPrevY, clientNewY) + brushSize;
  737.            InvalidateRect(hwnd, &dirty, FALSE);
  738.        }
  739.        return 0;
  740.    }
  741.    case WM_USER + 1:
  742.    {
  743.        // Custom message after state loading.
  744.        offscreenDirty = true;
  745.        UpdateOffscreenBuffer(hwnd);
  746.        InvalidateRect(hwnd, NULL, TRUE);
  747.        break;
  748.    }
  749.    case WM_ERASEBKGND:
  750.        return 1;
  751.    case WM_PAINT:
  752.    {
  753.        PAINTSTRUCT ps;
  754.        BeginPaint(hwnd, &ps);
  755.  
  756.        pRenderTarget->BeginDraw();
  757.  
  758.        // Update offscreen buffer if dirty.
  759.        if (offscreenDirty)
  760.        {
  761.            UpdateOffscreenBuffer(hwnd);
  762.        }
  763.  
  764.        // Draw the persistent offscreen render target.
  765.        ID2D1Bitmap* pOffscreenBitmap = nullptr;
  766.        pOffscreenRT->GetBitmap(&pOffscreenBitmap);
  767.        pRenderTarget->DrawBitmap(pOffscreenBitmap);
  768.        pOffscreenBitmap->Release();
  769.  
  770.        // Overlay in-progress stroke.
  771.        if (isDrawing && !strokeBuffer.empty())
  772.        {
  773.            DrawSmoothStroke(pRenderTarget, strokeBuffer, isEraserMode, currentBrushColor, brushSize, scrollX, scrollY);
  774.        }
  775.  
  776.        // Get the full client area for grid drawing.
  777.        RECT rcClient;
  778.        GetClientRect(hwnd, &rcClient);
  779.        D2D1_RECT_F d2dRect = D2D1::RectF(0, 0, (FLOAT)rcClient.right, (FLOAT)rcClient.bottom);
  780.        if (showGrid)
  781.        {
  782.            DrawGrid(pRenderTarget, d2dRect);
  783.        }
  784.  
  785.        // Render the status bar using Direct2D/DirectWrite.
  786.        {
  787.            float statusBarHeight = 30.0f;
  788.            D2D1_RECT_F statusRect = D2D1::RectF(
  789.                0,
  790.                (FLOAT)rcClient.bottom - statusBarHeight,
  791.                (FLOAT)rcClient.right,
  792.                (FLOAT)rcClient.bottom
  793.            );
  794.            // Fill status bar background.
  795.            ID2D1SolidColorBrush* pStatusBgBrush = nullptr;
  796.            pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(0.2f, 0.2f, 0.2f), &pStatusBgBrush);
  797.            pRenderTarget->FillRectangle(statusRect, pStatusBgBrush);
  798.            pStatusBgBrush->Release();
  799.            // Draw status text.
  800.            ID2D1SolidColorBrush* pTextBrush = nullptr;
  801.            pRenderTarget->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pTextBrush);
  802.            pRenderTarget->DrawTextW(
  803.                g_statusText.c_str(),
  804.                static_cast<UINT32>(g_statusText.length()),
  805.                pTextFormat,
  806.                &statusRect,
  807.                pTextBrush,
  808.                D2D1_DRAW_TEXT_OPTIONS_NONE,
  809.                DWRITE_MEASURING_MODE_NATURAL
  810.            );
  811.            pTextBrush->Release();
  812.        }
  813.  
  814.        HRESULT hr = pRenderTarget->EndDraw();
  815.        EndPaint(hwnd, &ps);
  816.        return 0;
  817.    }
  818.    case WM_SETCURSOR:
  819.    {
  820.        if (LOWORD(lParam) == HTCLIENT) {
  821.            if (isSpacePressed) {
  822.                SetCursor(LoadCursor(NULL, IDC_SIZEALL));
  823.                return TRUE;
  824.            }
  825.            else if (isPaintbrushSelected || isEraserMode) {
  826.                SetCursor(LoadCursor(NULL, IDC_CROSS));
  827.                return TRUE;
  828.            }
  829.        }
  830.        return DefWindowProc(hwnd, uMsg, wParam, lParam);
  831.    }
  832.    case WM_DESTROY:
  833.    {
  834.        if (sessionDirty)
  835.        {
  836.            SaveCanvasState();
  837.            sessionDirty = false;
  838.        }
  839.        DiscardDeviceResources();
  840.        if (pFactory)
  841.        {
  842.            pFactory->Release();
  843.            pFactory = nullptr;
  844.        }
  845.        if (pTextFormat)
  846.        {
  847.            pTextFormat->Release();
  848.            pTextFormat = nullptr;
  849.        }
  850.        if (pDWriteFactory)
  851.        {
  852.            pDWriteFactory->Release();
  853.            pDWriteFactory = nullptr;
  854.        }
  855.        PostQuitMessage(0);
  856.        return 0;
  857.    }
  858.    default:
  859.        return DefWindowProc(hwnd, uMsg, wParam, lParam);
  860.    }
  861.    return 0;
  862. }
  863.  
  864. //----------------------------------------------------------------
  865. // WinMain
  866. //----------------------------------------------------------------
  867.  
  868. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) {
  869.    INITCOMMONCONTROLSEX icex = { sizeof(INITCOMMONCONTROLSEX), ICC_BAR_CLASSES };
  870.    InitCommonControlsEx(&icex);
  871.    const wchar_t CLASS_NAME[] = L"InfiniteCanvasClass";
  872.    WNDCLASS wc = {};
  873.    wc.lpfnWndProc = WindowProc;
  874.    wc.hInstance = hInstance;
  875.    wc.lpszClassName = CLASS_NAME;
  876.    wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1));
  877.    RegisterClass(&wc);
  878.    hInst = hInstance;
  879.    hWnd = CreateWindowEx(0, CLASS_NAME,
  880.        L"Infinite Canvas Doodle App (Direct2D Accelerated, P=Brush, E=Eraser, C=Clear, +/-=BrushSize, Space+Drag/Arrow=Panning, Home=Reset, Q=Color, G=Grid, A=Alpha, PgUp=ZoomIn, PgDn=ZoomOut, F1=About)",
  881.        WS_OVERLAPPEDWINDOW | WS_MAXIMIZE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
  882.        NULL, NULL, hInstance, NULL);
  883.    if (hWnd == NULL)
  884.        return 0;
  885.    // Enable double buffering via WS_EX_COMPOSITED.
  886.    SetWindowLongPtr(hWnd, GWL_EXSTYLE, GetWindowLongPtr(hWnd, GWL_EXSTYLE) | WS_EX_COMPOSITED);
  887.    ShowWindow(hWnd, SW_SHOWMAXIMIZED);
  888.    MSG msg = {};
  889.    while (GetMessage(&msg, NULL, 0, 0)) {
  890.        TranslateMessage(&msg);
  891.        DispatchMessage(&msg);
  892.    }
  893.    return 0;
  894. }
  895. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement