GameView.mm 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. //
  2. // GameView.m
  3. // danmaku
  4. //
  5. // Created by Sam Jaffe on 5/22/19.
  6. // Copyright © 2019 Sam Jaffe. All rights reserved.
  7. //
  8. #import "GameView.h"
  9. #include <memory>
  10. #include <OpenGL/gl3.h>
  11. #include "danmaku/world.hpp"
  12. #include "game/engine/events.hpp"
  13. #include "game/engine/game_dispatch.hpp"
  14. #include "game/graphics/renderer.hpp"
  15. namespace env { namespace detail {
  16. extern void resize_screen(math::vec2i const&);
  17. }}
  18. @implementation GameView {
  19. std::shared_ptr<graphics::direct_renderer> renderer;
  20. std::shared_ptr<engine::game_dispatch> game;
  21. }
  22. - (id)initWithFrame:(NSRect)aRect {
  23. NSOpenGLPixelFormatAttribute attr[] = {
  24. NSOpenGLPFADoubleBuffer,
  25. NSOpenGLPFAOpenGLProfile,
  26. NSOpenGLProfileVersion3_2Core,
  27. 0
  28. };
  29. // create pixel format
  30. NSOpenGLPixelFormat *nsglFormat = [[NSOpenGLPixelFormat alloc]
  31. initWithAttributes:attr];
  32. // create the context...
  33. if (!(self = [super initWithFrame:aRect pixelFormat:nsglFormat])) {
  34. return nil;
  35. }
  36. using graphics::direct_renderer;
  37. using graphics::driver;
  38. renderer = std::make_shared<direct_renderer>(driver::openGL);
  39. game = std::make_shared<engine::game_dispatch>(renderer);
  40. auto world = danmaku::world::load_world("scripts/level/world.json", game);
  41. game->register_scene(world);
  42. game->activate_scene("light-1");
  43. // make the context current
  44. NSOpenGLContext* context = [[NSOpenGLContext alloc] initWithFormat:nsglFormat
  45. shareContext:nil];
  46. [self setOpenGLContext:context];
  47. [self setPixelFormat:nsglFormat];
  48. [[self openGLContext] makeCurrentContext];
  49. return self;
  50. }
  51. - (void)prepareOpenGL {
  52. // enable vertical sychronization to refresh rate
  53. const GLint vals = 0x01;
  54. [[self openGLContext] setValues:&vals forParameter:NSOpenGLCPSwapInterval];
  55. const GLint opaque = 0;
  56. [[self openGLContext] setValues:&opaque
  57. forParameter:NSOpenGLCPSurfaceOpacity];
  58. }
  59. - (void)drawRect:(NSRect)dirtyRect {
  60. // glClear(GL_COLOR_BUFFER_BIT);
  61. // glLoadIdentity();
  62. env::detail::resize_screen({{(int)dirtyRect.size.width,
  63. (int)dirtyRect.size.height}});
  64. if (game) {
  65. renderer->clear();
  66. game->render();
  67. }
  68. // glFlush();
  69. // the correct way to do double buffering on Mac is this:
  70. [[self openGLContext] flushBuffer];
  71. int err;
  72. if ((err = glGetError()) != 0) {
  73. NSLog(@"glGetError(): %d", err);
  74. }
  75. }
  76. - (void)reshape {
  77. NSRect newFrame = {0, 0, [[self window] frame].size.width,
  78. [[self window] frame].size.height};
  79. [self setFrame:newFrame];
  80. // window resize; width and height are in pixel coordinates
  81. // but they are floats
  82. float screen_w = [self frame].size.width;
  83. float screen_h = [self frame].size.height;
  84. // glViewport(0,0, screen_w, screen_h);
  85. // here I cast floats to ints; most systems use integer coordinate systems
  86. env::detail::resize_screen({{(int)screen_w, (int)screen_h}});
  87. }
  88. - (BOOL)acceptsFirstResponder {
  89. return YES;
  90. }
  91. - (void) press_key:(int)key forEvent:(NSEvent *)evt ns_key:(int)local
  92. down:(BOOL)pressed {
  93. if ([evt keyCode] == local) {
  94. game->process_key_event(key, pressed);
  95. }
  96. }
  97. - (void) toggle_key:(int)key forEvent:(NSEvent *)evt ns_key:(int)local {
  98. NSUInteger flags = [evt modifierFlags] &
  99. NSEventModifierFlagDeviceIndependentFlagsMask;
  100. game->process_key_event(key, flags & local);
  101. }
  102. - (void)keyDown:(NSEvent *)theEvent {
  103. if (!game) {
  104. // This is a really ugly hack because, for dumb reasons, there are two
  105. // GameView objects, one that I initialize, and one that I don't
  106. return [(GameView*)[[self window] delegate] keyDown:theEvent];
  107. }
  108. if ([theEvent isARepeat])
  109. return;
  110. NSString *str = [theEvent charactersIgnoringModifiers];
  111. unichar c = [str characterAtIndex:0];
  112. // only ASCII please
  113. if (c < ' ' || c > '~') {
  114. c = 0;
  115. }
  116. //(unsigned long)[theEvent modifierFlags]
  117. using namespace engine::keys;
  118. [self toggle_key:MOD_SHIFT forEvent:theEvent
  119. ns_key:NSEventModifierFlagShift];
  120. [self toggle_key:MOD_CONTROL forEvent:theEvent
  121. ns_key:NSEventModifierFlagControl];
  122. [self toggle_key:MOD_ALT forEvent:theEvent
  123. ns_key:NSEventModifierFlagOption];
  124. [self toggle_key:MOD_COMMAND forEvent:theEvent
  125. ns_key:NSEventModifierFlagCommand];
  126. [self press_key:UP_ARROW forEvent:theEvent ns_key:0x007e down:YES];
  127. [self press_key:DOWN_ARROW forEvent:theEvent ns_key:0x007d down:YES];
  128. [self press_key:LEFT_ARROW forEvent:theEvent ns_key:0x007b down:YES];
  129. [self press_key:RIGHT_ARROW forEvent:theEvent ns_key:0x007c down:YES];
  130. NSLog(@"keyDown -> { 0x%04x, 0x%08lx, 0x%02x=%c }", [theEvent keyCode],
  131. [theEvent modifierFlags], c, c);
  132. game->process_key_event(c, true);
  133. }
  134. - (void)keyUp:(NSEvent *)theEvent {
  135. if (!game) {
  136. // This is a really ugly hack because, for dumb reasons, there are two
  137. // GameView objects, one that I initialize, and one that I don't
  138. return [(GameView*)[[self window] delegate] keyDown:theEvent];
  139. }
  140. NSLog(@"keyUp -> { 0x%04x, 0x%08lx }", [theEvent keyCode],
  141. [theEvent modifierFlags]);
  142. NSString *str = [theEvent charactersIgnoringModifiers];
  143. unichar c = [str characterAtIndex:0];
  144. // only ASCII please
  145. if (c < ' ' || c > '~') {
  146. c = 0;
  147. }
  148. using namespace engine::keys;
  149. [self press_key:UP_ARROW forEvent:theEvent ns_key:0x007e down:NO];
  150. [self press_key:DOWN_ARROW forEvent:theEvent ns_key:0x007d down:NO];
  151. [self press_key:LEFT_ARROW forEvent:theEvent ns_key:0x007b down:NO];
  152. [self press_key:RIGHT_ARROW forEvent:theEvent ns_key:0x007c down:NO];
  153. game->process_key_event(c, false);
  154. }
  155. static NSTimer *timer = nil;
  156. static NSTimer *frameTimer = nil;
  157. static NSTimeInterval const FRAME_INTERVAL = 1.0 / 60.0;
  158. - (void)windowDidResignMain:(NSNotification *)notification {
  159. NSLog(@"window did resign main");
  160. [timer invalidate];
  161. [frameTimer invalidate];
  162. // env::pause_clock();
  163. [self setNeedsDisplay:YES];
  164. }
  165. - (void)windowDidBecomeMain:(NSNotification *)notification {
  166. NSLog(@"window did become main");
  167. // env::resume_clock();
  168. [self setNeedsDisplay:YES];
  169. // TODO (sjaffe): Become able to change framerate
  170. // TODO (sjaffe): Link this with env::fps::v60, etc.
  171. timer = [NSTimer timerWithTimeInterval:FRAME_INTERVAL
  172. target:self
  173. selector:@selector(timerEvent:)
  174. userInfo:nil
  175. repeats:YES];
  176. frameTimer = [NSTimer timerWithTimeInterval:FRAME_INTERVAL
  177. target:self
  178. selector:@selector(renderEvent:)
  179. userInfo:nil
  180. repeats:YES];
  181. [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
  182. [[NSRunLoop currentRunLoop] addTimer:frameTimer forMode:NSDefaultRunLoopMode];
  183. }
  184. - (void)renderEvent:(NSTimer *)t {
  185. game->render();
  186. [[self openGLContext] flushBuffer];
  187. }
  188. - (void)timerEvent:(NSTimer *)t {
  189. game->update();
  190. [self setNeedsDisplay:YES];
  191. }
  192. - (void) awakeFromNib
  193. {
  194. NSOpenGLPixelFormatAttribute attributes [] = {
  195. NSOpenGLPFADepthSize, (NSOpenGLPixelFormatAttribute)24,
  196. NSOpenGLPFAOpenGLProfile, NSOpenGLProfileVersion3_2Core,
  197. (NSOpenGLPixelFormatAttribute)0
  198. };
  199. NSOpenGLPixelFormat *pf = [[NSOpenGLPixelFormat alloc]
  200. initWithAttributes:attributes];
  201. [self setPixelFormat:pf];
  202. }
  203. @end