Created
July 24, 2026 15:23
-
-
Save cynthia2006/b2105686f4b534c16bcd4d7790b32dbc to your computer and use it in GitHub Desktop.
Anti-aliased line-drawing toy program
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <vector> | |
| #include <SDL3/SDL.h> | |
| #include "SDL3_gfxPrimitives.h" | |
| struct PointPair { | |
| SDL_Point begin, end; | |
| // Constructor required for emplace_back(); not POD. | |
| PointPair(SDL_Point a, SDL_Point b): begin(a), end(b) {} | |
| }; | |
| int main() { | |
| SDL_Init(SDL_INIT_VIDEO); | |
| SDL_Window *w; | |
| SDL_Renderer *r; | |
| SDL_Point begin{}, end{}; | |
| SDL_Event e; | |
| bool dragging = false, running = true; | |
| std::vector<PointPair> points; | |
| SDL_CreateWindowAndRenderer("Line Sketch", 800, 600, 0, &w, &r); | |
| while (running) { | |
| while (SDL_PollEvent(&e)) { | |
| switch (e.type) { | |
| case SDL_EVENT_KEY_DOWN: | |
| switch (e.key.key) { | |
| case SDLK_ESCAPE: | |
| running = false; | |
| break; | |
| } | |
| break; | |
| case SDL_EVENT_MOUSE_BUTTON_DOWN: | |
| if (e.button.button == SDL_BUTTON_LEFT) | |
| { | |
| dragging = true; | |
| begin.x = end.x = e.button.x; | |
| begin.y = end.y = e.button.y; | |
| } | |
| break; | |
| case SDL_EVENT_MOUSE_BUTTON_UP: | |
| if (e.button.button == SDL_BUTTON_LEFT) | |
| { | |
| dragging = false; | |
| points.emplace_back(begin, end); | |
| } else if (e.button.button == SDL_BUTTON_RIGHT) { | |
| points.clear(); | |
| } | |
| break; | |
| case SDL_EVENT_MOUSE_MOTION: | |
| if (dragging) | |
| { | |
| end.x = e.motion.x; | |
| end.y = e.motion.y; | |
| } | |
| break; | |
| case SDL_EVENT_QUIT: | |
| running = false; | |
| break; | |
| } | |
| } | |
| SDL_SetRenderDrawColor(r, 0x0, 0x0, 0x0, 0x0); | |
| SDL_RenderClear(r); | |
| // SDL_SetRenderDrawColor(r, 0xFF, 0xFF, 0xFF, 0xFF); | |
| for (const auto& pair: points) { | |
| aalineColor(r, pair.begin.x, pair.begin.y, pair.end.x, pair.end.y, 0xFFFFFFFF); | |
| } | |
| if (dragging) | |
| aalineColor(r, begin.x, begin.y, end.x, end.y, 0xFFFFFFFF); | |
| // if (dragging) | |
| // SDL_RenderLine(r, begin.x, begin.y, end.x, end.y); | |
| SDL_RenderPresent(r); | |
| } | |
| SDL_DestroyRenderer(r); | |
| SDL_DestroyWindow(w); | |
| SDL_Quit(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment