コード例 #1
0
void ProjectExporter::checkRes(ProjectModel *project)
{
    QMap<QString, QString> settings = project->getSettings();
    QMap<QString, QString>::iterator i;

    for(i = settings.begin(); i != settings.end(); i++)
    {
        if(i.key() == "wps" || i.key() == "rwps" || i.key() == "sbs"
                || i.key() == "rsbs" || i.key() == "fms" || i.key() == "rfms")
        {
            checkWPS(project, i.value());
        }
        else if(i.value().contains("/.rockbox")
                && i.key() != "configfile" && i.key() != "themebase")
        {
            QString absPath = i.value().replace("/.rockbox",
                                                settings.value("themebase"));
            if(QFile::exists(absPath))
            {
                addSuccess(i.key() + tr(" found"));
            }
            else
            {
                if(i.key() == "font")
                {
                    QSettings qset;
                    qset.beginGroup("RBFont");
                    QString fontDir = qset.value("fontDir", "").toString();
                    qset.endGroup();

                    QString newDir = fontDir + "/" + absPath.split("/").last();

                    if(QFile::exists(newDir))
                    {
                        addSuccess(tr("font found in font pack"));
                    }
                    else
                    {
                        addWarning(tr("font not found"));
                    }

                }
                else
                {
                    addWarning(i.key() + tr(" not found"));
                }
            }
        }
    }
}
コード例 #2
0
/** @brief Identify required regions.
 *
 * Takes a list of @a instruments as argument (which are planned to be combined
 * as separate dimension zones of a certain dimension into one single new
 * instrument) and fulfills the following tasks:
 *
 * - 1. Identification of total amount of regions required to create a new
 *      instrument to become a combined version of the given instruments.
 * - 2. Precise key range of each of those identified required regions to be
 *      created in that new instrument.
 * - 3. Grouping the original source regions of the given original instruments
 *      to the respective target key range (new region) of the instrument to be
 *      created.
 *
 * @param instruments - list of instruments that are planned to be combined
 * @returns structured result of the tasks described above
 */
static RegionGroups groupByRegionIntersections(std::vector<gig::Instrument*>& instruments) {
    RegionGroups groups;

    // find all region intersections of all instruments
    std::vector<DLS::range_t> intersections;
    for (int iStart = 0; iStart <= 127; ) {
        iStart = findLowestRegionPoint(instruments, iStart);
        if (iStart < 0) break;
        const int iEnd = findFirstRegionEnd(instruments, iStart);
        DLS::range_t range = { uint16_t(iStart), uint16_t(iEnd) };
        intersections.push_back(range);
        iStart = iEnd + 1;
    }

    // now sort all regions to those found intersections
    for (uint i = 0; i < intersections.size(); ++i) {
        const DLS::range_t& range = intersections[i];
        RegionGroup group = getAllRegionsWhichOverlapRange(instruments, range);
        if (!group.empty())
            groups[range] = group;
        else
            addWarning("Empty region group!");
    }

    return groups;
}
コード例 #3
0
 void Document::addWarning(ParserWarningTypes inWarning, const XML::ParserPos &inPos)
 {
   if (mEnableWarnings)
   {
     pushPos(inPos);
     addWarning(inWarning);
     popPos();
   }
 }
コード例 #4
0
/**
 * Returns all regions of the given @a instruments where the respective region's
 * key range overlaps the given @a range. The regions returned are ordered (in a
 * map) by their instrument pointer.
 */
static RegionGroup getAllRegionsWhichOverlapRange(std::vector<gig::Instrument*>& instruments, DLS::range_t range) {
    RegionGroup group;
    for (uint i = 0; i < instruments.size(); ++i) {
        gig::Instrument* instr = instruments[i];
        std::vector<gig::Region*> v = getAllRegionsWhichOverlapRange(instr, range);
        if (v.empty()) continue;
        if (v.size() > 1) {
            addWarning("More than one region found!");
        }
        group[instr] = v[0];
    }
    return group;
}
コード例 #5
0
ファイル: SLHAreader.c プロジェクト: HEP-KBFI/susy-dm
int slhaBasicReader( int mode, int (*getLnPar)(int, char*), int *anydate,char * end)
{
  char buff[StrLn],name[StrLn],rest[StrLn];
  int n,err,m1,m4,m8,m2,m16;
  double scale;
  char wTxt[100];

  _end_=end;  
  *anydate=0;
  m1=mode&1;
  m2=mode&2;
  m4=mode&4;
  m8=mode&8;
  m16=mode&16;
  
  nLine=0;
  FError=0;
  getLnPtr=getLnPar;
  
  if(m1==0)cleanSLHAdata();
    
  err=readLine(StrLn,buff);
  if(err){FError=1;  if(err==-1 )  return -3 ; else  return err;}
  
  for(;;) 
  { char*block="BLOCK ";
    int L;
    char * bComm, *c;
    
    bComm=strchr(buff,'#'); if(bComm) bComm[0]=0;
 
    for(L=0;L<6 && buff[L]&& toupper(buff[L])==block[L] ;L++) continue;
    if(L==6)
    { int i;
      if( sscanf(buff+6," %s ",name)!=1)
      { 
         sprintf(wTxt,"SLHAreader: Line %d : block name is absent",nLine);
         addWarning(wTxt);
         if(m2) 
         { cleanSLHAdata();
           printf("%s\n",wTxt);
           addWarning(wTxt);
           FError=1;
           return nLine;
         }
         if(!findNewBlock(buff)) return -1;
         continue;   
      }  

      if(strlen(name)>=BlckLn)
      {
         sprintf(wTxt,"SLHAreader: Line %d: Too long name of BLOCK",nLine);
         addWarning(wTxt);
         if(m2) 
         {  cleanSLHAdata();
           printf("%s\n",wTxt);
           addWarning(wTxt);
            FError=1;
            return nLine;
         }
         if(!findNewBlock(buff)) return -1;
         continue; 
      }
      for(i=0;name[i];i++) name[i]=toupper(name[i]);
/* SPINFO & DCINFO */
      if(strcmp(name,"SPINFO")==0 ||strcmp(name,"DCINFO")==0 )
      { 
       *anydate=1;
       for(;;)
       { err=readLine(StrLn,buff); if(err){ return err;}
         if(sscanf(buff,"%d",&n)!=1)  break; 
         if(n==1) sscanf(buff,"%*d %[^\n]",creator);
         else if(n==2) sscanf(buff,"%*d %[^\n]",version);
         else if(n==4)
         {  cleanSLHAdata();  
            addWarning(buff);
            FError=1;                      
            return -2;
         }
         else if(n==3) addWarning(buff);
       }
      }
/* QNUMBERS */      
      else if( strcmp(name,"QNUMBERS")==0) 
      {  *anydate=1;
         if(m16) { if(!findNewBlock(buff)) return -1; else continue;} 
         else  
         {
           int val;
           qNumberStr * newQ;
           
           if( sscanf(buff+6,"%*s %d", &val)!=1) 
           { 
              sprintf(wTxt,"SLHAreader: line %d No pdg code for Qnumbers",nLine);
              addWarning(wTxt);
              if(m2)
              {  cleanSLHAdata();
                 printf("%s\n",wTxt);
                 addWarning(wTxt);
                 FError=1;
                 return nLine;
              }
              if(!findNewBlock(buff)) { return -1;}
              continue;                                                    
           }
           newQ =(qNumberStr*)malloc(sizeof(qNumberStr));
           newQ->next=qNumberList;
           qNumberList=newQ;
           newQ->pdg=val;
           newQ->txt=getComment(bComm);
           newQ->spinDim=newQ->eQ3=newQ->cDim=newQ->anti=-88888888;
           
           for(;;)
           { err=readLine(StrLn,buff); if(err) return err;
             if(sscanf(buff,"%d %d",&n,&val)!=2)  break;
             switch(n)
             {
               case 1: newQ->eQ3=val;      break;
               case 2: newQ->spinDim=val;  break;
               case 3: newQ->cDim=val;     break;
               case 4: newQ->anti=val;  break;
               default:
               {  
                  sprintf(wTxt,"SLHAreader: line %d: unexpected key for QNUMBERS",nLine);
                  addWarning(wTxt);  
               }
             }
           } 
         }   
      }
      else   
/* NORMAL BLOCK */      
      { blockStr*newBlock;
        if( sscanf(buff+6,"%*s %s", rest)==EOF) scale=-1;  
        else if(sscanf(buff+6,"%*s %*s %lf %s", &scale, rest)!=1)
        { 
           sprintf(wTxt,"SLHAreader: line %d: Unexpected BLOCK specification",nLine);
           addWarning(wTxt);
           if(m2)
           {  cleanSLHAdata();
              printf("%s\n",wTxt);
              addWarning(wTxt);
              FError=1;
              return nLine;
           }
           if(!findNewBlock(buff)) { return -1;}
           continue;       
        }

        *anydate=1;         
        if(m8) for(;;)
        {
          err=readLine(StrLn,buff); if(err) return err;
          if(!isdigit(buff[0])) break;
        }
        else
        {
          newBlock=(blockStr*)malloc(sizeof(blockStr));
          newBlock->next=blockList;
          strcpy(newBlock->name,name);         
          newBlock->dataList=NULL;
          newBlock->scale=scale;
          blockList=newBlock;
          newBlock->txt=getComment(bComm);
          
          for(;;)
          { int err=0,nkey=0,k,keys[KeyMLn];
            long double re=0,im=0;
            blockRec*dr;
            
            err=readLine(StrLn,buff); if(err) return err;

            if(buff[0]!=' ')    break;
            
            bComm=strchr(buff,'#'); if(bComm) bComm[0]=0;
            
            for(c=buff+strlen(buff)-1  ;c>buff && c[0]==' ';c--);
            
            c[1]=0;

            dr=(blockRec*)malloc(sizeof(blockRec));
            dr->next=blockList->dataList;
            blockList->dataList=dr;
            dr->val=0;
            dr->nkey=-1;
            dr->txt=getComment(bComm);
            dr->body=malloc(strlen(buff)+1);
            strcpy(dr->body,buff);
            
            if(c[0]==')') 
            {
              for(;c>buff && c[0]!='(';c--);
              if(2!=sscanf(c,"( %Lf , %Lf)", &re,&im))  err=1; 
            } else
            { char rest[StrLn];
              for(;c>buff && c[0]!=' ';c--);
              if(1!=sscanf(c,"%Lf%s",&re,rest))  err=1;
            }
            if(err) continue;
#ifdef OLD            
            { sprintf(wTxt,"SLHAreader: line %d: Unexpected last token " ,nLine);
              addWarning(wTxt);
              if(m2) { cleanSLHAdata(); printf("%s\n",wTxt); FError=1; return nLine; }
              else continue;                                                                       
            } 
#endif
            else 
            c[0]=0;
            
            for(c=strtok(buff," ");c && nkey<KeyMLn;c=strtok(NULL," "),nkey++)
            {   
              if(1!=sscanf(c,"%d%s",keys+nkey,rest)) { err=1; break;}
            }
          
            if(err) continue;
#ifdef OLD            
            {  
              sprintf(wTxt,"SLHAreader: line %d: Unexpected %d token" ,nLine,nkey+1);
              addWarning(wTxt);
              if(m2) { cleanSLHAdata(); printf("%s\n",wTxt); FError=1; return nLine;}
              else continue; 
            }
#endif
            dr->val=re+I*im;
            dr->nkey=nkey;
            for(k=0;k<nkey;k++) dr->keys[k]=keys[k];          
          }
        } 
      }
    }else 
コード例 #6
0
ファイル: ogr_file_format.cpp プロジェクト: 999999333/mapper
void OgrFileImport::import(bool load_symbols_only)
{
	auto file = qobject_cast<QFile*>(stream);
	if (!file)
	{
		throw FileFormatException("Internal error"); /// \todo Review design and/or message
	}
	
	auto filename = file->fileName();
	// GDAL 2.0: ... = GDALOpenEx(template_path.toLatin1(), GDAL_OF_VECTOR, nullptr, nullptr, nullptr);
	auto data_source = ogr::unique_datasource(OGROpen(filename.toLatin1(), 0, nullptr));
	if (data_source == nullptr)
	{
		throw FileFormatException(Importer::tr("Could not read '%1'")
		                          .arg(filename));
	}
	
	empty_geometries = 0;
	no_transformation = 0;
	failed_transformation = 0;
	unsupported_geometry_type = 0;
	too_few_coordinates = 0;
	
	importStyles(data_source.get());

	if (!load_symbols_only)
	{
		auto num_layers = OGR_DS_GetLayerCount(data_source.get());
		for (int i = 0; i < num_layers; ++i)
		{
			auto layer = OGR_DS_GetLayer(data_source.get(), i);
			if (!layer)
			{
				addWarning(tr("Unable to load layer %1.").arg(i));
				continue;
			}
			
			auto part = map->getCurrentPart();
			if (option(QLatin1String("Separate layers")).toBool())
			{
				if (num_layers > 0)
				{
					if (part->getNumObjects() == 0)
					{
						part->setName(OGR_L_GetName(layer));
					}
					else
					{
						part = new MapPart(OGR_L_GetName(layer), map);
						auto index = map->getNumParts();
						map->addPart(part, index);
						map->setCurrentPartIndex(index);
					}
				}
			}
				
			importLayer(part, layer);
		}
	}
	
	if (empty_geometries)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, empty_geometries)
		           .arg(tr("Empty geometry.")));
	}
	if (no_transformation)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, no_transformation)
		           .arg(tr("Can't determine the coordinate transformation: %1").arg(CPLGetLastErrorMsg())));
	}
	if (failed_transformation)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, failed_transformation)
		           .arg(tr("Failed to transform the coordinates.")));
	}
	if (unsupported_geometry_type)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, unsupported_geometry_type)
		           .arg(tr("Unknown or unsupported geometry type.")));
	}
	if (too_few_coordinates)
	{
		addWarning(tr("Unable to load %n objects, reason: %1", nullptr, too_few_coordinates)
		           .arg(tr("Not enough coordinates.")));
	}
}
コード例 #7
0
ファイル: ogr_file_format.cpp プロジェクト: 999999333/mapper
OgrFileImport::OgrFileImport(QIODevice* stream, Map* map, MapView* view, bool drawing_from_projected)
 : Importer(stream, map, view)
 , map_srs{ OSRNewSpatialReference(nullptr) }
 , manager{ OGR_SM_Create(nullptr) }
 , drawing_from_projected{ drawing_from_projected }
{
	GdalManager().configure();
	
	setOption(QLatin1String{ "Separate layers" }, QVariant{ false });
	
	auto spec = QByteArray::fromRawData("WGS84", 6);
	auto error = OSRSetWellKnownGeogCS(map_srs.get(), spec);
	if (!map->getGeoreferencing().isLocal() && !error)
	{
		spec = map->getGeoreferencing().getProjectedCRSSpec().toLatin1();
		error = OSRImportFromProj4(map_srs.get(), spec);
	}
	
	if (error)
	{
		addWarning(tr("Unable to setup \"%1\" SRS for GDAL: %2")
		           .arg(QString::fromLatin1(spec), QString::number(error)));
	}
	
	// Reasonable default?
	
	// OGR feature style defaults
	default_pen_color = new MapColor("Black", 0); 
	default_pen_color->setRgb({0.0, 0.0, 0.0});
	default_pen_color->setCmykFromRgb();
	map->addColor(default_pen_color, 0);
	
	auto default_brush_color = new MapColor("Black 50%", 0);
	default_brush_color->setRgb({0.5, 0.5, 0.5});
	default_brush_color->setCmykFromRgb();
	map->addColor(default_brush_color, 1);
	
	default_point_symbol = new PointSymbol();
	default_point_symbol->setName(tr("Point"));
	default_point_symbol->setNumberComponent(0, 1);
	default_point_symbol->setInnerColor(default_pen_color);
	map->addSymbol(default_point_symbol, 0);
	
	default_line_symbol = new LineSymbol();
	default_line_symbol->setName(tr("Line"));
	default_line_symbol->setNumberComponent(0, 2);
	default_line_symbol->setColor(default_pen_color);
	default_line_symbol->setLineWidth(0.1); // (0.1 mm, nearly cosmetic)
	default_line_symbol->setCapStyle(LineSymbol::FlatCap);
	default_line_symbol->setJoinStyle(LineSymbol::MiterJoin);
	map->addSymbol(default_line_symbol, 1);
	
	default_area_symbol = new AreaSymbol();
	default_area_symbol->setName(tr("Area"));
	default_area_symbol->setNumberComponent(0, 3);
	default_area_symbol->setColor(default_brush_color);
	map->addSymbol(default_area_symbol, 2);
	
	default_text_symbol = new TextSymbol();
	default_text_symbol->setName(tr("Text"));
	default_text_symbol->setNumberComponent(0, 4);
	default_text_symbol->setColor(default_pen_color);
	map->addSymbol(default_text_symbol, 3);
}
コード例 #8
0
/* ******************************************************************************
*  Function Name : ReadRFSDCreateAnimGeo()
*
*
*  Input Arguments : OP_Context &context
*
*  Return Value : int
*
***************************************************************************** */
inline int SOP_RF_Import::ReadRFSDCreateAnimGeo(UT_Interrupt * boss)
{

   UT_XformOrder xformOrder(UT_XformOrder::SRT);
   UT_Matrix4 work_matrix;
   GEO_Point * ppt;

   try {

         // For each object in the SD file, read it's frame header and geometry
         for(int cur_object = 0; cur_object < myRFSDFile->myRF_SD_Header.num_objects; cur_object++) {

               // read the object's frame header data
               if(myRFSDFile->readSDObjFrameHdr())
                  throw SOP_RF_Import_Exception(canNotReadSDObjectFrameHeader, exceptionError);


#ifdef DEBUG
               std::cout << "obj_name_len: " << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_name_len << std::endl;
               std::cout << "Object Name: " << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_name << std::endl;
               std::cout << "Object Transform:" << std::endl;
               for(int i = 0; i < 12; i++)
                  std::cout << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_world_xform[i] << "\t";
               std::cout << std::endl;
               std::cout << "Translation Vector: " << std::endl;
               for(int i = 0; i < 3; i++)
                  std::cout << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_trans_vec[i] << "\t";
               std::cout << std::endl;
               std::cout << "Rotation Vector: " << std::endl;
               for(int i = 0; i < 3; i++)
                  std::cout << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_rot_vec[i] << "\t";
               std::cout << std::endl;
               std::cout << "Scale Vector: " << std::endl;
               for(int i = 0; i < 3; i++)
                  std::cout << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_scale_vec[i] << "\t";
               std::cout << std::endl;
               std::cout << "Pivot Position: " << std::endl;
               for(int i = 0; i < 3; i++)
                  std::cout << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_pivot_pos[i] << "\t";
               std::cout << std::endl << std::endl;
               std::cout << "CG Position: " << std::endl;
               for(int i = 0; i < 3; i++)
                  std::cout << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_pos[i] << "\t";
               std::cout << std::endl;
               std::cout << "CG Velocity: " << std::endl;
               for(int i = 0; i < 3; i++)
                  std::cout << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_vel[i] << "\t";
               std::cout << std::endl;
               std::cout << "CG Rotation: " << std::endl;
               for(int i = 0; i < 3; i++)
                  std::cout << myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_rot[i] << "\t";
               std::cout << std::endl << std::endl;
#endif

               if(myGUIState.t_sd_cg) {
                     work_matrix.identity();
                     work_matrix.xform(xformOrder,
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_trans_vec[0],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_trans_vec[1],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_trans_vec[2],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_rot_vec[0],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_rot_vec[1],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_rot_vec[2],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_scale_vec[0],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_scale_vec[1],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_scale_vec[2],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_pivot_pos[0],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_pivot_pos[1],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_pivot_pos[2]);
                     // Transform the geometry
                     gdp->transformPoints(work_matrix, (const GA_PointGroup *)objPrimitiveGrpList[cur_object]);
                  }

               if(myGUIState.t_sd_cg_xform) {
                     work_matrix.identity();
                     work_matrix.xform(xformOrder,
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_pos[0],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_pos[1],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_pos[2],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_rot[0],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_rot[1],
                                       myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_rot[2]);
                     // Transform the geometry
                     gdp->transformPoints(work_matrix, (const GA_PointGroup *)objPrimitiveGrpList[cur_object]);
                  }

#ifdef DEBUG
               std::cout << "Current primitive group: " << objPrimitiveGrpList[cur_object]->getName() << std::endl;
#endif

               GA_RWAttributeRef attrRef;
               GA_RWHandleI attrIntHandle;
               GA_RWHandleF attrFloatHandle;
               GA_RWHandleV3 attrVector3Handle;

               // If the user wants the CG data, add it to the geo detail
               if(myGUIState.t_sd_cg) {

                     if(myAttributeRefs.sd_CG_pos.isValid()) {
                           attrVector3Handle.bind(myAttributeRefs.sd_CG_pos.getAttribute());
                           attrVector3Handle.set(0, UT_Vector3(myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_pos));
                        }

                     if(myAttributeRefs.sd_CG_vel.isValid()) {
                           attrVector3Handle.bind(myAttributeRefs.sd_CG_vel.getAttribute());
                           attrVector3Handle.set(0, UT_Vector3(myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_vel));
                        }

                     if(myAttributeRefs.sd_CG_rot.isValid()) {
                           attrVector3Handle.bind(myAttributeRefs.sd_CG_rot.getAttribute());
                           attrVector3Handle.set(0, UT_Vector3(myRFSDFile->myRF_SD_Obj_Frame_Header.obj_CG_rot));
                        }

                  }


               // If vertex mode, update coordinates
               if(myRFSDFile->myRF_SD_Obj_Header.obj_mode) {

                     for(int cur_point = 0; cur_point < myRFSDFile->obj_detail[cur_object].num_points; cur_point++) {

#ifdef DEBUG
                           std::cout << "vertex number: " << cur_point + 1 << " of "
                                     << myRFSDFile->myRF_SD_Obj_Header.num_vertices
                                     << " vertices " << std::endl;
#endif

                           if(myRFSDFile->readSDFaceCoord())
                              throw SOP_RF_Import_Exception(canNotReadSDAnimFaceData, exceptionError);

#ifdef DEBUG
                           std::cout << "Vertex Coordinates: " << std::endl;
                           std::cout << myRFSDFile->myRF_SD_Face_Data.vertex[0] << "\t";
                           std::cout << myRFSDFile->myRF_SD_Face_Data.vertex[1] << "\t";
                           std::cout << myRFSDFile->myRF_SD_Face_Data.vertex[2] << std::endl;
#endif

                           // update points
                           if(boss->opInterrupt())
                              throw SOP_RF_Import_Exception(theSDAnimGeoCreationInterrupt, exceptionWarning);

                           myCurrPoint = cur_point;

                           // Get the current point to either update position
                           ppt = gdp->points().entry(cur_point);

                           if(ppt == NULL)
                              throw SOP_RF_Import_Exception(theSDAnimGeoCreationPointNULL, exceptionError);

#ifdef DEBUG
                           std::cout << "cur_object: " << cur_object << std::endl;
#endif

                           gdp->points()[cur_point]->setPos((float)myRFSDFile->myRF_SD_Face_Data.vertex[0],
                                                            (float)myRFSDFile->myRF_SD_Face_Data.vertex[1],
                                                            (float)myRFSDFile->myRF_SD_Face_Data.vertex[2], 1.0);

#ifdef DEBUG
                           std::cout << "position assigned" << std::endl;
#endif

                        } // for(int cur_point=0; ...
                  } // if(myRFSDFile->myRF_SD_Obj_Header.obj_mode)
            } // if vertex mode


      }
   catch(SOP_RF_Import_Exception e) {
         e.what();

         if(e.getSeverity() == exceptionWarning)
            addWarning(SOP_MESSAGE, errorMsgs[e.getErrorCode()]);
         else
            if(e.getSeverity() == exceptionError)
               addError(SOP_MESSAGE, errorMsgs[e.getErrorCode()]);

         if(myRFSDFile->SDifstream.is_open()) {
               myRFSDFile->closeSDFile(RF_FILE_READ);
            }

         return 1;
      }

   return 0;
}
コード例 #9
0
OP_ERROR
SOP_PointsFromVoxels::cookMySop(OP_Context &context)
{
    bool                        cull, store;
    fpreal                      now, value;
    int                         rx, ry, rz;
    unsigned                    primnum;

    GA_Offset                   ptOff;
    GA_ROAttributeRef           input_attr_gah;
    GA_RWAttributeRef           attr_gah;
    GA_ROHandleS                input_attr_h;
    GA_RWHandleF                attr_h;

    const GU_Detail             *input_geo;
    const GEO_Primitive         *prim;
    const GEO_PrimVolume        *vol;

    UT_String                   attr_name;
    UT_Vector3                  pos;
    UT_VoxelArrayIteratorF      vit;

    now = context.getTime();

    if (lockInputs(context) >= UT_ERROR_ABORT)
    {
        return error();
    }

    // Get the primitive number.
    primnum = PRIM(now);

    // Check for culling.
    cull = CULL(now);

    store = STORE(now);

    // Clear out the detail since we only want our new points.
    gdp->clearAndDestroy();

    // Get the input geometry as read only.
    GU_DetailHandleAutoReadLock gdl(inputGeoHandle(0));
    input_geo = gdl.getGdp();

    // Primitive number is valid.
    if (primnum < input_geo->getNumPrimitives())
    {
        // Get the primitive we need.
        prim = input_geo->primitives()(primnum);

        // The primitive is a volume primitive.
        if (prim->getTypeId().get() == GEO_PRIMVOLUME)
        {
            // Get the actual PrimVolume.
            vol = (const GEO_PrimVolume *)prim;

            // Get a voxel read handle from the primitive.
            UT_VoxelArrayReadHandleF    vox(vol->getVoxelHandle());

            // Attach the voxel iterator to the handle.
            vit.setHandle(vox);

            if (store)
            {
                // Try to find a 'name' attribute.
                input_attr_gah = input_geo->findPrimitiveAttribute("name");

                if (input_attr_gah.isValid())
                {
                    // Get this primitive's name.
                    input_attr_h.bind(input_attr_gah.getAttribute());
                    attr_name = input_attr_h.get(primnum);
                }

                // No name, so just use 'value'.
                else
                {
                    attr_name = "value";
                }

                // Add a float point attribute to store the values.
                attr_gah = gdp->addFloatTuple(GA_ATTRIB_POINT, attr_name, 1);

                // Attach an attribute handle.
                attr_h.bind(attr_gah.getAttribute());
            }

            // Culling empty voxels.
            if (cull)
            {
                // Iterate over all the voxels.
                for (vit.rewind(); !vit.atEnd(); vit.advance())
                {
                    // The voxel value.
                    value = vit.getValue();

                    // Skip voxels with a value of 0.
                    if (value == 0)
                    {
                        continue;
                    }

                    // Convert the voxel index to a position.
                    vol->indexToPos(vit.x(), vit.y(), vit.z(), pos);

                    // Create a point and set it to the position of the
                    // voxel.
                    ptOff = gdp->appendPointOffset();
                    gdp->setPos3(ptOff, pos);

                    // Store the value if necessary.
                    if (store)
                    {
                        attr_h.set(ptOff, value);
                    }
                }
            }

            else
            {
                // Get the resolution of the volume.
                vol->getRes(rx, ry, rz);

                // Add points for each voxel.
                ptOff = gdp->appendPointBlock(rx * ry * rz);

                // Iterate over all the voxels.
                for (vit.rewind(); !vit.atEnd(); vit.advance())
                {
                    // Convert the voxel index to a position.
                    vol->indexToPos(vit.x(), vit.y(), vit.z(), pos);

                    // Set the position for the current offset.
                    gdp->setPos3(ptOff, pos);

                    // Get and store the value if necessary.
                    if (store)
                    {
                        value = vit.getValue();
                        attr_h.set(ptOff, value);
                    }

                    // Increment the offset since the block of points we
                    // created is guaranteed to be contiguous.
                    ptOff++;
                }
            }
        }
        // Primitive isn't a volume primitive.
        else
        {
            addError(SOP_MESSAGE, "Not a volume primitive.");
        }
    }
    // Picked a primitive number that is out of range.
    else
    {
        addWarning(SOP_MESSAGE, "Invalid source index. Index out of range.");
    }

    unlockInputs();
    return error();
}
コード例 #10
0
ファイル: qscheck.cpp プロジェクト: aschet/qsaqt5
void QSCheckData::addWarning( const QSNode *node, const QString &msg )
{
    addWarning( node, QSErrGeneral, msg );
}
コード例 #11
0
bool IPLCanvasSize::processInputData(IPLImage* image , int, bool)
{
    // delete previous result
    delete _result;
    _result = NULL;
    int width  = image->width();
    int height = image->height();

    _result = new IPLImage(image->type(), width, height);

    // get properties
    int         new_width   = getProcessPropertyInt("width");
    int         new_height  = getProcessPropertyInt("height");
    IPLColor    color       = getProcessPropertyColor("color");
    int         anchor      = getProcessPropertyInt("anchor");

    _result = new IPLImage(image->type(), new_width, new_height);

    int progress = 0;
    int maxProgress = image->height() * image->getNumberOfPlanes();
    int nrOfPlanes = _result->getNumberOfPlanes();

    //Anchor:Top Left|Top|Top Right|Left|Center|Right|Bottom Left|Bottom|Bottom Right

    // Top Left
    int offset_x = 0;
    int offset_y = 0;
    if(anchor == 1)
    {
        // Top
        offset_x = (new_width-width) * 0.5;
        offset_y = 0;
    }
    else if(anchor == 2)
    {
        // Top Right
        offset_x = new_width-width;
        offset_y = 0;
    }
    else if(anchor == 3)
    {
        // Left
        offset_x = 0;
        offset_y = (new_height-height) * 0.5;
    }
    else if(anchor == 4)
    {
        // Center
        offset_x = (new_width-width) * 0.5;
        offset_y = (new_height-height) * 0.5;
    }
    else if(anchor == 5)
    {
        // Right
        offset_x = new_width-width;
        offset_y = (new_height-height) * 0.5;
    }
    else if(anchor == 6)
    {
        // Bottom Left
        offset_x = 0;
        offset_y = new_height-height;
    }
    else if(anchor == 7)
    {
        // Bottom
        offset_x = (new_width-width) * 0.5;
        offset_y = new_height-height;
    }
    else if(anchor == 8)
    {
        // Bottom Right
        offset_x = new_width-width;
        offset_y = new_height-height;
    }

    if(nrOfPlanes == 1)
    {
        addWarning("For grayscale images, the red slider is used as background value.");
    }

    #pragma omp parallel for
    for( int planeNr=0; planeNr < nrOfPlanes; planeNr++ )
    {
        IPLImagePlane* plane = image->plane( planeNr );
        IPLImagePlane* newplane = _result->plane( planeNr );
        ipl_basetype background = 0.0;

        if(planeNr == 0)
            background = color.red();
        else if(planeNr == 1)
            background = color.green();
        if(planeNr == 2)
            background = color.blue();

        for(int y=0; y<new_height; y++)
        {
            // progress
           notifyProgressEventHandler(100*progress++/maxProgress);

            for(int x=0; x<new_width; x++)
            {
                int from_x = x - offset_x;
                int from_y = y - offset_y;

                // check if inside source image
                if(from_x < 0 || from_y < 0 || from_x > plane->width() || from_y > plane->height())
                {
                    newplane->p(x, y) = background;
                }
                else
                {
                    newplane->p(x, y) = plane->p(from_x, from_y);
                }
            }
        }
    }

    return true;
}
コード例 #12
0
void ProjectExporter::checkWPS(ProjectModel* project, QString file)
{
    /* Set this to false if any resource checks fail */
    bool check = true;

    QSettings settings;
    settings.beginGroup("RBFont");
    QString fontPack = settings.value("fontDir", "").toString() + "/";
    settings.endGroup();

    QString fontDir = project->getSetting("themebase", "") + "/fonts/";
    QString wpsName = file.split("/").last().split(".").first();
    QString imDir = project->getSetting("themebase", "") + "/wps/" + wpsName +
                    "/";

    QFile fin(file.replace("/.rockbox", project->getSetting("themebase", "")));
    if(!fin.open(QFile::ReadOnly | QFile::Text))
    {
        addWarning(tr("Couldn't open ") + file.split("/").last());
    }

    QString contents(fin.readAll());
    fin.close();

    skin_element* root;
    root = skin_parse(contents.toAscii());
    if(!root)
    {
        addWarning(tr("Couldn't parse ") + file.split("/").last());
        return;
    }

    /* Now we scan through the tree to check all the resources */
    /* Outer loop scans through all viewports */
    while(root)
    {
        skin_element* line;
        if(root->children_count == 0)
            line = 0;
        else
            line = root->children[0];

        /* Next loop scans through logical lines */
        while(line)
        {

            /* Innermost loop gives top-level tags */
            skin_element* current;
            if(line->children_count == 0)
                current = 0;
            else
                current = line->children[0];
            while(current)
            {
                if(current->type == TAG)
                {
                    if(QString(current->tag->name) == "Fl")
                    {
                        QString font = current->params[1].data.text;
                        if(!QFile::exists(fontDir + font)
                                && !QFile::exists(fontPack + font))
                        {
                            check = false;
                            addWarning(font + tr(" not found"));
                        }
                    }
                    else if(QString(current->tag->name) == "X")
                    {
                        QString backdrop = current->params[0].data.text;
                        if(!QFile::exists(imDir + backdrop))
                        {
                            check = false;
                            addWarning(backdrop + tr(" not found"));
                        }
                    }
                    else if(QString(current->tag->name) == "xl")
                    {
                        QString image = current->params[1].data.text;
                        if(!QFile::exists(imDir + image))
                        {
                            check = false;
                            addWarning(image + tr(" not found"));
                        }
                    }
                }
                current = current->next;
            }

            line = line->next;
        }

        root = root->next;
    }

    if(check)
        addSuccess(file.split("/").last() + tr(" passed resource check"));
    else
        addWarning(file.split("/").last() + tr(" failed resource check"));

}
コード例 #13
0
ファイル: file_import_export.cpp プロジェクト: kshji/mapper
void Importer::doImport(bool load_symbols_only, const QString& map_path)
{
	import(load_symbols_only);
	
	// Object post processing:
	// - make sure that there is no object without symbol
	// - make sure that all area-only path objects are closed
	// - make sure that there are no special points in wrong places (e.g. curve starts inside curves)
	for (int p = 0; p < map->getNumParts(); ++p)
	{
		MapPart* part = map->getPart(p);
		for (int o = 0; o < part->getNumObjects(); ++o)
		{
			Object* object = part->getObject(o);
			if (object->getSymbol() == NULL)
			{
				addWarning(Importer::tr("Found an object without symbol."));
				if (object->getType() == Object::Point)
					object->setSymbol(map->getUndefinedPoint(), true);
				else if (object->getType() == Object::Path)
					object->setSymbol(map->getUndefinedLine(), true);
				else
				{
					// There is no undefined symbol for this type of object, delete the object
					part->deleteObject(o, false);
					--o;
					continue;
				}
			}
			
			if (object->getType() == Object::Path)
			{
				PathObject* path = object->asPath();
				Symbol::Type contained_types = path->getSymbol()->getContainedTypes();
				if (contained_types & Symbol::Area && !(contained_types & Symbol::Line))
					path->closeAllParts();
				
				for (MapCoordVector::size_type i = 0; i < path->getCoordinateCount(); ++i)
				{
					if (path->getCoordinate(i).isCurveStart())
					{
						if (i+3 >= path->getCoordinateCount())
						{
							path->getCoordinate(i).setCurveStart(false);
							continue;
						}
						
						if (path->getCoordinate(i + 1).isClosePoint() || path->getCoordinate(i + 1).isHolePoint() ||
						    path->getCoordinate(i + 2).isClosePoint() || path->getCoordinate(i + 2).isHolePoint())
						{
							path->getCoordinate(i).setCurveStart(false);
							continue;
						}
						
						path->getCoordinate(i + 1).setCurveStart(false);
						path->getCoordinate(i + 1).setDashPoint(false);
						path->getCoordinate(i + 2).setCurveStart(false);
						path->getCoordinate(i + 2).setDashPoint(false);
						i += 2;
					}
					
					if (i > 0 && path->getCoordinate(i).isHolePoint())
					{
						if (path->getCoordinate(i-1).isHolePoint())
							path->deleteCoordinate(i, false);
					}
				}
			}
		}
	}
	
	// Symbol post processing
	for (int i = 0; i < map->getNumSymbols(); ++i)
	{
		if (!map->getSymbol(i)->loadFinished(map))
			throw FileFormatException(Importer::tr("Error during symbol post-processing."));
	}
	
	// Template loading: try to find all template files
	bool have_lost_template = false;
	for (int i = 0; i < map->getNumTemplates(); ++i)
	{
		Template* temp = map->getTemplate(i);
		
		bool loaded_from_template_dir = false;
		temp->tryToFindAndReloadTemplateFile(map_path, &loaded_from_template_dir);
		if (loaded_from_template_dir)
			addWarning(Importer::tr("Template \"%1\" has been loaded from the map's directory instead of the relative location to the map file where it was previously.").arg(temp->getTemplateFilename()));
		
		if (temp->getTemplateState() != Template::Loaded)
			have_lost_template = true;
	}
	if (have_lost_template)
	{
#if defined(Q_OS_ANDROID)
		addWarning(tr("At least one template file could not be found."));
#else
		addWarning(tr("At least one template file could not be found.") + " " +
		           tr("Click the red template name(s) in the Templates -> Template setup window to locate the template file name(s)."));
#endif
	}
}
コード例 #14
0
/** @brief Combine given list of instruments to one instrument.
 *
 * Takes a list of @a instruments as argument and combines them to one single
 * new @a output instrument. For this task, it will create a dimension of type
 * given by @a mainDimension in the new instrument and copies the source
 * instruments to those dimension zones.
 *
 * @param instruments - (input) list of instruments that shall be combined,
 *                      they will only be read, so they will be left untouched
 * @param gig - (input/output) .gig file where the new combined instrument shall
 *              be created
 * @param output - (output) on success this pointer will be set to the new
 *                 instrument being created
 * @param mainDimension - the dimension that shall be used to combine the
 *                        instruments
 * @throw RIFF::Exception on any kinds of errors
 */
