void monte_carlo::single_run(model& m, output_type& out, const precalculate& p, const igrid& ig, rng& generator, grid& user_grid) const { conf_size s = m.get_size(); change g(s); vec authentic_v(1000, 1000, 1000); out.e = max_fl; output_type current(out); minimization_params minparms = ssd_par.minparm; if(minparms.maxiters == 0) minparms.maxiters = ssd_par.evals; quasi_newton quasi_newton_par(minparms); VINA_U_FOR(step, num_steps) { output_type candidate(current.c, max_fl); mutate_conf(candidate.c, m, mutation_amplitude, generator); quasi_newton_par(m, p, ig, candidate, g, hunt_cap, user_grid); if(step == 0 || metropolis_accept(current.e, candidate.e, temperature, generator)) { quasi_newton_par(m, p, ig, candidate, g, authentic_v, user_grid); current = candidate; if(current.e < out.e) out = current; } }
void DocumentStyleSheetCollection::collectStyleSheetsFromCandidates(StyleEngine* engine, DocumentStyleSheetCollector& collector) { DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin(); DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end(); for (DocumentOrderedList::iterator it = begin; it != end; ++it) { Node* n = *it; StyleSheetCandidate candidate(*n); ASSERT(!candidate.isXSL()); if (candidate.isImport()) { Document* document = candidate.importedDocument(); if (!document) continue; if (collector.hasVisited(document)) continue; collector.willVisit(document); document->styleEngine()->updateStyleSheetsInImport(collector); continue; } if (candidate.isEnabledAndLoading()) { // it is loading but we should still decide which style sheet set to use if (candidate.hasPreferrableName(engine->preferredStylesheetSetName())) engine->selectStylesheetSetName(candidate.title()); continue; } StyleSheet* sheet = candidate.sheet(); if (!sheet) continue; if (candidate.hasPreferrableName(engine->preferredStylesheetSetName())) engine->selectStylesheetSetName(candidate.title()); collector.appendSheetForList(sheet); if (candidate.canBeActivated(engine->preferredStylesheetSetName())) collector.appendActiveStyleSheet(toCSSStyleSheet(sheet)); } }
void RtcStream::SetRemoteCandidate(const std::string& msg) { // convert to local json object Json::Reader reader; Json::Value jmessage; std::string decodedMsg = talk_base::Base64::Decode(msg, talk_base::Base64::DO_STRICT); if (!reader.parse(decodedMsg, jmessage)) { LOG(WARNING) << " Parse the JSON failed"; return; } // parse the received json object std::string sdp_mid; int sdp_mlineindex = 0; std::string sdp; if (!GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid) || !GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName, &sdp_mlineindex) || !GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp)) { LOG(WARNING) << "Can't parse received message."; return; } talk_base::scoped_ptr<webrtc::IceCandidateInterface> candidate( webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp)); if (!candidate.get()) { LOG(WARNING) << "Can't parse received candidate message."; return; } if (!connection_->AddIceCandidate(candidate.get())) { LOG(WARNING) << "Failed to apply the received candidate"; return; } return; }
TEST( CandidateTest, QueryMatchResultCaseInsensitiveIsSubsequence ) { Candidate candidate( "foobaaar" ); EXPECT_TRUE( candidate.QueryMatchResult( "foobaaar", false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "foOBAaar", false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "FOOBAAAR", false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "fobar" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "fbr" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "f" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "F" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "o" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "O" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "a" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "r" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "b" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "bar" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "oa" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "obr" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "oar" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "oo" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "aaa" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "AAA" , false ).IsSubsequence() ); EXPECT_TRUE( candidate.QueryMatchResult( "" , false ).IsSubsequence() ); }
TEST( CandidateTest, QueryMatchResultCaseSensitiveIsntSubsequence ) { Candidate candidate( "FooBaAAr" ); EXPECT_FALSE( candidate.QueryMatchResult( "foobaaar", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "foobaAAr", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "fbAA" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "fbaa" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "R" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "b" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "f" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "O" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "OO" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "OBA" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FBAR" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "fbar" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FBAAR" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "Oar" , true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FooBaAAR", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FooBAAAr", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FOoBaAAr", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "FOobaaar", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "fOobaaar", true ).IsSubsequence() ); EXPECT_FALSE( candidate.QueryMatchResult( "foobaaaR", true ).IsSubsequence() ); }
std::vector<int> Cross_variog_computer::compute_variogram_values(Discrete_function &f, GsTLVector<int> v,int num, float var,std::string& model_type, double mod_param) { const RGrid *tempGrid=dynamic_cast<const RGrid*>(grid_); SGrid_cursor cursor=*(tempGrid->cursor()); cursor.set_multigrid_level(1); std::vector<std::vector<std::pair<float,float> > >table; int i,j; for (i=0;i<num;i++) { std::vector<std::pair<float,float> > temp; table.push_back(temp); for(j=0;j<tempGrid->size();j++) { int x,y,z; cursor.coords(j,x,y,z); GsTLGridNode point(x,y,z); GsTLVector<int> vect(v.x()*(i+1),v.y()*(i+1),v.z()*(i+1)); GsTLGridNode candidate(point.x()+vect.x(),point.y()+vect.y(),point.z()+vect.z()); int node_id=cursor.node_id((int)candidate.x(),(int)candidate.y(), (int)candidate.z()); if((node_id!=-1)&&(cursor.check_triplet((int)candidate.x(),(int)candidate.y(), (int)candidate.z()))) { std::pair<float,float> temp; const GsTLGridProperty *prop1=tempGrid->selected_property(); temp.first=prop1->get_value(j); const GsTLGridProperty *prop2=tempGrid->property(temp_prop_name); if (prop2->is_informed(node_id)) { temp.second=prop2->get_value(node_id); table[i].push_back(temp); } } } } GsTLInt nx=tempGrid->nx(); GsTLInt ny=tempGrid->ny(); GsTLInt nz=tempGrid->nz(); std::vector<double> x_values; std::vector<double> y_values; float temp; for(i=0;i<static_cast<signed>(table.size());i++) { temp=compute_single_value(table[i],model_type,mod_param); if((prim_var_*sec_var_)!=0) y_values.push_back(temp/sqrt(prim_var_*sec_var_)); else y_values.push_back(temp); //y_values.push_back(temp/var); x_values.push_back( (i+1) * sqrt( double( v.x()*v.x() + v.y()*v.y() + v.z()*v.z() ) ) ); } //Set y_values and x_values of discrete function object f.set_y_values(y_values); f.set_x_values(x_values); std::vector<int> num_pairs; for(int j2=0;j2<static_cast<signed>(table.size());j2++) num_pairs.push_back(table[j2].size()); grid_->remove_property(temp_prop_name); return num_pairs; }
int Diff::execute() { Options sourceOptions; { sourceOptions.add<std::string>("filename", m_sourceFile); sourceOptions.add<bool>("debug", isDebug()); sourceOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } boost::scoped_ptr<Stage> source(AppSupport::makeReader(sourceOptions)); source->initialize(); boost::uint32_t chunkSize(source->getNumPoints()); if (m_chunkSize) chunkSize = m_chunkSize; PointBuffer source_data(source->getSchema(), chunkSize); boost::scoped_ptr<StageSequentialIterator> source_iter(source->createSequentialIterator(source_data)); ptree errors; Options candidateOptions; { candidateOptions.add<std::string>("filename", m_candidateFile); candidateOptions.add<bool>("debug", isDebug()); candidateOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } boost::scoped_ptr<Stage> candidate(AppSupport::makeReader(candidateOptions)); candidate->initialize(); PointBuffer candidate_data(candidate->getSchema(), chunkSize); boost::scoped_ptr<StageSequentialIterator> candidate_iter(candidate->createSequentialIterator(candidate_data)); if (candidate->getNumPoints() != source->getNumPoints()) { std::ostringstream oss; oss << "Source and candidate files do not have the same point count"; errors.put<std::string>("count.error", oss.str()); errors.put<boost::uint32_t>("count.candidate" , candidate->getNumPoints()); errors.put<boost::uint32_t>("count.source" , source->getNumPoints()); } pdal::Metadata source_metadata = source->collectMetadata(); pdal::Metadata candidate_metadata = candidate->collectMetadata(); if (source_metadata != candidate_metadata) { std::ostringstream oss; oss << "Source and candidate files do not have the same metadata count"; errors.put<std::string>("metadata.error", oss.str()); errors.put_child("metadata.source", source_metadata.toPTree()); errors.put_child("metadata.candidate", candidate_metadata.toPTree()); } Schema const& candidate_schema = candidate_data.getSchema(); Schema const& source_schema = source_data.getSchema(); if (! ( candidate_schema == source_schema)) { std::ostringstream oss; oss << "Source and candidate files do not have the same schema"; errors.put<std::string>("schema.error", oss.str()); errors.put_child("schema.source", source_schema.toPTree()); errors.put_child("schema.candidate", candidate_schema.toPTree()); } if (errors.size()) { write_json(std::cout, errors); return 1; } else { // If we made it this far with no errors, now we'll // check the points. checkPoints(source_iter.get(), source_data, candidate_iter.get(), candidate_data, errors); if (errors.size()) { write_json(std::cout, errors); return 1; } } return 0; }
void AlmostCliqueRule::apply() { init(); bool terminate = false; while (!terminate && _connectivity.size() > 0) { WorkingCopyGraph::NodeMap<bool> candidate(_instance.getGraph(), false); WorkingCopyGraph::NodeMap<double> connectivityCandidate(_instance.getGraph(), 0.0); WorkingCopyGraph::Node start = _connectivity.top(); _connectivity.pop(); candidate[start] = true; double prevConnectivity = 0; WorkingCopyGraph::Node u = findNodeMaxConnectivity(start, candidate, connectivityCandidate); if(u == INVALID) { terminate = true; } while (u != INVALID && connectivityCandidate[u] >= prevConnectivity && !terminate) { candidate[u] = true; prevConnectivity = connectivityCandidate[u]; //if u is connected to more nodes in V\C than to nodes in C terminate! int internal = 0; int external = 0; for(WorkingCopyGraph::IncEdgeIt uv(_instance.getGraph(), u); uv != INVALID; ++uv) { if(_instance.getWeight(uv) <= 0) { continue; } WorkingCopyGraph::Node v = _instance.getGraph().oppositeNode(u, uv); if(candidate[v]) { internal++; } else { external++; } } int bound = (int) ceil((double) countNodes(_instance.getGraph()) / 2)* internal; if(bound <= external) { terminate = true; } else { u = findNodeMaxConnectivity(u, candidate, connectivityCandidate); if(u == INVALID) { terminate = true; } } } if(mapCount(_instance.getGraph(), candidate, true) < 2) { continue; } double cost = computeCost(candidate); double minCutValue = computeMinCutValue(candidate); if ((cost <= minCutValue && !_conserveMultipleSolutions) || (cost < minCutValue && _conserveMultipleSolutions)) { _success = true; merge(candidate); } } }
TEST( CandidateTest, TextValid ) { std::string text = "foo"; Candidate candidate( text ); EXPECT_EQ( text, candidate.Text() ); }
void FirmwareDownloader::checkForNewFirmware() { QString platformString; switch (m_pebble->hardwareRevision()) { case HardwareRevisionUNKNOWN: case HardwareRevisionTINTIN_EV1: case HardwareRevisionTINTIN_EV2: case HardwareRevisionTINTIN_EV2_3: case HardwareRevisionSNOWY_EVT2: case HardwareRevisionSPALDING_EVT: case HardwareRevisionTINTIN_BB: case HardwareRevisionTINTIN_BB2: case HardwareRevisionSNOWY_BB: case HardwareRevisionSNOWY_BB2: case HardwareRevisionSPALDING_BB2: qWarning() << "Hardware revision not supported for firmware upgrades" << m_pebble->hardwareRevision(); return; case HardwareRevisionTINTIN_EV2_4: platformString = "ev2_4"; break; case HardwareRevisionTINTIN_V1_5: platformString = "v1_5"; break; case HardwareRevisionBIANCA: platformString = "v2_0"; break; case HardwareRevisionSNOWY_DVT: platformString = "snowy_dvt"; break; case HardwareRevisionBOBBY_SMILES: platformString = "snowy_s3"; break; case HardwareRevisionSPALDING: platformString = "spalding"; break; } QString url("https://pebblefw.s3.amazonaws.com/pebble/%1/%2/latest.json"); url = url.arg(platformString).arg("release-v3.8"); qDebug() << "fetching firmware info:" << url; QNetworkRequest request(url); QNetworkReply *reply = m_nam->get(request); connect(reply, &QNetworkReply::finished, [this, reply]() { QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(reply->readAll(), &error); qDebug() << "firmware info reply:" << jsonDoc.toJson(); if (error.error != QJsonParseError::NoError) { qWarning() << "Error parsing firmware fetch reply" << jsonDoc.toJson(QJsonDocument::Indented); return; } QVariantMap resultMap = jsonDoc.toVariant().toMap(); if (!resultMap.contains("normal")) { qWarning() << "Could not find normal firmware package" << jsonDoc.toJson(QJsonDocument::Indented); return; } qDebug() << "current:" << m_pebble->softwareVersion() << "candidate:" << resultMap.value("normal").toMap().value("friendlyVersion").toString(); FirmwareVersion baseline("v3.0.0"); FirmwareVersion current(m_pebble->softwareVersion()); FirmwareVersion candidate(resultMap.value("normal").toMap().value("friendlyVersion").toString()); QVariantMap targetFirmware; if (resultMap.contains("3.x-migration") && baseline > current) { targetFirmware = resultMap.value("3.x-migration").toMap(); } else if (current > baseline && candidate > current){ targetFirmware = resultMap.value("normal").toMap(); } if (targetFirmware.isEmpty()) { qDebug() << "Watch firmware is up to date"; m_updateAvailable = false; emit updateAvailableChanged(); return; } qDebug() << targetFirmware; m_candidateVersion = targetFirmware.value("friendlyVersion").toString(); m_releaseNotes = targetFirmware.value("notes").toString(); m_url = targetFirmware.value("url").toString(); m_hash = targetFirmware.value("sha-256").toByteArray(); m_updateAvailable = true; qDebug() << "candidate firmware upgrade" << m_candidateVersion << m_releaseNotes << m_url; emit updateAvailableChanged(); }); }
static void players_database( const char *event, const char *site, const char *date, const char *round, const char *white, const char *black, const char *result, const char *white_elo, const char *black_elo, const char *eco, int nbr_moves, thc::Move *moves, uint64_t *UNUSED(hashes) ) { bool warningw; bool warningb; int candw = candidate( warningw, white ); int candb = candidate( warningb, black ); if( candw>=0 && candb>=0 ) { char buf[1000]; strcpy( buf, event ); char *q = buf; while( *q ) { char c = *q; if( isascii(c) && isupper(c) ) *q = tolower(c); q++; } char buf2[1000]; strcpy( buf2, site ); q = buf2; while( *q ) { char c = *q; if( isascii(c) && isupper(c) ) *q = tolower(c); q++; } bool rapid = strstr(buf,"rapid") || strstr(buf2,"rapid"); bool blitz = strstr(buf,"blitz") || strstr(buf2,"blitz"); if( !rapid && !blitz ) { int year = atoi( date ); int elow = atoi( white_elo ); int elob = atoi( black_elo ); bool keep=true; int stage = 0; if( year >= 2010 ) stage = 2010; else if( year >= 2005 ) stage = 2005; else if( year >= 2000 ) stage = 2000; else if( year >= 1995 ) stage = 1995; else if( year >= 1990 ) stage = 1990; else if( year >= 1980 ) stage = 1980; else if( year >= 1970 ) stage = 1970; else stage = 0; switch( stage ) { case 2010: keep = (elow>=2550 && elob>=2550); break; case 2005: keep = (elow>=2500 && elob>=2500); break; case 2000: keep = (elow>=2450 && elob>=2450); break; case 1995: keep = (elow>=2400 && elob>=2400); break; case 1990: keep = (elow>=2300 && elob>=2300); break; case 1980: keep = (elow==0&&elob==0) || (elow>=2250 && elob>=2250); break; case 1970: keep = (elow==0&&elob==0) || (elow>=2200 && elob>=2200); break; default: keep = (year>=1880); break; } if( keep ) { char buf3[1000]; for( int known=0; keep && known<3; known++ ) // known issues { switch(known) { case 0: keep = (0!=strcmp( "Fischer, Robert J", players[candw].full)) || (0!=strcmp( "Owen, John", players[candb].full)); break; case 1: keep = (0!=strcmp( "Steinitz, Wilhelm", players[candw].full)) || (0!=strcmp( "Short, Nigel", players[candb].full)); break; case 2: keep = (0!=strcmp( "Vajda, Arpad", players[candw].full)) || (0!=strcmp( "Carlsen, Magnus", players[candb].full)); break; } } if( !keep ) { sprintf( buf3, "reject %s-%s %s %d not %s-%s\n", white, black, site, year, players[candw].full, players[candb].full ); cprintf( "%s", buf3 ); fprintf( logfile, "%s", buf3 ); } } if( keep ) { if( candw == candb ) { sprintf( buf, "reject %s-%s %s %d not both %s?\n", white, black, site, year, players[candw].full ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); keep = false; } if( warningw ) { sprintf( buf, "reject %s-%s %s %d is this really %s?\n", white, black, site, year, players[candw].full ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); keep = false; } if( warningb ) { sprintf( buf, "reject %s-%s %s %d is this really %s?\n", white, black, site, year, players[candb].full ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); keep = false; } } if( keep ) { if( elow && elow<2300 ) { sprintf( buf, "check %s-%s %s %d white_elo=%d?\n", white, black, site, year, elow ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); } if( elob && elob<2300 ) { sprintf( buf, "check %s-%s %s %d black_elo=%d?\n", white, black, site, year, elob ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); } int peakw = players[candw].year; if( year-peakw > (players[candw].long_career?50:30) ) { if( players[candw].draws_false_positives ) keep = false; sprintf( buf, "%s(%d) in %d %s > %s-%s\n", players[candw].full, players[candw].year, year, keep? "too old?":"definitely too old rejected", white, black ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); } if( peakw-year > (players[candw].long_career?30:20) ) { if( players[candw].draws_false_positives ) keep = false; sprintf( buf, "%s(%d) in %d %s > %s-%s\n", players[candw].full, players[candw].year, year, keep? "too young?":"definitely too young rejected", white, black ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); } } if( keep ) { int peakb = players[candb].year; if( year-peakb > (players[candb].long_career?50:30) ) { if( players[candb].draws_false_positives ) keep = false; sprintf( buf, "%s(%d) in %d %s > %s-%s\n", players[candb].full, players[candb].year, year, keep? "too old?":"definitely too old rejected", white, black ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); } if( peakb-year > (players[candb].long_career?30:20) ) { if( players[candb].draws_false_positives ) keep = false; sprintf( buf, "%s(%d) in %d %s > %s-%s\n", players[candb].full, players[candb].year, year, keep? "too young?":"definitely too young rejected", white, black ); cprintf( "%s", buf ); fprintf( logfile, "%s", buf ); } } if( keep ) { players[candw].count++; players[candb].count++; fprintf( ofile, "[Event \"%s\"]\n", event ); fprintf( ofile, "[Site \"%s\"]\n", site ); fprintf( ofile, "[Date \"%s\"]\n", date ); fprintf( ofile, "[Round \"%s\"]\n", round ); fprintf( ofile, "[White \"%s\"]\n", players[candw].full ); fprintf( ofile, "[Black \"%s\"]\n", players[candb].full ); fprintf( ofile, "[Result \"%s\"]\n", result ); if( elow ) fprintf( ofile, "[WhiteElo \"%s\"]\n", white_elo ); if( elob ) fprintf( ofile, "[BlackElo \"%s\"]\n", black_elo ); if( *eco ) fprintf( ofile, "[ECO \"%s\"]\n\n", eco ); std::string moves_txt; thc::ChessRules cr; for( int i=0; i<nbr_moves; i++ ) { if( i != 0 ) moves_txt += " "; if( cr.white ) { char buf3[100]; sprintf( buf3, "%d. ", cr.full_move_count ); moves_txt += buf3; } thc::Move mv = moves[i]; std::string s = mv.NaturalOut(&cr); moves_txt += s; cr.PlayMove(mv); } moves_txt += " "; moves_txt += result; std::string justified; const char *s = moves_txt.c_str(); int col=0; while( *s ) { char c = *s++; col++; if( c == ' ' ) { const char *t = s; int col_end_of_next_word = col+1; while( *t!=' ' && *t!='\0' ) { col_end_of_next_word++; t++; } if( col_end_of_next_word > 81 ) { c = '\n'; col = 0; } } justified += c; } fprintf( ofile, "%s\n\n", justified.c_str() ); players_database_total++; } } } }
void ezImageConversion::RebuildConversionTable() { s_conversionTable.Clear(); // Prime conversion table with known conversions for (ezImageConversionStep* conversion = ezImageConversionStep::GetFirstInstance(); conversion; conversion = conversion->GetNextInstance()) { ezArrayPtr<const ezImageConversionEntry> entries = conversion->GetSupportedConversions(); for (ezUInt32 subIndex = 0; subIndex < (ezUInt32)entries.GetCount(); subIndex++) { const ezImageConversionEntry& subConversion = entries[subIndex]; if (subConversion.m_flags.IsAnySet(ezImageConversionFlags::InPlace)) { EZ_ASSERT_DEV(ezImageFormat::IsCompressed(subConversion.m_sourceFormat) == ezImageFormat::IsCompressed(subConversion.m_targetFormat) && ezImageFormat::GetBitsPerBlock(subConversion.m_sourceFormat) == ezImageFormat::GetBitsPerBlock(subConversion.m_targetFormat), "In-place conversions are only allowed between formats of the same number of bits per pixel and compressedness"); } ezUInt32 tableIndex = MakeKey(subConversion.m_sourceFormat, subConversion.m_targetFormat); // Use the cheapest known conversion for each combination in case there are multiple ones TableEntry candidate(conversion, subConversion); TableEntry existing; if (!s_conversionTable.TryGetValue(tableIndex, existing) || candidate < existing) { s_conversionTable.Insert(tableIndex, candidate); } } } for (ezUInt32 i = 0; i < ezImageFormat::NUM_FORMATS; i++) { ezImageFormat::Enum format = static_cast<ezImageFormat::Enum>(i); // Add copy-conversion (from and to same format) s_conversionTable.Insert(MakeKey(format, format), TableEntry(nullptr, ezImageConversionEntry(ezImageConversionEntry(static_cast<ezImageFormat::Enum>(i), static_cast<ezImageFormat::Enum>(i), ezImageConversionFlags::InPlace)))); } // Straight from http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm for (ezUInt32 k = 1; k < ezImageFormat::NUM_FORMATS; k++) { for (ezUInt32 i = 1; i < ezImageFormat::NUM_FORMATS; i++) { if (k == i) { continue; } ezUInt32 tableIndexIK = MakeKey(static_cast<ezImageFormat::Enum>(i), static_cast<ezImageFormat::Enum>(k)); TableEntry entryIK; if (!s_conversionTable.TryGetValue(tableIndexIK, entryIK)) { continue; } for (ezUInt32 j = 1; j < ezImageFormat::NUM_FORMATS; j++) { if (j == i || j == k) { continue; } ezUInt32 tableIndexIJ = MakeKey(static_cast<ezImageFormat::Enum>(i), static_cast<ezImageFormat::Enum>(j)); ezUInt32 tableIndexKJ = MakeKey(static_cast<ezImageFormat::Enum>(k), static_cast<ezImageFormat::Enum>(j)); TableEntry entryKJ; if (!s_conversionTable.TryGetValue(tableIndexKJ, entryKJ)) { continue; } TableEntry candidate = TableEntry::chain(entryIK, entryKJ); TableEntry existing; if (candidate.isAdmissible() && candidate < s_conversionTable[tableIndexIJ]) { // To Convert from format I to format J, first Convert from I to K s_conversionTable[tableIndexIJ] = candidate; } } } } s_conversionTableValid = true; }
int Diff::execute() { PointContext sourceCtx; Options sourceOptions; { sourceOptions.add<std::string>("filename", m_sourceFile); sourceOptions.add<bool>("debug", isDebug()); sourceOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } std::unique_ptr<Stage> source(AppSupport::makeReader(m_sourceFile)); source->setOptions(sourceOptions); source->prepare(sourceCtx); PointBufferSet sourceSet = source->execute(sourceCtx); ptree errors; PointContext candidateCtx; Options candidateOptions; { candidateOptions.add<std::string>("filename", m_candidateFile); candidateOptions.add<bool>("debug", isDebug()); candidateOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } std::unique_ptr<Stage> candidate(AppSupport::makeReader(m_candidateFile)); candidate->setOptions(candidateOptions); candidate->prepare(candidateCtx); PointBufferSet candidateSet = candidate->execute(candidateCtx); assert(sourceSet.size() == 1); assert(candidateSet.size() == 1); PointBufferPtr sourceBuf = *sourceSet.begin(); PointBufferPtr candidateBuf = *candidateSet.begin(); if (candidateBuf->size() != sourceBuf->size()) { std::ostringstream oss; oss << "Source and candidate files do not have the same point count"; errors.put("count.error", oss.str()); errors.put("count.candidate", candidateBuf->size()); errors.put("count.source", sourceBuf->size()); } MetadataNode source_metadata = sourceCtx.metadata(); MetadataNode candidate_metadata = candidateCtx.metadata(); if (source_metadata != candidate_metadata) { std::ostringstream oss; oss << "Source and candidate files do not have the same metadata count"; errors.put("metadata.error", oss.str()); errors.put_child("metadata.source", pdal::utils::toPTree(source_metadata)); errors.put_child("metadata.candidate", pdal::utils::toPTree(candidate_metadata)); } if (candidateCtx.dims().size() != sourceCtx.dims().size()) { std::ostringstream oss; oss << "Source and candidate files do not have the same " "number of dimensions"; errors.put<std::string>("schema.error", oss.str()); //Need to "ptree" the PointContext dimension list in some way // errors.put_child("schema.source", sourceCtx.schema()->toPTree()); // errors.put_child("schema.candidate", // candidateCtx.schema()->toPTree()); } if (errors.size()) { write_json(std::cout, errors); return 1; } else { // If we made it this far with no errors, now we'll // check the points. checkPoints(*sourceBuf, *candidateBuf, errors); if (errors.size()) { write_json(std::cout, errors); return 1; } } return 0; }
void AabbSpawnUtil::getNewSpawnPosition(const hkVector4& aabbDims, hkVector4& positionOut) { // Try each volume in turn while (1) { hkVector4 avaliableDiag; avaliableDiag.setSub4( m_spawnVolumes[m_currentSpawnVolume].m_max, m_spawnVolumes[m_currentSpawnVolume].m_min ); avaliableDiag.sub4(aabbDims); if ( avaliableDiag(0) < 0 || avaliableDiag(2) < 0 ) { HK_ASSERT2(0, 0, "No spawn space large enough for requested aabb"); return; } // Try 100 random positions in the volume int numTries = m_allowOverlaps ? 1 : 100; for (int j = 0; j < numTries; ++j) { hkVector4 minPos(m_pseudoRandomGenerator.getRandReal01(), m_pseudoRandomGenerator.getRandReal01(), m_pseudoRandomGenerator.getRandReal01() ); if (avaliableDiag(1) < 0) { minPos(1) = 0; } minPos.mul4(avaliableDiag); minPos.add4(m_spawnVolumes[m_currentSpawnVolume].m_min); hkVector4 maxPos; maxPos.setAdd4( minPos, aabbDims ); hkAabb candidate( minPos, maxPos ); bool aabbCollides = false; if (!m_allowOverlaps) { for ( int k = 0; k < m_spawnedAabbs[m_currentSpawnVolume].getSize(); k++ ) { if ( m_spawnedAabbs[m_currentSpawnVolume][k].overlaps(candidate)) { aabbCollides = true; break; } } } if ( !aabbCollides ) { m_spawnedAabbs[m_currentSpawnVolume].pushBack(candidate); hkVector4 position; positionOut.setInterpolate4( candidate.m_min, candidate.m_max, .5f ); // If we allow penetrations, take each spawn volume in turn if ( m_allowOverlaps ) { m_currentSpawnVolume++; if (m_currentSpawnVolume == m_spawnVolumes.getSize()) { m_currentSpawnVolume = 0; } } return; } } // If we couldn't find a space, try the next volume m_currentSpawnVolume++; if (m_currentSpawnVolume == m_spawnVolumes.getSize()) { m_currentSpawnVolume = 0; m_allowOverlaps = true; } } }
bool QHangulPlatformInputContext::filterEvent(const QEvent *event) { if (event->type() != QEvent::KeyPress) return false; const QKeyEvent *keyevent = static_cast<const QKeyEvent*>(event); if (m_candidateList != NULL && m_candidateList->isVisible()) { if (m_candidateList->filterEvent(keyevent)) { if (m_candidateList->isSelected()) { hangul_ic_reset(m_hic); QString candidate(m_candidateList->getCandidate()); commitText(candidate); } m_candidateList->close(); } return true; } if (keyevent->key() == Qt::Key_Shift) return false; if (keyevent->key() == Qt::Key_Backspace) return backspace(); if (isTriggerKey(keyevent)) { if (m_mode == MODE_DIRECT) { m_mode = MODE_HANGUL; } else { reset(); m_mode = MODE_DIRECT; } setModeInfo(m_mode); return true; } if (isCandidateKey(keyevent)) { return popupCandidateList(); } if (keyevent->modifiers() & Qt::ControlModifier || keyevent->modifiers() & Qt::AltModifier || keyevent->modifiers() & Qt::MetaModifier) { reset(); return false; } if (m_mode == MODE_HANGUL) { QString text = keyevent->text(); if (keyevent->modifiers() & Qt::ShiftModifier) text = text.toUpper(); else text = text.toLower(); int ascii = 0; if (!text.isEmpty()) ascii = text[0].unicode(); bool ret = hangul_ic_process(m_hic, ascii); QString commitString = getCommitString(); if (!commitString.isEmpty()) commitText(commitString); QString preeditString = getPreeditString(); if (!preeditString.isEmpty()) updatePreedit(preeditString); return ret; } return false; }
void EventHandler::onWordCandidateReleased(QString word) { WordCandidate candidate(WordCandidate::SourcePrediction, word); Q_EMIT wordCandidateReleased(candidate); }
AlphaReal AbstainableLearner::doFullAbstention(const vector<sRates>& mu, AlphaReal currEnergy, sRates& eps, AlphaReal& alpha, vector<AlphaReal>& v) { const int numClasses = mu.size(); vector<char> best(numClasses, 1); vector<char> candidate(numClasses); sRates newEps; // candidate AlphaReal newAlpha; AlphaReal newEnergy; sRates bestEps = eps; for (int l = 1; l < numClasses; ++l) { // starts with an array with just one 0 (and the rest 1), // then two 0, then three 0, etc.. fill( candidate.begin(), candidate.begin()+l, 0 ); fill( candidate.begin()+l, candidate.end(), 1 ); // checks all the possible permutations of such array do { newEps = eps; for ( int j = 0; j < numClasses; ++j ) { if ( candidate[j] == 0 ) { newEps.rMin -= mu[j].rMin; newEps.rPls -= mu[j].rPls; newEps.rZero += mu[j].rZero; } } if ( nor_utils::is_zero(_theta) ) { newAlpha = getAlpha(newEps.rMin, newEps.rPls); newEnergy = BaseLearner::getEnergy(newEps.rMin, newEps.rPls); } else { newAlpha = getAlpha(newEps.rMin, newEps.rPls, _theta); newEnergy = BaseLearner::getEnergy(newEps.rMin, newEps.rPls, newAlpha, _theta); } if ( newAlpha > 0 && newEnergy + _smallVal < currEnergy ) { currEnergy = newEnergy; best = candidate; alpha = newAlpha; bestEps = newEps; // assert: eps- + eps+ + eps0 = 1 //cout.precision(10); //cout << newEps.rMin + newEps.rPls + newEps.rZero << endl; assert( newEps.rMin + newEps.rPls + newEps.rZero <= 1 + _smallVal && newEps.rMin + newEps.rPls + newEps.rZero >= 1 - _smallVal ); } } while ( next_permutation(candidate.begin(), candidate.end()) ); } for (int l = 0; l < numClasses; ++l) v[l] = v[l] * best[l]; // avoiding v[l] *= best[l] because of a (weird) warning eps = bestEps; return currEnergy; // this is what we are trying to minimize: 2*sqrt(eps+*eps-)+eps0 }
TArray<FString> I_GetSteamPath() { TArray<FString> result; TArray<FString> SteamInstallFolders; // Linux and OS X actually allow the user to install to any location, so // we need to figure out on an app-by-app basis where the game is installed. // To do so, we read the virtual registry. #ifdef __APPLE__ const FString appSupportPath = M_GetMacAppSupportPath(); FString regPath = appSupportPath + "/Steam/config/config.vdf"; try { SteamInstallFolders = ParseSteamRegistry(regPath); } catch(class CDoomError &error) { // If we can't parse for some reason just pretend we can't find anything. return result; } SteamInstallFolders.Push(appSupportPath + "/Steam/SteamApps/common"); #else char* home = getenv("HOME"); if(home != NULL && *home != '\0') { FString regPath; regPath.Format("%s/.steam/config/config.vdf", home); // [BL] The config seems to have moved from the more modern .local to // .steam at some point. Not sure if it's just my setup so I guess we // can fall back on it? if(!FileExists(regPath)) regPath.Format("%s/.local/share/Steam/config/config.vdf", home); try { SteamInstallFolders = ParseSteamRegistry(regPath); } catch(class CDoomError &error) { // If we can't parse for some reason just pretend we can't find anything. return result; } regPath.Format("%s/.local/share/Steam/SteamApps/common", home); SteamInstallFolders.Push(regPath); } #endif for(unsigned int i = 0;i < SteamInstallFolders.Size();++i) { for(unsigned int app = 0;app < countof(AppInfo);++app) { struct stat st; FString candidate(SteamInstallFolders[i] + "/" + AppInfo[app].BasePath); if(DirExists(candidate)) result.Push(candidate); } } return result; }
// Utility function for finding a text string in another string bool white_list(const char *item, const char *list) { std::string candidate(item); std::string white_list(list); return (white_list.find(candidate) != std::string::npos); }
void FocusController::findFocusableNodeInDirection(Node* outer, Node* focusedNode, FocusDirection direction, KeyboardEvent* event, FocusCandidate& closest, const FocusCandidate& candidateParent) #endif { #if PLATFORM(WKC) CRASH_IF_STACK_OVERFLOW(WKC_STACK_MARGIN_DEFAULT); #endif ASSERT(outer); ASSERT(candidateParent.isNull() || candidateParent.node->isFrameOwnerElement() || isScrollableContainerNode(candidateParent.node)); // Walk all the child nodes and update closest if we find a nearer node. Node* node = outer; while (node) { // Inner documents case. if (node->isFrameOwnerElement()) { deepFindFocusableNodeInDirection(node, focusedNode, direction, event, closest, specificRect); // Scrollable block elements (e.g. <div>, etc) case. } else if (isScrollableContainerNode(node) && !node->renderer()->isTextArea()) { deepFindFocusableNodeInDirection(node, focusedNode, direction, event, closest, specificRect); node = node->traverseNextSibling(); continue; #if PLATFORM(WKC) } else if (node != focusedNode && node->isFocusable() && isNodeInSpecificRect(node, specificRect)) { #else } else if (node != focusedNode && node->isKeyboardFocusable(event)) { #endif FocusCandidate candidate(node); // There are two ways to identify we are in a recursive call from deepFindFocusableNodeInDirection // (i.e. processing an element in an iframe, frame or a scrollable block element): // 1) If candidateParent is not null, and it holds the distance and alignment data of the // parent container element itself; // 2) Parent of outer is <frame> or <iframe>; // 3) Parent is any other scrollable block element. if (!candidateParent.isNull()) { candidate.parentAlignment = candidateParent.alignment; candidate.parentDistance = candidateParent.distance; candidate.enclosingScrollableBox = candidateParent.node; } else if (!isInRootDocument(outer)) { #if PLATFORM(WKC) if (outer->parent() && outer->parent()->isDocumentNode()) { Document* document = static_cast<Document*>(outer->parent()); candidate.enclosingScrollableBox = static_cast<Node*>(document->ownerElement()); } #else if (Document* document = static_cast<Document*>(outer->parent())) candidate.enclosingScrollableBox = static_cast<Node*>(document->ownerElement()); #endif } else if (isScrollableContainerNode(outer->parent())) candidate.enclosingScrollableBox = outer->parent(); // Get distance and alignment from current candidate. distanceDataForNode(direction, focusedNode, candidate); // Bail out if distance is maximum. if (candidate.distance == maxDistance()) { node = node->traverseNextNode(outer->parent()); continue; } updateFocusCandidateIfCloser(focusedNode, candidate, closest); } node = node->traverseNextNode(outer->parent()); } }
// return 0 if the job, with the given delay bound, // will complete by its deadline, and won't cause other jobs to miss deadlines. // static inline int check_deadline( WORKUNIT& wu, APP& app, BEST_APP_VERSION& bav ) { if (config.ignore_delay_bound) return 0; // skip delay check if host currently doesn't have any work // and it's not a hard app. // (i.e. everyone gets one result, no matter how slow they are) // if (get_estimated_delay(bav) == 0 && !hard_app(app)) { if (config.debug_send) { log_messages.printf(MSG_NORMAL, "[send] est delay 0, skipping deadline check\n" ); } return 0; } // if it's a hard app, don't send it to a host with no credit // if (hard_app(app) && g_reply->host.total_credit == 0) { return INFEASIBLE_CPU; } // do EDF simulation if possible; else use cruder approximation // if (config.workload_sim && g_request->have_other_results_list) { double est_dur = estimate_duration(wu, bav); if (g_reply->wreq.edf_reject_test(est_dur, wu.delay_bound)) { return INFEASIBLE_WORKLOAD; } IP_RESULT candidate("", wu.delay_bound, est_dur); safe_strcpy(candidate.name, wu.name); if (check_candidate(candidate, g_wreq->effective_ncpus, g_request->ip_results)) { // it passed the feasibility test, // but don't add it to the workload yet; // wait until we commit to sending it } else { g_reply->wreq.edf_reject(est_dur, wu.delay_bound); g_reply->wreq.speed.set_insufficient(0); return INFEASIBLE_WORKLOAD; } } else { double ewd = estimate_duration(wu, bav); if (hard_app(app)) ewd *= 1.3; double est_report_delay = get_estimated_delay(bav) + ewd; double diff = est_report_delay - wu.delay_bound; if (diff > 0) { if (config.debug_send) { log_messages.printf(MSG_NORMAL, "[send] [WU#%u] deadline miss %d > %d\n", wu.id, (int)est_report_delay, wu.delay_bound ); } g_reply->wreq.speed.set_insufficient(diff); return INFEASIBLE_CPU; } else { if (config.debug_send) { log_messages.printf(MSG_NORMAL, "[send] [WU#%u] meets deadline: %.2f + %.2f < %d\n", wu.id, get_estimated_delay(bav), ewd, wu.delay_bound ); } } } return 0; }
HRESULT CTextService::_HandleKey(TfEditCookie ec, ITfContext *pContext, WPARAM wParam) { /* * FIXME: the following keys are not handled: * shift left VK_LSHIFT * shift right VK_RSHIFT * caps lock VK_CAPITAL * page up VK_PRIOR * page down VK_NEXT * ctrl num * shift space * numlock num VK_NUMLOCK */ if (('A' <= wParam && wParam <= 'Z')) { chewing_handle_Default(mChewingContext, wParam - 'A' + 'a'); } else if ('0' <= wParam && wParam <= '9') { chewing_handle_Default(mChewingContext, wParam); } else { switch(wParam) { case VK_OEM_COMMA: chewing_handle_Default(mChewingContext, ','); break; case VK_OEM_MINUS: chewing_handle_Default(mChewingContext, '-'); break; case VK_OEM_PERIOD: chewing_handle_Default(mChewingContext, '.'); break; case VK_OEM_1: chewing_handle_Default(mChewingContext, ';'); break; case VK_OEM_2: chewing_handle_Default(mChewingContext, '/'); break; case VK_OEM_3: chewing_handle_Default(mChewingContext, '`'); break; case VK_SPACE: chewing_handle_Space(mChewingContext); break; case VK_ESCAPE: chewing_handle_Esc(mChewingContext); break; case VK_RETURN: chewing_handle_Enter(mChewingContext); break; case VK_DELETE: chewing_handle_Del(mChewingContext); break; case VK_BACK: chewing_handle_Backspace(mChewingContext); break; case VK_UP: chewing_handle_Up(mChewingContext); break; case VK_DOWN: chewing_handle_Down(mChewingContext); case VK_LEFT: chewing_handle_Left(mChewingContext); break; case VK_RIGHT: chewing_handle_Right(mChewingContext); break; case VK_HOME: chewing_handle_Home(mChewingContext); break; case VK_END: chewing_handle_End(mChewingContext); break; default: return S_OK; } } // Remove old candidate list. We will create a new one if necessary. _pCandidateList->_EndCandidateList(); ChewingCandidates candidate(mChewingContext); if (!candidate.IsEmpty()) { _SetCompositionDisplayAttributes(ec, pContext, _gaDisplayAttributeConverted); // // The document manager object is not cached. Get it from pContext. // ITfDocumentMgr *pDocumentMgr; if (pContext->GetDocumentMgr(&pDocumentMgr) == S_OK) { // // get the composition range. // ITfRange *pRange; if (_pComposition->GetRange(&pRange) == S_OK) { _pCandidateList->_StartCandidateList(_tfClientId, pDocumentMgr, pContext, ec, pRange, candidate); pRange->Release(); } pDocumentMgr->Release(); } return S_OK; } ChewingString commit(mChewingContext, CHEWING_STRING_COMMIT); if (!commit.IsEmpty()) { // FIXME: Need a better way to submit a string if (!_IsComposing()) _StartComposition(pContext); ULONG cFetched; BOOL fCovered; TF_SELECTION tfSelection; // FIXME: Why we need this here? // first, test where a keystroke would go in the document if an insert is done if (pContext->GetSelection(ec, TF_DEFAULT_SELECTION, 1, &tfSelection, &cFetched) != S_OK || cFetched != 1) return S_FALSE; // FIXME: Why we need this here? // is the insertion point covered by a composition? ITfRange *pRangeComposition; if (_pComposition->GetRange(&pRangeComposition) == S_OK) { fCovered = IsRangeCovered(ec, tfSelection.range, pRangeComposition); pRangeComposition->Release(); if (!fCovered) { goto End3; } } if (tfSelection.range->SetText(ec, 0, commit.GetString(), commit.GetLength()) != S_OK) goto End3; _TerminateComposition(ec, pContext); End3: // FIXME: RAII? tfSelection.range->Release(); } /* * Composition is mapped to preedit buffer + zuin buffer */ ChewingString preedit_zuin(mChewingContext, CHEWING_STRING_PREEDIT_ZUIN); if (preedit_zuin.IsEmpty()) { // Remove composition if (_IsComposing()) { ULONG cFetched; BOOL fCovered; TF_SELECTION tfSelection; // FIXME: Why we need this here? // first, test where a keystroke would go in the document if an insert is done if (pContext->GetSelection(ec, TF_DEFAULT_SELECTION, 1, &tfSelection, &cFetched) != S_OK || cFetched != 1) return S_FALSE; // FIXME: Why we need this here? // is the insertion point covered by a composition? ITfRange *pRangeComposition; if (_pComposition->GetRange(&pRangeComposition) == S_OK) { fCovered = IsRangeCovered(ec, tfSelection.range, pRangeComposition); pRangeComposition->Release(); if (!fCovered) { goto End; } } // Empties the composition tfSelection.range->SetText(ec, 0, L"", 0); _TerminateComposition(ec, pContext); End: // FIXME: RAII? tfSelection.range->Release(); } } else { if (!_IsComposing()) _StartComposition(pContext); ULONG cFetched; BOOL fCovered; TF_SELECTION tfSelection; // FIXME: Why we need this here? // first, test where a keystroke would go in the document if an insert is done if (pContext->GetSelection(ec, TF_DEFAULT_SELECTION, 1, &tfSelection, &cFetched) != S_OK || cFetched != 1) return S_FALSE; // FIXME: Why we need this here? // is the insertion point covered by a composition? ITfRange *pRangeComposition; if (_pComposition->GetRange(&pRangeComposition) == S_OK) { fCovered = IsRangeCovered(ec, tfSelection.range, pRangeComposition); pRangeComposition->Release(); if (!fCovered) { goto End2; } } if (tfSelection.range->SetText(ec, 0, preedit_zuin.GetString(), preedit_zuin.GetLength()) != S_OK) goto End2; _SetCompositionDisplayAttributes(ec, pContext, _gaDisplayAttributeInput); End2: // FIXME: RAII? tfSelection.range->Release(); } return S_OK; }
void PhotonMappingRenderer::TracePhoton(PhotonKdtree& photonMap, Ray* photonRay, glm::vec3 lightIntensity, std::vector<char>& path, float currentIOR, int remainingBounces) { // check the recursive base case if (remainingBounces < 0) { return; } assert(photonRay); IntersectionState state(0, 0); state.currentIOR = currentIOR; // Trace the photon ray and test for intersections bool didIntersect = storedScene->Trace(photonRay, &state); if (!didIntersect) { return; } // Get the normal to the intersection glm::vec3 normal = state.ComputeNormal(); // Move the ray to the intersection point + a little offset glm::vec3 intersectionPoint = state.intersectionRay.GetRayPosition(state.intersectionT); photonRay->SetRayPosition(intersectionPoint + normal * SMALL_EPSILON); if (path.size() > 1) { // This photon did NOT come directly from the light, so // create and store a new Photon in the photon map Ray toLightRay(glm::vec3(photonRay->GetPosition()), -photonRay->GetRayDirection(), photonRay->GetMaxT()); Photon myPhoton; myPhoton.position = glm::vec3(photonRay->GetPosition()); myPhoton.intensity = lightIntensity; myPhoton.toLightRay = toLightRay; photonMap.insert(myPhoton); } // --------determine whether this photon is scattered or absorbed-------- const MeshObject* hitMeshObject = state.intersectedPrimitive->GetParentMeshObject(); const Material* hitMaterial = hitMeshObject->GetMaterial(); glm::vec3 diffuseResponse = hitMaterial->GetBaseDiffuseReflection(); // the probability of reflection is the max of the RGB components of the diffuse response float max = diffuseResponse.x; if (diffuseResponse.y > max) { max = diffuseResponse.y; } if (diffuseResponse.z > max) { max = diffuseResponse.z; } // 0 to RAND_MAX float rand_f = static_cast<float>(rand()); // 0 to 1 rand_f /= RAND_MAX; if (rand_f > max) { // photon absorbed return; } // ------scatter the photon------ // sample the hemisphere around the point in order to // pick a diffuse reflection direction // 0 to RAND_MAX float u1 = static_cast<float>(rand()); float u2 = static_cast<float>(rand()); // 0 to 1 u1 /= RAND_MAX; u2 /= RAND_MAX; float r = sqrt(u1); float theta = 2 * PI * u2; float x = r * cos(theta); float y = r * sin(theta); float z = sqrt(1 - u1); glm::vec3 newDir = glm::normalize(glm::vec3(x, y, z)); // ---transform from tangent space to world space--- // pick one of (1, 0, 0) (0, 1, 0) (0, 0, 1) as long as // dot product is not close to 1 (therefore not parallel) // to cross the normal with glm::vec3 candidate(1.f, 0.f, 0.f); float dot = glm::dot(normal, candidate); if (dot > 0.9) { candidate = glm::vec3(0.f, 1.f, 0.f); } glm::vec3 tangent = glm::cross(normal, candidate); glm::vec3 bitangent = glm::cross(normal, tangent); // construct 3x3 matrix where columns of the matrix are the // tangent, bitangent, and normal vectors (in that order) glm::mat3 mat(tangent, bitangent, normal); // multiply 3x3 matrix by the newDir vector in the previous step // to get the diffuse reflection ray direction in world space glm::vec3 worldDir = mat * newDir; photonRay->SetRayDirection(worldDir); // append to path vector, decrement remaining bounces path.push_back('L'); remainingBounces--; // recursive call TracePhoton(photonMap, photonRay, lightIntensity, path, currentIOR, remainingBounces); }