// This test hammers the GPU textblobcache and font atlas static void text_blob_cache_inner(skiatest::Reporter* reporter, GrContext* context, int maxTotalText, int maxGlyphID, int maxFamilies, bool normal, bool stressTest) { // setup surface uint32_t flags = 0; SkSurfaceProps props(flags, SkSurfaceProps::kLegacyFontHost_InitType); // configure our context for maximum stressing of cache and atlas if (stressTest) { GrTest::SetupAlwaysEvictAtlas(context); context->contextPriv().setTextBlobCacheLimit_ForTesting(0); } SkImageInfo info = SkImageInfo::Make(kWidth, kHeight, kN32_SkColorType, kPremul_SkAlphaType); auto surface(SkSurface::MakeRenderTarget(context, SkBudgeted::kNo, info, 0, &props)); REPORTER_ASSERT(reporter, surface); if (!surface) { return; } SkCanvas* canvas = surface->getCanvas(); sk_sp<SkFontMgr> fm(SkFontMgr::RefDefault()); int count = SkMin32(fm->countFamilies(), maxFamilies); // make a ton of text SkAutoTArray<uint16_t> text(maxTotalText); for (int i = 0; i < maxTotalText; i++) { text[i] = i % maxGlyphID; } // generate textblobs SkTArray<sk_sp<SkTextBlob>> blobs; for (int i = 0; i < count; i++) { SkPaint paint; paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); paint.setTextSize(48); // draw big glyphs to really stress the atlas SkString familyName; fm->getFamilyName(i, &familyName); sk_sp<SkFontStyleSet> set(fm->createStyleSet(i)); for (int j = 0; j < set->count(); ++j) { SkFontStyle fs; set->getStyle(j, &fs, nullptr); // We use a typeface which randomy returns unexpected mask formats to fuzz sk_sp<SkTypeface> orig(set->createTypeface(j)); if (normal) { paint.setTypeface(orig); } else { paint.setTypeface(sk_make_sp<SkRandomTypeface>(orig, paint, true)); } SkTextBlobBuilder builder; for (int aa = 0; aa < 2; aa++) { for (int subpixel = 0; subpixel < 2; subpixel++) { for (int lcd = 0; lcd < 2; lcd++) { paint.setAntiAlias(SkToBool(aa)); paint.setSubpixelText(SkToBool(subpixel)); paint.setLCDRenderText(SkToBool(lcd)); if (!SkToBool(lcd)) { paint.setTextSize(160); } const SkTextBlobBuilder::RunBuffer& run = builder.allocRun(paint, maxTotalText, 0, 0, nullptr); memcpy(run.glyphs, text.get(), maxTotalText * sizeof(uint16_t)); } } } blobs.emplace_back(builder.make()); } } // create surface where LCD is impossible info = SkImageInfo::MakeN32Premul(kWidth, kHeight); SkSurfaceProps propsNoLCD(0, kUnknown_SkPixelGeometry); auto surfaceNoLCD(canvas->makeSurface(info, &propsNoLCD)); REPORTER_ASSERT(reporter, surface); if (!surface) { return; } SkCanvas* canvasNoLCD = surfaceNoLCD->getCanvas(); // test redraw draw(canvas, 2, blobs); draw(canvasNoLCD, 2, blobs); // test draw after free context->freeGpuResources(); draw(canvas, 1, blobs); context->freeGpuResources(); draw(canvasNoLCD, 1, blobs); // test draw after abandon context->abandonContext(); draw(canvas, 1, blobs); }
PyObject* WindowXML_New(PyTypeObject *type, PyObject *args, PyObject *kwds) { WindowXML *self; self = (WindowXML*)type->tp_alloc(type, 0); if (!self) return NULL; new(&self->sXMLFileName) string(); new(&self->sFallBackPath) string(); new(&self->vecControls) std::vector<Control*>(); self->iWindowId = -1; PyObject* pyOXMLname = NULL; PyObject* pyOname = NULL; PyObject* pyDName = NULL; PyObject* pyRes = NULL; string strXMLname, strFallbackPath; string strDefault = "Default"; string resolution = "720p"; if (!PyArg_ParseTuple(args, (char*)"OO|OO", &pyOXMLname, &pyOname, &pyDName, &pyRes)) return NULL; PyXBMCGetUnicodeString(strXMLname, pyOXMLname); PyXBMCGetUnicodeString(strFallbackPath, pyOname); if (pyDName) PyXBMCGetUnicodeString(strDefault, pyDName); if (pyRes) PyXBMCGetUnicodeString(resolution, pyRes); // Check to see if the XML file exists in current skin. If not use fallback path to find a skin for the script RESOLUTION_INFO res; CStdString strSkinPath = g_SkinInfo->GetSkinPath(strXMLname, &res); if (!XFILE::CFile::Exists(strSkinPath)) { // Check for the matching folder for the skin in the fallback skins folder CStdString fallbackPath = URIUtils::AddFileToFolder(strFallbackPath, "resources"); fallbackPath = URIUtils::AddFileToFolder(fallbackPath, "skins"); CStdString basePath = URIUtils::AddFileToFolder(fallbackPath, g_SkinInfo->ID()); strSkinPath = g_SkinInfo->GetSkinPath(strXMLname, &res, basePath); if (!XFILE::CFile::Exists(strSkinPath)) { // Finally fallback to the DefaultSkin as it didn't exist in either the XBMC Skin folder or the fallback skin folder CStdString str("none"); AddonProps props(str, ADDON_SKIN, "", ""); props.path = URIUtils::AddFileToFolder(fallbackPath, strDefault); CSkinInfo::TranslateResolution(resolution, res); CSkinInfo skinInfo(props, res); skinInfo.Start(); strSkinPath = skinInfo.GetSkinPath(strXMLname, &res); if (!XFILE::CFile::Exists(strSkinPath)) { PyErr_SetString(PyExc_TypeError, "XML File for Window is missing"); return NULL; } } } self->sFallBackPath = strFallbackPath; self->sXMLFileName = strSkinPath; self->bUsingXML = true; // create new GUIWindow if (!Window_CreateNewWindow((Window*)self, false)) { // error is already set by Window_CreateNewWindow, just release the memory self->vecControls.clear(); self->vecControls.~vector(); self->sFallBackPath.~string(); self->sXMLFileName.~string(); self->ob_type->tp_free((PyObject*)self); return NULL; } ((CGUIWindow*)(self->pWindow))->SetCoordsRes(res); return (PyObject*)self; }
void MaterialPropertyStorage::prolongStatefulProps(const std::vector<std::vector<QpMap> > & refinement_map, QBase & qrule, QBase & qrule_face, MaterialPropertyStorage & parent_material_props, MaterialData & child_material_data, const Elem & elem, const int input_parent_side, const int input_child, const int input_child_side) { mooseAssert(input_child != -1 || input_parent_side == input_child_side, "Invalid inputs!"); unsigned int n_qpoints = 0; // If we passed in -1 for these then we really need to store properties at 0 unsigned int parent_side = input_parent_side == -1 ? 0 : input_parent_side; unsigned int child_side = input_child_side == -1 ? 0 : input_child_side; if (input_child_side == -1) // Not doing side projection (ie, doing volume projection) n_qpoints = qrule.n_points(); else n_qpoints = qrule_face.n_points(); child_material_data.size(n_qpoints); unsigned int n_children = elem.n_children(); std::vector<unsigned int> children; if (input_child != -1) // Passed in a child explicitly children.push_back(input_child); else { children.resize(n_children); for (unsigned int child=0; child < n_children; child++) children[child] = child; } for (const auto & child : children) { // If we're not projecting an internal child side, but we are projecting sides, see if this child is on that side if (input_child == -1 && input_child_side != -1 && !elem.is_child_on_side(child, parent_side)) continue; const Elem * child_elem = elem.child(child); mooseAssert(child < refinement_map.size(), "Refinement_map vector not initialized"); const std::vector<QpMap> & child_map = refinement_map[child]; if (props()[child_elem][child_side].size() == 0) props()[child_elem][child_side].resize(_stateful_prop_id_to_prop_id.size()); if (propsOld()[child_elem][child_side].size() == 0) propsOld()[child_elem][child_side].resize(_stateful_prop_id_to_prop_id.size()); if (propsOlder()[child_elem][child_side].size() == 0) propsOlder()[child_elem][child_side].resize(_stateful_prop_id_to_prop_id.size()); // init properties (allocate memory. etc) for (unsigned int i=0; i < _stateful_prop_id_to_prop_id.size(); ++i) { // duplicate the stateful property in property storage (all three states - we will reuse the allocated memory there) // also allocating the right amount of memory, so we do not have to resize, etc. if (props()[child_elem][child_side][i] == NULL) props()[child_elem][child_side][i] = child_material_data.props()[ _stateful_prop_id_to_prop_id[i] ]->init(n_qpoints); if (propsOld()[child_elem][child_side][i] == NULL) propsOld()[child_elem][child_side][i] = child_material_data.propsOld()[ _stateful_prop_id_to_prop_id[i] ]->init(n_qpoints); if (hasOlderProperties()) if (propsOlder()[child_elem][child_side][i] == NULL) propsOlder()[child_elem][child_side][i] = child_material_data.propsOlder()[ _stateful_prop_id_to_prop_id[i] ]->init(n_qpoints); // Copy from the parent stateful properties for (unsigned int qp=0; qp<refinement_map[child].size(); qp++) { PropertyValue * child_property = props()[child_elem][child_side][i]; mooseAssert(props().contains(&elem), "Parent pointer is not in the MaterialProps data structure"); PropertyValue * parent_property = parent_material_props.props()[&elem][parent_side][i]; child_property->qpCopy(qp, parent_property, child_map[qp]._to); propsOld()[child_elem][child_side][i]->qpCopy(qp, parent_material_props.propsOld()[&elem][parent_side][i], child_map[qp]._to); if (hasOlderProperties()) propsOlder()[child_elem][child_side][i]->qpCopy(qp, parent_material_props.propsOlder()[&elem][parent_side][i], child_map[qp]._to); } } } }
size_t generateVPLs(const Scene *scene, Random *random, size_t offset, size_t count, int maxDepth, bool prune, std::deque<VPL> &vpls) { if (maxDepth <= 1) return 0; static Sampler *sampler = NULL; if (!sampler) { Properties props("halton"); props.setInteger("scramble", 0); sampler = static_cast<Sampler *> (PluginManager::getInstance()-> createObject(MTS_CLASS(Sampler), props)); sampler->configure(); sampler->generate(Point2i(0)); } const Sensor *sensor = scene->getSensor(); Float time = sensor->getShutterOpen() + sensor->getShutterOpenTime() * sampler->next1D(); const Frame stdFrame(Vector(1,0,0), Vector(0,1,0), Vector(0,0,1)); int retries = 0; while (vpls.size() < count) { sampler->setSampleIndex(++offset); if (vpls.empty() && ++retries > 10000) { /* Unable to generate VPLs in this scene -- give up. */ return 0; } PositionSamplingRecord pRec(time); DirectionSamplingRecord dRec; Spectrum weight = scene->sampleEmitterPosition(pRec, sampler->next2D()); size_t start = vpls.size(); /* Sample an emitted particle */ const Emitter *emitter = static_cast<const Emitter *>(pRec.object); if (!emitter->isEnvironmentEmitter() && emitter->needsDirectionSample()) { VPL lumVPL(EPointEmitterVPL, weight); lumVPL.its.p = pRec.p; lumVPL.its.time = time; lumVPL.its.shFrame = pRec.n.isZero() ? stdFrame : Frame(pRec.n); lumVPL.emitter = emitter; appendVPL(scene, random, lumVPL, prune, vpls); weight *= emitter->sampleDirection(dRec, pRec, sampler->next2D()); } else { /* Hack to get the proper information for directional VPLs */ DirectSamplingRecord diRec( scene->getKDTree()->getAABB().getCenter(), pRec.time); Spectrum weight2 = emitter->sampleDirect(diRec, sampler->next2D()) / scene->pdfEmitterDiscrete(emitter); if (weight2.isZero()) continue; VPL lumVPL(EDirectionalEmitterVPL, weight2); lumVPL.its.p = Point(0.0); lumVPL.its.time = time; lumVPL.its.shFrame = Frame(-diRec.d); lumVPL.emitter = emitter; appendVPL(scene, random, lumVPL, false, vpls); dRec.d = -diRec.d; Point2 offset = warp::squareToUniformDiskConcentric(sampler->next2D()); Vector perpOffset = Frame(diRec.d).toWorld(Vector(offset.x, offset.y, 0)); BSphere geoBSphere = scene->getKDTree()->getAABB().getBSphere(); pRec.p = geoBSphere.center + (perpOffset - dRec.d) * geoBSphere.radius; weight = weight2 * M_PI * geoBSphere.radius * geoBSphere.radius; } int depth = 2; Ray ray(pRec.p, dRec.d, time); Intersection its; while (!weight.isZero() && (depth < maxDepth || maxDepth == -1)) { if (!scene->rayIntersect(ray, its)) break; const BSDF *bsdf = its.getBSDF(); BSDFSamplingRecord bRec(its, sampler, EImportance); Spectrum bsdfVal = bsdf->sample(bRec, sampler->next2D()); if (bsdfVal.isZero()) break; /* Assuming that BSDF importance sampling is perfect, the following should equal the maximum albedo over all spectral samples */ Float approxAlbedo = std::min((Float) 0.95f, bsdfVal.max()); if (sampler->next1D() > approxAlbedo) break; else weight /= approxAlbedo; /* Modified by Lifan Wu Assume Lambertian BRDF */ VPL vpl(ESurfaceVPL, weight); //VPL vpl(ESurfaceVPL, weight * bsdfVal); vpl.its = its; if (BSDF::getMeasure(bRec.sampledType) == ESolidAngle) appendVPL(scene, random, vpl, prune, vpls); weight *= bsdfVal; Vector wi = -ray.d, wo = its.toWorld(bRec.wo); ray = Ray(its.p, wo, 0.0f); /* Prevent light leaks due to the use of shading normals -- [Veach, p. 158] */ Float wiDotGeoN = dot(its.geoFrame.n, wi), woDotGeoN = dot(its.geoFrame.n, wo); if (wiDotGeoN * Frame::cosTheta(bRec.wi) <= 0 || woDotGeoN * Frame::cosTheta(bRec.wo) <= 0) break; /* Disabled for now -- this increases VPL weights and accuracy is not really a big requirement */ #if 0 /* Adjoint BSDF for shading normals -- [Veach, p. 155] */ weight *= std::abs( (Frame::cosTheta(bRec.wi) * woDotGeoN)/ (Frame::cosTheta(bRec.wo) * wiDotGeoN)); #endif ++depth; } size_t end = vpls.size(); for (size_t i=start; i<end; ++i) vpls[i].emitterScale = 1.0f / (end - start); } return offset; }
MainWindow::MainWindow(QWidget *parent) : QWidget(parent) , ui(new Ui::MainWindowClass) , menu(0) , menuActive(false) , lastPage(0) , updateCounter(1) , updateInterval(1) , gc(this) , fifo(qgetenv("VLASOVSOFT_FIFO1")) , pt(qgetenv("VLASOVSOFT_FIFO2")) { ui->setupUi(this); QString dataDir = qApp->applicationDirPath() + QDir::toNativeSeparators(QString("/data/")); QString cacheDir = dataDir + "cache"; QString bookmarksDir = dataDir + "bookmarks"; QString histFile = dataDir + "cr3hist.bmk"; QString iniFile = dataDir + "cr3.ini"; QString cssFile = dataDir + "fb2.css"; QString hyphDir = dataDir + "hyph" + QDir::separator(); ui->view->setHyphDir(hyphDir); ldomDocCache::init(qt2cr(cacheDir), DOC_CACHE_SIZE); ui->view->setPropsChangeCallback(this); ui->view->loadSettings(iniFile); ui->view->loadHistory(histFile); ui->view->loadCSS(cssFile); #if ENABLE_BOOKMARKS_DIR==1 ui->view->setBookmarksDir(bookmarksDir); #endif ui->view->getDocView()->setBatteryState( ui->view->getBatteryState() ); ui->view->getDocView()->setCallback(this); updateCounter = updateInterval = ui->view->getOptions()->getIntDef(PROP_DISPLAY_FULL_UPDATE_INTERVAL, 1); // Fill action list aList.push_back(ui->actionEmpty); // 0 aList.push_back(ui->actionShowMenu); // 1 aList.push_back(ui->actionBack); // 2 aList.push_back(ui->actionForward); // 3 aList.push_back(ui->actionNextPage); // 4 aList.push_back(ui->actionPreviousPage); // 5 aList.push_back(ui->actionNext10Pages); aList.push_back(ui->actionPrevious10Pages); aList.push_back(ui->actionNextChapter); aList.push_back(ui->actionPreviousChapter); aList.push_back(ui->actionFirstPage); aList.push_back(ui->actionLastPage); aList.push_back(ui->actionPosition); aList.push_back(ui->actionOpen); aList.push_back(ui->actionClose); aList.push_back(ui->actionTOC); aList.push_back(ui->actionRecentBooks); aList.push_back(ui->actionSettings); aList.push_back(ui->actionAddBookmark); aList.push_back(ui->actionShowBookmarksList); aList.push_back(ui->actionFileProperties); aList.push_back(ui->actionScreenRotation); aList.push_back(ui->actionFrontlight); aList.push_back(ui->actionFrontlightToggle); aList.push_back(ui->actionFrontlightPlus); aList.push_back(ui->actionFrontlightMinus); aList.push_back(ui->actionZoomIn); aList.push_back(ui->actionZoomOut); aList.push_back(ui->actionToggleInversion); aList.push_back(ui->actionToggleHeader); aList.push_back(ui->actionSuspend); aList.push_back(ui->actionScreenRotation0); aList.push_back(ui->actionScreenRotation90); aList.push_back(ui->actionScreenRotation180); aList.push_back(ui->actionScreenRotation270); aList.push_back(ui->actionScreenRotationPlus90); aList.push_back(ui->actionScreenRotationPlus180); aList.push_back(ui->actionScreenRotationMinus90); aList.push_back(ui->actionDeleteCurrentDocument); aList.push_back(ui->actionDictionary); PropsRef props( ui->view->getOptions() ); // use right column for next page by default setDefaultTapZoneAction( props,0,2,0,4 ); setDefaultTapZoneAction( props,0,2,1,4 ); setDefaultTapZoneAction( props,0,2,2,4 ); // use left column for previous page by default setDefaultTapZoneAction( props,0,0,0,5 ); setDefaultTapZoneAction( props,0,0,1,5 ); setDefaultTapZoneAction( props,0,0,2,5 ); // use center column for menu by default setDefaultTapZoneAction( props,0,1,0,1 ); setDefaultTapZoneAction( props,0,1,1,1 ); setDefaultTapZoneAction( props,0,1,2,1 ); ui->view->setOptions(props); gc.setRotation( props->getIntDef(PROP_ROTATE_ANGLE, 0) ); gc.setWeights( QSize(props->getIntDef(PROP_APP_UI_SWIPES_X_WEIGHT, 1), props->getIntDef(PROP_APP_UI_SWIPES_Y_WEIGHT, 1)) ); QObject::connect( &gc, SIGNAL(sigGesture(QPoint,GesturesController::GestureType)), this, SLOT(onGesture(QPoint,GesturesController::GestureType)) ); QObject::connect( &pt, SIGNAL(sigPipeMsg(QString)), this, SLOT(pipeMsg(QString)) ); // set margins int top = g_pConfig->readInt("margin_top", 1); int bottom = g_pConfig->readInt("margin_bottom", 0); int left = g_pConfig->readInt("margin_left", 0); int right = g_pConfig->readInt("margin_right", 0); if ( top <= 0 ) top = 1; // to handle full/partial updates ui->layout->setContentsMargins(left,top,right,bottom); writeFifoCommand(fifo, "n+"); }
auto reHashExpr(NH) { auto temp = MapBuilder<I, S, F, O, P, NH>{std::forward<F>(this->_func), std::move(this->_prev)}; temp.props(this->props()); temp.dumpProps(this->dumpProps()); return temp; }
/*! Insert a span of text into the document \param b Buffer containing UCS text to insert Uses appropriate function for clipboard or file */ bool IE_Imp_Text::_insertSpan(UT_GrowBuf &b) { UT_uint32 iLength = b.getLength(); const UT_UCS4Char * pData = (const UT_UCS4Char *)b.getPointer(0); // handle block direction if needed ... if(pData && m_bBlockDirectionPending) { const UT_UCS4Char * p = pData; // we look for the first strong character for(UT_uint32 i = 0; i < iLength; i++, p++) { UT_BidiCharType type = UT_bidiGetCharType(*p); if(UT_BIDI_IS_STRONG(type)) { m_bBlockDirectionPending = false; // set 'dom-dir' property of the block ... const gchar * propsArray[3]; propsArray[0] = "props"; propsArray[1] = NULL; propsArray[2] = NULL; UT_String props("dom-dir:"); if(UT_BIDI_IS_RTL(type)) props += "rtl;text-align:right"; else props += "ltr;text-align:left"; propsArray[1] = props.c_str(); // we need to modify the existing formatting ... if(m_pBlock == NULL) { PL_StruxDocHandle sdh = NULL; if(getDoc()->getStruxOfTypeFromPosition(getDocPos(), PTX_Block,&sdh)) { m_pBlock = static_cast<pf_Frag_Strux *>(const_cast<void *>(sdh)); } } appendStruxFmt(m_pBlock, static_cast<const gchar **>(&propsArray[0])); // if this is the first data in the block and the first // character is LRM or RLM followed by a strong character, // then we will remove it if(m_bFirstBlockData && i==0 && iLength > 1 && (*p == UCS_LRM || *p == UCS_RLM)) { UT_BidiCharType next_type = UT_bidiGetCharType(*(p+1)); if(UT_BIDI_IS_STRONG(next_type)) { pData++; iLength--; } } break; } } } bool bRes = appendSpan (pData, iLength); b.truncate(0); m_bFirstBlockData = false; return bRes; }
void QTextEngine::shapeTextMac(int item) const { QScriptItem &si = layoutData->items[item]; si.glyph_data_offset = layoutData->used; QFontEngine *font = fontEngine(si, &si.ascent, &si.descent, &si.leading); if (font->type() != QFontEngine::Multi) { shapeTextWithHarfbuzz(item); return; } #ifndef QT_MAC_USE_COCOA QFontEngineMacMulti *fe = static_cast<QFontEngineMacMulti *>(font); #else QCoreTextFontEngineMulti *fe = static_cast<QCoreTextFontEngineMulti *>(font); #endif QTextEngine::ShaperFlags flags; if (si.analysis.bidiLevel % 2) flags |= RightToLeft; if (option.useDesignMetrics()) flags |= DesignMetrics; attributes(); // pre-initialize char attributes const int len = length(item); int num_glyphs = length(item); const QChar *str = layoutData->string.unicode() + si.position; ushort upperCased[256]; if (si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase || si.analysis.flags == QScriptAnalysis::Lowercase) { ushort *uc = upperCased; if (len > 256) uc = new ushort[len]; for (int i = 0; i < len; ++i) { if(si.analysis.flags == QScriptAnalysis::Lowercase) uc[i] = str[i].toLower().unicode(); else uc[i] = str[i].toUpper().unicode(); } str = reinterpret_cast<const QChar *>(uc); } ensureSpace(num_glyphs); num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used; QGlyphLayout g = availableGlyphs(&si); g.numGlyphs = num_glyphs; unsigned short *log_clusters = logClusters(&si); bool stringToCMapFailed = false; // Skip shaping of line or paragraph separators since we are not // going to draw them anyway if (si.analysis.flags == QScriptAnalysis::LineOrParagraphSeparator && !(option.flags() & QTextOption::ShowLineAndParagraphSeparators)) { memset(log_clusters, 0, len * sizeof(unsigned short)); goto cleanUp; } if (!fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters, attributes(), &si)) { ensureSpace(num_glyphs); g = availableGlyphs(&si); stringToCMapFailed = !fe->stringToCMap(str, len, &g, &num_glyphs, flags, log_clusters, attributes(), &si); } if (!stringToCMapFailed) { heuristicSetGlyphAttributes(str, len, &g, log_clusters, num_glyphs); si.num_glyphs = num_glyphs; layoutData->used += si.num_glyphs; QGlyphLayout g = shapedGlyphs(&si); if (si.analysis.script == QUnicodeTables::Arabic) { QVarLengthArray<QArabicProperties> props(len + 2); QArabicProperties *properties = props.data(); int f = si.position; int l = len; if (f > 0) { --f; ++l; ++properties; } if (f + l < layoutData->string.length()) { ++l; } qt_getArabicProperties((const unsigned short *)(layoutData->string.unicode()+f), l, props.data()); unsigned short *log_clusters = logClusters(&si); for (int i = 0; i < len; ++i) { int gpos = log_clusters[i]; g.attributes[gpos].justification = properties[i].justification; } } } cleanUp: const ushort *uc = reinterpret_cast<const ushort *>(str); if ((si.analysis.flags == QScriptAnalysis::SmallCaps || si.analysis.flags == QScriptAnalysis::Uppercase || si.analysis.flags == QScriptAnalysis::Lowercase) && uc != upperCased) delete [] uc; }
void first_pass(const Index& index, const Context ctx, borrowed_ptr<php::Block> const blk, State state) { std::vector<Bytecode> newBCs; newBCs.reserve(blk->hhbcs.size()); PropertiesInfo props(index, ctx, nullptr); Interpreter interp { &index, ctx, props, blk, state }; for (auto& op : blk->hhbcs) { FTRACE(2, " == {}\n", show(op)); auto gen = [&] (const Bytecode& newb) { newBCs.push_back(newb); newBCs.back().srcLoc = op.srcLoc; FTRACE(2, " + {}\n", show(newBCs.back())); }; auto const flags = interp.step(op); if (flags.calledNoReturn) { gen(op); gen(bc::BreakTraceHint {}); // The rest of this code is going to // be unreachable. // It would be nice to put a fatal here, but we can't because it // will mess up the bytecode invariant about blocks // not-reachable via fallthrough if the stack depth is non-zero. // It can also mess up FPI regions. continue; } if (options.RemoveDeadBlocks && flags.tookBranch) { switch (op.op) { case Op::JmpNZ: blk->fallthrough = op.JmpNZ.target; break; case Op::JmpZ: blk->fallthrough = op.JmpZ.target; break; default: // No support for switch, etc, right now. always_assert(0 && "unsupported tookBranch case"); } /* * We need to pop the cell that was on the stack for the * conditional jump. Note: this also conceptually needs to * execute any side effects a conversion to bool can have. * (Currently that is none.) (TODO: could insert the bool conv * and let DCE remove it.) */ gen(bc::PopC {}); continue; } if (options.ConstantProp && flags.canConstProp) { if (propagate_constants(op, state, gen)) continue; } if (options.StrengthReduce && flags.strengthReduced) { for (auto& hh : *flags.strengthReduced) gen(hh); continue; } gen(op); } blk->hhbcs = std::move(newBCs); }
void edit_main_rep::set_int_property (string what, int val) { props (what)= as_tree (val); }
void edit_main_rep::set_string_property (string what, string val) { props (what)= val; }
void edit_main_rep::set_bool_property (string what, bool val) { props (what)= (val? string ("true"): string ("false")); }
void edit_main_rep::set_property (scheme_tree what, scheme_tree val) { props (what)= val; }
bool ScriptInterface::EnumeratePropertyNamesWithPrefix(JS::HandleValue objVal, const char* prefix, std::vector<std::string>& out) { JSAutoRequest rq(m->m_cx); if (!objVal.isObjectOrNull()) { LOGERROR("EnumeratePropertyNamesWithPrefix expected object type!"); return false; } if (objVal.isNull()) return true; // reached the end of the prototype chain JS::RootedObject obj(m->m_cx, &objVal.toObject()); JS::AutoIdArray props(m->m_cx, JS_Enumerate(m->m_cx, obj)); if (!props) return false; for (size_t i = 0; i < props.length(); ++i) { JS::RootedId id(m->m_cx, props[i]); JS::RootedValue val(m->m_cx); if (!JS_IdToValue(m->m_cx, id, &val)) return false; if (!val.isString()) continue; // ignore integer properties JS::RootedString name(m->m_cx, val.toString()); size_t len = strlen(prefix)+1; std::vector<char> buf(len); size_t prefixLen = strlen(prefix) * sizeof(char); JS_EncodeStringToBuffer(m->m_cx, name, &buf[0], prefixLen); buf[len-1]= '\0'; if (0 == strcmp(&buf[0], prefix)) { if (JS_StringHasLatin1Chars(name)) { size_t length; JS::AutoCheckCannotGC nogc; const JS::Latin1Char* chars = JS_GetLatin1StringCharsAndLength(m->m_cx, nogc, name, &length); if (chars) out.push_back(std::string(chars, chars+length)); } else { size_t length; JS::AutoCheckCannotGC nogc; const char16_t* chars = JS_GetTwoByteStringCharsAndLength(m->m_cx, nogc, name, &length); if (chars) out.push_back(std::string(chars, chars+length)); } } } // Recurse up the prototype chain JS::RootedObject prototype(m->m_cx); if (JS_GetPrototype(m->m_cx, obj, &prototype)) { JS::RootedValue prototypeVal(m->m_cx, JS::ObjectOrNullValue(prototype)); if (!EnumeratePropertyNamesWithPrefix(prototypeVal, prefix, out)) return false; } return true; }
void KIconEditGrid::editPaste(bool paste) { bool ok = false; const QImage *tmp = clipboardImage(ok); fixTransparence((QImage*)tmp); Properties *pprops = props(this); if(ok) { if( (tmp->size().width() > img->size().width()) || (tmp->size().height() > img->size().height()) ) { if(KMsgBox::yesNo(this, i18n("Warning"), i18n("The clipboard image is larger than the current image!\nPaste as new image?")) == 1) { editPasteAsNew(); } delete tmp; return; } else if(!paste) { ispasting = true; cbsize = tmp->size(); //debug("insrect size: %d x %d", insrect.width(), insrect.height()); return; emit newmessage(i18n("Pasting")); } else { //debug("KIconEditGrid: Pasting at: %d x %d", insrect.x(), insrect.y()); QApplication::setOverrideCursor(waitCursor); for(int y = insrect.y(), ny = 0; y < numRows(), ny < insrect.height(); y++, ny++) { uint *l = ((uint*)img->scanLine(y)+insrect.x()); uint *cl = (uint*)tmp->scanLine(ny); for(int x = insrect.x(), nx = 0; x < numCols(), nx < insrect.width(); x++, nx++, l++, cl++) { if(*cl != TRANSPARENT || pprops->pastetransparent) { *l = *cl; setColor((y*numCols())+x, (uint)*cl, false); } } } updateColors(); repaint(insrect.x()*cellSize(), insrect.y()*cellSize(), insrect.width()*cellSize(), insrect.height()*cellSize(), false); QApplication::restoreOverrideCursor(); modified = true; p = *img; emit changed(QPixmap(p)); emit sizechanged(numCols(), numRows()); emit colorschanged(numColors(), data()); emit newmessage(i18n("Done pasting")); } } else { QString msg = i18n("Invalid pixmap data in clipboard!\n"); KMsgBox::message(this, i18n("Warning"), msg.data()); } delete tmp; }
void Object::LoadConfig(std::istream &is, int version) { if(!props()) this->init_properties(); Archive::xml_iarchive ar(is); ObjectPropable::serialize(ar,0); }
auto reMapExpr(NO) { // NOTE: while calling with T cast arg. is req auto temp = MapBuilder<I, S, F, NO, P, H>{std::forward<F>(this->_func), std::move(this->_prev)}; temp.props(this->props()); temp.dumpProps(this->dumpProps()); return temp; }
virtual void onDraw(SkCanvas* inputCanvas) override { #ifdef SK_BUILD_FOR_ANDROID SkScalar textSizes[] = { 9.0f, 9.0f*2.0f, 9.0f*5.0f, 9.0f*2.0f*5.0f }; #else SkScalar textSizes[] = { 11.0f, 11.0f*2.0f, 11.0f*5.0f, 11.0f*2.0f*5.0f }; #endif SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f }; // set up offscreen rendering with distance field text #if SK_SUPPORT_GPU GrContext* ctx = inputCanvas->getGrContext(); SkImageInfo info = SkImageInfo::MakeN32Premul(onISize()); SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag, SkSurfaceProps::kLegacyFontHost_InitType); SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(ctx, SkSurface::kNo_Budgeted, info, 0, &props)); SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas; // init our new canvas with the old canvas's matrix canvas->setMatrix(inputCanvas->getTotalMatrix()); #else SkCanvas* canvas = inputCanvas; #endif // apply global scale to test glyph positioning canvas->scale(1.05f, 1.05f); canvas->clear(0xffffffff); SkPaint paint; paint.setAntiAlias(true); paint.setSubpixelText(true); sk_tool_utils::set_portable_typeface(&paint, "Times New Roman", SkTypeface::kNormal); const char* text = "Hamburgefons"; const size_t textLen = strlen(text); // check scaling up SkScalar x = SkIntToScalar(0); SkScalar y = SkIntToScalar(78); for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) { SkAutoCanvasRestore acr(canvas, true); canvas->translate(x, y); canvas->scale(scales[i], scales[i]); paint.setTextSize(textSizes[i]); canvas->drawText(text, textLen, 0, 0, paint); y += paint.getFontMetrics(NULL)*scales[i]; } // check rotation for (size_t i = 0; i < 5; ++i) { SkScalar rotX = SkIntToScalar(10); SkScalar rotY = y; SkAutoCanvasRestore acr(canvas, true); canvas->translate(SkIntToScalar(10 + i * 200), -80); rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY); for (int ps = 6; ps <= 32; ps += 3) { paint.setTextSize(SkIntToScalar(ps)); canvas->drawText(text, textLen, rotX, rotY, paint); rotY += paint.getFontMetrics(NULL); } } // check scaling down paint.setLCDRenderText(true); x = SkIntToScalar(680); y = SkIntToScalar(20); size_t arraySize = SK_ARRAY_COUNT(textSizes); for (size_t i = 0; i < arraySize; ++i) { SkAutoCanvasRestore acr(canvas, true); canvas->translate(x, y); SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]); canvas->scale(scaleFactor, scaleFactor); paint.setTextSize(textSizes[i]); canvas->drawText(text, textLen, 0, 0, paint); y += paint.getFontMetrics(NULL)*scaleFactor; } // check pos text { SkAutoCanvasRestore acr(canvas, true); canvas->scale(2.0f, 2.0f); SkAutoTArray<SkPoint> pos(SkToInt(textLen)); SkAutoTArray<SkScalar> widths(SkToInt(textLen)); paint.setTextSize(textSizes[0]); paint.getTextWidths(text, textLen, &widths[0]); SkScalar x = SkIntToScalar(340); SkScalar y = SkIntToScalar(75); for (unsigned int i = 0; i < textLen; ++i) { pos[i].set(x, y); x += widths[i]; } canvas->drawPosText(text, textLen, &pos[0], paint); } // check gamma-corrected blending const SkColor fg[] = { 0xFFFFFFFF, 0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF, 0xFFFF0000, 0xFF00FF00, 0xFF0000FF, 0xFF000000, }; paint.setColor(0xFFF1F1F1); SkRect r = SkRect::MakeLTRB(670, 250, 820, 460); canvas->drawRect(r, paint); x = SkIntToScalar(680); y = SkIntToScalar(270); #ifdef SK_BUILD_FOR_ANDROID paint.setTextSize(SkIntToScalar(19)); #else paint.setTextSize(SkIntToScalar(22)); #endif for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) { paint.setColor(fg[i]); canvas->drawText(text, textLen, x, y, paint); y += paint.getFontMetrics(NULL); } paint.setColor(0xFF1F1F1F); r = SkRect::MakeLTRB(820, 250, 970, 460); canvas->drawRect(r, paint); x = SkIntToScalar(830); y = SkIntToScalar(270); #ifdef SK_BUILD_FOR_ANDROID paint.setTextSize(SkIntToScalar(19)); #else paint.setTextSize(SkIntToScalar(22)); #endif for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) { paint.setColor(fg[i]); canvas->drawText(text, textLen, x, y, paint); y += paint.getFontMetrics(NULL); } // check skew { paint.setLCDRenderText(false); SkAutoCanvasRestore acr(canvas, true); canvas->skew(0.0f, 0.151515f); paint.setTextSize(SkIntToScalar(32)); canvas->drawText(text, textLen, 745, 70, paint); } { paint.setLCDRenderText(true); SkAutoCanvasRestore acr(canvas, true); canvas->skew(0.5f, 0.0f); paint.setTextSize(SkIntToScalar(32)); canvas->drawText(text, textLen, 580, 230, paint); } // check color emoji paint.setTypeface(fTypeface); #ifdef SK_BUILD_FOR_ANDROID paint.setTextSize(SkIntToScalar(19)); #else paint.setTextSize(SkIntToScalar(22)); #endif canvas->drawText(text, textLen, 670, 100, paint); #if SK_SUPPORT_GPU // render offscreen buffer if (surface) { SkAutoCanvasRestore acr(inputCanvas, true); // since we prepended this matrix already, we blit using identity inputCanvas->resetMatrix(); SkImage* image = surface->newImageSnapshot(); inputCanvas->drawImage(image, 0, 0, NULL); image->unref(); } #endif }
void VariableRegistryTestFixture::testCodec(){ VariableRegistry *r = new VariableRegistry(global_outgoing_event_buffer); Datum generated_codec(r->generateCodecDatum()); // #codec, #componentCodec, #termination (all generated by default) checkCodec(generated_codec, 0); CPPUNIT_ASSERT(r->getNVariables() == 0); Datum test1((float)5); VariableProperties props(&test1, "test", "Test test", "Testy test test test", M_NEVER, M_WHEN_CHANGED, true, false, M_CONTINUOUS_INFINITE, ""); shared_ptr<Variable> testvar = r->createGlobalVariable(&props); int n_variables = 1; CPPUNIT_ASSERT(r->lookupVariable("test").getInteger() == 5); CPPUNIT_ASSERT(r->getNVariables() == n_variables); //r->generateCodec(); Datum generated_codec2(r->generateCodecDatum()); checkCodec(generated_codec2, n_variables); shared_ptr<Variable> _testvar = r->getVariable("test"); shared_ptr<Variable> __testvar = r->getVariable(N_RESERVED_CODEC_CODES); CPPUNIT_ASSERT(__testvar != NULL); CPPUNIT_ASSERT(_testvar->getValue() == testvar->getValue()); CPPUNIT_ASSERT(__testvar->getValue() == testvar->getValue()); CPPUNIT_ASSERT(r->hasVariable("test")); CPPUNIT_ASSERT(!r->hasVariable("test2")); CPPUNIT_ASSERT(r->getNVariables() == 1); // regenerate a new registry from the codec VariableRegistry *r2 = new VariableRegistry(global_outgoing_event_buffer); r2->updateFromCodecDatum(generated_codec2); Datum generated_codec3(r2->generateCodecDatum()); checkCodec(generated_codec3, 1); CPPUNIT_ASSERT(r->lookupVariable("test").getInteger() == 5); CPPUNIT_ASSERT(r2->lookupVariable("test").getInteger() == 5); CPPUNIT_ASSERT(r->getNVariables() == n_variables); CPPUNIT_ASSERT(r2->getNVariables() == n_variables); Datum test2((long)15); VariableProperties props2(&test2, "test2", "Test2 test2", "Testy test2 test2 test2", M_NEVER, M_WHEN_CHANGED, true, false, M_CONTINUOUS_INFINITE, ""); shared_ptr<Variable> testvar2 = r2->createGlobalVariable(&props2); n_variables++; _testvar = r2->getVariable("test"); __testvar = r2->getVariable(N_RESERVED_CODEC_CODES); CPPUNIT_ASSERT(_testvar->getValue() == testvar->getValue()); CPPUNIT_ASSERT(__testvar->getValue() == testvar->getValue()); CPPUNIT_ASSERT(__testvar->getValue() == _testvar->getValue()); shared_ptr<Variable> _testvar2 = r2->getVariable("test2"); shared_ptr<Variable> __testvar2 = r2->getVariable(N_RESERVED_CODEC_CODES + 1); CPPUNIT_ASSERT(_testvar2->getValue() == testvar2->getValue()); CPPUNIT_ASSERT(__testvar2->getValue() == testvar2->getValue()); CPPUNIT_ASSERT(__testvar2->getValue() == _testvar2->getValue()); CPPUNIT_ASSERT(r2->hasVariable("test")); CPPUNIT_ASSERT(r2->hasVariable("test2")); CPPUNIT_ASSERT(r2->getNVariables() == n_variables); CPPUNIT_ASSERT(r->lookupVariable("test").getInteger() == 5); CPPUNIT_ASSERT(r2->lookupVariable("test").getInteger() == 5); CPPUNIT_ASSERT(r2->lookupVariable("test2").getInteger() == 15); Datum generated_codec4(r2->generateCodecDatum()); checkCodec(generated_codec4, 2); delete r; delete r2; }
int run(int argc, char **argv) { if(argc != 7 && argc != 9) { cout << "Down-sample grid volume data by a scale" << endl; cout << "Syntax: mtsutil downSampleVolume 0 <grid_volume> <scale x> <scale y> <scale z> <target_volume>" << endl; cout << "Syntax: mtsutil downSampleVolume 1 <hgrid_volume_dict> <scale x> <scale y> <scale z> <prefix> <origin_suffix> <target_suffix>" << endl; return -1; } if (strcmp(argv[1], "0") == 0) { char *end_ptr = NULL; scale.x = strtol(argv[3], &end_ptr, 10); if (*end_ptr != '\0') SLog(EError, "Could not parse integer value"); scale.y = strtol(argv[4], &end_ptr, 10); if (*end_ptr != '\0') SLog(EError, "Could not parse integer value"); scale.z = strtol(argv[5], &end_ptr, 10); if (*end_ptr != '\0') SLog(EError, "Could not parse integer value"); Properties props("gridvolume"); props.setString("filename", argv[2]); props.setBoolean("sendData", false); VolumeDataSource *originVol = static_cast<VolumeDataSource *> (PluginManager::getInstance()-> createObject(MTS_CLASS(VolumeDataSource), props)); originVol->configure(); Log(EInfo, "%s", originVol->getClass()->getName().c_str()); Log(EInfo, "res = (%d, %d, %d)", originVol->getResolution().x, originVol->getResolution().y, originVol->getResolution().z); Log(EInfo, "channels = %d", originVol->getChannels()); Log(EInfo, "min = (%.6f, %.6f, %.6f)", originVol->getAABB().min.x, originVol->getAABB().min.y, originVol->getAABB().min.z); Log(EInfo, "max = (%.6f, %.6f, %.6f)", originVol->getAABB().max.x, originVol->getAABB().max.y, originVol->getAABB().max.z); AABB bbox = originVol->getAABB(); GridData s; downSample(originVol, s); Log(EInfo, "finish down-sampling, save volume data to file"); ref<FileStream> outFile = new FileStream(argv[6], FileStream::ETruncReadWrite); writeVolume(s, bbox, originVol->getChannels(), outFile); } else if (strcmp(argv[1], "1") == 0) { char *end_ptr = NULL; scale.x = strtol(argv[3], &end_ptr, 10); if (*end_ptr != '\0') SLog(EError, "Could not parse integer value"); scale.y = strtol(argv[4], &end_ptr, 10); if (*end_ptr != '\0') SLog(EError, "Could not parse integer value"); scale.z = strtol(argv[5], &end_ptr, 10); if (*end_ptr != '\0') SLog(EError, "Could not parse integer value"); fs::path resolved = Thread::getThread()->getFileResolver()->resolve(argv[2]); Log(EInfo, "Loading hierarchical grid dictrionary \"%s\"", argv[2]); ref<FileStream> stream = new FileStream(resolved, FileStream::EReadOnly); stream->setByteOrder(Stream::ELittleEndian); Float xmin = stream->readSingle(), ymin = stream->readSingle(), zmin = stream->readSingle(); Float xmax = stream->readSingle(), ymax = stream->readSingle(), zmax = stream->readSingle(); AABB aabb = AABB(Point(xmin, ymin, zmin), Point(xmax, ymax, zmax)); Vector3i res = Vector3i(stream); int nCells = res.x * res.y * res.z; int numBlocks = 0; while (!stream->isEOF()) { Vector3i block = Vector3i(stream); Assert(block.x >= 0 && block.y >= 0 && block.z >= 0 && block.x < res.x && block.y < res.y && block.z < res.z); Properties props("gridvolume"); props.setString("filename", formatString("%s%03i_%03i_%03i%s", argv[6], block.x, block.y, block.z, argv[7])); props.setBoolean("sendData", false); VolumeDataSource *ori = static_cast<VolumeDataSource *> (PluginManager::getInstance()-> createObject(MTS_CLASS(VolumeDataSource), props)); ori->configure(); //Log(EInfo, "Loading grid %03i_%03i_%03i", block.x, block.y, block.z); AABB bbox = ori->getAABB(); GridData s; downSample(ori, s); std::string filename(formatString("%s%03i_%03i_%03i%s", argv[6], block.x, block.y, block.z, argv[8])); ref<FileStream> outFile = new FileStream(filename.c_str(), FileStream::ETruncReadWrite); writeVolume(s, bbox, ori->getChannels(), outFile); ++numBlocks; } Log(EInfo, "%i blocks total, %s, resolution=%s", numBlocks, aabb.toString().c_str(), res.toString().c_str()); } return 0; }
wxString SvnCommitDialog::GetMesasge() { SubversionLocalProperties props(m_url); wxString msg = NormalizeMessage(m_stcMessage->GetText()); msg << wxT("\n"); // Append any bug URLs to the commit message if(m_textCtrlBugID->IsShown()) { wxString bugTrackerMsg = props.ReadProperty(SubversionLocalProperties::BUG_TRACKER_MESSAGE); wxString bugTrackerUrl = props.ReadProperty(SubversionLocalProperties::BUG_TRACKER_URL); wxString bugId = m_textCtrlBugID->GetValue(); bugId.Trim().Trim(false); if(bugId.IsEmpty() == false) { // Loop over the bug IDs and append message for each bug wxArrayString bugs = wxStringTokenize(bugId, wxT(","), wxTOKEN_STRTOK); for(size_t i=0; i<bugs.size(); i++) { bugs[i].Trim().Trim(false); if(bugs[i].IsEmpty()) continue; wxString tmpMsg = bugTrackerMsg; wxString tmpUrl = bugTrackerUrl; tmpUrl.Replace(wxT("$(BUGID)"), bugs[i]); tmpMsg.Replace(wxT("$(BUG_URL)"), tmpUrl); tmpMsg.Replace(wxT("$(BUGID)"), bugs[i]); msg << tmpMsg << wxT("\n"); } } } // Append any FR URLs to the commit message if(m_textCtrlFrID->IsShown()) { wxString frTrackerMsg = props.ReadProperty(SubversionLocalProperties::FR_TRACKER_MESSAGE); wxString frTrackerUrl = props.ReadProperty(SubversionLocalProperties::FR_TRACKER_URL); wxString frId = m_textCtrlFrID->GetValue(); frId.Trim().Trim(false); if(frId.IsEmpty() == false) { // Loop over the bug IDs and append message for each bug wxArrayString frs = wxStringTokenize(frId, wxT(","), wxTOKEN_STRTOK); for(size_t i=0; i<frs.size(); i++) { frs[i].Trim().Trim(false); if(frs[i].IsEmpty()) continue; wxString tmpMsg = frTrackerMsg; wxString tmpUrl = frTrackerUrl; tmpUrl.Replace(wxT("$(FRID)"), frs[i]); tmpMsg.Replace(wxT("$(FR_URL)"), tmpUrl); tmpMsg.Replace(wxT("$(FRID)"), frs[i]); msg << tmpMsg << wxT("\n"); } } } msg.Trim().Trim(false); return msg; }
int genpname::MMain(int argc, char* argv[]) { int32_t i, j; UErrorCode status = U_ZERO_ERROR; u_init(&status); if (U_FAILURE(status) && status != U_FILE_ACCESS_ERROR) { fprintf(stderr, "Error: u_init returned %s\n", u_errorName(status)); status = U_ZERO_ERROR; } /* preset then read command line options */ options[3].value=u_getDataDirectory(); argc=u_parseArgs(argc, argv, sizeof(options)/sizeof(options[0]), options); /* error handling, printing usage message */ if (argc<0) { fprintf(stderr, "error in command line argument \"%s\"\n", argv[-argc]); } debug = options[5].doesOccur ? (*options[5].value - '0') : 0; if (argc!=1 || options[0].doesOccur || options[1].doesOccur || debug < 0 || debug > 9) { fprintf(stderr, "usage: %s [-options]\n" "\tcreate " PNAME_DATA_NAME "." PNAME_DATA_TYPE "\n" "options:\n" "\t-h or -? or --help this usage text\n" "\t-v or --verbose turn on verbose output\n" "\t-c or --copyright include a copyright notice\n" "\t-d or --destdir destination directory, followed by the path\n" "\t-D or --debug 0..9 emit debugging messages (if > 0)\n", argv[0]); return argc<0 ? U_ILLEGAL_ARGUMENT_ERROR : U_ZERO_ERROR; } /* get the options values */ useCopyright=options[2].doesOccur; verbose = options[4].doesOccur; // ------------------------------------------------------------ // Do not sort the string table, instead keep it in data.h order. // This simplifies data swapping and testing thereof because the string // table itself need not be sorted during swapping. // The NameToEnum sorter sorts each such map's string offsets instead. if (debug>1) { printf("String pool: %d\n", (int)STRING_COUNT); for (i=0; i<STRING_COUNT; ++i) { if (i != 0) { printf(", "); } printf("%s (%d)", STRING_TABLE[i].str, (int)STRING_TABLE[i].index); } printf("\n\n"); } // ------------------------------------------------------------ // Create top-level property indices PropertyArrayList props(PROPERTY, PROPERTY_COUNT); int32_t propNameCount; NameToEnumEntry* propName = createNameIndex(props, propNameCount); EnumToNameGroupEntry* propEnum = createEnumIndex(props); // ------------------------------------------------------------ // Create indices for the value list for each enumerated property // This will have more entries than we need... EnumToValueEntry* enumToValue = MALLOC(EnumToValueEntry, PROPERTY_COUNT); int32_t enumToValue_count = 0; for (i=0, j=0; i<PROPERTY_COUNT; ++i) { if (PROPERTY[i].valueCount == 0) continue; AliasArrayList values(PROPERTY[i].valueList, PROPERTY[i].valueCount); enumToValue[j].enumValue = PROPERTY[i].enumValue; enumToValue[j].enumToName = createEnumIndex(values); enumToValue[j].enumToName_count = PROPERTY[i].valueCount; enumToValue[j].nameToEnum = createNameIndex(values, enumToValue[j].nameToEnum_count); ++j; } enumToValue_count = j; uprv_sortArray(enumToValue, enumToValue_count, sizeof(enumToValue[0]), compareEnumToValueEntry, NULL, FALSE, &status); // ------------------------------------------------------------ // Build PropertyAliases layout in memory Builder builder(debug); builder.buildTopLevelProperties(propName, propNameCount, propEnum, PROPERTY_COUNT); builder.buildValues(enumToValue, enumToValue_count); builder.buildStringPool(STRING_TABLE, STRING_COUNT, NAME_GROUP, NAME_GROUP_COUNT); builder.fixup(); //////////////////////////////////////////////////////////// // Write the output file //////////////////////////////////////////////////////////// int32_t wlen = writeDataFile(options[3].value, builder); if (verbose) { fprintf(stdout, "Output file: %s.%s, %ld bytes\n", U_ICUDATA_NAME "_" PNAME_DATA_NAME, PNAME_DATA_TYPE, (long)wlen); } return 0; // success }
int SDL_main(int argc, char** argv) { #else int main(int argc, char** argv) { #endif uint32_t windowFlags = 0; SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_GLContext glContext = nullptr; #if defined(SK_BUILD_FOR_ANDROID) || defined(SK_BUILD_FOR_IOS) // For Android/iOS we need to set up for OpenGL ES and we make the window hi res & full screen SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS | SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_ALLOW_HIGHDPI; #else // For all other clients we use the core profile and operate in a window SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); windowFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE; #endif static const int kStencilBits = 8; // Skia needs 8 stencil bits SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, kStencilBits); SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); // If you want multisampling, uncomment the below lines and set a sample count static const int kMsaaSampleCount = 0; //4; // SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); // SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, kMsaaSampleCount); /* * In a real application you might want to initialize more subsystems */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { handle_error(); return 1; } // Setup window // This code will create a window with the same resolution as the user's desktop. SDL_DisplayMode dm; if (SDL_GetDesktopDisplayMode(0, &dm) != 0) { handle_error(); return 1; } SDL_Window* window = SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, dm.w, dm.h, windowFlags); if (!window) { handle_error(); return 1; } // To go fullscreen // SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); // try and setup a GL context glContext = SDL_GL_CreateContext(window); if (!glContext) { handle_error(); return 1; } int success = SDL_GL_MakeCurrent(window, glContext); if (success != 0) { handle_error(); return success; } uint32_t windowFormat = SDL_GetWindowPixelFormat(window); int contextType; SDL_GL_GetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, &contextType); int dw, dh; SDL_GL_GetDrawableSize(window, &dw, &dh); glViewport(0, 0, dw, dh); glClearColor(1, 1, 1, 1); glClearStencil(0); glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // setup GrContext auto interface = GrGLMakeNativeInterface(); // setup contexts sk_sp<GrContext> grContext(GrContext::MakeGL(interface)); SkASSERT(grContext); // Wrap the frame buffer object attached to the screen in a Skia render target so Skia can // render to it GrGLint buffer; GR_GL_GetIntegerv(interface.get(), GR_GL_FRAMEBUFFER_BINDING, &buffer); GrGLFramebufferInfo info; info.fFBOID = (GrGLuint) buffer; SkColorType colorType; //SkDebugf("%s", SDL_GetPixelFormatName(windowFormat)); // TODO: the windowFormat is never any of these? if (SDL_PIXELFORMAT_RGBA8888 == windowFormat) { info.fFormat = GR_GL_RGBA8; colorType = kRGBA_8888_SkColorType; } else { colorType = kBGRA_8888_SkColorType; if (SDL_GL_CONTEXT_PROFILE_ES == contextType) { info.fFormat = GR_GL_BGRA8; } else { // We assume the internal format is RGBA8 on desktop GL info.fFormat = GR_GL_RGBA8; } } GrBackendRenderTarget target(dw, dh, kMsaaSampleCount, kStencilBits, info); // setup SkSurface // To use distance field text, use commented out SkSurfaceProps instead // SkSurfaceProps props(SkSurfaceProps::kUseDeviceIndependentFonts_Flag, // SkSurfaceProps::kLegacyFontHost_InitType); SkSurfaceProps props(SkSurfaceProps::kLegacyFontHost_InitType); sk_sp<SkSurface> surface(SkSurface::MakeFromBackendRenderTarget(grContext.get(), target, kBottomLeft_GrSurfaceOrigin, colorType, nullptr, &props)); SkCanvas* canvas = surface->getCanvas(); canvas->scale((float)dw/dm.w, (float)dh/dm.h); ApplicationState state; const char* helpMessage = "Click and drag to create rects. Press esc to quit."; SkPaint paint; // create a surface for CPU rasterization sk_sp<SkSurface> cpuSurface(SkSurface::MakeRaster(canvas->imageInfo())); SkCanvas* offscreen = cpuSurface->getCanvas(); offscreen->save(); offscreen->translate(50.0f, 50.0f); offscreen->drawPath(create_star(), paint); offscreen->restore(); sk_sp<SkImage> image = cpuSurface->makeImageSnapshot(); int rotation = 0; SkFont font; while (!state.fQuit) { // Our application loop SkRandom rand; canvas->clear(SK_ColorWHITE); handle_events(&state, canvas); paint.setColor(SK_ColorBLACK); canvas->drawString(helpMessage, 100.0f, 100.0f, font, paint); for (int i = 0; i < state.fRects.count(); i++) { paint.setColor(rand.nextU() | 0x44808080); canvas->drawRect(state.fRects[i], paint); } // draw offscreen canvas canvas->save(); canvas->translate(dm.w / 2.0, dm.h / 2.0); canvas->rotate(rotation++); canvas->drawImage(image, -50.0f, -50.0f); canvas->restore(); canvas->flush(); SDL_GL_SwapWindow(window); } if (glContext) { SDL_GL_DeleteContext(glContext); } //Destroy window SDL_DestroyWindow(window); //Quit SDL subsystems SDL_Quit(); return 0; }
DEF_GPUTEST(ReadWriteAlpha, reporter, factory) { for (int type = 0; type < GrContextFactory::kLastGLContextType; ++type) { GrContextFactory::GLContextType glType = static_cast<GrContextFactory::GLContextType>(type); if (!GrContextFactory::IsRenderingGLContext(glType)) { continue; } GrContext* context = factory->get(glType); if (NULL == context) { continue; } unsigned char textureData[X_SIZE][Y_SIZE]; memset(textureData, 0, X_SIZE * Y_SIZE); GrSurfaceDesc desc; // let Skia know we will be using this texture as a render target desc.fFlags = kRenderTarget_GrSurfaceFlag; // it is a single channel texture desc.fConfig = kAlpha_8_GrPixelConfig; desc.fWidth = X_SIZE; desc.fHeight = Y_SIZE; // We are initializing the texture with zeros here GrTexture* texture = context->textureProvider()->createTexture(desc, false, textureData, 0); if (!texture) { return; } SkAutoTUnref<GrTexture> au(texture); // create a distinctive texture for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { textureData[x][y] = x*Y_SIZE+y; } } // upload the texture texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, textureData, 0); unsigned char readback[X_SIZE][Y_SIZE]; // clear readback to something non-zero so we can detect readback failures memset(readback, 0x1, X_SIZE * Y_SIZE); // read the texture back texture->readPixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, readback, 0); // make sure the original & read back versions match bool match = true; for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { if (textureData[x][y] != readback[x][y]) { match = false; } } } REPORTER_ASSERT(reporter, match); // Now try writing on the single channel texture SkSurfaceProps props(SkSurfaceProps::kLegacyFontHost_InitType); SkAutoTUnref<SkBaseDevice> device(SkGpuDevice::Create(texture->asRenderTarget(), &props, SkGpuDevice::kUninit_InitContents)); SkCanvas canvas(device); SkPaint paint; const SkRect rect = SkRect::MakeLTRB(-10, -10, X_SIZE + 10, Y_SIZE + 10); paint.setColor(SK_ColorWHITE); canvas.drawRect(rect, paint); texture->readPixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, readback, 0); match = true; for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { if (0xFF != readback[x][y]) { match = false; } } } REPORTER_ASSERT(reporter, match); } }
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(ReadWriteAlpha, reporter, context) { unsigned char alphaData[X_SIZE * Y_SIZE]; bool match; static const size_t kRowBytes[] = {0, X_SIZE, X_SIZE + 1, 2 * X_SIZE - 1}; for (int rt = 0; rt < 2; ++rt) { GrSurfaceDesc desc; // let Skia know we will be using this texture as a render target desc.fFlags = rt ? kRenderTarget_GrSurfaceFlag : kNone_GrSurfaceFlags; // it is a single channel texture desc.fConfig = kAlpha_8_GrPixelConfig; desc.fWidth = X_SIZE; desc.fHeight = Y_SIZE; // We are initializing the texture with zeros here memset(alphaData, 0, X_SIZE * Y_SIZE); SkAutoTUnref<GrTexture> texture( context->textureProvider()->createTexture(desc, SkBudgeted::kNo , alphaData, 0)); if (!texture) { if (!rt) { ERRORF(reporter, "Could not create alpha texture."); } continue; } // create a distinctive texture for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { alphaData[y * X_SIZE + x] = y*X_SIZE+x; } } for (auto rowBytes : kRowBytes) { // upload the texture (do per-rowbytes iteration because we may overwrite below). texture->writePixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, alphaData, 0); size_t nonZeroRowBytes = rowBytes ? rowBytes : X_SIZE; SkAutoTDeleteArray<uint8_t> readback(new uint8_t[nonZeroRowBytes * Y_SIZE]); // clear readback to something non-zero so we can detect readback failures memset(readback.get(), 0x1, nonZeroRowBytes * Y_SIZE); // read the texture back texture->readPixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, readback.get(), rowBytes); // make sure the original & read back versions match SkString msg; msg.printf("rt:%d, rb:%d", rt, SkToU32(rowBytes)); validate_alpha_data(reporter, X_SIZE, Y_SIZE, readback.get(), nonZeroRowBytes, alphaData, msg); // Now try writing on the single channel texture (if we could create as a RT). if (texture->asRenderTarget()) { SkSurfaceProps props(SkSurfaceProps::kLegacyFontHost_InitType); SkAutoTUnref<SkBaseDevice> device(SkGpuDevice::Create( texture->asRenderTarget(), &props, SkGpuDevice::kUninit_InitContents)); SkCanvas canvas(device); SkPaint paint; const SkRect rect = SkRect::MakeLTRB(-10, -10, X_SIZE + 10, Y_SIZE + 10); paint.setColor(SK_ColorWHITE); canvas.drawRect(rect, paint); memset(readback.get(), 0x1, nonZeroRowBytes * Y_SIZE); texture->readPixels(0, 0, desc.fWidth, desc.fHeight, desc.fConfig, readback.get(), rowBytes); match = true; for (int y = 0; y < Y_SIZE && match; ++y) { for (int x = 0; x < X_SIZE && match; ++x) { uint8_t rbValue = readback.get()[y * nonZeroRowBytes + x]; if (0xFF != rbValue) { ERRORF(reporter, "Failed alpha readback after clear. Expected: 0xFF, Got: 0x%02x" " at (%d,%d), rb:%d", rbValue, x, y, SkToU32(rowBytes)); match = false; } } } } } } static const GrPixelConfig kRGBAConfigs[] { kRGBA_8888_GrPixelConfig, kBGRA_8888_GrPixelConfig, kSRGBA_8888_GrPixelConfig }; for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { alphaData[y * X_SIZE + x] = y*X_SIZE+x; } } // Attempt to read back just alpha from a RGBA/BGRA texture. Once with a texture-only src and // once with a render target. for (auto cfg : kRGBAConfigs) { for (int rt = 0; rt < 2; ++rt) { GrSurfaceDesc desc; desc.fFlags = rt ? kRenderTarget_GrSurfaceFlag : kNone_GrSurfaceFlags; desc.fConfig = cfg; desc.fWidth = X_SIZE; desc.fHeight = Y_SIZE; uint32_t rgbaData[X_SIZE * Y_SIZE]; // Make the alpha channel of the rgba texture come from alphaData. for (int y = 0; y < Y_SIZE; ++y) { for (int x = 0; x < X_SIZE; ++x) { rgbaData[y * X_SIZE + x] = GrColorPackRGBA(6, 7, 8, alphaData[y * X_SIZE + x]); } } SkAutoTUnref<GrTexture> texture( context->textureProvider()->createTexture(desc, SkBudgeted::kNo, rgbaData, 0)); if (!texture) { // We always expect to be able to create a RGBA texture if (!rt && kRGBA_8888_GrPixelConfig == desc.fConfig) { ERRORF(reporter, "Failed to create RGBA texture."); } continue; } for (auto rowBytes : kRowBytes) { size_t nonZeroRowBytes = rowBytes ? rowBytes : X_SIZE; SkAutoTDeleteArray<uint8_t> readback(new uint8_t[nonZeroRowBytes * Y_SIZE]); // Clear so we don't accidentally see values from previous iteration. memset(readback.get(), 0x0, nonZeroRowBytes * Y_SIZE); // read the texture back texture->readPixels(0, 0, desc.fWidth, desc.fHeight, kAlpha_8_GrPixelConfig, readback.get(), rowBytes); // make sure the original & read back versions match SkString msg; msg.printf("rt:%d, rb:%d", rt, SkToU32(rowBytes)); validate_alpha_data(reporter, X_SIZE, Y_SIZE, readback.get(), nonZeroRowBytes, alphaData, msg); } } } }
int main(int argc, char *argv[]) { # include "setRootCase.H" # include "createTime.H" Info << "\nReading g" << endl; uniformDimensionedVectorField g ( IOobject ( "g", runTime.constant(), runTime, IOobject::MUST_READ, IOobject::NO_WRITE ) ); Info << "\nReading waveProperties\n" << endl; IOdictionary waveProperties ( IOobject ( "waveProperties.input", runTime.constant(), runTime, IOobject::MUST_READ, IOobject::NO_WRITE ) ); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // IOobject wOut ( "waveProperties", runTime.constant(), runTime, IOobject::NO_READ, IOobject::NO_WRITE ); // Write waveProperties with the above computed changes OFstream os ( wOut.objectPath(), #if EXTBRANCH==1 ios_base::out|ios_base::trunc, #elif OFPLUSBRANCH==1 // Nothing to be put here #else #if OFVERSION<170 ios_base::out|ios_base::trunc, #endif #endif IOstream::ASCII, IOstream::currentVersion, IOstream::UNCOMPRESSED ); // Write the OF banner wOut.writeBanner( os ); // Write the file information. Class name is not correct when // using wOut.writeHeader( os ); hence manual entries os << "FoamFile" << nl; os << token::BEGIN_BLOCK << incrIndent << nl; os << indent << "version" << tab << IOstream::currentVersion << token::END_STATEMENT << nl; os << indent << "format" << tab << "ascii;" << nl; os << indent << "class" << tab << "dictionary;" << nl; os << indent << "object" << tab << "waveProperties;" << nl; os << decrIndent << indent << token::END_BLOCK << nl; // Write the divider wOut.writeDivider( os ); os << nl; /* Loop over all subdicts in waveProperties. For each of them compute the wave parameters relevant for that particular wave theory. */ wordList toc = waveProperties.toc(); forAll (toc, item) { // If a sub-dictionary, then compute parameters and write the subdict if (waveProperties.isDict(toc[item])) { dictionary& sd = waveProperties.subDict(toc[item]); autoPtr<setWaveProperties> props ( setWaveProperties::New(runTime, sd, true) ); props->set( os ); } else { label Nspaces = 20; // Read the entry and write to the dummy output file ITstream read = waveProperties.lookup(toc[item]); os << toc[item] << token::SPACE; for (int i=toc[item].size(); i<Nspaces-1; i++) { os << token::SPACE; } forAll (read, ri) { if (ri < read.size() - 1) { os << read[ri] << token::SPACE; } else { os << read[ri]; } } os << token::END_STATEMENT << nl << endl; // Additional level of check, such that the code does not crash at // runTime: if (toc[item] == "seaLevel") { // Read the magnitude of the sea level scalar sL = readScalar(waveProperties.lookup("seaLevel")); // If the Switch seaLevelAsReference is not found _and_ the // magnitude of the sea level differs from 0 (zero), stop the // evaluation of the wave parameters if ( !waveProperties.found("seaLevelAsReference") && SMALL < Foam::mag(sL) ) { // This merely looks up the string, it will not be found // and the user is forced to correct waveProperties.input, // before any execution is possible. waveProperties.lookup("seaLevelAsReference"); } } } } // Write end divider wOut.writeEndDivider(os); // End Info<< "\nEnd\n" << endl; return 0; }
void MaterialPropertyStorage::restrictStatefulProps(const std::vector<std::pair<unsigned int, QpMap> > & coarsening_map, std::vector<const Elem *> & coarsened_element_children, QBase & qrule, QBase & qrule_face, MaterialData & material_data, const Elem & elem, int input_side) { unsigned int side; bool doing_a_side = input_side != -1; unsigned int n_qpoints = 0; if (!doing_a_side) { side = 0; // Use 0 for the elem n_qpoints = qrule.n_points(); } else { side = input_side; n_qpoints = qrule_face.n_points(); } material_data.size(n_qpoints); // First, make sure that storage has been set aside for this element. //initStatefulProps(material_data, mats, n_qpoints, elem, side); if (props()[&elem][side].size() == 0) props()[&elem][side].resize(_stateful_prop_id_to_prop_id.size()); if (propsOld()[&elem][side].size() == 0) propsOld()[&elem][side].resize(_stateful_prop_id_to_prop_id.size()); if (propsOlder()[&elem][side].size() == 0) propsOlder()[&elem][side].resize(_stateful_prop_id_to_prop_id.size()); // init properties (allocate memory. etc) for (unsigned int i=0; i < _stateful_prop_id_to_prop_id.size(); ++i) { // duplicate the stateful property in property storage (all three states - we will reuse the allocated memory there) // also allocating the right amount of memory, so we do not have to resize, etc. if (props()[&elem][side][i] == NULL) props()[&elem][side][i] = material_data.props()[ _stateful_prop_id_to_prop_id[i] ]->init(n_qpoints); if (propsOld()[&elem][side][i] == NULL) propsOld()[&elem][side][i] = material_data.propsOld()[ _stateful_prop_id_to_prop_id[i] ]->init(n_qpoints); if (hasOlderProperties()) if (propsOlder()[&elem][side][i] == NULL) propsOlder()[&elem][side][i] = material_data.propsOlder()[ _stateful_prop_id_to_prop_id[i] ]->init(n_qpoints); } // Copy from the child stateful properties for (unsigned int qp=0; qp<coarsening_map.size(); qp++) { const std::pair<unsigned int, QpMap> & qp_pair = coarsening_map[qp]; unsigned int child = qp_pair.first; mooseAssert(child < coarsened_element_children.size(), "Coarsened element children vector not initialized"); const Elem * child_elem = coarsened_element_children[child]; const QpMap & qp_map = qp_pair.second; for (unsigned int i=0; i < _stateful_prop_id_to_prop_id.size(); ++i) { mooseAssert(props().contains(child_elem), "Child element pointer is not in the MaterialProps data structure"); PropertyValue * child_property = props()[child_elem][side][i]; PropertyValue * parent_property = props()[&elem][side][i]; parent_property->qpCopy(qp, child_property, qp_map._to); propsOld()[&elem][side][i]->qpCopy(qp, propsOld()[child_elem][side][i], qp_map._to); if (hasOlderProperties()) propsOlder()[&elem][side][i]->qpCopy(qp, propsOlder()[child_elem][side][i], qp_map._to); } } }
void VulkanWindowContext::createBuffers(VkFormat format) { GrVkFormatToPixelConfig(format, &fPixelConfig); fGetSwapchainImagesKHR(fBackendContext->fDevice, fSwapchain, &fImageCount, nullptr); SkASSERT(fImageCount); fImages = new VkImage[fImageCount]; fGetSwapchainImagesKHR(fBackendContext->fDevice, fSwapchain, &fImageCount, fImages); // set up initial image layouts and create surfaces fImageLayouts = new VkImageLayout[fImageCount]; fSurfaces = new sk_sp<SkSurface>[fImageCount]; for (uint32_t i = 0; i < fImageCount; ++i) { fImageLayouts[i] = VK_IMAGE_LAYOUT_UNDEFINED; GrBackendRenderTargetDesc desc; GrVkImageInfo info; info.fImage = fImages[i]; info.fAlloc = VK_NULL_HANDLE; info.fImageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; info.fImageTiling = VK_IMAGE_TILING_OPTIMAL; info.fFormat = format; info.fLevelCount = 1; desc.fWidth = fWidth; desc.fHeight = fHeight; desc.fConfig = fPixelConfig; desc.fOrigin = kTopLeft_GrSurfaceOrigin; desc.fSampleCnt = 0; desc.fStencilBits = 0; desc.fRenderTargetHandle = (GrBackendObject) &info; SkSurfaceProps props(GrPixelConfigIsSRGB(fPixelConfig) ? SkSurfaceProps::kGammaCorrect_Flag : 0, kUnknown_SkPixelGeometry); fSurfaces[i] = SkSurface::MakeFromBackendRenderTarget(fContext, desc, &props); } // create the command pool for the command buffers if (VK_NULL_HANDLE == fCommandPool) { VkCommandPoolCreateInfo commandPoolInfo; memset(&commandPoolInfo, 0, sizeof(VkCommandPoolCreateInfo)); commandPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; // this needs to be on the render queue commandPoolInfo.queueFamilyIndex = fBackendContext->fGraphicsQueueIndex; commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; GR_VK_CALL_ERRCHECK(fBackendContext->fInterface, CreateCommandPool(fBackendContext->fDevice, &commandPoolInfo, nullptr, &fCommandPool)); } // set up the backbuffers VkSemaphoreCreateInfo semaphoreInfo; memset(&semaphoreInfo, 0, sizeof(VkSemaphoreCreateInfo)); semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; semaphoreInfo.pNext = nullptr; semaphoreInfo.flags = 0; VkCommandBufferAllocateInfo commandBuffersInfo; memset(&commandBuffersInfo, 0, sizeof(VkCommandBufferAllocateInfo)); commandBuffersInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; commandBuffersInfo.pNext = nullptr; commandBuffersInfo.commandPool = fCommandPool; commandBuffersInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; commandBuffersInfo.commandBufferCount = 2; VkFenceCreateInfo fenceInfo; memset(&fenceInfo, 0, sizeof(VkFenceCreateInfo)); fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext = nullptr; fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; // we create one additional backbuffer structure here, because we want to // give the command buffers they contain a chance to finish before we cycle back fBackbuffers = new BackbufferInfo[fImageCount + 1]; for (uint32_t i = 0; i < fImageCount + 1; ++i) { fBackbuffers[i].fImageIndex = -1; GR_VK_CALL_ERRCHECK(fBackendContext->fInterface, CreateSemaphore(fBackendContext->fDevice, &semaphoreInfo, nullptr, &fBackbuffers[i].fAcquireSemaphore)); GR_VK_CALL_ERRCHECK(fBackendContext->fInterface, CreateSemaphore(fBackendContext->fDevice, &semaphoreInfo, nullptr, &fBackbuffers[i].fRenderSemaphore)); GR_VK_CALL_ERRCHECK(fBackendContext->fInterface, AllocateCommandBuffers(fBackendContext->fDevice, &commandBuffersInfo, fBackbuffers[i].fTransitionCmdBuffers)); GR_VK_CALL_ERRCHECK(fBackendContext->fInterface, CreateFence(fBackendContext->fDevice, &fenceInfo, nullptr, &fBackbuffers[i].fUsageFences[0])); GR_VK_CALL_ERRCHECK(fBackendContext->fInterface, CreateFence(fBackendContext->fDevice, &fenceInfo, nullptr, &fBackbuffers[i].fUsageFences[1])); } fCurrentBackbufferIndex = fImageCount; }
bool UnIgnoreCommand::Execute() { CString filelist; BOOL err = FALSE; for (int nPath = 0; nPath < pathList.GetCount(); ++nPath) { CString name = CPathUtils::PathPatternEscape(pathList[nPath].GetFileOrDirectoryName()); if (parser.HasKey(L"onlymask")) name = L'*' + pathList[nPath].GetFileExtension(); filelist += name + L'\n'; CTSVNPath parentfolder = pathList[nPath].GetContainingDirectory(); SVNProperties props(parentfolder, SVNRev::REV_WC, false); CStringA value; for (int i = 0; i < props.GetCount(); ++i) { CString propname(props.GetItemName(i).c_str()); if (propname.CompareNoCase(L"svn:ignore") == 0) { //treat values as normal text even if they're not value = (char *)props.GetItemValue(i).c_str(); break; } } value = value.Trim("\n\r"); value += '\n'; value.Remove('\r'); value.Replace("\n\n", "\n"); // Delete all occurrences of 'name' // "\n" is temporarily prepended to make the algorithm easier value = "\n" + value; value.Replace("\n" + CUnicodeUtils::GetUTF8(name) + "\n", "\n"); value = value.Mid(1); CStringA sTrimmedvalue = value; sTrimmedvalue.Trim(); if (sTrimmedvalue.IsEmpty()) { if (!props.Remove(L"svn:ignore")) { CString temp; temp.Format(IDS_ERR_FAILEDUNIGNOREPROPERTY, (LPCTSTR)name); CMessageBox::Show(hwndExplorer, temp, L"TortoiseGit", MB_ICONERROR); err = TRUE; break; } } else { if (!props.Add(L"svn:ignore", (LPCSTR)value)) { CString temp; temp.Format(IDS_ERR_FAILEDUNIGNOREPROPERTY, (LPCTSTR)name); CMessageBox::Show(hwndExplorer, temp, L"TortoiseGit", MB_ICONERROR); err = TRUE; break; } } } if (err == FALSE) { CString temp; temp.Format(IDS_PROC_UNIGNORESUCCESS, (LPCTSTR)filelist); CMessageBox::Show(hwndExplorer, temp, L"TortoiseGit", MB_ICONINFORMATION); return true; } return false; }
Emitter *getElement(size_t i) { if (i != 0) return NULL; if (m_sunRadiusScale == 0) { Properties props("directional"); const Transform &trafo = m_worldTransform->eval(0); props.setVector("direction", -trafo(m_sunDir)); props.setFloat("samplingWeight", m_samplingWeight); props.setSpectrum("irradiance", m_radiance * m_solidAngle); Emitter *emitter = static_cast<Emitter *>( PluginManager::getInstance()->createObject( MTS_CLASS(Emitter), props)); emitter->configure(); return emitter; } /* Rasterizing the sphere to an environment map and checking the individual pixels for coverage (which is what Mitsuba 0.3.0 did) was slow and not very effective; for instance the power varied dramatically with resolution changes. Since the sphere generally just covers a few pixels, the code below rasterizes it much more efficiently by generating a few thousand QMC samples. Step 1: compute a *very* rough estimate of how many pixel in the output environment map will be covered by the sun */ size_t pixelCount = m_resolution*m_resolution/2; Float cosTheta = std::cos(m_theta * m_sunRadiusScale); /* Ratio of the sphere that is covered by the sun */ Float coveredPortion = 0.5f * (1 - cosTheta); /* Approx. number of samples that need to be generated, be very conservative */ size_t nSamples = (size_t) std::max((Float) 100, (pixelCount * coveredPortion * 1000)); ref<Bitmap> bitmap = new Bitmap(SUN_PIXELFORMAT, Bitmap::EFloat, Vector2i(m_resolution, m_resolution/2)); bitmap->clear(); Frame frame(m_sunDir); Point2 factor(bitmap->getWidth() / (2*M_PI), bitmap->getHeight() / M_PI); Spectrum *target = (Spectrum *) bitmap->getFloatData(); Spectrum value = m_radiance * (2 * M_PI * (1-std::cos(m_theta))) * static_cast<Float>(bitmap->getWidth() * bitmap->getHeight()) / (2 * M_PI * M_PI * nSamples); for (size_t i=0; i<nSamples; ++i) { Vector dir = frame.toWorld( Warp::squareToUniformCone(cosTheta, sample02(i))); Float sinTheta = math::safe_sqrt(1-dir.y*dir.y); SphericalCoordinates sphCoords = fromSphere(dir); Point2i pos( std::min(std::max(0, (int) (sphCoords.azimuth * factor.x)), bitmap->getWidth()-1), std::min(std::max(0, (int) (sphCoords.elevation * factor.y)), bitmap->getHeight()-1)); target[pos.x + pos.y * bitmap->getWidth()] += value / std::max((Float) 1e-3f, sinTheta); } /* Instantiate a nested envmap plugin */ Properties props("envmap"); Properties::Data bitmapData; bitmapData.ptr = (uint8_t *) bitmap.get(); bitmapData.size = sizeof(Bitmap); props.setData("bitmap", bitmapData); props.setAnimatedTransform("toWorld", m_worldTransform); props.setFloat("samplingWeight", m_samplingWeight); Emitter *emitter = static_cast<Emitter *>( PluginManager::getInstance()->createObject( MTS_CLASS(Emitter), props)); emitter->configure(); return emitter; }