static void combineInstruments(std::vector<gig::Instrument*>& instruments, gig::File* gig, gig::Instrument*& output, gig::dimension_t mainDimension) {
    output = NULL;

    // divide the individual regions to (probably even smaller) groups of
    // regions, coping with the fact that the source regions of the instruments
    // might have quite different range sizes and start and end points
    RegionGroups groups = groupByRegionIntersections(instruments);
    #if DEBUG_COMBINE_INSTRUMENTS
    std::cout << std::endl << "New regions: " << std::flush;
    printRanges(groups);
    std::cout << std::endl;
    #endif

    if (groups.empty())
        throw gig::Exception(_("No regions found to create a new instrument with."));

    // create a new output instrument
    gig::Instrument* outInstr = gig->AddInstrument();
    outInstr->pInfo->Name = _("NEW COMBINATION");

    // Distinguishing in the following code block between 'horizontal' and
    // 'vertical' regions. The 'horizontal' ones are meant to be the key ranges
    // in the output instrument, while the 'vertical' regions are meant to be
    // the set of source regions that shall be layered to that 'horizontal'
    // region / key range. It is important to know, that the key ranges defined
    // in the 'horizontal' and 'vertical' regions might differ.

    // merge the instruments to the new output instrument
    for (RegionGroups::iterator itGroup = groups.begin();
         itGroup != groups.end(); ++itGroup) // iterate over 'horizontal' / target regions ...
    {
        gig::Region* outRgn = outInstr->AddRegion();
        outRgn->SetKeyRange(itGroup->first.low, itGroup->first.high);
        #if DEBUG_COMBINE_INSTRUMENTS
        printf("---> Start target region %d..%d\n", itGroup->first.low, itGroup->first.high);
        #endif

        // detect the total amount of zones required for the given main
        // dimension to build up this combi for current key range
        int iTotalZones = 0;
        for (RegionGroup::iterator itRgn = itGroup->second.begin();
             itRgn != itGroup->second.end(); ++itRgn)
        {
            gig::Region* inRgn = itRgn->second;
            gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
            iTotalZones += (def) ? def->zones : 1;
        }
        #if DEBUG_COMBINE_INSTRUMENTS
        printf("Required total zones: %d, vertical regions: %d\n", iTotalZones, itGroup->second.size());
        #endif

        // create all required dimensions for this output region
        // (except the main dimension used for separating the individual
        // instruments, we create that particular dimension as next step)
        Dimensions dims = getDimensionsForRegionGroup(itGroup->second);
        // the given main dimension which is used to combine the instruments is
        // created separately after the next code block, and the main dimension
        // should not be part of dims here, because it also used for iterating
        // all dimensions zones, which would lead to this dimensions being
        // iterated twice
        dims.erase(mainDimension);
        {
            std::vector<gig::dimension_t> skipTheseDimensions; // used to prevent a misbehavior (i.e. crash) of the combine algorithm in case one of the source instruments has a dimension with only one zone, which is not standard conform

            for (Dimensions::iterator itDim = dims.begin();
                itDim != dims.end(); ++itDim)
            {
                gig::dimension_def_t def;
                def.dimension = itDim->first; // dimension type
                def.zones = itDim->second.size();
                def.bits = zoneCountToBits(def.zones);
                if (def.zones < 2) {
                    addWarning(
                        "Attempt to create dimension with type=0x%x with only "
                        "ONE zone (because at least one of the source "
                        "instruments seems to have such a velocity dimension "
                        "with only ONE zone, which is odd)! Skipping this "
                        "dimension for now.",
                        (int)itDim->first
                    );
                    skipTheseDimensions.push_back(itDim->first);
                    continue;
                }
                #if DEBUG_COMBINE_INSTRUMENTS
                std::cout << "Adding new regular dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
                #endif
                outRgn->AddDimension(&def);
                #if DEBUG_COMBINE_INSTRUMENTS
                std::cout << "OK" << std::endl << std::flush;
                #endif
            }
            // prevent the following dimensions to be processed further below
            // (since the respective dimension was not created above)
            for (int i = 0; i < skipTheseDimensions.size(); ++i)
                dims.erase(skipTheseDimensions[i]);
        }

        // create the main dimension (if necessary for current key range)
        if (iTotalZones > 1) {
            gig::dimension_def_t def;
            def.dimension = mainDimension; // dimension type
            def.zones = iTotalZones;
            def.bits = zoneCountToBits(def.zones);
            #if DEBUG_COMBINE_INSTRUMENTS
            std::cout << "Adding new main combi dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
            #endif
            outRgn->AddDimension(&def);
            #if DEBUG_COMBINE_INSTRUMENTS
            std::cout << "OK" << std::endl << std::flush;
            #endif
        } else {
            dims.erase(mainDimension);
        }

        // for the next task we need to have the current RegionGroup to be
        // sorted by instrument in the same sequence as the 'instruments' vector
        // argument passed to this function (because the std::map behind the
        // 'RegionGroup' type sorts by memory address instead, and that would
        // sometimes lead to the source instruments' region to be sorted into
        // the wrong target layer)
        OrderedRegionGroup currentGroup = sortRegionGroup(itGroup->second, instruments);

        // schedule copying the source dimension regions to the target dimension
        // regions
        CopyAssignSchedule schedule;
        int iDstMainBit = 0;
        for (OrderedRegionGroup::iterator itRgn = currentGroup.begin();
             itRgn != currentGroup.end(); ++itRgn) // iterate over 'vertical' / source regions ...
        {
            gig::Region* inRgn = itRgn->second;
            #if DEBUG_COMBINE_INSTRUMENTS
            printf("[source region of '%s']\n", inRgn->GetParent()->pInfo->Name.c_str());
            #endif

            // determine how many main dimension zones this input region requires
            gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
            const int inRgnMainZones = (def) ? def->zones : 1;

            for (uint iSrcMainBit = 0; iSrcMainBit < inRgnMainZones; ++iSrcMainBit, ++iDstMainBit) {
                scheduleCopyDimensionRegions(
                    outRgn, inRgn, dims, mainDimension,
                    iDstMainBit, iSrcMainBit, &schedule
                );
            }
        }

        // finally copy the scheduled source -> target dimension regions
        for (uint i = 0; i < schedule.size(); ++i) {
            CopyAssignSchedEntry& e = schedule[i];

            // backup the target DimensionRegion's current dimension zones upper
            // limits (because the target DimensionRegion's upper limits are
            // already defined correctly since calling AddDimension(), and the
            // CopyAssign() call next, will overwrite those upper limits
            // unfortunately
            DimensionRegionUpperLimits dstUpperLimits = getDimensionRegionUpperLimits(e.dst);
            DimensionRegionUpperLimits srcUpperLimits = getDimensionRegionUpperLimits(e.src);

            // now actually copy over the current DimensionRegion
            const gig::Region* const origRgn = e.dst->GetParent(); // just for sanity check below
            e.dst->CopyAssign(e.src);
            assert(origRgn == e.dst->GetParent()); // if gigedit is crashing here, then you must update libgig (to at least SVN r2547, v3.3.0.svn10)

            // restore all original dimension zone upper limits except of the
            // velocity dimension, because the velocity dimension zone sizes are
            // allowed to differ for individual DimensionRegions in gig v3
            // format
            //
            // if the main dinension is the 'velocity' dimension, then skip
            // restoring the source's original velocity zone limits, because
            // dealing with merging that is not implemented yet
            // TODO: merge custom velocity splits if main dimension is the velocity dimension (for now equal sized velocity zones are used if mainDim is 'velocity')
            if (srcUpperLimits.count(gig::dimension_velocity) && mainDimension != gig::dimension_velocity) {
                if (!dstUpperLimits.count(gig::dimension_velocity)) {
                    addWarning("Source instrument seems to have a velocity dimension whereas new target instrument doesn't!");
                } else {
                    dstUpperLimits[gig::dimension_velocity] =
                        (e.velocityZone >= e.totalSrcVelocityZones)
                            ? 127 : srcUpperLimits[gig::dimension_velocity];
                }
            }
            restoreDimensionRegionUpperLimits(e.dst, dstUpperLimits);
        }
    }

    // success
    output = outInstr;
}
コード例 #15
0
/** @brief Schedule copying DimensionRegions from source Region to target Region.
 *
 * Schedules copying the entire articulation informations (including sample
 * reference) from all individual DimensionRegions of source Region @a inRgn to
 * target Region @a outRgn. It is expected that the required dimensions (thus
 * the required dimension regions) were already created before calling this
 * function.
 *
 * To be precise, it does the task above only for the dimension zones defined by
 * the three arguments @a mainDim, @a iSrcMainBit, @a iDstMainBit, which reflect
 * a selection which dimension zones shall be copied. All other dimension zones
 * will not be scheduled to be copied by a single call of this function. So this
 * function needs to be called several time in case all dimension regions shall
 * be copied of the entire region (@a inRgn, @a outRgn).
 *
 * @param outRgn - where the dimension regions shall be copied to
 * @param inRgn - all dimension regions that shall be copied from
 * @param dims - precise dimension definitions of target region
 * @param mainDim - this dimension type, in combination with @a iSrcMainBit and
 *                  @a iDstMainBit defines a selection which dimension region
 *                  zones shall be copied by this call of this function
 * @param iDstMainBit - destination bit of @a mainDim
 * @param iSrcMainBit - source bit of @a mainDim
 * @param schedule - list of all DimensionRegion copy operations which is filled
 *                   during the nested loops / recursions of this function call
 * @param dimCase - just for internal purpose (function recursion), don't pass
 *                  anything here, this function will call itself recursively
 *                  will fill this container with concrete dimension values for
 *                  selecting the precise dimension regions during its task
 */
