bool loadDictionaryFromFile( const std::string& filename, ghoul::Dictionary& dictionary, lua_State* state ) { const static std::string _loggerCat = "lua_loadDictionaryFromFile"; if (state == nullptr) { if (_state == nullptr) { LDEBUG("Creating Lua state"); _state = luaL_newstate(); if (_state == nullptr) { LFATAL("Error creating new Lua state: Memory allocation error"); return false; } LDEBUG("Open libraries"); luaL_openlibs(_state); } state = _state; } if (filename.empty()) { LERROR("Filename was empty"); return false; } if (!FileSys.fileExists(absPath(filename))) { LERROR("File '" << absPath(filename) << "' did not exist"); return false; } LDEBUG("Loading dictionary script '" << filename << "'"); int status = luaL_loadfile(state, absPath(filename).c_str()); if (status != LUA_OK) { LERROR("Error loading script: '" << lua_tostring(state, -1) << "'"); return false; } LDEBUG("Executing script"); if (lua_pcall(state, 0, LUA_MULTRET, 0)) { LERROR("Error executing script: " << lua_tostring(state, -1)); return false; } if (lua_isnil(state, -1)) { LERROR("Error in script: '" << filename << "'. Script did not return anything."); return false; } if (!lua_istable(state, -1)) { LERROR("Error in script: '" << filename << "'. Script did not return a table."); return false; } luaDictionaryFromState(state, dictionary); // Clean up after ourselves by cleaning the stack lua_settop(state, 0); return true; }
/* * write information about an global declared/defined symbol * with storage class extern * * informations about function definitions are written in outfdef(), * not here */ void outsym(sym_t *sym, scl_t sc, def_t def) { /* * Static function declarations must also be written to the output * file. Compatibility of function declarations (for both static * and extern functions) must be checked in lint2. Lint1 can't do * this, especially not, if functions are declared at block level * before their first declaration at level 0. */ if (sc != EXTERN && !(sc == STATIC && sym->s_type->t_tspec == FUNC)) return; /* reset buffer */ outclr(); /* * line number of .c source, 'd' for declaration, Id of current * source (.c or .h), and line in current source. */ outint(csrc_pos.p_line); outchar('d'); outint(getfnid(sym->s_dpos.p_file)); outchar('.'); outint(sym->s_dpos.p_line); /* flags */ switch (def) { case DEF: /* defined */ outchar('d'); break; case TDEF: /* tentative defined */ outchar('t'); break; case DECL: /* declared */ outchar('e'); break; default: LERROR("outsym()"); } if (llibflg && def != DECL) { /* * mark it as used so we get no warnings from lint2 about * unused symbols in libraries. */ outchar('u'); } if (sc == STATIC) outchar('s'); /* name of the symbol */ outname(sym->s_name); /* renamed name of symbol, if necessary */ if (sym->s_rename) { outchar('r'); outname(sym->s_rename); } /* type of the symbol */ outtype(sym->s_type); }
/* * Write type into the output buffer. * The type is written as a sequence of substrings, each of which describes a * node of type type_t * a node is coded as follows: * _Bool B * _Complex float s X * _Complex double X * _Complex long double l X * char C * signed char s C * unsigned char u C * short S * unsigned short u S * int I * unsigned int u I * long L * unsigned long u L * long long Q * unsigned long long u Q * float s D * double D * long double l D * void V * * P * [n] A n * () F * (void) F 0 * (n arguments) F n arg1 arg2 ... argn * (n arguments, ...) F n arg1 arg2 ... argn-1 E * (a, b, c, ...) f n arg1 arg2 ... * enum tag e T tag_or_typename * struct tag s T tag_or_typename * union tag u T tag_or_typename * * tag_or_typename 0 no tag or type name * 1 n tag Tag * 2 n typename only type name * * spaces are only for better readability * additionaly it is possible to prepend the characters 'c' (for const) * and 'v' (for volatile) */ void outtype(type_t *tp) { int t, s, na; sym_t *arg; tspec_t ts; while (tp != NULL) { if ((ts = tp->t_tspec) == INT && tp->t_isenum) ts = ENUM; switch (ts) { case BOOL: t = 'B'; s = '\0'; break; case CHAR: t = 'C'; s = '\0'; break; case SCHAR: t = 'C'; s = 's'; break; case UCHAR: t = 'C'; s = 'u'; break; case SHORT: t = 'S'; s = '\0'; break; case USHORT: t = 'S'; s = 'u'; break; case INT: t = 'I'; s = '\0'; break; case UINT: t = 'I'; s = 'u'; break; case LONG: t = 'L'; s = '\0'; break; case ULONG: t = 'L'; s = 'u'; break; case QUAD: t = 'Q'; s = '\0'; break; case UQUAD: t = 'Q'; s = 'u'; break; case FLOAT: t = 'D'; s = 's'; break; case DOUBLE: t = 'D'; s = '\0'; break; case LDOUBLE: t = 'D'; s = 'l'; break; case VOID: t = 'V'; s = '\0'; break; case PTR: t = 'P'; s = '\0'; break; case ARRAY: t = 'A'; s = '\0'; break; case FUNC: t = 'F'; s = '\0'; break; case ENUM: t = 'T'; s = 'e'; break; case STRUCT: t = 'T'; s = 's'; break; case UNION: t = 'T'; s = 'u'; break; case FCOMPLEX: t = 'X'; s = 's'; break; case DCOMPLEX: t = 'X'; s = '\0'; break; case LCOMPLEX: t = 'X'; s = 'l'; break; default: LERROR("outtyp()"); } if (tp->t_const) outchar('c'); if (tp->t_volatile) outchar('v'); if (s != '\0') outchar(s); outchar(t); if (ts == ARRAY) { outint(tp->t_dim); } else if (ts == ENUM) { outtt(tp->t_enum->etag, tp->t_enum->etdef); } else if (ts == STRUCT || ts == UNION) { outtt(tp->t_str->stag, tp->t_str->stdef); } else if (ts == FUNC && tp->t_proto) { na = 0; for (arg = tp->t_args; arg != NULL; arg = arg->s_nxt) na++; if (tp->t_vararg) na++; outint(na); for (arg = tp->t_args; arg != NULL; arg = arg->s_nxt) outtype(arg->s_type); if (tp->t_vararg) outchar('E'); } tp = tp->t_subt; } }
void ItkReader::ReadImageDirect(DataContainer& data) { typedef itk::ImageIOBase::IOComponentType ScalarPixelType; itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(p_url.getValue().c_str(), itk::ImageIOFactory::ReadMode); if (imageIO.IsNotNull()) { WeaklyTypedPointer wtp; imageIO->SetFileName(p_url.getValue()); imageIO->ReadImageInformation(); const ScalarPixelType pixelType = imageIO->GetComponentType(); const size_t numDimensions = imageIO->GetNumberOfDimensions(); LDEBUG("Reading Image with Reader " << imageIO->GetNameOfClass()); LDEBUG("Pixel Type is " << imageIO->GetComponentTypeAsString(pixelType)); LDEBUG("numDimensions: " << numDimensions); if (numDimensions > 3) { LERROR("Error: Dimensions higher than 3 not supported!"); return; } itk::ImageIORegion ioRegion(numDimensions); itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize(); cgt::vec3 imageOffset(0.f); cgt::vec3 voxelSize(1.f); cgt::ivec3 size_i(1); //we assured above that numDimensions is < 3 for (int i = 0; i < static_cast<int>(numDimensions); i++) { size_i[i] = imageIO->GetDimensions(i); imageOffset[i] = imageIO->GetOrigin(i); voxelSize[i] = imageIO->GetSpacing(i); ioStart[i] = 0; ioSize[i] = size_i[i]; } cgt::svec3 size(size_i); size_t dimensionality = (size_i[2] == 1) ? ((size_i[1] == 1) ? 1 : 2) : 3; LDEBUG("Image Size is " << size); LDEBUG("Voxel Size is " << voxelSize); LDEBUG("Image Offset is " << imageOffset); LDEBUG("component size: " << imageIO->GetComponentSize()); LDEBUG("components: " << imageIO->GetNumberOfComponents()); LDEBUG("pixel type (string): " << imageIO->GetPixelTypeAsString(imageIO->GetPixelType())); // 'vector' LDEBUG("pixel type: " << imageIO->GetPixelType()); // '5' switch (pixelType) { case itk::ImageIOBase::CHAR: wtp._baseType = WeaklyTypedPointer::INT8; break; case itk::ImageIOBase::UCHAR: wtp._baseType = WeaklyTypedPointer::UINT8; break; case itk::ImageIOBase::SHORT: wtp._baseType = WeaklyTypedPointer::INT16; break; case itk::ImageIOBase::USHORT: wtp._baseType = WeaklyTypedPointer::UINT16; break; case itk::ImageIOBase::INT: wtp._baseType = WeaklyTypedPointer::INT32; break; case itk::ImageIOBase::UINT: wtp._baseType = WeaklyTypedPointer::UINT32; break; case itk::ImageIOBase::DOUBLE: LWARNING("Pixel Type is DOUBLE. Conversion to float may result in loss of precision!"); case itk::ImageIOBase::FLOAT: wtp._baseType = WeaklyTypedPointer::FLOAT; break; default: LERROR("Error while loading ITK image: unsupported type: " << pixelType); return; } wtp._numChannels = imageIO->GetNumberOfComponents(); //Setup the image region to read ioRegion.SetIndex(ioStart); ioRegion.SetSize(ioSize); imageIO->SetIORegion(ioRegion); if (pixelType != itk::ImageIOBase::DOUBLE) { //Finally, allocate buffer and read the image data wtp._pointer = new uint8_t[imageIO->GetImageSizeInBytes()]; imageIO->Read(wtp._pointer); } else { //convert float volume to double volume double * inputBuf = new double[imageIO->GetImageSizeInComponents()]; wtp._pointer = new uint8_t[imageIO->GetImageSizeInComponents() * sizeof(float)]; imageIO->Read(inputBuf); double * dptr = inputBuf; float * fptr = static_cast<float*>(wtp._pointer); for (int i = 0, s = imageIO->GetImageSizeInComponents(); i < s; ++i) { *fptr = *dptr; fptr++; dptr++; } delete[] inputBuf; } ImageData* image = new ImageData(dimensionality, size, wtp._numChannels); ImageRepresentationLocal::create(image, wtp); image->setMappingInformation(ImageMappingInformation(size, imageOffset/* + p_imageOffset.getValue()*/, voxelSize /** p_voxelSize.getValue()*/)); data.addData(p_targetImageID.getValue(), image); } else { LWARNING("Unable to create ImageIO Instance; No suitable reader found!"); } }
static int do_anyka_write(struct fsg_dev *fsg) { struct lun *curlun = fsg->curlun; struct fsg_buffhd *bh; int get_some_more; u32 amount_left_to_req, amount_left_to_write; loff_t file_offset; unsigned int amount; ssize_t nwritten; int rc; /* Carry out the file writes */ get_some_more = 1; file_offset = 0; amount_left_to_req = amount_left_to_write = fsg->data_size_from_cmnd; while (amount_left_to_write > 0) { /* Queue a request for more data from the host */ bh = fsg->next_buffhd_to_fill; if (bh->state == BUF_STATE_EMPTY && get_some_more) { amount = min(amount_left_to_req, mod_data.buflen); /* Get the next buffer */ fsg->usb_amount_left -= amount; amount_left_to_req -= amount; if (amount_left_to_req == 0) get_some_more = 0; /* amount is always divisible by 512, hence by * the bulk-out maxpacket size */ bh->outreq->length = bh->bulk_out_intended_length = amount; bh->outreq->short_not_ok = 1; start_transfer(fsg, fsg->bulk_out, bh->outreq, &bh->outreq_busy, &bh->state); fsg->next_buffhd_to_fill = bh->next; continue; } /* Write the received data to the backing file */ bh = fsg->next_buffhd_to_drain; if (bh->state == BUF_STATE_EMPTY && !get_some_more) break; // We stopped early if (bh->state == BUF_STATE_FULL) { smp_rmb(); fsg->next_buffhd_to_drain = bh->next; bh->state = BUF_STATE_EMPTY; /* Did something go wrong with the transfer? */ if (bh->outreq->status != 0) { curlun->sense_data = SS_COMMUNICATION_FAILURE; // curlun->sense_data_info = file_offset >> 9; curlun->info_valid = 1; break; } amount = bh->outreq->actual; if (fsg->data_size_from_cmnd - file_offset < amount) { LERROR(curlun, "write %u @ %llu beyond end %llu\n", amount, (unsigned long long) file_offset, (unsigned long long) curlun->file_length); amount = curlun->file_length - file_offset; } /* Perform the write */ nwritten = 0; nwritten = usbburn_write(bh->buf + nwritten, amount); file_offset += nwritten; amount_left_to_write -= nwritten; fsg->residue -= nwritten; /* Did the host decide to stop early? */ if (bh->outreq->actual != bh->outreq->length) { fsg->short_packet_received = 1; break; } continue; } /* Wait for something to happen */ rc = sleep_thread(fsg); if (rc) return rc; } return -EIO; // No default reply }
inline void init_param_options ( int argc, const char* argv[], po::variables_map *vm ) { try { po::options_description desc ( "Command-line/configuration file options" ); initAllCreateSSGrammarOptions (desc); // All createssgrammar options are used initCommonApplylmOptions (desc); // Add generic language model options desc.add_options() ( HifstConstants::kServerEnable.c_str() , po::value<std::string>()->default_value ( "no" ) , "Run in server mode (yes|no)" ) ( HifstConstants::kServerPort.c_str() , po::value<short>()->default_value ( 1209 ) , "Server port" ) ( HifstConstants::kTargetStore.c_str() , po::value<std::string>()->default_value ( "-" ) , "Source text file -- this option is ignored in server mode" ) ( HifstConstants::kFeatureweights.c_str() , po::value<std::string>()->default_value ( "" ) , "Feature weights applied in hifst. This is a comma-separated sequence " "of language model(s) and grammar feature weights.\n" "IMPORTANT: If this option is not empty string, then it will override " "any values in lm.featureweights and grammar.featureweights" ) ( HifstConstants::kReferencefilterLoad.c_str() , po::value<std::string>()->default_value ( "" ) , "Reference lattice to filter the translation" ) ( HifstConstants::kReferencefilterWrite.c_str() , po::value<std::string>()->default_value ( "" ) , "Write reference lattice" ) ( HifstConstants::kReferencefilterSubstring.c_str() , po::value<std::string>()->default_value ( "yes" ) , "Substring the reference lattice (yes|no)" ) ( HifstConstants::kReferencefilterPrunereferenceweight.c_str() , po::value<float>()->default_value ( std::numeric_limits<float>::max() ) , "Likelihood beam to prune the reference lattice" ) ( HifstConstants::kReferencefilterPrunereferenceshortestpath.c_str() , po::value<unsigned>()->default_value ( std::numeric_limits<unsigned>::max() ) ) ( HifstConstants::kCykparserHrmaxheight.c_str() , po::value<unsigned>()->default_value ( 10 ) , "Default maximum span for hierarchical rules" ) ( HifstConstants::kCykparserHmax.c_str() , po::value<std::string>()->default_value ( "" ) , "Maximum span for individual non-terminals, constrained to hrmaxheight : e.g. X,10,V,6" ) ( HifstConstants::kCykparserHmin.c_str() , po::value<std::string>()->default_value ( "" ) , "Minimum span for individual non-terminals, constrained to hrmaxheight: e.g. X,3,V,2" ) ( HifstConstants::kCykparserNtexceptionsmaxspan.c_str() , po::value<std::string>()->default_value ( "S" ) , "List of non-terminals not affected by cykparser.hrmaxheight. S should always be in this list!" ) ( HifstConstants::kHifstLatticeStore.c_str() , po::value<std::string>()->default_value ( "" ) , "Store hifst translation lattice" ) ( HifstConstants::kHifstAlilatsmode.c_str() , po::value<std::string>()->default_value ( "no" ) , "Include derivations in the left side of transducers (yes|no)" ) ( HifstConstants::kHifstUsepdt.c_str() , po::value<std::string>()->default_value ( "no" ) , "Run hifst using pdt representation, aka hipdt (yes|no)" ) ( HifstConstants::kHifstRtnopt.c_str() , po::value<std::string>()->default_value ( "yes" ) , " Use openfst rtn optimizations (yes|no)" ) ( HifstConstants::kHifstOptimizecells.c_str() , po::value<std::string>()->default_value ( "yes" ) , "Determinize/minimize any FSA component of the RTN (yes|no)" ) ( HifstConstants::kHifstReplacefstbyarcNonterminals.c_str() , po::value<std::string>()->default_value ( "" ) , "Determine which cell fsts are always replaced by single arc according to its non-terminals, e.g: replacefstbyarc=X,V" ) ( HifstConstants::kHifstReplacefstbyarcNumstates.c_str() , po::value<unsigned>()->default_value ( 4 ) , "Determine the minimum number of states that triggers replacement by arc." ) ( HifstConstants::kHifstReplacefstbyarcExceptions.c_str() , po::value<std::string>()->default_value ( "S" ) , "Categories that will definitely not be replaced (takes over replacefstbyarc and replacefstbyarc.numstates)" ) ( HifstConstants::kHifstLocalpruneEnable.c_str() , po::value<std::string>()->default_value ( "no" ) , "Apply local pruning strategy based con cyk cells and number of states (yes|no)" ) ( HifstConstants::kHifstLocalpruneLmLoad.c_str() , po::value<std::string>()->default_value ( "" ) , "Load one or more language model files: (gzipped) arpa format or kenlm binary format (uses memory mapping); separated by commas" ) ( HifstConstants::kHifstLocalpruneLmFeatureweights.c_str() , po::value<std::string>()->default_value ( "1.0" ) , "Scaling factor(s) applied to the language model: arpa_weight * -log(10) * gscale. Scales separated by commas." ) ( HifstConstants::kHifstLocalpruneLmWordpenalty.c_str() , po::value<std::string>()->default_value ( "0.0" ) , "Word penalty applied along the language models (separated by commas). Assumed as 0 if not specified " ) ( HifstConstants::kHifstLocalpruneNumstates.c_str() , po::value<unsigned>()->default_value ( 10000 ) , "Maximum number of states threshold after cell pruning an FSA, If beneath the threshold, determinization/minimization is applied to pruned lattice. Also applicable in alignment mode when filtering against substring acceptor. ") ( HifstConstants::kHifstLocalpruneConditions.c_str() , po::value<std::string>()->default_value ( "" ) , "Local pruning conditions. These are sequences of 4-tuples separated by commas: category,span,number_of_states,weight. The three first are actual thresholds that trigger local pruning, whereas the weight is the likelihood beam for pruning, IF a language model has been applied." ) ( HifstConstants::kHifstPrune.c_str() , po::value<float>()->default_value ( std::numeric_limits<float>::max() ) , "Likelihood beam to prune the translation lattice. Only applied IF a language model is available." ) ( HifstConstants::kHifstWritertn.c_str() , po::value<std::string>()->default_value ( "") , "Write the rtn to disk -- long list of FSAs. Use %%rtn_label%% and ? to format file names appropriately, e.g. --hifst.writertn=rtn/?/%%rtn_label%%.fst" ) ( HifstConstants::kRecaserLmLoad.c_str() , po::value<std::string>()->default_value ( "" ) , "Language model for recasing" ) ( HifstConstants::kRecaserLmFeatureweight.c_str() , po::value<std::string>()->default_value ( "1.0" ) , "Scaling factor applied to the language model" ) ( HifstConstants::kRecaserUnimapLoad.c_str() , po::value<std::string>()->default_value ( "" ) , "unigram transduction model " ) ( HifstConstants::kRecaserUnimapWeight.c_str() , po::value<float>()->default_value ( 1.0f ) , "Scaling factors applied to the unigram model " ) ( HifstConstants::kRecaserPrune.c_str() , po::value<std::string>()->default_value ( "byshortestpath,1" ) , "Choose between byshortestpath,numpaths or byweight,weight" ) ( HifstConstants::kRecaserOutput.c_str() , po::value<std::string>()->default_value ("") , "Output true cased lattice" ) ( HifstConstants::kPostproWordmapLoad.c_str() , po::value<std::string>()->default_value ( "" ) , "Load a reverse integer mapping file so the decoder can map integers to target words" ) ( HifstConstants::kPostproDetokenizeEnable.c_str() , po::value<std::string>()->default_value ( "no" ) , "Detokenize translated 1best (yes|no) -- NOT IMPLEMENTED!" ) ( HifstConstants::kPostproDetokenizeLanguage.c_str() , po::value<std::string>()->default_value ( "" ), "NOT IMPLEMENTED" ) ( HifstConstants::kPostproCapitalizefirstwordEnable.c_str() , po::value<std::string>()->default_value ( "no" ) , "Capitalize first word (yes|no). Only applies if previously mapped back to words (postpro.wordmap.load)" ) ( HifstConstants::kStatsHifstWrite.c_str() , po::value<std::string>()->default_value ( "" ) , "Dump hifst-specific stats (cyk, local pruning, etc)" ) ( HifstConstants::kStatsHifstCykgridEnable.c_str() , po::value<std::string>()->default_value ( "no" ) , "Write cyk/rtn stats to the file (yes|no)" ) ( HifstConstants::kStatsHifstCykgridCellwidth.c_str() , po::value<unsigned>()->default_value ( 30 ) , "Width of the printed cyk cell" ) ( HifstConstants::kStatsWrite.c_str() , po::value<std::string>()->default_value ( "" ) , "Dump general stats (speed and general messages)" ) ; parseOptionsGeneric (desc, vm, argc, argv); checkCreateSSGrammarOptions (vm); if ( (*vm) [HifstConstants::kPatternstoinstancesMaxspan.c_str() ].as<unsigned>() < (*vm) [ HifstConstants::kCykparserHrmaxheight.c_str()].as<unsigned>() ) { LERROR ( HifstConstants::kPatternstoinstancesMaxspan << " cannot be smaller than " << HifstConstants::kCykparserHrmaxheight); exit (EXIT_FAILURE ); } if ( (*vm) [HifstConstants::kFeatureweights.c_str()].as<std::string>() != "" && ( (*vm) [HifstConstants::kLmFeatureweights.c_str()].as<std::string>() != "" || (*vm) [HifstConstants::kGrammarFeatureweights.c_str()].as<std::string>() != "" ) ) { LWARN ("Program option featureweights OVERRIDES grammar.featureweights and lm.featureweights!!"); } } catch ( std::exception& e ) { cerr << "error: " << e.what() << "\n"; exit ( EXIT_FAILURE ); } catch ( ... ) { cerr << "Exception of unknown type!\n"; exit ( EXIT_FAILURE ); } LINFO ( "Configuration loaded" ); };
void ItkReader::ReadImageSeries(DataContainer& data) { typedef itk::ImageIOBase::IOComponentType ScalarPixelType; std::vector<std::string> imageFileNames = GetImageFileNames(); if (!imageFileNames.size()) return; itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO(imageFileNames[0].c_str(), itk::ImageIOFactory::ReadMode); const int numSlices = imageFileNames.size(); if (imageIO.IsNotNull()) { WeaklyTypedPointer wtp; imageIO->SetFileName(imageFileNames[0]); imageIO->ReadImageInformation(); const ScalarPixelType pixelType = imageIO->GetComponentType(); const size_t numDimensions = imageIO->GetNumberOfDimensions(); LDEBUG("Reading Image with Reader " << imageIO->GetNameOfClass()); LDEBUG("Pixel Type is " << imageIO->GetComponentTypeAsString(pixelType)); LDEBUG("numDimensions: " << numDimensions); if (numDimensions > 3) { LERROR("Error: Dimensions higher than 3 not supported!"); return; } itk::ImageIORegion ioRegion(numDimensions); itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize(); cgt::vec3 imageOffset(0.f); cgt::vec3 voxelSize(1.f); cgt::ivec3 size_i(1); //we assured above that numDimensions is < 3 for (int i = 0; i < static_cast<int>(numDimensions); i++) { size_i[i] = imageIO->GetDimensions(i); imageOffset[i] = imageIO->GetOrigin(i); voxelSize[i] = imageIO->GetSpacing(i); ioStart[i] = 0; ioSize[i] = size_i[i]; } cgt::svec3 size(size_i); size_t dimensionality = (size_i[2] == 1) ? ((size_i[1] == 1) ? 1 : 2) : 3; if (dimensionality > 2) { LERROR("Error: Cannot load image series with more than two dimensions!"); return; } LDEBUG("Image Size is " << size); LDEBUG("Voxel Size is " << voxelSize); LDEBUG("Image Offset is " << imageOffset); LDEBUG("component size: " << imageIO->GetComponentSize()); LDEBUG("components: " << imageIO->GetNumberOfComponents()); LDEBUG("pixel type (string): " << imageIO->GetPixelTypeAsString(imageIO->GetPixelType())); LDEBUG("pixel type: " << imageIO->GetPixelType()); switch (pixelType) { case itk::ImageIOBase::CHAR: wtp._baseType = WeaklyTypedPointer::INT8; break; case itk::ImageIOBase::UCHAR: wtp._baseType = WeaklyTypedPointer::UINT8; break; case itk::ImageIOBase::SHORT: wtp._baseType = WeaklyTypedPointer::INT16; break; case itk::ImageIOBase::USHORT: wtp._baseType = WeaklyTypedPointer::UINT16; break; case itk::ImageIOBase::INT: wtp._baseType = WeaklyTypedPointer::INT32; break; case itk::ImageIOBase::UINT: wtp._baseType = WeaklyTypedPointer::UINT32; break; case itk::ImageIOBase::DOUBLE: LWARNING("Pixel Type is DOUBLE. Conversion to float may result in loss of precision!"); case itk::ImageIOBase::FLOAT: wtp._baseType = WeaklyTypedPointer::FLOAT; break; default: LERROR("Error while loading ITK image: unsupported type: " << pixelType); return; } wtp._numChannels = imageIO->GetNumberOfComponents(); //Setup the image region to read ioRegion.SetIndex(ioStart); ioRegion.SetSize(ioSize); imageIO->SetIORegion(ioRegion); //allocate a temporary buffer if necessary double* inputBuf = (pixelType == itk::ImageIOBase::DOUBLE) ? new double[imageIO->GetImageSizeInComponents()] : nullptr; size_t sliceSize = (pixelType == itk::ImageIOBase::DOUBLE) ? imageIO->GetImageSizeInComponents() * sizeof(float) : imageIO->GetImageSizeInBytes(); wtp._pointer = new uint8_t[numSlices * sliceSize]; for (int idx = 0; idx < numSlices; ++idx) { itk::ImageIOBase::Pointer fileIO = imageIO; //itk::ImageIOFactory::CreateImageIO(imageFileNames[idx].c_str(), itk::ImageIOFactory::ReadMode); fileIO->SetFileName(imageFileNames[idx]); fileIO->ReadImageInformation(); fileIO->SetIORegion(ioRegion); size_t currentSliceSize = (pixelType == itk::ImageIOBase::DOUBLE) ? imageIO->GetImageSizeInComponents() * sizeof(float) : fileIO->GetImageSizeInBytes(); if (currentSliceSize != sliceSize) { LERROR("Image " << imageFileNames[idx] << " has different dimensionality or data type!"); delete static_cast<uint8_t*>(wtp._pointer); delete inputBuf; wtp._pointer = nullptr; return; } uint8_t* sliceBuffer = static_cast<uint8_t*>(wtp._pointer) + idx * sliceSize; if (pixelType != itk::ImageIOBase::DOUBLE) { // directly read slice into buffer fileIO->Read(sliceBuffer); } else { //convert float volume to double volume fileIO->Read(inputBuf); double* dptr = inputBuf; float* fptr = reinterpret_cast<float*>(sliceBuffer); for (int i = 0, s = fileIO->GetImageSizeInComponents(); i < s; ++i) { *fptr = static_cast<float>(*dptr); fptr++; dptr++; } } } delete[] inputBuf; size[2] = numSlices; //series adds one dimension ImageData* image = new ImageData(dimensionality+1, size, wtp._numChannels); ImageRepresentationLocal::create(image, wtp); image->setMappingInformation(ImageMappingInformation(size, imageOffset/* + p_imageOffset.getValue()*/, voxelSize /** p_voxelSize.getValue()*/)); data.addData(p_targetImageID.getValue(), image); } else { LWARNING("Unable to create ImageIO Instance; No suitable reader found!"); } }
// ############################################################################################################## void jevois::Camera::setFormat(jevois::VideoMapping const & m) { JEVOIS_TRACE(2); JEVOIS_TIMED_LOCK(itsMtx); // Get current format: itsFormat.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; XIOCTL(itsFd, VIDIOC_G_FMT, &itsFormat); // Set desired format: itsFormat.fmt.pix.width = m.cw; itsFormat.fmt.pix.height = m.ch; itsFormat.fmt.pix.pixelformat = m.cfmt; itsFormat.fmt.pix.field = V4L2_FIELD_NONE; itsFps = m.cfps; LDEBUG("Requesting video format " << itsFormat.fmt.pix.width << 'x' << itsFormat.fmt.pix.height << ' ' << jevois::fccstr(itsFormat.fmt.pix.pixelformat)); XIOCTL(itsFd, VIDIOC_S_FMT, &itsFormat); // Get the format back as the driver may have adjusted some sizes, etc: XIOCTL(itsFd, VIDIOC_G_FMT, &itsFormat); // The driver returns a different format code, may be the mbus code instead of the v4l2 fcc... itsFormat.fmt.pix.pixelformat = v4l2sunxiFix(itsFormat.fmt.pix.pixelformat); LINFO("Camera set video format to " << itsFormat.fmt.pix.width << 'x' << itsFormat.fmt.pix.height << ' ' << jevois::fccstr(itsFormat.fmt.pix.pixelformat)); // Because modules may rely on the exact format that they request, throw if the camera modified it: if (itsFormat.fmt.pix.width != m.cw || itsFormat.fmt.pix.height != m.ch || itsFormat.fmt.pix.pixelformat != m.cfmt) LFATAL("Camera did not accept the requested video format as specified"); // Reset cropping parameters. NOTE: just open()'ing the device does not reset it, according to the unix toolchain // philosophy. Hence, although here we do not provide support for cropping, we still need to ensure that it is // properly reset. Note that some cameras do not support this so here we swallow that exception: try { struct v4l2_cropcap cropcap = { }; cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; XIOCTL_QUIET(itsFd, VIDIOC_CROPCAP, &cropcap); struct v4l2_crop crop = { }; crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; crop.c = cropcap.defrect; XIOCTL_QUIET(itsFd, VIDIOC_S_CROP, &crop); LDEBUG("Set cropping rectangle to " << cropcap.defrect.width << 'x' << cropcap.defrect.height << " @ (" << cropcap.defrect.left << ", " << cropcap.defrect.top << ')'); } catch (...) { LDEBUG("Querying/setting crop rectangle not supported"); } // Set frame rate: try { struct v4l2_streamparm parms = { }; parms.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; parms.parm.capture.timeperframe = jevois::VideoMapping::fpsToV4l2(m.cfps); parms.parm.capture.capturemode = 2; // V4L2_MODE_VIDEO not defined in our headers? its value is 2. XIOCTL(itsFd, VIDIOC_S_PARM, &parms); LDEBUG("Set framerate to " << m.cfps << " fps"); } catch (...) { LERROR("Setting frame rate to " << m.cfps << " fps failed -- IGNORED"); } }
// ###################################################################### Image<int> IntegerSimpleChannel::getOutputInt() { GVX_TRACE(__PRETTY_FUNCTION__); if (!this->hasInput()) // if you think this LFATAL() has been triggered incorrectly, then // first make sure that somebody has called setInputDims() CLFATAL("Oops! can't get output -- I don't even have any input yet"); if (!this->outputAvailable()) { // it's possible that we have input but don't yet have output in // the case of a channel that requires several input frames // before it can start generating output (such as a flicker or // motion channel); in that case we just return an empty image // of the appropriate size LERROR("No %s channel yet! -- IGNORING.", this->tagName().c_str()); return Image<int>(this->getMapDims(), ZEROS); } if (!itsOutputCache.initialized()) { itsOutputCache = Image<int>(getMapDims(), ZEROS); // compute max-normalized weighted sum of center-surround at all levels: for (uint idx = 0; idx < itsLevelSpec.getVal().maxIndex(); ++idx) { const Image<int> submap = getSubmapInt(idx); // get the unweighted map // add submap to our sum itsOutputCache += (submap / int(itsLevelSpec.getVal().maxIndex())); if (MYLOGVERB >= LOG_DEBUG) { uint clev = 0, slev = 0; itsLevelSpec.getVal().indexToCS(idx, clev, slev); LDEBUG("%s(%d,%d): weight %f", tagName().c_str(), clev, slev, 1.0f); } } // apply max-normalization on the output as needed: if (itsNormalizeOutput.getVal()) { LDEBUG("%s: Normalizing output: %s(%d .. %d)", tagName().c_str(), maxNormTypeName(itsNormType.getVal()), itsOutputRangeMin.getVal(), itsOutputRangeMax.getVal()); itsOutputCache = intgMaxNormalize(itsOutputCache, itsOutputRangeMin.getVal(), itsOutputRangeMax.getVal(), itsNormType.getVal()); } // print some debug info if in debug mode: if (MYLOGVERB >= LOG_DEBUG) { int mi, ma; getMinMax(itsOutputCache, mi, ma); LDEBUG("%s: final range [%d .. %d]", tagName().c_str(), mi, ma); } LINFO("Computed %s Conspicuity Map", descriptiveName().c_str()); } return itsOutputCache; }
bool LocalErrorHistogramManager::buildFromBstChild(unsigned int bstOffset, unsigned int octreeOffset) { // Add errors to bst parent histogram int numOtNodes = _tsp->numOTNodes(); unsigned int childIndex = bstOffset * numOtNodes + octreeOffset; bool isBstLeaf = _tsp->isBstLeaf(childIndex); if (bstOffset > 0) { // Not BST root std::vector<float> childValues; std::vector<float> parentValues; int bstParent = parentOffset(bstOffset, 2); unsigned int parentIndex = bstParent * numOtNodes + octreeOffset; unsigned int parentInnerNodeIndex = brickToInnerNodeIndex(parentIndex); if (isBstLeaf) { childValues = readValues(childIndex); } else { unsigned int childInnerNodeIndex = brickToInnerNodeIndex(childIndex); auto it = _voxelCache.find(childInnerNodeIndex); if (it != _voxelCache.end()) { childValues = it->second; } else { LERROR("Child " << childIndex << " visited without cache"); return false; } } int bstChildIndex = bstOffset % 2; if (bstChildIndex == 1) { parentValues = readValues(parentIndex); _voxelCache[parentInnerNodeIndex] = parentValues; } else { auto it = _voxelCache.find(parentInnerNodeIndex); if (it != _voxelCache.end()) { parentValues = it->second; } else { LERROR("Parent " << parentIndex << " visited without cache"); return false; } } // Compare values and add errors to parent histogram unsigned int paddedBrickDim = _tsp->paddedBrickDim(); unsigned int brickDim = _tsp->brickDim(); unsigned int padding = (paddedBrickDim - brickDim) / 2; for (int z = 0; z < brickDim; z++) { for (int y = 0; y < brickDim; y++) { for (int x = 0; x < brickDim; x++) { glm::vec3 samplePoint = glm::vec3(x, y, z) + glm::vec3(padding); unsigned int linearSamplePoint = linearCoords(samplePoint); float childValue = childValues[linearSamplePoint]; float parentValue = parentValues[linearSamplePoint]; // Divide by number of child voxels that will be taken into account float rectangleHeight = std::abs(childValue - parentValue) / 2.0; _temporalHistograms[parentInnerNodeIndex].addRectangle(childValue, parentValue, rectangleHeight); } } } bool isLastBstChild = bstOffset > 0 && bstChildIndex == 0; if (isLastBstChild) { buildFromBstChild(bstParent, octreeOffset); } } if (!isBstLeaf) { unsigned int childInnerNodeIndex = brickToInnerNodeIndex(childIndex); _voxelCache.erase(childInnerNodeIndex); } int octreeChildIndex = (octreeOffset - 1) % 8; bool isLastOctreeChild = octreeOffset > 0 && octreeChildIndex == 7; if (isBstLeaf && isLastOctreeChild) { int octreeParent = parentOffset(octreeOffset, 8); buildFromBstChild(bstOffset, octreeParent); } return true; }
bool LocalErrorHistogramManager::buildHistograms(int numBins) { LINFO("Build histograms with " << numBins << " bins each"); _numBins = numBins; _file = &(_tsp->file()); if (!_file->is_open()) { return false; } _minBin = 0.0; // Should be calculated from tsp file _maxBin = 1.0; // Should be calculated from tsp file as (maxValue - minValue) unsigned int numOtLevels = _tsp->numOTLevels(); unsigned int numOtLeaves = pow(8, numOtLevels - 1); unsigned int numBstLeaves = pow(2, _tsp->numBSTLevels() - 1); _numInnerNodes = _tsp->numTotalNodes() - numOtLeaves * numBstLeaves; _spatialHistograms = std::vector<Histogram>(_numInnerNodes); _temporalHistograms = std::vector<Histogram>(_numInnerNodes); for (unsigned int i = 0; i < _numInnerNodes; i++) { _spatialHistograms[i] = Histogram(_minBin, _maxBin, numBins); _temporalHistograms[i] = Histogram(_minBin, _maxBin, numBins); } // All TSP Leaves int numOtNodes = _tsp->numOTNodes(); int otOffset = (pow(8, numOtLevels - 1) - 1) / 7; int numBstNodes = _tsp->numBSTNodes(); int bstOffset = numBstNodes / 2; int numberOfLeaves = numOtLeaves * numBstLeaves; LINFO("Building spatial histograms"); ProgressBar pb1(numberOfLeaves); int processedLeaves = 0; pb1.print(processedLeaves); bool success = true; for (int bst = bstOffset; bst < numBstNodes; bst++) { for (int ot = otOffset; ot < numOtNodes; ot++) { success &= buildFromOctreeChild(bst, ot); if (!success) LERROR("Failed in buildFromOctreeChild"); if (!success) return false; pb1.print(processedLeaves++); } } //pb1.stop(); LINFO("Building temporal histograms"); ProgressBar pb2(numberOfLeaves); processedLeaves = 0; pb2.print(processedLeaves); for (int ot = otOffset; ot < numOtNodes; ot++) { for (int bst = bstOffset; bst < numBstNodes; bst++) { success &= buildFromBstChild(bst, ot); if (!success) LERROR("Failed in buildFromBstChild"); if (!success) return false; pb2.print(processedLeaves++); } } //pb2.stop(); return success; }
bool SceneGraph::loadFromFile(const std::string& sceneDescription) { clear(); // Move this to a later stage to retain a proper scenegraph when the loading fails ---abock std::string absSceneFile = absPath(sceneDescription); // See if scene file exists if (!FileSys.fileExists(absSceneFile, true)) { LERROR("Could not load scene file '" << absSceneFile << "'. " << "File not found"); return false; } LINFO("Loading SceneGraph from file '" << absSceneFile << "'"); // Load dictionary ghoul::Dictionary sceneDictionary; try { ghoul::lua::loadDictionaryFromFile(absSceneFile, sceneDictionary); } catch (...) { return false; } std::string sceneDescriptionDirectory = ghoul::filesystem::File(absSceneFile, true).directoryName(); std::string sceneDirectory("."); sceneDictionary.getValue(KeyPathScene, sceneDirectory); // The scene path could either be an absolute or relative path to the description // paths directory std::string relativeCandidate = sceneDescriptionDirectory + ghoul::filesystem::FileSystem::PathSeparator + sceneDirectory; std::string absoluteCandidate = absPath(sceneDirectory); if (FileSys.directoryExists(relativeCandidate)) sceneDirectory = relativeCandidate; else if (FileSys.directoryExists(absoluteCandidate)) sceneDirectory = absoluteCandidate; else { LERROR("The '" << KeyPathScene << "' pointed to a " "path '" << sceneDirectory << "' that did not exist"); return false; } ghoul::Dictionary moduleDictionary; bool success = sceneDictionary.getValue(KeyModules, moduleDictionary); if (!success) // There are no modules that are loaded return true; lua_State* state = ghoul::lua::createNewLuaState(); OsEng.scriptEngine().initializeLuaState(state); // Get the common directory bool commonFolderSpecified = sceneDictionary.hasKey(KeyCommonFolder); bool commonFolderCorrectType = sceneDictionary.hasKeyAndValue<std::string>(KeyCommonFolder); if (commonFolderSpecified) { if (commonFolderCorrectType) { std::string commonFolder = sceneDictionary.value<std::string>(KeyCommonFolder); std::string fullCommonFolder = FileSys.pathByAppendingComponent( sceneDirectory, commonFolder ); if (!FileSys.directoryExists(fullCommonFolder)) LERROR("Specified common folder '" << fullCommonFolder << "' did not exist"); else { if (!commonFolder.empty()) { FileSys.registerPathToken(_commonModuleToken, commonFolder); size_t nKeys = moduleDictionary.size(); moduleDictionary.setValue(std::to_string(nKeys + 1), commonFolder); } } } else LERROR("Specification for 'common' folder has invalid type"); } std::vector<std::string> keys = moduleDictionary.keys(); std::map<std::string, std::vector<std::string>> dependencies; std::map<std::string, std::string> parents; _rootNode = new SceneGraphNode; _rootNode->setName(SceneGraphNode::RootNodeName); SceneGraphNodeInternal* internalRoot = new SceneGraphNodeInternal; internalRoot->node = _rootNode; _nodes.push_back(internalRoot); std::sort(keys.begin(), keys.end()); ghoul::filesystem::Directory oldDirectory = FileSys.currentDirectory(); for (const std::string& key : keys) { std::string moduleName = moduleDictionary.value<std::string>(key); std::string modulePath = FileSys.pathByAppendingComponent(sceneDirectory, moduleName); if (!FileSys.directoryExists(modulePath)) { LERROR("Could not load module '" << moduleName << "'. Directory did not exist"); continue; } std::string moduleFile = FileSys.pathByAppendingComponent( modulePath, moduleName + _moduleExtension ); if (!FileSys.fileExists(moduleFile)) { LERROR("Could not load module file '" << moduleFile << "'. File did not exist"); continue; } ghoul::Dictionary moduleDictionary; try { ghoul::lua::loadDictionaryFromFile(moduleFile, moduleDictionary, state); } catch (...) { continue; } std::vector<std::string> keys = moduleDictionary.keys(); for (const std::string& key : keys) { if (!moduleDictionary.hasValue<ghoul::Dictionary>(key)) { LERROR("SceneGraphNode '" << key << "' is not a table in module '" << moduleFile << "'"); continue; } ghoul::Dictionary element; std::string nodeName; std::string parentName; moduleDictionary.getValue(key, element); element.setValue(KeyPathModule, modulePath); element.getValue(SceneGraphNode::KeyName, nodeName); element.getValue(SceneGraphNode::KeyParentName, parentName); FileSys.setCurrentDirectory(modulePath); SceneGraphNode* node = SceneGraphNode::createFromDictionary(element); if (node == nullptr) { LERROR("Error loading SceneGraphNode '" << nodeName << "' in module '" << moduleName << "'"); continue; //clear(); //return false; } dependencies[nodeName].push_back(parentName); parents[nodeName] = parentName; // Also include loaded dependencies if (element.hasKey(SceneGraphNode::KeyDependencies)) { if (element.hasValue<ghoul::Dictionary>(SceneGraphNode::KeyDependencies)) { ghoul::Dictionary nodeDependencies; element.getValue(SceneGraphNode::KeyDependencies, nodeDependencies); std::vector<std::string> keys = nodeDependencies.keys(); for (const std::string& key : keys) { std::string value = nodeDependencies.value<std::string>(key); dependencies[nodeName].push_back(value); } } else { LERROR("Dependencies did not have the corrent type"); } } SceneGraphNodeInternal* internalNode = new SceneGraphNodeInternal; internalNode->node = node; _nodes.push_back(internalNode); } } ghoul::lua::destroyLuaState(state); FileSys.setCurrentDirectory(oldDirectory); for (SceneGraphNodeInternal* node : _nodes) { if (node->node == _rootNode) continue; std::string parent = parents[node->node->name()]; SceneGraphNode* parentNode = sceneGraphNode(parent); if (parentNode == nullptr) { LERROR("Could not find parent '" << parent << "' for '" << node->node->name() << "'"); } node->node->setParent(parentNode); } // Setup dependencies for (SceneGraphNodeInternal* node : _nodes) { std::vector<std::string> nodeDependencies = dependencies[node->node->name()]; for (const std::string& dep : nodeDependencies) { SceneGraphNodeInternal* n = nodeByName(dep); if (n == nullptr) { LERROR("Dependent node '" << dep << "' was not loaded for '" <<node->node->name() << "'"); continue; } node->outgoingEdges.push_back(n); n->incomingEdges.push_back(node); } } std::vector<SceneGraphNodeInternal*> nodesToDelete; for (SceneGraphNodeInternal* node : _nodes) { if (!nodeIsDependentOnRoot(node)) { LERROR("Node '" << node->node->name() << "' has no direct connection to Root."); nodesToDelete.push_back(node); } } for (SceneGraphNodeInternal* node : nodesToDelete) { _nodes.erase(std::find(_nodes.begin(), _nodes.end(), node)); delete node; } bool s = sortTopologically(); if (!s) { LERROR("Topological sort failed"); return false; } return true; }
std::string DatVolumeWriter::getDatFileString(const VolumeBase* const volumeHandle, const std::string& rawFileName) { std::ostringstream datout; tgtAssert(volumeHandle, "No volume"); const VolumeRAM* volume = volumeHandle->getRepresentation<VolumeRAM>(); if (!volume) { LWARNING("No volume or no storage for casted volume data!"); return ""; } // write dat file std::string format; std::string model = "I"; if (dynamic_cast<const VolumeRAM_UInt8*>(volume)) { format = "UCHAR"; } else if (dynamic_cast<const VolumeRAM_Int8*>(volume)) { format = "CHAR"; } else if (dynamic_cast<const VolumeRAM_UInt16*>(volume)) { format = "USHORT"; } else if (dynamic_cast<const VolumeRAM_Int16*>(volume)) { format = "SHORT"; } else if (dynamic_cast<const VolumeRAM_UInt32*>(volume)) { format = "UINT"; } else if (dynamic_cast<const VolumeRAM_Int32*>(volume)) { format = "INT"; } else if (dynamic_cast<const VolumeRAM_UInt64*>(volume)) { format = "UINT64"; } else if (dynamic_cast<const VolumeRAM_Int64*>(volume)) { format = "INT64"; } else if (dynamic_cast<const VolumeRAM_Float*>(volume)) { format = "FLOAT"; } else if (dynamic_cast<const VolumeRAM_Double*>(volume)) { format = "DOUBLE"; } // vec2 types else if (dynamic_cast<const VolumeRAM_2xUInt8*>(volume)) { format = "UCHAR"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xInt8*>(volume)) { format = "CHAR"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xUInt16*>(volume)) { format = "USHORT"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xInt16*>(volume)) { format = "SHORT"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xUInt32*>(volume)) { format = "UINT"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xInt32*>(volume)) { format = "INT"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xUInt64*>(volume)) { format = "UINT64"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xInt64*>(volume)) { format = "INT64"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xFloat*>(volume)) { format = "FLOAT"; model = "LA"; //< luminance alpha } else if (dynamic_cast<const VolumeRAM_2xDouble*>(volume)) { format = "DOUBLE"; model = "LA"; //< luminance alpha } // vec3 types else if (dynamic_cast<const VolumeRAM_3xUInt8*>(volume)) { format = "UCHAR"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xInt8*>(volume)) { format = "CHAR"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xUInt16*>(volume)) { format = "USHORT"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xInt16*>(volume)) { format = "SHORT"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xUInt32*>(volume)) { format = "UINT"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xInt32*>(volume)) { format = "INT"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xUInt64*>(volume)) { format = "UINT64"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xInt64*>(volume)) { format = "INT64"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xFloat*>(volume)) { format = "FLOAT"; model = "RGB"; } else if (dynamic_cast<const VolumeRAM_3xDouble*>(volume)) { format = "DOUBLE"; model = "RGB"; } // vec4 types else if (dynamic_cast<const VolumeRAM_4xUInt8*>(volume)) { format = "UCHAR"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xInt8*>(volume)) { format = "CHAR"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xUInt16*>(volume)) { format = "USHORT"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xInt16*>(volume)) { format = "SHORT"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xUInt32*>(volume)) { format = "UINT"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xInt32*>(volume)) { format = "INT"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xUInt64*>(volume)) { format = "UINT64"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xInt64*>(volume)) { format = "INT64"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xFloat*>(volume)) { format = "FLOAT"; model = "RGBA"; } else if (dynamic_cast<const VolumeRAM_4xDouble*>(volume)) { format = "DOUBLE"; model = "RGBA"; } // special types else if (dynamic_cast<const VolumeRAM_Mat3Float*>(volume)) { format = "FLOAT"; model = "MAT3"; } else if (dynamic_cast<const VolumeRAM_Tensor2Float*>(volume)) { format = "FLOAT"; model = "TENSOR_UP"; } else LERROR("Format currently not supported"); datout << "ObjectFileName:\t" << tgt::FileSystem::fileName(rawFileName) << std::endl; tgt::ivec3 dimensions = volume->getDimensions(); datout << "Resolution:\t" << dimensions.x << " " << dimensions.y << " " << dimensions.z << std::endl; tgt::vec3 spacing = volumeHandle->getSpacing(); datout << "SliceThickness:\t" << spacing.x << " " << spacing.y << " " << spacing.z << std::endl; datout << "Format:\t\t" << format << std::endl; datout << "ObjectModel:\t" << model << std::endl; datout << "Modality:\t" << volumeHandle->getModality() << std::endl; datout << "Checksum:\t" << volumeHandle->getRawDataHash() << std::endl; // write transformation matrix unless it is the identity matrix tgt::mat4 transformation = volumeHandle->getPhysicalToWorldMatrix(); if (transformation != tgt::mat4::createIdentity()) datout << "TransformMatrix: row0\t" << transformation[0][0] << " " << transformation[0][1] << " " << transformation[0][2] << " " << transformation[0][3] << std::endl << "TransformMatrix: row1\t" << transformation[1][0] << " " << transformation[1][1] << " " << transformation[1][2] << " " << transformation[1][3] << std::endl << "TransformMatrix: row2\t" << transformation[2][0] << " " << transformation[2][1] << " " << transformation[2][2] << " " << transformation[2][3] << std::endl << "TransformMatrix: row3\t" << transformation[3][0] << " " << transformation[3][1] << " " << transformation[3][2] << " " << transformation[3][3] << std::endl; return datout.str(); }
Texture* TextureReaderDevil::loadTexture(const std::string& filename, Texture::Filter filter, bool compress, bool keepPixels, bool createOGLTex, bool textureRectangle) { #ifndef GL_TEXTURE_RECTANGLE_ARB if (textureRectangle){ LERROR("Texture Rectangles not supported!"); textureRectangle = false; } #endif File* file = FileSys.open(filename); // check if file is open if (!file || !file->isOpen()) { delete file; return 0; } size_t len = file->size(); // check if file is empty if (len == 0) { delete file; return 0; } // allocate memory char* imdata = new char[len]; if (imdata == 0) { delete file; return 0; // allocation failed } file->read(imdata, len); file->close(); delete file; /* FIXME: I think the keepPixels option does not work properly -> I don't see why...afaik keepPixels has been used in some project (stefan) */ ILuint ImageName; ilGenImages(1, &ImageName); ilBindImage(ImageName); Texture* t = new Texture(); t->setName(filename); if (!ilLoadL(IL_TYPE_UNKNOWN, imdata, static_cast<ILuint>(len))) { LERROR("Failed to open via ilLoadL " << filename); delete[] imdata; delete t; return 0; } delete[] imdata; imdata = 0; t->setBpp(ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL)); // determine image format ILint devilFormat; switch (ilGetInteger(IL_IMAGE_FORMAT)) { case IL_LUMINANCE: // intensity channel only devilFormat = IL_LUMINANCE; t->setFormat(GL_LUMINANCE); break; case IL_LUMINANCE_ALPHA: // intensity-alpha channels devilFormat = IL_LUMINANCE_ALPHA; t->setFormat(GL_LUMINANCE_ALPHA); break; case IL_RGB: devilFormat = IL_RGB; // three color channels t->setFormat(GL_RGB); break; case IL_RGBA: devilFormat = IL_RGBA; // color-alpha channels t->setFormat(GL_RGBA); break; case IL_BGR: devilFormat = IL_RGB; // B-G-R ordered color channels, convert to RGB t->setFormat(GL_RGB); break; case IL_BGRA: devilFormat = IL_RGBA; // R-G-B-A ordered color channels, convert to RGBA t->setFormat(GL_RGBA); break; default: LERROR("unsupported format: " << ilGetInteger(IL_IMAGE_FORMAT) << " (" << filename << ")"); delete t; return 0; } // determine data type ILint devilDataType; switch (ilGetInteger(IL_IMAGE_TYPE)) { case IL_UNSIGNED_BYTE: devilDataType = IL_UNSIGNED_BYTE; t->setDataType(GL_UNSIGNED_BYTE); break; case IL_BYTE: devilDataType = IL_BYTE; t->setDataType(GL_BYTE); break; case IL_UNSIGNED_SHORT: devilDataType = IL_UNSIGNED_SHORT; t->setDataType(GL_UNSIGNED_SHORT); break; case IL_SHORT: devilDataType = IL_SHORT; t->setDataType(GL_SHORT); break; case IL_UNSIGNED_INT: devilDataType = IL_UNSIGNED_INT; t->setDataType(GL_UNSIGNED_INT); break; case IL_INT: devilDataType = IL_INT; t->setDataType(GL_INT); break; case IL_FLOAT: devilDataType = IL_FLOAT; t->setDataType(GL_FLOAT); break; default: LERROR("unsupported data type: " << ilGetInteger(IL_IMAGE_TYPE) << " (" << filename << ")"); delete t; return 0; } if (!ilConvertImage(devilFormat, devilDataType)) { LERROR("failed to convert loaded image: " << filename); delete t; return 0; } tgt::ivec3 dims; dims.x = ilGetInteger(IL_IMAGE_WIDTH); dims.y = ilGetInteger(IL_IMAGE_HEIGHT); dims.z = ilGetInteger(IL_IMAGE_DEPTH); t->setDimensions(dims); LDEBUG("Image dimensions: " << t->getDimensions()); tgtAssert( dims.z == 1, "depth is not equal 1"); #ifdef GL_TEXTURE_RECTANGLE_ARB if (textureRectangle) t->setType( GL_TEXTURE_RECTANGLE_ARB ); else #endif t->setType( GL_TEXTURE_2D ); t->alloc(); memcpy(t->getPixelData(), ilGetData(), t->getArraySize()); bool success; if (textureRectangle) success = createRectangleTexture(t, filter, compress, createOGLTex); else { if (dims.y == 1) success = create1DTexture(t, filter, compress, createOGLTex); else success = create2DTexture(t, filter, compress, createOGLTex); } if (!success) { ilDeleteImages(1, &ImageName); if (!keepPixels) t->setPixelData(0); delete t; return 0; } ilDeleteImages(1, &ImageName); if (!keepPixels) { delete[] t->getPixelData(); t->setPixelData(0); } return t; }
uint64_t OctreeBrickPoolManagerDisk::allocateBrick() throw (VoreenException){ boost::unique_lock<boost::mutex> lock(mutex_); //case1: actual buffer is not full -> use it //case2: we have free bricks -> use them //case3: we have to allocate a new buffer //case 1 if (nextVirtualMemoryAddress_%singleBufferSizeBytes_ != 0) { uint64_t returnValue = nextVirtualMemoryAddress_; nextVirtualMemoryAddress_ += static_cast<uint64_t>(getBrickMemorySizeInByte()); return returnValue; } else //case2 if (!deletedBricks_.empty()) { uint64_t returnValue = deletedBricks_.back(); deletedBricks_.pop_back(); return returnValue; } else { //case3 /* std::ofstream outfile(path.str().c_str(), std::ios::out | std::ios::binary | std::ios::trunc); if(outfile.fail()) throw VoreenException("Could not open: " + path.str()); outfile << itos(0,(int)singleBufferSizeBytes_); outfile.close();*/ std::stringstream path; path << brickPoolPath_ << "/" << bufferFilePrefix_ << itos(bufferFiles_.size(), 10); bufferFiles_.push_back(path.str()); bufferVector_.push_back(new BufferEntry(numBrickSlotsPerBuffer_, 0, 0)); if(numBuffersInRAM_ == maxNumBuffersInRAM_) { //find LRU buffer size_t removeBuffer = brickPoolManagerQueue_.last_->previous_->data_; tgtAssert(bufferVector_.size() > removeBuffer, "buffer is not in ram!") if(bufferVector_[removeBuffer]->inUse_ > 0) { tgtAssert(false,"All bricks are in use!"); LERROR("All bricks are in use!"); throw VoreenException("All bricks are in use!"); } //safe old buffer if(bufferVector_[removeBuffer]->mustBeSavedToDisk_) saveBufferToDisk(removeBuffer); //clean up if(removeBuffer != brickPoolManagerQueue_.removeLast()) { tgtAssert(false, "something went wrong!"); LERROR("something went wrong!"); } delete[] bufferVector_[removeBuffer]->data_; bufferVector_[removeBuffer]->data_ = 0; bufferVector_[removeBuffer]->node_ = 0; bufferVector_[removeBuffer]->isInRAM_ = false; //LERROR("kicked: " << removeBuffer << " loaded: " << bufferID); numBuffersInRAM_--; } char* buffer = 0; try { buffer = new char[singleBufferSizeBytes_]; } catch(std::bad_alloc& e) { tgtAssert(false,e.what()); LERROR(e.what()); throw VoreenException(e.what()); } size_t bufferID = bufferVector_.size()-1; BrickPoolManagerQueueNode<size_t>* node = brickPoolManagerQueue_.insertToFront(bufferID); bufferVector_.back()->data_ = buffer; bufferVector_[bufferID]->isInRAM_ = true; bufferVector_[bufferID]->inUse_ = 0; bufferVector_[bufferID]->mustBeSavedToDisk_ = true; bufferVector_[bufferID]->node_ = node; numBuffersInRAM_++; uint64_t returnValue = nextVirtualMemoryAddress_; nextVirtualMemoryAddress_ += static_cast<uint64_t>(getBrickMemorySizeInByte()); return returnValue; }
/* * Called after a function declaration which introduces a function definition * and before an (optional) old style argument declaration list. * * Puts all symbols declared in the Prototype or in an old style argument * list back to the symbol table. * * Does the usual checking of storage class, type (return value), * redeclaration etc.. */ void funcdef(sym_t *fsym) { int n, dowarn; sym_t *arg, *sym, *rdsym; funcsym = fsym; /* * Put all symbols declared in the argument list back to the * symbol table. */ for (sym = dcs->d_fpsyms; sym != NULL; sym = sym->s_dlnxt) { if (sym->s_blklev != -1) { if (sym->s_blklev != 1) LERROR("funcdef()"); inssym(1, sym); } } /* * In osfunc() we did not know whether it is an old style function * definition or only an old style declaration, if there are no * arguments inside the argument list ("f()"). */ if (!fsym->s_type->t_proto && fsym->s_args == NULL) fsym->s_osdef = 1; chktyp(fsym); /* * chktyp() checks for almost all possible errors, but not for * incomplete return values (these are allowed in declarations) */ if (fsym->s_type->t_subt->t_tspec != VOID && incompl(fsym->s_type->t_subt)) { /* cannot return incomplete type */ error(67); } fsym->s_def = DEF; if (fsym->s_scl == TYPEDEF) { fsym->s_scl = EXTERN; /* illegal storage class */ error(8); } if (dcs->d_inline) fsym->s_inline = 1; /* * Arguments in new style function declarations need a name. * (void is already removed from the list of arguments) */ n = 1; for (arg = fsym->s_type->t_args; arg != NULL; arg = arg->s_nxt) { if (arg->s_scl == ABSTRACT) { if (arg->s_name != unnamed) LERROR("funcdef()"); /* formal parameter lacks name: param #%d */ error(59, n); } else { if (arg->s_name == unnamed) LERROR("funcdef()"); } n++; } /* * We must also remember the position. s_dpos is overwritten * if this is an old style definition and we had already a * prototype. */ STRUCT_ASSIGN(dcs->d_fdpos, fsym->s_dpos); if ((rdsym = dcs->d_rdcsym) != NULL) { if (!isredec(fsym, (dowarn = 0, &dowarn))) { /* * Print nothing if the newly defined function * is defined in old style. A better warning will * be printed in cluparg(). */ if (dowarn && !fsym->s_osdef) { /* redeclaration of %s */ (*(sflag ? error : warning))(27, fsym->s_name); prevdecl(-1, rdsym); } /* copy usage information */ cpuinfo(fsym, rdsym); /* * If the old symbol was a prototype and the new * one is none, overtake the position of the * declaration of the prototype. */ if (fsym->s_osdef && rdsym->s_type->t_proto) STRUCT_ASSIGN(fsym->s_dpos, rdsym->s_dpos); /* complete the type */ compltyp(fsym, rdsym); /* once a function is inline it remains inline */ if (rdsym->s_inline) fsym->s_inline = 1; } /* remove the old symbol from the symbol table */ rmsym(rdsym); } if (fsym->s_osdef && !fsym->s_type->t_proto) { if (sflag && hflag && strcmp(fsym->s_name, "main") != 0) /* function definition is not a prototyp */ warning(286); } if (dcs->d_notyp) /* return value is implicitly declared to be int */ fsym->s_rimpl = 1; reached = 1; }
void RenderablePlaneProjection::updatePlane(const Image img, double currentTime) { std::string frame; std::vector<glm::dvec3> bounds; glm::dvec3 boresight; std::string target = _defaultTarget; // Turned on if the plane should be attached to the closest target, // rather than the target specified in img //if (!_moving) { // target = findClosestTarget(currentTime); //} if (img.path != "") target = img.target; setTarget(target); try { SpiceManager::FieldOfViewResult res = SpiceManager::ref().fieldOfView(_instrument); frame = std::move(res.frameName); bounds = std::move(res.bounds); boresight = std::move(res.boresightVector); } catch (const SpiceManager::SpiceException& e) { LERROR(e.what()); } double lt; psc projection[4]; glm::dvec3 vecToTarget = SpiceManager::ref().targetPosition( _target.body, _spacecraft, GalacticFrame, { SpiceManager::AberrationCorrection::Type::ConvergedNewtonianStellar, SpiceManager::AberrationCorrection::Direction::Reception }, currentTime, lt ); // The apparent position, CN+S, makes image align best with target for (int j = 0; j < bounds.size(); ++j) { bounds[j] = SpiceManager::ref().frameTransformationMatrix(frame, GalacticFrame, currentTime) * bounds[j]; glm::dvec3 cornerPosition = glm::proj(vecToTarget, bounds[j]); if (!_moving) { cornerPosition -= vecToTarget; } cornerPosition = SpiceManager::ref().frameTransformationMatrix(GalacticFrame, _target.frame, currentTime) * cornerPosition; projection[j] = PowerScaledCoordinate::CreatePowerScaledCoordinate(cornerPosition[0], cornerPosition[1], cornerPosition[2]); projection[j][3] += 3; } if (!_moving) { SceneGraphNode* thisNode = OsEng.renderEngine().scene()->sceneGraphNode(_name); SceneGraphNode* newParent = OsEng.renderEngine().scene()->sceneGraphNode(_target.node); if (thisNode != nullptr && newParent != nullptr) thisNode->setParent(newParent); } const GLfloat vertex_data[] = { // square of two triangles drawn within fov in target coordinates // x y z w s t projection[1][0], projection[1][1], projection[1][2], projection[1][3], 0, 1, // Lower left 1 projection[3][0], projection[3][1], projection[3][2], projection[3][3], 1, 0, // Upper right 2 projection[2][0], projection[2][1], projection[2][2], projection[2][3], 0, 0, // Upper left 3 projection[1][0], projection[1][1], projection[1][2], projection[1][3], 0, 1, // Lower left 4 = 1 projection[0][0], projection[0][1], projection[0][2], projection[0][3], 1, 1, // Lower right 5 projection[3][0], projection[3][1], projection[3][2], projection[3][3], 1, 0, // Upper left 6 = 2 }; glBindVertexArray(_quad); // bind array glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); // bind buffer glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data), vertex_data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(0)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast<void*>(sizeof(GLfloat) * 4)); if (!_moving && img.path != "") { _texturePath = img.path; loadTexture(); } }
/* * Process a label. * * typ type of the label (T_NAME, T_DEFAULT or T_CASE). * sym symbol table entry of label if typ == T_NAME * tn expression if typ == T_CASE */ void label(int typ, sym_t *sym, tnode_t *tn) { cstk_t *ci; clst_t *cl; val_t *v; val_t nv; tspec_t t; switch (typ) { case T_NAME: if (sym->s_set) { /* label %s redefined */ error(194, sym->s_name); } else { setsflg(sym); } break; case T_CASE: /* find the stack entry for the innermost switch statement */ for (ci = cstk; ci != NULL && !ci->c_switch; ci = ci->c_nxt) continue; if (ci == NULL) { /* case not in switch */ error(195); tn = NULL; } else if (tn != NULL && tn->tn_op != CON) { /* non-constant case expression */ error(197); tn = NULL; } else if (tn != NULL && !isityp(tn->tn_type->t_tspec)) { /* non-integral case expression */ error(198); tn = NULL; } if (tn != NULL) { if (ci->c_swtype == NULL) LERROR("label()"); if (reached && !ftflg) { if (hflag) /* fallthrough on case statement */ warning(220); } t = tn->tn_type->t_tspec; if (t == LONG || t == ULONG || t == QUAD || t == UQUAD) { if (tflag) /* case label must be of type ... */ warning(203); } /* * get the value of the expression and convert it * to the type of the switch expression */ v = constant(tn, 1); (void) memset(&nv, 0, sizeof nv); cvtcon(CASE, 0, ci->c_swtype, &nv, v); free(v); /* look if we had this value already */ for (cl = ci->c_clst; cl != NULL; cl = cl->cl_nxt) { if (cl->cl_val.v_quad == nv.v_quad) break; } if (cl != NULL && isutyp(nv.v_tspec)) { /* duplicate case in switch, %lu */ error(200, (u_long)nv.v_quad); } else if (cl != NULL) { /* duplicate case in switch, %ld */ error(199, (long)nv.v_quad); } else { /* * append the value to the list of * case values */ cl = xcalloc(1, sizeof (clst_t)); STRUCT_ASSIGN(cl->cl_val, nv); cl->cl_nxt = ci->c_clst; ci->c_clst = cl; } } tfreeblk(); break; case T_DEFAULT: /* find the stack entry for the innermost switch statement */ for (ci = cstk; ci != NULL && !ci->c_switch; ci = ci->c_nxt) continue; if (ci == NULL) { /* default outside switch */ error(201); } else if (ci->c_default) { /* duplicate default in switch */ error(202); } else { if (reached && !ftflg) { if (hflag) /* fallthrough on default statement */ warning(284); } ci->c_default = 1; } break; }; reached = 1; }
VolumeList* ECAT7VolumeReader::read(const std::string &url, int volumeId) throw(tgt::CorruptedFileException, tgt::IOException, std::bad_alloc) { LINFO("Loading dataset " << url << " vid: " << volumeId); VolumeURL origin(url); std::string fileName = origin.getPath(); FILE* fin = fopen(fileName.c_str(), "rb"); if(!fin) { throw tgt::FileNotFoundException("ECAT7: File not found", fileName); } ECAT7VolumeReader::ECAT7Structure s = readStructure(fileName); VolumeList* vc = new VolumeList(); for(size_t i=0; i<s.subVolumes_.size(); i++) { fseek(fin, s.subVolumes_[i].de_.startBlock_ * 512, SEEK_SET); fseek(fin, 512, SEEK_CUR); //skip past header (already read) tgt::svec3 dimensions = s.subVolumes_[i].getDimensions(); //tgt::mat4 m = s.subVolumes_[i].getTransformation(); tgt::vec3 spacing = s.subVolumes_[i].getSpacing(); tgt::vec3 offset = s.subVolumes_[i].getOffset(); if(volumeId != -1) { if(volumeId != s.subVolumes_[i].getId()) continue; } if(s.subVolumes_[i].ih_.num_dimensions != 3) continue; if (getProgressBar()) { getProgressBar()->setTitle("Loading Volume"); getProgressBar()->setProgressMessage("Loading volume: " + fileName); } VolumeRAM* vol; RealWorldMapping denormalize; if(s.h_.file_type == 6) { vol = new VolumeRAM_UInt8(dimensions); denormalize = RealWorldMapping::createDenormalizingMapping<uint8_t>(); } else if(s.h_.file_type == 7) { vol = new VolumeRAM_UInt16(dimensions); denormalize = RealWorldMapping::createDenormalizingMapping<uint16_t>(); } else { LERROR("Unknown file format detected."); return 0; } float scale = s.subVolumes_[i].ih_.scale_factor * s.h_.ecat_calibration_factor; RealWorldMapping rwm(scale, 0.0f, s.h_.data_units); VolumeReader::read(vol, fin); // Assume that the pixel size values given in the ecat header are in cm. Multiply spacing and offset // with 0.1 to convert to mm. Volume* vh = new Volume(vol, spacing * 0.1f, offset * 0.1f); vh->setRealWorldMapping(RealWorldMapping::combine(denormalize, rwm)); if(s.swapEndianness_) VolumeOperatorSwapEndianness::APPLY_OP(vh); // TODO: This must depend on some parameter in the headers, figure out which and how bool mirrorZ = true; if(mirrorZ) { Volume* mirrored = VolumeOperatorMirrorZ::APPLY_OP(vh); delete vh; vh = mirrored; } VolumeURL o("ecat7", fileName); o.addSearchParameter("volumeId", itos(s.subVolumes_[i].de_.id_)); vh->setOrigin(o); s.transformMetaData(vh->getMetaDataContainer(), static_cast<int>(i)); if(length(offset) == 0.f) centerVolume(vh); vc->add(vh); if (getProgressBar()) getProgressBar()->hide(); } fclose(fin); return vc; }
/****** cull/list/lWriteListXMLTo() ********************************************** * NAME * lWriteListXMLTo() -- Write a list to a file stream * * SYNOPSIS * void lWriteListXMLTo(const lList *lp, FILE *fp) * * FUNCTION * Write a list to a file stream in XML format * * INPUTS * const lList *lp - list * int nesting_level - current nesting level * FILE *fp - file stream * * NOTE: * MT-NOTE: is thread save, works only on the objects which are passed in * *******************************************************************************/ static void lWriteListXML_(const lList *lp, int nesting_level, FILE *fp, int ignore_cull_name) { lListElem *ep; char indent[128]; int i; bool is_XML_elem = false; dstring attr = DSTRING_INIT; bool is_attr = false; DENTER(CULL_LAYER, "lWriteListXML_"); if (!lp) { LERROR(LELISTNULL); DEXIT; return; } { int max = nesting_level * 2; if (max > 128) max = 128; for (i = 0; i < max; i++) indent[i] = ' '; indent[i] = '\0'; } for_each(ep, lp) { is_XML_elem = false; is_attr = false; if (lGetPosViaElem(ep, XMLE_Attribute, SGE_NO_ABORT) != -1) { sge_dstring_clear(&attr); is_attr = lAttributesToString_(lGetList(ep, XMLE_Attribute), &attr); is_XML_elem = true; } if (is_XML_elem && (lGetBool(ep, XMLE_Print))) { lListElem *elem = lGetObject(ep, XMLE_Element); if (!fp) { if (lGetString(elem, XMLA_Value) != NULL) { DPRINTF(("%s<%s%s>", indent, lGetString(elem, XMLA_Name), (is_attr?sge_dstring_get_string(&attr):""))); DPRINTF(("%s", lGetString(elem, XMLA_Value))); lWriteListXML_(lGetList(ep, XMLE_List), nesting_level+1, fp, ignore_cull_name); DPRINTF(("</%s>\n", lGetString(elem, XMLA_Name))); } else { DPRINTF(("%s<%s%s>\n", indent, lGetString(elem, XMLA_Name), (is_attr?sge_dstring_get_string(&attr):""))); lWriteListXML_(lGetList(ep, XMLE_List), nesting_level+1, fp, ignore_cull_name); DPRINTF(("%s</%s>\n", indent,lGetString(elem, XMLA_Name))); } } else { if (lGetString(elem, XMLA_Value) != NULL) { fprintf(fp, "%s<%s%s>", indent, lGetString(elem, XMLA_Name), (is_attr?sge_dstring_get_string(&attr):"")); fprintf(fp, "%s", lGetString(elem, XMLA_Value)); lWriteListXML_(lGetList(ep, XMLE_List), nesting_level+1, fp, ignore_cull_name); fprintf(fp, "</%s>\n", lGetString(elem, XMLA_Name)); } else { fprintf(fp, "%s<%s%s>\n", indent, lGetString(elem, XMLA_Name), (is_attr?sge_dstring_get_string(&attr):"")); lWriteListXML_(lGetList(ep, XMLE_List), nesting_level+1, fp, ignore_cull_name); fprintf(fp, "%s</%s>\n", indent, lGetString(elem, XMLA_Name)); } } } else { const char* listName = lGetListName(lp); if (strcmp (listName, "No list name specified") == 0) { listName = "element"; } if (!fp) { DPRINTF(("%s<%s%s>\n", indent, listName, ((is_attr)?sge_dstring_get_string(&attr):""))); lWriteElemXML_(ep, nesting_level+1, NULL, ignore_cull_name); DPRINTF(("%s</%s>\n", indent, listName)); } else { fprintf(fp, "%s<%s%s>\n", indent, listName, ((is_attr)?sge_dstring_get_string(&attr):"")); lWriteElemXML_(ep, nesting_level+1, fp, ignore_cull_name); fprintf(fp, "%s</%s>\n", indent, listName); } } }
std::vector<std::string> ItkReader::GetImageFileNames() { std::vector<std::string> filenames; std::string first = p_url.getValue(); std::string last = p_lastUrl.getValue(); //either one is empty - we cant do anything if (!first.size() || !last.size()) return filenames; //this is a pretty naive scheme to find out the naming convention of the files //we first scan both filenames from left to find the first position where they diverge size_t diverge_left = 0; for (; diverge_left < first.size(); ++diverge_left) { //check if we are outside last string if (diverge_left >= last.size()) break; if (first[diverge_left] != last[diverge_left]) break; } std::string fileBegin = first.substr(0, diverge_left); //strings are equal? if (diverge_left == first.size() && diverge_left == last.size()) { LWARNING("First and last filenames are equal!"); filenames.push_back(first); return filenames; } // now we assume the diverging letters are a number, which we skip forward int digitFirstEnd = diverge_left; if (!isdigit(first[digitFirstEnd])) { LERROR("Cannot find sequence between first and last filename!"); return filenames; } while (isdigit(first[digitFirstEnd])) digitFirstEnd++; int digitLastEnd = diverge_left; if (!isdigit(last[digitLastEnd])) { LERROR("Cannot find sequence between first and last filename!"); return filenames; } while (isdigit(last[digitLastEnd])) digitLastEnd++; std::string fileEnd = first.substr(digitFirstEnd, std::string::npos); if (fileEnd != last.substr(digitLastEnd, std::string::npos)) { LERROR("Filename Tails mismatch!"); return filenames; } //now, we have diverge_left and diverge_right LINFO("Diverge Left: " << diverge_left << "; digit end position: " << digitFirstEnd); LINFO("String begin: " << fileBegin << "; end: " << fileEnd); //the substrings of first and last filename are converted to numbers to get the numerical range int numFirst = StringUtils::fromString<int>(first.substr(diverge_left, digitFirstEnd - diverge_left)); int numLast = StringUtils::fromString<int>(last.substr(diverge_left, digitLastEnd - diverge_left)); LINFO("Indices from " << first.substr(diverge_left, digitFirstEnd - diverge_left) << "(" << numFirst << ") to " << numLast); //then we step through all numbers in the range and generate filenames by replacing the diverged substring //with the generated number for (int imgIdx = numFirst; imgIdx <= numLast; ++imgIdx) { std::stringstream s; if (first.size() == last.size()) { s << std::setfill('0'); s << std::setw(digitFirstEnd - diverge_left); } s.clear(); s << imgIdx; filenames.push_back(fileBegin + s.str() + fileEnd); //LINFO(filenames.back()); } return filenames; }
void GlGaussianFilter::updateResult(DataContainer& data) { ImageRepresentationGL::ScopedRepresentation img(data, p_inputImage.getValue()); if (img != 0) { if (img->getParent()->getDimensionality() > 1) { cgt::ivec3 size = img->getSize(); int halfKernelSize = static_cast<int>(2.5 * p_sigma.getValue()); cgtAssert(halfKernelSize < MAX_HALF_KERNEL_SIZE, "halfKernelSize too big -> kernel uniform buffer will be out of bounds!") cgt::TextureUnit inputUnit, kernelUnit; inputUnit.activate(); // create texture for result cgt::Texture* resultTextures[2]; for (size_t i = 0; i < 2; ++i) { resultTextures[i] = new cgt::Texture(img->getTexture()->getType(), size, img->getTexture()->getInternalFormat(), cgt::Texture::LINEAR); } // we need to distinguish 2D and 3D case cgt::Shader* leShader = (size.z == 1) ? _shader2D : _shader3D; // activate shader leShader->activate(); leShader->setUniform("_halfKernelSize", halfKernelSize); // bind kernel buffer texture kernelUnit.activate(); glBindTexture(GL_TEXTURE_BUFFER, _kernelBufferTexture); glTexBuffer(GL_TEXTURE_BUFFER, GL_R32F, _kernelBuffer->getId()); leShader->setUniform("_kernel", kernelUnit.getUnitNumber()); LGL_ERROR; // activate FBO and attach texture _fbo->activate(); glViewport(0, 0, static_cast<GLsizei>(size.x), static_cast<GLsizei>(size.y)); // start 3 passes of convolution: in X, Y and Z direction: { // X pass leShader->setUniform("_direction", cgt::ivec3(1, 0, 0)); img->bind(leShader, inputUnit); // render quad to compute difference measure by shader for (int z = 0; z < size.z; ++z) { float zTexCoord = static_cast<float>(z)/static_cast<float>(size.z) + .5f/static_cast<float>(size.z); if (size.z > 1) leShader->setUniform("_zTexCoord", zTexCoord); _fbo->attachTexture(resultTextures[0], GL_COLOR_ATTACHMENT0, 0, z); LGL_ERROR; QuadRdr.renderQuad(); } } { // Y pass leShader->setUniform("_direction", cgt::ivec3(0, 1, 0)); inputUnit.activate(); resultTextures[0]->bind(); // render quad to compute difference measure by shader for (int z = 0; z < size.z; ++z) { float zTexCoord = static_cast<float>(z)/static_cast<float>(size.z) + .5f/static_cast<float>(size.z); if (size.z > 1) leShader->setUniform("_zTexCoord", zTexCoord); _fbo->attachTexture(resultTextures[1], GL_COLOR_ATTACHMENT0, 0, z); LGL_ERROR; QuadRdr.renderQuad(); } } // we need the third pass only in the 3D case if (size.z > 1) { // Z pass leShader->setUniform("_direction", cgt::ivec3(0, 0, 1)); inputUnit.activate(); resultTextures[1]->bind(); // render quad to compute difference measure by shader for (int z = 0; z < size.z; ++z) { float zTexCoord = static_cast<float>(z)/static_cast<float>(size.z) + .5f/static_cast<float>(size.z); leShader->setUniform("_zTexCoord", zTexCoord); _fbo->attachTexture(resultTextures[0], GL_COLOR_ATTACHMENT0, 0, z); LGL_ERROR; QuadRdr.renderQuad(); } } else { // in the 2D case we just swap the result textures, so that we write the correct image out in the lines below. std::swap(resultTextures[0], resultTextures[1]); } _fbo->detachAll(); _fbo->deactivate(); leShader->deactivate(); // put resulting image into DataContainer ImageData* id = new ImageData(img->getParent()->getDimensionality(), size, img->getParent()->getNumChannels()); ImageRepresentationGL::create(id, resultTextures[0]); id->setMappingInformation(img->getParent()->getMappingInformation()); data.addData(p_outputImage.getValue(), id); delete resultTextures[1]; cgt::TextureUnit::setZeroUnit(); LGL_ERROR; } else { LERROR("Supports only 2D and 3D Gaussian Blur."); } } else { LDEBUG("No suitable input image found."); } }
void MorphologicalGradientImageFilterITK::morphologicalGradientImageFilterITK() { if (!enableProcessing_.get()) { outport1_.setData(inport1_.getData(), false); return; } typedef itk::Image<T, 3> InputImageType1; typedef itk::Image<T, 3> OutputImageType1; typedef T PixelType; typename InputImageType1::Pointer p1 = voreenToITK<T>(inport1_.getData()); if(structuringElement_.get() == "binaryBall"){ shape_.setVisible(false); typedef itk::BinaryBallStructuringElement < PixelType, 3 > KernelType; typedef itk::MorphologicalGradientImageFilter<InputImageType1, OutputImageType1, KernelType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); filter->SetAlgorithm(algorithm_.get()); KernelType structuringElement; typename KernelType::SizeType radius; radius[0] = radius_.get().x; radius[1] = radius_.get().y; radius[2] = radius_.get().z; structuringElement.SetRadius(radius); structuringElement.CreateStructuringElement(); filter->SetKernel(structuringElement); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } else if(structuringElement_.get() == "binaryCross"){ shape_.setVisible(false); typedef itk::BinaryCrossStructuringElement < PixelType, 3 > KernelType; typedef itk::MorphologicalGradientImageFilter<InputImageType1, OutputImageType1, KernelType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); filter->SetAlgorithm(algorithm_.get()); KernelType structuringElement; typename KernelType::SizeType radius; radius[0] = radius_.get().x; radius[1] = radius_.get().y; radius[2] = radius_.get().z; structuringElement.SetRadius(radius); structuringElement.CreateStructuringElement(); filter->SetKernel(structuringElement); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } else if(structuringElement_.get() == "flat"){ shape_.setVisible(true); typedef itk::FlatStructuringElement < 3 > KernelType; typename KernelType::SizeType radius; radius[0] = radius_.get().x; radius[1] = radius_.get().y; radius[2] = radius_.get().z; if(shape_.get() == "box"){ KernelType structuringElement = KernelType::Box(radius); typedef itk::MorphologicalGradientImageFilter<InputImageType1, OutputImageType1, KernelType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); filter->SetAlgorithm(algorithm_.get()); filter->SetKernel(structuringElement); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } else if(shape_.get() == "ball"){ KernelType structuringElement = KernelType::Ball(radius); typedef itk::MorphologicalGradientImageFilter<InputImageType1, OutputImageType1, KernelType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); filter->SetAlgorithm(algorithm_.get()); filter->SetKernel(structuringElement); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } else if(shape_.get() == "cross"){ KernelType structuringElement = KernelType::Cross(radius); typedef itk::MorphologicalGradientImageFilter<InputImageType1, OutputImageType1, KernelType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); filter->SetAlgorithm(algorithm_.get()); filter->SetKernel(structuringElement); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } else if(shape_.get() == "annulus"){ KernelType structuringElement = KernelType::Annulus(radius); typedef itk::MorphologicalGradientImageFilter<InputImageType1, OutputImageType1, KernelType> FilterType; typename FilterType::Pointer filter = FilterType::New(); filter->SetInput(p1); filter->SetAlgorithm(algorithm_.get()); filter->SetKernel(structuringElement); observe(filter.GetPointer()); try { filter->Update(); } catch (itk::ExceptionObject &e) { LERROR(e); } Volume* outputVolume1 = 0; outputVolume1 = ITKToVoreenCopy<T>(filter->GetOutput()); if (outputVolume1) { transferRWM(inport1_.getData(), outputVolume1); transferTransformation(inport1_.getData(), outputVolume1); outport1_.setData(outputVolume1); } else outport1_.setData(0); } } }
void NrrdVolumeWriter::write(const std::string& filename, const VolumeBase* volumeHandle) throw (tgt::IOException) { tgtAssert(volumeHandle, "No volume"); const VolumeRAM* volume = volumeHandle->getRepresentation<VolumeRAM>(); if (!volume) { LWARNING("No volume"); return; } std::string nhdrname = filename; std::string rawname = getFileNameWithoutExtension(filename) + ".raw"; LINFO("saving " << nhdrname << " and " << rawname); std::fstream nhdrout(nhdrname.c_str(), std::ios::out); std::fstream rawout(rawname.c_str(), std::ios::out | std::ios::binary); if (nhdrout.bad() || rawout.bad()) { LWARNING("Can't open file"); throw tgt::IOException(); } // write nrrd header std::string type; const char* data = 0; size_t numbytes = 0; if (const VolumeRAM_UInt8* vol = dynamic_cast<const VolumeRAM_UInt8*>(volume)) { type = "uchar"; data = reinterpret_cast<const char*>(vol->voxel()); numbytes = vol->getNumBytes(); } else if (const VolumeRAM_UInt16* vol = dynamic_cast<const VolumeRAM_UInt16*>(volume)) { type = "ushort"; data = reinterpret_cast<const char*>(vol->voxel()); numbytes = vol->getNumBytes(); } else if (const VolumeRAM_4xUInt8* vol = dynamic_cast<const VolumeRAM_4xUInt8*>(volume)) { type = "uint"; data = reinterpret_cast<const char*>(vol->voxel()); numbytes = vol->getNumBytes(); } else LERROR("Format currently not supported"); tgt::ivec3 dimensions = volumeHandle->getDimensions(); tgt::vec3 spacing = volumeHandle->getSpacing(); nhdrout << "NRRD0001" << std::endl; // magic number nhdrout << "content: " << tgt::FileSystem::fileName(filename) << std::endl; nhdrout << "dimension: 3" << std::endl; nhdrout << "type: " << type << std::endl; nhdrout << "sizes: " << dimensions.x << " " << dimensions.y << " " << dimensions.z << std::endl; nhdrout << "spacings: " << spacing.x << " " << spacing.y << " " << spacing.z << std::endl; nhdrout << "datafile: " << tgt::FileSystem::fileName(rawname) << std::endl; nhdrout << "encoding: raw" << std::endl; nhdrout.close(); // write raw file rawout.write(data, numbytes); rawout.close(); }
void VolumeIOHelper::loadRawVolume(const std::string& filenameStd) { QString filename = QString::fromStdString(filenameStd); if (filename.isEmpty()) return; // query raw parameters via dialog std::string objectModel; std::string format; int numFrames; tgt::ivec3 dim; tgt::vec3 spacing; int headerSkip; bool bigEndian; tgt::mat4 trafoMat = tgt::mat4::identity; RawVolumeWidget* rawVW = new RawVolumeWidget(parent_, tr("Please enter the properties for <br><strong>") + filename + "</strong>", objectModel, format, numFrames, dim, spacing, headerSkip, bigEndian, trafoMat); if (!rawVW->exec() == QDialog::Accepted) return; // derive expected file size from provided properties uint formatBytes = 1;; if (format == "USHORT" || format == "USHORT_12" || format == "SHORT") formatBytes = 2; else if (format == "FLOAT") formatBytes = 4; else if (format == "UINT" || format == "INT") formatBytes = 4; int numChannels = 1; if (objectModel == "RGB") numChannels = 3; else if (objectModel == "RGBA") numChannels = 4; else if (objectModel.find("TENSOR_") == 0) numChannels = 6; uint rawSize = headerSkip + formatBytes * numChannels * (dim.x * dim.y * dim.z) * numFrames; // inform/query user, if file size does not match if (QFile(filename).size() != rawSize) { QMessageBox::StandardButton retButton = QMessageBox::Yes; if(QFile(filename).size() > rawSize) { QString msg = tr("The provided properties result in a size smaller\nthan the actual file size. Do you want to continue?"); retButton = QMessageBox::question(parent_, tr("Size mismatch"), msg, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes); } else if (QFile(filename).size() < rawSize) { QString msg = tr("The provided properties result in a size\ngreater than the actual file size."); retButton = QMessageBox::warning(parent_, tr("Size mismatch"), msg, QMessageBox::Cancel); } if (retButton != QMessageBox::Yes && retButton != QMessageBox::Ok) return; } qApp->processEvents(); // load raw volume try { for (int frame=0; frame < numFrames; ++frame) { RawVolumeReader rawReader(progressBar_); rawReader.setReadHints(dim, spacing, objectModel, format, frame, headerSkip, bigEndian); VolumeList* collection = rawReader.read(filename.toStdString()); if (collection && !collection->empty()) { tgtAssert(collection->size() == 1, "More than one raw volume returned"); Volume* volumeHandle = static_cast<Volume*>(collection->first()); oldVolumePosition(volumeHandle); volumeHandle->setPhysicalToWorldMatrix(trafoMat); volumeHandle->setTimestep(static_cast<float>(frame)); emit(volumeLoaded(volumeHandle)); } delete collection; } } catch (const tgt::FileException& e) { LERROR(e.what()); QErrorMessage* errorMessageDialog = new QErrorMessage(VoreenApplicationQt::qtApp()->getMainWindow()); errorMessageDialog->showMessage(e.what()); } catch (std::bad_alloc&) { LERROR("bad allocation while reading file: " << filename.toStdString()); QErrorMessage* errorMessageDialog = new QErrorMessage(VoreenApplicationQt::qtApp()->getMainWindow()); errorMessageDialog->showMessage("Bad allocation while reading file: " + filename); } }
void OTBSpectralAngleDistanceImageFilterProcessor::process() { try { //Detect the number of spectral bands the input image has. nbBands = inPort_.getData()->GetNumberOfComponentsPerPixel(); LINFO("Number of Bands detected: " << nbBands); updateBands(nbBands); MultiSpectralImageType::PixelType pixelRef; //Pass the parameters to filter //depending on input image's spectral bands. switch (nbBands) { case 1: { pixelRef.SetSize(1); pixelRef[0] = refPixel0_.get(); break; } case 2: { pixelRef.SetSize(2); pixelRef[0] = refPixel0_.get(); pixelRef[1] = refPixel1_.get(); break; } case 3: { pixelRef.SetSize(3); pixelRef[0] = refPixel0_.get(); pixelRef[1] = refPixel1_.get(); pixelRef[2] = refPixel2_.get(); break; } case 4: { pixelRef.SetSize(4); pixelRef[0] = refPixel0_.get(); pixelRef[1] = refPixel1_.get(); pixelRef[2] = refPixel2_.get(); pixelRef[3] = refPixel3_.get(); break; } case 5: { pixelRef.SetSize(5); pixelRef[0] = refPixel0_.get(); pixelRef[1] = refPixel1_.get(); pixelRef[2] = refPixel2_.get(); pixelRef[3] = refPixel3_.get(); pixelRef[4] = refPixel4_.get(); break; } case 6: { pixelRef.SetSize(6); pixelRef[0] = refPixel0_.get(); pixelRef[1] = refPixel1_.get(); pixelRef[2] = refPixel2_.get(); pixelRef[3] = refPixel3_.get(); pixelRef[4] = refPixel4_.get(); pixelRef[5] = refPixel5_.get(); break; } case 7: { pixelRef.SetSize(7); pixelRef[0] = refPixel0_.get(); pixelRef[1] = refPixel1_.get(); pixelRef[2] = refPixel2_.get(); pixelRef[3] = refPixel3_.get(); pixelRef[4] = refPixel4_.get(); pixelRef[5] = refPixel5_.get(); pixelRef[6] = refPixel6_.get(); break; } case 8: { pixelRef.SetSize(8); pixelRef[0] = refPixel0_.get(); pixelRef[1] = refPixel1_.get(); pixelRef[2] = refPixel2_.get(); pixelRef[3] = refPixel3_.get(); pixelRef[4] = refPixel4_.get(); pixelRef[5] = refPixel5_.get(); pixelRef[6] = refPixel6_.get(); pixelRef[7] = refPixel7_.get(); break; } } filter->SetInput(inPort_.getData()); filter->SetReferencePixel(pixelRef); filter->UpdateLargestPossibleRegion(); filter->Update(); outPort_.setData(filter->GetOutput()); LINFO("Spectral Angle Distance Image Filter Connected!"); } catch (int e) { LERROR("Error in Spectral Angle Distance Image Filter"); return; } }
/* * extracts potential format specifiers for printf() and scanf() and * writes them, enclosed in "" and qouted if necessary, to the output buffer */ static void outfstrg(strg_t *strg) { int c, oc, first; u_char *cp; if (strg->st_tspec != CHAR) LERROR("outfstrg()"); cp = strg->st_cp; outchar('"'); c = *cp++; while (c != '\0') { if (c != '%') { c = *cp++; continue; } outqchar('%'); c = *cp++; /* flags for printf and scanf and *-fieldwidth for printf */ while (c != '\0' && (c == '-' || c == '+' || c == ' ' || c == '#' || c == '0' || c == '*')) { outqchar(c); c = *cp++; } /* numeric field width */ while (c != '\0' && isdigit(c)) { outqchar(c); c = *cp++; } /* precision for printf */ if (c == '.') { outqchar(c); if ((c = *cp++) == '*') { outqchar(c); c = *cp++; } else { while (c != '\0' && isdigit(c)) { outqchar(c); c = *cp++; } } } /* h, l, L and q flags fpr printf and scanf */ if (c == 'h' || c == 'l' || c == 'L' || c == 'q') { outqchar(c); c = *cp++; } /* * The last character. It is always written so we can detect * invalid format specifiers. */ if (c != '\0') { outqchar(c); oc = c; c = *cp++; /* * handle [ for scanf. [-] means that a minus sign * was found at an undefined position. */ if (oc == '[') { if (c == '^') c = *cp++; if (c == ']') c = *cp++; first = 1; while (c != '\0' && c != ']') { if (c == '-') { if (!first && *cp != ']') outqchar(c); } first = 0; c = *cp++; } if (c == ']') { outqchar(c); c = *cp++; } } } } outchar('"'); }
void PropertyLink::deserialize(XmlDeserializer& s) { // Deserialize source property reference... s.deserialize("SourceProperty", src_); // Deserialize destination property reference... s.deserialize("DestinationProperty", dest_); // Was either the source or the destination property not deserialized? if (!src_ || !dest_) { std::string addOn; if (!src_ && !dest_) { addOn = "No source and destination."; } else if (src_) { addOn = "Link source: '"; if (src_->getOwner()) addOn += src_->getOwner()->getID() + "::"; addOn += src_->getGuiName() + "'"; } else if (dest_) { addOn = "Link dest: '"; if (dest_->getOwner()) addOn += dest_->getOwner()->getID() + "::"; addOn += dest_->getGuiName() + "'"; } s.raise(XmlSerializationMemoryAllocationException("Property link could not be established. " + addOn)); } src_->registerLink(this); // Deserialize link evaluator... s.deserialize("Evaluator", evaluator_); if (dest_->getLink(src_) && dest_->getLink(src_)->getLinkEvaluator() == evaluator_) { // this should never happen, but if it does, replace evaluator with fresh instance LWARNING("deserialize(): link has been assigned the same evaluator as its reverse link: " << "src=" << src_->getFullyQualifiedID() << ", dest=" << dest_->getFullyQualifiedID()); evaluator_ = dynamic_cast<LinkEvaluatorBase*>(evaluator_->create()); if (evaluator_) { LERROR(evaluator_->getClassName() << "::create() " << " did not return a LinkEvaluatorBase"); delete evaluator_; evaluator_ = 0; } } if (evaluator_) { // auto-convert old LinkEvaluatorId: if (evaluator_->getClassName() == "LinkEvaluatorId") { std::vector<std::pair<std::string, std::string> > availableFunctions = LinkEvaluatorHelper::getCompatibleLinkEvaluators(src_, dest_); std::string evalType = ""; for(std::vector<std::pair<std::string, std::string> >::iterator i=availableFunctions.begin(); i!=availableFunctions.end(); i++) { if(i->second == "id") evalType = i->first; } if(!evalType.empty()) { //delete evaluator_; evaluator_ = LinkEvaluatorHelper::createEvaluator(evalType); LINFO("Replaced deprecated link evaluator with " << evaluator_->getClassName()); } else { LERROR("Could not find and alternative for old LinkEvaluatorId between " << src_->getTypeDescription() << " and " << dest_->getTypeDescription()); } } // -------------------------------- // auto-convert old LinkEvaluatorIdNormalized: if (evaluator_->getClassName() == "LinkEvaluatorIdNormalized") { std::vector<std::pair<std::string, std::string> > availableFunctions = LinkEvaluatorHelper::getCompatibleLinkEvaluators(src_, dest_); std::string evalType = ""; for(std::vector<std::pair<std::string, std::string> >::iterator i=availableFunctions.begin(); i!=availableFunctions.end(); i++) { if(i->second == "id normalized") evalType = i->first; } if(!evalType.empty()) { //delete evaluator_; evaluator_ = LinkEvaluatorHelper::createEvaluator(evalType); LINFO("Replaced deprecated link evaluator with " << evaluator_->getClassName()); } else { LERROR("Could not find and alternative for old LinkEvaluatorIdNormalized between " << src_->getTypeDescription() << " and " << dest_->getTypeDescription()); } } evaluator_->propertiesChanged(src_, dest_); } }
RenderableGalaxy::RenderableGalaxy(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _stepSize("stepSize", "Step Size", 0.012, 0.0005, 0.05) , _pointStepSize("pointStepSize", "Point Step Size", 0.01, 0.01, 0.1) , _translation("translation", "Translation", glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0), glm::vec3(10.0)) , _rotation("rotation", "Euler rotation", glm::vec3(0.0, 0.0, 0.0), glm::vec3(0), glm::vec3(6.28)) , _enabledPointsRatio("nEnabledPointsRatio", "Enabled points", 0.2, 0, 1) { float stepSize; glm::vec3 scaling, translation, rotation; glm::vec4 color; ghoul::Dictionary volumeDictionary, pointsDictionary; if (dictionary.getValue("Translation", translation)) { _translation = translation; } if (dictionary.getValue("Rotation", rotation)) { _rotation = rotation; } if (dictionary.getValue("StepSize", stepSize)) { _stepSize = stepSize; } if (dictionary.getValue("Volume", volumeDictionary)) { std::string volumeFilename; if (volumeDictionary.getValue("Filename", volumeFilename)) { _volumeFilename = absPath(volumeFilename); } else { LERROR("No volume filename specified."); } glm::vec3 volumeDimensions; if (volumeDictionary.getValue("Dimensions", volumeDimensions)) { _volumeDimensions = static_cast<glm::ivec3>(volumeDimensions); } else { LERROR("No volume dimensions specified."); } glm::vec3 volumeSize; if (volumeDictionary.getValue("Size", volumeSize)) { _volumeSize = static_cast<glm::vec3>(volumeSize); } else { LERROR("No volume dimensions specified."); } } else { LERROR("No volume dictionary specified."); } if (dictionary.getValue("Points", pointsDictionary)) { std::string pointsFilename; if (pointsDictionary.getValue("Filename", pointsFilename)) { _pointsFilename = absPath(pointsFilename); } else { LERROR("No points filename specified."); } glm::vec3 pointsScaling; if (pointsDictionary.getValue("Scaling", pointsScaling)) { _pointScaling = static_cast<glm::vec3>(pointsScaling); } else { LERROR("No volume dimensions specified."); } } else { LERROR("No points dictionary specified."); } }
bool WavefrontGeometry::loadModel(const std::string& filename) { std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; bool success = tinyobj::LoadObj(shapes, materials, err, filename.c_str(), filename.c_str()); if (!success) { LERROR(err); return false; } if (shapes.size() > 1) { LWARNING("Loading models with more than one shape is currently untested"); } size_t totalSizeIndex = 0; size_t totalSizeVertex = 0; for (int i = 0; i < shapes.size(); ++i) { totalSizeIndex += shapes[i].mesh.indices.size(); totalSizeVertex += shapes[i].mesh.positions.size(); if (shapes[i].mesh.positions.size() != shapes[i].mesh.normals.size()) LERROR( "#positions (" << shapes[i].mesh.positions.size() << ")" " != #normals (" << shapes[i].mesh.normals.size() ); } _vertices.resize(totalSizeVertex); std::memset(_vertices.data(), 0, _vertices.size() * sizeof(Vertex)); _indices.resize(totalSizeIndex); std::memset(_indices.data(), 0, _indices.size() * sizeof(int)); // We add all shapes of the model into the same vertex array, one after the other // The _shapeCounts array stores for each shape, how many vertices that shape has size_t currentPosition = 0; size_t p = 0; psc tmp; for (int i = 0; i < shapes.size(); ++i) { for (int j = 0; j < shapes[i].mesh.positions.size() / 3; ++j) { tmp = PowerScaledCoordinate::CreatePowerScaledCoordinate(shapes[i].mesh.positions[3 * j + 0], shapes[i].mesh.positions[3 * j + 1], shapes[i].mesh.positions[3 * j + 2] ); _vertices[j + currentPosition].location[0] = tmp[0]; _vertices[j + currentPosition].location[1] = tmp[1]; _vertices[j + currentPosition].location[2] = tmp[2]; _vertices[j + currentPosition].location[3] = tmp[3]; _vertices[j + currentPosition].normal[0] = shapes[i].mesh.normals[3 * j + 0]; _vertices[j + currentPosition].normal[1] = shapes[i].mesh.normals[3 * j + 1]; _vertices[j + currentPosition].normal[2] = shapes[i].mesh.normals[3 * j + 2]; if (2 * j + 1 < shapes[i].mesh.texcoords.size()) { _vertices[j + currentPosition].tex[0] = shapes[i].mesh.texcoords[2 * j + 0]; _vertices[j + currentPosition].tex[1] = shapes[i].mesh.texcoords[2 * j + 1]; } } currentPosition += shapes[i].mesh.positions.size() / 3; std::copy( shapes[i].mesh.indices.begin(), shapes[i].mesh.indices.end(), _indices.begin() + p ); p += shapes[i].mesh.indices.size(); } return true; }