DisplayDevicePtr DisplayDevice::factory(const std::string& type) { ASSERT_LOG(!get_display_registry().empty(), "No display device drivers registered."); auto it = get_display_registry().find(type); if(it == get_display_registry().end()) { LOG_WARN("Requested display driver '" << type << "' not found, using default: " << get_display_registry().begin()->first); current_display_device() = get_display_registry().begin()->second(); return get_display_registry().begin()->second(); } current_display_device() = it->second(); return it->second(); }
float convert_numeric(const variant& node) { if(node.is_int()) { return clamp<int>(node.as_int32(), 0, 255) / 255.0f; } else if(node.is_float()) { return clamp<float>(node.as_float(), 0.0f, 1.0f); } else if(node.is_string()) { return convert_string_to_number(node.as_string()); } ASSERT_LOG(false, "attribute of Color value was expected to be numeric type."); return 1.0f; }
double as3_value::to_number() { switch(type_) { case UNDEFINED: return std::numeric_limits<double>::infinity(); case BOOLEAN: return b_ ? 1 : 0; case NUMERIC: return d_; case OBJECT: return o_ == NULL ? 0 : o_->to_number(); case PROPERTY: { ASSERT_LOG(false, "XXX todo PROPERTY::to_number"); } } ASSERT_LOG(type_ != STRING, "FATAL: unknown type_ value: " << type_); // String case -- we do thing the lazy way, not the compliant way. double num = std::numeric_limits<double>::infinity(); try { num = boost::lexical_cast<double>(s_); } catch(boost::bad_lexical_cast&) { std::cerr << "Caught a bad floating point cast from " << s_ << " assuming infinity" << std::endl; } return num; }
void swap_buffers() { #if SDL_VERSION_ATLEAST(2, 0, 0) ASSERT_LOG(global_main_window != NULL, "swap_buffers called on NULL window"); SDL_GL_SwapWindow(global_main_window ); #else SDL_GL_SwapBuffers(); #endif #if defined(__ANDROID__) graphics::reset_opengl_state(); #endif }
const SDL_Color& get_color_from_name(std::string name) { if(get_color_cache().empty()) { color_cache_init(); } std::map<std::string,boost::function<const SDL_Color&()> >::iterator it = get_color_cache().find(name); if(it != get_color_cache().end()) { return it->second(); } ASSERT_LOG(false, "Color \"" << name << "\" not known!"); return color_black(); }
rect quick_draw(int x, int y, const std::string& str, const std::string& font, int size, const color& c) { SDL_Color bg = {0, 0, 0, 255}; surface_ptr surf = surface_ptr(new surface(TTF_RenderUTF8_Shaded(font::get_font(font, size).get(), str.c_str(), c.as_sdl_color(), bg))); ASSERT_LOG(surf != NULL, "Couldn't render text into texture"); blit_2d_texture(texture::get(surf), static_cast<float>(x), static_cast<float>(y), static_cast<float>(surf->width()), static_cast<float>(surf->height())); return rect(x, y, surf->width(), surf->height()); }
void write_file(const std::string& fname, const std::string& data) { path p(fname); ASSERT_LOG(p.has_filename(), "No filename found in write_file path: " << fname); // Create any needed directories boost::system::error_code ec; create_directories(p.parent_path(), ec); // Write the file. std::ofstream file(fname.c_str(), std::ios_base::binary); file << data; }
void write_file(const std::string& fname, const std::string& data) { bool absolute_path = fname[0] == '/' ? true : false; //Try to ensure that the dir the file is in exists. std::vector<std::string> components; boost::split(components, fname, std::bind2nd(std::equal_to<char>(), '/')); boost::filesystem::path p(fname); ASSERT_LOG(get_dir(p.parent_path().string()) != "", "Couldn't create directory: " << p.parent_path().string()); //Write the file. std::ofstream file(fname.c_str(),std::ios_base::binary); file << data; }
bool File::readBuffer(uint8_t* _pBuffer, int iBufferSize) { ASSERT_LOG(m_pHandle != NULL, "File handle is invalid"); ASSERT_LOG(_pBuffer != NULL, "Buffer is invalid"); if (-1 == iBufferSize) { iBufferSize = getLength(); } if (0 == iBufferSize) { return false; } if (static_cast<int>(fread(_pBuffer, 1, iBufferSize, (FILE*)m_pHandle)) != iBufferSize) { return false; } return true; }
void text::quick_draw(render& render_obj, GLfloat x, GLfloat y, const std::string& str, const std::string& font, int size, const color& c) { SDL_Color bg = {0, 0, 0, 255}; surface_ptr surf = surface_ptr(TTF_RenderUTF8_Shaded(font::get_font(font, size).get(), str.c_str(), c.as_sdl_color(), bg), SDL_FreeSurface); ASSERT_LOG(surf != NULL, "Couldn't render text into texture"); render_obj.blit_2d_texture(texture::get(surf), x, y); }
SurfacePtr Surface::create(int width, int height, int bpp, uint32_t rmask, uint32_t gmask, uint32_t bmask, uint32_t amask) { // XXX no caching as default? ASSERT_LOG(get_surface_creator().empty() == false, "No resources registered to create surfaces from masks."); auto create_fn_tuple = get_surface_creator().begin()->second; return std::get<2>(create_fn_tuple)(width, height, bpp, rmask, gmask, bmask, amask); }
Surface::BlendMode SurfaceSDL::getBlendMode() const { SDL_BlendMode sdl_bm; SDL_GetSurfaceBlendMode(surface_, &sdl_bm); switch(sdl_bm) { case SDL_BLENDMODE_NONE: return BLEND_MODE_NONE; case SDL_BLENDMODE_BLEND: return BLEND_MODE_BLEND; case SDL_BLENDMODE_ADD: return BLEND_MODE_ADD; case SDL_BLENDMODE_MOD: return BLEND_MODE_MODULATE; } ASSERT_LOG(false, "Unrecognised SDL blend mode: " << sdl_bm); return BLEND_MODE_NONE; }
void Material::init(const variant& node) { blend_.set(BlendModeConstants::BM_SRC_ALPHA, BlendModeConstants::BM_ONE_MINUS_SRC_ALPHA); if(node.is_string()) { name_ = node.as_string(); tex_.emplace_back(DisplayDevice::createTexture(name_)); } else if(node.is_map()) { name_ = node["name"].as_string(); // XXX: technically a material could have multiple technique's and passes -- ignoring for now. ASSERT_LOG(node.has_key("technique"), "PSYSTEM2: 'material' must have 'technique' attribute."); ASSERT_LOG(node["technique"].has_key("pass"), "PSYSTEM2: 'material' must have 'pass' attribute."); const variant& pass = node["technique"]["pass"]; use_lighting_ = pass["lighting"].as_bool(false); use_fog_ = pass["fog_override"].as_bool(false); do_depth_write_ = pass["depth_write"].as_bool(true); do_depth_check_ = pass["depth_check"].as_bool(true); if(pass.has_key("scene_blend")) { blend_.set(pass["scene_blend"]); } if(pass.has_key("texture_unit")) { if(pass["texture_unit"].is_map()) { tex_.emplace_back(createTexture(pass["texture_unit"])); } else if(pass["texture_unit"].is_list()) { for(size_t n = 0; n != pass["texture_unit"].num_elements(); ++n) { tex_.emplace_back(createTexture(pass["texture_unit"][n])); } } else { ASSERT_LOG(false, "'texture_unit' attribute must be map or list "); } } if(pass.has_key("rect")) { draw_rect_ = rectf(pass["rect"]); } } else { ASSERT_LOG(false, "Materials(Textures) must be either a single string filename or a map."); } }
/* Handle a response to a given request. if this is a quorum setting, choose the * right response. Then make sure all the requests are satisfied in a fragmented * request scenario and then use the post coalesce logic to cook up a combined * response */ static rstatus_t client_handle_response(struct conn *conn, msgid_t reqid, struct msg *rsp) { ASSERT_LOG(!rsp->peer, "response %lu:%lu has peer set", rsp->id, rsp->parent_id); // now the handler owns the response. ASSERT(conn->type == CONN_CLIENT); // Fetch the original request struct msg *req = dictFetchValue(conn->outstanding_msgs_dict, &reqid); if (!req) { log_notice("looks like we already cleanedup the request for %d", reqid); rsp_put(rsp); return DN_OK; } // we have to submit the response irrespective of the unref status. rstatus_t status = msg_handle_response(req, rsp); if (conn->waiting_to_unref) { // dont care about the status. if (req->awaiting_rsps) return DN_OK; // all responses received dictDelete(conn->outstanding_msgs_dict, &reqid); log_info("Putting req %d", req->id); req_put(req); client_unref_internal_try_put(conn); return DN_OK; } if (status == DN_NOOPS) { // by now the response is dropped if (!req->awaiting_rsps) { // if we have sent the response for this request or the connection // is closed and we are just waiting to drain off the messages. if (req->rsp_sent) { dictDelete(conn->outstanding_msgs_dict, &reqid); log_info("Putting req %d", req->id); req_put(req); } } } else if (status == DN_OK) { g_pre_coalesce(req->selected_rsp); if (req_done(conn, req)) { struct context *ctx = conn_to_ctx(conn); status = event_add_out(ctx->evb, conn); if (status != DN_OK) { conn->err = errno; } } } return status; }
std::vector<char> compress(const std::vector<char>& data, int compression_level) { z_stream strm; int ret; int pos_in = 0; int pos_out = 0; int flush; std::vector<char> in(data); // <-- annoying work around for old versions of zlib that don't define z_stream.in as const, by defining ZLIB_CONST std::vector<char> out; ASSERT_LOG(compression_level >= -1 && compression_level <= 9, "Compression level must be between -1(default) and 9."); memset(&strm, 0, sizeof(z_stream)); if(deflateInit(&strm, compression_level) != Z_OK) { CompressionException e = {"Unable to initialise deflation routines."}; throw CompressionException(e); } do { strm.avail_in = (in.size() - pos_in) > CHUNK ? CHUNK : in.size() - pos_in; flush = (strm.avail_in + pos_in) == in.size() ? Z_FINISH : Z_NO_FLUSH; if(in.size()) { strm.next_in = reinterpret_cast<Bytef*>(&in[pos_in]); } else { strm.next_in = 0; } do { out.resize(pos_out - out.size() + CHUNK); strm.avail_out = CHUNK; strm.next_out = reinterpret_cast<Bytef*>(&out[pos_out]); ret = deflate(&strm, flush); // no bad return value ASSERT_LOG(ret != Z_STREAM_ERROR, "Error in the compression stream"); pos_out += CHUNK - strm.avail_out; } while (strm.avail_out == 0); ASSERT_LOG(strm.avail_in == 0, "zip::compress(): All input used"); // all input will be used } while(flush != Z_FINISH); ASSERT_LOG(ret == Z_STREAM_END, "zip::compress(): stream will be complete"); deflateEnd(&strm); out.resize(pos_out); return out; }
float node::as_float() const { switch(type()) { case NODE_TYPE_INTEGER: return float(i_); case NODE_TYPE_FLOAT: return f_; case NODE_TYPE_BOOL: return b_ ? 1.0f : 0.0f; default: break; } ASSERT_LOG(false, "as_float() type conversion error from " << type_as_string() << " to float"); return 0; }
tile::tile(int x, int y, const std::string& data) : loc_(x, y) { std::vector<std::string> v = util::split(data, ' '); ASSERT_GE(v.size(), 1); terrain_ = terrain::get(v.front()); ASSERT_LOG(terrain_, "Could not find terrain " << v.front()); if(v.size() > 1) { productivity_ = atoi(v[1].c_str()); } else { productivity_ = terrain_->calculate_production_value(); } }
void internal_server::disconnect(int session_id) { if(session_id == -1) { return; } for(auto i = connections_.begin(); i != connections_.end(); ++i) { if(i->second.session_id == session_id) { connections_.erase(i); return; } } ASSERT_LOG(false, "Trying to erase unknown session_id: " << session_id); }
void run_utility(const std::string& utility_name, const std::vector<std::string>& arg) { UtilityProgram util = get_utility_map()[utility_name]; if(!util) { std::string known; for(UtilityMap::const_iterator i = get_utility_map().begin(); i != get_utility_map().end(); ++i) { if(i->second) { known += i->first + " "; } } ASSERT_LOG(false, "Unknown utility: '" << utility_name << "'; known utilities: " << known); } util(arg); }
void internal_server::disconnect(int session_id) { if(session_id == -1) { return; } for(std::map<send_function, socket_info, send_function_less>::iterator i = connections_.begin(); i != connections_.end(); ++i) { if(i->second.session_id == session_id) { connections_.erase(i); return; } } ASSERT_LOG(false, "Trying to erase unknown session_id: " << session_id); }
void copy_file(const std::string& from, const std::string& to) { #ifdef _WINDOWS ASSERT_LOG(CopyFileA(from.c_str(), to.c_str(), false), "copy_file: (" << from << " : " << to << ") failed."); #else // Note that this is a pretty gross copy operation and won't preserve meta-data // it will only copy the file data. If your API has a better copy option, I'd // suggest implementing it here. std::fstream file1(from.c_str(), std::ios_base::in | std::ios_base::binary); std::ofstream file2(to.c_str(), std::ios_base::out | std::ios_base::binary); file1 << std::noskipws; std::copy(std::istream_iterator<char>(file1),std::istream_iterator<char>(),std::ostream_iterator<char>(file2)); #endif }
int64_t node::as_int() const { switch(type()) { case NODE_TYPE_INTEGER: return i_; case NODE_TYPE_FLOAT: return static_cast<int64_t>(f_); case NODE_TYPE_BOOL: return b_ ? 1 : 0; default: break; } ASSERT_LOG(false, "as_int() type conversion error from " << type_as_string() << " to int"); return 0; }
void generate_color_wheel(int num_points, std::vector<glm::u8vec4>* color_array, const Color& centre, float start_hue, float end_hue) { ASSERT_LOG(num_points > 0, "Must be more than one point in call to generate_color_wheel()"); color_array->emplace_back(centre.ri(), centre.gi(), centre.bi(), centre.ai()); // center color. float hue = start_hue; const float sat = 1.0f; const float value = 1.0f; for(int n = 0; n != num_points; n++) { auto c = Color::from_hsv(hue, sat, value); color_array->emplace_back(c.ri(), c.gi(), c.bi(), c.ai()); hue += (end_hue - start_hue)/static_cast<float>(num_points); } color_array->emplace_back((*color_array)[1]); }
void graphical_font_label::set_value(const std::string& key, const variant& v) { if(key == "text") { set_text(v.as_string()); } else if(key == "font") { font_ = graphical_font::get(v.as_string()); ASSERT_LOG(font_.get(), "UNKNOWN FONT: " << v.as_string()); reset_text_dimensions(); } else if(key == "size") { size_ = v.as_int(); reset_text_dimensions(); } //widget::set_value(key); }
void program_object::set_uniform(const_actives_map_iterator it, const GLfloat* value) { const actives& u = it->second; ASSERT_LOG(value != NULL, "set_uniform(): value is NULL"); switch(u.type) { case GL_FLOAT: { glUniform1f(u.location, *value); break; } case GL_FLOAT_VEC2: { glUniform2fv(u.location, u.num_elements, value); break; } case GL_FLOAT_VEC3: { glUniform3fv(u.location, u.num_elements, value); break; } case GL_FLOAT_VEC4: { glUniform4fv(u.location, u.num_elements, value); break; } case GL_FLOAT_MAT2: { glUniformMatrix2fv(u.location, u.num_elements, GL_FALSE, value); break; } case GL_FLOAT_MAT3: { glUniformMatrix3fv(u.location, u.num_elements, GL_FALSE, value); break; } case GL_FLOAT_MAT4: { glUniformMatrix4fv(u.location, u.num_elements, GL_FALSE, value); break; } default: ASSERT_LOG(false, "Unhandled uniform type: " << it->second.type); } }
bool lua_context::execute(const variant& value, game_logic::formula_callable* callable) { bool res = false; if(callable) { set_self_callable(*callable); } if(value.is_string()) { res = dostring("", value.as_string()); } else { lua_compiled_ptr compiled = value.try_convert<lua_compiled>(); ASSERT_LOG(compiled != NULL, "FATAL: object given couldn't be converted to type 'lua_compiled'"); res = compiled->run(context_ptr()); } return res; }
void get_unique_filenames_under_dir(const std::string& dir, std::map<std::string, std::string>* file_map, const std::string& prefix) { ASSERT_LOG(file_map != NULL, "get_unique_filenames_under_dir() passed a NULL file_map"); path p(dir); if(!is_directory(p)) { return; } for(recursive_directory_iterator it = recursive_directory_iterator(p); it != recursive_directory_iterator(); ++it) { if(!is_directory(it->path())) { (*file_map)[prefix + it->path().filename().generic_string()] = it->path().generic_string(); } } }
void read_voxels(const variant& v, VoxelMap* out) { std::vector<int> pos = v["loc"].as_list_int(); ASSERT_LOG(pos.size()%3 == 0, "Bad location: " << v.write_json() << v.debug_location()); graphics::color color(v["color"]); while(pos.empty() == false) { VoxelPair result; std::copy(pos.end()-3, pos.end(), &result.first[0]); result.second.color = color; out->insert(result); pos.resize(pos.size() - 3); } }
variant get_value(const std::string& key) const { if(value_names_) { for(int n = 0; n != value_names_->size(); ++n) { if((*value_names_)[n] == key) { return values_[n]; } } } if(fallback_) { return fallback_->query_value(key); } ASSERT_LOG(false, "GET VALUE " << key << " FROM SLOT CALLABLE"); return variant(); }
void cairo_context::render_svg(const std::string& fname) { GError *error = NULL; static std::map<std::string, RsvgHandle*> cache; RsvgHandle* handle = NULL; auto itor = cache.find(fname); if(itor == cache.end()) { std::string real_fname = module::map_file(fname); ASSERT_LOG(sys::file_exists(real_fname), "Could not find svg file: " << fname); handle = rsvg_handle_new_from_file(real_fname.c_str(), &error); ASSERT_LOG(error == NULL, "SVG rendering error: " << error->message); } else { handle = itor->second; } rsvg_handle_render_cairo(handle, cairo_); cairo_status_t status = cairo_status(cairo_); ASSERT_LOG(status == 0, "SVG rendering error: " << cairo_status_to_string(status)); }