SprayTool.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include "SprayTool.h"
  2. #include "PaintableWidget.h"
  3. #include <AK/Queue.h>
  4. #include <AK/SinglyLinkedList.h>
  5. #include <LibGUI/GPainter.h>
  6. #include <LibGUI/GAction.h>
  7. #include <LibGUI/GMenu.h>
  8. #include <LibDraw/GraphicsBitmap.h>
  9. #include <stdio.h>
  10. #include <LibM/math.h>
  11. SprayTool::SprayTool()
  12. {
  13. m_timer = CTimer::construct();
  14. m_timer->on_timeout = [&]() {
  15. paint_it();
  16. };
  17. m_timer->set_interval(200);
  18. }
  19. SprayTool::~SprayTool()
  20. {
  21. }
  22. static double nrand()
  23. {
  24. return double(rand()) / double(RAND_MAX);
  25. }
  26. void SprayTool::paint_it()
  27. {
  28. GPainter painter(m_widget->bitmap());
  29. auto& bitmap = m_widget->bitmap();
  30. ASSERT(bitmap.bpp() == 32);
  31. m_widget->update();
  32. const double minimal_radius = 10;
  33. const double base_radius = minimal_radius * m_thickness;
  34. for (int i = 0; i < 100 + (nrand() * 800); i++) {
  35. double radius = base_radius * nrand();
  36. double angle = 2 * M_PI * nrand();
  37. const int xpos = m_last_pos.x() + radius * cos(angle);
  38. const int ypos = m_last_pos.y() - radius * sin(angle);
  39. if (xpos < 0 || xpos >= bitmap.width())
  40. continue;
  41. if (ypos < 0 || ypos >= bitmap.height())
  42. continue;
  43. bitmap.set_pixel<GraphicsBitmap::Format::RGB32>(xpos, ypos, m_color);
  44. }
  45. }
  46. void SprayTool::on_mousedown(GMouseEvent& event)
  47. {
  48. if (!m_widget->rect().contains(event.position()))
  49. return;
  50. m_color = m_widget->color_for(event);
  51. m_last_pos = event.position();
  52. m_timer->start();
  53. paint_it();
  54. }
  55. void SprayTool::on_mousemove(GMouseEvent& event)
  56. {
  57. m_last_pos = event.position();
  58. if (m_timer->is_active()) {
  59. paint_it();
  60. m_timer->restart(m_timer->interval());
  61. }
  62. }
  63. void SprayTool::on_mouseup(GMouseEvent&)
  64. {
  65. m_timer->stop();
  66. }
  67. void SprayTool::on_contextmenu(GContextMenuEvent& event)
  68. {
  69. if (!m_context_menu) {
  70. m_context_menu = make<GMenu>();
  71. m_context_menu->add_action(GAction::create("1", [this](auto&) {
  72. m_thickness = 1;
  73. }));
  74. m_context_menu->add_action(GAction::create("2", [this](auto&) {
  75. m_thickness = 2;
  76. }));
  77. m_context_menu->add_action(GAction::create("3", [this](auto&) {
  78. m_thickness = 3;
  79. }));
  80. m_context_menu->add_action(GAction::create("4", [this](auto&) {
  81. m_thickness = 4;
  82. }));
  83. }
  84. m_context_menu->popup(event.screen_position());
  85. }