LLFace* LLDrawable::addFace(LLFacePool *poolp, LLViewerTexture *texturep) { LLMemType mt(LLMemType::MTYPE_DRAWABLE); LLFace *face = new LLFace(this, mVObjp); if (!face) llerrs << "Allocating new Face: " << mFaces.size() << llendl; if (face) { mFaces.push_back(face); if (poolp) { face->setPool(poolp, texturep); } if (isState(UNLIT)) { face->setState(LLFace::FULLBRIGHT); } } return face; }
forceinline ExecStatus ManProp<ManTask,Cap>::post(Home home, Cap c, TaskArray<ManTask>& t) { // Capacity must be nonnegative GECODE_ME_CHECK(c.gq(home, 0)); // Check that tasks do not overload resource for (int i=t.size(); i--; ) if (t[i].c() > c.max()) return ES_FAILED; if (t.size() == 1) GECODE_ME_CHECK(c.gq(home, t[0].c())); if (t.size() > 1) { if (c.assigned() && c.val()==1) { TaskArray<typename TaskTraits<ManTask>::UnaryTask> mt(home,t.size()); for (int i=t.size(); i--; ) mt[i]=t[i]; return Unary::ManProp<typename TaskTraits<ManTask>::UnaryTask> ::post(home,mt); } else { (void) new (home) ManProp<ManTask,Cap>(home,c,t); } } return ES_OK; }
int main(int argc, char **argv) { // (A) ==== Read in command-line options: ==== // if (argc < 2) { fprintf(stderr,"usage: %s [-f <Input data file>] [-model <model type>] [-gapfile <file with concentration dilution steps.] [-mfile <file with model parameters>] [-pfile <file with priors>] [-n <number of nested objects>] [-max <max number of nesting iterations>] [-mc <number of MCMC trials for finding a new object>] [-D <size of unweighted posterior sample>] [-out <file with unweighted posterior sample>] [-rs <random seed>] \n",argv[0]); exit(1); } int argbase = 1; Options *opt = ReadArguments(argbase, argc, argv); // (B) ==== Read in data and model parameters from files ==== // DATAtable dt(opt->file); DELTAtable dxt(opt->gapfile); Mtable mt(opt->mfile); Ptable pt(opt->pfile); // (C) ==== Carry out nested sampling ==== // Nested nst(dt, dxt, mt, pt, opt->model, opt->n, opt->max, opt->mc, opt->rs); nst.Results(dt, dxt); if (opt->outfile != "none") { nst.MCPosterior(dt, dxt, opt->D, opt->outfile, "adaptive"); // adaptive/fixed } }
void lua::QLocalSocket_metatable(lua_State* const state, const int pos) { lua::QIODevice_metatable(state, pos); lua::index mt(state, pos); mt["abort"] = &QLocalSocket::abort; mt["connectToServer"] = QLocalSocket_connectToServer; mt["disconnectFromServer"] = &QLocalSocket::disconnectFromServer; mt["error"] = QLocalSocket_error; mt["flush"] = &QLocalSocket::flush; mt["fullServerName"] = &QLocalSocket::fullServerName; mt["isValid"] = &QLocalSocket::isValid; mt["open"] = QLocalSocket_open; mt["readBufferSize"] = &QLocalSocket::readBufferSize; mt["serverName"] = &QLocalSocket::serverName; mt["setReadBufferSize"] = &QLocalSocket::setReadBufferSize; mt["setServerName"] = &QLocalSocket::setServerName; mt["setSocketDescriptor"] = QLocalSocket_setSocketDescriptor; mt["socketDescriptor"] = &QLocalSocket::socketDescriptor; mt["state"] = &QLocalSocket::state; mt["waitForConnected"] = QLocalSocket_waitForConnected; mt["waitForDisconnected"] = QLocalSocket_waitForDisconnected; }
void LLVertexBuffer::updateNumIndices(S32 nindices) { LLMemType mt(LLMemType::MTYPE_VERTEX_DATA); llassert(nindices >= 0); mRequestedNumIndices = nindices; if (!mDynamicSize) { mNumIndices = nindices; } else if (mUsage == GL_STATIC_DRAW_ARB || nindices > mNumIndices || nindices < mNumIndices/2) { if (mUsage != GL_STATIC_DRAW_ARB) { nindices += nindices/4; } mNumIndices = nindices; } }
LLVertexBuffer::LLVertexBuffer(U32 typemask, S32 usage) : LLRefCount(), mNumVerts(0), mNumIndices(0), mUsage(usage), mGLBuffer(0), mGLIndices(0), mMappedData(NULL), mMappedIndexData(NULL), mLocked(FALSE), mFinal(FALSE), mFilthy(FALSE), mEmpty(TRUE), mResized(FALSE), mDynamicSize(FALSE) { LLMemType mt(LLMemType::MTYPE_VERTEX_DATA); if (!sEnableVBOs) { mUsage = 0 ; } S32 stride = calcStride(typemask, mOffsets); mTypeMask = typemask; mStride = stride; sCount++; }
void LLViewerPartSourceChat::updatePart(LLViewerPart &part, const F32 dt) { LLMemType mt(LLMemType::MTYPE_PARTICLES); F32 frac = part.mLastUpdateTime/part.mMaxAge; LLVector3 center_pos; LLViewerPartSource *ps = (LLViewerPartSource*)part.mPartSourcep; LLViewerPartSourceChat *pss = (LLViewerPartSourceChat *)ps; if (!pss->mSourceObjectp.isNull() && !pss->mSourceObjectp->mDrawable.isNull()) { part.mPosAgent = pss->mSourceObjectp->getRenderPosition(); } else { part.mPosAgent = pss->mPosAgent; } F32 x = sin(F_TWO_PI*frac + part.mParameter); F32 y = cos(F_TWO_PI*frac + part.mParameter); part.mPosAgent.mV[VX] += x; part.mPosAgent.mV[VY] += y; part.mPosAgent.mV[VZ] += -0.5f + frac; }
void lua::QScreen_metatable(lua_State* const state, const int pos) { lua::QObject_metatable(state, pos); lua::index mt(state, pos); mt["angleBetween"] = &QScreen::angleBetween; mt["availableGeometry"] = &QScreen::availableGeometry; mt["availableSize"] = &QScreen::availableSize; mt["availableVirtualGeometry"] = &QScreen::availableVirtualGeometry; mt["availableVirtualSize"] = &QScreen::availableVirtualSize; mt["depth"] = &QScreen::depth; mt["devicePixelRatio"] = &QScreen::devicePixelRatio; mt["geometry"] = &QScreen::geometry; //mt["grabWindow"] = &QScreen::grabWindow; mt["isLandscape"] = &QScreen::isLandscape; mt["isPortrait"] = &QScreen::isPortrait; mt["logicalDotsPerInch"] = &QScreen::logicalDotsPerInch; mt["logicalDotsPerInchX"] = &QScreen::logicalDotsPerInchX; mt["logicalDotsPerInchY"] = &QScreen::logicalDotsPerInchY; mt["mapBetween"] = &QScreen::mapBetween; mt["name"] = &QScreen::name; mt["nativeOrientation"] = &QScreen::nativeOrientation; mt["orientation"] = &QScreen::orientation; mt["orientationUpdateMask"] = &QScreen::orientationUpdateMask; mt["physicalDotsPerInch"] = &QScreen::physicalDotsPerInch; mt["physicalDotsPerInchX"] = &QScreen::physicalDotsPerInchX; mt["physicalDotsPerInchY"] = &QScreen::physicalDotsPerInchY; mt["physicalSize"] = &QScreen::physicalSize; mt["primaryOrientation"] = &QScreen::primaryOrientation; mt["refreshRate"] = &QScreen::refreshRate; mt["setOrientationUpdateMask"] = &QScreen::setOrientationUpdateMask; mt["size"] = &QScreen::size; mt["transformBetween"] = &QScreen::transformBetween; mt["virtualGeometry"] = &QScreen::virtualGeometry; mt["virtualSiblings"] = &QScreen::virtualSiblings; mt["virtualSize"] = &QScreen::virtualSize; }
LLPanelMainInventory::LLPanelMainInventory() : LLPanel(), mActivePanel(NULL), mSavedFolderState(NULL), mFilterText(""), mMenuGearDefault(NULL), mMenuAdd(NULL), mNeedUploadCost(true) { LLMemType mt(LLMemType::MTYPE_INVENTORY_VIEW_INIT); // Menu Callbacks (non contex menus) mCommitCallbackRegistrar.add("Inventory.DoToSelected", boost::bind(&LLPanelMainInventory::doToSelected, this, _2)); mCommitCallbackRegistrar.add("Inventory.CloseAllFolders", boost::bind(&LLPanelMainInventory::closeAllFolders, this)); mCommitCallbackRegistrar.add("Inventory.EmptyTrash", boost::bind(&LLInventoryModel::emptyFolderType, &gInventory, "ConfirmEmptyTrash", LLFolderType::FT_TRASH)); mCommitCallbackRegistrar.add("Inventory.EmptyLostAndFound", boost::bind(&LLInventoryModel::emptyFolderType, &gInventory, "ConfirmEmptyLostAndFound", LLFolderType::FT_LOST_AND_FOUND)); mCommitCallbackRegistrar.add("Inventory.DoCreate", boost::bind(&LLPanelMainInventory::doCreate, this, _2)); mCommitCallbackRegistrar.add("Inventory.NewWindow", boost::bind(&LLPanelMainInventory::newWindow, this)); mCommitCallbackRegistrar.add("Inventory.ShowFilters", boost::bind(&LLPanelMainInventory::toggleFindOptions, this)); mCommitCallbackRegistrar.add("Inventory.ResetFilters", boost::bind(&LLPanelMainInventory::resetFilters, this)); mCommitCallbackRegistrar.add("Inventory.SetSortBy", boost::bind(&LLPanelMainInventory::setSortBy, this, _2)); mCommitCallbackRegistrar.add("Inventory.Share", boost::bind(&LLAvatarActions::shareWithAvatars)); // Controls // *TODO: Just use persistant settings for each of these U32 sort_order = gSavedSettings.getU32(LLInventoryPanel::DEFAULT_SORT_ORDER); BOOL sort_by_name = ! ( sort_order & LLInventoryFilter::SO_DATE ); BOOL sort_folders_by_name = ( sort_order & LLInventoryFilter::SO_FOLDERS_BY_NAME ); BOOL sort_system_folders_to_top = ( sort_order & LLInventoryFilter::SO_SYSTEM_FOLDERS_TO_TOP ); gSavedSettings.declareBOOL("Inventory.SortByName", sort_by_name, "Declared in code", FALSE); gSavedSettings.declareBOOL("Inventory.SortByDate", !sort_by_name, "Declared in code", FALSE); gSavedSettings.declareBOOL("Inventory.FoldersAlwaysByName", sort_folders_by_name, "Declared in code", FALSE); gSavedSettings.declareBOOL("Inventory.SystemFoldersToTop", sort_system_folders_to_top, "Declared in code", FALSE); mSavedFolderState = new LLSaveFolderState(); mSavedFolderState->setApply(FALSE); }
bool CustomPoiMatch::isConflicting(const Match& other, const ConstOsmMapPtr& map) const { const CustomPoiMatch* cpm = dynamic_cast<const CustomPoiMatch*>(&other); if (cpm == 0) { return true; } else { shared_ptr<const MatchThreshold> mt(new MatchThreshold()); // if they don't have any EIDs in common then it isn't a conflict. if (_eid1 != cpm->_eid1 && _eid2 != cpm->_eid2 && _eid1 != cpm->_eid2 && _eid2 != cpm->_eid1) { return false; } // make sure all combinations of matches are also considered matches. CustomPoiMatch m1(map, _rf, _eid1, cpm->_eid1, mt); CustomPoiMatch m2(map, _rf, _eid1, cpm->_eid2, mt); CustomPoiMatch m3(map, _rf, _eid2, cpm->_eid1, mt); CustomPoiMatch m4(map, _rf, _eid2, cpm->_eid2, mt); if (m1.getType() == MatchType::Match && m2.getType() == MatchType::Match && m3.getType() == MatchType::Match && m4.getType() == MatchType::Match) { return false; } else { return true; } } }
void ApproxDistanceSensor::drawPhysics(unsigned int flags) const { glPushMatrix(); glMultMatrixf(transformation); if(flags & SimRobotCore2::Renderer::showSensors) { Vector3<> ml(max, -tanf(angleX * 0.5f) * max, 0); Vector3<> mt(max, 0, tanf(angleY * 0.5f) * max); Vector3<> tl(max, ml.y, mt.z); Vector3<> tr(max, -ml.y, mt.z); Vector3<> bl(max, ml.y, -mt.z); Vector3<> br(max, -ml.y, -mt.z); glBegin(GL_LINE_LOOP); glColor3f(0.5f, 0, 0); glNormal3f (0, 0, 1.f); glVertex3f(tl.x, tl.y, tl.z); glVertex3f(tr.x, tr.y, tr.z); glVertex3f(br.x, br.y, br.z); glVertex3f(bl.x, bl.y, bl.z); glEnd(); glBegin(GL_LINE_STRIP); glVertex3f(tl.x, tl.y, tl.z); glVertex3f(0.f, 0.f, 0.f); glVertex3f(tr.x, tr.y, tr.z); glEnd(); glBegin(GL_LINE_STRIP); glVertex3f(bl.x, bl.y, bl.z); glVertex3f(0.f, 0.f, 0.f); glVertex3f(br.x, br.y, br.z); glEnd(); } Sensor::drawPhysics(flags); glPopMatrix(); }
void LLVertexBuffer::createGLIndices() { LLMemType mt(LLMemType::MTYPE_VERTEX_DATA); U32 size = getIndicesSize(); if (mGLIndices) { destroyGLIndices(); } if (size == 0) { return; } mEmpty = TRUE; //pad by 16 bytes for aligned copies size += 16; if (useVBOs()) { //pad by another 16 bytes for VBO pointer adjustment size += 16; mMappedIndexData = NULL; genIndices(); mResized = TRUE; } else { mMappedIndexData = (U8*) ll_aligned_malloc_16(size); if(!sOmitBlank) memset((void*)mMappedIndexData, 0, size); static int gl_buffer_idx = 0; mGLIndices = ++gl_buffer_idx; } }
system::Guess Randy::guess(const Game &game) const { auto &opp_hand = game.board.hands[system::Playsidetoi(system::invert(playside))]; // 入力 size_t place; int number; std::random_device rnd; std::mt19937 mt(rnd()); std::uniform_int_distribution <> rnd_place(0, opp_hand.size() - 1); while (true) { place = rnd_place(mt); if (!opp_hand[place].is_front) { break; } } std::uniform_int_distribution <> rnd_number(0, 11); number = rnd_number(mt); return system::Guess(place, number); }
void LLDrawable::updateTexture() { LLMemType mt(LLMemType::MTYPE_DRAWABLE); if (isDead()) { llwarns << "Dead drawable updating texture!" << llendl; return; } if (getNumFaces() != mVObjp->getNumTEs()) { //drawable is transitioning its face count return; } if (getVOVolume()) { if (!isActive()) { //gPipeline.markMoved(this); } else { if (isRoot()) { mQuietCount = 0; } else { getParent()->mQuietCount = 0; } } gPipeline.markRebuild(this, LLDrawable::REBUILD_MATERIAL, TRUE); } }
void IRODS::ExtractFileInfos(TString& s, DMSFile_t* f) const { // extract info (name, size, modification date) from listing line // such as : // indramgr 0 diskcache2 208207872 2009-10-06.16:56 & run_0002.dat.15-Feb-07.18:00:58 // indramgr 1 HPSS2 208207872 2009-10-06.16:56 & run_0002.dat.15-Feb-07.18:00:58 // indramgr 0 diskcache2 208224256 2009-10-06.16:56 & run_0003.dat.15-Feb-07.20:21:50 // indramgr 1 HPSS2 208224256 2009-10-06.16:56 & run_0003.dat.15-Feb-07.20:21:50 // // note that when used outside of CCIN2P3, only 'ils' works, not 'ils -l', so the listing looks like: // run_0002.dat.15-Feb-07.18:00:58 // run_0003.dat.15-Feb-07.20:21:50 #ifdef CCIN2P3_BUILD TObjArray* fstats = s.Tokenize(" "); f->SetName(((TObjString*)(*fstats)[fstats->GetEntries() - 1])->String().Remove(TString::kBoth, ' ').Data()); f->SetSize((UInt_t)((TObjString*)(*fstats)[3])->String().Remove(TString::kBoth, ' ').Atoi()); KVDatime mt(((TObjString*)(*fstats)[4])->String().Remove(TString::kBoth, ' ').Data(), KVDatime::kIRODS); f->SetModTime(mt); delete fstats; #else f->SetName(s.Remove(TString::kBoth, ' ')); #endif }
void CorrectMediaType(AM_MEDIA_TYPE* pmt) { if (!pmt) { return; } CMediaType mt(*pmt); if (mt.formattype == FORMAT_VideoInfo) { VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)mt.pbFormat; for (UINT i = 0; i < VIHSIZE; i++) { if (mt.subtype == *vihs[i].subtype && vih->bmiHeader.biCompression == vihs[i].vih.bmiHeader.biCompression) { mt.AllocFormatBuffer(vihs[i].size); memcpy(mt.pbFormat, &vihs[i], vihs[i].size); memcpy(mt.pbFormat, pmt->pbFormat, sizeof(VIDEOINFOHEADER)); break; } } } else if (mt.formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)mt.pbFormat; for (UINT i = 0; i < VIHSIZE; i++) { if (mt.subtype == *vih2s[i].subtype && vih2->bmiHeader.biCompression == vih2s[i].vih.bmiHeader.biCompression) { mt.AllocFormatBuffer(vih2s[i].size); memcpy(mt.pbFormat, &vih2s[i], vih2s[i].size); memcpy(mt.pbFormat, pmt->pbFormat, sizeof(VIDEOINFOHEADER2)); break; } } } CopyMediaType(pmt, &mt); }
int main(int argc, char *argv[]) { const int test_size = 128; std::random_device rd; std::seed_seq s{ rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd() }; std::mt19937 mt(s); EasyCL *cl = EasyCL::createForFirstGpuOtherwiseCpu(); CLKernel *kern = cl->buildKernel("test.cl", "test"); std::vector<uint32_t> inbuf(test_size*4), outbuf(test_size), compare(test_size); std::generate(inbuf.begin(), inbuf.end(), mt); std::cout << "Running CL implementation" << std::endl; kern->in(inbuf.size(), &inbuf[0]); kern->out(outbuf.size(), &outbuf[0]); size_t global_size[] = { test_size }; kern->run(1, global_size, nullptr); delete kern; std::cout << "Running local implementation" << std::endl; for (int i = 0; i < compare.size(); ++i) { compare[i] = inbuf[i] ^ inbuf[i + 1] ^ inbuf[i + 2] ^ inbuf[i + 3]; } std::cout << "Comparing CL test with local implementation" << std::endl; for (int i = 0; i < compare.size(); ++i) { if (outbuf[i] != compare[i]) { std::cout << "Error in index " << i << " " << outbuf[i] << " != " << compare[i] << std::endl; } } return 0; }
int main() { PokeRNG::Parameters5Gen<PokeRNG::ROMType::B1Ja> b1; PokeRNG::DateTimeRange range; PokeRNG::LCG5Gen lcg; PokeRNG::Calc5GenSeed calc_seed; b1.set_mac_addr(0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0); b1.set_timer0(0xc7a); range.set_year(0, 99); range.set_month(1, 12); range.set_day(1, 31); range.set_hour(0, 23); range.set_minute(0, 59); range.set_second(0, 59); for(const auto &it : range) { b1.set_date_time(it); PokeRNG::u64 seed1 = lcg.next(calc_seed(b1)); PokeRNG::MT mt(seed1 >> 32); PokeRNG::u32 H = mt() >> 27; PokeRNG::u32 A = mt() >> 27; PokeRNG::u32 B = mt() >> 27; mt(); PokeRNG::u32 D = mt() >> 27; PokeRNG::u32 S = mt() >> 27; if(H == 31 && A == 31 && B == 31 && D == 31 && S == 31) { std::cout<<it<<std::endl; printf("found! %lx\n", seed1); } } return 0; }
HRESULT CMpcAudioRenderer::DoRenderSampleWasapi(IMediaSample *pMediaSample) { HRESULT hr = S_OK; REFERENCE_TIME rtStart = 0; REFERENCE_TIME rtStop = 0; BYTE *pMediaBuffer = NULL; BYTE *pInputBufferPointer = NULL; BYTE *pInputBufferEnd = NULL; BYTE *pData; bufferSize = pMediaSample->GetActualDataLength(); const long lSize = bufferSize; pMediaSample->GetTime (&rtStart, &rtStop); AM_MEDIA_TYPE *pmt; if (SUCCEEDED(pMediaSample->GetMediaType(&pmt)) && pmt!=NULL) { CMediaType mt(*pmt); if ((WAVEFORMATEXTENSIBLE*)mt.Format() != NULL) { hr=CheckAudioClient(&(((WAVEFORMATEXTENSIBLE*)mt.Format())->Format)); } else { hr=CheckAudioClient((WAVEFORMATEX*)mt.Format()); } if (FAILED(hr)) { TRACE(_T("CMpcAudioRenderer::DoRenderSampleWasapi Error while checking audio client with input media type\n")); return hr; } DeleteMediaType(pmt); pmt=NULL; } // Initialization hr = pMediaSample->GetPointer(&pMediaBuffer); if (FAILED (hr)) { return hr; } pInputBufferPointer=&pMediaBuffer[0]; pInputBufferEnd=&pMediaBuffer[0]+lSize; WORD frameSize = m_pWaveFileFormat->nBlockAlign; // Sleep for half the buffer duration since last buffer feed DWORD currentTime=GetTickCount(); if (lastBufferTime!=0 && hnsActualDuration!= 0 && lastBufferTime<currentTime && (currentTime-lastBufferTime)<hnsActualDuration) { hnsActualDuration=hnsActualDuration-(currentTime-lastBufferTime); Sleep(hnsActualDuration); } // Each loop fills one of the two buffers. while (pInputBufferPointer < pInputBufferEnd) { UINT32 numFramesPadding=0; pAudioClient->GetCurrentPadding(&numFramesPadding); UINT32 numFramesAvailable = nFramesInBuffer - numFramesPadding; UINT32 nAvailableBytes=numFramesAvailable*frameSize; UINT32 nBytesToWrite=nAvailableBytes; // More room than enough in the output buffer if (nAvailableBytes > (size_t)(pInputBufferEnd - pInputBufferPointer)) { nBytesToWrite=pInputBufferEnd - pInputBufferPointer; numFramesAvailable=(UINT32)((float)nBytesToWrite/frameSize); } // Grab the next empty buffer from the audio device. hr = pRenderClient->GetBuffer(numFramesAvailable, &pData); if (FAILED (hr)) { TRACE(_T("CMpcAudioRenderer::DoRenderSampleWasapi GetBuffer failed with size %ld : (error %lx)\n"),nFramesInBuffer,hr); return hr; } // Load the buffer with data from the audio source. if (pData != NULL) { memcpy(&pData[0], pInputBufferPointer, nBytesToWrite); pInputBufferPointer += nBytesToWrite; } else { TRACE(_T("CMpcAudioRenderer::DoRenderSampleWasapi Output buffer is NULL\n")); } hr = pRenderClient->ReleaseBuffer(numFramesAvailable, 0); // no flags if (FAILED (hr)) { TRACE(_T("CMpcAudioRenderer::DoRenderSampleWasapi ReleaseBuffer failed with size %ld (error %lx)\n"),nFramesInBuffer,hr); return hr; } if (!isAudioClientStarted) { TRACE(_T("CMpcAudioRenderer::DoRenderSampleWasapi Starting audio client\n")); pAudioClient->Start(); isAudioClientStarted=true; } if (pInputBufferPointer >= pInputBufferEnd) { lastBufferTime=GetTickCount(); // This is the duration of the filled buffer hnsActualDuration=(double)REFTIMES_PER_SEC * numFramesAvailable / m_pWaveFileFormat->nSamplesPerSec; // Sleep time is half this duration hnsActualDuration=(DWORD)(hnsActualDuration/REFTIMES_PER_MILLISEC/2); break; } // Buffer not completely filled, sleep for half buffer capacity duration hnsActualDuration=(double)REFTIMES_PER_SEC * nFramesInBuffer / m_pWaveFileFormat->nSamplesPerSec; // Sleep time is half this duration hnsActualDuration=(DWORD)(hnsActualDuration/REFTIMES_PER_MILLISEC/2); Sleep(hnsActualDuration); } return hr; }
void Switchboard::DeferredBroadcast(Message* message, float delay) { MessageTimer mt(message, delay); _delayedMessages.push_back(mt); }
void LLViewerObjectList::update(LLAgent &agent, LLWorld &world) { LLMemType mt(LLMemType::MTYPE_OBJECT); // Update globals gVelocityInterpolate = gSavedSettings.getBOOL("VelocityInterpolate"); gPingInterpolate = gSavedSettings.getBOOL("PingInterpolate"); gAnimateTextures = gSavedSettings.getBOOL("AnimateTextures"); // update global timer F32 last_time = gFrameTimeSeconds; U64 time = totalTime(); // this will become the new gFrameTime when the update is done // Time _can_ go backwards, for example if the user changes the system clock. // It doesn't cause any fatal problems (just some oddness with stats), so we shouldn't assert here. // llassert(time > gFrameTime); F64 time_diff = U64_to_F64(time - gFrameTime)/(F64)SEC_TO_MICROSEC; gFrameTime = time; F64 time_since_start = U64_to_F64(gFrameTime - gStartTime)/(F64)SEC_TO_MICROSEC; gFrameTimeSeconds = (F32)time_since_start; gFrameIntervalSeconds = gFrameTimeSeconds - last_time; if (gFrameIntervalSeconds < 0.f) { gFrameIntervalSeconds = 0.f; } //clear avatar LOD change counter LLVOAvatar::sNumLODChangesThisFrame = 0; const F64 frame_time = LLFrameTimer::getElapsedSeconds(); std::vector<LLViewerObject*> kill_list; S32 num_active_objects = 0; LLViewerObject *objectp = NULL; // Make a copy of the list in case something in idleUpdate() messes with it std::vector<LLViewerObject*> idle_list; idle_list.reserve( mActiveObjects.size() ); for (std::set<LLPointer<LLViewerObject> >::iterator active_iter = mActiveObjects.begin(); active_iter != mActiveObjects.end(); active_iter++) { objectp = *active_iter; if (objectp) { idle_list.push_back( objectp ); } else { // There shouldn't be any NULL pointers in the list, but they have caused // crashes before. This may be idleUpdate() messing with the list. llwarns << "LLViewerObjectList::update has a NULL objectp" << llendl; } } if (gSavedSettings.getBOOL("FreezeTime")) { for (std::vector<LLViewerObject*>::iterator iter = idle_list.begin(); iter != idle_list.end(); iter++) { objectp = *iter; if (objectp->getPCode() == LLViewerObject::LL_VO_CLOUDS || objectp->isAvatar()) { objectp->idleUpdate(agent, world, frame_time); } } } else { for (std::vector<LLViewerObject*>::iterator idle_iter = idle_list.begin(); idle_iter != idle_list.end(); idle_iter++) { objectp = *idle_iter; if (!objectp->idleUpdate(agent, world, frame_time)) { // If Idle Update returns false, kill object! kill_list.push_back(objectp); } else { num_active_objects++; } } for (std::vector<LLViewerObject*>::iterator kill_iter = kill_list.begin(); kill_iter != kill_list.end(); kill_iter++) { objectp = *kill_iter; killObject(objectp); } } mNumSizeCulled = 0; mNumVisCulled = 0; // compute all sorts of time-based stats // don't factor frames that were paused into the stats if (! mWasPaused) { gViewerStats->updateFrameStats(time_diff); } /* // Debugging code for viewing orphans, and orphaned parents LLUUID id; char id_str[UUID_STR_LENGTH + 20]; for (i = 0; i < mOrphanParents.count(); i++) { id = sIndexAndLocalIDToUUID[mOrphanParents[i]]; LLViewerObject *objectp = findObject(id); if (objectp) { sprintf(id_str, "Par: "); objectp->mID.toString(id_str + 5); addDebugBeacon(objectp->getPositionAgent(), id_str, LLColor4(1.f,0.f,0.f,1.f), LLColor4(1.f,1.f,1.f,1.f)); } } LLColor4 text_color; for (i = 0; i < mOrphanChildren.count(); i++) { OrphanInfo oi = mOrphanChildren[i]; LLViewerObject *objectp = findObject(oi.mChildInfo); if (objectp) { if (objectp->getParent()) { sprintf(id_str, "ChP: "); text_color = LLColor4(0.f, 1.f, 0.f, 1.f); } else { sprintf(id_str, "ChNoP: "); text_color = LLColor4(1.f, 0.f, 0.f, 1.f); } id = sIndexAndLocalIDToUUID[oi.mParentInfo]; objectp->mID.toString(id_str + 8); addDebugBeacon(objectp->getPositionAgent() + LLVector3(0.f, 0.f, -0.25f), id_str, LLColor4(0.25f,0.25f,0.25f,1.f), text_color); } i++; } */ mNumObjectsStat.addValue(mObjects.count()); mNumActiveObjectsStat.addValue(num_active_objects); mNumSizeCulledStat.addValue(mNumSizeCulled); mNumVisCulledStat.addValue(mNumVisCulled); }
void QColormap_metatable(lua_State* const state, const int pos) { lua::index mt(state, pos); // TODO Set up metatable methods for this class }
int main(int argc, char** argv) { int randomSwaps = 0; int seed = 0; if (argc < 2) { cerr << "Error: Missing filename! Use " << argv[0] << " <filename>" << std::endl; return -1; } if (argc > 3 && std::string(argv[2]) == "-swap") randomSwaps = atoi(argv[3]); if (argc > 4 && std::string(argv[2]) == "-swap") seed = atoi(argv[4]); else { std::random_device rd; seed = rd(); } parseInputFile(argv[1]); // for (auto& x : commonvars::allBlocks) // x.print(); cout << "Found " << commonvars::allBlocks.size() << " blocks." << endl; cout << "Found a max of " << commonvars::maxNetNum << " nets." << endl; init_graphics("Analytical Placer", WHITE); set_visible_world(0, 0, 1010, 1010); for (int i = 1; i <= commonvars::maxNetNum; i++) { commonvars::allNets.emplace_back(i); commonvars::allNets.back().buildBlockList(&commonvars::allBlocks); // commonvars::allNets.back().print(); } //Part 2 - random IO swaps std::mt19937 mt(seed); for (int i = 0; i < randomSwaps; i++) { doRandomSwaps(&mt); // event_loop(NULL, NULL, NULL, drawscreen); } commonvars::tempRouting.clear(); for (auto& x : commonvars::allNets) { x.buildConnections();// &commonvars::allBlocks); } initialPlace(&commonvars::allBlocks); cout << "Used "<< wireusage(&commonvars::allNets) << " units of wiring. " << endl; event_loop(NULL, NULL, NULL, drawscreen); simpleOverlap(); cout << "Used " << wireusage(&commonvars::allNets) << " units of wiring. (basic spread)" << endl; event_loop(NULL, NULL, NULL, drawscreen); #if DO_FULL_SPREADING recurseRemoveOverlap(&commonvars::allBlocks, 2); cout << "Used " << wireusage(&commonvars::allNets) << " units of wiring. (full spread)" << endl; event_loop(NULL, NULL, NULL, drawscreen); #endif return 0; }
void LLViewerPartGroup::updateParticles(const F32 lastdt) { LLMemType mt(LLMemType::MTYPE_PARTICLES); F32 dt; LLVector3 gravity(0.f, 0.f, GRAVITY); LLViewerPartSim::checkParticleCount(mParticles.size()); LLViewerRegion *regionp = getRegion(); S32 end = (S32) mParticles.size(); for (S32 i = 0 ; i < (S32)mParticles.size();) { LLVector3 a(0.f, 0.f, 0.f); LLViewerPart* part = mParticles[i] ; dt = lastdt + mSkippedTime - part->mSkipOffset; part->mSkipOffset = 0.f; // Update current time const F32 cur_time = part->mLastUpdateTime + dt; const F32 frac = cur_time / part->mMaxAge; // "Drift" the object based on the source object if (part->mFlags & LLPartData::LL_PART_FOLLOW_SRC_MASK) { part->mPosAgent = part->mPartSourcep->mPosAgent; part->mPosAgent += part->mPosOffset; } // Do a custom callback if we have one... if (part->mVPCallback) { (*part->mVPCallback)(*part, dt); } if (part->mFlags & LLPartData::LL_PART_WIND_MASK) { LLVector3 tempVel(part->mVelocity); part->mVelocity *= 1.f - 0.1f*dt; part->mVelocity += 0.1f*dt*regionp->mWind.getVelocity(regionp->getPosRegionFromAgent(part->mPosAgent)); } // Now do interpolation towards a target if (part->mFlags & LLPartData::LL_PART_TARGET_POS_MASK) { F32 remaining = part->mMaxAge - part->mLastUpdateTime; F32 step = dt / remaining; step = llclamp(step, 0.f, 0.1f); step *= 5.f; // we want a velocity that will result in reaching the target in the // Interpolate towards the target. LLVector3 delta_pos = part->mPartSourcep->mTargetPosAgent - part->mPosAgent; delta_pos /= remaining; part->mVelocity *= (1.f - step); part->mVelocity += step*delta_pos; } if (part->mFlags & LLPartData::LL_PART_TARGET_LINEAR_MASK) { LLVector3 delta_pos = part->mPartSourcep->mTargetPosAgent - part->mPartSourcep->mPosAgent; part->mPosAgent = part->mPartSourcep->mPosAgent; part->mPosAgent += frac*delta_pos; part->mVelocity = delta_pos; } else { // Do velocity interpolation part->mPosAgent += dt*part->mVelocity; part->mPosAgent += 0.5f*dt*dt*part->mAccel; part->mVelocity += part->mAccel*dt; } // Do a bounce test if (part->mFlags & LLPartData::LL_PART_BOUNCE_MASK) { // Need to do point vs. plane check... // For now, just check relative to object height... F32 dz = part->mPosAgent.mV[VZ] - part->mPartSourcep->mPosAgent.mV[VZ]; if (dz < 0) { part->mPosAgent.mV[VZ] += -2.f*dz; part->mVelocity.mV[VZ] *= -0.75f; } } // Reset the offset from the source position if (part->mFlags & LLPartData::LL_PART_FOLLOW_SRC_MASK) { part->mPosOffset = part->mPosAgent; part->mPosOffset -= part->mPartSourcep->mPosAgent; } // Do color interpolation if (part->mFlags & LLPartData::LL_PART_INTERP_COLOR_MASK) { part->mColor.setVec(part->mStartColor); // note: LLColor4's v%k means multiply-alpha-only, // LLColor4's v*k means multiply-rgb-only part->mColor *= 1.f - frac; // rgb*k part->mColor %= 1.f - frac; // alpha*k part->mColor += frac%(frac*part->mEndColor); // rgb,alpha } // Do scale interpolation if (part->mFlags & LLPartData::LL_PART_INTERP_SCALE_MASK) { part->mScale.setVec(part->mStartScale); part->mScale *= 1.f - frac; part->mScale += frac*part->mEndScale; } // Set the last update time to now. part->mLastUpdateTime = cur_time; // Kill dead particles (either flagged dead, or too old) if ((part->mLastUpdateTime > part->mMaxAge) || (LLViewerPart::LL_PART_DEAD_MASK == part->mFlags)) { mParticles[i] = mParticles.back() ; mParticles.pop_back() ; delete part ; } else { F32 desired_size = calc_desired_size(part->mPosAgent, part->mScale); if (!posInGroup(part->mPosAgent, desired_size)) { // Transfer particles between groups LLViewerPartSim::getInstance()->put(part) ; mParticles[i] = mParticles.back() ; mParticles.pop_back() ; } else { i++ ; } } } S32 removed = end - (S32)mParticles.size(); if (removed > 0) { // we removed one or more particles, so flag this group for update if (mVOPartGroupp.notNull()) { gPipeline.markRebuild(mVOPartGroupp->mDrawable, LLDrawable::REBUILD_ALL, TRUE); } LLViewerPartSim::decPartCount(removed); } // Kill the viewer object if this particle group is empty if (mParticles.empty()) { gObjectList.killObject(mVOPartGroupp); mVOPartGroupp = NULL; } LLViewerPartSim::checkParticleCount() ; }
void LLViewerPartSim::updateSimulation() { LLMemType mt(LLMemType::MTYPE_PARTICLES); static LLFrameTimer update_timer; const F32 dt = llmin(update_timer.getElapsedTimeAndResetF32(), 0.1f); if (!(gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_PARTICLES))) { return; } LLFastTimer ftm(LLFastTimer::FTM_SIMULATE_PARTICLES); // Start at a random particle system so the same // particle system doesn't always get first pick at the // particles. Theoretically we'd want to do this in distance // order or something, but sorting particle sources will be a big // pain. S32 i; S32 count = (S32) mViewerPartSources.size(); S32 start = (S32)ll_frand((F32)count); S32 dir = 1; S32 deldir = 0; if (ll_frand() > 0.5f) { dir = -1; deldir = -1; } S32 num_updates = 0; for (i = start; num_updates < count;) { if (i >= count) { i = 0; } if (i < 0) { i = count - 1; } if (!mViewerPartSources[i]->isDead()) { BOOL upd = TRUE; if (!LLPipeline::sRenderAttachedParticles) { LLViewerObject* vobj = mViewerPartSources[i]->mSourceObjectp; if (vobj && (vobj->getPCode() == LL_PCODE_VOLUME)) { LLVOVolume* vvo = (LLVOVolume *)vobj; if (vvo && vvo->isAttachment()) { upd = FALSE; } } } if (upd) { mViewerPartSources[i]->update(dt); } } if (mViewerPartSources[i]->isDead()) { mViewerPartSources.erase(mViewerPartSources.begin() + i); count--; i+=deldir; } else { i += dir; } num_updates++; } count = (S32) mViewerPartGroups.size(); for (i = 0; i < count; i++) { LLViewerObject* vobj = mViewerPartGroups[i]->mVOPartGroupp; S32 visirate = 1; if (vobj) { LLSpatialGroup* group = vobj->mDrawable->getSpatialGroup(); if (group && !group->isVisible()) // && !group->isState(LLSpatialGroup::OBJECT_DIRTY)) { visirate = 8; } } if ((LLDrawable::getCurrentFrame()+mViewerPartGroups[i]->mID)%visirate == 0) { if (vobj) { gPipeline.markRebuild(vobj->mDrawable, LLDrawable::REBUILD_ALL, TRUE); } mViewerPartGroups[i]->updateParticles(dt * visirate); mViewerPartGroups[i]->mSkippedTime=0.0f; if (!mViewerPartGroups[i]->getCount()) { delete mViewerPartGroups[i]; mViewerPartGroups.erase(mViewerPartGroups.begin() + i); i--; count--; } } else { mViewerPartGroups[i]->mSkippedTime+=dt; } } if (LLDrawable::getCurrentFrame()%16==0) { if (sParticleCount > sMaxParticleCount * 0.875f && sParticleAdaptiveRate < 2.0f) { sParticleAdaptiveRate *= PART_ADAPT_RATE_MULT; } else { if (sParticleCount < sMaxParticleCount * 0.5f && sParticleAdaptiveRate > 0.03125f) { sParticleAdaptiveRate *= PART_ADAPT_RATE_MULT_RECIP; } } } updatePartBurstRate() ; //llinfos << "Particles: " << sParticleCount << " Adaptive Rate: " << sParticleAdaptiveRate << llendl; }
void LLParticlePartition::getGeometry(LLSpatialGroup* group) { LLMemType mt(LLMemType::MTYPE_SPACE_PARTITION); LLFastTimer ftm(mDrawableType == LLPipeline::RENDER_TYPE_GRASS ? LLFastTimer::FTM_REBUILD_GRASS_VB : LLFastTimer::FTM_REBUILD_PARTICLE_VB); std::sort(mFaceList.begin(), mFaceList.end(), LLFace::CompareDistanceGreater()); U32 index_count = 0; U32 vertex_count = 0; group->clearDrawMap(); LLVertexBuffer* buffer = group->mVertexBuffer; LLStrider<U16> indicesp; LLStrider<LLVector3> verticesp; LLStrider<LLVector3> normalsp; LLStrider<LLVector2> texcoordsp; LLStrider<LLColor4U> colorsp; buffer->getVertexStrider(verticesp); buffer->getNormalStrider(normalsp); buffer->getColorStrider(colorsp); buffer->getTexCoord0Strider(texcoordsp); buffer->getIndexStrider(indicesp); LLSpatialGroup::drawmap_elem_t& draw_vec = group->mDrawMap[mRenderPass]; for (std::vector<LLFace*>::iterator i = mFaceList.begin(); i != mFaceList.end(); ++i) { LLFace* facep = *i; LLAlphaObject* object = (LLAlphaObject*) facep->getViewerObject(); facep->setGeomIndex(vertex_count); facep->setIndicesIndex(index_count); facep->mVertexBuffer = buffer; facep->setPoolType(LLDrawPool::POOL_ALPHA); object->getGeometry(facep->getTEOffset(), verticesp, normalsp, texcoordsp, colorsp, indicesp); vertex_count += facep->getGeomCount(); index_count += facep->getIndicesCount(); S32 idx = draw_vec.size()-1; BOOL fullbright = facep->isState(LLFace::FULLBRIGHT); F32 vsize = facep->getVirtualSize(); if (idx >= 0 && draw_vec[idx]->mEnd == facep->getGeomIndex()-1 && draw_vec[idx]->mTexture == facep->getTexture() && (U16) (draw_vec[idx]->mEnd - draw_vec[idx]->mStart + facep->getGeomCount()) <= (U32) gGLManager.mGLMaxVertexRange && //draw_vec[idx]->mCount + facep->getIndicesCount() <= (U32) gGLManager.mGLMaxIndexRange && draw_vec[idx]->mEnd - draw_vec[idx]->mStart + facep->getGeomCount() < 4096 && draw_vec[idx]->mFullbright == fullbright) { draw_vec[idx]->mCount += facep->getIndicesCount(); draw_vec[idx]->mEnd += facep->getGeomCount(); draw_vec[idx]->mVSize = llmax(draw_vec[idx]->mVSize, vsize); } else { U32 start = facep->getGeomIndex(); U32 end = start + facep->getGeomCount()-1; U32 offset = facep->getIndicesStart(); U32 count = facep->getIndicesCount(); LLDrawInfo* info = new LLDrawInfo(start,end,count,offset,facep->getTexture(), buffer, fullbright); info->mExtents[0] = group->mObjectExtents[0]; info->mExtents[1] = group->mObjectExtents[1]; info->mVSize = vsize; draw_vec.push_back(info); //for alpha sorting facep->setDrawInfo(info); } } buffer->setBuffer(0); mFaceList.clear(); }
//this IS the EM...estimate away int classifier::fit2(segment * data, vector<double> mu_seeds, int topology, int elon_move ){ //========================================================================= //compute just a uniform model...no need for the EM if (K == 0){ ll = 0; double l = (data->maxX-data->minX); double pos = 0; double neg = 0; for (int i = 0; i < data->XN; i++){ pos+=data->X[1][i]; neg+=data->X[2][i]; } double pi = pos / (pos + neg); for (int i = 0; i < data->XN; i++){ if (pi > 0){ ll+=log(pi / l)*data->X[1][i]; } if (pi < 1){ ll+=log((1-pi) / l)*data->X[2][i]; } } components = new component[1]; return 1; } random_device rd; mt19937 mt(rd()); int add = noise_max>0; components = new component[K+add]; //=========================================================================== //initialize(1) components with user defined hyperparameters for (int k = 0; k < K; k++){ components[k].set_priors(ALPHA_0, BETA_0, ALPHA_1, BETA_1, ALPHA_2, ALPHA_3,data->N, K); } //=========================================================================== //random seeding, initialize(2), center of pausing components int i = 0; double mu; double mus[K]; for (int k = 0; k < K; k++){ if (mu_seeds.size()>0 ){ i = sample_centers(mu_seeds , p); mu = mu_seeds[i]; if (r_mu > 0){ normal_distribution<double> dist_r_mu(mu, r_mu); mu = dist_r_mu(mt); } }else{ normal_distribution<double> dist_MU((data->minX+data->maxX)/2., r_mu); mu = dist_MU(mt); } mus[k] = mu; if (mu_seeds.size() > 0 ){ mu_seeds.erase (mu_seeds.begin()+i); } } sort_vector(mus, K); for (int k = 0; k < K;k++){ //random seeding, intializ(3) other parameters components[k].initialize_bounds(mus[k], data, K, data->SCALE , 0., topology,foot_print, data->maxX, data->maxX); } sort_components(components, K); for (int k = 0; k < K; k++){ if (k > 0){ components[k].reverse_neighbor = &components[k-1]; }else{ components[k].reverse_neighbor = NULL; } if (k+1 < K){ components[k].forward_neighbor = &components[k+1]; }else{ components[k].forward_neighbor = NULL; } } if (add){ components[K].initialize_bounds(0., data, 0., 0. , noise_max, pi, foot_print, data->minX, data->maxX); } //=========================================================================== int t = 0; //EM loop ticker double prevll = nINF; //previous iterations log likelihood converged = false; //has the EM converged? int u = 0; //elongation movement ticker double norm_forward, norm_reverse,N; //helper variables while (t < max_iterations && not converged){ //====================================================== //reset old sufficient statistics for (int k=0; k < K+add; k++){ //components[k].print(); components[k].reset(); if (components[k].EXIT){ converged=false, ll=nINF; return 0; } } //====================================================== //E-step, grab all the stats and responsiblities ll = 0; for (int i =0; i < data->XN;i++){ norm_forward=0; norm_reverse=0; for (int k=0; k < K+add; k++){ //computing the responsbility terms if (data->X[1][i]){//if there is actually data point here... norm_forward+=components[k].evaluate(data->X[0][i],1); } if (data->X[2][i]){//if there is actually data point here... norm_reverse+=components[k].evaluate(data->X[0][i],-1); } } if (norm_forward > 0){ ll+=LOG(norm_forward)*data->X[1][i]; } if (norm_reverse > 0){ ll+=LOG(norm_reverse)*data->X[2][i]; } //now we need to add the sufficient statistics, need to compute expectations for (int k=0; k < K+add; k++){ if (norm_forward){ components[k].add_stats(data->X[0][i], data->X[1][i], 1, norm_forward); } if (norm_reverse){ components[k].add_stats(data->X[0][i], data->X[2][i], -1, norm_reverse); } } } //====================================================== //M-step N=0; //get normalizing constant for (int k = 0; k < K+add; k++){ N+=(components[k].get_all_repo()); } for (int k = 0; k < K+add; k++){ components[k].update_parameters(N, K); } if (abs(ll-prevll)<convergence_threshold){ converged=true; } if (not isfinite(ll)){ ll = nINF; return 0; } //====================================================== //should we try to move the uniform component? if (u > 200 ){ sort_components(components, K); //check_mu_positions(components, K); if (elon_move){ update_j_k(components,data, K, N); update_l(components, data, K); } u = 0; } u++; t++; prevll=ll; } return 1; }
// Set for rendering void LLVertexBuffer::setBuffer(U32 data_mask) { LLMemType mt(LLMemType::MTYPE_VERTEX_DATA); //set up pointers if the data mask is different ... BOOL setup = (sLastMask != data_mask); if (useVBOs()) { if (mGLBuffer && (mGLBuffer != sGLRenderBuffer || !sVBOActive)) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, mGLBuffer); sVBOActive = TRUE; setup = TRUE; // ... or the bound buffer changed } if (mGLIndices && (mGLIndices != sGLRenderIndices || !sIBOActive)) { glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, mGLIndices); sIBOActive = TRUE; } unmapBuffer(); } else { if (mGLBuffer) { if (sEnableVBOs && sVBOActive) { glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0); sVBOActive = FALSE; setup = TRUE; // ... or a VBO is deactivated } if (sGLRenderBuffer != mGLBuffer) { setup = TRUE; // ... or a client memory pointer changed } } if (sEnableVBOs && mGLIndices && sIBOActive) { glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0); sIBOActive = FALSE; } } if (mGLIndices) { sGLRenderIndices = mGLIndices; } if (mGLBuffer) { sGLRenderBuffer = mGLBuffer; if (data_mask && setup) { if (!sRenderActive) { llwarns << "Vertex buffer set for rendering outside of render frame." << llendl; } setupVertexBuffer(data_mask); // subclass specific setup (virtual function) sLastMask = data_mask; } } }
void LLVertexBuffer::unmapBuffer() { LLMemType mt(LLMemType::MTYPE_VERTEX_DATA); if (mMappedData || mMappedIndexData) { if (useVBOs() && mLocked) { if (mGLBuffer) { if (mResized) { glBufferDataARB(GL_ARRAY_BUFFER_ARB, getSize(), mMappedData, mUsage); } else { if (mEmpty || mDirtyRegions.empty()) { glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, 0, getSize(), mMappedData); } else { for (std::vector<DirtyRegion>::iterator i = mDirtyRegions.begin(); i != mDirtyRegions.end(); ++i) { DirtyRegion& region = *i; glBufferSubDataARB(GL_ARRAY_BUFFER_ARB, region.mIndex*mStride, region.mCount*mStride, mMappedData + region.mIndex*mStride); } } } } if (mGLIndices) { if (mResized) { glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, getIndicesSize(), mMappedIndexData, mUsage); } else { if (mEmpty || mDirtyRegions.empty()) { glBufferSubDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0, getIndicesSize(), mMappedIndexData); } else { for (std::vector<DirtyRegion>::iterator i = mDirtyRegions.begin(); i != mDirtyRegions.end(); ++i) { DirtyRegion& region = *i; glBufferSubDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, region.mIndicesIndex*sizeof(U32), region.mIndicesCount*sizeof(U32), mMappedIndexData + region.mIndicesIndex*sizeof(U32)); } } } } mDirtyRegions.clear(); mFilthy = FALSE; mResized = FALSE; if (mUsage == GL_STATIC_DRAW_ARB) { //static draw buffers can only be mapped a single time //throw out client data (we won't be using it again) delete [] mMappedData; delete [] mMappedIndexData; mMappedIndexData = NULL; mMappedData = NULL; mEmpty = TRUE; mFinal = TRUE; } else { mEmpty = FALSE; } mLocked = FALSE; glFlush(); } } }
void LLVertexBuffer::resizeBuffer(S32 newnverts, S32 newnindices) { LLMemType mt(LLMemType::MTYPE_VERTEX_DATA); mDynamicSize = TRUE; if (mUsage == GL_STATIC_DRAW_ARB) { //always delete/allocate static buffers on resize destroyGLBuffer(); destroyGLIndices(); allocateBuffer(newnverts, newnindices, TRUE); mFinal = FALSE; } else if (newnverts > mNumVerts || newnindices > mNumIndices || newnverts < mNumVerts/2 || newnindices < mNumIndices/2) { sAllocatedBytes -= getSize() + getIndicesSize(); S32 oldsize = getSize(); S32 old_index_size = getIndicesSize(); updateNumVerts(newnverts); updateNumIndices(newnindices); S32 newsize = getSize(); S32 new_index_size = getIndicesSize(); sAllocatedBytes += newsize + new_index_size; if (newsize) { if (!mGLBuffer) { //no buffer exists, create a new one createGLBuffer(); } else { //delete old buffer, keep GL buffer for now U8* old = mMappedData; mMappedData = new U8[newsize]; if (old) { memcpy(mMappedData, old, llmin(newsize, oldsize)); if (newsize > oldsize) { memset(mMappedData+oldsize, 0, newsize-oldsize); } delete [] old; } else { memset(mMappedData, 0, newsize); mEmpty = TRUE; } mResized = TRUE; } } else if (mGLBuffer) { destroyGLBuffer(); } if (new_index_size) { if (!mGLIndices) { createGLIndices(); } else { //delete old buffer, keep GL buffer for now U8* old = mMappedIndexData; mMappedIndexData = new U8[new_index_size]; if (old) { memcpy(mMappedIndexData, old, llmin(new_index_size, old_index_size)); if (new_index_size > old_index_size) { memset(mMappedIndexData+old_index_size, 0, new_index_size - old_index_size); } delete [] old; } else { memset(mMappedIndexData, 0, new_index_size); mEmpty = TRUE; } mResized = TRUE; } } else if (mGLIndices) { destroyGLIndices(); } } }