void Pokemon::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { QRectF source(0,0,image.width(),image.height()); painter->drawPixmap(boundingRect(), image, source); }
/** * Initialize GSI Authentication. * This method asks the server for authentication. * @param sock the socket descriptot * @return true on success, false otherwise. */ bool GSISocketClient::InitGSIAuthentication(int sock) { OM_uint32 major_status = 0; OM_uint32 minor_status = 0; gss_cred_id_t credential = GSS_C_NO_CREDENTIAL; OM_uint32 req_flags = 0; OM_uint32 ret_flags = 0; int token_status = 0; bool return_status = false; gss_name_t targ_name; gss_buffer_desc name_buffer; char service[1024]; //acquire our credentials major_status = globus_gss_assist_acquire_cred(&minor_status, GSS_C_BOTH, &credential); if(major_status != GSS_S_COMPLETE) { char buf[32]; std::string msg(FAILED_ACQ_CRED); sprintf(buf, "%d", port); msg.append(host + ":" + std::string(buf)); char *gssmsg = NULL; globus_gss_assist_display_status_str( &gssmsg, NULL, major_status, minor_status, token_status); std::string source(gssmsg); free(gssmsg); return false; } //Request that remote peer authenticate tself req_flags = GSS_C_MUTUAL_FLAG; if(_delegate_credentials) { req_flags |= GSS_C_DELEG_FLAG; } snprintf(service, sizeof(service), "host@%s", host.c_str()); //initialize the security context // credential has to be fill in beforehand std::pair<int,int> arg(sock, m_auth_timeout); major_status = globus_gss_assist_init_sec_context(&minor_status, credential, &gss_context, _server_contact.empty() ? service :(char*) _server_contact.c_str(), req_flags, &ret_flags, &token_status, get_token, (void *) &arg, send_token, (void *) &arg); gss_release_cred(&minor_status, &credential); if(major_status != GSS_S_COMPLETE) { char *gssmsg = NULL; globus_gss_assist_display_status_str(&gssmsg, NULL, major_status, minor_status, token_status); if(gss_context != GSS_C_NO_CONTEXT) { gss_delete_sec_context(&minor_status, &gss_context, GSS_C_NO_BUFFER); } std::string source(gssmsg); free(gssmsg); return_status = false; } else { major_status = gss_inquire_context(&minor_status, gss_context, NULL, &targ_name, NULL, NULL, NULL, NULL, NULL); return_status = (major_status == GSS_S_COMPLETE); major_status = gss_display_name(&minor_status, targ_name, &name_buffer, NULL); gss_release_name(&minor_status, &targ_name); } if (return_status == false && gss_context != GSS_C_NO_CONTEXT) { gss_delete_sec_context(&minor_status, &gss_context, GSS_C_NO_BUFFER); } if (return_status == false) { char *gssmsg = NULL; globus_gss_assist_display_status_str( &gssmsg, NULL, major_status, minor_status, token_status); std::string source(gssmsg); free(gssmsg); } return return_status; }
// Update map window screen // top_tile top left tile to draw. Not necessarily visible. // extRect, extRect = map window on screen // moveX, moveY: when a hero is in movement indicates how to shift the map. Range is -31 to + 31. void CMapHandler::terrainRect( int3 top_tile, ui8 anim, const std::vector< std::vector< std::vector<ui8> > > * visibilityMap, bool otherHeroAnim, ui8 heroAnim, SDL_Surface * extSurf, const SDL_Rect * extRect, int moveX, int moveY, bool puzzleMode, int3 grailPosRel ) const { // Width and height of the portion of the map to process. Units in tiles. ui32 dx = tilesW; ui32 dy = tilesH; // Basic rectangle for a tile. Should be a const but conflicts with SDL headers SDL_Rect rtile = { 0, 0, 32, 32 }; // Absolute coords of the first pixel in the top left corner int srx_init = offsetX + extRect->x; int sry_init = offsetY + extRect->y; int srx, sry; // absolute screen coordinates in pixels // If moving, we need to add an extra column/line if (moveX != 0) { dx++; srx_init += moveX; if (moveX > 0) { // Moving right. We still need to draw the old tile on the // left, so adjust our referential top_tile.x --; srx_init -= 32; } } if (moveY != 0) { dy++; sry_init += moveY; if (moveY > 0) { // Moving down. We still need to draw the tile on the top, // so adjust our referential. top_tile.y --; sry_init -= 32; } } // Reduce sizes if we go out of the full map. if (top_tile.x < -frameW) top_tile.x = -frameW; if (top_tile.y < -frameH) top_tile.y = -frameH; if (top_tile.x + dx > sizes.x + frameW) dx = sizes.x + frameW - top_tile.x; if (top_tile.y + dy > sizes.y + frameH) dy = sizes.y + frameH - top_tile.y; if(!otherHeroAnim) heroAnim = anim; //the same, as it should be SDL_Rect prevClip; SDL_GetClipRect(extSurf, &prevClip); SDL_SetClipRect(extSurf, extRect); //preventing blitting outside of that rect const BlitterWithRotationVal blitterWithRotation = CSDL_Ext::getBlitterWithRotation(extSurf); const BlitterWithRotationVal blitterWithRotationAndAlpha = CSDL_Ext::getBlitterWithRotationAndAlpha(extSurf); //const BlitterWithRotationAndAlphaVal blitterWithRotation = CSDL_Ext::getBlitterWithRotation(extSurf); // printing terrain srx = srx_init; for (int bx = 0; bx < dx; bx++, srx+=32) { // Skip column if not in map if (top_tile.x+bx < 0 || top_tile.x+bx >= sizes.x) continue; sry = sry_init; for (int by=0; by < dy; by++, sry+=32) { int3 pos(top_tile.x+bx, top_tile.y+by, top_tile.z); //blitted tile position // Skip tile if not in map if (pos.y < 0 || pos.y >= sizes.y) continue; const TerrainTile2 & tile = ttiles[pos.x][pos.y][pos.z]; const TerrainTile &tinfo = map->getTile(int3(pos.x, pos.y, pos.z)); SDL_Rect sr; sr.x=srx; sr.y=sry; sr.h=sr.w=32; //blit terrain with river/road if(tile.terbitmap) { //if custom terrain graphic - use it SDL_Rect temp_rect = genRect(sr.h, sr.w, 0, 0); CSDL_Ext::blitSurface(tile.terbitmap, &temp_rect, extSurf, &sr); } else //use default terrain graphic { blitterWithRotation(terrainGraphics[tinfo.terType][tinfo.terView],rtile, extSurf, sr, tinfo.extTileFlags%4); } if(tinfo.riverType) //print river if present { blitterWithRotationAndAlpha(staticRiverDefs[tinfo.riverType-1]->ourImages[tinfo.riverDir].bitmap,rtile, extSurf, sr, (tinfo.extTileFlags>>2)%4); } //Roads are shifted by 16 pixels to bottom. We have to draw both parts separately if (pos.y > 0 && map->getTile(int3(pos.x, pos.y-1, pos.z)).roadType != ERoadType::NO_ROAD) { //part from top tile const TerrainTile &topTile = map->getTile(int3(pos.x, pos.y-1, pos.z)); Rect source(0, 16, 32, 16); Rect dest(sr.x, sr.y, sr.w, sr.h/2); blitterWithRotationAndAlpha(roadDefs[topTile.roadType - 1]->ourImages[topTile.roadDir].bitmap, source, extSurf, dest, (topTile.extTileFlags>>4)%4); } if(tinfo.roadType != ERoadType::NO_ROAD) //print road from this tile { Rect source(0, 0, 32, 32); Rect dest(sr.x, sr.y+16, sr.w, sr.h/2); blitterWithRotationAndAlpha(roadDefs[tinfo.roadType-1]->ourImages[tinfo.roadDir].bitmap, source, extSurf, dest, (tinfo.extTileFlags>>4)%4); } //blit objects const std::vector < std::pair<const CGObjectInstance*,SDL_Rect> > &objects = tile.objects; for(auto & object : objects) { const CGObjectInstance *obj = object.first; if (!graphics->getDef(obj)) processDef(obj->appearance); if (!graphics->getDef(obj) && !obj->appearance.animationFile.empty()) { logGlobal->errorStream() << "Failed to load image " << obj->appearance.animationFile; } PlayerColor color = obj->tempOwner; //checking if object has non-empty graphic on this tile if(obj->ID != Obj::HERO && !obj->coveringAt(top_tile.x + bx, top_tile.y + by)) continue; static const int notBlittedInPuzzleMode[] = {124}; //don't print flaggable objects in puzzle mode if(puzzleMode && (obj->isVisitable() || std::find(notBlittedInPuzzleMode, notBlittedInPuzzleMode+1, obj->ID) != notBlittedInPuzzleMode+1)) //? continue; SDL_Rect sr2(sr); SDL_Rect pp = object.second; pp.h = sr.h; pp.w = sr.w; const CGHeroInstance * themp = (obj->ID != Obj::HERO ? nullptr : static_cast<const CGHeroInstance*>(obj)); //print hero / boat and flag if((themp && themp->moveDir && themp->type) || (obj->ID == Obj::BOAT)) //it's hero or boat { const int IMGVAL = 8; //frames per group of movement animation ui8 dir; std::vector<Cimage> * iv = nullptr; std::vector<CDefEssential *> Graphics::*flg = nullptr; SDL_Surface * tb = nullptr; //surface to blitted if(themp) //hero { if(themp->tempOwner >= PlayerColor::PLAYER_LIMIT) //Neutral hero? { logGlobal->errorStream() << "A neutral hero (" << themp->name << ") at " << themp->pos << ". Should not happen!"; continue; } dir = themp->moveDir; //pick graphics of hero (or boat if hero is sailing) if (themp->boat) iv = &graphics->boatAnims[themp->boat->subID]->ourImages; else if (themp->sex) iv = &graphics->heroAnims[themp->type->heroClass->imageMapFemale]->ourImages; else iv = &graphics->heroAnims[themp->type->heroClass->imageMapMale]->ourImages; //pick appropriate flag set if(themp->boat) { switch (themp->boat->subID) { case 0: flg = &Graphics::flags1; break; case 1: flg = &Graphics::flags2; break; case 2: flg = &Graphics::flags3; break; default: logGlobal->errorStream() << "Not supported boat subtype: " << themp->boat->subID; } } else { flg = &Graphics::flags4; } } else //boat { const CGBoat *boat = static_cast<const CGBoat*>(obj); dir = boat->direction; iv = &graphics->boatAnims[boat->subID]->ourImages; } if(themp && !themp->isStanding) //hero is moving { size_t gg; for(gg=0; gg<iv->size(); ++gg) { if((*iv)[gg].groupNumber==getHeroFrameNum(dir, true)) { tb = (*iv)[gg+heroAnim%IMGVAL].bitmap; break; } } CSDL_Ext::blit8bppAlphaTo24bpp(tb,&pp,extSurf,&sr2); //printing flag pp.y+=IMGVAL*2-32; sr2.y-=16; CSDL_Ext::blitSurface((graphics->*flg)[color.getNum()]->ourImages[gg+heroAnim%IMGVAL+35].bitmap, &pp, extSurf, &sr2); } else //hero / boat stands still { size_t gg; for(gg=0; gg < iv->size(); ++gg) { if((*iv)[gg].groupNumber==getHeroFrameNum(dir, false)) { tb = (*iv)[gg].bitmap; break; } } CSDL_Ext::blit8bppAlphaTo24bpp(tb,&pp,extSurf,&sr2); //printing flag if(flg && obj->pos.x == top_tile.x + bx && obj->pos.y == top_tile.y + by) { SDL_Rect bufr = sr2; bufr.x-=2*32; bufr.y-=1*32; bufr.h = 64; bufr.w = 96; if(bufr.x-extRect->x>-64) CSDL_Ext::blitSurface((graphics->*flg)[color.getNum()]->ourImages[getHeroFrameNum(dir, false) *8+(heroAnim/4)%IMGVAL].bitmap, nullptr, extSurf, &bufr); } } } else //blit normal object { const std::vector<Cimage> &ourImages = graphics->getDef(obj)->ourImages; SDL_Surface *bitmap = ourImages[(anim+getPhaseShift(obj))%ourImages.size()].bitmap; //setting appropriate flag color if(color < PlayerColor::PLAYER_LIMIT || color==PlayerColor::NEUTRAL) CSDL_Ext::setPlayerColor(bitmap, color); CSDL_Ext::blit8bppAlphaTo24bpp(bitmap,&pp,extSurf,&sr2); } } //objects blitted //X sign if(puzzleMode) { if(bx == grailPosRel.x && by == grailPosRel.y) { CSDL_Ext::blit8bppAlphaTo24bpp(graphics->heroMoveArrows->ourImages[0].bitmap, nullptr, extSurf, &sr); } } }
std::string ArmatureExporter::add_inv_bind_mats_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id) { std::string source_id = controller_id + BIND_POSES_SOURCE_ID_SUFFIX; int totjoint = 0; for (bDeformGroup *def = (bDeformGroup*)defbase->first; def; def = def->next) { if (is_bone_defgroup(ob_arm, def)) totjoint++; } COLLADASW::FloatSourceF source(mSW); source.setId(source_id); source.setArrayId(source_id + ARRAY_ID_SUFFIX); source.setAccessorCount(totjoint); //BLI_countlist(defbase)); source.setAccessorStride(16); source.setParameterTypeName(&COLLADASW::CSWC::CSW_VALUE_TYPE_FLOAT4x4); COLLADASW::SourceBase::ParameterNameList ¶m = source.getParameterNameList(); param.push_back("TRANSFORM"); source.prepareToAppendValues(); bPose *pose = ob_arm->pose; bArmature *arm = (bArmature*)ob_arm->data; int flag = arm->flag; // put armature in rest position if (!(arm->flag & ARM_RESTPOS)) { arm->flag |= ARM_RESTPOS; where_is_pose(scene, ob_arm); } for (bDeformGroup *def = (bDeformGroup*)defbase->first; def; def = def->next) { if (is_bone_defgroup(ob_arm, def)) { bPoseChannel *pchan = get_pose_channel(pose, def->name); float mat[4][4]; float world[4][4]; float inv_bind_mat[4][4]; // SECOND_LIFE_COMPATIBILITY if(export_settings->second_life) { // Only translations, no rotation vs armature float temp[4][4]; unit_m4(temp); copy_v3_v3(temp[3], pchan->bone->arm_mat[3]); mult_m4_m4m4(world, ob_arm->obmat, temp); } else { // make world-space matrix, arm_mat is armature-space mult_m4_m4m4(world, ob_arm->obmat, pchan->bone->arm_mat); } invert_m4_m4(mat, world); converter.mat4_to_dae(inv_bind_mat, mat); source.appendValues(inv_bind_mat); } } // back from rest positon if (!(flag & ARM_RESTPOS)) { arm->flag = flag; where_is_pose(scene, ob_arm); } source.finish(); return source_id; }
/*! Returns \c true if the source effectively is a pixmap, e.g., a QGraphicsPixmapItem. This function is useful for optimization purposes. For instance, there's no point in drawing the source in device coordinates to avoid pixmap scaling if this function returns \c true - the source pixmap will be scaled anyways. */ bool QGraphicsEffect::sourceIsPixmap() const { return source() ? source()->isPixmap() : false; }
GLuint CompileShader(const DKString& implement, DKShader::Type t, DKString& err) { if (implement.Length() == 0) { err = L"No implementation."; return 0; } if (t != DKShader::TypeFragmentShader && t != DKShader::TypeGeometryShader && t != DKShader::TypeVertexShader) { err = L"Unknown shader type"; return 0; } DKStringU8 source(implement); if (source.Bytes() == 0) { err = L"Failed to convert source encoding (UTF-8)"; return 0; } GLuint hShader = 0; if (t == DKShader::TypeVertexShader) // vertex shader { hShader = glCreateShader(GL_VERTEX_SHADER); } else if (t == DKShader::TypeFragmentShader) // fragment shader (pixel shader) { hShader = glCreateShader(GL_FRAGMENT_SHADER); } else { #ifdef GL_GEOMETRY_SHADER hShader = glCreateShader(GL_GEOMETRY_SHADER); #else err = L"Geometry shader not supported in this implementation."; DKLog("Error: Geometry shader not supported in this implementation.\n"); return 0; #endif } if (hShader == 0) { err = L"Failed to create shader object"; return 0; } const char* src = (const char*)source; glShaderSource(hShader, 1, &src, NULL); glCompileShader(hShader); // retrieve compiler log int nLogLen = 0; glGetShaderiv(hShader, GL_INFO_LOG_LENGTH, &nLogLen); if (nLogLen > 1) { char *pLog = (char*)DKMemoryHeapAlloc(nLogLen); int nCharsWritten = 0; glGetShaderInfoLog(hShader, nLogLen, &nCharsWritten, pLog); err = pLog; DKMemoryHeapFree(pLog); } //////////////////////////////////////////////////////////////////////////////// // get compilation result. int result = 0; glGetShaderiv(hShader, GL_COMPILE_STATUS, &result); glFlush(); if (result) { return hShader; } // compile error. if (err.Length() == 0) err = L"Failed to compile shader."; glDeleteShader(hShader); return 0; }
void CollationIteratorTest::TestClearBuffers(/* char* par */) { UErrorCode status = U_ZERO_ERROR; RuleBasedCollator *c = new RuleBasedCollator((UnicodeString)"&a < b < c & ab = d", status); if (c == NULL || U_FAILURE(status)) { errln("Couldn't create a RuleBasedCollator."); delete c; return; } UnicodeString source("abcd"); CollationElementIterator *i = c->createCollationElementIterator(source); int32_t e0 = i->next(status); // save the first collation element if (U_FAILURE(status)) { errln("call to i->next() failed. err=%s", u_errorName(status)); } else { i->setOffset(3, status); // go to the expanding character if (U_FAILURE(status)) { errln("call to i->setOffset(3) failed. err=%s", u_errorName(status)); } else { i->next(status); // but only use up half of it if (U_FAILURE(status)) { errln("call to i->next() failed. err=%s", u_errorName(status)); } else { i->setOffset(0, status); // go back to the beginning if (U_FAILURE(status)) { errln("call to i->setOffset(0) failed. err=%s", u_errorName(status)); } else { int32_t e = i->next(status); // and get this one again if (U_FAILURE(status)) { errln("call to i->next() failed. err=%s", u_errorName(status)); } else if (e != e0) { errln("got 0x%X, expected 0x%X", e, e0); } } } } } delete i; delete c; }
void compute_adjacencies_with_polygon (const Matrix &X, const Vector &weights, const Matrix &polygon, std::vector<std::vector<Segment>> &adjedges, std::vector<std::vector<size_t>> &adjverts) { auto rt = MA::details::make_regular_triangulation(X,weights); int Np = polygon.rows(); int Nv = X.rows(); adjedges.assign(Nv, std::vector<Segment>()); adjverts.assign(Nv, std::vector<size_t>()); for (int p = 0; p < Np; ++p) { int pnext = (p + 1) % Np; //int pprev = (p + Np - 1) % Np; Point source(polygon(p,0), polygon(p,1)); Point target(polygon(pnext,0), polygon(pnext,1)); auto u = rt.nearest_power_vertex(source); auto v = rt.nearest_power_vertex(target); adjverts[u->info()].push_back(p); Point pointprev = source; auto uprev = u; while (u != v) { // find next vertex intersecting with segment auto c = rt.incident_edges(u), done(c); do { if (rt.is_infinite(c)) continue; // we do not want to go back to the previous vertex! auto unext = (c->first)->vertex(rt.ccw(c->second)); if (unext == uprev) continue; // check whether dual edge (which can be a ray, a line // or a segment) intersects with the constraint Point point; if (!edge_dual_and_segment_isect(rt.dual(c), Segment(source,target), point)) continue; adjedges[u->info()].push_back(Segment(pointprev,point)); pointprev = point; uprev = u; u = unext; break; } while(++c != done); } adjverts[v->info()].push_back(pnext); adjedges[v->info()].push_back(Segment(pointprev, target)); } }
int subCmd_logSend(int argc, char **argv, qi::ApplicationSession& app) { po::options_description desc("Usage: qicli log-send <message>"); desc.add_options() ("help,h", "Print this help message and exit") ("verbose,v", "Set sent message verbosity to verbose.") ("debug,d", "Set sent message verbosity to debug.") ("level,l", po::value<int>()->default_value(4), "Change the log minimum level: [0-6] (default:4). This option accepts the same arguments' format than --qi-log-level.") ("category,c", po::value<std::string>(), "Message's category (default: \"qicli.qilog.logsend\").") ("message,m", po::value<std::string>(), "Message to send.") ; po::positional_options_description positionalOptions; positionalOptions.add("message", -1); po::variables_map vm; if (!poDefault(po::command_line_parser(argc, argv) .options(desc).positional(positionalOptions), vm, desc)) return 1; qiLogVerbose() << "Connecting to service directory"; app.startSession(); qi::SessionPtr s = app.session(); qiLogVerbose() << "Resolving services"; qi::AnyObject logger = s->service("LogManager"); qi::os::timeval tv(qi::SystemClock::now()); std::string source(__FILE__); source += ':'; source += __FUNCTION__; source += ':'; source += boost::lexical_cast<std::string>(__LINE__); int level = 4; if (vm.count("level")) { level = vm["level"].as<int>(); if (level > 6) level = 6; else if (level <= 0) level = 0; } if (vm.count("verbose")) level = 5; if (vm.count("debug")) level = 6; std::string category = "qicli.qilog.logsend"; if (vm.count("category")) category = vm["category"].as<std::string>(); std::string location = qi::os::getMachineId() + ":" + boost::lexical_cast<std::string>(qi::os::getpid());; std::string message = ""; if (vm.count("message")) message = vm["message"].as<std::string>(); // timestamp qi::AnyReferenceVector timeVectRef; timeVectRef.push_back(qi::AnyReference::from(tv.tv_sec)); timeVectRef.push_back(qi::AnyReference::from(tv.tv_usec)); qi::AnyValue timeVal = qi::AnyValue::makeTuple(timeVectRef); qi::AnyReferenceVector msgVectRef; msgVectRef.push_back(qi::AnyReference::from(source)); msgVectRef.push_back(qi::AnyReference::from(level)); msgVectRef.push_back(timeVal.asReference()); //timestamp msgVectRef.push_back(qi::AnyReference::from(category)); msgVectRef.push_back(qi::AnyReference::from(location)); msgVectRef.push_back(qi::AnyReference::from(message)); msgVectRef.push_back(qi::AnyReference::from(0)); std::vector<qi::AnyValue> msgs; msgs.push_back(qi::AnyValue::makeTuple(msgVectRef)); logger.call<void>("log", qi::AnyValue::from(msgs)); logger.reset(); return 0; }
void mitk::CompressedImageContainer::SetImage( Image* image ) { for (auto iter = m_ByteBuffers.begin(); iter != m_ByteBuffers.end(); ++iter) { free( iter->first ); } m_ByteBuffers.clear(); // Compress diff image using zlib (will be restored on demand) // determine memory size occupied by voxel data m_ImageDimension = image->GetDimension(); m_ImageDimensions.clear(); m_PixelType = new mitk::PixelType( image->GetPixelType()); m_OneTimeStepImageSizeInBytes = m_PixelType->GetSize(); // bits per element divided by 8 for (unsigned int i = 0; i < m_ImageDimension; ++i) { unsigned int currentImageDimension = image->GetDimension(i); m_ImageDimensions.push_back( currentImageDimension ); if (i < 3) { m_OneTimeStepImageSizeInBytes *= currentImageDimension; // only the 3D memory size } } m_ImageGeometry = image->GetGeometry(); m_NumberOfTimeSteps = 1; if (m_ImageDimension > 3) { m_NumberOfTimeSteps = image->GetDimension(3); } for (unsigned int timestep = 0; timestep < m_NumberOfTimeSteps; ++timestep) { // allocate a buffer as specified by zlib unsigned long bufferSize = m_OneTimeStepImageSizeInBytes + static_cast<unsigned long>(m_OneTimeStepImageSizeInBytes * 0.2) + 12; unsigned char* byteBuffer = (unsigned char*) malloc(bufferSize); if (itk::Object::GetDebug()) { // compress image here into a buffer MITK_INFO << "Using ZLib version: '" << zlibVersion() << "'" << std::endl << "Attempting to compress " << m_OneTimeStepImageSizeInBytes << " image bytes into a buffer of size " << bufferSize << std::endl; } ImageReadAccessor imgAcc(image, image->GetVolumeData(timestep)); ::Bytef* dest(byteBuffer); ::uLongf destLen(bufferSize); ::Bytef* source( (unsigned char*) imgAcc.GetData() ); ::uLongf sourceLen( m_OneTimeStepImageSizeInBytes ); int zlibRetVal = ::compress(dest, &destLen, source, sourceLen); if (itk::Object::GetDebug()) { if (zlibRetVal == Z_OK) { MITK_INFO << "Success, using " << destLen << " bytes of the buffer (ratio " << ((double)destLen / (double)sourceLen) << ")" << std::endl; } else { switch ( zlibRetVal ) { case Z_MEM_ERROR: MITK_ERROR << "not enough memory" << std::endl; break; case Z_BUF_ERROR: MITK_ERROR << "output buffer too small" << std::endl; break; default: MITK_ERROR << "other, unspecified error" << std::endl; break; } } } // only use the neccessary amount of memory, realloc the buffer! byteBuffer = (unsigned char*) realloc( byteBuffer, destLen ); bufferSize = destLen; //MITK_INFO << "Using " << bufferSize << " bytes to store compressed image (" << destLen << " needed)" << std::endl; m_ByteBuffers.push_back( std::pair<unsigned char*, unsigned long>( byteBuffer, bufferSize ) ); } }
Shader::Shader( ShaderType::shader_type_t shader, const std::string& code ):Shader(shader) { source( code ); compile(); }
shader::shader( type t, const std::string &code ) : shader( t ) { source( code ); compile(); }
PhotometricStereo::PhotometricStereo(int width, int height, int imageIntensity) : width(width), height(height), minIntensity(imageIntensity) { /* setup pre calibrated global light sources */ cv::Mat lightSrcs = (cv::Mat_<float>(8,3) << -0.2222, 0.0074, 0.9749, -0.1629, -0.1407, 0.9765, 0.0370, -0.2000, 0.9790, 0.1481, -0.1407, 0.9789, 0.2222, 0.0296, 0.9745, 0.1333, 0.1481, 0.9799, -0.0222, 0.2000, 0.9795, -0.1555, 0.1481, 0.9766); cv::invert(lightSrcs, lightSrcsInv, cv::DECOMP_SVD); /* initialize non-changing x,y coords of 3d model */ XCoords = cv::Mat(height, width, CV_32F, cv::Scalar::all(0)); YCoords = cv::Mat(height, width, CV_32F, cv::Scalar::all(0)); for (int y=0; y<width; y++) { for (int x=0; x<height; x++) { XCoords.at<float>(x, y) = x; YCoords.at<float>(x, y) = y; } } /* adjustable ps parameters */ maxpq = 10.0f; lambda = 0.4f; mu = 0.4f; unsharpScaleFactor = 0.0f; /* counter indicating current active LED */ imgIdx = START_LED; /* vector for storing (8) ps images, initially black */ for (int i=0; i<8; i++) { cv::Mat tmp(height, width, CV_8UC1); psImages.push_back(tmp); } /* initialize OpenCL object and context */ std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); cl_context_properties props[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0}; /* try using CPU, since data is large, computations simple and BUS data transfer is slow */ cl_int clError; context = cl::Context(CL_DEVICE_TYPE_CPU, props, NULL, NULL, &clError); if (clError != CL_SUCCESS) { /* fallback to gpu device */ context = cl::Context(CL_DEVICE_TYPE_GPU, props, NULL, NULL, &clError); } devices = context.getInfo<CL_CONTEXT_DEVICES>(); /* create command queue for OpenCL, using first device available */ queue = cl::CommandQueue(context, devices[0], 0, &error); /* load kernel source */ int pl; std::stringstream s; s << PATH_KERNELS << "ps.cl"; std::string kernelSource = s.str(); char *programCode = OCLUtils::fileContents(kernelSource.data(), &pl); cl::Program::Sources source(1, std::make_pair(programCode, pl)); program = cl::Program(context, source); /* build program */ program.build(devices); std::cout << "Build Status: " << program.getBuildInfo<CL_PROGRAM_BUILD_STATUS>(devices[0]) << std::endl; std::cout << "Build Log:\t " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]) << std::endl; /* initialize kernels from program */ calcNormKernel = cl::Kernel(program, "calcNormals", &error); integKernel = cl::Kernel(program, "integrate", &error); updateNormKernel = cl::Kernel(program, "updateNormals", &error); }
void write_graphviz_subgraph (std::ostream& out, const subgraph<Graph_>& g, RandomAccessIterator vertex_marker, RandomAccessIterator edge_marker) { typedef subgraph<Graph_> Graph; typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex; typedef typename boost::graph_traits<Graph>::directed_category cat_type; typedef graphviz_io_traits<cat_type> Traits; typedef typename graph_property<Graph, graph_name_t>::type NameType; const NameType& g_name = get_property(g, graph_name); if ( g.is_root() ) out << Traits::name() ; else out << "subgraph"; out << " " << g_name << " {" << std::endl; typename Graph::const_children_iterator i_child, j_child; //print graph/node/edge attributes #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 typedef typename graph_property<Graph, graph_graph_attribute_t>::type GAttrMap; typedef typename graph_property<Graph, graph_vertex_attribute_t>::type NAttrMap; typedef typename graph_property<Graph, graph_edge_attribute_t>::type EAttrMap; GAttrMap gam = get_property(g, graph_graph_attribute); NAttrMap nam = get_property(g, graph_vertex_attribute); EAttrMap eam = get_property(g, graph_edge_attribute); graph_attributes_writer<GAttrMap, NAttrMap, EAttrMap> writer(gam, nam, eam); writer(out); #else make_graph_attributes_writer(g)(out); #endif //print subgraph for ( boost::tie(i_child,j_child) = g.children(); i_child != j_child; ++i_child ) write_graphviz_subgraph(out, *i_child, vertex_marker, edge_marker); // Print out vertices and edges not in the subgraphs. typename boost::graph_traits<Graph>::vertex_iterator i, end; typename boost::graph_traits<Graph>::edge_iterator ei, edge_end; typename property_map<Graph, vertex_index_t>::const_type indexmap = get(vertex_index, g.root()); for(boost::tie(i,end) = boost::vertices(g); i != end; ++i) { Vertex v = g.local_to_global(*i); int pos = get(indexmap, v); if ( vertex_marker[pos] ) { vertex_marker[pos] = false; out << v; #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 typedef typename property_map<Graph, vertex_attribute_t>::const_type VertexAttributeMap; attributes_writer<VertexAttributeMap> vawriter(get(vertex_attribute, g.root())); vawriter(out, v); #else make_vertex_attributes_writer(g.root())(out, v); #endif out << ";" << std::endl; } } for (boost::tie(ei, edge_end) = edges(g); ei != edge_end; ++ei) { Vertex u = g.local_to_global(source(*ei,g)), v = g.local_to_global(target(*ei, g)); int pos = get(get(edge_index, g.root()), g.local_to_global(*ei)); if ( edge_marker[pos] ) { edge_marker[pos] = false; out << u << " " << Traits::delimiter() << " " << v; #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 typedef typename property_map<Graph, edge_attribute_t>::const_type EdgeAttributeMap; attributes_writer<EdgeAttributeMap> eawriter(get(edge_attribute, g)); eawriter(out, *ei); #else make_edge_attributes_writer(g)(out, *ei); //print edge properties #endif out << ";" << std::endl; } } out << "}" << std::endl; }
void toremote(char *targ, int argc, char **argv) { char *bp, *host, *src, *suser, *thost, *tuser, *arg; arglist alist; int i; u_int j; memset(&alist, '\0', sizeof(alist)); alist.list = NULL; *targ++ = 0; if (*targ == 0) targ = "."; arg = xstrdup(argv[argc - 1]); if ((thost = strrchr(arg, '@'))) { /* user@host */ *thost++ = 0; tuser = arg; if (*tuser == '\0') tuser = NULL; } else { thost = arg; tuser = NULL; } if (tuser != NULL && !okname(tuser)) { free(arg); return; } for (i = 0; i < argc - 1; i++) { src = colon(argv[i]); if (src && throughlocal) { /* extended remote to remote */ *src++ = 0; if (*src == 0) src = "."; host = strrchr(argv[i], '@'); if (host) { *host++ = 0; host = cleanhostname(host); suser = argv[i]; if (*suser == '\0') suser = pwd->pw_name; else if (!okname(suser)) continue; } else { host = cleanhostname(argv[i]); suser = NULL; } xasprintf(&bp, "%s -f %s%s", cmd, *src == '-' ? "-- " : "", src); if (do_cmd(host, suser, bp, &remin, &remout) < 0) exit(1); free(bp); host = cleanhostname(thost); xasprintf(&bp, "%s -t %s%s", cmd, *targ == '-' ? "-- " : "", targ); if (do_cmd2(host, tuser, bp, remin, remout) < 0) exit(1); free(bp); (void) close(remin); (void) close(remout); remin = remout = -1; } else if (src) { /* standard remote to remote */ freeargs(&alist); addargs(&alist, "%s", ssh_program); addargs(&alist, "-x"); addargs(&alist, "-oClearAllForwardings=yes"); addargs(&alist, "-n"); for (j = 0; j < remote_remote_args.num; j++) { addargs(&alist, "%s", remote_remote_args.list[j]); } *src++ = 0; if (*src == 0) src = "."; host = strrchr(argv[i], '@'); if (host) { *host++ = 0; host = cleanhostname(host); suser = argv[i]; if (*suser == '\0') suser = pwd->pw_name; else if (!okname(suser)) continue; addargs(&alist, "-l"); addargs(&alist, "%s", suser); } else { host = cleanhostname(argv[i]); } addargs(&alist, "--"); addargs(&alist, "%s", host); addargs(&alist, "%s", cmd); addargs(&alist, "%s", src); addargs(&alist, "%s%s%s:%s", tuser ? tuser : "", tuser ? "@" : "", thost, targ); if (do_local_cmd(&alist) != 0) errs = 1; } else { /* local to remote */ if (remin == -1) { xasprintf(&bp, "%s -t %s%s", cmd, *targ == '-' ? "-- " : "", targ); host = cleanhostname(thost); if (do_cmd(host, tuser, bp, &remin, &remout) < 0) exit(1); if (response() < 0) exit(1); free(bp); } source(1, argv + i); } } free(arg); }
bool QgsMapLayer::writeLayerXML( QDomElement& layerElement, QDomDocument& document ) { // use scale dependent visibility flag layerElement.setAttribute( "hasScaleBasedVisibilityFlag", hasScaleBasedVisibility() ? 1 : 0 ); layerElement.setAttribute( "minimumScale", QString::number( minimumScale() ) ); layerElement.setAttribute( "maximumScale", QString::number( maximumScale() ) ); // ID QDomElement layerId = document.createElement( "id" ); QDomText layerIdText = document.createTextNode( id() ); layerId.appendChild( layerIdText ); layerElement.appendChild( layerId ); // data source QDomElement dataSource = document.createElement( "datasource" ); QString src = source(); QgsVectorLayer *vlayer = qobject_cast<QgsVectorLayer *>( this ); // TODO: what about postgres, mysql and others, they should not go through writePath() if ( vlayer && vlayer->providerType() == "spatialite" ) { QgsDataSourceURI uri( src ); QString database = QgsProject::instance()->writePath( uri.database() ); uri.setConnection( uri.host(), uri.port(), database, uri.username(), uri.password() ); src = uri.uri(); } else if ( vlayer && vlayer->providerType() == "ogr" ) { QStringList theURIParts = src.split( "|" ); theURIParts[0] = QgsProject::instance()->writePath( theURIParts[0] ); src = theURIParts.join( "|" ); } else if ( vlayer && vlayer->providerType() == "delimitedtext" ) { QUrl urlSource = QUrl::fromEncoded( src.toAscii() ); QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->writePath( urlSource.toLocalFile() ) ); urlDest.setQueryItems( urlSource.queryItems() ); src = QString::fromAscii( urlDest.toEncoded() ); } else { src = QgsProject::instance()->writePath( src ); } QDomText dataSourceText = document.createTextNode( src ); dataSource.appendChild( dataSourceText ); layerElement.appendChild( dataSource ); // layer name QDomElement layerName = document.createElement( "layername" ); QDomText layerNameText = document.createTextNode( originalName() ); layerName.appendChild( layerNameText ); // layer title QDomElement layerTitle = document.createElement( "title" ) ; QDomText layerTitleText = document.createTextNode( title() ); layerTitle.appendChild( layerTitleText ); // layer abstract QDomElement layerAbstract = document.createElement( "abstract" ); QDomText layerAbstractText = document.createTextNode( abstract() ); layerAbstract.appendChild( layerAbstractText ); layerElement.appendChild( layerName ); layerElement.appendChild( layerTitle ); layerElement.appendChild( layerAbstract ); // layer keyword list QStringList keywordStringList = keywordList().split( "," ); if ( keywordStringList.size() > 0 ) { QDomElement layerKeywordList = document.createElement( "keywordList" ); for ( int i = 0; i < keywordStringList.size(); ++i ) { QDomElement layerKeywordValue = document.createElement( "value" ); QDomText layerKeywordText = document.createTextNode( keywordStringList.at( i ).trimmed() ); layerKeywordValue.appendChild( layerKeywordText ); layerKeywordList.appendChild( layerKeywordValue ); } layerElement.appendChild( layerKeywordList ); } // layer metadataUrl QString aDataUrl = dataUrl(); if ( !aDataUrl.isEmpty() ) { QDomElement layerDataUrl = document.createElement( "dataUrl" ) ; QDomText layerDataUrlText = document.createTextNode( aDataUrl ); layerDataUrl.appendChild( layerDataUrlText ); layerDataUrl.setAttribute( "format", dataUrlFormat() ); layerElement.appendChild( layerDataUrl ); } // layer attribution QString aAttribution = attribution(); if ( !aAttribution.isEmpty() ) { QDomElement layerAttribution = document.createElement( "attribution" ) ; QDomText layerAttributionText = document.createTextNode( aAttribution ); layerAttribution.appendChild( layerAttributionText ); layerAttribution.setAttribute( "href", attributionUrl() ); layerElement.appendChild( layerAttribution ); } // layer metadataUrl QString aMetadataUrl = metadataUrl(); if ( !aMetadataUrl.isEmpty() ) { QDomElement layerMetadataUrl = document.createElement( "metadataUrl" ) ; QDomText layerMetadataUrlText = document.createTextNode( aMetadataUrl ); layerMetadataUrl.appendChild( layerMetadataUrlText ); layerMetadataUrl.setAttribute( "type", metadataUrlType() ); layerMetadataUrl.setAttribute( "format", metadataUrlFormat() ); layerElement.appendChild( layerMetadataUrl ); } // timestamp if supported if ( timestamp() > QDateTime() ) { QDomElement stamp = document.createElement( "timestamp" ); QDomText stampText = document.createTextNode( timestamp().toString( Qt::ISODate ) ); stamp.appendChild( stampText ); layerElement.appendChild( stamp ); } layerElement.appendChild( layerName ); // zorder // This is no longer stored in the project file. It is superfluous since the layers // are written and read in the proper order. // spatial reference system id QDomElement mySrsElement = document.createElement( "srs" ); mCRS->writeXML( mySrsElement, document ); layerElement.appendChild( mySrsElement ); #if 0 // <transparencyLevelInt> QDomElement transparencyLevelIntElement = document.createElement( "transparencyLevelInt" ); QDomText transparencyLevelIntText = document.createTextNode( QString::number( getTransparency() ) ); transparencyLevelIntElement.appendChild( transparencyLevelIntText ); maplayer.appendChild( transparencyLevelIntElement ); #endif // now append layer node to map layer node writeCustomProperties( layerElement, document ); return writeXml( layerElement, document ); } // bool QgsMapLayer::writeXML
Weight weight( const LinkIndex& j) const { return weight( source(j), target(j) ); }
OCLRendererThread::OCLRendererThread(const size_t threadIndex, OCLRenderer *renderer, cl::Device device) : index(threadIndex), renderer(renderer), dev(device), usedDeviceMemory(0) { const GameLevel &gameLevel(*(renderer->gameLevel)); const unsigned int width = gameLevel.gameConfig->GetScreenWidth(); const unsigned int height = gameLevel.gameConfig->GetScreenHeight(); const CompiledScene &compiledScene(*(renderer->compiledScene)); if (renderer->renderThread.size() > 1) cpuFrameBuffer = new FrameBuffer(width, height); else cpuFrameBuffer = NULL; //-------------------------------------------------------------------------- // OpenCL setup //-------------------------------------------------------------------------- // Allocate a context with the selected device VECTOR_CLASS<cl::Device> devices; devices.push_back(dev); cl::Platform platform = dev.getInfo<CL_DEVICE_PLATFORM>(); // The first thread uses OpenCL/OpenGL interoperability if (index == 0) { #if defined (__APPLE__) CGLContextObj kCGLContext = CGLGetCurrentContext(); CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext); cl_context_properties cps[] = { CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE, (cl_context_properties)kCGLShareGroup, 0 }; #else #ifdef WIN32 cl_context_properties cps[] = { CL_GL_CONTEXT_KHR, (intptr_t)wglGetCurrentContext(), CL_WGL_HDC_KHR, (intptr_t)wglGetCurrentDC(), CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 }; #else cl_context_properties cps[] = { CL_GL_CONTEXT_KHR, (intptr_t)glXGetCurrentContext(), CL_GLX_DISPLAY_KHR, (intptr_t)glXGetCurrentDisplay(), CL_CONTEXT_PLATFORM, (cl_context_properties)platform(), 0 }; #endif #endif ctx = new cl::Context(devices, cps); } else ctx = new cl::Context(devices); // Allocate the queue for this device cmdQueue = new cl::CommandQueue(*ctx, dev); //-------------------------------------------------------------------------- // Allocate the buffers //-------------------------------------------------------------------------- passFrameBuffer = NULL; tmpFrameBuffer = NULL; frameBuffer = NULL; toneMapFrameBuffer = NULL; bvhBuffer = NULL; gpuTaskBuffer = NULL; cameraBuffer = NULL; infiniteLightBuffer = NULL; matBuffer = NULL; matIndexBuffer = NULL; texMapBuffer = NULL; texMapRGBBuffer = NULL; texMapInstanceBuffer = NULL; bumpMapInstanceBuffer = NULL; AllocOCLBufferRW(&passFrameBuffer, sizeof(Pixel) * width * height, "Pass FrameBuffer"); AllocOCLBufferRW(&tmpFrameBuffer, sizeof(Pixel) * width * height, "Temporary FrameBuffer"); if (index == 0) { AllocOCLBufferRW(&frameBuffer, sizeof(Pixel) * width * height, "FrameBuffer"); AllocOCLBufferRW(&toneMapFrameBuffer, sizeof(Pixel) * width * height, "ToneMap FrameBuffer"); } AllocOCLBufferRW(&gpuTaskBuffer, sizeof(ocl_kernels::GPUTask) * width * height, "GPUTask"); AllocOCLBufferRO(&cameraBuffer, sizeof(compiledscene::Camera), "Camera"); AllocOCLBufferRO(&infiniteLightBuffer, (void *)(gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetPixels()), sizeof(Spectrum) * gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetWidth() * gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetHeight(), "Inifinite Light"); AllocOCLBufferRO(&matBuffer, (void *)(&compiledScene.mats[0]), sizeof(compiledscene::Material) * compiledScene.mats.size(), "Materials"); AllocOCLBufferRO(&matIndexBuffer, (void *)(&compiledScene.sphereMats[0]), sizeof(unsigned int) * compiledScene.sphereMats.size(), "Material Indices"); if (compiledScene.texMaps.size() > 0) { AllocOCLBufferRO(&texMapBuffer, (void *)(&compiledScene.texMaps[0]), sizeof(compiledscene::TexMap) * compiledScene.texMaps.size(), "Texture Maps"); AllocOCLBufferRO(&texMapRGBBuffer, (void *)(compiledScene.rgbTexMem), sizeof(Spectrum) * compiledScene.totRGBTexMem, "Texture Map Images"); AllocOCLBufferRO(&texMapInstanceBuffer, (void *)(&compiledScene.sphereTexs[0]), sizeof(compiledscene::TexMapInstance) * compiledScene.sphereTexs.size(), "Texture Map Instances"); if (compiledScene.sphereBumps.size() > 0) AllocOCLBufferRO(&bumpMapInstanceBuffer, (void *)(&compiledScene.sphereBumps[0]), sizeof(compiledscene::BumpMapInstance) * compiledScene.sphereBumps.size(), "Bump Map Instances"); } SFERA_LOG("[OCLRenderer] Total OpenCL device memory used: " << fixed << setprecision(2) << usedDeviceMemory / (1024 * 1024) << "Mbytes"); if (index == 0) { //-------------------------------------------------------------------------- // Create pixel buffer object for display //-------------------------------------------------------------------------- glGenBuffersARB(1, &pbo); glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo); glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, width * height * sizeof(GLubyte) * 4, 0, GL_STREAM_DRAW_ARB); glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0); pboBuff = new cl::BufferGL(*ctx, CL_MEM_READ_WRITE, pbo); } //-------------------------------------------------------------------------- // Compile the kernel source //-------------------------------------------------------------------------- // Set #define symbols stringstream ss; ss.precision(6); ss << scientific << " -D PARAM_SCREEN_WIDTH=" << width << " -D PARAM_SCREEN_HEIGHT=" << height << " -D PARAM_SCREEN_SAMPLEPERPASS="******" -D PARAM_RAY_EPSILON=" << EPSILON << "f" << " -D PARAM_MAX_DIFFUSE_BOUNCE=" << gameLevel.maxPathDiffuseBounces << " -D PARAM_MAX_SPECULARGLOSSY_BOUNCE=" << gameLevel.maxPathSpecularGlossyBounces << " -D PARAM_IL_SHIFT_U=" << gameLevel.scene->infiniteLight->GetShiftU() << "f" << " -D PARAM_IL_SHIFT_V=" << gameLevel.scene->infiniteLight->GetShiftV() << "f" << " -D PARAM_IL_GAIN_R=" << gameLevel.scene->infiniteLight->GetGain().r << "f" << " -D PARAM_IL_GAIN_G=" << gameLevel.scene->infiniteLight->GetGain().g << "f" << " -D PARAM_IL_GAIN_B=" << gameLevel.scene->infiniteLight->GetGain().b << "f" << " -D PARAM_IL_MAP_WIDTH=" << gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetWidth() << " -D PARAM_IL_MAP_HEIGHT=" << gameLevel.scene->infiniteLight->GetTexture()->GetTexMap()->GetHeight() << " -D PARAM_GAMMA=" << gameLevel.toneMap->GetGamma() << "f" << " -D PARAM_MEM_TYPE=" << gameLevel.gameConfig->GetOpenCLMemType(); if (compiledScene.enable_MAT_MATTE) ss << " -D PARAM_ENABLE_MAT_MATTE"; if (compiledScene.enable_MAT_MIRROR) ss << " -D PARAM_ENABLE_MAT_MIRROR"; if (compiledScene.enable_MAT_GLASS) ss << " -D PARAM_ENABLE_MAT_GLASS"; if (compiledScene.enable_MAT_METAL) ss << " -D PARAM_ENABLE_MAT_METAL"; if (compiledScene.enable_MAT_ALLOY) ss << " -D PARAM_ENABLE_MAT_ALLOY"; if (texMapBuffer) { ss << " -D PARAM_HAS_TEXTUREMAPS"; if (compiledScene.sphereBumps.size() > 0) ss << " -D PARAM_HAS_BUMPMAPS"; } switch (gameLevel.toneMap->GetType()) { case TONEMAP_REINHARD02: ss << " -D PARAM_TM_LINEAR_SCALE=1.0f"; break; case TONEMAP_LINEAR: { LinearToneMap *tm = (LinearToneMap *)gameLevel.toneMap; ss << " -D PARAM_TM_LINEAR_SCALE=" << tm->scale << "f"; break; } default: assert (false); } #if defined(__APPLE__) ss << " -D __APPLE__"; #endif SFERA_LOG("[OCLRenderer] Defined symbols: " << ss.str()); SFERA_LOG("[OCLRenderer] Compiling kernels"); cl::Program::Sources source(1, std::make_pair(KernelSource_kernel_core.c_str(), KernelSource_kernel_core.length())); cl::Program program = cl::Program(*ctx, source); try { VECTOR_CLASS<cl::Device> buildDevice; buildDevice.push_back(dev); program.build(buildDevice, ss.str().c_str()); } catch (cl::Error err) { cl::STRING_CLASS strError = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(dev); SFERA_LOG("[OCLRenderer] Kernel compilation error:\n" << strError.c_str()); throw err; } kernelInit = new cl::Kernel(program, "Init"); kernelInit->setArg(0, *gpuTaskBuffer); cmdQueue->enqueueNDRangeKernel(*kernelInit, cl::NullRange, cl::NDRange(RoundUp<unsigned int>(width * height, WORKGROUP_SIZE)), cl::NDRange(WORKGROUP_SIZE)); kernelInitFrameBuffer = new cl::Kernel(program, "InitFB"); if (index == 0) { kernelInitFrameBuffer->setArg(0, *frameBuffer); cmdQueue->enqueueNDRangeKernel(*kernelInitFrameBuffer, cl::NullRange, cl::NDRange(RoundUp<unsigned int>(width * height, WORKGROUP_SIZE)), cl::NDRange(WORKGROUP_SIZE)); } kernelInitFrameBuffer->setArg(0, *passFrameBuffer); kernelPathTracing = new cl::Kernel(program, "PathTracing"); unsigned int argIndex = 0; kernelPathTracing->setArg(argIndex++, *gpuTaskBuffer); argIndex++; kernelPathTracing->setArg(argIndex++, *cameraBuffer); kernelPathTracing->setArg(argIndex++, *infiniteLightBuffer); kernelPathTracing->setArg(argIndex++, *passFrameBuffer); kernelPathTracing->setArg(argIndex++, *matBuffer); kernelPathTracing->setArg(argIndex++, *matIndexBuffer); if (texMapBuffer) { kernelPathTracing->setArg(argIndex++, *texMapBuffer); kernelPathTracing->setArg(argIndex++, *texMapRGBBuffer); kernelPathTracing->setArg(argIndex++, *texMapInstanceBuffer); if (compiledScene.sphereBumps.size() > 0) kernelPathTracing->setArg(argIndex++, *bumpMapInstanceBuffer); } kernelApplyBlurLightFilterXR1 = new cl::Kernel(program, "ApplyBlurLightFilterXR1"); kernelApplyBlurLightFilterXR1->setArg(0, *passFrameBuffer); kernelApplyBlurLightFilterXR1->setArg(1, *tmpFrameBuffer); kernelApplyBlurLightFilterYR1 = new cl::Kernel(program, "ApplyBlurLightFilterYR1"); kernelApplyBlurLightFilterYR1->setArg(0, *tmpFrameBuffer); kernelApplyBlurLightFilterYR1->setArg(1, *passFrameBuffer); kernelApplyBlurHeavyFilterXR1 = new cl::Kernel(program, "ApplyBlurHeavyFilterXR1"); kernelApplyBlurHeavyFilterXR1->setArg(0, *passFrameBuffer); kernelApplyBlurHeavyFilterXR1->setArg(1, *tmpFrameBuffer); kernelApplyBlurHeavyFilterYR1 = new cl::Kernel(program, "ApplyBlurHeavyFilterYR1"); kernelApplyBlurHeavyFilterYR1->setArg(0, *tmpFrameBuffer); kernelApplyBlurHeavyFilterYR1->setArg(1, *passFrameBuffer); kernelApplyBoxFilterXR1 = new cl::Kernel(program, "ApplyBoxFilterXR1"); kernelApplyBoxFilterXR1->setArg(0, *passFrameBuffer); kernelApplyBoxFilterXR1->setArg(1, *tmpFrameBuffer); kernelApplyBoxFilterYR1 = new cl::Kernel(program, "ApplyBoxFilterYR1"); kernelApplyBoxFilterYR1->setArg(0, *tmpFrameBuffer); kernelApplyBoxFilterYR1->setArg(1, *passFrameBuffer); if (index == 0) { kernelBlendFrame = new cl::Kernel(program, "BlendFrame"); kernelBlendFrame->setArg(0, *passFrameBuffer); kernelBlendFrame->setArg(1, *frameBuffer); kernelToneMapLinear = new cl::Kernel(program, "ToneMapLinear"); kernelToneMapLinear->setArg(0, *frameBuffer); kernelToneMapLinear->setArg(1, *toneMapFrameBuffer); kernelUpdatePixelBuffer = new cl::Kernel(program, "UpdatePixelBuffer"); kernelUpdatePixelBuffer->setArg(0, *toneMapFrameBuffer); kernelUpdatePixelBuffer->setArg(1, *pboBuff); } else { kernelBlendFrame = NULL; kernelToneMapLinear = NULL; kernelUpdatePixelBuffer = NULL; } }
rmove() { register struct node *p; register int r; register r1, flt; for (p=first.forw; p!=0; p = p->forw) { flt = 0; switch (p->op) { case MOVF: case MOVFO: case MOVOF: flt = NREG; case MOV: if (p->subop==BYTE) goto dble; dualop(p); if ((r = findrand(regs[RT1], flt)) >= 0) { if (r == flt+isreg(regs[RT2]) && p->forw->op!=CBR && p->forw->op!=SXT && p->forw->op!=CFCC) { p->forw->back = p->back; p->back->forw = p->forw; redunm++; nchange++; continue; } } if (equstr(regs[RT1], "$0")) { p->op = CLR; strcpy(regs[RT1], regs[RT2]); regs[RT2][0] = 0; p->code = copy(1, regs[RT1]); nchange++; goto sngl; } repladdr(p, 0, flt); r = isreg(regs[RT1]); r1 = isreg(regs[RT2]); dest(regs[RT2], flt); if (r >= 0) if (r1 >= 0) savereg(r1+flt, regs[r+flt]); else savereg(r+flt, regs[RT2]); else if (r1 >= 0) savereg(r1+flt, regs[RT1]); else setcon(regs[RT1], regs[RT2]); source(regs[RT1]); setcc(regs[RT2]); continue; case ADDF: case SUBF: case DIVF: case MULF: flt = NREG; goto dble; case ADD: case SUB: case BIC: case BIS: case MUL: case DIV: case ASH: dble: dualop(p); if (p->op==BIC && (equstr(regs[RT1], "$-1") || equstr(regs[RT1], "$177777"))) { p->op = CLR; strcpy(regs[RT1], regs[RT2]); regs[RT2][0] = 0; p->code = copy(1, regs[RT1]); nchange++; goto sngl; } if ((p->op==BIC || p->op==BIS) && equstr(regs[RT1], "$0")) { if (p->forw->op!=CBR) { p->back->forw = p->forw; p->forw->back = p->back; nchange++; continue; } } /* * the next block of code looks for the sequences (which extract the * high byte of a word or the low byte respectively): * ash $-10,r * bic $-400,r * or * mov natural,r * bic $-400,r * and transforms them into: * clrb r * swab r * or * clr r * bisb natural,r * These constructs occur often enough in the kernel (dealing with major/minor * device numbers, etc) it's worth a little extra work at compile time. */ if (p->op == BIC && (equstr(regs[RT1],"$-400") || equstr(regs[RT1],"$-177400"))) { if (p->back->op == ASH) { r = isreg(regs[RT2]); dualop(p->back); if ((equstr(regs[RT1], "$-10") || equstr(regs[RT1], "$177770")) && r == isreg(regs[RT2])) { strcpy(regs[RT1], regs[RT2]); regs[RT2][0] = 0; p->back->op = CLR; p->back->subop = BYTE; p->back->code = copy(1, regs[RT1]); p->op = SWAB; p->code = copy(1, regs[RT1]); nchange++; goto sngl; } } else if (p->back->op == MOV && p->forw->op != CBR) { char temp[50]; r = isreg(regs[RT2]); if (r < 0 && !xnatural(regs[RT2])) goto out; strcpy(temp, regs[RT2]); dualop(p->back); if (isreg(regs[RT2]) == r && natural(regs[RT1])) { if (r < 0 && (!xnatural(regs[RT2]) || !equstr(temp, regs[RT2]))) goto out; /* * XXX - the sequence "movb rN,rN; bic $-400,rN" can not be transformed * because the 'clr' would lose all information about 'rN'. The best that can * be done is to remove the 'movb' instruction and leave the 'bic'. */ if (isreg(regs[RT1]) == r && r >= 0) { p = p->back; p->forw->back = p->back; p->back->forw = p->forw; nchange++; continue; } dest(regs[RT1], flt); p->back->op = CLR; p->back->subop = 0; p->back->code = copy(1, regs[RT2]); p->op = BIS; p->subop = BYTE; strcat(regs[RT1], ","); p->code = copy(2, regs[RT1], regs[RT2]); nchange++; } } out: dualop(p); /* restore banged up parsed operands */ } repladdr(p, 0, flt); source(regs[RT1]); dest(regs[RT2], flt); if (p->op==DIV && (r = isreg(regs[RT2]))>=0) regs[r|1][0] = 0; switch (p->op) { case ADD: case SUB: case BIC: case BIS: case ASH: setcc(regs[RT2]); break; default: ccloc[0] = 0; } continue; case SXT: singop(p); if (p->forw->op == CLR && p->forw->subop != BYTE && xnatural(regs[RT1]) && !strcmp(p->code, p->forw->code)){ p->forw->back = p->back; p->back->forw = p->forw; nchange++; continue; } goto sngl; case CLRF: case NEGF: flt = NREG; case CLR: case COM: case INC: case DEC: case NEG: case ASR: case ASL: case SWAB: singop(p); sngl: dest(regs[RT1], flt); if (p->op==CLR && flt==0) { if ((r = isreg(regs[RT1])) >= 0) savereg(r, "$0"); else setcon("$0", regs[RT1]); ccloc[0] = 0; } else setcc(regs[RT1]); continue; case TSTF: flt = NREG; case TST: singop(p); repladdr(p, 0, flt); source(regs[RT1]); if (p->back->op == TST && !flt && not_sp(regs[RT1])) { char rt1[MAXCPS + 2]; strcpy(rt1, regs[RT1]); singop(p->back); if (!strcmp("(sp)+", regs[RT1])) { p->back->subop = p->subop; p->back->forw = p->forw; p->forw->back = p->back; p = p->back; p->op = MOV; p->code = copy(2, rt1, ",(sp)+"); nrtst++; nchange++; continue; } singop(p); } if (p->back->op == MOV && p->back->subop == BYTE) { dualop(p->back); setcc(regs[RT2]); singop(p); } if (equstr(regs[RT1], ccloc) && p->subop == p->back->subop) { p->back->forw = p->forw; p->forw->back = p->back; p = p->back; nrtst++; nchange++; } else setcc(regs[RT1]); /* XXX - double TST in a row */ continue; case CMPF: flt = NREG; case CMP: case BIT: dualop(p); source(regs[RT1]); source(regs[RT2]); if(p->op==BIT) { if (equstr(regs[RT1], "$-1") || equstr(regs[RT1], "$177777")) { p->op = TST; strcpy(regs[RT1], regs[RT2]); regs[RT2][0] = 0; p->code = copy(1, regs[RT1]); nchange++; nsaddr++; } else if (equstr(regs[RT2], "$-1") || equstr(regs[RT2], "$177777")) { p->op = TST; regs[RT2][0] = 0; p->code = copy(1, regs[RT1]); nchange++; nsaddr++; } if (equstr(regs[RT1], "$0")) { p->op = TST; regs[RT2][0] = 0; p->code = copy(1, regs[RT1]); nchange++; nsaddr++; } else if (equstr(regs[RT2], "$0")) { p->op = TST; strcpy(regs[RT1], regs[RT2]); regs[RT2][0] = 0; p->code = copy(1, regs[RT1]); nchange++; nsaddr++; } } repladdr(p, 1, flt); ccloc[0] = 0; continue; case CBR: r = -1; if (p->back->op==TST || p->back->op==CMP) { if (p->back->op==TST) { singop(p->back); savereg(RT2, "$0"); } else dualop(p->back); if (equstr(regs[RT1], regs[RT2]) && natural(regs[RT1]) && natural(regs[RT2])) r = compare(p->subop, "$1", "$1"); else r = compare(p->subop, findcon(RT1), findcon(RT2)); if (r==0) { if (p->forw->op==CBR || p->forw->op==SXT || p->forw->op==CFCC) { p->back->forw = p->forw; p->forw->back = p->back; } else { p->back->back->forw = p->forw; p->forw->back = p->back->back; } decref(p->ref); p = p->back->back; nchange++; } else if (r>0) { p->op = JBR; p->subop = 0; p->back->back->forw = p; p->back = p->back->back; p = p->back; nchange++; } /* * If the instruction prior to the conditional branch was a 'tst' then * save the condition code status. The C construct: * if (x) * if (x > 0) * generates "tst _x; jeq ...; tst _x; jmi ...;jeq ...". The code below removes * the second "tst _x", leaving "tst _x; jeq ...;jmi ...; jeq ...". */ if (p->back->op == TST) { singop(p->back); setcc(regs[RT1]); break; } } /* * If the previous instruction was also a conditional branch then * attempt to merge the two into a single branch. */ if (p->back->op == CBR) fixupbr(p); case CFCC: ccloc[0] = 0; continue; /* * Unrecognized (unparsed) instructions, assignments (~foo=r2), and * data arrive here. In order to prevent throwing away information * about register contents just because a local assignment is done * we check for the first character being a tilde. */ case 0: if (p->code[0] != '~') clearreg(); continue; case JBR: redunbr(p); default: clearreg(); } } }
int Diff::execute() { PointContext sourceCtx; Options sourceOptions; { sourceOptions.add<std::string>("filename", m_sourceFile); sourceOptions.add<bool>("debug", isDebug()); sourceOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } std::unique_ptr<Stage> source(AppSupport::makeReader(m_sourceFile)); source->setOptions(sourceOptions); source->prepare(sourceCtx); PointBufferSet sourceSet = source->execute(sourceCtx); ptree errors; PointContext candidateCtx; Options candidateOptions; { candidateOptions.add<std::string>("filename", m_candidateFile); candidateOptions.add<bool>("debug", isDebug()); candidateOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } std::unique_ptr<Stage> candidate(AppSupport::makeReader(m_candidateFile)); candidate->setOptions(candidateOptions); candidate->prepare(candidateCtx); PointBufferSet candidateSet = candidate->execute(candidateCtx); assert(sourceSet.size() == 1); assert(candidateSet.size() == 1); PointBufferPtr sourceBuf = *sourceSet.begin(); PointBufferPtr candidateBuf = *candidateSet.begin(); if (candidateBuf->size() != sourceBuf->size()) { std::ostringstream oss; oss << "Source and candidate files do not have the same point count"; errors.put("count.error", oss.str()); errors.put("count.candidate", candidateBuf->size()); errors.put("count.source", sourceBuf->size()); } MetadataNode source_metadata = sourceCtx.metadata(); MetadataNode candidate_metadata = candidateCtx.metadata(); if (source_metadata != candidate_metadata) { std::ostringstream oss; oss << "Source and candidate files do not have the same metadata count"; errors.put("metadata.error", oss.str()); errors.put_child("metadata.source", pdal::utils::toPTree(source_metadata)); errors.put_child("metadata.candidate", pdal::utils::toPTree(candidate_metadata)); } if (candidateCtx.dims().size() != sourceCtx.dims().size()) { std::ostringstream oss; oss << "Source and candidate files do not have the same " "number of dimensions"; errors.put<std::string>("schema.error", oss.str()); //Need to "ptree" the PointContext dimension list in some way // errors.put_child("schema.source", sourceCtx.schema()->toPTree()); // errors.put_child("schema.candidate", // candidateCtx.schema()->toPTree()); } if (errors.size()) { write_json(std::cout, errors); return 1; } else { // If we made it this far with no errors, now we'll // check the points. checkPoints(*sourceBuf, *candidateBuf, errors); if (errors.size()) { write_json(std::cout, errors); return 1; } } return 0; }
void CollationIteratorTest::TestAssignment() { UErrorCode status = U_ZERO_ERROR; RuleBasedCollator *coll = (RuleBasedCollator *)Collator::createInstance(status); if (coll == NULL || U_FAILURE(status)) { errln("Couldn't create a default collator."); return; } UnicodeString source("abcd"); CollationElementIterator *iter1 = coll->createCollationElementIterator(source); CollationElementIterator iter2 = *iter1; if (*iter1 != iter2) { errln("Fail collation iterator assignment does not produce the same elements"); } CollationElementIterator iter3(*iter1); if (*iter1 != iter3) { errln("Fail collation iterator copy constructor does not produce the same elements"); } source = CharsToUnicodeString("a\\u0300\\u0325"); coll->setAttribute(UCOL_NORMALIZATION_MODE, UCOL_ON, status); CollationElementIterator *iter4 = coll->createCollationElementIterator(source); CollationElementIterator iter5(*iter4); if (*iter4 != iter5) { errln("collation iterator assignment does not produce the same elements"); } iter4->next(status); if (U_FAILURE(status) || *iter4 == iter5) { errln("collation iterator not equal"); } iter5.next(status); if (U_FAILURE(status) || *iter4 != iter5) { errln("collation iterator equal"); } iter4->next(status); if (U_FAILURE(status) || *iter4 == iter5) { errln("collation iterator not equal"); } iter5.next(status); if (U_FAILURE(status) || *iter4 != iter5) { errln("collation iterator equal"); } CollationElementIterator iter6(*iter4); if (*iter4 != iter6) { errln("collation iterator equal"); } iter4->next(status); if (U_FAILURE(status) || *iter4 == iter5) { errln("collation iterator not equal"); } iter5.next(status); if (U_FAILURE(status) || *iter4 != iter5) { errln("collation iterator equal"); } iter4->next(status); if (U_FAILURE(status) || *iter4 == iter5) { errln("collation iterator not equal"); } iter5.next(status); if (U_FAILURE(status) || *iter4 != iter5) { errln("collation iterator equal"); } delete iter1; delete iter4; delete coll; }
bool transaction::from_data(std::istream& stream) { istream_reader source(stream); return from_data(source); }
void FunctionBodyNode::finishParsing(PassRefPtr<FunctionParameters> parameters, const Identifier& ident) { Q_ASSERT(!source().isNull()); m_parameters = parameters; m_ident = ident; }
void operator()(Edge e, const Graph& g) { put(m_predecessor, target(e, g), source(e, g)); }
typename graph_traits<VertexListGraph>::degree_size_type edge_connectivity(VertexListGraph& g, OutputIterator disconnecting_set) { //------------------------------------------------------------------------- // Type Definitions typedef graph_traits<VertexListGraph> Traits; typedef typename Traits::vertex_iterator vertex_iterator; typedef typename Traits::edge_iterator edge_iterator; typedef typename Traits::out_edge_iterator out_edge_iterator; typedef typename Traits::vertex_descriptor vertex_descriptor; typedef typename Traits::degree_size_type degree_size_type; typedef color_traits<default_color_type> Color; typedef adjacency_list_traits<vecS, vecS, directedS> Tr; typedef typename Tr::edge_descriptor Tr_edge_desc; typedef adjacency_list<vecS, vecS, directedS, no_property, property<edge_capacity_t, degree_size_type, property<edge_residual_capacity_t, degree_size_type, property<edge_reverse_t, Tr_edge_desc> > > > FlowGraph; typedef typename graph_traits<FlowGraph>::edge_descriptor edge_descriptor; //------------------------------------------------------------------------- // Variable Declarations vertex_descriptor u, v, p, k; edge_descriptor e1, e2; bool inserted; vertex_iterator vi, vi_end; edge_iterator ei, ei_end; degree_size_type delta, alpha_star, alpha_S_k; std::set<vertex_descriptor> S, neighbor_S; std::vector<vertex_descriptor> S_star, non_neighbor_S; std::vector<default_color_type> color(num_vertices(g)); std::vector<edge_descriptor> pred(num_vertices(g)); //------------------------------------------------------------------------- // Create a network flow graph out of the undirected graph FlowGraph flow_g(num_vertices(g)); typename property_map<FlowGraph, edge_capacity_t>::type cap = get(edge_capacity, flow_g); typename property_map<FlowGraph, edge_residual_capacity_t>::type res_cap = get(edge_residual_capacity, flow_g); typename property_map<FlowGraph, edge_reverse_t>::type rev_edge = get(edge_reverse, flow_g); for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) { u = source(*ei, g), v = target(*ei, g); tie(e1, inserted) = add_edge(u, v, flow_g); cap[e1] = 1; tie(e2, inserted) = add_edge(v, u, flow_g); cap[e2] = 1; // not sure about this rev_edge[e1] = e2; rev_edge[e2] = e1; } //------------------------------------------------------------------------- // The Algorithm tie(p, delta) = detail::min_degree_vertex(g); S_star.push_back(p); alpha_star = delta; S.insert(p); neighbor_S.insert(p); detail::neighbors(g, S.begin(), S.end(), std::inserter(neighbor_S, neighbor_S.begin())); std::set_difference(vertices(g).first, vertices(g).second, neighbor_S.begin(), neighbor_S.end(), std::back_inserter(non_neighbor_S)); while (!non_neighbor_S.empty()) { // at most n - 1 times k = non_neighbor_S.front(); alpha_S_k = edmunds_karp_max_flow (flow_g, p, k, cap, res_cap, rev_edge, &color[0], &pred[0]); if (alpha_S_k < alpha_star) { alpha_star = alpha_S_k; S_star.clear(); for (tie(vi, vi_end) = vertices(flow_g); vi != vi_end; ++vi) if (color[*vi] != Color::white()) S_star.push_back(*vi); } S.insert(k); neighbor_S.insert(k); detail::neighbors(g, k, std::inserter(neighbor_S, neighbor_S.begin())); non_neighbor_S.clear(); std::set_difference(vertices(g).first, vertices(g).second, neighbor_S.begin(), neighbor_S.end(), std::back_inserter(non_neighbor_S)); } //------------------------------------------------------------------------- // Compute edges of the cut [S*, ~S*] std::vector<bool> in_S_star(num_vertices(g), false); typename std::vector<vertex_descriptor>::iterator si; for (si = S_star.begin(); si != S_star.end(); ++si) in_S_star[*si] = true; degree_size_type c = 0; for (si = S_star.begin(); si != S_star.end(); ++si) { out_edge_iterator ei, ei_end; for (tie(ei, ei_end) = out_edges(*si, g); ei != ei_end; ++ei) if (!in_S_star[target(*ei, g)]) { *disconnecting_set++ = *ei; ++c; } } return c; }
void operator()(Edge e, const Graph& g) { typename graph_traits<Graph>::vertex_descriptor u = source(e, g), v = target(e, g); put(m_distance, v, get(m_distance, u) + 1); }
/** ** Create a missile. ** ** @param l Lua state. */ static int CclMissile(lua_State *l) { MissileType *type = NULL; PixelPos position(-1, -1); PixelPos destination(-1, -1); PixelPos source(-1, -1); Missile *missile = NULL; DebugPrint("FIXME: not finished\n"); const int args = lua_gettop(l); for (int j = 0; j < args; ++j) { const char *value = LuaToString(l, j + 1); ++j; if (!strcmp(value, "type")) { type = MissileTypeByIdent(LuaToString(l, j + 1)); } else if (!strcmp(value, "pos")) { if (!lua_istable(l, j + 1) || lua_rawlen(l, j + 1) != 2) { LuaError(l, "incorrect argument"); } lua_rawgeti(l, j + 1, 1); position.x = LuaToNumber(l, -1); lua_pop(l, 1); lua_rawgeti(l, j + 1, 2); position.y = LuaToNumber(l, -1); lua_pop(l, 1); } else if (!strcmp(value, "origin-pos")) { if (!lua_istable(l, j + 1) || lua_rawlen(l, j + 1) != 2) { LuaError(l, "incorrect argument"); } lua_rawgeti(l, j + 1, 1); source.x = LuaToNumber(l, -1); lua_pop(l, 1); lua_rawgeti(l, j + 1, 2); source.y = LuaToNumber(l, -1); lua_pop(l, 1); } else if (!strcmp(value, "goal")) { if (!lua_istable(l, j + 1) || lua_rawlen(l, j + 1) != 2) { LuaError(l, "incorrect argument"); } lua_rawgeti(l, j + 1, 1); destination.x = LuaToNumber(l, -1); lua_pop(l, 1); lua_rawgeti(l, j + 1, 2); destination.y = LuaToNumber(l, -1); lua_pop(l, 1); } else if (!strcmp(value, "local")) { Assert(type); missile = MakeLocalMissile(*type, position, destination); missile->Local = 1; --j; } else if (!strcmp(value, "global")) { Assert(type); missile = MakeMissile(*type, position, destination); missile->position = position; missile->source = source; missile->destination = destination; missile->Local = 0; --j; } else if (!strcmp(value, "frame")) { Assert(missile); missile->SpriteFrame = LuaToNumber(l, j + 1); } else if (!strcmp(value, "state")) { Assert(missile); missile->State = LuaToNumber(l, j + 1); } else if (!strcmp(value, "anim-wait")) { Assert(missile); missile->AnimWait = LuaToNumber(l, j + 1); } else if (!strcmp(value, "wait")) { Assert(missile); missile->Wait = LuaToNumber(l, j + 1); } else if (!strcmp(value, "delay")) { Assert(missile); missile->Delay = LuaToNumber(l, j + 1); } else if (!strcmp(value, "source")) { Assert(missile); lua_pushvalue(l, j + 1); missile->SourceUnit = CclGetUnitFromRef(l); lua_pop(l, 1); } else if (!strcmp(value, "target")) { Assert(missile); lua_pushvalue(l, j + 1); missile->TargetUnit = CclGetUnitFromRef(l); lua_pop(l, 1); } else if (!strcmp(value, "damage")) { Assert(missile); missile->Damage = LuaToNumber(l, j + 1); } else if (!strcmp(value, "ttl")) { Assert(missile); missile->TTL = LuaToNumber(l, j + 1); } else if (!strcmp(value, "hidden")) { Assert(missile); missile->Hidden = 1; --j; } else if (!strcmp(value, "step")) { Assert(missile); if (!lua_istable(l, j + 1) || lua_rawlen(l, j + 1) != 2) { LuaError(l, "incorrect argument"); } lua_rawgeti(l, j + 1, 1); missile->CurrentStep = LuaToNumber(l, -1); lua_pop(l, 1); lua_rawgeti(l, j + 1, 2); missile->TotalStep = LuaToNumber(l, -1); lua_pop(l, 1); } else { LuaError(l, "Unsupported tag: %s" _C_ value); } } // we need to reinitialize position parameters - that's because of // the way InitMissile() (called from MakeLocalMissile()) computes // them - it works for creating a missile during a game but breaks // loading the missile from a file. missile->position = position; missile->source = source; missile->destination = destination; return 0; }
int main(int argc, char **argv) { int ch, fflag, tflag, status, n; char *targ, **newargv; const char *errstr; extern char *optarg; extern int optind; /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ sanitise_stdfd(); /* Copy argv, because we modify it */ newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv)); for (n = 0; n < argc; n++) newargv[n] = xstrdup(argv[n]); argv = newargv; __progname = ssh_get_progname(argv[0]); memset(&args, '\0', sizeof(args)); memset(&remote_remote_args, '\0', sizeof(remote_remote_args)); args.list = remote_remote_args.list = NULL; addargs(&args, "%s", ssh_program); addargs(&args, "-x"); addargs(&args, "-oForwardAgent=no"); addargs(&args, "-oPermitLocalCommand=no"); addargs(&args, "-oClearAllForwardings=yes"); fflag = tflag = 0; while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1) switch (ch) { /* User-visible flags. */ case '1': case '2': case '4': case '6': case 'C': addargs(&args, "-%c", ch); addargs(&remote_remote_args, "-%c", ch); break; case '3': throughlocal = 1; break; case 'o': case 'c': case 'i': case 'F': addargs(&remote_remote_args, "-%c", ch); addargs(&remote_remote_args, "%s", optarg); addargs(&args, "-%c", ch); addargs(&args, "%s", optarg); break; case 'P': addargs(&remote_remote_args, "-p"); addargs(&remote_remote_args, "%s", optarg); addargs(&args, "-p"); addargs(&args, "%s", optarg); break; case 'B': addargs(&remote_remote_args, "-oBatchmode=yes"); addargs(&args, "-oBatchmode=yes"); break; case 'l': limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024, &errstr); if (errstr != NULL) usage(); limit_kbps *= 1024; /* kbps */ bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN); break; case 'p': pflag = 1; break; case 'r': iamrecursive = 1; break; case 'S': ssh_program = xstrdup(optarg); break; case 'v': addargs(&args, "-v"); addargs(&remote_remote_args, "-v"); verbose_mode = 1; break; case 'q': addargs(&args, "-q"); addargs(&remote_remote_args, "-q"); showprogress = 0; break; /* Server options. */ case 'd': targetshouldbedirectory = 1; break; case 'f': /* "from" */ iamremote = 1; fflag = 1; break; case 't': /* "to" */ iamremote = 1; tflag = 1; #ifdef HAVE_CYGWIN setmode(0, O_BINARY); #endif break; default: usage(); } argc -= optind; argv += optind; if ((pwd = getpwuid(userid = getuid())) == NULL) fatal("unknown user %u", (u_int) userid); if (!isatty(STDOUT_FILENO)) showprogress = 0; remin = STDIN_FILENO; remout = STDOUT_FILENO; if (fflag) { /* Follow "protocol", send data. */ (void) response(); source(argc, argv); exit(errs != 0); } if (tflag) { /* Receive data. */ sink(argc, argv); exit(errs != 0); } if (argc < 2) usage(); if (argc > 2) targetshouldbedirectory = 1; remin = remout = -1; do_cmd_pid = -1; /* Command to be executed on remote system using "ssh". */ (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "", iamrecursive ? " -r" : "", pflag ? " -p" : "", targetshouldbedirectory ? " -d" : ""); (void) signal(SIGPIPE, lostconn); if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */ toremote(targ, argc, argv); else { if (targetshouldbedirectory) verifydir(argv[argc - 1]); tolocal(argc, argv); /* Dest is local host. */ } /* * Finally check the exit status of the ssh process, if one was forked * and no error has occurred yet */ if (do_cmd_pid != -1 && errs == 0) { if (remin != -1) (void) close(remin); if (remout != -1) (void) close(remout); if (waitpid(do_cmd_pid, &status, 0) == -1) errs = 1; else { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) errs = 1; } } exit(errs != 0); }
void object::test<3>() { OGRErr err = OGRERR_NONE; OGRDataSourceH ds = NULL; ds = OGR_Dr_CreateDataSource(drv_, data_tmp_.c_str(), NULL); ensure("Can't open or create data source", NULL != ds); // Create memory Layer OGRLayerH lyr = NULL; lyr = OGR_DS_CreateLayer(ds, "tpoly", NULL, wkbPolygon, NULL); ensure("Can't create layer", NULL != lyr); // Create schema OGRFieldDefnH fld = NULL; fld = OGR_Fld_Create("AREA", OFTReal); err = OGR_L_CreateField(lyr, fld, true); OGR_Fld_Destroy(fld); ensure_equals("Can't create field", OGRERR_NONE, err); fld = OGR_Fld_Create("EAS_ID", OFTInteger); err = OGR_L_CreateField(lyr, fld, true); OGR_Fld_Destroy(fld); ensure_equals("Can't create field", OGRERR_NONE, err); fld = OGR_Fld_Create("PRFEDEA", OFTString); err = OGR_L_CreateField(lyr, fld, true); OGR_Fld_Destroy(fld); ensure_equals("Can't create field", OGRERR_NONE, err); // Check schema OGRFeatureDefnH featDefn = OGR_L_GetLayerDefn(lyr); ensure("Layer schema is NULL", NULL != featDefn); ensure_equals("Fields creation failed", 3, OGR_FD_GetFieldCount(featDefn)); // Copy ogr/poly.shp to temporary layer OGRFeatureH featDst = OGR_F_Create(featDefn); ensure("Can't create empty feature", NULL != featDst); std::string source(data_); source += SEP; source += "poly.shp"; OGRDataSourceH dsSrc = OGR_Dr_Open(drv_, source.c_str(), false); ensure("Can't open source layer", NULL != dsSrc); OGRLayerH lyrSrc = OGR_DS_GetLayer(dsSrc, 0); ensure("Can't get source layer", NULL != lyrSrc); OGRFeatureH featSrc = NULL; while (NULL != (featSrc = OGR_L_GetNextFeature(lyrSrc))) { err = OGR_F_SetFrom(featDst, featSrc, true); ensure_equals("Can't set festure from source", OGRERR_NONE, err); err = OGR_L_CreateFeature(lyr, featDst); ensure_equals("Can't write feature to layer", OGRERR_NONE, err); OGR_F_Destroy(featSrc); } // Release and close resources OGR_F_Destroy(featDst); OGR_DS_Destroy(dsSrc); OGR_DS_Destroy(ds); }
void lua::store_lua_Integer(lua_Integer& destination, lua_State* const state, const int source_pos) { lua::index source(state, source_pos); // Directly retrieve boolean types. if(source.type().boolean()) { destination = static_cast<lua_Integer>(lua_toboolean(source.state(), source.pos())); return; } // Directly retrieve numeric types. if(source.type().number()) { destination = static_cast<lua_Integer>(lua_tointeger(source.state(), source.pos())); return; } // Convert the first character of a string to its numeric value. if(source.type().string()) { destination = source.get<const char*>()[0]; return; } // Convert userdata to integers by interpreting the data as-is. if(source.type().userdata()) { auto valueSize = lua::object_size(state, source_pos); if(valueSize == sizeof(long long)) { destination = static_cast<lua_Integer>( *static_cast<long long*>(lua::get<void*>(source)) ); return; } if(valueSize == sizeof(long)) { destination = static_cast<lua_Integer>( *static_cast<long*>(lua::get<void*>(source)) ); return; } if(valueSize == sizeof(int)) { destination = static_cast<lua_Integer>( *static_cast<int*>(lua::get<void*>(source)) ); return; } if(valueSize == sizeof(short)) { destination = static_cast<lua_Integer>( *static_cast<short*>(lua::get<void*>(source)) ); return; } if(valueSize == sizeof(char)) { destination = static_cast<lua_Integer>( *static_cast<char*>(lua::get<void*>(source)) ); return; } if(valueSize == sizeof(bool)) { destination = static_cast<lua_Integer>( *static_cast<bool*>(lua::get<void*>(source)) ); return; } } // Nothing retrieved, so clear destination. destination = 0; }