void TaskEngine::init() { taskAvailable = SDL_CreateCond(); threadLock = SDL_CreateMutex(); Logger::info << "Spawning " << SDL_GetCPUCount() << " threads" << std::endl; for (int i = 0; i < SDL_GetCPUCount(); i++) { threads.push_back(SDL_CreateThread(routine, "Worker Thread", NULL)); } }
void init_mesh_build_threads(void) { int i; int num_proc = SDL_GetCPUCount(); init_WakeableWaiter(&manager_monitor); init_threadsafe_queue(&built_meshes, MAX_BUILT_MESHES, sizeof(built_queue[0]), built_queue); init_threadsafe_queue(&pending_meshes, MAX_TASKS, sizeof(mesh_task_queue[0]), mesh_task_queue); init_threadsafe_queue(&pending_gen , MAX_TASKS, sizeof(gen_task_queue[0]), gen_task_queue); init_threadsafe_queue(&finished_gen, MAX_GEN_CHUNKS, sizeof(gen_queue[0]), gen_queue); pending_task_count = SDL_CreateSemaphore(0); if (num_proc > 6) num_mesh_workers = num_proc/2; else if (num_proc > 4) num_mesh_workers = 4; else num_mesh_workers = num_proc-1; if (num_mesh_workers > MAX_MESH_WORKERS) num_mesh_workers = MAX_MESH_WORKERS; if (num_mesh_workers < 1) num_mesh_workers = 1; for (i=0; i < num_mesh_workers; ++i) SDL_CreateThread(mesh_worker_handler, "mesh worker", NULL); SDL_CreateThread(worker_manager, "thread manager thread", NULL); }
MainGame::MainGame() { ConfigurationManager configManager(resourcePath() + "configuration.txt"); //if SDL fails, close program if (SDL_Init(SDL_INIT_VIDEO)) throw std::logic_error("Failed to initialize SDL! " + std::string(SDL_GetError())); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); if (configManager.GetItem<bool>("Multisampling")) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, configManager.GetItem<int>("MultisampleBuffers")); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, configManager.GetItem<int>("MultisampleSamples")); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_DisplayMode mode; SDL_GetCurrentDisplayMode(0, &mode); Uint32 windowFlags = SDL_WINDOW_OPENGL; size_t width = configManager.GetItem<float>("WindowWidth"), height = configManager.GetItem<float>("WindowHeight"); if (configManager.GetItem<bool>("Fullscreen")) { // width = mode.w; height = mode.h; windowFlags|=SDL_WINDOW_FULLSCREEN_DESKTOP; } window = SDL_CreateWindow("Genetic Algorithm", 0, 0, width, height, windowFlags); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetSwapInterval(1); SDL_SetRelativeMouseMode(SDL_TRUE); if (window==nullptr) throw std::logic_error("Window failed to be initialized"); SDL_GLContext context = SDL_GL_CreateContext(window); if (context==nullptr) throw std::logic_error("SDL_GL could not be initialized!"); int cpuCount = SDL_GetCPUCount(); GLManager glManager(resourcePath() + "fragmentShader.glsl", resourcePath() + "vertexShader.glsl", configManager); std::string fileLoc =resourcePath() + "performance.csv"; EvolutionSystem evolutionSystem(fileLoc, configManager, cpuCount); Camera camera(configManager.GetItem<float>("WindowWidth"), configManager.GetItem<float>("WindowHeight"), configManager); while (GameState!=GameState::EXIT) { Update(evolutionSystem); camera.Update(); glManager.Programs[0].SetMatrix4("transformMatrix", glm::value_ptr(camera.GetTransformMatrix())); Draw(evolutionSystem); SDL_GL_SwapWindow(window); HandleEvents(evolutionSystem,camera); } }
void QuerySystemInformation() { num_cpus = SDL_GetCPUCount(); ram = SDL_GetSystemRAM(); l1_cache = SDL_GetCPUCacheLineSize(); const char *_vendor = reinterpret_cast<const char*>(glGetString(GL_VENDOR)); const char *_renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER)); const char *_version = reinterpret_cast<const char*>(glGetString(GL_VERSION)); strcpy(platform, SDL_GetPlatform()); strcpy(vendor, _vendor); strcpy(renderer, _renderer); strcpy(version, _version); }
int main(int argc, const char *argv[]) { signal(SIGSEGV, crashHandler); signal(SIGABRT, crashHandler); signal(SIGFPE, fpeHandler); initBacktrace(); initLoggingSystem(); initJobSystem(SDL_GetCPUCount()+1); int result = EXIT_FAILURE; try { result = unsafeMain(argc, argv); } catch (std::exception& e) { logFatal("Unhandled exception caught: %s\n", e.what()); } catch (scripting::UnhandledExcException& e) { scripting::Value exc = e.getException(); logFatal("Unhandled script exception:\n"); if (exc.type == scripting::ValueType::Exception) { logFatal(" %s\n", ((scripting::ExceptionData *)exc.p)->error.getData()); } } catch (const Exception& e) { logFatal("Unhandled exception caught: %s\n", e.getString()); logFatal(" File: %s\n", e.getFile()); logFatal(" Line: %d\n", e.getLine()); logFatal(" Function: %s\n", e.getFunction()); } catch (...) { logFatal("Unhandled exception caught."); } deinitJobSystem(); deinitLoggingSystem(); deinitBacktrace(); return result; }
internal void OutputSystemInfo() { SDL_Log("System Info\n"); int ram = SDL_GetSystemRAM(); SDL_Log("Ram: %dMB\n", ram); int cpu_count = SDL_GetCPUCount(); SDL_Log("CPU Count: %d\n", cpu_count); const char *platform = SDL_GetPlatform(); SDL_Log("Platform: %s\n", platform); int display_num = SDL_GetNumVideoDisplays(); SDL_Log("Display Count: %d\n", display_num); for (int i = 0; i < display_num; i++) { SDL_Rect rect; SDL_GetDisplayBounds(i, &rect); const char *name = SDL_GetDisplayName(i); SDL_Log("Display: %s\n", name); SDL_Log("-X: %d, ", rect.x); SDL_Log("Y: %d, ", rect.y); SDL_Log("Width: %d, ", rect.w); SDL_Log("Height: %d\n", rect.h); for (int j = 0; j < SDL_GetNumDisplayModes(i); j++) { SDL_DisplayMode mode; SDL_GetDisplayMode(i, j, &mode); SDL_Log("--Mode: \n"); SDL_Log("---Width: %d\n", mode.w); SDL_Log("---Height: %d\n", mode.h); SDL_Log("---Refresh Rate: %d\n", mode.refresh_rate); } } }
void Sys_CPUCount( int& numLogicalCPUCores, int& numPhysicalCPUCores, int& numCPUPackages ) { numPhysicalCPUCores = 1; numLogicalCPUCores = SDL_GetCPUCount(); numCPUPackages = 1; }
int system_getProcessorCount() { return SDL_GetCPUCount(); }
#include "SDL.h" #include "SDL_thread.h" #include <stdlib.h> #include "log.h" #define THREADPOOL_TIMEOUT (5 * 100) /* The time a worker thread waits */ #define THREADSIG_STOP (1) /* The signal to stop a worker thread */ #define THREADSIG_RUN (0) /* The signal to indicate the worker thread is running */ #if SDL_VERSION_ATLEAST(1,3,0) const int MAXTHREADS = SDL_GetCPUCount()+1; #else const int MAXTHREADS = 8; #endif /** * @brief Node in the thread queue. */ typedef struct Node_ { void *data; /* The element in the list */ struct Node_ *next; /* The next node in the list */ } Node; /** * @brief Threadqueue itself.
int System::GetCPUCount() { return SDL_GetCPUCount(); }
TaskManager* taskmgr_create(uint numthreads, SDL_ThreadPriority prio, const char *name) { int numcores = SDL_GetCPUCount(); uint maxthreads = numcores * 8; if(numcores < 1) { log_warn("SDL_GetCPUCount() returned %i, assuming 1", numcores); numcores = 1; } if(numthreads == 0) { numthreads = numcores * 4; } else if(numthreads > maxthreads) { log_warn("Number of threads capped to %i (%i requested)", maxthreads, numthreads); numthreads = maxthreads; } TaskManager *mgr = calloc(1, sizeof(TaskManager) + numthreads * sizeof(SDL_Thread*)); if(!(mgr->mutex = SDL_CreateMutex())) { log_sdl_error(LOG_WARN, "SDL_CreateMutex"); goto fail; } if(!(mgr->cond = SDL_CreateCond())) { log_sdl_error(LOG_WARN, "SDL_CreateCond"); goto fail; } mgr->numthreads = numthreads; mgr->thread_prio = prio; for(uint i = 0; i < numthreads; ++i) { int digits = i ? log10(i) + 1 : 0; static const char *const prefix = "taskmgr"; char threadname[sizeof(prefix) + strlen(name) + digits + 2]; snprintf(threadname, sizeof(threadname), "%s:%s/%i", prefix, name, i); if(!(mgr->threads[i] = SDL_CreateThread(taskmgr_thread, threadname, mgr))) { log_sdl_error(LOG_WARN, "SDL_CreateThread"); for(uint j = 0; j < i; ++j) { SDL_DetachThread(mgr->threads[j]); mgr->threads[j] = NULL; } SDL_LockMutex(mgr->mutex); mgr->aborted = true; SDL_CondBroadcast(mgr->cond); SDL_UnlockMutex(mgr->mutex); goto fail; } } SDL_LockMutex(mgr->mutex); mgr->running = true; SDL_CondBroadcast(mgr->cond); SDL_UnlockMutex(mgr->mutex); log_debug( "Created task manager %s (%p) with %u threads at priority %i", name, (void*)mgr, mgr->numthreads, prio ); return mgr; fail: taskmgr_free(mgr); return NULL; }
size_t fe_hw_get_cpu_count(void) { return SDL_GetCPUCount(); }
Engine::Engine(util::Dir *data_dir, const char *windowtitle) : OptionNode{"Engine"}, running{false}, drawing_debug_overlay{this, "drawing_debug_overlay", true}, drawing_huds{this, "drawing_huds", true}, engine_coord_data{this->get_coord_data()}, current_player{this, "current_player", 1}, data_dir{data_dir}, audio_manager{} { for (uint32_t size : {12, 20}) { fonts[size] = std::unique_ptr<Font>{new Font{"DejaVu Serif", "Book", size}}; } this->logsink_file = std::make_unique<log::FileSink>("/tmp/openage-log", true); // enqueue the engine's own input handler to the // execution list. this->register_resize_action(this); // register the engines input manager this->register_input_action(&this->input_manager); if (SDL_Init(SDL_INIT_VIDEO) < 0) { throw Error(MSG(err) << "SDL video initialization: " << SDL_GetError()); } else { log::log(MSG(info) << "Initialized SDL video subsystems."); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); int32_t window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED; this->window = SDL_CreateWindow( windowtitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, this->engine_coord_data->window_size.x, this->engine_coord_data->window_size.y, window_flags ); if (this->window == nullptr) { throw Error(MSG(err) << "Failed to create SDL window: " << SDL_GetError()); } // load support for the PNG image formats, jpg bit: IMG_INIT_JPG int wanted_image_formats = IMG_INIT_PNG; int sdlimg_inited = IMG_Init(wanted_image_formats); if ((sdlimg_inited & wanted_image_formats) != wanted_image_formats) { throw Error(MSG(err) << "Failed to init PNG support: " << IMG_GetError()); } this->glcontext = SDL_GL_CreateContext(this->window); if (this->glcontext == nullptr) { throw Error(MSG(err) << "Failed creating OpenGL context: " << SDL_GetError()); } // check the OpenGL version, for shaders n stuff if (!epoxy_is_desktop_gl() || epoxy_gl_version() < 21) { throw Error(MSG(err) << "OpenGL 2.1 not available"); } // to quote the standard doc: // 'The value gives a rough estimate // of the largest texture that the GL can handle' // -> wat? // anyways, we need at least 1024x1024. int max_texture_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size); log::log(MSG(dbg) << "Maximum supported texture size: " << max_texture_size); if (max_texture_size < 1024) { throw Error(MSG(err) << "Maximum supported texture size too small: " << max_texture_size); } int max_texture_units; glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units); log::log(MSG(dbg) << "Maximum supported texture units: " << max_texture_units); if (max_texture_units < 2) { throw Error(MSG(err) << "Your GPU has too less texture units: " << max_texture_units); } // vsync on SDL_GL_SetSwapInterval(1); // enable alpha blending glEnable(GL_BLEND); // order of drawing relevant for depth // what gets drawn last is displayed on top. glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialize job manager with cpucount-2 worker threads int number_of_worker_threads = SDL_GetCPUCount() - 2; if (number_of_worker_threads <= 0) { number_of_worker_threads = 1; } this->job_manager = new job::JobManager{number_of_worker_threads}; // initialize audio auto devices = audio::AudioManager::get_devices(); if (devices.empty()) { throw Error{MSG(err) << "No audio devices found"}; } // initialize engine related global keybinds auto &global_input_context = this->get_input_manager().get_global_context(); global_input_context.bind(input::action_t::STOP_GAME, [this](const input::action_arg_t &) { this->stop(); }); global_input_context.bind(input::action_t::TOGGLE_HUD, [this](const input::action_arg_t &) { this->drawing_huds.value = !this->drawing_huds.value; }); global_input_context.bind(input::action_t::SCREENSHOT, [this](const input::action_arg_t &) { this->get_screenshot_manager().save_screenshot(); }); global_input_context.bind(input::action_t::TOGGLE_DEBUG_OVERLAY, [this](const input::action_arg_t &) { this->drawing_debug_overlay.value = !this->drawing_debug_overlay.value; }); global_input_context.bind(input::action_t::TOGGLE_PROFILER, [this](const input::action_arg_t &) { if (this->external_profiler.currently_profiling) { this->external_profiler.stop(); this->external_profiler.show_results(); } else { this->external_profiler.start(); } }); global_input_context.bind(input::event_class::MOUSE, [this](const input::action_arg_t &arg) { if (arg.e.cc.has_class(input::event_class::MOUSE_MOTION) && this->get_input_manager().is_down(input::event_class::MOUSE_BUTTON, 2)) { this->move_phys_camera(arg.motion.x, arg.motion.y); return true; } return false; }); // Switching between players with the 1-8 keys auto bind_player_switch = [this, &global_input_context](input::action_t action, int player) { global_input_context.bind(action, [this, player](const input::action_arg_t &) { this->current_player.value = player; }); }; bind_player_switch(input::action_t::SWITCH_TO_PLAYER_1, 1); bind_player_switch(input::action_t::SWITCH_TO_PLAYER_2, 2); bind_player_switch(input::action_t::SWITCH_TO_PLAYER_3, 3); bind_player_switch(input::action_t::SWITCH_TO_PLAYER_4, 4); bind_player_switch(input::action_t::SWITCH_TO_PLAYER_5, 5); bind_player_switch(input::action_t::SWITCH_TO_PLAYER_6, 6); bind_player_switch(input::action_t::SWITCH_TO_PLAYER_7, 7); bind_player_switch(input::action_t::SWITCH_TO_PLAYER_8, 8); }
void readSettings(reactivision_settings *config) { config->port = 3333; sprintf(config->host,"localhost"); sprintf(config->tree_config,"none"); sprintf(config->grid_config,"none"); sprintf(config->midi_config,"none"); sprintf(config->camera_config,"none"); config->invert_x = false; config->invert_y = false; config->invert_a = false; config->midi = false; config->amoeba = true; config->classic = false; config->background = false; config->fullscreen = false; config->headless = false; config->finger_size = 0; config->finger_sensitivity = 100; config->gradient_gate = 32; config->tile_size = 10; config->thread_count = 1; config->display_mode = 2; if (strcmp( config->file, "none" ) == 0) { #ifdef __APPLE__ char app_path[1024]; CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef mainBundleURL = CFBundleCopyBundleURL( mainBundle); CFStringRef cfStringRef = CFURLCopyFileSystemPath( mainBundleURL, kCFURLPOSIXPathStyle); CFStringGetCString( cfStringRef, app_path, 1024, kCFStringEncodingASCII); CFRelease( mainBundleURL); CFRelease( cfStringRef); sprintf(config->file,"%s/Contents/Resources/reacTIVision.xml",app_path); #elif !defined WIN32 if (access ("./reacTIVision.xml", F_OK )==0) sprintf(config->file,"./reacTIVision.xml"); else if (access ("/usr/share/reacTIVision/reacTIVision.xml", F_OK )==0) sprintf(config->file,"/usr/share/reacTIVision/reacTIVision.xml"); else if (access ("/usr/local/share/reacTIVision/reacTIVision.xml", F_OK )==0) sprintf(config->file,"/usr/local/share/reacTIVision/reacTIVision.xml"); else if (access ("/opt/share/reacTIVision/reacTIVision.xml", F_OK )==0) sprintf(config->file,"/opt/share/reacTIVision/reacTIVision.xml"); #else sprintf(config->file,"./reacTIVision.xml"); #endif } TiXmlDocument xml_settings( config->file ); xml_settings.LoadFile(); if( xml_settings.Error() ) { std::cout << "Error loading configuration file: " << config->file << std::endl; return; } TiXmlHandle docHandle( &xml_settings ); TiXmlHandle config_root = docHandle.FirstChild("reactivision"); TiXmlElement* tuio_element = config_root.FirstChild("tuio").Element(); if( tuio_element!=NULL ) { if(tuio_element->Attribute("host")!=NULL) sprintf(config->host,"%s",tuio_element->Attribute("host")); if(tuio_element->Attribute("port")!=NULL) config->port = atoi(tuio_element->Attribute("port")); } TiXmlElement* camera_element = config_root.FirstChild("camera").Element(); if( camera_element!=NULL ) { if(camera_element->Attribute("config")!=NULL) sprintf(config->camera_config,"%s",camera_element->Attribute("config")); } TiXmlElement* midi_element = config_root.FirstChild("midi").Element(); if( midi_element!=NULL ) { if(midi_element->Attribute("config")!=NULL) { sprintf(config->midi_config,"%s",midi_element->Attribute("config")); config->midi=true; } } TiXmlElement* finger_element = config_root.FirstChild("finger").Element(); if( finger_element!=NULL ) { if(finger_element->Attribute("size")!=NULL) config->finger_size = atoi(finger_element->Attribute("size")); if(finger_element->Attribute("sensitivity")!=NULL) config->finger_sensitivity = atoi(finger_element->Attribute("sensitivity")); } TiXmlElement* image_element = config_root.FirstChild("image").Element(); if( image_element!=NULL ) { if(image_element->Attribute("display")!=NULL) { if ( strcmp( image_element->Attribute("display"), "none" ) == 0 ) config->display_mode = 0; else if ( strcmp( image_element->Attribute("display"), "src" ) == 0 ) config->display_mode = 1; else if ( strcmp( image_element->Attribute("display"), "dest" ) == 0 ) config->display_mode = 2; } if(image_element->Attribute("equalize")!=NULL) { if ((strcmp( image_element->Attribute("equalize"), "true" ) == 0) || atoi(image_element->Attribute("equalize"))==1) config->background = true; } if(image_element->Attribute("fullscreen")!=NULL) { if ((strcmp( image_element->Attribute("fullscreen"), "true" ) == 0) || atoi(image_element->Attribute("fullscreen"))==1) config->fullscreen = true; } } TiXmlElement* threshold_element = config_root.FirstChild("threshold").Element(); if( threshold_element!=NULL ) { if(threshold_element->Attribute("gradient")!=NULL) { if (strcmp(threshold_element->Attribute("gradient"), "max" ) == 0) config->gradient_gate=64; else if (strcmp(threshold_element->Attribute("gradient"), "min" ) == 0) config->gradient_gate=0; else config->gradient_gate = atoi(threshold_element->Attribute("gradient")); } if(threshold_element->Attribute("tile")!=NULL) { if (strcmp(threshold_element->Attribute("tile"), "max" ) == 0) config->tile_size=INT_MAX; else if (strcmp(threshold_element->Attribute("tile"), "min" ) == 0) config->tile_size=2; else config->tile_size = atoi(threshold_element->Attribute("tile")); } if(threshold_element->Attribute("threads")!=NULL) { if (strcmp(threshold_element->Attribute("threads"), "max" ) == 0) config->thread_count=SDL_GetCPUCount(); else if (strcmp(threshold_element->Attribute("threads"), "min" ) == 0) config->thread_count=1; else { config->thread_count = atoi(threshold_element->Attribute("threads")); if(config->thread_count<1) config->thread_count = 1; if(config->thread_count>SDL_GetCPUCount()) config->thread_count = SDL_GetCPUCount(); } } } TiXmlElement* fiducial_element = config_root.FirstChild("fiducial").Element(); if( fiducial_element!=NULL ) { if(fiducial_element->Attribute("engine")!=NULL) { if ( strcmp( fiducial_element->Attribute("engine"), "amoeba" ) == 0 ) config->amoeba = true; else if ( strcmp( fiducial_element->Attribute("engine"), "classic" ) == 0 ) { config->classic = true; config->amoeba = false; } } if(fiducial_element->Attribute("tree")!=NULL) sprintf(config->tree_config,"%s",fiducial_element->Attribute("tree")); } TiXmlElement* calibration_element = config_root.FirstChild("calibration").Element(); if( calibration_element!=NULL ) { if(calibration_element->Attribute("invert")!=NULL) { if (strstr(calibration_element->Attribute("invert"),"x")>0) config->invert_x = true; if (strstr(calibration_element->Attribute("invert"),"y")>0) config->invert_y = true; if (strstr(calibration_element->Attribute("invert"),"a")>0) config->invert_a = true; } if(calibration_element->Attribute("grid")!=NULL) sprintf(config->grid_config,"%s",calibration_element->Attribute("grid")); } }
static void _sys_info_reset(void) { memset(sys_info_buffer,0,sizeof(sys_info_buffer)); _sys_info_printf("SDL information:\n" "----------------\n" "\n" "SDL_GetPlatform(): %s\n\n" "SDL_GetCPUCount(): %d (Number of logical CPU cores)\n" #if SDL_VERSION_ATLEAST(2,0,1) "SDL_GetSystemRAM(): %d MB\n" #endif "SDL_GetCPUCacheLineSize(): %d kB (Cache L1)\n\n", SDL_GetPlatform(), SDL_GetCPUCount(), #if SDL_VERSION_ATLEAST(2,0,1) SDL_GetSystemRAM(), #endif SDL_GetCPUCacheLineSize() ); int total_secs, pct; SDL_PowerState st = SDL_GetPowerInfo(&total_secs,&pct); char * st_string; switch(st) { default: case SDL_POWERSTATE_UNKNOWN: st_string = "SDL_POWERSTATE_UNKNOWN (cannot determine power status)"; break; case SDL_POWERSTATE_ON_BATTERY: st_string = "SDL_POWERSTATE_ON_BATTERY (not plugged in, running on battery)"; break; case SDL_POWERSTATE_NO_BATTERY: st_string = "SDL_POWERSTATE_NO_BATTERY (plugged in, no battery available)"; break; case SDL_POWERSTATE_CHARGING: st_string = "SDL_POWERSTATE_CHARGING (plugged in, charging battery)"; break; case SDL_POWERSTATE_CHARGED: st_string = "SDL_POWERSTATE_CHARGED (plugged in, battery charged)"; break; } unsigned int hours = ((unsigned int)total_secs)/3600; unsigned int min = (((unsigned int)total_secs)-(hours*3600))/60; unsigned int secs = (((unsigned int)total_secs)-(hours*3600)-(min*60)); _sys_info_printf("SDL_GetPowerInfo():\n %s\n Time left: %d:%02d:%02d\n Percentage: %3d%%\n\n", st_string,hours,min,secs,pct); #ifdef ENABLE_OPENGL _sys_info_printf("OpenGL information:\n" "-------------------\n" "\n" "GL_RENDERER = %s\n" "GL_VERSION = %s\n" "GL_VENDOR = %s\n" "GL_EXTENSIONS = ", (char*)glGetString(GL_RENDERER),(char*)glGetString(GL_VERSION), (char*)glGetString(GL_VENDOR)); _sys_info_print((char*)glGetString(GL_EXTENSIONS)); #endif _sys_info_printf("\n\nEND LOG\n"); }
int main(int argc, char* argv[]) { signal(SIGSEGV, segFault); if (argc < 2) { printUsage(); return 0; } #ifdef DEPRECATED printf("*Deprecation warning*\n"); fflush(0); #endif randomizer.timeSeed(); Scene& scene = *Scene::getInstance(); Texture screen; int w = 300, h = 300; bool threads_changed = 0; std::string filename, output = "out.bmp"; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "--no-preview")) { settings.show_preview = 0; } else if (!strcmp(argv[i], "--size")) { sscanf(argv[++i], "%d", &w); sscanf(argv[++i], "%d", &h); } else if (!strcmp(argv[i], "--renders")) { sscanf(argv[++i], "%d", &settings.nrenders); } else if (!strcmp(argv[i], "--samples")) { sscanf(argv[++i], "%d", &settings.nsamples); } else if (!strcmp(argv[i], "--shadows")) { sscanf(argv[++i], "%d", &settings.nshadows); } else if (!strcmp(argv[i], "--coherent")) { settings.coherence = 1; } else if (!strcmp(argv[i], "--point-lights")) { settings.point_lights = 1; } else if (!strcmp(argv[i], "--dof-degrees")) { sscanf(argv[++i], "%f", &settings.dof_range); settings.dof_range *= PI / 180.0; } else if (!strcmp(argv[i], "--no-aa")) { settings.aa_enabled = 0; } else if (!strcmp(argv[i], "--aa-threshold")) { sscanf(argv[++i], "%f", &settings.aa_threshold); } else if (!strcmp(argv[i], "--threads")) { threads_changed = 1; sscanf(argv[++i], "%d", &settings.nworkers); } else if (!strcmp(argv[i], "--output") || !strcmp(argv[i], "-o")) { output = argv[++i]; } else if (!strcmp(argv[i], "--no-output")) { output = ""; } else { if (filename.empty()) { filename = argv[i]; } else { printf("Unrecognized token \"%s\".\n", argv[i]); exit(0); } } } if (settings.show_preview) { if (SDL_Init(SDL_INIT_VIDEO) < 0) return -1; } else { if (SDL_Init(0) < 0) return -1; } atexit(SDL_Quit); if (!threads_changed) { settings.nworkers = SDL_GetCPUCount(); if (settings.nworkers > 1) settings.nworkers--; //Use n threads (counting this one) on n-core machines, but 2 threads for single-core machines } try { Parser parser; parser.parseInto(filename.c_str(), &scene); } catch (std::exception& e) { fprintf(stderr, "%s\n", e.what()); return 1; } scene.init(); /* * Set up scene */ scene.camera.setScreen(w, h, (float)w / h, 1, PI / 2); screen.setDimensions(scene.camera.pxw, scene.camera.pxh); drawPattern(screen); if (settings.show_preview) { window = SDL_CreateWindow(TITLE, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, scene.camera.pxw, scene.camera.pxh, 0); px = new PixelRenderer(SDL_CreateRenderer(window, -1, 0), scene.camera.pxw, scene.camera.pxh); redraw(screen); } Uint32 started = SDL_GetTicks(); std::vector<Texture> screens; for (int i = 0; i < settings.nrenders; i++) { render(scene, screen, i + 1, settings.nrenders); screens.push_back(screen); randomizer.advanceSeed(); } screen = Texture(screens); #ifndef SHOW_AA if (settings.show_preview) redraw(screen); #endif printf("Tracing complete:\n"); printf("\tTotal time elapsed: %.3fs\n", 0.001 * (SDL_GetTicks() - started)); fflush(0); if (output != "") screen.save_filename(output); if (settings.show_preview) { SDL_Event event; bool exitflag = 0; while (!exitflag) { while (SDL_PollEvent(&event)) if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) exitflag = 1; SDL_Delay(100); } SDL_DestroyRenderer(px->getRenderer()); delete px; SDL_DestroyWindow(window); } return 0; }
Engine::Engine(util::Dir *data_dir, const char *windowtitle) : running{false}, drawing_debug_overlay{true}, drawing_huds{true}, engine_coord_data{this->get_coord_data()}, current_player{1}, data_dir{data_dir}, audio_manager{} { for (uint32_t size : {12, 20}) { fonts[size] = std::unique_ptr<Font>{new Font{"DejaVu Serif", "Book", size}}; } this->logsink_file = std::make_unique<log::FileSink>("/tmp/openage-log", true); // enqueue the engine's own input handler to the // execution list. this->register_resize_action(this); if (SDL_Init(SDL_INIT_VIDEO) < 0) { throw util::Error(MSG(err) << "SDL video initialization: " << SDL_GetError()); } else { log::log(MSG(info) << "Initialized SDL video subsystems."); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); int32_t window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED; this->window = SDL_CreateWindow( windowtitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, this->engine_coord_data->window_size.x, this->engine_coord_data->window_size.y, window_flags ); if (this->window == nullptr) { throw util::Error(MSG(err) << "Failed to create SDL window: " << SDL_GetError()); } // load support for the PNG image formats, jpg bit: IMG_INIT_JPG int wanted_image_formats = IMG_INIT_PNG; int sdlimg_inited = IMG_Init(wanted_image_formats); if ((sdlimg_inited & wanted_image_formats) != wanted_image_formats) { throw util::Error(MSG(err) << "Failed to init PNG support: " << IMG_GetError()); } this->glcontext = SDL_GL_CreateContext(this->window); if (this->glcontext == nullptr) { throw util::Error(MSG(err) << "Failed creating OpenGL context: " << SDL_GetError()); } // check the OpenGL version, for shaders n stuff if (!epoxy_is_desktop_gl() || epoxy_gl_version() < 21) { throw util::Error(MSG(err) << "OpenGL 2.1 not available"); } // to quote the standard doc: // 'The value gives a rough estimate // of the largest texture that the GL can handle' // -> wat? // anyways, we need at least 1024x1024. int max_texture_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size); log::log(MSG(dbg) << "Maximum supported texture size: " << max_texture_size); if (max_texture_size < 1024) { throw util::Error(MSG(err) << "Maximum supported texture size too small: " << max_texture_size); } int max_texture_units; glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units); log::log(MSG(dbg) << "Maximum supported texture units: " << max_texture_units); if (max_texture_units < 2) { throw util::Error(MSG(err) << "Your GPU has too less texture units: " << max_texture_units); } // vsync on SDL_GL_SetSwapInterval(1); // enable alpha blending glEnable(GL_BLEND); // order of drawing relevant for depth // what gets drawn last is displayed on top. glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialize job manager with cpucount-2 worker threads int number_of_worker_threads = SDL_GetCPUCount() - 2; if (number_of_worker_threads <= 0) { number_of_worker_threads = 1; } this->job_manager = new job::JobManager{number_of_worker_threads}; // initialize audio auto devices = audio::AudioManager::get_devices(); if (devices.empty()) { throw util::Error{MSG(err) << "No audio devices found"}; } }
Engine::Engine(util::Dir *data_dir, const char *windowtitle) : running{false}, drawing_debug_overlay{true}, drawing_huds{true}, window_size{800, 600}, camgame_phys{10 * coord::settings::phys_per_tile, 10 * coord::settings::phys_per_tile, 0}, camgame_window{400, 300}, camhud_window{0, 600}, tile_halfsize{48, 24}, // TODO: get from convert script data_dir{data_dir}, audio_manager{48000, AUDIO_S16LSB, 2, 4096} { for (uint32_t size : {12, 20}) { fonts[size] = std::unique_ptr<Font>{new Font{"DejaVu Serif", "Book", size}}; } // enqueue the engine's own input handler to the // execution list. this->register_input_action(&this->input_handler); this->input_handler.register_resize_action(this); if (SDL_Init(SDL_INIT_VIDEO) < 0) { throw util::Error("SDL video initialization: %s", SDL_GetError()); } else { log::msg("initialized SDL video subsystems."); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); int32_t window_flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_MAXIMIZED; this->window = SDL_CreateWindow( windowtitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, this->window_size.x, this->window_size.y, window_flags ); if (this->window == nullptr) { throw util::Error("Failed creating SDL window: %s", SDL_GetError()); } // load support for the PNG image formats, jpg bit: IMG_INIT_JPG int wanted_image_formats = IMG_INIT_PNG; int sdlimg_inited = IMG_Init(wanted_image_formats); if ((sdlimg_inited & wanted_image_formats) != wanted_image_formats) { throw util::Error("Failed to init PNG support: %s", IMG_GetError()); } this->glcontext = SDL_GL_CreateContext(this->window); if (this->glcontext == nullptr) { throw util::Error("Failed creating OpenGL context: %s", SDL_GetError()); } // initialize glew, for shaders n stuff GLenum glew_state = glewInit(); if (glew_state != GLEW_OK) { throw util::Error("GLEW initialization failed"); } if (!GLEW_VERSION_2_1) { throw util::Error("OpenGL 2.1 not available"); } // to quote the standard doc: // 'The value gives a rough estimate // of the largest texture that the GL can handle' // -> wat? // anyways, we need at least 1024x1024. int max_texture_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_texture_size); log::dbg("Maximum supported texture size: %d", max_texture_size); if (max_texture_size < 1024) { throw util::Error("Maximum supported texture size too small: %d", max_texture_size); } int max_texture_units; glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &max_texture_units); log::dbg("Maximum supported texture units: %d", max_texture_units); if (max_texture_units < 2) { throw util::Error("Your GPU has too less texture units: %d", max_texture_units); } // vsync on SDL_GL_SetSwapInterval(1); // enable alpha blending glEnable(GL_BLEND); // order of drawing relevant for depth // what gets drawn last is displayed on top. glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialize job manager with cpucount-2 worker threads int number_of_worker_threads = SDL_GetCPUCount() - 2; if (number_of_worker_threads <= 0) { number_of_worker_threads = 1; } this->job_manager = new job::JobManager{number_of_worker_threads}; // initialize audio auto devices = audio::AudioManager::get_devices(); if (devices.empty()) { throw util::Error{"No audio devices found"}; } }
int System::getProcessorCount() const { return SDL_GetCPUCount(); }
static mrb_value mrb_sdl2_cpuinfo_get_cpu_count(mrb_state *mrb, mrb_value self) { int result = SDL_GetCPUCount(); return mrb_fixnum_value(result); }