/*! \brief Lookup a dmz::Mask stored as an unbounded attribute of dmz::UInt32 elements. \note This function does not have an \a Element parameter. Since a mask is unbounded, it is not possible to know in advance the number of elements required to store it. Thus a mask always starts at element zero. \param[in] AttrHandle Attribute handle. \param[out] value Variable to be stored. \return Returns dmz::True if the mask was successfully retrieved. */ dmz::Boolean dmz::Data::lookup_mask (const Handle AttrHandle, Mask &value) const { Boolean result (False); dataStruct *ds = _state.get_data (AttrHandle); if (ds && (ds->Attr.Type == BaseTypeUInt32)) { const Int32 ElementSize (ds->Attr.Size); if (ElementSize > 0) { const Int32 Count (ds->size / ElementSize); value.clear (); value.grow (Count); result = True; UInt32 *ptr ((UInt32 *)(ds->data)); if (ptr) { for (Int32 ix = 0; ix < Count; ix++) { if (!value.set_sub_mask (ix, ptr[ix])) { result = False; } } } } } return result; }
void UpdateMask(Mask& mask, std::vector<RegionalizedData *>& sliced_chip) { unsigned int numRegions = sliced_chip.size(); for (unsigned int rgn=0; rgn<numRegions; ++rgn) { RegionalizedData& local_patch = *sliced_chip[rgn]; int numWells = local_patch.GetNumLiveBeads(); int rowOffset = local_patch.region->row; int colOffset = local_patch.region->col; for (int well=0; well<numWells; ++well) { BeadParams& bead = local_patch.GetParams (well); bead_state& state = *bead.my_state; // Record clonal reads in mask: int row = rowOffset + bead.y; int col = colOffset + bead.x; if(mask.Match(col, row, MaskLib)){ if(state.bad_read) mask.Set(col, row, MaskFilteredBadKey); else if(state.ppf >= mixed_ppf_cutoff()) mask.Set(col, row, MaskFilteredBadResidual); else if(not state.clonal_read) mask.Set(col, row, MaskFilteredBadPPF); } } } }
void multi_img::setBand(unsigned int band, const Band &data, const Mask &mask) { assert(band < size()); assert(data.rows == height && data.cols == width); Band &b = bands[band]; BandConstIt bit = b.begin(); MaskConstIt dit = dirty.begin(); /* we use opencv to copy the band data. afterwards, we update the pixels cache. we do this only for pixels, which are not dirty yet (and would need a complete rebuild anyways. As we instantly fix the other pixels, those do not get marked as dirty by us. */ if (!mask.empty()) { assert(mask.rows == height && mask.cols == width); MaskConstIt mit = mask.begin(); data.copyTo(b, mask); for (int i = 0; bit != b.end(); ++bit, ++dit, ++mit, ++i) if ((*mit > 0)&&(*dit == 0)) pixels[i][band] = *bit; } else { data.copyTo(b); for (int i = 0; bit != b.end(); ++bit, ++dit, ++i) { if ((*dit == 0)) pixels[i][band] = *bit; } } }
void ApplySuperMixedFilter (Mask& mask, std::vector<RegionalizedData *>& sliced_chip) { unsigned int numRegions = sliced_chip.size(); for (unsigned int rgn=0; rgn<numRegions; ++rgn) { RegionalizedData& local_patch = *sliced_chip[rgn]; int numWells = local_patch.GetNumLiveBeads(); int rowOffset = local_patch.region->row; int colOffset = local_patch.region->col; for (int well=0; well<numWells; ++well) { BeadParams& bead = local_patch.GetParams (well); bead_state& state = *bead.my_state; int row = rowOffset + bead.y; int col = colOffset + bead.x; if(mask.Match(col, row, MaskLib)) if (state.ppf < mixed_ppf_cutoff()) state.clonal_read = true; else state.clonal_read = false; else if(mask.Match(col, row, MaskTF)) state.clonal_read = true; } } }
void NewBrushCommand::onQuickboxEnd(const gfx::Rect& rect, ui::MouseButtons buttons) { Mask mask; mask.replace(rect); createBrush(&mask); selectPencilTool(); // If the right-button was used, we clear the selected area. if (buttons & ui::kButtonRight) { try { ContextWriter writer(UIContext::instance(), 250); Transaction transaction(writer.context(), "Clear"); transaction.execute(new cmd::ClearRect(writer.cel(), rect)); transaction.commit(); } catch (const std::exception& ex) { Console::showException(ex); } } // Update the context bar // TODO find a way to avoid all these singletons. Maybe a simple // signal in the context like "brush has changed" could be enough. App::instance()->getMainWindow()->getContextBar() ->updateForCurrentTool(); current_editor->backToPreviousState(); }
inline void bi::SparseStaticUpdaterVisitorHost<B,S,L,PX,OX>::accept( State<B,ON_HOST>& s, const Mask<L>& mask, const int p, const PX& pax, OX& x) { typedef typename front<S>::type front; typedef typename pop_front<S>::type pop_front; typedef typename front::target_type target_type; typedef typename front::coord_type coord_type; const int id = var_id<target_type>::value; int ix = 0; coord_type cox; if (mask.isDense(id)) { while (ix < mask.getSize(id)) { front::simulates(s, p, ix, cox, pax, x); ++cox; ++ix; } } else if (mask.isSparse(id)) { while (ix < mask.getSize(id)) { cox.setIndex(mask.getIndex(id, ix)); front::simulates(s, p, ix, cox, pax, x); ++ix; } } SparseStaticUpdaterVisitorHost<B,pop_front,L,PX,OX>::accept(s, mask, p, pax, x); }
dmz::Mask dmz::ArchivePluginObject::_filter_state ( const Handle AttrHandle, const Mask &Value, const UInt32 Mode) { Mask result (Value); if (_currentFilterList) { FilterStruct *filter = _currentFilterList->list; while (filter) { if (filter->mode & Mode) { Mask *filterMask (filter->stateTable.lookup (AttrHandle)); if (filterMask) { result.unset (*filterMask); } } filter = filter->next; } } return result; }
void ParseWell(size_t rowIx, size_t colIx, size_t regionIx, vector<int> &match, Mask &mask, int maskCenter, int maskMatch, vector<Traces> &flows, ostream &out, int frameStart, int frameEnd) { int idx = mask.ToIndex(rowIx, colIx); if ((mask[idx] & maskCenter) == 0) { return; } centerSeen++; vector<int> wells; vector<float> trace; mask.GetNeighbors(rowIx, colIx, wells); ION_ASSERT(wells.size() == match.size(), "Wells don't match string."); if (PatternMatch(match, wells, mask, maskMatch)) { out <<rowIx << "\t" << colIx << "\t" << idx << "\t" << regionIx << "\t"; for (size_t i = 0; i < wells.size(); i++) { int full = ((mask[wells[i]] & maskMatch) > 0) ? 1 : 0; out << full; } for (size_t i = 0; i < flows.size(); i++) { flows[i].GetTraces(idx, trace); float sum = 0; for (int fIx = frameStart; fIx < frameEnd; fIx++) { sum += trace[fIx]; } sum = sum / (frameEnd - frameStart); out << "\t" << sum; } for (size_t i = 0; i < flows.size(); i++) { out << "\t" << flows[i].GetT0(idx); } out << endl; } }
void TraceStoreCol::Init(Mask &mask, size_t frames, const char *flowOrder, int numFlowsBuff, int maxFlow, int rowStep, int colStep) { pthread_mutex_init (&mLock, NULL); mUseMeshNeighbors = 1; mRowRefStep = rowStep; mColRefStep = colStep; mMinRefProbes = floor (mRowRefStep * mColRefStep * .1); mRows = mask.H(); mCols = mask.W(); mFrames = frames; mFrameStride = mRows * mCols; mFlows = mFlowsBuf = maxFlow; mFlowFrameStride = mFrameStride * maxFlow; mMaxDist = 2 * sqrt(rowStep*rowStep + colStep+colStep); mFlowOrder = flowOrder; mWells = mRows * mCols; mUseAsReference.resize (mWells, false); int keep = 0; int empties = 0; mRefGridsValid.resize (mFlowsBuf, 0); mRefGrids.resize (mFlowsBuf); mData.resize (mWells * mFrames * mFlowsBuf); std::fill (mData.begin(), mData.end(), 0); }
CvConnectedComp* MeanShift::track(const Image* image, const Mask* probabilisticMap) { if (!m_trackingHist || !image) return NULL; //Obtain probabilistic image from backProject of histogram Mask* probimage = m_trackingHist->calcBackProjection(image); if (probabilisticMap) (*probimage) &= (*probabilisticMap); if ((m_lastPostition.width < 0) || (m_lastPostition.height < 0) || (m_lastPostition.x > image->width()) || (m_lastPostition.y > image->height())) return &m_components; //cvTermCriteria with CV_TERMCRIT_ITER specifies number of iteratios until center of mass found //cvTermCriteria with CV_TERMCRIT_EPS specifies the max error of the result cvMeanShift(probimage->cvImage(), m_lastPostition, cvTermCriteria(CV_TERMCRIT_EPS, 256, .001l), &m_components); //Update lastPosition m_lastPostition = m_components.rect; delete probimage; return &m_components; }
static Mask *ase_file_read_mask_chunk(FILE *f) { int c, u, v, byte; Mask *mask; // Read chunk data int x = fgetw(f); int y = fgetw(f); int w = fgetw(f); int h = fgetw(f); ase_file_read_padding(f, 8); std::string name = ase_file_read_string(f); mask = new Mask(); mask->setName(name.c_str()); mask->replace(x, y, w, h); // Read image data for (v=0; v<h; v++) for (u=0; u<(w+7)/8; u++) { byte = fgetc(f); for (c=0; c<8; c++) image_putpixel(mask->getBitmap(), u*8+c, v, byte & (1<<(7-c))); } return mask; }
bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source, float& computedEnergy) const { itk::Index<2> targetPixel = ITKHelpers::CreateIndex(target); itk::ImageRegion<2> targetRegion = ITKHelpers::GetRegionInRadiusAroundPixel(targetPixel, HalfWidth); itk::Index<2> sourcePixel = ITKHelpers::CreateIndex(source); itk::ImageRegion<2> sourceRegion = ITKHelpers::GetRegionInRadiusAroundPixel(sourcePixel, HalfWidth); // Compute the variance of the valid pixels in the target region std::vector<itk::Index<2> > validPixelsTargetRegion = MaskImage->GetValidPixelsInRegion(targetRegion); typename TImage::PixelType targetRegionSourcePixelVariance = ITKHelpers::VarianceOfPixelsAtIndices(Image, validPixelsTargetRegion); // Compute the variance of the pixels in the source region corresponding to hole pixels in the target region. std::vector<itk::Offset<2> > holeOffsets = MaskImage->GetHoleOffsetsInRegion(targetRegion); std::vector<itk::Index<2> > sourcePatchHolePixels = ITKHelpers::OffsetsToIndices(holeOffsets, sourceRegion.GetIndex()); typename TImage::PixelType sourceRegionTargetPixelVariance = ITKHelpers::VarianceOfPixelsAtIndices(Image, sourcePatchHolePixels); // Compute the difference computedEnergy = (targetRegionSourcePixelVariance - sourceRegionTargetPixelVariance).GetNorm(); std::cout << "VarianceDifferenceAcceptanceVisitor Energy: " << computedEnergy << std::endl; if(computedEnergy < DifferenceThreshold) { std::cout << "VarianceDifferenceAcceptanceVisitor: Match accepted (less than " << DifferenceThreshold << ")" << std::endl; return true; } else { std::cout << "VarianceDifferenceAcceptanceVisitor: Match rejected (greater than " << DifferenceThreshold << ")" << std::endl; return false; } };
void dmz::CyclesPluginWallOSG::update_object_state ( const UUID &Identity, const Handle ObjectHandle, const Handle AttributeHandle, const Mask &Value, const Mask *PreviousValue) { const Boolean IsDead (Value.contains (_deadState)); const Boolean WasDead (PreviousValue ? PreviousValue->contains (_deadState) : False); const Boolean IsOn (Value.contains (_engineOnState)); const Boolean WasOn (PreviousValue ? PreviousValue->contains (_engineOnState) : False); if ((IsDead && !WasDead) || (!IsOn && WasOn)) { ObjectStruct *os (_objectTable.remove (ObjectHandle)); if (os && !_deadTable.store (ObjectHandle, os)) { _remove_wall (*os); delete os; os = 0; } } else if (IsOn && !WasOn) { ObjectModule *objMod (get_object_module ()); if (objMod) { _create_object_wall (ObjectHandle, objMod->lookup_object_type (ObjectHandle)); } } }
void ApplyClonalFilter (Mask& mask, std::vector<RegionalizedData *>& sliced_chip, const deque<float>& ppf, const deque<float>& ssq, const PolyclonalFilterOpts & opts) { clonal_filter filter; filter_counts counts; make_filter (filter, counts, ppf, ssq, opts); unsigned int numRegions = sliced_chip.size(); for (unsigned int rgn=0; rgn<numRegions; ++rgn) { RegionalizedData& local_patch = *sliced_chip[rgn]; int numWells = local_patch.GetNumLiveBeads(); int rowOffset = local_patch.region->row; int colOffset = local_patch.region->col; for (int well=0; well<numWells; ++well) { BeadParams& bead = local_patch.GetParams (well); bead_state& state = *bead.my_state; int row = rowOffset + bead.y; int col = colOffset + bead.x; if(mask.Match(col, row, MaskLib)) state.clonal_read = filter.is_clonal (state.ppf, state.ssq, opts.mixed_stringency); else if(mask.Match(col, row, MaskTF)) state.clonal_read = true; } } }
PixelNeighbors::PixelNeighbors(int width, int height, const Mask& mask, Mask::Value maskValidNeighborValue, int x, int y) : m_hasTop(y > 0 && mask.GetValue(x, y - 1) == maskValidNeighborValue) , m_hasBottom(y < height - 1 && mask.GetValue(x, y + 1) == maskValidNeighborValue) , m_hasLeft(x > 0 && mask.GetValue(x - 1, y) == maskValidNeighborValue) , m_hasRight(x < width - 1 && mask.GetValue(x + 1, y) == maskValidNeighborValue) { CacheNum(); }
// Loads a MSK file (Animator and Animator Pro format) Mask* load_msk_file(const char* filename) { #if (MAKE_VERSION(4, 2, 1) >= MAKE_VERSION(ALLEGRO_VERSION, \ ALLEGRO_SUB_VERSION, \ ALLEGRO_WIP_VERSION)) int orig_size = file_size(filename); #else int orig_size = file_size_ex(filename); #endif int i, c, u, v, byte, magic, size; Mask *mask = NULL; PACKFILE *f; f = pack_fopen(filename, F_READ); if (!f) return NULL; size = pack_igetl(f); magic = pack_igetw(f); // Animator Pro MSK format if ((size == orig_size) && (magic == 0x9500)) { int x, y; pack_fclose(f); // Just load an Animator Pro PIC file base::UniquePtr<Image> image(load_pic_file(filename, &x, &y, NULL)); if (image != NULL && (image->getPixelFormat() == IMAGE_BITMAP)) { mask = new Mask(x, y, image.release()); } } // Animator MSK format else if (orig_size == 8000) { mask = new Mask(); mask->replace(0, 0, 320, 200); u = v = 0; for (i=0; i<8000; i++) { byte = pack_getc (f); for (c=0; c<8; c++) { mask->getBitmap()->putpixel(u, v, byte & (1<<(7-c))); u++; if (u == 320) { u = 0; v++; } } } pack_fclose(f); } else { pack_fclose(f); } return mask; }
bool MaskSequence::add(const Mask &frame) // use && { if (frame.size().size_x == _size.size_x && frame.size().size_y == _size.size_y) { _frames.push_back(frame); _size.size_t++; return true; } return false; }
/** * Add Exchange in GridBuffer memory space. * * An Exchange is added to this GridBuffer. The exchange buffers use * the same memory as this GridBuffer. * * @param dataPlace place where received data are stored [GUARD | BORDER] * if dataPlace=GUARD than copy other BORDER to my GUARD * if dataPlace=BORDER than copy other GUARD to my BORDER * @param receive a Mask which describes the directions for the exchange * @param guardingCells number of guarding cells in each dimension * @param sizeOnDevice if true, internal buffers have their size information on the device, too */ void addExchange(uint32_t dataPlace, const Mask &receive, DataSpace<DIM> guardingCells, uint32_t communicationTag, bool sizeOnDevice = false) { if (hasOneExchange && (communicationTag != lastUsedCommunicationTag)) throw std::runtime_error("It is not allowed to give the same GridBuffer different communicationTags"); lastUsedCommunicationTag = communicationTag; receiveMask = receiveMask + receive; sendMask = this->receiveMask.getMirroredMask(); Mask send = receive.getMirroredMask(); for (uint32_t ex = 1; ex< -12 * (int) DIM + 6 * (int) DIM * (int) DIM + 9; ++ex) { if (send.isSet(ex)) { uint32_t uniqCommunicationTag = (communicationTag << 5) | ex; if (!hasOneExchange && !privateGridBuffer::UniquTag::getInstance().isTagUniqu(uniqCommunicationTag)) { std::stringstream message; message << "unique exchange communication tag (" << uniqCommunicationTag << ") witch is created from communicationTag (" << communicationTag << ") allready used for other gridbuffer exchange"; throw std::runtime_error(message.str()); } hasOneExchange = true; if (sendExchanges[ex] != NULL) { throw std::runtime_error("Exchange already added!"); } //std::cout<<"Add Exchange: send="<<ex<<" receive="<<Mask::getMirroredExchangeType((ExchangeType)ex)<<std::endl; maxExchange = std::max(maxExchange, ex + 1u); sendExchanges[ex] = new ExchangeIntern<BORDERTYPE, DIM > (*deviceBuffer, gridLayout, guardingCells, (ExchangeType) ex, uniqCommunicationTag, dataPlace == GUARD ? BORDER : GUARD, sizeOnDevice); ExchangeType recvex = Mask::getMirroredExchangeType(ex); maxExchange = std::max(maxExchange, recvex + 1u); receiveExchanges[recvex] = new ExchangeIntern<BORDERTYPE, DIM > ( *deviceBuffer, gridLayout, guardingCells, recvex, uniqCommunicationTag, dataPlace == GUARD ? GUARD : BORDER, sizeOnDevice); } } }
int LoadMask(Mask &mask, char *fileName, int version, MaskType withThese) { int beadsFound = 0; int n = 0; int w, h; w = mask.W(); h = mask.H(); FILE *fp = NULL; fopen_s(&fp, fileName, "r"); if (fp) { int x, y; // read the XY offset and the size of the input mask x = 0; y = 0; if (version == 1) { // version 1 masks are from TorrentExplorer, so they are not full-chip sized double _x, _y; n = fscanf_s(fp, "%lf,%lf\n", &_x, &_y); assert(n == 2); x = (int)_x; y = (int)_y; n = fscanf_s(fp, "%d,%d\n", &w, &h); assert(n==2); } int i,j; int val; for(j=0;j<h;j++) { for(i=0;i<w;i++) { if (i < (w-1)) { n = fscanf_s(fp, "%d,", &val); // comma scanned in, but seems to also work with just a space in a mask input file assert(n==1); } else { n = fscanf_s(fp, "%d\n", &val); // last entry per row has no comma assert(n==1); } if (val > 0) { // if (val == 64) // mask[(i+x)+(j+y)*mask.W()] |= MaskBead; // else mask[(i+x)+(j+y)*mask.W()] |= withThese; beadsFound++; } } } fclose(fp); } else { fprintf (stderr, "%s: %s\n", fileName, strerror(errno)); } return beadsFound; }
Status Resolver::resolveCached( const vector<Address>& addresses, vector<ExpandedNodeId>& expandedNodeIds, vector<Status>& statuses, Mask& expandedNodeIdMask, Mask& relativePathMask) { logger_->debug("Resolving the addresses by querying the cache"); // declare the return status Status ret(statuscodes::Good); // declare the number of addresses size_t noOfAddresses = addresses.size(); // resize the masks expandedNodeIdMask.resize(noOfAddresses); relativePathMask.resize(noOfAddresses); // loop through the addresses for (size_t i=0; i<noOfAddresses; i++) { logger_->debug("Trying to find address %d in the cache", i); if (database_->addressCache.find(addresses[i], expandedNodeIds[i])) { statuses[i] = statuscodes::Good; logger_->debug("Address %d was already cached", i); } else { if (addresses[i].isExpandedNodeId()) { expandedNodeIdMask.set(i); logger_->debug("Address %d is an ExpandedNodeId not found in the cache", i); } else if (addresses[i].isRelativePath()) { relativePathMask.set(i); logger_->debug("Address %d is a RelativePath not found in the cache", i); } else { ret = EmptyAddressError(); logger_->error("Address %d cannot be resolved since it's an empty address", i); break; } } } return ret; }
Status Resolver::resolveRelativePathsStartingAddresses( const vector<Address>& relativePathAddresses, Mask& mask, vector<BrowsePath>& results, vector<Status>& statuses) { // declare the return status Status ret(statuscodes::Good); // declare the number of relative paths size_t noOfRelativePaths = relativePathAddresses.size(); // resize the output parameters results.resize(noOfRelativePaths); statuses.resize(noOfRelativePaths); // fill a vector containing all starting addresses vector<Address> startingAddresses; for (size_t i = 0; i < noOfRelativePaths && ret.isGood(); i++) { if (mask.isSet(i)) startingAddresses.push_back(*(relativePathAddresses[i].getStartingAddress())); } // resolve them (recursively!) vector<ExpandedNodeId> startingAddressesResults; vector<Status> startingAddressesStatuses; ret = resolve(startingAddresses, startingAddressesResults, startingAddressesStatuses); // update the results for (size_t i = 0, j = 0; i < noOfRelativePaths && ret.isGood(); i++) { if (mask.isSet(i)) { // update the results results[i].startingExpandedNodeId = startingAddressesResults[j]; results[i].relativePath = relativePathAddresses[i].getRelativePath(); // update the statuses statuses[i] = startingAddressesStatuses[j]; // update the mask (only resolved starting addresses should be processed further!) if (statuses[i].isNotGood()) mask.unset(i); // increment the index of the startingAddressesResults j++; } } return ret; }
int main(const int argc, char* argv[]) { namespace js = anu_am::json; char* infile = argv[1]; if (argc < 2) { std::cerr << "Usage:" << argv[0] << " INPUT [OUTPUT]" << std::endl; return 1; } // Read the data for this process. NCFileInfo const info = readFileInfo(infile); Variable const var = findVolumeVariable(info); std::vector<size_t> const dims = readDimensions(info); CubicalComplex complex(dims.at(0), dims.at(1), dims.at(2)); Scalars::DataPtr scalarData = readVolumeData<Value>(infile); Scalars scalars(complex, scalarData); // Process the data. Mask const out = boundaries(complex, scalars); // Generate metadata std::string const parentID = guessDatasetID(infile, info.attributes()); std::string const thisID = derivedID(parentID, "segmented", "BBG"); std::string const outfile = argc > 2 ? argv[2] : (stripTimestamp(thisID) + ".nc"); js::Object const fullSpec = js::Object ("id" , thisID) ("process" , "Basin Boundaries via Gyulassi-Bremer-Pascucci Method") ("sourcefile" , __FILE__) ("revision" , js::Object("id", GIT_REVISION)("date", GIT_TIMESTAMP)) ("parent" , parentID) ("predecessors", js::Array(parentID)) ("parameters" , js::Object()); std::string const description = js::toString(fullSpec, 2); // Write the results to the output file writeVolumeData( out.data(), outfile, "segmented", dims.at(0), dims.at(1), dims.at(2), VolumeWriteOptions() .fileAttributes(inheritableAttributes(info.attributes())) .datasetID(thisID) .description(description) .computeHistogram(false)); }
// TimeSlice Interface void dmz::EntityPluginDeadTimer::update_time_slice (const Float64 TimeDelta) { ObjectModule *objMod (get_object_module ()); if (objMod && _hil) { Mask state; objMod->lookup_state (_hil, _defaultHandle, state); state.unset (_deadState); objMod->store_state (_hil, _defaultHandle, state); } }
void InvertMaskCommand::onExecute(Context* context) { bool hasMask = false; { const ContextReader reader(context); if (reader.document()->isMaskVisible()) hasMask = true; } // without mask?... if (!hasMask) { // so we select all Command* mask_all_cmd = CommandsModule::instance()->getCommandByName(CommandId::MaskAll); context->executeCommand(mask_all_cmd); } // invert the current mask else { ContextWriter writer(context); Document* document(writer.document()); Sprite* sprite(writer.sprite()); // Select all the sprite area base::UniquePtr<Mask> mask(new Mask()); mask->replace(sprite->bounds()); // Remove in the new mask the current sprite marked region const gfx::Rect& maskBounds = document->mask()->bounds(); doc::fill_rect(mask->bitmap(), maskBounds.x, maskBounds.y, maskBounds.x + maskBounds.w-1, maskBounds.y + maskBounds.h-1, 0); Mask* curMask = document->mask(); if (curMask->bitmap()) { // Copy the inverted region in the new mask (we just modify the // document's mask temporaly here) curMask->freeze(); curMask->invert(); doc::copy_image(mask->bitmap(), curMask->bitmap(), curMask->bounds().x, curMask->bounds().y); curMask->invert(); curMask->unfreeze(); } // We need only need the area inside the sprite mask->intersect(sprite->bounds()); // Set the new mask Transaction transaction(writer.context(), "Mask Invert", DoesntModifyDocument); transaction.execute(new cmd::SetMask(document, mask)); transaction.commit(); document->generateMaskBoundaries(); update_screen_for_document(document); } }
// Loads a MSK file (Animator and Animator Pro format) Mask* load_msk_file(const char* filename) { int orig_size = base::file_size(filename); int i, c, u, v, byte, magic, size; Mask* mask = NULL; FILE* f = base::open_file_raw(filename, "r"); if (!f) return NULL; size = base::fgetl(f); magic = base::fgetw(f); // Animator Pro MSK format if ((size == orig_size) && (magic == 0x9500)) { int x, y; fclose(f); // Just load an Animator Pro PIC file base::UniquePtr<Image> image(load_pic_file(filename, &x, &y, NULL)); if (image != NULL && (image->pixelFormat() == IMAGE_BITMAP)) mask = new Mask(x, y, image.release()); } // Animator MSK format else if (orig_size == 8000) { mask = new Mask(); mask->replace(0, 0, 320, 200); u = v = 0; for (i=0; i<8000; i++) { byte = getc(f); for (c=0; c<8; c++) { mask->bitmap()->putPixel(u, v, byte & (1<<(7-c))); u++; if (u == 320) { u = 0; v++; } } } fclose(f); } else { fclose(f); } return mask; }
void dmz::QtPluginCanvasObjectBasic::_update_group_state ( StateGroupStruct &group, const Mask &Value, const Mask &PreviousValue) { StateStruct *ssToHide (0); StateStruct *ssToShow (0); StateStruct *ss (group.stateList); Boolean done (False); while (ss && !done) { if (!ssToShow) { if (!Value) { ssToShow = group.defaultState; } else if (ss->State) { if (Value.contains (ss->State)) { ssToShow = ss; } } } if (!ssToHide) { if (!PreviousValue) { ssToHide = group.defaultState; } else if (ss->State) { if (PreviousValue.contains (ss->State)) { ssToHide = ss; } } } if (ssToShow && ssToHide) { done = True; } ss = ss->next; } if (ssToHide) { ssToHide->set_visible (False); } else if (group.defaultState) { group.defaultState->set_visible (False); } if (ssToShow) { ssToShow->set_visible (True); } else if (group.defaultState) { group.defaultState->set_visible (True); } }
void Loader::setupMaskJson(Mask& mask, const ofJson& json, const ofVec2f &size) { mask.name_ = json.value("name", "noname"); const string& blend_mode = json.value("mode", "none"); if(blend_mode == "none") { mask.blend_mode_ = OF_BLENDMODE_ALPHA; } if(blend_mode == "add") { mask.blend_mode_ = OF_BLENDMODE_ADD; } if(blend_mode == "subtract") { mask.blend_mode_ = OF_BLENDMODE_SUBTRACT; } { auto prop = mask.getPathProperty(); setupPropertyKeysJson(*prop, json); prop->setSize(size); prop->setInverted(json.value("inverted", false)); } setupPropertyKeysJson(*mask.getOpacityProperty(), json["opacity"], 0.01f); }
void MaskContentCommand::onExecute(Context* context) { Document* document; { ContextWriter writer(context); document = writer.document(); Cel* cel = writer.cel(); // Get current cel (can be NULL) if (!cel) return; gfx::Color color; if (writer.layer()->isBackground()) { ColorPicker picker; picker.pickColor(*writer.site(), gfx::PointF(0.0, 0.0), current_editor->projection(), ColorPicker::FromComposition); color = color_utils::color_for_layer(picker.color(), writer.layer()); } else color = cel->image()->maskColor(); Mask newMask; gfx::Rect imgBounds = cel->image()->bounds(); if (algorithm::shrink_bounds(cel->image(), imgBounds, color)) { newMask.replace(imgBounds.offset(cel->bounds().origin())); } else { newMask.replace(cel->bounds()); } Transaction transaction(writer.context(), "Select Content", DoesntModifyDocument); transaction.execute(new cmd::SetMask(document, &newMask)); transaction.commit(); document->resetTransformation(); document->generateMaskBoundaries(); } // Select marquee tool if (tools::Tool* tool = App::instance()->toolBox() ->getToolById(tools::WellKnownTools::RectangularMarquee)) { ToolBar::instance()->selectTool(tool); } update_screen_for_document(document); }
__parallel__ void stencilKernel(Array<int> input,Array<int> output,Mask<int> mask,int null,size_t i){ int sum=input(i); for(int z=0;z<mask.size;z++){ sum += mask.get(z,input,i); } output(i) = sum; }
RefTargetHandle Mask::Clone(RemapDir &remap) { Mask *mnew = new Mask(); *((MtlBase*)mnew) = *((MtlBase*)this); // copy superclass stuff mnew->ReplaceReference(2,remap.CloneRef(pblock)); mnew->ivalid.SetEmpty(); mnew->mapValid.SetEmpty(); for (int i = 0; i<NSUBTEX; i++) { mnew->subTex[i] = NULL; if (subTex[i]) mnew->ReplaceReference(i,remap.CloneRef(subTex[i])); mnew->mapOn[i] = mapOn[i]; mnew->invertMask = invertMask; } BaseClone(this, mnew, remap); return (RefTargetHandle)mnew; }