static void scheduleCopyDimensionRegions(gig::Region* outRgn, gig::Region* inRgn,
                                 Dimensions dims, gig::dimension_t mainDim,
                                 int iDstMainBit, int iSrcMainBit,
                                 CopyAssignSchedule* schedule,
                                 DimensionCase dimCase = DimensionCase())
{
    if (dims.empty()) { // reached deepest level of function recursion ...
        CopyAssignSchedEntry e;

        // resolve the respective source & destination DimensionRegion ...        
        uint srcDimValues[8] = {};
        uint dstDimValues[8] = {};
        DimensionCase srcDimCase = dimCase;
        DimensionCase dstDimCase = dimCase;
        srcDimCase[mainDim] = iSrcMainBit;
        dstDimCase[mainDim] = iDstMainBit;

        #if DEBUG_COMBINE_INSTRUMENTS
        printf("-------------------------------\n");
        printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
        #endif

        // first select source & target dimension region with an arbitrary
        // velocity split zone, to get access to the precise individual velocity
        // split zone sizes (if there is actually a velocity dimension at all,
        // otherwise we already select the desired source & target dimension
        // region here)
        #if DEBUG_COMBINE_INSTRUMENTS
        printf("src "); fflush(stdout);
        #endif
        fillDimValues(srcDimValues, srcDimCase, inRgn, false);
        #if DEBUG_COMBINE_INSTRUMENTS
        printf("dst "); fflush(stdout);
        #endif
        fillDimValues(dstDimValues, dstDimCase, outRgn, false);
        gig::DimensionRegion* srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
        gig::DimensionRegion* dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
        #if DEBUG_COMBINE_INSTRUMENTS
        printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
        printf("srcDimRgn=%lx dstDimRgn=%lx\n", (uint64_t)srcDimRgn, (uint64_t)dstDimRgn);
        printf("srcSample='%s' dstSample='%s'\n",
               (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str()),
               (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str())
        );
        #endif

        assert(srcDimRgn->GetParent() == inRgn);
        assert(dstDimRgn->GetParent() == outRgn);

        // now that we have access to the precise velocity split zone upper
        // limits, we can select the actual source & destination dimension
        // regions we need to copy (assuming that source or target region has
        // a velocity dimension)
        if (outRgn->GetDimensionDefinition(gig::dimension_velocity)) {
            // re-select target dimension region (with correct velocity zone)
            DimensionZones dstZones = preciseDimensionZonesFor(gig::dimension_velocity, dstDimRgn);
            assert(dstZones.size() > 1);
            const int iDstZoneIndex =
                (mainDim == gig::dimension_velocity)
                    ? iDstMainBit : dstDimCase[gig::dimension_velocity]; // (mainDim == gig::dimension_velocity) exception case probably unnecessary here
            e.velocityZone = iDstZoneIndex;
            #if DEBUG_COMBINE_INSTRUMENTS
            printf("dst velocity zone: %d/%d\n", iDstZoneIndex, (int)dstZones.size());
            #endif
            assert(uint(iDstZoneIndex) < dstZones.size());
            dstDimCase[gig::dimension_velocity] = dstZones[iDstZoneIndex].low; // arbitrary value between low and high
            #if DEBUG_COMBINE_INSTRUMENTS
            printf("dst velocity value = %d\n", dstDimCase[gig::dimension_velocity]);
            printf("dst refilled "); fflush(stdout);
            #endif
            fillDimValues(dstDimValues, dstDimCase, outRgn, false);
            dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
            #if DEBUG_COMBINE_INSTRUMENTS
            printf("reselected dstDimRgn=%lx\n", (uint64_t)dstDimRgn);
            printf("dstSample='%s'%s\n",
                (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str()),
                (dstDimRgn->pSample ? " <--- ERROR ERROR ERROR !!!!!!!!! " : "")
            );
            #endif

            // re-select source dimension region with correct velocity zone
            // (if it has a velocity dimension that is)
            if (inRgn->GetDimensionDefinition(gig::dimension_velocity)) {
                DimensionZones srcZones = preciseDimensionZonesFor(gig::dimension_velocity, srcDimRgn);
                e.totalSrcVelocityZones = srcZones.size();
                assert(srcZones.size() > 0);
                if (srcZones.size() <= 1) {
                    addWarning("Input region has a velocity dimension with only ONE zone!");
                }
                int iSrcZoneIndex =
                    (mainDim == gig::dimension_velocity)
                        ? iSrcMainBit : iDstZoneIndex;
                if (uint(iSrcZoneIndex) >= srcZones.size())
                    iSrcZoneIndex = srcZones.size() - 1;
                srcDimCase[gig::dimension_velocity] = srcZones[iSrcZoneIndex].low; // same zone as used above for target dimension region (no matter what the precise zone ranges are)
                #if DEBUG_COMBINE_INSTRUMENTS
                printf("src refilled "); fflush(stdout);
                #endif
                fillDimValues(srcDimValues, srcDimCase, inRgn, false);
                srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
                #if DEBUG_COMBINE_INSTRUMENTS
                printf("reselected srcDimRgn=%lx\n", (uint64_t)srcDimRgn);
                printf("srcSample='%s'\n",
                    (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str())
                );
                #endif
            }
        }

        // Schedule copy operation of source -> target DimensionRegion for the
        // time after all nested loops have been traversed. We have to postpone
        // the actual copy operations this way, because otherwise it would
        // overwrite informations inside the destination DimensionRegion object
        // that we need to read in the code block above.
        e.src = srcDimRgn;
        e.dst = dstDimRgn;
        schedule->push_back(e);

        return; // returning from deepest level of function recursion
    }

    // Copying n dimensions requires n nested loops. That's why this function
    // is calling itself recursively to provide the required amount of nested
    // loops. With each call it pops from argument 'dims' and pushes to
    // argument 'dimCase'.

    Dimensions::iterator itDimension = dims.begin();
    gig::dimension_t type = itDimension->first;
    DimensionZones  zones = itDimension->second;
    dims.erase(itDimension);

    int iZone = 0;
    for (DimensionZones::iterator itZone = zones.begin();
         itZone != zones.end(); ++itZone, ++iZone)
    {
        DLS::range_t zoneRange = *itZone;
        gig::dimension_def_t* def = outRgn->GetDimensionDefinition(type);
        dimCase[type] = (def->split_type == gig::split_type_bit) ? iZone : zoneRange.low;

        // recurse until 'dims' is exhausted (and dimCase filled up with concrete value)
        scheduleCopyDimensionRegions(outRgn, inRgn, dims, mainDim, iDstMainBit, iSrcMainBit, schedule, dimCase);
    }
}
コード例 #16
0
ファイル: ExecMsgs.hpp プロジェクト: VaysseB/openfluid
 void addWarning(std::string Sender, openfluid::core::TimeStep_t TimeStep, std::string WarningMsg) { addWarning(Message(Sender,"",TimeStep,WarningMsg)); };
