Cube.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@gmx.de>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <LibCore/ArgsParser.h>
  27. #include <LibCore/ElapsedTimer.h>
  28. #include <LibGUI/Application.h>
  29. #include <LibGUI/Icon.h>
  30. #include <LibGUI/Label.h>
  31. #include <LibGUI/Menu.h>
  32. #include <LibGUI/Menubar.h>
  33. #include <LibGUI/Painter.h>
  34. #include <LibGUI/Widget.h>
  35. #include <LibGUI/Window.h>
  36. #include <LibGfx/Bitmap.h>
  37. #include <LibGfx/Matrix4x4.h>
  38. #include <LibGfx/Vector3.h>
  39. #include <stdio.h>
  40. #include <stdlib.h>
  41. #include <unistd.h>
  42. const int WIDTH = 200;
  43. const int HEIGHT = 200;
  44. static bool flag_hide_window_frame = false;
  45. class Cube final : public GUI::Widget {
  46. C_OBJECT(Cube)
  47. public:
  48. virtual ~Cube() override;
  49. void set_stat_label(RefPtr<GUI::Label> l) { m_stats = l; };
  50. void set_show_window_frame(bool);
  51. bool show_window_frame() const { return m_show_window_frame; }
  52. Function<void(GUI::ContextMenuEvent&)> on_context_menu_request;
  53. protected:
  54. virtual void context_menu_event(GUI::ContextMenuEvent& event) override
  55. {
  56. if (on_context_menu_request)
  57. on_context_menu_request(event);
  58. }
  59. private:
  60. Cube();
  61. RefPtr<Gfx::Bitmap> m_bitmap;
  62. RefPtr<GUI::Label> m_stats;
  63. virtual void paint_event(GUI::PaintEvent&) override;
  64. virtual void timer_event(Core::TimerEvent&) override;
  65. int m_accumulated_time;
  66. int m_cycles;
  67. int m_phase;
  68. bool m_show_window_frame { true };
  69. };
  70. Cube::Cube()
  71. {
  72. m_bitmap = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, { WIDTH, HEIGHT });
  73. m_accumulated_time = 0;
  74. m_cycles = 0;
  75. m_phase = 0;
  76. stop_timer();
  77. start_timer(20);
  78. }
  79. Cube::~Cube()
  80. {
  81. }
  82. void Cube::paint_event(GUI::PaintEvent& event)
  83. {
  84. GUI::Painter painter(*this);
  85. painter.add_clip_rect(event.rect());
  86. /* Blit it! */
  87. painter.draw_scaled_bitmap(event.rect(), *m_bitmap, m_bitmap->rect());
  88. }
  89. void Cube::timer_event(Core::TimerEvent&)
  90. {
  91. Core::ElapsedTimer timer;
  92. timer.start();
  93. const FloatVector3 vertices[8] {
  94. { -1, -1, -1 },
  95. { -1, 1, -1 },
  96. { 1, 1, -1 },
  97. { 1, -1, -1 },
  98. { -1, -1, 1 },
  99. { -1, 1, 1 },
  100. { 1, 1, 1 },
  101. { 1, -1, 1 },
  102. };
  103. #define QUAD(a, b, c, d) a, b, c, c, d, a
  104. const int indices[] {
  105. QUAD(0, 1, 2, 3),
  106. QUAD(7, 6, 5, 4),
  107. QUAD(4, 5, 1, 0),
  108. QUAD(3, 2, 6, 7),
  109. QUAD(1, 5, 6, 2),
  110. QUAD(0, 3, 7, 4),
  111. };
  112. const Color colors[] {
  113. Color::Red,
  114. Color::Red,
  115. Color::Green,
  116. Color::Green,
  117. Color::Blue,
  118. Color::Blue,
  119. Color::Magenta,
  120. Color::Magenta,
  121. Color::White,
  122. Color::White,
  123. Color::Yellow,
  124. Color::Yellow,
  125. };
  126. FloatVector3 transformed_vertices[8];
  127. static float angle = 0;
  128. angle += 0.02f;
  129. auto matrix = FloatMatrix4x4::translate(FloatVector3(0, 0, 1.5f))
  130. * FloatMatrix4x4::rotate(FloatVector3(1, 0, 0), angle * 1.17356641f)
  131. * FloatMatrix4x4::rotate(FloatVector3(0, 1, 0), angle * 0.90533273f)
  132. * FloatMatrix4x4::rotate(FloatVector3(0, 0, 1), angle);
  133. for (int i = 0; i < 8; i++) {
  134. transformed_vertices[i] = matrix.transform_point(vertices[i]);
  135. }
  136. GUI::Painter painter(*m_bitmap);
  137. if (m_show_window_frame)
  138. painter.fill_rect_with_gradient(Gfx::Orientation::Vertical, m_bitmap->rect(), Gfx::Color::White, Gfx::Color::Blue);
  139. else
  140. painter.clear_rect(m_bitmap->rect(), Gfx::Color::Transparent);
  141. auto to_point = [](const FloatVector3& v) {
  142. return Gfx::IntPoint(v.x(), v.y());
  143. };
  144. for (size_t i = 0; i < sizeof(indices) / sizeof(indices[0]) / 3; i++) {
  145. auto a = transformed_vertices[indices[i * 3]];
  146. auto b = transformed_vertices[indices[i * 3 + 1]];
  147. auto c = transformed_vertices[indices[i * 3 + 2]];
  148. auto normal = (b - a).cross(c - a);
  149. normal.normalize();
  150. // Perspective projection
  151. a.set_x(WIDTH / 2 + a.x() / (1 + a.z() * 0.35f) * WIDTH / 3);
  152. a.set_y(HEIGHT / 2 - a.y() / (1 + a.z() * 0.35f) * WIDTH / 3);
  153. b.set_x(WIDTH / 2 + b.x() / (1 + b.z() * 0.35f) * WIDTH / 3);
  154. b.set_y(HEIGHT / 2 - b.y() / (1 + b.z() * 0.35f) * WIDTH / 3);
  155. c.set_x(WIDTH / 2 + c.x() / (1 + c.z() * 0.35f) * WIDTH / 3);
  156. c.set_y(HEIGHT / 2 - c.y() / (1 + c.z() * 0.35f) * WIDTH / 3);
  157. float winding = (b.x() - a.x()) * (c.y() - a.y()) - (b.y() - a.y()) * (c.x() - a.x());
  158. if (winding < 0)
  159. continue;
  160. float shade = 0.5f + normal.y() * 0.5f;
  161. auto color = colors[i];
  162. color.set_red(color.red() * shade);
  163. color.set_green(color.green() * shade);
  164. color.set_blue(color.blue() * shade);
  165. painter.draw_triangle(to_point(a), to_point(b), to_point(c), color);
  166. }
  167. if ((m_cycles % 50) == 0) {
  168. dbgln("{} total cycles. finished 50 in {} ms, avg {} ms", m_cycles, m_accumulated_time, m_accumulated_time / 50);
  169. m_stats->set_text(String::formatted("{} ms", m_accumulated_time / 50));
  170. m_accumulated_time = 0;
  171. }
  172. update();
  173. m_accumulated_time += timer.elapsed();
  174. m_cycles++;
  175. }
  176. void Cube::set_show_window_frame(bool show)
  177. {
  178. if (show == m_show_window_frame)
  179. return;
  180. m_show_window_frame = show;
  181. m_stats->set_visible(m_show_window_frame);
  182. auto& w = *window();
  183. w.set_frameless(!m_show_window_frame);
  184. w.set_has_alpha_channel(!m_show_window_frame);
  185. w.set_alpha_hit_threshold(m_show_window_frame ? 0 : 1);
  186. }
  187. int main(int argc, char** argv)
  188. {
  189. auto app = GUI::Application::construct(argc, argv);
  190. if (pledge("stdio recvfd sendfd rpath", nullptr) < 0) {
  191. perror("pledge");
  192. return 1;
  193. }
  194. if (unveil("/res", "r") < 0) {
  195. perror("unveil");
  196. return 1;
  197. }
  198. if (unveil(nullptr, nullptr) < 0) {
  199. perror("unveil");
  200. return 1;
  201. }
  202. Core::ArgsParser parser;
  203. parser.set_general_help("Create a window with a spinning cube.");
  204. parser.add_option(flag_hide_window_frame, "Hide window frame", "hide-window", 'h');
  205. parser.parse(argc, argv);
  206. auto window = GUI::Window::construct();
  207. window->set_double_buffering_enabled(true);
  208. window->set_title("Cube");
  209. window->set_resizable(false);
  210. window->resize(WIDTH, HEIGHT);
  211. window->set_has_alpha_channel(true);
  212. window->set_alpha_hit_threshold(1);
  213. auto& cube = window->set_main_widget<Cube>();
  214. auto& time = cube.add<GUI::Label>();
  215. time.set_relative_rect({ 0, 4, 40, 10 });
  216. time.move_by({ window->width() - time.width(), 0 });
  217. cube.set_stat_label(time);
  218. auto app_icon = GUI::Icon::default_icon("app-cube");
  219. window->set_icon(app_icon.bitmap_for_size(16));
  220. auto menubar = GUI::Menubar::construct();
  221. auto& app_menu = menubar->add_menu("File");
  222. auto show_window_frame_action = GUI::Action::create_checkable("Show window frame", [&](auto& action) {
  223. cube.set_show_window_frame(action.is_checked());
  224. });
  225. cube.set_show_window_frame(!flag_hide_window_frame);
  226. show_window_frame_action->set_checked(cube.show_window_frame());
  227. app_menu.add_action(move(show_window_frame_action));
  228. app_menu.add_separator();
  229. app_menu.add_action(GUI::CommonActions::make_quit_action([&](auto&) { app->quit(); }));
  230. auto& help_menu = menubar->add_menu("Help");
  231. help_menu.add_action(GUI::CommonActions::make_about_action("Cube Demo", app_icon, window));
  232. window->set_menubar(move(menubar));
  233. cube.on_context_menu_request = [&](auto& event) {
  234. app_menu.popup(event.screen_position());
  235. };
  236. window->show();
  237. return app->exec();
  238. }