SDLRenderer::SDLRenderer() : m_window(), m_renderer(), m_viewport(), m_desktop_size(0, 0), m_scale(1.0f, 1.0f) { SDL_DisplayMode mode; if (SDL_GetDesktopDisplayMode(0, &mode) != 0) { log_warning << "Couldn't get desktop display mode: " << SDL_GetError() << std::endl; } else { m_desktop_size = Size(mode.w, mode.h); } log_info << "creating SDLRenderer" << std::endl; int width = g_config->window_size.width; int height = g_config->window_size.height; int flags = SDL_WINDOW_RESIZABLE; if(g_config->use_fullscreen) { if (g_config->fullscreen_size == Size(0, 0)) { flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; width = g_config->window_size.width; height = g_config->window_size.height; } else { flags |= SDL_WINDOW_FULLSCREEN; width = g_config->fullscreen_size.width; height = g_config->fullscreen_size.height; } } SCREEN_WIDTH = width; SCREEN_HEIGHT = height; m_viewport.x = 0; m_viewport.y = 0; m_viewport.w = width; m_viewport.h = height; SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "2"); int ret = SDL_CreateWindowAndRenderer(width, height, flags, &m_window, &m_renderer); if(ret != 0) { std::stringstream msg; msg << "Couldn't set video mode (" << width << "x" << height << "): " << SDL_GetError(); throw std::runtime_error(msg.str()); } SDL_RendererInfo info; if (SDL_GetRendererInfo(m_renderer, &info) != 0) { log_warning << "Couldn't get RendererInfo: " << SDL_GetError() << std::endl; } else { log_info << "SDL_Renderer: " << info.name << std::endl; log_info << "SDL_RendererFlags: " << std::endl; if (info.flags & SDL_RENDERER_SOFTWARE) { log_info << " SDL_RENDERER_SOFTWARE" << std::endl; } if (info.flags & SDL_RENDERER_ACCELERATED) { log_info << " SDL_RENDERER_ACCELERATED" << std::endl; } if (info.flags & SDL_RENDERER_PRESENTVSYNC) { log_info << " SDL_RENDERER_PRESENTVSYNC" << std::endl; } if (info.flags & SDL_RENDERER_TARGETTEXTURE) { log_info << " SDL_RENDERER_TARGETTEXTURE" << std::endl; } log_info << "Texture Formats: " << std::endl; for(size_t i = 0; i < info.num_texture_formats; ++i) { log_info << " " << SDL_GetPixelFormatName(info.texture_formats[i]) << std::endl; } log_info << "Max Texture Width: " << info.max_texture_width << std::endl; log_info << "Max Texture Height: " << info.max_texture_height << std::endl; } g_config->window_size = Size(width, height); apply_config(); }
int main(int argc, char *argv[]) { SDL_Window *window; // Declare a pointer, main window GLfloat dx = 0; GLfloat dy = 0; GLfloat zoom = 1.0; min_x = 0; max_x = width; min_y = 0; max_y = height; // Initialize SDL2 if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } // Create an application window with the following settings: window = SDL_CreateWindow("Drawing - OpenGL", // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position width, // width, in pixels height, // height, in pixels SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE // flags ); // Check that the window was successfully created if (window == NULL) { // In the case that the window could not be made... fprintf(stderr, "SDL_CreateWindow failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } SDL_Renderer *displayRenderer = NULL; SDL_RendererInfo displayRendererInfo; displayRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_GetRendererInfo(displayRenderer, &displayRendererInfo); if ((displayRendererInfo.flags & SDL_RENDERER_ACCELERATED) == 0 || (displayRendererInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) { fprintf(stderr, "We have no render surface and not accelerated.\n"); } Display_InitGL(); Display_SetViewport(width, height, dx, dy, zoom); int fullscreen = 0; int drag = 0; int xcursor = 0; int ycursor = 0; SDL_Event event; int quit = 0; time_t t = time(NULL); time_t ctime = time(NULL); int frames = 0; Display_Render(displayRenderer, width, height, dx, dy, zoom); while (!quit) { Display_SetViewport(width, height, dx, dy, zoom); Display_Render(displayRenderer, width, height, dx, dy, zoom); while (SDL_PollEvent(&event)) // User's actions { switch (event.type) { case SDL_QUIT: // Close button quit = 1; break; case SDL_KEYUP: // Key release if (event.key.keysym.sym == SDLK_f) // F key { if (fullscreen == 0) { fullscreen = 1; SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); } else if (fullscreen == 1) { fullscreen = 0; SDL_SetWindowFullscreen(window, 0); } } if (event.key.keysym.sym == SDLK_KP_PLUS) { if (zoom > 0.1) { dx = dx + 0.1 * pixelsize * (xcursor - width / 2); dy = dy - 0.1 * pixelsize * (ycursor - height / 2); } if (zoom > 0.1) zoom -= 0.1; } if (event.key.keysym.sym == SDLK_KP_MINUS) { dx = dx - 0.1 * pixelsize * (xcursor - width / 2); dy = dy + 0.1 * pixelsize * (ycursor - height / 2); zoom += 0.1; } if (event.key.keysym.sym == SDLK_r) { zoom = 1.0; dx = 0.0; dy = 0.0; } break; case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: width = event.window.data1; height = event.window.data2; break; case SDL_WINDOWEVENT_SIZE_CHANGED: width = event.window.data1; height = event.window.data2; break; default: // printf("Window %d got unknown event %d\n", event.window.windowID, event.window.event); break; } break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) drag = 1; break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) drag = 0; break; case SDL_MOUSEMOTION: xcursor = event.motion.x; ycursor = event.motion.y; if (drag != 0) { dx -= pixelsize * event.motion.xrel * zoom; dy += pixelsize * event.motion.yrel * zoom; } break; case SDL_MOUSEWHEEL: if (zoom > 0.03) { dx = dx + 0.03 * pixelsize * event.wheel.y * (xcursor - width / 2); dy = dy - 0.03 * pixelsize * event.wheel.y * (ycursor - height / 2); } if (event.wheel.y > 0 && zoom > 0.01) zoom -= 0.03; else if (event.wheel.y < 0) zoom += 0.03; break; default: //printf("unknown event"); break; } } frames++; ctime = time(NULL); if (t != ctime) { t = ctime; fprintf(stdout, "%d fps\n", frames); frames = 0; } } // Close and destroy the window SDL_DestroyWindow(window); // Clean up SDL_Quit(); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { AVFormatContext *pFormatCtx = NULL; int i, videoStream; AVCodecContext *pCodecCtx = NULL; AVCodec *pCodec = NULL; AVFrame *pFrame = NULL; AVPacket packet; int frameFinished; //float aspect_ratio; AVDictionary *optionsDict = NULL; struct SwsContext *sws_ctx = NULL; /*SDL_Overlay *bmp = NULL;*/ /*SDL_Surface *screen = NULL;*/ SDL_Rect rect; SDL_Event event; if(argc < 2) { fprintf(stderr, "Usage: test <file>\n"); exit(1); } // Register all formats and codecs av_register_all(); if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) { fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError()); exit(1); } // Open video file if(avformat_open_input(&pFormatCtx, argv[1], NULL, NULL)!=0) return -1; // Couldn't open file // Retrieve stream information if(avformat_find_stream_info(pFormatCtx, NULL)<0) return -1; // Couldn't find stream information // Dump information about file onto standard error av_dump_format(pFormatCtx, 0, argv[1], 0); // Find the first video stream videoStream=-1; for(i=0; i<pFormatCtx->nb_streams; i++) if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) { videoStream=i; break; } if(videoStream==-1) return -1; // Didn't find a video stream // Get a pointer to the codec context for the video stream pCodecCtx=pFormatCtx->streams[videoStream]->codec; // Find the decoder for the video stream pCodec=avcodec_find_decoder(pCodecCtx->codec_id); if(pCodec==NULL) { fprintf(stderr, "Unsupported codec!\n"); return -1; // Codec not found } // Open codec if(avcodec_open2(pCodecCtx, pCodec, &optionsDict)<0) return -1; // Could not open codec // Allocate video frame pFrame=avcodec_alloc_frame(); // Make a screen to put our video /*#ifndef __DARWIN__*/ /*screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 0, 0);*/ SDL_Window *sdlWindow = SDL_CreateWindow("sjr_title", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, pCodecCtx->width, pCodecCtx->height, SDL_WINDOW_FULLSCREEN_DESKTOP); /*#else*/ /*screen = SDL_SetVideoMode(pCodecCtx->width, pCodecCtx->height, 24, 0);*/ /*#endif*/ if(!sdlWindow) { fprintf(stderr, "SDL: could not Create window - exiting\n"); exit(1); } SDL_RendererInfo info; SDL_Texture *texture; SDL_Surface *image; SDL_Renderer *renderer = SDL_CreateRenderer(sdlWindow, -1, 0); if (!renderer) { fprintf(stderr, "Couldn't set create renderer: %s\n", SDL_GetError()); quit(6); } SDL_GetRendererInfo(renderer, &info); printf("Using %s rendering\n", info.name); texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, pCodecCtx->width, pCodecCtx->height); sws_ctx = sws_getContext( pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL ); // Read frames and save first five frames to disk i=0; while(av_read_frame(pFormatCtx, &packet)>=0) { // Is this a packet from the video stream? if(packet.stream_index==videoStream) { // Decode video frame avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet); // Did we get a video frame? if(frameFinished) { /*SDL_LockYUVOverlay(bmp);*/ AVPicture pict; pict.data[0] = pFrame->data[0]; pict.data[1] = pFrame->data[2]; pict.data[2] = pFrame->data[1]; pict.linesize[0] = pFrame->linesize[0]; pict.linesize[1] = pFrame->linesize[2]; pict.linesize[2] = pFrame->linesize[1]; // Convert the image into YUV format that SDL uses sws_scale( sws_ctx, (uint8_t const * const *)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, pict.data, pict.linesize ); /*SDL_UnlockYUVOverlay(bmp);*/ rect.x = 0; rect.y = 0; rect.w = pCodecCtx->width; rect.h = pCodecCtx->height; /*SDL_DisplayYUVOverlay(bmp, &rect);*/ } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); SDL_PollEvent(&event); switch(event.type) { case SDL_QUIT: SDL_Quit(); exit(0); break; default: break; } } // Free the YUV frame av_free(pFrame); // Close the codec avcodec_close(pCodecCtx); // Close the video file avformat_close_input(&pFormatCtx); return 0; }
SDL_Surface *ANDROID_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags) { SDL_PixelFormat format; int bpp1; __android_log_print(ANDROID_LOG_INFO, "libSDL", "SDL_SetVideoMode(): application requested mode %dx%d OpenGL %d HW %d BPP %d", width, height, flags & SDL_OPENGL, flags & SDL_HWSURFACE, SDL_ANDROID_BITSPERPIXEL); if( ! SDL_ANDROID_InsideVideoThread() ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Error: calling %s not from the main thread!", __PRETTY_FUNCTION__); return NULL; } sdl_opengl = (flags & SDL_OPENGL) ? 1 : 0; SDL_ANDROID_sFakeWindowWidth = width; SDL_ANDROID_sFakeWindowHeight = height; current->flags = (flags & SDL_FULLSCREEN) | (flags & SDL_OPENGL) | SDL_DOUBLEBUF | ( flags & SDL_HWSURFACE ); current->w = width; current->h = height; current->pitch = SDL_ANDROID_sFakeWindowWidth * SDL_ANDROID_BYTESPERPIXEL; current->pixels = NULL; current->hwdata = NULL; HwSurfaceCount = 0; HwSurfaceList = NULL; DEBUGOUT("ANDROID_SetVideoMode() HwSurfaceCount %d HwSurfaceList %p", HwSurfaceCount, HwSurfaceList); if( ! sdl_opengl ) { SDL_DisplayMode mode; SDL_RendererInfo SDL_VideoRendererInfo; SDL_SelectVideoDisplay(0); SDL_VideoWindow = SDL_CreateWindow("", 0, 0, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL); SDL_memset(&mode, 0, sizeof(mode)); mode.format = PixelFormatEnum; SDL_SetWindowDisplayMode(SDL_VideoWindow, &mode); if (SDL_CreateRenderer(SDL_VideoWindow, -1, 0) < 0) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "SDL_SetVideoMode(): Error creating renderer"); return NULL; } SDL_GetRendererInfo(&SDL_VideoRendererInfo); current->hwdata = NULL; if( ! (flags & SDL_HWSURFACE) ) { current->pixels = SDL_malloc(width * height * SDL_ANDROID_BYTESPERPIXEL); if ( ! current->pixels ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Couldn't allocate buffer for requested mode"); SDL_SetError("Couldn't allocate buffer for requested mode"); return(NULL); } SDL_memset(current->pixels, 0, width * height * SDL_ANDROID_BYTESPERPIXEL); current->hwdata = (struct private_hwdata *)SDL_CreateTexture(PixelFormatEnum, SDL_TEXTUREACCESS_STATIC, width, height); if( !current->hwdata ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Couldn't allocate texture for SDL_CurrentVideoSurface"); SDL_free(current->pixels); current->pixels = NULL; SDL_OutOfMemory(); return(NULL); } if( SDL_ANDROID_SmoothVideo ) SDL_SetTextureScaleMode((SDL_Texture *)current->hwdata, SDL_SCALEMODE_SLOW); // Register main video texture to be recreated when needed HwSurfaceCount++; HwSurfaceList = SDL_realloc( HwSurfaceList, HwSurfaceCount * sizeof(SDL_Surface *) ); HwSurfaceList[HwSurfaceCount-1] = current; DEBUGOUT("ANDROID_SetVideoMode() HwSurfaceCount %d HwSurfaceList %p", HwSurfaceCount, HwSurfaceList); } glViewport(0, 0, SDL_ANDROID_sRealWindowWidth, SDL_ANDROID_sRealWindowHeight); glOrthof(0.0, (GLfloat) SDL_ANDROID_sWindowWidth, (GLfloat) SDL_ANDROID_sWindowHeight, 0.0, 0.0, 1.0); } /* Allocate the new pixel format for the screen */ SDL_memset(&format, 0, sizeof(format)); SDL_PixelFormatEnumToMasks( PixelFormatEnum, &bpp1, &format.Rmask, &format.Gmask, &format.Bmask, &format.Amask ); format.BitsPerPixel = bpp1; format.BytesPerPixel = SDL_ANDROID_BYTESPERPIXEL; if ( ! SDL_ReallocFormat(current, SDL_ANDROID_BITSPERPIXEL, format.Rmask, format.Gmask, format.Bmask, format.Amask) ) { __android_log_print(ANDROID_LOG_INFO, "libSDL", "Couldn't allocate new pixel format for requested mode"); SDL_SetError("Couldn't allocate new pixel format for requested mode"); return(NULL); } /* Set up the new mode framebuffer */ SDL_CurrentVideoSurface = current; /* We're done */ return(current); }
SDL_bool CommonInit(CommonState * state) { int i, j, m, n; SDL_DisplayMode fullscreen_mode; if (state->flags & SDL_INIT_VIDEO) { if (state->verbose & VERBOSE_VIDEO) { n = SDL_GetNumVideoDrivers(); if (n == 0) { fprintf(stderr, "No built-in video drivers\n"); } else { fprintf(stderr, "Built-in video drivers:"); for (i = 0; i < n; ++i) { if (i > 0) { fprintf(stderr, ","); } fprintf(stderr, " %s", SDL_GetVideoDriver(i)); } fprintf(stderr, "\n"); } } if (SDL_VideoInit(state->videodriver, 0) < 0) { fprintf(stderr, "Couldn't initialize video driver: %s\n", SDL_GetError()); return SDL_FALSE; } if (state->verbose & VERBOSE_VIDEO) { fprintf(stderr, "Video driver: %s\n", SDL_GetCurrentVideoDriver()); } if (state->verbose & VERBOSE_MODES) { SDL_DisplayMode mode; int bpp; Uint32 Rmask, Gmask, Bmask, Amask; n = SDL_GetNumVideoDisplays(); fprintf(stderr, "Number of displays: %d\n", n); for (i = 0; i < n; ++i) { fprintf(stderr, "Display %d:\n", i); SDL_SelectVideoDisplay(i); SDL_GetDesktopDisplayMode(&mode); SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask, &Bmask, &Amask); fprintf(stderr, " Current mode: %dx%d@%dHz, %d bits-per-pixel\n", mode.w, mode.h, mode.refresh_rate, bpp); if (Rmask || Gmask || Bmask) { fprintf(stderr, " Red Mask = 0x%.8x\n", Rmask); fprintf(stderr, " Green Mask = 0x%.8x\n", Gmask); fprintf(stderr, " Blue Mask = 0x%.8x\n", Bmask); if (Amask) fprintf(stderr, " Alpha Mask = 0x%.8x\n", Amask); } /* Print available fullscreen video modes */ m = SDL_GetNumDisplayModes(); if (m == 0) { fprintf(stderr, "No available fullscreen video modes\n"); } else { fprintf(stderr, " Fullscreen video modes:\n"); for (j = 0; j < m; ++j) { SDL_GetDisplayMode(j, &mode); SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask, &Bmask, &Amask); fprintf(stderr, " Mode %d: %dx%d@%dHz, %d bits-per-pixel\n", j, mode.w, mode.h, mode.refresh_rate, bpp); if (Rmask || Gmask || Bmask) { fprintf(stderr, " Red Mask = 0x%.8x\n", Rmask); fprintf(stderr, " Green Mask = 0x%.8x\n", Gmask); fprintf(stderr, " Blue Mask = 0x%.8x\n", Bmask); if (Amask) fprintf(stderr, " Alpha Mask = 0x%.8x\n", Amask); } } } } } SDL_SelectVideoDisplay(state->display); if (state->verbose & VERBOSE_RENDER) { SDL_RendererInfo info; n = SDL_GetNumRenderDrivers(); if (n == 0) { fprintf(stderr, "No built-in render drivers\n"); } else { fprintf(stderr, "Built-in render drivers:\n"); for (i = 0; i < n; ++i) { SDL_GetRenderDriverInfo(i, &info); PrintRenderer(&info); } } } switch (state->depth) { case 8: fullscreen_mode.format = SDL_PIXELFORMAT_INDEX8; break; case 15: fullscreen_mode.format = SDL_PIXELFORMAT_RGB555; break; case 16: fullscreen_mode.format = SDL_PIXELFORMAT_RGB565; break; default: fullscreen_mode.format = SDL_PIXELFORMAT_RGB888; break; } fullscreen_mode.w = state->window_w; fullscreen_mode.h = state->window_h; fullscreen_mode.refresh_rate = state->refresh_rate; SDL_SetFullscreenDisplayMode(&fullscreen_mode); state->windows = (SDL_WindowID *) SDL_malloc(state->num_windows * sizeof(*state->windows)); if (!state->windows) { fprintf(stderr, "Out of memory!\n"); return SDL_FALSE; } for (i = 0; i < state->num_windows; ++i) { char title[1024]; if (state->num_windows > 1) { SDL_snprintf(title, SDL_arraysize(title), "%s %d", state->window_title, i + 1); } else { SDL_strlcpy(title, state->window_title, SDL_arraysize(title)); } state->windows[i] = SDL_CreateWindow(title, state->window_x, state->window_y, state->window_w, state->window_h, state->window_flags); if (!state->windows[i]) { fprintf(stderr, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } if (!state->skip_renderer && (state->renderdriver || !(state->window_flags & SDL_WINDOW_OPENGL))) { m = -1; if (state->renderdriver) { SDL_RendererInfo info; n = SDL_GetNumRenderDrivers(); for (j = 0; j < n; ++j) { SDL_GetRenderDriverInfo(j, &info); if (SDL_strcasecmp(info.name, state->renderdriver) == 0) { m = j; break; } } if (m == n) { fprintf(stderr, "Couldn't find render driver named %s", state->renderdriver); return SDL_FALSE; } } if (SDL_CreateRenderer (state->windows[i], m, state->render_flags) < 0) { fprintf(stderr, "Couldn't create renderer: %s\n", SDL_GetError()); return SDL_FALSE; } if (state->verbose & VERBOSE_RENDER) { SDL_RendererInfo info; fprintf(stderr, "Current renderer:\n"); SDL_GetRendererInfo(&info); PrintRenderer(&info); } } } SDL_SelectRenderer(state->windows[0]); } if (state->flags & SDL_INIT_AUDIO) { if (state->verbose & VERBOSE_AUDIO) { n = SDL_GetNumAudioDrivers(); if (n == 0) { fprintf(stderr, "No built-in audio drivers\n"); } else { fprintf(stderr, "Built-in audio drivers:"); for (i = 0; i < n; ++i) { if (i > 0) { fprintf(stderr, ","); } fprintf(stderr, " %s", SDL_GetAudioDriver(i)); } fprintf(stderr, "\n"); } } if (SDL_AudioInit(state->audiodriver) < 0) { fprintf(stderr, "Couldn't initialize audio driver: %s\n", SDL_GetError()); return SDL_FALSE; } if (state->verbose & VERBOSE_VIDEO) { fprintf(stderr, "Audio driver: %s\n", SDL_GetCurrentAudioDriver()); } if (SDL_OpenAudio(&state->audiospec, NULL) < 0) { fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); return SDL_FALSE; } } return SDL_TRUE; }
//------------------------------------------------------------------------ bool platform_support::init(unsigned width, unsigned height, unsigned flags) { ERROR_PRINT("platform_support::init %d,%d\n", width, height); m_window_flags = flags; int wflags = 0; if(m_specific->m_texture) SDL_DestroyTexture(m_specific->m_texture); if(m_specific->m_renderer) SDL_DestroyRenderer(m_specific->m_renderer); if(m_specific->m_surface) SDL_FreeSurface(m_specific->m_surface); //if(m_specific->m_mwindow) SDL_DestroyWindow(m_specific->m_mwindow); m_specific->m_texture = 0; m_specific->m_renderer = 0; m_specific->m_surface = 0; //m_specific->m_mwindow = 0; if(m_window_flags & window_resize) { wflags |= SDL_WINDOW_RESIZABLE; } if(m_window_flags & window_fullscreen) { wflags |= SDL_WINDOW_FULLSCREEN; #ifdef __ANDROID__DISABLED width = Android_ScreenWidth; height = Android_ScreenHeight; #endif #ifdef __ANDROID__ if (m_window_flags & window_keep_aspect_ratio) { width = (double)Android_ScreenWidth/Android_ScreenHeight*height; width_factor = (double)width/Android_ScreenWidth; hight_factor = (double)height/Android_ScreenHeight; } #endif } DEBUG_PRINT("platform_support::init %d,%d,%d", width, height, wflags); int numRendDrv = SDL_GetNumRenderDrivers(); DEBUG_PRINT("num rend drv %d\n", numRendDrv); for (int i = 0; i < numRendDrv; i++) { SDL_RendererInfo info; SDL_GetRenderDriverInfo(i, &info); DEBUG_PRINT("index %i, %s, flags %x, texture formats %x\n", i, info.name, info.flags, info.texture_formats[0]); } if (!m_specific->m_mwindow) { m_specific->m_mwindow = SDL_CreateWindow(m_caption, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, wflags); } if (m_specific->m_mwindow == 0) { ERROR_PRINT( "Unable to create %dx%d %d bpp window: %s\n", width, height, m_bpp, SDL_GetError()); return false; } m_specific->m_surface = SDL_CreateRGBSurface(0, width, height, m_bpp, m_specific->m_rmask, m_specific->m_gmask, m_specific->m_bmask, m_specific->m_amask); DEBUG_PRINT("surface at %p", m_specific->m_surface); if(m_specific->m_surface == 0) { ERROR_PRINT( "Unable to create image buffer %dx%d %d bpp: %s\n", width, height, m_bpp, SDL_GetError()); return false; } m_specific->m_renderer = SDL_CreateRenderer(m_specific->m_mwindow, -1, 0); if(m_specific->m_renderer == 0) { ERROR_PRINT( "Unable to create renderer: %s\n", SDL_GetError()); return false; } { SDL_RendererInfo info; SDL_GetRendererInfo(m_specific->m_renderer, &info); DEBUG_PRINT("Current, %s, flags %x, texture formats %x, %x\n", info.name, info.flags, SDL_PIXELFORMAT_ARGB8888, info.texture_formats[0]); } m_specific->m_texture = SDL_CreateTexture( m_specific->m_renderer, m_specific->m_pformat, SDL_TEXTUREACCESS_STREAMING, width, height); if(m_specific->m_renderer == 0) { ERROR_PRINT( "Unable to create texture: %s\n", SDL_GetError()); return false; } void* pixels; int pitch; if (SDL_LockTexture(m_specific->m_texture, NULL, &pixels, &pitch) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't lock texture: %s\n", SDL_GetError()); } m_rbuf_window.attach((unsigned char*)pixels, width, height, m_flip_y ? -pitch : pitch); if (!m_specific->m_initialized) { m_initial_width = width; m_initial_height = height; on_init(); m_specific->m_initialized = true; } on_resize(m_rbuf_window.width(), m_rbuf_window.height()); m_specific->m_update_flag = true; return true; }
int main(int argc, char **argv) { if(SDL_Init(SDL_INIT_VIDEO) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); return -1; } if(TTF_Init() < 0) { fprintf(stderr, "Couldn't initialize font rendering: %s\n", TTF_GetError()); return -1; } int width = 800; int height = 600; Uint32 frameRate = BASE_FRAME_RATE_MS; SDL_bool vsync = SDL_FALSE; #if SDL_MAJOR_VERSION == 2 SDL_DisplayMode current; for(int i = 0; i < SDL_GetNumVideoDisplays(); ++i){ if(SDL_GetCurrentDisplayMode(i, ¤t) != 0) fprintf(stderr, "Couldn't get display mode: %s\n", SDL_GetError()); else { printf("Display %d is %dx%d\n", i, current.w, current.h); width = current.w; height = current.h; } } Uint32 flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC; if(argc > 1) { if(strncmp(argv[1], "-novsync", 8) == 0) flags &= ~SDL_RENDERER_PRESENTVSYNC; if(strncmp(argv[1], "-software", 9) == 0) flags = SDL_RENDERER_SOFTWARE; char *n = strchr(argv[1], '='); if(n) { n++; frameRate = strtoul(n, 0, 0); } } SDL_Window *window = SDL_CreateWindow(argv[0], SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width + GetIntelOffset(), height, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, flags); SDL_ShowCursor(SDL_DISABLE); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); SDL_DisableScreenSaver(); SDL_RendererInfo info; if(SDL_GetRendererInfo(renderer, &info) == 0) { printf("Using video driver: %s with renderer %s\n", SDL_GetCurrentVideoDriver(), info.name); if(info.flags & SDL_RENDERER_SOFTWARE) printf("*** Using SDL_RENDERER_SOFTWARE\n"); if(info.flags & SDL_RENDERER_ACCELERATED) printf("*** Using SDL_RENDERER_ACCELERATED\n"); if(info.flags & SDL_RENDERER_PRESENTVSYNC) { printf("*** Using SDL_RENDERER_PRESENTVSYNC\n"); vsync = SDL_TRUE; } if(info.flags & SDL_RENDERER_TARGETTEXTURE) printf("*** Using SDL_RENDERER_TARGETTEXTURE\n"); } #else const SDL_VideoInfo *pVideoInfo = SDL_GetVideoInfo(); if(pVideoInfo == 0) { fprintf(stderr, "Couldn't get display information: %s\n", SDL_GetError()); exit(1); } printf("Display is %dx%d\n", pVideoInfo->current_w, pVideoInfo->current_h); width = pVideoInfo->current_w; height = pVideoInfo->current_h; SDL_Surface *screen = SDL_SetVideoMode(width, height, pVideoInfo->vfmt->BitsPerPixel, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN); if(screen == 0) { fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError()); exit(1); } SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_ShowCursor(SDL_DISABLE); #endif TTF_Font *font = TTF_OpenFont("AlteHaasGroteskBold.ttf", 60); if(font == 0) { fprintf(stderr, "Can't open font for stats: %s", TTF_GetError()); goto cleanup; } SDL_Event event; SDL_bool m_run = SDL_TRUE; Uint32 lastFrame = 0; float fps = 0.0f; SDL_Color foregroundColor = { 0xff, 0xff, 0 }; char tmp[64]; int delta = 1; int position = 0; while(m_run) { while(SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if(event.key.keysym.sym == SDLK_ESCAPE) m_run = SDL_FALSE; break; case SDL_QUIT: m_run = SDL_FALSE; break; default: break; } } Uint32 start = SDL_GetTicks(); #if SDL_MAJOR_VERSION == 2 SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xff); SDL_RenderClear(renderer); #else SDL_FillRect(screen, 0, 0); #endif snprintf(tmp, sizeof(tmp), "Current fps = %.1f", fps); SDL_Surface *textSurface = TTF_RenderText_Solid(font, tmp, foregroundColor); if(textSurface) { #if SDL_MAJOR_VERSION == 2 SDL_Texture *textTexture = SDL_CreateTextureFromSurface(renderer, textSurface); #endif SDL_Rect location; location.h = textSurface->h; location.w = textSurface->w; location.x = position; location.y = height / 2 - textSurface->h / 2; #if SDL_MAJOR_VERSION == 1 SDL_BlitSurface(textSurface, 0, screen, &location); #endif SDL_FreeSurface(textSurface); position += delta; if(position >= width - textSurface->w || position <= 0) delta *= -1; #if SDL_MAJOR_VERSION == 2 if(textTexture) { SDL_RenderCopy(renderer, textTexture, 0, &location); SDL_DestroyTexture(textTexture); } #endif } #if SDL_MAJOR_VERSION == 2 SDL_RenderPresent(renderer); #else SDL_Flip(screen); #endif Uint32 end = SDL_GetTicks(); Uint32 elapsed = end - lastFrame; // delay for the remainder of the base rate so we keep a decent frame rate if there's no vsync if(vsync == SDL_FALSE && frameRate > elapsed) SDL_Delay(frameRate - elapsed); if(elapsed > frameRate * 3) { struct timeb tp; ftime(&tp); time_t now; struct tm *ti; char buf[255]; time(&now); ti = localtime(&now); strftime(buf, sizeof(buf), "%I:%M:%S", ti); printf("%s.%d: Frame took %ums\n", buf, tp.millitm, elapsed); } // remember now as the starting point for the next frame lastFrame = SDL_GetTicks(); // update statistics elapsed = lastFrame - start; fps = 1000.0f / (float)elapsed; //printf("Current frame rate is %6.3f fps (%ums) \r", fps, elapsed); } printf("\n"); cleanup: #if SDL_MAJOR_VERSION == 2 SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); #else SDL_FreeSurface(screen); #endif TTF_Quit(); SDL_Quit(); return 0; }
int main(int argc, char *argv[]) { int i; SDL_Event event; Uint32 then, now, frames; FPSmanager fpsm; /* Initialize test framework */ state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO); if (!state) { return 1; } SDL_Log("SDL2_gfx %i.%i.%i: testframerate", SDL2_GFXPRIMITIVES_MAJOR, SDL2_GFXPRIMITIVES_MINOR, SDL2_GFXPRIMITIVES_MICRO); SDL_Log("Platform: %s", SDL_GetPlatform()); for (i = 1; i < argc;) { int consumed; consumed = SDLTest_CommonArg(state, i); if (consumed == 0) { consumed = -1; if (SDL_strcasecmp(argv[i], "--x") == 0) { if (argv[i + 1]) { x = SDL_atoi(argv[i + 1]); if (x < 0) x = 0; if (x >= WIDTH) x = WIDTH - 1; consumed = 2; } } else if (SDL_strcasecmp(argv[i], "--y") == 0) { if (argv[i + 1]) { y = SDL_atoi(argv[i + 1]); if (y < 0) y = 0; if (y >= HEIGHT) y = HEIGHT - 1; consumed = 2; } } } if (consumed < 0) { SDL_Log("Usage: %s %s [--x #] [--y #]\n", argv[0], SDLTest_CommonUsage(state)); return 1; } i += consumed; } if (!SDLTest_CommonInit(state)) { return 2; } /* Create the windows and initialize the renderers */ for (i = 0; i < state->num_windows; ++i) { SDL_Renderer *renderer = state->renderers[i]; SDL_RendererInfo info; SDL_GetRendererInfo(state->renderers[i], &info); SDL_Log("Renderer %i: %s %s", i, info.name, (info.flags | SDL_RENDERER_ACCELERATED) ? "(Accelerated)" : ""); SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF); SDL_RenderClear(renderer); } /* Initialize random number generator */ srand((unsigned int)time(NULL)); /* Create common message buffer */ messageText = (char *)SDL_malloc(1024); if (messageText == NULL) { return -1; } /* Initialize framerate manager */ SDL_initFramerate(&fpsm); /* Main render loop */ frames = 0; then = SDL_GetTicks(); done = 0; while (!done) { /* Check for events */ ++frames; while (SDL_PollEvent(&event) && !done) { SDLTest_CommonEvent(state, &event, &done); } /* Do all the drawing work */ Draw(state->renderers[0], &fpsm); } /* Print out some timing information */ now = SDL_GetTicks(); if (now > then) { double fps = ((double) frames * 1000) / (now - then); SDL_Log("%2.2f frames per second\n", fps); } /* Free common message buffer */ if (messageText) { free(messageText); } /* Shutdown SDL */ SDLTest_CommonQuit(state); return 0; }
extern SkinSurface* skin_surface_create_window(int x, int y, int w, int h, int original_w, int original_h, int is_fullscreen) { static SkinSurface* result = NULL; SDL_Window* window = skin_winsys_get_window(); SDL_Renderer* renderer = globals_get_renderer(); D("%s: x=%d y=%d w=%d h=%d original_w=%d original_h=%d is_fullscreen=%d", __FUNCTION__, x, y, w, h, original_w, original_h, is_fullscreen); // Textures do not survive window resize events, so globals_foreach_surface(&_skin_surface_destroy_texture, NULL); if (!window) { // NOTE: Don't use SDL_WINDOW_ALLOW_HIGHDPI here. On OS X, this will // make mouse event coordinates twice smaller than needed // when running on a high-dpi machine (e.g. recent MacBook Pro), // making the UI unusable. Note that this doesn't happen on a // 'low-dpi' device such as a MacPro connected to a 30" monitor. int window_flags = SDL_WINDOW_OPENGL; if (is_fullscreen) { window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; } window = SDL_CreateWindow("Android emulator", x, y, w, h, window_flags); if (!window) { panic("Could not create SDL2 window: %s\n", SDL_GetError()); } skin_winsys_set_window(window); } else { if (is_fullscreen) { SDL_CHECK(SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP)); #if DEBUG #endif } else { SDL_CHECK(SDL_SetWindowFullscreen(window, 0)); SDL_SetWindowPosition(window, x, y); SDL_SetWindowSize(window, w, h); } } // Generate renderer if (!renderer) { SDL_CHECK(SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear")); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED| SDL_RENDERER_PRESENTVSYNC| SDL_RENDERER_TARGETTEXTURE); if (!renderer) { panic("Could not create renderer: %s\n", SDL_GetError()); } globals_set_renderer(renderer); } SDL_CHECK(SDL_RenderSetLogicalSize(renderer, original_w, original_h)); if (DEBUG && VERBOSE_CHECK(surface)) { SDL_RendererInfo info; SDL_CHECK(SDL_GetRendererInfo(renderer, &info)); printf("renderer.name = %s\n", info.name); printf("renderer.flags = 0x%x\n", info.flags); printf("renderer.num_texture_formats = %d\n", info.num_texture_formats); int nn; for (nn = 0; nn < info.num_texture_formats; ++nn) { printf(" 0x%x (%s)\n", info.texture_formats[nn], SDL_GetPixelFormatName(info.texture_formats[nn])); } printf("renderer.max_texture_width = %d\n", info.max_texture_width); printf("renderer.max_texture_height = %d\n", info.max_texture_height); } // Compute scaling parameters. { int window_x, window_y, window_w, window_h; SDL_GetWindowSize(window, &window_w, &window_h); SDL_GetWindowPosition(window, &window_x, &window_y); D("Window pos=(%d,%d) size=(%d,%d)", window_x, window_y, window_w, window_h); double x_scale = window_w * 1.0 / original_w; double y_scale = window_h * 1.0 / original_h; double scale = (x_scale <= y_scale) ? x_scale : y_scale; double effective_x = 0.; double effective_y = 0.; if (is_fullscreen) { effective_x = (window_w - original_w * scale) * 0.5; effective_y = (window_h - original_h * scale) * 0.5; } globals_set_window_scale(scale, effective_x, effective_y); } SDL_Texture* texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, original_w, original_h); if (!texture) { panic("Could not create window texture: %s", SDL_GetError()); } SDL_CHECK(SDL_SetRenderTarget(renderer, texture)); SDL_CHECK(SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255)); SDL_CHECK(SDL_RenderClear(renderer)); SDL_CHECK(SDL_SetRenderTarget(renderer, NULL)); SDL_CHECK(SDL_SetRenderDrawColor(renderer, 0, 0, 128, 255)); SDL_CHECK(SDL_RenderClear(renderer)); SDL_CHECK(SDL_RenderCopy(renderer, texture, NULL, NULL)); SDL_RenderPresent(renderer); if (!result) { result = _skin_surface_create(NULL, texture, original_w, original_h); } else { result->texture = texture; result->w = original_w; result->h = original_h; } skin_surface_ref(result); // Ensure all textures are regenerated properly. globals_foreach_surface(&_skin_surface_reset_texture, renderer); return result; }
int main(int argc, char *argv[]) { const unsigned int cameraIndex = 0u; const unsigned int numImagesPerFPSMeasurement = 240u; const int windowWidth = 1440; const int windowHeight = 900; const char cascadeFilename[] = "haarcascade_frontalface_alt.xml"; const double detectionScaleFactor = 1.25; const int detectionMinNeighbours = 4; const int detectionFlags = CV_HAAR_SCALE_IMAGE; const cv::Size detectionMinSize(120, 120); const cv::Size detectionMaxSize; const cv::Scalar detectionDrawColor(255.0, 0.0, 255.0); char strBuffer[256u]; const size_t strBufferSize = 256u; int matType; cv::Mat equalizedGrayMat; #ifdef _WIN32 snprintf(strBuffer, strBufferSize, "%s/../%s", argv[0], cascadeFilename); cv::CascadeClassifier detector(strBuffer); #else cv::CascadeClassifier detector(cascadeFilename); #endif if (detector.empty()) { snprintf(strBuffer, strBufferSize, "%s could not be loaded.", cascadeFilename); SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Failed to Load Cascade File", strBuffer, NULL); return EXIT_FAILURE; } std::vector<cv::Rect> detectionRects; fc2Error error; fc2Image image; error = fc2CreateImage(&image); if (error != FC2_ERROR_OK) { showFC2Error(error); return EXIT_FAILURE; } fc2Context context; error = fc2CreateContext(&context); if (error != FC2_ERROR_OK) { showFC2Error(error); return EXIT_FAILURE; } fc2PGRGuid cameraGUID; error = fc2GetCameraFromIndex(context, cameraIndex, &cameraGUID); if (error != FC2_ERROR_OK) { showFC2Error(error); return EXIT_FAILURE; } error = fc2Connect(context, &cameraGUID); if (error != FC2_ERROR_OK) { showFC2Error(error); return EXIT_FAILURE; } error = fc2StartCapture(context); if (error != FC2_ERROR_OK) { fc2Disconnect(context); showFC2Error(error); return EXIT_FAILURE; } if (SDL_Init(SDL_INIT_VIDEO) < 0) { fc2StopCapture(context); fc2Disconnect(context); showSDLError(); return EXIT_FAILURE; } SDL_Window *window = SDL_CreateWindow( "LookSpry", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, windowWidth, windowHeight, 0u); if (window == NULL) { fc2StopCapture(context); fc2Disconnect(context); showSDLError(); return EXIT_FAILURE; } SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0u); if (renderer == NULL) { fc2StopCapture(context); fc2Disconnect(context); SDL_DestroyWindow(window); showSDLError(); return EXIT_FAILURE; } SDL_RendererInfo rendererInfo; SDL_GetRendererInfo(renderer, &rendererInfo); if (strcmp(rendererInfo.name, "direct3d") == 0) { SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best"); } else if (strcmp(rendererInfo.name, "opengl") == 0) { SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); } snprintf(strBuffer, strBufferSize, "LookSpry | %s", rendererInfo.name); SDL_SetWindowTitle(window, strBuffer); SDL_Texture *videoTex = NULL; void *videoTexPixels; int pitch; clock_t startTicks = clock(); clock_t endTicks; unsigned int numImagesCaptured = 0u; bool running = true; bool detecting = true; bool mirroring = true; SDL_Event event; while (running) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; break; } else if (event.type == SDL_KEYUP) { switch(event.key.keysym.sym) { // When 'd' is pressed, start or stop [d]etection. case SDLK_d: detecting = !detecting; break; // When 'm' is pressed, [m]irror or un-mirror the video. case SDLK_m: mirroring = !mirroring; break; default: break; } } } error = fc2RetrieveBuffer(context, &image); if (error != FC2_ERROR_OK) { fc2Disconnect(context); SDL_DestroyTexture(videoTex); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); showFC2Error(error); return EXIT_FAILURE; } if (videoTex == NULL) { equalizedGrayMat.create(image.rows, image.cols, CV_8UC1); SDL_RenderSetLogicalSize(renderer, image.cols, image.rows); Uint32 videoTexPixelFormat; switch (image.format) { // For monochrome capture modes, plan to render captured data to the Y // plane of a planar YUV texture. case FC2_PIXEL_FORMAT_RAW8: case FC2_PIXEL_FORMAT_MONO8: videoTexPixelFormat = SDL_PIXELFORMAT_YV12; matType = CV_8UC1; break; // For color capture modes, plan to render captured data to the entire // space of a texture in a matching color format. case FC2_PIXEL_FORMAT_422YUV8: videoTexPixelFormat = SDL_PIXELFORMAT_UYVY; matType = CV_8UC2; break; case FC2_PIXEL_FORMAT_RGB: videoTexPixelFormat = SDL_PIXELFORMAT_RGB24; matType = CV_8UC3; break; case FC2_PIXEL_FORMAT_BGR: videoTexPixelFormat = SDL_PIXELFORMAT_BGR24; matType = CV_8UC3; break; default: fc2StopCapture(context); fc2Disconnect(context); SDL_DestroyTexture(videoTex); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR, "Unsupported FlyCapture2 Pixel Format", "LookSpry supports RAW8, MONO8, 422YUV8, RGB, and BGR.", NULL); return EXIT_FAILURE; } videoTex = SDL_CreateTexture( renderer, videoTexPixelFormat, SDL_TEXTUREACCESS_STREAMING, image.cols, image.rows); if (videoTex == NULL) { fc2StopCapture(context); fc2Disconnect(context); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); showSDLError(); return EXIT_FAILURE; } snprintf( strBuffer, strBufferSize, "LookSpry | %s | %dx%d --> %dx%d", rendererInfo.name, image.cols, image.rows, windowWidth, windowHeight); SDL_SetWindowTitle(window, strBuffer); } cv::Mat srcMat(image.rows, image.cols, matType, image.pData, image.stride); if (detecting) { switch (image.format) { // For monochrome capture modes, just equalize. case FC2_PIXEL_FORMAT_RAW8: case FC2_PIXEL_FORMAT_MONO8: cv::equalizeHist(srcMat, equalizedGrayMat); break; // For color capture modes, convert to gray and equalize. case FC2_PIXEL_FORMAT_422YUV8: cv::cvtColor(srcMat, equalizedGrayMat, cv::COLOR_YUV2GRAY_UYVY); cv::equalizeHist(equalizedGrayMat, equalizedGrayMat); break; case FC2_PIXEL_FORMAT_RGB: cv::cvtColor(srcMat, equalizedGrayMat, cv::COLOR_RGB2GRAY); cv::equalizeHist(equalizedGrayMat, equalizedGrayMat); break; case FC2_PIXEL_FORMAT_BGR: cv::cvtColor(srcMat, equalizedGrayMat, cv::COLOR_BGR2GRAY); cv::equalizeHist(equalizedGrayMat, equalizedGrayMat); break; default: break; } // Run the detector on the equalized image. detector.detectMultiScale( equalizedGrayMat, detectionRects, detectionScaleFactor, detectionMinNeighbours, detectionFlags, detectionMinSize, detectionMaxSize); // Draw the resulting detection rectangles on the original image. for (cv::Rect detectionRect : detectionRects) { cv::rectangle(srcMat, detectionRect, detectionDrawColor); } } SDL_LockTexture(videoTex, NULL, &videoTexPixels, &pitch); switch (image.format) { case FC2_PIXEL_FORMAT_RAW8: case FC2_PIXEL_FORMAT_MONO8: // Make the planar YUV video gray by setting all bytes in its U and V // planes to 128 (the middle of the range). memset(((unsigned char *)videoTexPixels + image.dataSize), 128, image.dataSize / 2u); break; default: break; } if (mirroring) { // Flip the image data while copying it to the texture. cv::Mat dstMat(image.rows, image.cols, matType, videoTexPixels, image.stride); cv::flip(srcMat, dstMat, 1); } else { // Copy the image data, as-is, to the texture. // Note that the PointGrey image and srcMat have pointers to the same // data, so the following code does reference the data that we modified // earlier via srcMat. memcpy(videoTexPixels, image.pData, image.dataSize); } SDL_UnlockTexture(videoTex); SDL_RenderCopy(renderer, videoTex, NULL, NULL); SDL_RenderPresent(renderer); numImagesCaptured++; if (numImagesCaptured >= numImagesPerFPSMeasurement) { endTicks = clock(); snprintf( strBuffer, strBufferSize, "LookSpry | %s | %dx%d --> %dx%d | %ld FPS", rendererInfo.name, image.cols, image.rows, windowWidth, windowHeight, numImagesCaptured * CLOCKS_PER_SEC / (endTicks - startTicks)); SDL_SetWindowTitle(window, strBuffer); startTicks = endTicks; numImagesCaptured = 0u; } } fc2StopCapture(context); fc2Disconnect(context); SDL_DestroyTexture(videoTex); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); return EXIT_SUCCESS; }
void Renderer::init() { // TODO: android/ios // _width = deviceWidth; // _height = deviceHeight; // Game::getInstance()->engineSettings()->setFullscreen(true); // Game::getInstance()->engineSettings()->setScale(1); //or 2, if fullhd device std::string message = "SDL_CreateWindow " + std::to_string(_size.width()) + "x" + std::to_string(_size.height()) + "x" +std::to_string(32)+ " - "; uint32_t flags = SDL_WINDOW_SHOWN; if (Game::getInstance()->settings()->fullscreen()) { flags |= SDL_WINDOW_FULLSCREEN; } _sdlWindow = SDL_CreateWindow("", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _size.width(), _size.height(), flags); if (!_sdlWindow) { throw Exception(message + "[FAIL]"); } Logger::info("RENDERER") << message + "[OK]" << std::endl; message = "SDL_CreateRenderer - "; _sdlRenderer = SDL_CreateRenderer(_sdlWindow, -1, SDL_RENDERER_ACCELERATED); if (!_sdlRenderer) { throw Exception(message + "[FAIL]"); } Logger::info("RENDERER") << message + "[OK]" << std::endl; SDL_SetRenderDrawBlendMode(_sdlRenderer, SDL_BLENDMODE_BLEND); if (Game::getInstance()->settings()->scale() != 0) { switch (Game::getInstance()->settings()->scale()) { default: case 1: _size.setWidth((int)(_size.width() / (_size.height() / 480.0))); _size.setHeight(480); break; case 2: _size.setWidth((int)(_size.width() / (_size.height() / 960.0))); _size.setHeight(960); break; } SDL_RenderSetLogicalSize(_sdlRenderer, _size.width(), _size.height()); SDL_RenderGetScale(_sdlRenderer, &_scaleX, &_scaleY); } SDL_RendererInfo rendererInfo; SDL_GetRendererInfo(_sdlRenderer, &rendererInfo); Logger::info("RENDERER") << "name: " << rendererInfo.name << std::endl; if (rendererInfo.flags & SDL_RENDERER_SOFTWARE) { Logger::info("RENDERER") << "flags: SDL_RENDERER_SOFTWARE" << std::endl; } if (rendererInfo.flags & SDL_RENDERER_ACCELERATED) { Logger::info("RENDERER") << "flags: SDL_RENDERER_ACCELERATED" << std::endl; } Logger::info("RENDERER") << "num_texture_formats: " << rendererInfo.num_texture_formats << std::endl; for (unsigned int i = 0; i != 16; i++) { auto& info = Logger::info("RENDERER"); info << "texture_formats[" << i << "]: "; auto format = rendererInfo.texture_formats[i]; switch (format) { case SDL_PIXELFORMAT_INDEX1LSB: info << "SDL_PIXELFORMAT_INDEX1LSB"; break; case SDL_PIXELFORMAT_INDEX1MSB: info << "SDL_PIXELFORMAT_INDEX1MSB"; break; case SDL_PIXELFORMAT_INDEX4LSB: info << "SDL_PIXELFORMAT_INDEX4LSB"; break; case SDL_PIXELFORMAT_INDEX4MSB: info << "SDL_PIXELFORMAT_INDEX4MSB"; break; case SDL_PIXELFORMAT_INDEX8: info << "SDL_PIXELFORMAT_INDEX8"; break; case SDL_PIXELFORMAT_RGBA8888: info << "SDL_PIXELFORMAT_RGBA8888"; break; case SDL_PIXELFORMAT_ARGB8888: info << "SDL_PIXELFORMAT_ARGB8888"; break; case SDL_PIXELFORMAT_RGB888: info << "SDL_PIXELFORMAT_RGB888"; break; default: info << format; break; } info << std::endl; } Logger::info("RENDERER") << "max_texture_width: " << rendererInfo.max_texture_width << std::endl; Logger::info("RENDERER") << "max_texture_height: " << rendererInfo.max_texture_height << std::endl; }
/*GLOBAL FUNCTIONS*/ void NLF_screen_init() { int flags; int aux; char *str; int sdlRet; NLF_bool saydone; /*INITIALIZING SDL_IMAGE*/ flags = IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF; if((IMG_Init(flags) & flags) != flags) { flags = IMG_INIT_TIF; if((IMG_Init(flags) & flags) != flags) { printf("\tCan't initialize SDL_image\nSDL_IMAGE ERROR: %s\n", IMG_GetError()); printf("\ttraing for TIF format... "); flags = IMG_INIT_TIF; if((IMG_Init(flags) & flags) != flags) { printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError()); tifFlag = NLF_True; }else{ printf("done\n"); tifFlag = NLF_False; } printf("\ttraing for PNG format... \n"); flags = IMG_INIT_PNG; if((IMG_Init(flags) & flags) != flags) { printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError()); pngFlag = NLF_True; }else{ printf("done\n"); pngFlag = NLF_False; } printf("\ttraing for JPG format... \n"); flags = IMG_INIT_JPG; if((IMG_Init(flags) & flags) != flags) { printf("fail\n\tSDL_IMAGE ERROR: %s\n", IMG_GetError()); jpgFlag = NLF_True; }else{ printf("done\n"); jpgFlag = NLF_False; } if(jpgFlag == NLF_False && pngFlag == NLF_False && tifFlag == NLF_False) { printf("\tScreen module initialization has failed.\n"); str = SDL_GetError(); printf("\tSDL_ERROR: %s\n", str); printf("\tAborting\n"); NLF_error_make_file_crash_report(NLF_ErrorSDLImageInitializer, "Screen module initialization has failed", "SDL Error: ", str, NULL); exit(NLF_ErrorSDLImageInitializer); } } }else{ jpgFlag = NLF_True; pngFlag = NLF_True; tifFlag = NLF_True; } /************************/ /*SETTING GLOBALS VARIABLES*/ ///GETTING DISPLAY INFORMATIONS aux = SDL_GetNumVideoDisplays(); if(aux < 0) { //error case printf("Fail trying to get video display number.\n"); str = SDL_GetError(); printf("\tSDL_ERROR: %s\n", str); printf("\tAborting\n"); NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "Fail trying to get video display number", "SDL Error: ", str, NULL); exit(aux); }else{ displayInUse = 0; printf("\n\t%d Displays avaliable, piking the number %d as pattern\n", aux, displayInUse + 1); } displayInfoUnknown = NLF_False; for(aux = 0; aux < 3; aux++) { saydone = NLF_False; if(aux == 0) sdlRet = SDL_GetCurrentDisplayMode(displayInUse, &videoMode); else if(aux == 1) sdlRet = SDL_GetDisplayMode(displayInUse, displayInUse, &videoMode); else if(aux == 2) sdlRet = SDL_GetWindowDisplayMode(displayInUse, &videoMode); if(sdlRet != 0) { if(aux == 2) { //totally unsuccessful case printf("\tSorry, impossible to get display #%d mode:\n\tSDL_ERROR: %s\n", displayInUse + 1, SDL_GetError()); printf("\tstandard 800x600 will be set\n"); displayInfoUnknown = NLF_True; }else{ printf("\tSorry, could not get display #%d mode:\n\tSDL_ERROR: %s\n", displayInUse + 1, SDL_GetError()); printf("\ttrying another way...\n"); saydone = NLF_True; } }else{ printf("\tcurrent display(%d) mode detected %dx%dpx @ %dhz. \n", displayInUse + 1, videoMode.w, videoMode.h, videoMode.refresh_rate); if(videoMode.w == 0 || videoMode.h == 0 || videoMode.refresh_rate == 0) { printf("\tSorry, could not get all display #%d mode information\n", displayInUse + 1); printf("\ttrying another way...\n"); saydone = NLF_True; }else{ printf("\tdone\n"); aux = 3; } } } ///**************************** /*SETTING SOME GLOBAL VARIABLES*/ camera.x = 0; camera.y = 0; if(displayInfoUnknown == NLF_False) { camera.w = 800; camera.h = 600; }else{ camera.w = videoMode.w; camera.h = videoMode.h; } screens = NULL; currentFPS = 0; //there's just no need to the FPS be greater then the display refresh rate (videoMode.refresh_rate >= 60 || videoMode.refresh_rate == 0) ? (idealFPS = 60): (idealFPS = videoMode.refresh_rate); /*******************************/ ///CREATING WINDOW SET window = SDL_CreateWindow("NorthLionFramework Game", 0, 0, camera.w, camera.h, SDL_WINDOW_BORDERLESS | SDL_WINDOW_MAXIMIZED); if(window == NULL) { printf("\tCould not craete the window\n"); str = SDL_GetError(); printf("\tSDL_ERROR: %s\n", str); printf("\tAborting\n"); NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "Could not craete the window", "SDL Error: ", str, NULL); exit(NLF_ErrorSDLProblem); //I don't know what to do else but quiting... you know, we need a window .-. } //this loop will try to initialize the render the best way possible for(aux = 0; aux < 4 && window_rederer == NULL; aux++) { switch(aux) { case 0: flags = SDL_RENDERER_SOFTWARE | SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE; break; case 1: flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE; break; case 2: flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC; break; case 3: flags = SDL_RENDERER_ACCELERATED; break; } if(aux > 0) printf("\ttrying flags(%d)... ", flags); window_rederer = SDL_CreateRenderer(window, -1, flags); if(window_rederer == NULL) { if(aux > 0) printf("fail\n"); if(aux != 3) { printf("\tCould not create render with all flags(%d)\n", flags); printf("\tSDL_ERROR: %s\n", SDL_GetError()); }else{ printf("\tIt was impossible to create the render.\n"); str = SDL_GetError(); printf("\tSDL_ERROR: %s\n", str); printf("\tAborting\n"); NLF_error_make_file_crash_report(NLF_ErrorSDLProblem, "It was impossible to create the render", "SDL Error: ", str, NULL); exit(NLF_ErrorSDLProblem); //I don't know what to do else but quiting... you know, we also need a renderer .-. } }else{ if(aux > 0) printf("done\n"); } } if(aux > 0) ///******************* ///GETTING VIDEO CARD INFORMATION aux = 0; if(SDL_GetRendererInfo(window_rederer, &rendererInfo) < 0) { printf("\tCould not get information about the renderer.\n"); printf("\tSDL_ERROR: %s\n", SDL_GetError()); rendererInfoUnknown = NLF_True; }else{ aux = 1; rendererInfoUnknown = NLF_False; } if(SDL_GetRenderDriverInfo(displayInUse, &rendererDriverInfo) < 0) { printf("\tCould not get information about the renderer driver.\n"); printf("\tSDL_ERROR: %s\n", SDL_GetError()); rendererDriverInfoUnkown = NLF_True; }else{ aux = 1; rendererDriverInfoUnkown = NLF_False; } ///****************************** /***************************/ }
static void LimitTextureSize(int *w_upscale, int *h_upscale) { SDL_RendererInfo rinfo; int orig_w, orig_h; orig_w = *w_upscale; orig_h = *h_upscale; // Query renderer and limit to maximum texture dimensions of hardware: if (SDL_GetRendererInfo(renderer, &rinfo) != 0) { I_Error("CreateUpscaledTexture: SDL_GetRendererInfo() call failed: %s", SDL_GetError()); } while (*w_upscale * SCREENWIDTH > rinfo.max_texture_width) { --*w_upscale; } while (*h_upscale * SCREENHEIGHT > rinfo.max_texture_height) { --*h_upscale; } if ((*w_upscale < 1 && rinfo.max_texture_width > 0) || (*h_upscale < 1 && rinfo.max_texture_height > 0)) { I_Error("CreateUpscaledTexture: Can't create a texture big enough for " "the whole screen! Maximum texture size %dx%d", rinfo.max_texture_width, rinfo.max_texture_height); } // We limit the amount of texture memory used for the intermediate buffer, // since beyond a certain point there are diminishing returns. Also, // depending on the hardware there may be performance problems with very // huge textures, so the user can use this to reduce the maximum texture // size if desired. if (max_scaling_buffer_pixels < SCREENWIDTH * SCREENHEIGHT) { I_Error("CreateUpscaledTexture: max_scaling_buffer_pixels too small " "to create a texture buffer: %d < %d", max_scaling_buffer_pixels, SCREENWIDTH * SCREENHEIGHT); } while (*w_upscale * *h_upscale * SCREENWIDTH * SCREENHEIGHT > max_scaling_buffer_pixels) { if (*w_upscale > *h_upscale) { --*w_upscale; } else { --*h_upscale; } } if (*w_upscale != orig_w || *h_upscale != orig_h) { printf("CreateUpscaledTexture: Limited texture size to %dx%d " "(max %d pixels, max texture size %dx%d)\n", *w_upscale * SCREENWIDTH, *h_upscale * SCREENHEIGHT, max_scaling_buffer_pixels, rinfo.max_texture_width, rinfo.max_texture_height); } }
SDL_bool CommonInit(CommonState * state) { int i, j, m, n; SDL_DisplayMode fullscreen_mode; if (state->flags & SDL_INIT_VIDEO) { if (state->verbose & VERBOSE_VIDEO) { n = SDL_GetNumVideoDrivers(); if (n == 0) { fprintf(stderr, "No built-in video drivers\n"); } else { fprintf(stderr, "Built-in video drivers:"); for (i = 0; i < n; ++i) { if (i > 0) { fprintf(stderr, ","); } fprintf(stderr, " %s", SDL_GetVideoDriver(i)); } fprintf(stderr, "\n"); } } if (SDL_VideoInit(state->videodriver) < 0) { fprintf(stderr, "Couldn't initialize video driver: %s\n", SDL_GetError()); return SDL_FALSE; } if (state->verbose & VERBOSE_VIDEO) { fprintf(stderr, "Video driver: %s\n", SDL_GetCurrentVideoDriver()); } /* Upload GL settings */ SDL_GL_SetAttribute(SDL_GL_RED_SIZE, state->gl_red_size); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, state->gl_green_size); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, state->gl_blue_size); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, state->gl_alpha_size); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, state->gl_double_buffer); SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, state->gl_buffer_size); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, state->gl_depth_size); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, state->gl_stencil_size); SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, state->gl_accum_red_size); SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, state->gl_accum_green_size); SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, state->gl_accum_blue_size); SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, state->gl_accum_alpha_size); SDL_GL_SetAttribute(SDL_GL_STEREO, state->gl_stereo); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, state->gl_multisamplebuffers); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, state->gl_multisamplesamples); if (state->gl_accelerated >= 0) { SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, state->gl_accelerated); } SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, state->gl_retained_backing); if (state->gl_major_version) { SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, state->gl_major_version); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, state->gl_minor_version); } if (state->verbose & VERBOSE_MODES) { SDL_DisplayMode mode; int bpp; Uint32 Rmask, Gmask, Bmask, Amask; n = SDL_GetNumVideoDisplays(); fprintf(stderr, "Number of displays: %d\n", n); for (i = 0; i < n; ++i) { fprintf(stderr, "Display %d:\n", i); SDL_GetDesktopDisplayMode(i, &mode); SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask, &Bmask, &Amask); fprintf(stderr, " Current mode: %dx%d@%dHz, %d bits-per-pixel (%s)\n", mode.w, mode.h, mode.refresh_rate, bpp, SDL_GetPixelFormatName(mode.format)); if (Rmask || Gmask || Bmask) { fprintf(stderr, " Red Mask = 0x%.8x\n", Rmask); fprintf(stderr, " Green Mask = 0x%.8x\n", Gmask); fprintf(stderr, " Blue Mask = 0x%.8x\n", Bmask); if (Amask) fprintf(stderr, " Alpha Mask = 0x%.8x\n", Amask); } /* Print available fullscreen video modes */ m = SDL_GetNumDisplayModes(i); if (m == 0) { fprintf(stderr, "No available fullscreen video modes\n"); } else { fprintf(stderr, " Fullscreen video modes:\n"); for (j = 0; j < m; ++j) { SDL_GetDisplayMode(i, j, &mode); SDL_PixelFormatEnumToMasks(mode.format, &bpp, &Rmask, &Gmask, &Bmask, &Amask); fprintf(stderr, " Mode %d: %dx%d@%dHz, %d bits-per-pixel (%s)\n", j, mode.w, mode.h, mode.refresh_rate, bpp, SDL_GetPixelFormatName(mode.format)); if (Rmask || Gmask || Bmask) { fprintf(stderr, " Red Mask = 0x%.8x\n", Rmask); fprintf(stderr, " Green Mask = 0x%.8x\n", Gmask); fprintf(stderr, " Blue Mask = 0x%.8x\n", Bmask); if (Amask) fprintf(stderr, " Alpha Mask = 0x%.8x\n", Amask); } } } } } if (state->verbose & VERBOSE_RENDER) { SDL_RendererInfo info; n = SDL_GetNumRenderDrivers(); if (n == 0) { fprintf(stderr, "No built-in render drivers\n"); } else { fprintf(stderr, "Built-in render drivers:\n"); for (i = 0; i < n; ++i) { SDL_GetRenderDriverInfo(i, &info); PrintRenderer(&info); } } } SDL_zero(fullscreen_mode); switch (state->depth) { case 8: fullscreen_mode.format = SDL_PIXELFORMAT_INDEX8; break; case 15: fullscreen_mode.format = SDL_PIXELFORMAT_RGB555; break; case 16: fullscreen_mode.format = SDL_PIXELFORMAT_RGB565; break; case 24: fullscreen_mode.format = SDL_PIXELFORMAT_RGB24; break; default: fullscreen_mode.format = SDL_PIXELFORMAT_RGB888; break; } fullscreen_mode.refresh_rate = state->refresh_rate; state->windows = (SDL_Window **) SDL_malloc(state->num_windows * sizeof(*state->windows)); state->renderers = (SDL_Renderer **) SDL_malloc(state->num_windows * sizeof(*state->renderers)); if (!state->windows || !state->renderers) { fprintf(stderr, "Out of memory!\n"); return SDL_FALSE; } for (i = 0; i < state->num_windows; ++i) { char title[1024]; if (state->num_windows > 1) { SDL_snprintf(title, SDL_arraysize(title), "%s %d", state->window_title, i + 1); } else { SDL_strlcpy(title, state->window_title, SDL_arraysize(title)); } state->windows[i] = SDL_CreateWindow(title, state->window_x, state->window_y, state->window_w, state->window_h, state->window_flags); if (!state->windows[i]) { fprintf(stderr, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } SDL_GetWindowSize(state->windows[i], &state->window_w, &state->window_h); if (SDL_SetWindowDisplayMode(state->windows[i], &fullscreen_mode) < 0) { fprintf(stderr, "Can't set up fullscreen display mode: %s\n", SDL_GetError()); return SDL_FALSE; } if (state->window_icon) { SDL_Surface *icon = LoadIcon(state->window_icon); if (icon) { SDL_SetWindowIcon(state->windows[i], icon); SDL_FreeSurface(icon); } } SDL_ShowWindow(state->windows[i]); state->renderers[i] = NULL; if (!state->skip_renderer && (state->renderdriver || !(state->window_flags & SDL_WINDOW_OPENGL))) { m = -1; if (state->renderdriver) { SDL_RendererInfo info; n = SDL_GetNumRenderDrivers(); for (j = 0; j < n; ++j) { SDL_GetRenderDriverInfo(j, &info); if (SDL_strcasecmp(info.name, state->renderdriver) == 0) { m = j; break; } } if (m == n) { fprintf(stderr, "Couldn't find render driver named %s", state->renderdriver); return SDL_FALSE; } } state->renderers[i] = SDL_CreateRenderer(state->windows[i], m, state->render_flags); if (!state->renderers[i]) { fprintf(stderr, "Couldn't create renderer: %s\n", SDL_GetError()); return SDL_FALSE; } if (state->verbose & VERBOSE_RENDER) { SDL_RendererInfo info; fprintf(stderr, "Current renderer:\n"); SDL_GetRendererInfo(state->renderers[i], &info); PrintRenderer(&info); } } } } if (state->flags & SDL_INIT_AUDIO) { if (state->verbose & VERBOSE_AUDIO) { n = SDL_GetNumAudioDrivers(); if (n == 0) { fprintf(stderr, "No built-in audio drivers\n"); } else { fprintf(stderr, "Built-in audio drivers:"); for (i = 0; i < n; ++i) { if (i > 0) { fprintf(stderr, ","); } fprintf(stderr, " %s", SDL_GetAudioDriver(i)); } fprintf(stderr, "\n"); } } if (SDL_AudioInit(state->audiodriver) < 0) { fprintf(stderr, "Couldn't initialize audio driver: %s\n", SDL_GetError()); return SDL_FALSE; } if (state->verbose & VERBOSE_VIDEO) { fprintf(stderr, "Audio driver: %s\n", SDL_GetCurrentAudioDriver()); } if (SDL_OpenAudio(&state->audiospec, NULL) < 0) { fprintf(stderr, "Couldn't open audio: %s\n", SDL_GetError()); return SDL_FALSE; } } return SDL_TRUE; }
bool Graphics::InitVideo() { if (drawtarget == screen) drawtarget = NULL; if (screen) delete screen; uint32_t window_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_BORDERLESS; if (is_fullscreen) window_flags |= SDL_WINDOW_FULLSCREEN; if (window) { stat("second call to Graphics::InitVideo()"); abort(); } stat("SDL_CreateWindow: %dx%d @ %dbpp", Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE, screen_bpp); window = SDL_CreateWindow("NXEngine", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE, window_flags); if (!window) { staterr("Graphics::InitVideo: error setting video mode (SDL_CreateWindow: %s)", SDL_GetError()); return 1; } int drv_index = -1; #if 0 { int drivers = SDL_GetNumRenderDrivers(); SDL_RendererInfo info; for (int i = 0; i < drivers; ++i) { if (SDL_GetRenderDriverInfo(i, &info)) { staterr("Graphics::InitVideo: SDL_GetRenderDriverInfo() failed: %s", SDL_GetError()); } if (strcmp("opengl", info.name) == 0) { drv_index = i; break; } } } #endif renderer = SDL_CreateRenderer(window, drv_index, /*SDL_RENDERER_SOFTWARE | */SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE); if (!renderer) { staterr("Graphics::InitVideo: error setting video mode (SDL_CreateRenderer: %s)", SDL_GetError()); return 1; } SDL_RendererInfo info; if (SDL_GetRendererInfo(renderer, &info)) { staterr("Graphics::InitVideo: SDL_GetRendererInfo failed: %s", SDL_GetError()); return 1; } if (!(info.flags & SDL_RENDERER_TARGETTEXTURE)) { staterr("Graphics::InitVideo: SDL_RENDERER_TARGETTEXTURE is not supported"); return 1; } SDL_ShowCursor(is_fullscreen == false); screen = NXSurface::createScreen(Graphics::SCREEN_WIDTH*SCALE, Graphics::SCREEN_HEIGHT*SCALE, info.texture_formats[0]); if (!screen) { staterr("Graphics::InitVideo: no screen has been created"); return 1; } if (!drawtarget) drawtarget = screen; return 0; }
SDL_Surface * SDL_SetVideoMode(int width, int height, int bpp, Uint32 flags) { SDL_DisplayMode desktop_mode; SDL_DisplayMode mode; int window_x = SDL_WINDOWPOS_UNDEFINED; int window_y = SDL_WINDOWPOS_UNDEFINED; Uint32 window_flags; Uint32 desktop_format; Uint32 desired_format; Uint32 surface_flags; if (!SDL_GetVideoDevice()) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) { return NULL; } } SDL_GetDesktopDisplayMode(&desktop_mode); if (width == 0) { width = desktop_mode.w; } if (height == 0) { height = desktop_mode.h; } /* See if we can simply resize the existing window and surface */ if (SDL_ResizeVideoMode(width, height, bpp, flags) == 0) { return SDL_PublicSurface; } /* Destroy existing window */ SDL_PublicSurface = NULL; if (SDL_ShadowSurface) { SDL_FreeSurface(SDL_ShadowSurface); SDL_ShadowSurface = NULL; } if (SDL_VideoSurface) { SDL_DelPaletteWatch(SDL_VideoSurface->format->palette, SDL_VideoPaletteChanged, NULL); SDL_FreeSurface(SDL_VideoSurface); SDL_VideoSurface = NULL; } if (SDL_VideoContext) { /* SDL_GL_MakeCurrent(0, NULL); *//* Doesn't do anything */ SDL_GL_DeleteContext(SDL_VideoContext); SDL_VideoContext = NULL; } if (SDL_VideoWindow) { SDL_GetWindowPosition(SDL_VideoWindow, &window_x, &window_y); SDL_DestroyWindow(SDL_VideoWindow); } /* Set up the event filter */ if (!SDL_GetEventFilter(NULL, NULL)) { SDL_SetEventFilter(SDL_CompatEventFilter, NULL); } /* Create a new window */ window_flags = SDL_WINDOW_SHOWN; if (flags & SDL_FULLSCREEN) { window_flags |= SDL_WINDOW_FULLSCREEN; } if (flags & SDL_OPENGL) { window_flags |= SDL_WINDOW_OPENGL; } if (flags & SDL_RESIZABLE) { window_flags |= SDL_WINDOW_RESIZABLE; } if (flags & SDL_NOFRAME) { window_flags |= SDL_WINDOW_BORDERLESS; } GetEnvironmentWindowPosition(width, height, &window_x, &window_y); SDL_SetFullscreenDisplayMode(NULL); SDL_VideoWindow = SDL_CreateWindow(wm_title, window_x, window_y, width, height, window_flags); if (!SDL_VideoWindow) { return NULL; } SDL_SetWindowIcon(SDL_VideoWindow, SDL_VideoIcon); window_flags = SDL_GetWindowFlags(SDL_VideoWindow); surface_flags = 0; if (window_flags & SDL_WINDOW_FULLSCREEN) { surface_flags |= SDL_FULLSCREEN; } if (window_flags & SDL_WINDOW_OPENGL) { surface_flags |= SDL_OPENGL; } if (window_flags & SDL_WINDOW_RESIZABLE) { surface_flags |= SDL_RESIZABLE; } if (window_flags & SDL_WINDOW_BORDERLESS) { surface_flags |= SDL_NOFRAME; } /* Set up the desired display mode */ desktop_format = desktop_mode.format; if (desktop_format && ((flags & SDL_ANYFORMAT) || (bpp == SDL_BITSPERPIXEL(desktop_format)))) { desired_format = desktop_format; } else { switch (bpp) { case 0: if (desktop_format) { desired_format = desktop_format; } else { desired_format = SDL_PIXELFORMAT_RGB888; } bpp = SDL_BITSPERPIXEL(desired_format); break; case 8: desired_format = SDL_PIXELFORMAT_INDEX8; break; case 15: desired_format = SDL_PIXELFORMAT_RGB555; break; case 16: desired_format = SDL_PIXELFORMAT_RGB565; break; case 24: desired_format = SDL_PIXELFORMAT_RGB24; break; case 32: desired_format = SDL_PIXELFORMAT_RGB888; break; default: SDL_SetError("Unsupported bpp in SDL_SetVideoMode()"); return NULL; } } mode.format = desired_format; mode.w = width; mode.h = height; mode.refresh_rate = 0; /* Set the desired display mode */ if (flags & SDL_FULLSCREEN) { if (SDL_SetFullscreenDisplayMode(&mode) < 0) { return NULL; } } /* If we're in OpenGL mode, just create a stub surface and we're done! */ if (flags & SDL_OPENGL) { SDL_VideoContext = SDL_GL_CreateContext(SDL_VideoWindow); if (!SDL_VideoContext) { return NULL; } if (SDL_GL_MakeCurrent(SDL_VideoWindow, SDL_VideoContext) < 0) { return NULL; } SDL_VideoSurface = SDL_CreateRGBSurfaceFrom(NULL, width, height, bpp, 0, 0, 0, 0, 0); if (!SDL_VideoSurface) { return NULL; } SDL_VideoSurface->flags |= surface_flags; SDL_PublicSurface = SDL_VideoSurface; return SDL_PublicSurface; } /* Create a renderer for the window */ if (SDL_CreateRenderer (SDL_VideoWindow, -1, SDL_RENDERER_SINGLEBUFFER | SDL_RENDERER_PRESENTDISCARD) < 0) { return NULL; } SDL_GetRendererInfo(&SDL_VideoRendererInfo); /* Create a texture for the screen surface */ SDL_VideoTexture = SDL_CreateTexture(desired_format, SDL_TEXTUREACCESS_STREAMING, width, height); if (!SDL_VideoTexture) { SDL_VideoTexture = SDL_CreateTexture(desktop_format, SDL_TEXTUREACCESS_STREAMING, width, height); } if (!SDL_VideoTexture) { return NULL; } /* Create the screen surface */ SDL_VideoSurface = CreateVideoSurface(SDL_VideoTexture); if (!SDL_VideoSurface) { return NULL; } SDL_VideoSurface->flags |= surface_flags; /* Set a default screen palette */ if (SDL_VideoSurface->format->palette) { SDL_VideoSurface->flags |= SDL_HWPALETTE; SDL_DitherColors(SDL_VideoSurface->format->palette->colors, SDL_VideoSurface->format->BitsPerPixel); SDL_AddPaletteWatch(SDL_VideoSurface->format->palette, SDL_VideoPaletteChanged, SDL_VideoSurface); SDL_SetPaletteColors(SDL_VideoSurface->format->palette, SDL_VideoSurface->format->palette->colors, 0, SDL_VideoSurface->format->palette->ncolors); } /* Create a shadow surface if necessary */ if ((bpp != SDL_VideoSurface->format->BitsPerPixel) && !(flags & SDL_ANYFORMAT)) { SDL_ShadowSurface = SDL_CreateRGBSurface(0, width, height, bpp, 0, 0, 0, 0); if (!SDL_ShadowSurface) { return NULL; } SDL_ShadowSurface->flags |= surface_flags; /* 8-bit SDL_ShadowSurface surfaces report that they have exclusive palette */ if (SDL_ShadowSurface->format->palette) { SDL_ShadowSurface->flags |= SDL_HWPALETTE; if (SDL_VideoSurface->format->palette) { SDL_SetSurfacePalette(SDL_ShadowSurface, SDL_VideoSurface->format->palette); } else { SDL_DitherColors(SDL_ShadowSurface->format->palette->colors, SDL_ShadowSurface->format->BitsPerPixel); } SDL_AddPaletteWatch(SDL_ShadowSurface->format->palette, SDL_VideoPaletteChanged, SDL_ShadowSurface); } } SDL_PublicSurface = (SDL_ShadowSurface ? SDL_ShadowSurface : SDL_VideoSurface); SDL_VideoFlags = flags; ClearVideoSurface(); SetupScreenSaver(flags); /* We're finally done! */ return SDL_PublicSurface; }
int video_set_mode(s_videomodes videomodes) { //if(memcmp(&stored_videomodes, &videomodes, sizeof(videomodes))==0) return 1; stored_videomodes = videomodes; int b; int allocTextureWidth, allocTextureHeight; savedata.screen[videoMode][0] = 0; savedata.fullscreen = 1; bytes_per_pixel = videomodes.pixel; b = bytes_per_pixel - 1; //destroy all if(bscreen) { SDL_FreeSurface(bscreen); } bscreen = NULL; if(texture) { SDL_DestroyTexture(texture); } texture = NULL; if(buttons) { SDL_DestroyTexture(buttons); } buttons = NULL; //mysterious crash in sdl 2.0 if these are recreated, so leave them alone for now //if(renderer) SDL_DestroyRenderer(renderer); //renderer = NULL; //if(window) SDL_DestroyWindow(window); //window = NULL; if(videomodes.hRes == 0 && videomodes.vRes == 0) { return 0; } viewportWidth = nativeWidth; viewportHeight = nativeHeight; if(!window && !(window = SDL_CreateWindow("OpenBOR", 0, 0, nativeWidth, nativeHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN))) { printf("error: %s\n", SDL_GetError()); return 0; } if(!renderer && !(renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED))) { printf("error: %s\n", SDL_GetError()); return 0; } SDL_RendererInfo info; SDL_GetRendererInfo(renderer, &info); printf("SDL video Renderer: %s \n", info.name); SDL_SetHintWithPriority(SDL_HINT_RENDER_SCALE_QUALITY, savedata.glfilter[savedata.fullscreen] ? "nearest" : "linear", SDL_HINT_DEFAULT); // now create a texture textureWidth = videomodes.hRes; textureHeight = videomodes.vRes; allocTextureWidth = nextpowerof2(textureWidth); allocTextureHeight = nextpowerof2(textureHeight); int format = SDL_MasksToPixelFormatEnum (textureDepths[b], masks[b][0], masks[b][1], masks[b][2], masks[b][3]); if(!(texture = SDL_CreateTexture(renderer, format, SDL_TEXTUREACCESS_STREAMING, allocTextureWidth, allocTextureHeight))) { printf("error: %s\n", SDL_GetError()); return 0; } setup_touch(); if(!buttons) { bscreen = pngToSurface(buttonpng); if(!bscreen || !(buttons = SDL_CreateTextureFromSurface(renderer, bscreen))) { printf("error: %s\n", SDL_GetError()); return 0; } SDL_FreeSurface(bscreen); bscreen = NULL; } //create a buffer for 8bit mode, masks don't really matter but anyway set them if(bytes_per_pixel == 1) { bscreen = SDL_CreateRGBSurface(SDL_SWSURFACE, textureWidth, textureHeight, textureDepths[b], masks[b][0], masks[b][1], masks[b][2], masks[b][3]); } video_clearscreen(); return 1; }
int graphics_SetMode(int width, int height, int fullscreen, int resizable, const char* title, const char* renderer, char** error) { graphics_calculateUnitToPixels(width, height); #if defined(ANDROID) if (!fullscreen) { // do not use windowed on Android *error = strdup("Windowed mode is not supported on Android"); return 0; } #endif char errormsg[512]; // initialize SDL video if not done yet if (!graphics_InitVideoSubsystem(error)) { return 0; } // think about the renderer we want #ifndef WINDOWS #ifdef ANDROID char preferredrenderer[20] = "opengles"; #else char preferredrenderer[20] = "opengl"; #endif #else char preferredrenderer[20] = "direct3d"; #endif int softwarerendering = 0; if (renderer) { if (strcasecmp(renderer, "software") == 0) { #ifdef ANDROID // we don't want software rendering on Android #else softwarerendering = 1; strcpy(preferredrenderer, "software"); #endif } else { if (strcasecmp(renderer, "opengl") == 0) { #ifdef ANDROID // opengles is the opengl we want for android :-) strcpy(preferredrenderer, "opengles"); #else // regular opengl on desktop platforms strcpy(preferredrenderer, "opengl"); #endif } #ifdef WINDOWS // only windows knows direct3d obviously if (strcasecmp(renderer,"direct3d") == 0) { strcpy(preferredrenderer, "direct3d"); } #endif } } // get renderer index int rendererindex = -1; if (strlen(preferredrenderer) > 0 && !softwarerendering) { int count = SDL_GetNumRenderDrivers(); if (count > 0) { int r = 0; while (r < count) { SDL_RendererInfo info; SDL_GetRenderDriverInfo(r, &info); if (strcasecmp(info.name, preferredrenderer) == 0) { rendererindex = r; break; } r++; } } } // see if anything changes at all unsigned int oldw = 0; unsigned int oldh = 0; graphics_GetWindowDimensions(&oldw,&oldh); if (mainwindow && mainrenderer && width == (int)oldw && height == (int)oldh) { SDL_RendererInfo info; SDL_GetRendererInfo(mainrenderer, &info); if (strcasecmp(preferredrenderer, info.name) == 0) { // same renderer and resolution if (strcmp(SDL_GetWindowTitle(mainwindow), title) != 0) { SDL_SetWindowTitle(mainwindow, title); } // toggle fullscreen if desired if (graphics_IsFullscreen() != fullscreen) { graphics_ToggleFullscreen(); } return 1; } } // Check if we support the video mode for fullscreen - // This is done to avoid SDL allowing impossible modes and // giving us a fake resized/padded/whatever output we don't want. if (fullscreen) { // check all video modes in the list SDL returns for us int count = graphics_GetNumberOfVideoModes(); int i = 0; int supportedmode = 0; while (i < count) { int w,h; graphics_GetVideoMode(i, &w, &h); if (w == width && h == height) { supportedmode = 1; break; } i++; } if (!supportedmode) { // check for desktop video mode aswell int w,h; graphics_GetDesktopVideoMode(&w,&h); if (w == 0 || h == 0 || width != w || height != h) { *error = strdup("Video mode is not supported"); return 0; } } } // notify texture manager of device shutdown texturemanager_deviceLost(); // destroy old window/renderer if we got one graphics_Close(1); // create window if (fullscreen) { mainwindow = SDL_CreateWindow(title, 0, 0, width, height, SDL_WINDOW_FULLSCREEN); mainwindowfullscreen = 1; } else { mainwindow = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_MINIMIZED); mainwindowfullscreen = 0; } if (!mainwindow) { snprintf(errormsg, sizeof(errormsg), "Failed to open SDL window: %s", SDL_GetError()); errormsg[sizeof(errormsg)-1] = 0; *error = strdup(errormsg); return 0; } // see if we actually ended up with the resolution we wanted: int actualwidth, actualheight; SDL_GetWindowSize(mainwindow, &actualwidth, &actualheight); if (actualwidth != width || actualheight != height) { if (fullscreen) { // we failed to get the requested resolution: SDL_DestroyWindow(mainwindow); snprintf(errormsg, sizeof(errormsg), "Failed to open " "SDL window: ended up with other resolution than requested"); *error = strdup(errormsg); return 0; } } // Create renderer if (!softwarerendering) { mainrenderer = SDL_CreateRenderer(mainwindow, rendererindex, SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); if (!mainrenderer) { softwarerendering = 1; strcpy(preferredrenderer, "software"); } } if (softwarerendering) { mainrenderer = SDL_CreateRenderer(mainwindow, -1, SDL_RENDERER_SOFTWARE); } if (!mainrenderer) { // we failed to create the renderer if (mainwindow) { // destroy window aswell in case it is open SDL_DestroyWindow(mainwindow); mainwindow = NULL; } if (softwarerendering) { snprintf(errormsg, sizeof(errormsg), "Failed to create SDL renderer (backend software): %s", SDL_GetError()); } else { SDL_RendererInfo info; SDL_GetRenderDriverInfo(rendererindex, &info); snprintf(errormsg, sizeof(errormsg), "Failed to create SDL renderer (backend %s): %s", info.name, SDL_GetError()); } errormsg[sizeof(errormsg)-1] = 0; *error = strdup(errormsg); return 0; } else { SDL_RendererInfo info; SDL_GetRendererInfo(mainrenderer, &info); } // notify texture manager that device is back texturemanager_deviceRestored(); // Transfer textures back to SDL /*if (!graphicstexturelist_TransferTexturesToHW()) { SDL_RendererInfo info; SDL_GetRendererInfo(mainrenderer, &info); snprintf(errormsg, sizeof(errormsg), "Failed to create SDL renderer (backend %s): " "Cannot recreate textures", info.name); *error = strdup(errormsg); SDL_DestroyRenderer(mainrenderer); SDL_DestroyWindow(mainwindow); return 0; }*/ // Re-focus window if previously focussed if (!inbackground) { SDL_RaiseWindow(mainwindow); } graphicsactive = 1; return 1; }
/* * initialize sdl video * args: * width - video width * height - video height * flags - window flags: * 0- none * 1- fullscreen * 2- maximized * * asserts: * none * * returns: error code */ static int video_init(int width, int height, int flags) { int w = width; int h = height; int32_t my_flags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE; switch(flags) { case 2: my_flags |= SDL_WINDOW_MAXIMIZED; break; case 1: my_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; break; case 0: default: break; } if(verbosity > 0) printf("RENDER: Initializing SDL2 render\n"); if (sdl_window == NULL) /*init SDL*/ { if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0) { fprintf(stderr, "RENDER: Couldn't initialize SDL2: %s\n", SDL_GetError()); return -1; } SDL_SetHint("SDL_HINT_RENDER_SCALE_QUALITY", "1"); sdl_window = SDL_CreateWindow( "Guvcview Video", // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position w, // width, in pixels h, // height, in pixels my_flags ); if(sdl_window == NULL) { fprintf(stderr, "RENDER: (SDL2) Couldn't open window: %s\n", SDL_GetError()); render_sdl2_clean(); return -2; } int display_index = SDL_GetWindowDisplayIndex(sdl_window); int err = SDL_GetDesktopDisplayMode(display_index, &display_mode); if(!err) { if(verbosity > 0) printf("RENDER: video display %i -> %dx%dpx @ %dhz\n", display_index, display_mode.w, display_mode.h, display_mode.refresh_rate); } else fprintf(stderr, "RENDER: Couldn't determine display mode for video display %i\n", display_index); if(w > display_mode.w) w = display_mode.w; if(h > display_mode.h) h = display_mode.h; if(verbosity > 0) printf("RENDER: setting window size to %ix%i\n", w, h); SDL_SetWindowSize(sdl_window, w, h); } if(verbosity > 2) { /* Allocate a renderer info struct*/ SDL_RendererInfo *rend_info = (SDL_RendererInfo *) malloc(sizeof(SDL_RendererInfo)); if (!rend_info) { fprintf(stderr, "RENDER: Couldn't allocate memory for the renderer info data structure\n"); render_sdl2_clean(); return -5; } /* Print the list of the available renderers*/ printf("\nRENDER: Available SDL2 rendering drivers:\n"); int i = 0; for (i = 0; i < SDL_GetNumRenderDrivers(); i++) { if (SDL_GetRenderDriverInfo(i, rend_info) < 0) { fprintf(stderr, " Couldn't get SDL2 render driver information: %s\n", SDL_GetError()); } else { printf(" %2d: %s\n", i, rend_info->name); printf(" SDL_RENDERER_TARGETTEXTURE [%c]\n", (rend_info->flags & SDL_RENDERER_TARGETTEXTURE) ? 'X' : ' '); printf(" SDL_RENDERER_SOFTWARE [%c]\n", (rend_info->flags & SDL_RENDERER_SOFTWARE) ? 'X' : ' '); printf(" SDL_RENDERER_ACCELERATED [%c]\n", (rend_info->flags & SDL_RENDERER_ACCELERATED) ? 'X' : ' '); printf(" SDL_RENDERER_PRESENTVSYNC [%c]\n", (rend_info->flags & SDL_RENDERER_PRESENTVSYNC) ? 'X' : ' '); } } free(rend_info); } main_renderer = SDL_CreateRenderer(sdl_window, -1, SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); if(main_renderer == NULL) { fprintf(stderr, "RENDER: (SDL2) Couldn't get a accelerated renderer: %s\n", SDL_GetError()); fprintf(stderr, "RENDER: (SDL2) trying with a software renderer\n"); main_renderer = SDL_CreateRenderer(sdl_window, -1, SDL_RENDERER_TARGETTEXTURE | SDL_RENDERER_SOFTWARE); if(main_renderer == NULL) { fprintf(stderr, "RENDER: (SDL2) Couldn't get a software renderer: %s\n", SDL_GetError()); fprintf(stderr, "RENDER: (SDL2) giving up...\n"); render_sdl2_clean(); return -3; } } if(verbosity > 2) { /* Allocate a renderer info struct*/ SDL_RendererInfo *rend_info = (SDL_RendererInfo *) malloc(sizeof(SDL_RendererInfo)); if (!rend_info) { fprintf(stderr, "RENDER: Couldn't allocate memory for the renderer info data structure\n"); render_sdl2_clean(); return -5; } /* Print the name of the current rendering driver */ if (SDL_GetRendererInfo(main_renderer, rend_info) < 0) { fprintf(stderr, "Couldn't get SDL2 rendering driver information: %s\n", SDL_GetError()); } printf("RENDER: rendering driver in use: %s\n", rend_info->name); printf(" SDL_RENDERER_TARGETTEXTURE [%c]\n", (rend_info->flags & SDL_RENDERER_TARGETTEXTURE) ? 'X' : ' '); printf(" SDL_RENDERER_SOFTWARE [%c]\n", (rend_info->flags & SDL_RENDERER_SOFTWARE) ? 'X' : ' '); printf(" SDL_RENDERER_ACCELERATED [%c]\n", (rend_info->flags & SDL_RENDERER_ACCELERATED) ? 'X' : ' '); printf(" SDL_RENDERER_PRESENTVSYNC [%c]\n", (rend_info->flags & SDL_RENDERER_PRESENTVSYNC) ? 'X' : ' '); free(rend_info); } SDL_RenderSetLogicalSize(main_renderer, width, height); SDL_SetRenderDrawBlendMode(main_renderer, SDL_BLENDMODE_NONE); rending_texture = SDL_CreateTexture(main_renderer, #ifdef USE_PLANAR_YUV SDL_PIXELFORMAT_IYUV, /*yuv420p*/ #else SDL_PIXELFORMAT_YUY2, /*yuv422*/ #endif SDL_TEXTUREACCESS_STREAMING, width, height); if(rending_texture == NULL) { fprintf(stderr, "RENDER: (SDL2) Couldn't get a texture for rending: %s\n", SDL_GetError()); render_sdl2_clean(); return -4; } return 0; }
int video_init(int window_w, int window_h, int fullscreen, int vsync, const char* scaler_name, int scale_factor) { state.w = window_w; state.h = window_h; state.fs = fullscreen; state.vsync = vsync; state.fade = 1.0f; state.target = NULL; state.target_move_x = 0; state.target_move_y = 0; // Load scaler (if any) memset(state.scaler_name, 0, sizeof(state.scaler_name)); strncpy(state.scaler_name, scaler_name, sizeof(state.scaler_name)-1); if(video_load_scaler(scaler_name, scale_factor)) { DEBUG("Scaler \"%s\" plugin not found; using Nearest neighbour scaling.", scaler_name); state.scale_factor = 1; } else { DEBUG("Scaler \"%s\" loaded w/ factor %d", scaler_name, scale_factor); state.scale_factor = scale_factor; } // Clear palettes state.cur_palette = calloc(1, sizeof(screen_palette)); state.base_palette = calloc(1, sizeof(palette)); state.cur_palette->version = 1; // Form title string char title[32]; snprintf(title, 32, "OpenOMF v%d.%d.%d", V_MAJOR, V_MINOR, V_PATCH); // Open window state.window = SDL_CreateWindow( title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, window_w, window_h, SDL_WINDOW_SHOWN); if(state.window == NULL) { PERROR("Could not create window: %s", SDL_GetError()); return 1; } // Set fullscreen if needed if(state.fs) { if(SDL_SetWindowFullscreen(state.window, SDL_WINDOW_FULLSCREEN) != 0) { PERROR("Could not set fullscreen mode!"); } else { DEBUG("Fullscreen enabled!"); } } else { SDL_SetWindowFullscreen(state.window, 0); } // Form flags int renderer_flags = SDL_RENDERER_ACCELERATED; if(state.vsync) { renderer_flags |= SDL_RENDERER_PRESENTVSYNC; } // Create renderer state.renderer = SDL_CreateRenderer( state.window, -1, renderer_flags); if(state.renderer == NULL) { PERROR("Could not create renderer: %s", SDL_GetError()); return 1; } // Default resolution for renderer. This will them get scaled up to screen size. SDL_RenderSetLogicalSize(state.renderer, NATIVE_W * state.scale_factor, NATIVE_H * state.scale_factor); // Disable screensaver :/ SDL_DisableScreenSaver(); // Set rendertargets reset_targets(); // Init texture cache tcache_init(state.renderer, state.scale_factor, &state.scaler); // Init hardware renderer state.cur_renderer = VIDEO_RENDERER_HW; video_hw_init(&state); // Get renderer data SDL_RendererInfo rinfo; SDL_GetRendererInfo(state.renderer, &rinfo); // Show some info INFO("Video Init OK"); INFO(" * Driver: %s", SDL_GetCurrentVideoDriver()); INFO(" * Renderer: %s", rinfo.name); INFO(" * Accelerated: %s", (rinfo.flags & SDL_RENDERER_ACCELERATED) ? "Yes" : "No"); INFO(" * VSync support: %s", (rinfo.flags & SDL_RENDERER_PRESENTVSYNC) ? "Yes" : "No"); INFO(" * Target support: %s", (rinfo.flags & SDL_RENDERER_TARGETTEXTURE) ? "Yes" : "No"); return 0; }
int Display_Application(int argc, char *argv[]) { SDL_Window *window; // Declare a pointer, main window int width = 640; int height = 480; GLdouble dx = 0; GLdouble dy = 0; GLdouble zoom = 1.0; initNodesBounds(argv[1]); min_x = minx; max_x = maxx; min_y = miny; max_y = maxy; // Initialize SDL2 if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } // Create an application window with the following settings: window = SDL_CreateWindow("OSM Renderer", // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position width, // width, in pixels height, // height, in pixels SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE // flags ); // Check that the window was successfully created if (window == NULL) { // In the case that the window could not be made... fprintf(stderr, "SDL_CreateWindow failed: %s\n", SDL_GetError()); exit(EXIT_FAILURE); } fprintf(stdout, "Press the 'F' key to switch fullscreen.\n"); fprintf(stdout, "Press the 'R' key to reset the view.\n"); fprintf(stdout, "Press the [x] button to close the window.\n"); SDL_Renderer *displayRenderer = NULL; SDL_RendererInfo displayRendererInfo; displayRenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_GetRendererInfo(displayRenderer, &displayRendererInfo); if ((displayRendererInfo.flags & SDL_RENDERER_ACCELERATED) == 0 || (displayRendererInfo.flags & SDL_RENDERER_TARGETTEXTURE) == 0) { fprintf(stderr, "We have no render surface and not accelerated.\n"); } Display_InitGL(); Display_SetViewport(width, height, dx, dy, zoom); int fullscreen = 0; int drag = 0; int xcursor = 0; int ycursor = 0; SDL_Event event; int quit = 0; time_t t = time(NULL); time_t ctime = time(NULL); int frames = 0; GList *l; for (l = g_hash_table_get_values(ways_hashtable); l != NULL; l = l->next) { way *w = l->data; w->glist = tessellate(*w); } g_list_free(l); while (!quit) { Display_SetViewport(width, height, dx, dy, zoom); Display_Render(displayRenderer, width, height, dx, dy, zoom); while (SDL_PollEvent(&event)) // User's actions { switch (event.type) { case SDL_QUIT: // Close button quit = 1; break; case SDL_KEYUP: // Key release if (event.key.keysym.sym == SDLK_f) // F key { if (fullscreen == 0) { fullscreen = 1; SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); } else if (fullscreen == 1) { fullscreen = 0; SDL_SetWindowFullscreen(window, 0); } } if (event.key.keysym.sym == SDLK_KP_PLUS) { if (zoom > 0.1) { dx = dx + 0.1 * pixelsize * (xcursor - width / 2); dy = dy - 0.1 * pixelsize * (ycursor - height / 2); } if (zoom > 0.1) zoom -= 0.1; } if (event.key.keysym.sym == SDLK_KP_MINUS) { dx = dx - 0.1 * pixelsize * (xcursor - width / 2); dy = dy + 0.1 * pixelsize * (ycursor - height / 2); zoom += 0.1; } if (event.key.keysym.sym == SDLK_r) { zoom = 1.0; dx = 0.0; dy = 0.0; } if (event.key.keysym.sym == SDLK_s) { if (showFrame) showFrame = 0; else showFrame = 1; } if (event.key.keysym.sym == SDLK_c) { screenshoot = 1; } if (event.key.keysym.sym == SDLK_p) { projection = !projection; if (projection) { min_x = minx; max_x = maxx; min_y = miny; max_y = maxy; } else { min_x = minlon; max_x = maxlon; min_y = minlat; max_y = maxlat; } } break; case SDL_WINDOWEVENT: switch (event.window.event) { case SDL_WINDOWEVENT_RESIZED: width = event.window.data1; height = event.window.data2; break; case SDL_WINDOWEVENT_SIZE_CHANGED: width = event.window.data1; height = event.window.data2; break; default: // printf("Window %d got unknown event %d\n", event.window.windowID, event.window.event); break; } break; case SDL_MOUSEBUTTONDOWN: if (event.button.button == SDL_BUTTON_LEFT) drag = 1; break; case SDL_MOUSEBUTTONUP: if (event.button.button == SDL_BUTTON_LEFT) drag = 0; break; case SDL_MOUSEMOTION: xcursor = event.motion.x; ycursor = event.motion.y; if (drag != 0) { dx -= pixelsize * event.motion.xrel * zoom; dy += pixelsize * event.motion.yrel * zoom; } break; case SDL_MOUSEWHEEL: if (zoom > 0.01) { dx = dx + 0.02 * pixelsize * event.wheel.y * (xcursor - width / 2); dy = dy - 0.02 * pixelsize * event.wheel.y * (ycursor - height / 2); } if (event.wheel.y > 0 && zoom > 0.01) zoom -= 0.02; else if (event.wheel.y < 0) zoom += 0.02; break; default: //printf("unknown event"); break; } } frames++; ctime = time(NULL); if (t != ctime) { t = ctime; //fprintf(stdout, "%d fps\n", frames); frames = 0; } } // Close and destroy the window SDL_DestroyWindow(window); // Clean up SDL_Quit(); return EXIT_SUCCESS; }