コード例 #17
0
ファイル: ExecMsgs.hpp プロジェクト: VaysseB/openfluid
 void addWarning(std::string Sender, std::string WarningMsg) { addWarning(Message(Sender,"",WarningMsg)); };
コード例 #18
0
ファイル: file_format_native.cpp プロジェクト: sembruk/mapper
void NativeFileImport::import(bool load_symbols_only)
{
    addWarning(Importer::tr("This file uses an obsolete format. "
                            "Support for this format is to be removed from this program soon. "
                            "To be able to open the file in the future, save it again."));

    MapCoord::boundsOffset().reset(true);

    char buffer[4];
    stream->read(buffer, 4); // read the magic

    int version;
    stream->read((char*)&version, sizeof(int));
    if (version < 0)
    {
        addWarning(Importer::tr("Invalid file format version."));
    }
    else if (version < NativeFileFormat::least_supported_file_format_version)
    {
        throw FileFormatException(Importer::tr("Unsupported old file format version. Please use an older program version to load and update the file."));
    }
    else if (version > NativeFileFormat::current_file_format_version)
    {
        throw FileFormatException(Importer::tr("Unsupported new file format version. Some map features will not be loaded or saved by this version of the program. Consider updating."));
    }

    if (version <= 16)
	{
		Georeferencing georef;
		stream->read((char*)&georef.scale_denominator, sizeof(int));
		
		if (version >= 15)
			loadString(stream, map->map_notes);
		
		bool gps_projection_params_set; // obsolete
		stream->read((char*)&gps_projection_params_set, sizeof(bool));
		GPSProjectionParameters gps_projection_parameters; // obsolete
		stream->read((char*)&gps_projection_parameters, sizeof(GPSProjectionParameters));
		if (gps_projection_params_set)
		{
			LatLon ref_point = LatLon::fromRadiant(gps_projection_parameters.center_latitude, gps_projection_parameters.center_longitude);
			georef.setGeographicRefPoint(ref_point);
		}
		*map->georeferencing = georef;
	}
	else if (version >= 17)
	{
		loadString(stream, map->map_notes);
		
		Georeferencing georef;
		stream->read((char*)&georef.scale_denominator, sizeof(int));
		double value;
		if (version >= 18)
		{
			stream->read((char*)&value, sizeof(double));
			georef.declination = Georeferencing::roundDeclination(value);
		}
		stream->read((char*)&value, sizeof(double));
		georef.grivation = Georeferencing::roundDeclination(value);
		georef.grivation_error = value - georef.grivation;
		
		double x,y;
		stream->read((char*)&x, sizeof(double));
		stream->read((char*)&y, sizeof(double));
		georef.map_ref_point = MapCoord(x,y);
		stream->read((char*)&x, sizeof(double));
		stream->read((char*)&y, sizeof(double));
		georef.projected_ref_point = QPointF(x,y);
		loadString(stream, georef.projected_crs_id);
		loadString(stream, georef.projected_crs_spec);
		stream->read((char*)&y, sizeof(double));
		stream->read((char*)&x, sizeof(double));
		georef.geographic_ref_point = LatLon::fromRadiant(y, x); 
		QString geographic_crs_id, geographic_crs_spec;
		loadString(stream, geographic_crs_id);   // reserved for geographic crs id
		loadString(stream, geographic_crs_spec); // reserved for full geographic crs specification
		if (geographic_crs_spec != Georeferencing::geographic_crs_spec)
		{
			addWarning(
			  Importer::tr("The geographic coordinate reference system of the map was \"%1\". This CRS is not supported. Using \"%2\".").
			  arg(geographic_crs_spec).
			  arg(Georeferencing::geographic_crs_spec)
			);
		}
		if (version <= 17)
			georef.initDeclination();
		// Correctly set georeferencing state
		georef.setProjectedCRS(georef.projected_crs_id, georef.projected_crs_spec);
		*map->georeferencing = georef;
	}
	
	if (version >= 24)
		map->setGrid(MapGrid().load(stream, version));
	
	map->renderable_options = Symbol::RenderNormal;
	if (version >= 25)
	{
		bool area_hatching_enabled, baseline_view_enabled;
		stream->read((char*)&area_hatching_enabled, sizeof(bool));
		stream->read((char*)&baseline_view_enabled, sizeof(bool));
		if (area_hatching_enabled)
			map->renderable_options |= Symbol::RenderAreasHatched;
		if (baseline_view_enabled)
			map->renderable_options |= Symbol::RenderBaselines;
	}
	
	if (version >= 6)
	{
		bool print_params_set;
		stream->read((char*)&print_params_set, sizeof(bool));
		if (print_params_set)
		{
			MapPrinterConfig printer_config(*map);
			stream->read((char*)&printer_config.page_format.orientation, sizeof(int));
			stream->read((char*)&printer_config.page_format.paper_size, sizeof(int));
			
			float resolution;
			stream->read((char*)&resolution, sizeof(float));
			printer_config.options.resolution = qRound(resolution);
			stream->read((char*)&printer_config.options.show_templates, sizeof(bool));
			if (version >= 24)
				stream->read((char*)&printer_config.options.show_grid, sizeof(bool));
			else
				printer_config.options.show_grid = false;
			
			stream->read((char*)&printer_config.center_print_area, sizeof(bool));
			
			float print_area_left, print_area_top, print_area_width, print_area_height;
			stream->read((char*)&print_area_left, sizeof(float));
			stream->read((char*)&print_area_top, sizeof(float));
			stream->read((char*)&print_area_width, sizeof(float));
			stream->read((char*)&print_area_height, sizeof(float));
			printer_config.print_area = QRectF(print_area_left, print_area_top, print_area_width, print_area_height);
			
			if (version >= 26)
			{
				bool print_different_scale_enabled;
				stream->read((char*)&print_different_scale_enabled, sizeof(bool));
				stream->read((char*)&printer_config.options.scale, sizeof(int));
				if (!print_different_scale_enabled)
					printer_config.options.scale = map->getScaleDenominator();
			}
			map->setPrinterConfig(printer_config);
		}
	}
	
    if (version >= 16)
	{
		stream->read((char*)&map->image_template_use_meters_per_pixel, sizeof(bool));
		stream->read((char*)&map->image_template_meters_per_pixel, sizeof(double));
		stream->read((char*)&map->image_template_dpi, sizeof(double));
		stream->read((char*)&map->image_template_scale, sizeof(double));
	}

    // Load colors
    int num_colors;
    stream->read((char*)&num_colors, sizeof(int));
    map->color_set->colors.resize(num_colors);

    for (int i = 0; i < num_colors; ++i)
    {
        int priority;
        stream->read((char*)&priority, sizeof(int));
        MapColor* color = new MapColor(priority);

        MapColorCmyk cmyk;
        stream->read((char*)&cmyk.c, sizeof(float));
        stream->read((char*)&cmyk.m, sizeof(float));
        stream->read((char*)&cmyk.y, sizeof(float));
        stream->read((char*)&cmyk.k, sizeof(float));
        color->setCmyk(cmyk);
        float opacity;
        stream->read((char*)&opacity, sizeof(float));
        color->setOpacity(opacity);

        QString name;
        loadString(stream, name);
        color->setName(name);

        map->color_set->colors[i] = color;
    }

    // Load symbols
    int num_symbols;
    stream->read((char*)&num_symbols, sizeof(int));
    map->symbols.resize(num_symbols);

    for (int i = 0; i < num_symbols; ++i)
    {
        QScopedValueRollback<MapCoord::BoundsOffset> offset { MapCoord::boundsOffset() };
        MapCoord::boundsOffset().reset(false);

        int symbol_type;
        stream->read((char*)&symbol_type, sizeof(int));

        Symbol* symbol = Symbol::getSymbolForType(static_cast<Symbol::Type>(symbol_type));
        if (!symbol)
        {
            throw FileFormatException(Importer::tr("Error while loading a symbol with type %2.").arg(symbol_type));
        }

        if (!symbol->load(stream, version, map))
        {
            throw FileFormatException(Importer::tr("Error while loading a symbol."));
        }
        map->symbols[i] = symbol;
    }

    if (!load_symbols_only)
	{
		// Load templates
		stream->read((char*)&map->first_front_template, sizeof(int));

		int num_templates;
		stream->read((char*)&num_templates, sizeof(int));
		map->templates.resize(num_templates);

		for (int i = 0; i < num_templates; ++i)
		{
			QString path;
			loadString(stream, path);
			auto temp = Template::templateForFile(path, map);
			if (!temp)
				temp.reset(new TemplateImage(path, map)); // fallback
			
			if (version >= 27)
			{
				loadString(stream, path);
				temp->setTemplateRelativePath(path);
			}
			
			temp->loadTemplateConfiguration(stream, version);

			map->templates[i] = temp.release();
		}
		
		if (version >= 28)
		{
			int num_closed_templates;
			stream->read((char*)&num_closed_templates, sizeof(int));
			map->closed_templates.resize(num_closed_templates);
			
			for (int i = 0; i < num_closed_templates; ++i)
			{
				QString path;
				loadString(stream, path);
				auto temp = Template::templateForFile(path, map);
				if (!temp)
					temp.reset(new TemplateImage(path, map)); // fallback
				
				loadString(stream, path);
				temp->setTemplateRelativePath(path);
				
				temp->loadTemplateConfiguration(stream, version);
				
				map->closed_templates[i] = temp.release();
			}
		}

		// Restore widgets and views
		if (view)
		{
			view->load(stream, version);
		}
		else
		{
			MapView tmp{ map };
			tmp.load(stream, version);
		}

		// Load undo steps
		if (version >= 7)
		{
			if (!map->undoManager().load(stream, version))
			{
				throw FileFormatException(Importer::tr("Error while loading undo steps."));
			}
		}

		// Load parts
		stream->read((char*)&map->current_part_index, sizeof(int));

		int num_parts;
		if (stream->read((char*)&num_parts, sizeof(int)) < (int)sizeof(int))
		{
			throw FileFormatException(Importer::tr("Error while reading map part count."));
		}
		delete map->parts[0];
		map->parts.resize(num_parts);

		for (int i = 0; i < num_parts; ++i)
		{
			MapPart* part = new MapPart({}, map);
			if (!part->load(stream, version, map))
			{
				throw FileFormatException(Importer::tr("Error while loading map part %2.").arg(i+1));
			}
			map->parts[i] = part;
		}
	}
	
	emit map->currentMapPartIndexChanged(map->current_part_index);
	emit map->currentMapPartChanged(map->getPart(map->current_part_index));
}