hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
61f39db9a571f15c51777902873951279371c582
785
cpp
C++
Tutorials/30 Days of Code/Day 25/prime-numbers.cpp
xuedong/hacker-rank
ce8a60f80c2c6935b427f9409d7e826ee0d26a89
[ "MIT" ]
1
2021-02-22T17:37:45.000Z
2021-02-22T17:37:45.000Z
Tutorials/30 Days of Code/Day 25/prime-numbers.cpp
xuedong/hacker-rank
ce8a60f80c2c6935b427f9409d7e826ee0d26a89
[ "MIT" ]
null
null
null
Tutorials/30 Days of Code/Day 25/prime-numbers.cpp
xuedong/hacker-rank
ce8a60f80c2c6935b427f9409d7e826ee0d26a89
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int T; cin >> T; for (int i = 0; i < T; i++) { int n; cin >> n; if (n == 1) { cout << "Not prime" << endl; continue; } else if (n == 2) { cout << "Prime" << endl; continue; } bool flag = true; for (int j = 2; j < sqrt(n)+1; j++) { if (n % j == 0) flag = false; } if (flag) { cout << "Prime" << endl; } else { cout << "Not prime" << endl; } } return 0; }
19.146341
77
0.406369
[ "vector" ]
61f4d01afba7d5e95f34b788c5be961a7fde3d2f
5,646
cpp
C++
isis/src/hayabusa/apps/amica2isis/amica2isis.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/hayabusa/apps/amica2isis/amica2isis.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/hayabusa/apps/amica2isis/amica2isis.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
1
2021-07-12T06:05:03.000Z
2021-07-12T06:05:03.000Z
#include "Isis.h" #include <cstdio> #include <QString> #include <algorithm> #include "AlphaCube.h" #include "Brick.h" #include "FileName.h" #include "ImportFits.h" #include "iTime.h" #include "OriginalLabel.h" #include "PixelType.h" #include "ProcessImportPds.h" #include "UserInterface.h" using namespace std; using namespace Isis; void IsisMain () { ProcessImportPds p; UserInterface &ui = Application::GetUserInterface(); // Get input file and set translation processing FileName inFile = ui.GetFileName("FROM"); Pvl label; p.SetPdsFile (inFile.expanded(), "", label); // Add FITS header QString fitsImage = inFile.path() + "/" + (QString) label.findKeyword("^IMAGE"); FileName fitsFile(fitsImage); ImportFits fits(fitsFile, "FitsLabel"); label.addGroup(fits.label()); QString instid; QString missid; try { instid = (QString) label.findKeyword ("INSTRUMENT_ID", PvlObject::Traverse); missid = (QString) label.findKeyword ("INSTRUMENT_HOST_NAME", PvlObject::Traverse); } catch (IException &e) { QString msg = "Unable to read [INSTRUMENT_ID] or [INSTRUMENT_HOST_NAME] " "from input file [" + inFile.expanded() + "]"; throw IException(e, IException::Io,msg, _FILEINFO_); } instid = instid.simplified().trimmed(); missid = missid.simplified().trimmed(); if (missid != "HAYABUSA" && instid != "AMICA") { QString msg = "Input file [" + inFile.expanded() + "] does not appear to be a " + "Hayabusa/AMICA PDS label file."; throw IException(IException::Unknown, msg, _FILEINFO_); } QString target; if (ui.WasEntered("TARGET")) { target = ui.GetString("TARGET"); } // Set up image translation. Omit the inclusion of this .lbl file and we // add the label with the FITS header augmentation as the orginal label // further below. p.OmitOriginalLabel(); Cube *outcube = p.SetOutputCube ("TO"); p.StartProcess(); // Now flip the image lines since the first line is actually the last line. // Easiest way to do this is read the entire image array, flip lines and // rewrite the result back out. Brick image(outcube->sampleCount(), outcube->lineCount(), 1, Double); // Image extents int nsamps(outcube->sampleCount()); int nlines(outcube->lineCount()); int halfLines(nlines/2); // Just in case there is more than 1 band in the image... image.begin(); while (!image.end() ) { outcube->read(image); int samp0(0); // Index at first pixel of first line int samp1((nlines-1)*nsamps); // Index at first pixel of last line for (int line = 0 ; line < halfLines ; line++ ) { for (int i = samp0, j = samp1, n = 0 ; n < nsamps ; i++, j++, n++) { swap(image[i], image[j]); } samp0 += nsamps; samp1 -= nsamps; } outcube->write(image); image.next(); } // Get the directory where the Hayabusa translation tables are. PvlGroup dataDir (Preference::Preferences().findGroup("DataDirectory")); QString transDir = (QString) dataDir["Hayabusa"] + "/translations/"; // Create a PVL to store the translated labels in Pvl outLabel; // Translate the BandBin group FileName transFile (transDir + "amicaBandBin.trn"); PvlToPvlTranslationManager bandBinXlater (label, transFile.expanded()); bandBinXlater.Auto(outLabel); // Translate the Archive group transFile = transDir + "amicaArchive.trn"; PvlToPvlTranslationManager archiveXlater (label, transFile.expanded()); archiveXlater.Auto(outLabel); // Translate the Instrument group transFile = transDir + "amicaInstrument.trn"; PvlToPvlTranslationManager instrumentXlater (label, transFile.expanded()); instrumentXlater.Auto(outLabel); // Create YearDoy keyword in Archive group iTime stime(outLabel.findGroup("Instrument", Pvl::Traverse)["StartTime"][0]); PvlKeyword yeardoy("YearDoy", toString(stime.Year()*1000 + stime.DayOfYear())); (void) outLabel.findGroup("Archive", Pvl::Traverse).addKeyword(yeardoy); // Update target if user specifies it if (!target.isEmpty()) { PvlGroup &igrp = outLabel.findGroup("Instrument",Pvl::Traverse); igrp["TargetName"] = target; } // Write the BandBin, Archive, and Instrument groups // to the output cube label outcube->putGroup(outLabel.findGroup("BandBin",Pvl::Traverse)); outcube->putGroup(outLabel.findGroup("Archive",Pvl::Traverse)); outcube->putGroup(outLabel.findGroup("Instrument",Pvl::Traverse)); // Use the HAYABUSA_AMICA frame code rather than HAYABUSA_AMICA_IDEAL PvlGroup kerns("Kernels"); kerns += PvlKeyword("NaifFrameCode","-130102"); outcube->putGroup(kerns); // Now write the FITS augmented label as the original label OriginalLabel oldLabel(label); outcube->write(oldLabel); #if 0 // Check for subimage and create an AlphaCube that describes thes subarea and // update the cube labels. DO NOT adjust for scale. Camera model will handle // that. Coordinates in label are 0-based. if ( (1024 != nsamps) || (1024 != nlines) ) { PvlGroup inst = outLabel.findGroup("Instrument",Pvl::Traverse); int starting_samp = (int) inst["FirstSample"] + 1; int starting_line = (int) inst["FirstLine"] + 1; int ending_samp = (int) inst["LastSample"] + 1; int ending_line = (int) inst["LastLine"] + 1; AlphaCube subarea(1024, 1024, nsamps, nlines, starting_samp - 0.5, starting_line - 0.5, ending_samp + 0.5, ending_line + 0.5); subarea.UpdateGroup(*outcube); } #endif // All done... p.EndProcess(); }
32.825581
88
0.669678
[ "model" ]
61f5bc923686e123c5c4665532156b11d176f49e
22,538
cpp
C++
services/bluetooth_standard/service/src/map_mse/map_mse_params.cpp
openharmony-sig-ci/communication_bluetooth
c9d9614e881224abfb423505e25e72163dd25df3
[ "Apache-2.0" ]
null
null
null
services/bluetooth_standard/service/src/map_mse/map_mse_params.cpp
openharmony-sig-ci/communication_bluetooth
c9d9614e881224abfb423505e25e72163dd25df3
[ "Apache-2.0" ]
null
null
null
services/bluetooth_standard/service/src/map_mse/map_mse_params.cpp
openharmony-sig-ci/communication_bluetooth
c9d9614e881224abfb423505e25e72163dd25df3
[ "Apache-2.0" ]
1
2021-09-13T11:16:33.000Z
2021-09-13T11:16:33.000Z
/* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "map_mse_params.h" namespace bluetooth { // Tag Id const uint8_t MapMseParams::PARAM_MAX_LIST_COUNT; const uint8_t MapMseParams::PARAM_LIST_START_OFF_SET; const uint8_t MapMseParams::PARAM_FILTER_MESSAGE_TYPE; const uint8_t MapMseParams::PARAM_FILTER_PERIOD_BEGIN; const uint8_t MapMseParams::PARAM_FILTER_PERIOD_END; const uint8_t MapMseParams::PARAM_FILTER_READ_STATUS; const uint8_t MapMseParams::PARAM_FILTER_RECIPIENT; const uint8_t MapMseParams::PARAM_FILTER_ORIGINATOR; const uint8_t MapMseParams::PARAM_FILTER_PRIORITY; const uint8_t MapMseParams::PARAM_ATTACHMENT; const uint8_t MapMseParams::PARAM_TRANSPARENT; const uint8_t MapMseParams::PARAM_RETRY; const uint8_t MapMseParams::PARAM_NEW_MESSAGE; const uint8_t MapMseParams::PARAM_NOTIFICATION_STATUS; const uint8_t MapMseParams::PARAM_MAS_INSTANCEID; const uint8_t MapMseParams::PARAM_PARAMETER_MASK; const uint8_t MapMseParams::PARAM_FOLDER_LISTING_SIZE; const uint8_t MapMseParams::PARAM_LISTING_SIZE; const uint8_t MapMseParams::PARAM_SUBJECT_LENGTH; const uint8_t MapMseParams::PARAM_CHARSET; const uint8_t MapMseParams::PARAM_FRACTION_REQUEST; const uint8_t MapMseParams::PARAM_FRACTION_DELIVER; const uint8_t MapMseParams::PARAM_STATUS_INDICATOR; const uint8_t MapMseParams::PARAM_STATUS_VALUE; const uint8_t MapMseParams::PARAM_MSE_TIME; const uint8_t MapMseParams::PARAM_DATABASE_IDENTIFIER; const uint8_t MapMseParams::PARAM_CONVERSATION_LISTING_VERSION_COUNTER; const uint8_t MapMseParams::PARAM_PRESENCE_AVAILABILITY; const uint8_t MapMseParams::PARAM_PRESENCE_TEXT; const uint8_t MapMseParams::PARAM_LAST_ACTIVITY; const uint8_t MapMseParams::PARAM_FILTER_LAST_ACTIVITY_BEGIN; const uint8_t MapMseParams::PARAM_FILTER_LAST_ACTIVITY_END; const uint8_t MapMseParams::PARAM_CHAT_STATE; const uint8_t MapMseParams::PARAM_CONVERSATION_ID; const uint8_t MapMseParams::PARAM_FOLDER_VERSION_COUNTER; const uint8_t MapMseParams::PARAM_FILTER_MESSAGE_HANDLE; const uint8_t MapMseParams::PARAM_NOTIFICATION_FILTER_MASK; const uint8_t MapMseParams::PARAM_CONV_PARAMETER_MASK; const uint8_t MapMseParams::PARAM_OWNER_UCI; const uint8_t MapMseParams::PARAM_EXTENDED_DATA; const uint8_t MapMseParams::PARAM_MAP_SUPPORTED_FEATURES; const uint8_t MapMseParams::PARAM_MESSAGE_HANDLE; const uint8_t MapMseParams::PARAM_MODIFY_TEXT; // Tag Length const uint8_t MapMseParams::TAG_LEN_MAX_LIST_COUNT; const uint8_t MapMseParams::TAG_LEN_LIST_START_OFF_SET; const uint8_t MapMseParams::TAG_LEN_FILTER_MESSAGE_TYPE; const uint8_t MapMseParams::TAG_LEN_FILTER_PERIOD_BEGIN; const uint8_t MapMseParams::TAG_LEN_FILTER_PERIOD_END; const uint8_t MapMseParams::TAG_LEN_FILTER_READ_STATUS; const uint8_t MapMseParams::TAG_LEN_FILTER_PRIORITY; const uint8_t MapMseParams::TAG_LEN_ATTACHMENT; const uint8_t MapMseParams::TAG_LEN_TRANSPARENT; const uint8_t MapMseParams::TAG_LEN_RETRY; const uint8_t MapMseParams::TAG_LEN_NEW_MESSAGE; const uint8_t MapMseParams::TAG_LEN_NOTIFICATION_STATUS; const uint8_t MapMseParams::TAG_LEN_MAS_INSTANCEID; const uint8_t MapMseParams::TAG_LEN_PARAMETER_MASK; const uint8_t MapMseParams::TAG_LEN_FOLDER_LISTING_SIZE; const uint8_t MapMseParams::TAG_LEN_LISTING_SIZE; const uint8_t MapMseParams::TAG_LEN_SUBJECT_LENGTH; const uint8_t MapMseParams::TAG_LEN_CHARSET; const uint8_t MapMseParams::TAG_LEN_FRACTION_REQUEST; const uint8_t MapMseParams::TAG_LEN_FRACTION_DELIVER; const uint8_t MapMseParams::TAG_LEN_STATUS_INDICATOR; const uint8_t MapMseParams::TAG_LEN_STATUS_VALUE; const uint8_t MapMseParams::TAG_LEN_DATABASE_IDENTIFIER; const uint8_t MapMseParams::TAG_LEN_CONVERSATION_LISTING_VERSION_COUNTER; const uint8_t MapMseParams::TAG_LEN_PRESENCE_AVAILABILITY; const uint8_t MapMseParams::TAG_LEN_CHAT_STATE; const uint8_t MapMseParams::TAG_LEN_CONVERSATION_ID; const uint8_t MapMseParams::TAG_LEN_FOLDER_VERSION_COUNTER; const uint8_t MapMseParams::TAG_LEN_FILTER_MESSAGE_HANDLE; const uint8_t MapMseParams::TAG_LEN_NOTIFICATION_FILTER_MASK; const uint8_t MapMseParams::TAG_LEN_CONV_PARAMETER_MASK; const uint8_t MapMseParams::TAG_LEN_MAP_SUPPORTED_FEATURES; const uint8_t MapMseParams::TAG_LEN_MESSAGE_HANDLE; const uint8_t MapMseParams::TAG_LEN_MODIFY_TEXT; MapMseParams::MapMseParams(const ObexTlvParamters &tlvParams) { ParseParameter(tlvParams.GetTlvTriplets()); } MapMseParams::~MapMseParams() {} void MapMseParams::SetMaxListCount(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_MAX_LIST_COUNT) { MSE_LOG_ERROR("MAX_LIST_COUNT: Wrong length received: %hhx expected: less than %hhx", tlvTriplet->GetLen(), TAG_LEN_MAX_LIST_COUNT); return; } maxListCount_ = tlvTriplet->GetUint16(); } void MapMseParams::SetListStartOffSet(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_LIST_START_OFF_SET) { MSE_LOG_ERROR("LIST_START_OFF_SET: Wrong length received: %hhx expected: less than %hhx", tlvTriplet->GetLen(), TAG_LEN_LIST_START_OFF_SET); return; } listStartOffSet_ = tlvTriplet->GetUint16(); } void MapMseParams::SetFilterMessageType(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_FILTER_MESSAGE_TYPE) { MSE_LOG_ERROR("FILTER_MESSAGE_TYPE: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_FILTER_MESSAGE_TYPE); return; } filterMessageType_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetFilterOriginator(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() == 0x00) { MSE_LOG_ERROR("FILTER_ORIGINATOR: Wrong length received: %hhx expected to be more than 0", tlvTriplet->GetLen()); return; } filterOriginator_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::SetFilterPeriodBegin(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_FILTER_PERIOD_BEGIN) { MSE_LOG_ERROR("FILTER_PERIOD_BEGIN: Wrong length received: %hhx expected: less than %hhx", tlvTriplet->GetLen(), TAG_LEN_FILTER_PERIOD_BEGIN); return; } std::string ymdhmsStr((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); filterPeriodBegin_ = ymdhmsStr; } void MapMseParams::SetFilterPeriodEnd(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_FILTER_PERIOD_END) { MSE_LOG_ERROR("END_FILTER_PERIOD_END: Wrong length received: %hhx expected: less than %hhx", tlvTriplet->GetLen(), TAG_LEN_FILTER_PERIOD_END); return; } std::string ymdhmsStr((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); filterPeriodEnd_ = ymdhmsStr; } void MapMseParams::SetFilterReadStatus(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_FILTER_READ_STATUS) { MSE_LOG_ERROR("FILTER_READ_STATUS: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_FILTER_READ_STATUS); return; } filterReadStatus_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetFilterRecipient(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() == 0x00) { MSE_LOG_ERROR("FILTER_RECIPIENT: Wrong length received: %hhx expected to be more than 0", tlvTriplet->GetLen()); return; } filterRecipient_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::SetFilterPriority(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_FILTER_PRIORITY) { MSE_LOG_ERROR("FILTER_PRIORITY: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_FILTER_PRIORITY); return; } filterPriority_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetAttachment(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_ATTACHMENT) { MSE_LOG_ERROR("ATTACHMENT: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_ATTACHMENT); return; } attachment_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetTransparent(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_TRANSPARENT) { MSE_LOG_ERROR("TRANSPARENT: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_TRANSPARENT); return; } transparent_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetRetry(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_RETRY) { MSE_LOG_ERROR("RETRY: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_RETRY); return; } retry_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetNotificationStatus(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_NOTIFICATION_STATUS) { MSE_LOG_ERROR("NOTIFICATION_STATUS: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_NOTIFICATION_STATUS); return; } notificationStatus_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetMasInstanceId(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_MAS_INSTANCEID) { MSE_LOG_ERROR("MAS_INSTANCEID: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_MAS_INSTANCEID); return; } masInstanceId_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetParameterMask(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_PARAMETER_MASK) { MSE_LOG_ERROR("PARAMETER_MASK: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_PARAMETER_MASK); return; } parameterMask_ = tlvTriplet->GetUint32(); } void MapMseParams::SetFolderListingSize(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_FOLDER_LISTING_SIZE) { MSE_LOG_ERROR("FOLDER_LISTING_SIZE: Wrong length received: %hhx expected: less than %hhx", tlvTriplet->GetLen(), TAG_LEN_FOLDER_LISTING_SIZE); return; } folderListingSize_ = tlvTriplet->GetUint16(); } void MapMseParams::SetListingSize(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_LISTING_SIZE) { MSE_LOG_ERROR("LISTING_SIZE: Wrong length received: %hhx expected: less than %hhx", tlvTriplet->GetLen(), TAG_LEN_LISTING_SIZE); return; } listingSize_ = tlvTriplet->GetUint16(); } void MapMseParams::SetSubjectLength(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_SUBJECT_LENGTH) { MSE_LOG_ERROR("SUBJECT_LENGTH: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_SUBJECT_LENGTH); return; } subjectLength_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetCharset(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_CHARSET) { MSE_LOG_ERROR("CHARSET: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_CHARSET); return; } charSet_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetFractionRequest(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_FRACTION_REQUEST) { MSE_LOG_ERROR("FRACTION_REQUEST: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_FRACTION_REQUEST); return; } fractionRequest_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetFractionDeliver(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_FRACTION_DELIVER) { MSE_LOG_ERROR("FRACTION_DELIVER: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_FRACTION_DELIVER); return; } fractionDeliver_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetStatusIndicator(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_STATUS_INDICATOR) { MSE_LOG_ERROR("STATUS_INDICATOR: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_STATUS_INDICATOR); return; } statusIndicator_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetStatusValue(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_STATUS_VALUE) { MSE_LOG_ERROR( "STATUS_VALUE: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_STATUS_VALUE); return; } statusValue_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetExtendedData(const std::unique_ptr<TlvTriplet> &tlvTriplet) { extendedData_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::SetFilterLastActivityBegin(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() == 0x00) { MSE_LOG_ERROR("FILTER_LAST_ACTIVITY_BEGIN: Wrong length received: %hhx expected to be more than 0", tlvTriplet->GetLen()); return; } filterLastActivityBegin_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::SetFilterLastActivityEnd(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() == 0x00) { MSE_LOG_ERROR("FILTER_LAST_ACTIVITY_END: Wrong length received: %hhx expected to be more than 0", tlvTriplet->GetLen()); return; } filterLastActivityEnd_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::SetChatState(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_CHAT_STATE) { MSE_LOG_ERROR("CHAT_STATE: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_CHAT_STATE); return; } chatState_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetConversationId(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_CONVERSATION_ID) { MSE_LOG_ERROR("CONVERSATION_ID: Wrong length received: %hhx expected to be less than %hhx", tlvTriplet->GetLen(), TAG_LEN_CONVERSATION_ID); return; } conversationId_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::SetNotificationFilterMask(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_NOTIFICATION_FILTER_MASK) { MSE_LOG_ERROR("NOTIFICATION_FILTER_MASK: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_NOTIFICATION_FILTER_MASK); return; } notificationFilterMask_ = tlvTriplet->GetUint32(); } void MapMseParams::SetFilterMessageHandle(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_FILTER_MESSAGE_HANDLE) { MSE_LOG_ERROR("FILTER_MESSAGE_HANDLE: Wrong length received: %hhx expected to be less than %hhx", tlvTriplet->GetLen(), TAG_LEN_FILTER_MESSAGE_HANDLE); return; } filterMessageHandle_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::SetConvParameterMask(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_CONV_PARAMETER_MASK) { MSE_LOG_ERROR("CONV_PARAMETER_MASK: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_CONV_PARAMETER_MASK); return; } convParameterMask_ = tlvTriplet->GetUint32(); } void MapMseParams::SetOwnerUci(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() == 0x00) { MSE_LOG_ERROR("OWNER_UCI: Wrong length received: %hhx expected to be more than 0", tlvTriplet->GetLen()); return; } ownerUci_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::SetModifyText(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() != TAG_LEN_MODIFY_TEXT) { MSE_LOG_ERROR("MODIFY_TEXT: Wrong length received: %hhx expected: %hhx", tlvTriplet->GetLen(), TAG_LEN_MODIFY_TEXT); return; } modifyText_ = std::make_unique<uint8_t>(tlvTriplet->GetVal()[0]); } void MapMseParams::SetMessageHandle(const std::unique_ptr<TlvTriplet> &tlvTriplet) { if (tlvTriplet->GetLen() > TAG_LEN_MESSAGE_HANDLE) { MSE_LOG_ERROR("MESSAGE_HANDLE: Wrong length received: %hhx expected to be less than %hhx", tlvTriplet->GetLen(), TAG_LEN_MESSAGE_HANDLE); return; } messageHandle_ = std::string((char *)tlvTriplet->GetVal(), tlvTriplet->GetLen()); } void MapMseParams::ParseParameter(const std::vector<std::unique_ptr<TlvTriplet>> &tlvTriplets) { for (auto &para : tlvTriplets) { switch (para->GetTagId()) { case PARAM_MAX_LIST_COUNT: SetMaxListCount(para); break; case PARAM_LIST_START_OFF_SET: SetListStartOffSet(para); break; case PARAM_FILTER_MESSAGE_TYPE: SetFilterMessageType(para); break; case PARAM_FILTER_PERIOD_BEGIN: SetFilterPeriodBegin(para); break; case PARAM_FILTER_PERIOD_END: SetFilterPeriodEnd(para); break; case PARAM_FILTER_READ_STATUS: SetFilterReadStatus(para); break; case PARAM_FILTER_RECIPIENT: SetFilterRecipient(para); break; case PARAM_FILTER_ORIGINATOR: SetFilterOriginator(para); break; case PARAM_FILTER_PRIORITY: SetFilterPriority(para); break; case PARAM_ATTACHMENT: SetAttachment(para); break; case PARAM_TRANSPARENT: SetTransparent(para); break; case PARAM_RETRY: SetRetry(para); break; case PARAM_NEW_MESSAGE: break; case PARAM_NOTIFICATION_STATUS: SetNotificationStatus(para); break; case PARAM_MAS_INSTANCEID: SetMasInstanceId(para); break; case PARAM_PARAMETER_MASK: SetParameterMask(para); break; case PARAM_FOLDER_LISTING_SIZE: SetFolderListingSize(para); break; case PARAM_LISTING_SIZE: SetListingSize(para); break; case PARAM_SUBJECT_LENGTH: SetSubjectLength(para); break; case PARAM_CHARSET: SetCharset(para); break; case PARAM_FRACTION_REQUEST: SetFractionRequest(para); break; case PARAM_FRACTION_DELIVER: SetFractionDeliver(para); break; case PARAM_STATUS_INDICATOR: SetStatusIndicator(para); break; case PARAM_STATUS_VALUE: SetStatusValue(para); break; case PARAM_MSE_TIME: break; case PARAM_DATABASE_IDENTIFIER: break; case PARAM_CONVERSATION_LISTING_VERSION_COUNTER: break; case PARAM_PRESENCE_AVAILABILITY: break; case PARAM_PRESENCE_TEXT: break; case PARAM_LAST_ACTIVITY: break; case PARAM_FILTER_LAST_ACTIVITY_BEGIN: SetFilterLastActivityBegin(para); break; case PARAM_FILTER_LAST_ACTIVITY_END: SetFilterLastActivityEnd(para); break; case PARAM_CHAT_STATE: SetChatState(para); break; case PARAM_CONVERSATION_ID: SetConversationId(para); break; case PARAM_FOLDER_VERSION_COUNTER: break; case PARAM_FILTER_MESSAGE_HANDLE: SetFilterMessageHandle(para); break; case PARAM_NOTIFICATION_FILTER_MASK: SetNotificationFilterMask(para); break; case PARAM_CONV_PARAMETER_MASK: SetConvParameterMask(para); break; case PARAM_OWNER_UCI: SetOwnerUci(para); break; case PARAM_EXTENDED_DATA: SetExtendedData(para); break; case PARAM_MODIFY_TEXT: SetModifyText(para); break; case PARAM_MESSAGE_HANDLE: SetMessageHandle(para); break; default: break; } } } } // namespace bluetooth
37.688963
116
0.682847
[ "vector" ]
61f6f70ccf1315cd7b824ac88b8e28084ea42338
4,139
cxx
C++
src/Util/sumHists.cxx
fermi-lat/calibGenCAL
9b207d7ba56031f5ecd7aab544e68a6dedc7d776
[ "BSD-3-Clause" ]
null
null
null
src/Util/sumHists.cxx
fermi-lat/calibGenCAL
9b207d7ba56031f5ecd7aab544e68a6dedc7d776
[ "BSD-3-Clause" ]
null
null
null
src/Util/sumHists.cxx
fermi-lat/calibGenCAL
9b207d7ba56031f5ecd7aab544e68a6dedc7d776
[ "BSD-3-Clause" ]
null
null
null
// $Header: /nfs/slac/g/glast/ground/cvs/calibGenCAL/src/Util/sumHists.cxx,v 1.2 2008/05/13 16:54:00 fewtrell Exp $ /** @file @author Zachary Fewtrell Sum all histograms with same name across multiple files into a new file. All histograms that only appear in at least one file will be copied to new file Side effect: All sub-directories from all files will be present in output file. Note: only histograms with same name and relative path within different fo;e will be summed. @input: list of digi root files on commandline @output: single digi root file with all histograms from input files, histograms w/ same name & path are summed. */ // EXTLIB INCLUDES #include "TFile.h" #include "TIterator.h" #include "TClass.h" #include "TH1.h" #include "TROOT.h" // STD INCLUDES #include <string> #include <vector> #include <iostream> using namespace std; namespace { /// Recursively add all histograms and directories in inputDir to outputDir. // Any histograms with same name & path will be summed within outputDir void sumDir(TDirectory &outputDir, TDirectory &inputDir) { /// don't know if inputDir is TFile or TDirectory, simplest is to /// treat all as if TDirectory, if I want to do this, I need to read /// all objs into memory (otherwise I would have to use /// GetListOfKeys() instead of GetList()) /// /// if you know a better way, don't be shy! inputDir.ReadAll(); TIterator *it = inputDir.GetList()->MakeIterator(); TObject *obj; while ((obj = (TObject*)it->Next()) != 0) { TClass *cls = gROOT->GetClass(obj->ClassName()); /// CASE 1: Obj is histogram if (cls->InheritsFrom("TH1")) { TH1 *hnew = (TH1*)obj; TH1 *hout = 0; const string hname(obj->GetName()); /// CASE 1A: histogram already exist if ((hout = (TH1*)outputDir.Get(hname.c_str())) != 0) { cout << "Summing to existing histogram: " << inputDir.GetPathStatic() << "/" << hname << endl; hout->Add(hnew); outputDir.cd(); hout->Write(0,TObject::kOverwrite); } /// CASE 1B: histogram does not already exit else { cout << "Adding new histogram: " << inputDir.GetPathStatic() << "/" << hname << endl; outputDir.Add(hnew); outputDir.cd(); hnew->Write(); } } /// CASE 2: Obj is directory else if (cls->InheritsFrom("TDirectory")) { TDirectory *const dnew = (TDirectory*)obj; char const*const dname = dnew->GetName(); /// make subdir if it doesn't already exit TDirectory * dout = outputDir.GetDirectory(dname); if (dout == 0) dout = outputDir.mkdir(dname); /// recursively process subdirs sumDir(*dout, *dnew); } } } const string usage_str = "sumHists.cxx outputPath.root [inputPath.root]+\n" "where: \n" " outputPath.root = output ROOT file\n" " inputPath.root = list of 1 or more input ROOT files"; vector<string> getLinesFromFile(istream &infile) { vector<string> retval; string line; while (infile.good()) { getline(infile, line); if (infile.fail()) break; // bad get retval.push_back(line); } return retval; } } int main(const int argc, char const*const*const argv) { /// check commandline if (argc < 3) { cout << "Not enough paramters: " << endl; cout << usage_str << endl; return -1; } /// retrieve commandline args const string outputPath(argv[1]); vector<string> inputPaths; /// get input files from commandline inputPaths.insert(inputPaths.end(), &argv[2], &argv[argc]); cout << "Opening output file: " << outputPath << endl; TFile outputFile(outputPath.c_str(), "RECREATE"); /// loop through each input for (unsigned nFile = 0; nFile < inputPaths.size(); nFile++) { const string inputPath = inputPaths[nFile]; cout << "Opening input file: " << inputPath << endl; TFile fin(inputPath.c_str() ,"READ"); sumDir(outputFile, fin); } outputFile.Close(); }
29.35461
115
0.621648
[ "vector" ]
61f8f08fb6a3475cde2b1da01d71cc851a061ea7
1,583
cpp
C++
KickStart/2019/Round-A/Training/solution.cpp
icgw/LeetCode
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
4
2018-09-12T09:32:17.000Z
2018-12-06T03:17:38.000Z
KickStart/2019/Round-A/Training/solution.cpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
KickStart/2019/Round-A/Training/solution.cpp
icgw/algorithm
cb70ca87aa4604d1aec83d4224b3489eacebba75
[ "MIT" ]
null
null
null
/* * solution.cpp * Copyright (C) 2019 Guowei Chen <icgw@outlook.com> * * Distributed under terms of the MIT license. */ #include <iostream> #include <algorithm> #include <vector> using namespace std; /*{{{ First try: Time Limit Exceeded. (Brute Force) */ // int main() // { // int T; cin >> T; // for (int i = 1; i <= T; ++i) { // int N, P; // cin >> N >> P; // vector<int> stds (N); // for (int j = 0; j < N; ++j) { // cin >> stds[j]; // } // sort(stds.begin(), stds.end()); // int ans = 0x3f3f3f3f; // for (int m = 0; m <= N - P; ++m) { // int tmp = 0, hi = stds[m + P - 1]; // for (int k = m; k < m + P; ++k) { // tmp += (hi - stds[k]); // } // ans = min(tmp, ans); // } // cout << "Case #" << i << ": " << ans << "\n"; // } // return 0; // } /*}}}*/ int main() { int T; cin >> T; for (int i = 1; i <= T; ++i) { int N, P; cin >> N >> P; vector<int> stds (N); for (int j = 0; j < N; ++j) { cin >> stds[j]; } // NOTE: O(Nlog(N)) sort(stds.begin(), stds.end()); int pre = 0; for (int kk = 0; kk < P - 1; ++kk) { pre += (stds[P - 1] - stds[kk]); } int diff = stds[P - 1] - stds[0]; int ans = pre; // NOTE: O(N - P) for (int m = 1; m <= N - P; ++m) { int tmp = pre - diff, hi = stds[m + P - 1]; diff = hi - stds[m]; tmp += ((stds[m + P - 1] - stds[m + P - 2]) * (P - 1)); ans = min(tmp, ans); pre = tmp; } cout << "Case #" << i << ": " << ans << "\n"; } return 0; }
20.828947
61
0.404296
[ "vector" ]
110074c583f517e7dbfe82d9ccdcd212ed0b4b9e
6,106
cpp
C++
src/dawn/native/d3d12/D3D12Info.cpp
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
9
2021-11-05T11:08:14.000Z
2022-03-18T05:14:34.000Z
src/dawn/native/d3d12/D3D12Info.cpp
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
2
2021-12-01T05:08:59.000Z
2022-02-18T08:14:30.000Z
src/dawn/native/d3d12/D3D12Info.cpp
hexops/dawn
36cc72ad1c7b0c0a92be4754b95b1441850533b0
[ "Apache-2.0" ]
1
2022-02-11T17:39:44.000Z
2022-02-11T17:39:44.000Z
// Copyright 2019 The Dawn Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "dawn/native/d3d12/D3D12Info.h" #include <utility> #include "dawn/common/GPUInfo.h" #include "dawn/native/d3d12/AdapterD3D12.h" #include "dawn/native/d3d12/BackendD3D12.h" #include "dawn/native/d3d12/D3D12Error.h" #include "dawn/native/d3d12/PlatformFunctions.h" namespace dawn::native::d3d12 { ResultOrError<D3D12DeviceInfo> GatherDeviceInfo(const Adapter& adapter) { D3D12DeviceInfo info = {}; // Newer builds replace D3D_FEATURE_DATA_ARCHITECTURE with // D3D_FEATURE_DATA_ARCHITECTURE1. However, D3D_FEATURE_DATA_ARCHITECTURE can be used // for backwards compat. // https://docs.microsoft.com/en-us/windows/desktop/api/d3d12/ne-d3d12-d3d12_feature D3D12_FEATURE_DATA_ARCHITECTURE arch = {}; DAWN_TRY(CheckHRESULT(adapter.GetDevice()->CheckFeatureSupport(D3D12_FEATURE_ARCHITECTURE, &arch, sizeof(arch)), "ID3D12Device::CheckFeatureSupport")); info.isUMA = arch.UMA; D3D12_FEATURE_DATA_D3D12_OPTIONS options = {}; DAWN_TRY(CheckHRESULT(adapter.GetDevice()->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &options, sizeof(options)), "ID3D12Device::CheckFeatureSupport")); info.resourceHeapTier = options.ResourceHeapTier; // Windows builds 1809 and above can use the D3D12 render pass API. If we query // CheckFeatureSupport for D3D12_FEATURE_D3D12_OPTIONS5 successfully, then we can use // the render pass API. info.supportsRenderPass = false; D3D12_FEATURE_DATA_D3D12_OPTIONS5 featureOptions5 = {}; if (SUCCEEDED(adapter.GetDevice()->CheckFeatureSupport( D3D12_FEATURE_D3D12_OPTIONS5, &featureOptions5, sizeof(featureOptions5)))) { // Performance regressions been observed when using a render pass on Intel graphics // with RENDER_PASS_TIER_1 available, so fall back to a software emulated render // pass on these platforms. if (featureOptions5.RenderPassesTier < D3D12_RENDER_PASS_TIER_1 || !gpu_info::IsIntel(adapter.GetVendorId())) { info.supportsRenderPass = true; } } // Used to share resources cross-API. If we query CheckFeatureSupport for // D3D12_FEATURE_D3D12_OPTIONS4 successfully, then we can use cross-API sharing. info.supportsSharedResourceCapabilityTier1 = false; D3D12_FEATURE_DATA_D3D12_OPTIONS4 featureOptions4 = {}; if (SUCCEEDED(adapter.GetDevice()->CheckFeatureSupport( D3D12_FEATURE_D3D12_OPTIONS4, &featureOptions4, sizeof(featureOptions4)))) { // Tier 1 support additionally enables the NV12 format. Since only the NV12 format // is used by Dawn, check for Tier 1. if (featureOptions4.SharedResourceCompatibilityTier >= D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_1) { info.supportsSharedResourceCapabilityTier1 = true; } } D3D12_FEATURE_DATA_SHADER_MODEL knownShaderModels[] = {{D3D_SHADER_MODEL_6_2}, {D3D_SHADER_MODEL_6_1}, {D3D_SHADER_MODEL_6_0}, {D3D_SHADER_MODEL_5_1}}; uint32_t driverShaderModel = 0; for (D3D12_FEATURE_DATA_SHADER_MODEL shaderModel : knownShaderModels) { if (SUCCEEDED(adapter.GetDevice()->CheckFeatureSupport( D3D12_FEATURE_SHADER_MODEL, &shaderModel, sizeof(shaderModel)))) { driverShaderModel = shaderModel.HighestShaderModel; break; } } if (driverShaderModel < D3D_SHADER_MODEL_5_1) { return DAWN_INTERNAL_ERROR("Driver doesn't support Shader Model 5.1 or higher"); } // D3D_SHADER_MODEL is encoded as 0xMm with M the major version and m the minor version ASSERT(driverShaderModel <= 0xFF); uint32_t shaderModelMajor = (driverShaderModel & 0xF0) >> 4; uint32_t shaderModelMinor = (driverShaderModel & 0xF); ASSERT(shaderModelMajor < 10); ASSERT(shaderModelMinor < 10); info.shaderModel = 10 * shaderModelMajor + shaderModelMinor; // Profiles are always <stage>s_<minor>_<major> so we build the s_<minor>_major and add // it to each of the stage's suffix. std::wstring profileSuffix = L"s_M_n"; profileSuffix[2] = wchar_t('0' + shaderModelMajor); profileSuffix[4] = wchar_t('0' + shaderModelMinor); info.shaderProfiles[SingleShaderStage::Vertex] = L"v" + profileSuffix; info.shaderProfiles[SingleShaderStage::Fragment] = L"p" + profileSuffix; info.shaderProfiles[SingleShaderStage::Compute] = L"c" + profileSuffix; D3D12_FEATURE_DATA_D3D12_OPTIONS4 featureData4 = {}; if (SUCCEEDED(adapter.GetDevice()->CheckFeatureSupport( D3D12_FEATURE_D3D12_OPTIONS4, &featureData4, sizeof(featureData4)))) { info.supportsShaderFloat16 = driverShaderModel >= D3D_SHADER_MODEL_6_2 && featureData4.Native16BitShaderOpsSupported; } return std::move(info); } } // namespace dawn::native::d3d12
48.848
99
0.645922
[ "render", "model" ]
1101264bc15f4cc1bd52a44953da555f28345633
28,291
hxx
C++
inetcore/wininet/inc/hinet.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/wininet/inc/hinet.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/wininet/inc/hinet.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1994 Microsoft Corporation Module Name: handle.hxx Abstract: Contains client-side internet handle class Author: Madan Appiah (madana) 16-Nov-1994 Environment: User Mode - Win32 Revision History: Sophia Chung (sophiac) 12-Feb-1995 (added FTP handle obj. class defs) --*/ #ifndef _HINET_ #define _HINET_ // // manifests // #define OBJECT_SIGNATURE 0x41414141 // "AAAA" #define DESTROYED_OBJECT_SIGNATURE 0x5A5A5A5A // "ZZZZ" #define LOCAL_INET_HANDLE (HINTERNET)-2 #define INET_INVALID_HANDLE_VALUE (NULL) #define MAX_PROXY_BYPASS_BUCKETS 256 // // types // typedef DWORD (*URLGEN_FUNC)( INTERNET_SCHEME, LPSTR, LPSTR, LPSTR, LPSTR, DWORD, LPSTR *, LPDWORD ); // // typedef virtual close function // typedef BOOL (*CLOSE_HANDLE_FUNC)(HINTERNET); typedef BOOL (*CONNECT_CLOSE_HANDLE_FUNC)(HINTERNET, DWORD); // // forward references // class ICSocket; // // class implementations // /*++ Class Description: This is generic HINTERNET class definition. Private Member functions: None. Public Member functions: IsValid : Validates handle pointer. GetStatus : Gets status of the object. GetInternetHandle : Virtual function that gets the internet handle value form the generic object handle. GetHandle : Virtual function that gets the service handle value from the generic object handle. --*/ class HANDLE_OBJECT { private: // // _List - doubly-linked list of all handle objects // LIST_ENTRY _List; // // _Children - serialized list of all child handle objects // SERIALIZED_LIST _Children; // // _Siblings - doubly-linked list of all handle objects at the current level // and descended from a particular parent - e.g. all InternetConnect handles // belonging to InternetOpen handle. Linked to the parent's _Children list // LIST_ENTRY _Siblings; // // _Parent - this member has the address of the parent object. Mainly used // when we create an INTERNET_CONNECT_HANDLE_OBJECT on behalf of the object // created with InternetOpenUrl(). // We also need this field to locate the INTERNET_CONNECT_HANDLE_OBJECT that // is the parent of a HTTP request object: if the caller requests Keep-Alive // then the parent INTERNET_CONNECT_HANDLE_OBJECT will have the socket that // we must use // HANDLE_OBJECT* _Parent; // // _DeleteWithChild - used in conjunction with _Parent. In the case of an // INTERNET_CONNECT_HANDLE_OBJECT created on behalf of a HTTP, gopher or // FTP object created by InternetOpenUrl(), we need to delete the parent // handle when the child is closed via InternetCloseHandle(). If we don't // do this then the connect handle object will be orphaned (i.e. we will // have a memory leak) // // // BUGBUG - combine into bitfield // BOOL _DeleteWithChild; // // _Handle - the non-address pseudo-handle value returned at the API // HINTERNET _Handle; // // _ObjectType - type of handle object (mainly for debug purposes) // HINTERNET_HANDLE_TYPE _ObjectType; // // _ReferenceCount - number of references of this object. Used to protect // object against multi-threaded operations and can be used to delete // object when count is decremented to 0 // LONG _ReferenceCount; // // _Invalid - when this is TRUE the handle has been closed although it may // still be alive. The app cannot perform any further actions on this // handle object - it will soon be destroyed // // // BUGBUG - combine into bitfield // BOOL _Invalid; // // _Error - optionally set when invalidating the handle. If set (non-zero) // then this is the preferred error to return from an invalidated request // DWORD _Error; // // _Signature - used to perform sanity test of object // DWORD _Signature; protected: // // _Context - the context value specified in the API that created this // object. This member is inherited by all derived objects // DWORD_PTR _Context; // // _Status - used to store return codes whilst creating the object. If not // ERROR_SUCCESS when new() returns, the object is deleted // DWORD _Status; public: HANDLE_OBJECT( HANDLE_OBJECT * Parent ); virtual ~HANDLE_OBJECT( VOID ); DWORD Reference( VOID ); BOOL Dereference( VOID ); VOID Invalidate(VOID) { // // just mark the object as invalidated // DEBUG_PRINT(THRDINFO, INFO, ("HANDLE_OBJECT[%#x]::Invalidate()\n", this )); _Invalid = TRUE; } BOOL IsInvalidated(VOID) const { DEBUG_PRINT(THRDINFO, INFO, ("HANDLE_OBJECT[%#x]::IsInvalidated() returning %B\n", this, _Invalid )); return _Invalid; } VOID InvalidateWithError(DWORD dwError) { _Error = dwError; Invalidate(); } DWORD GetError(VOID) const { return _Error; } DWORD ReferenceCount(VOID) const { return _ReferenceCount; } VOID AddChild(PLIST_ENTRY Child) { DEBUG_ENTER((DBG_OBJECTS, None, "AddChild", "%#x", Child )); InsertAtTailOfSerializedList(&_Children, Child); // // each time we add a child object, we increase the reference count, and // correspondingly decrease it when we remove the child. This stops us // leaving orphaned child objects // Reference(); DEBUG_LEAVE(0); } VOID RemoveChild(PLIST_ENTRY Child) { DEBUG_ENTER((DBG_OBJECTS, None, "RemoveChild", "%#x", Child )); RemoveFromSerializedList(&_Children, Child); INET_DEBUG_ASSERT((Child->Flink == NULL) && (Child->Blink == NULL)); // // if this object was previously invalidated but could not be deleted // in case we orphaned child objects, then this dereference is going to // close this object // Dereference(); DEBUG_LEAVE(0); } BOOL HaveChildren(VOID) { return IsSerializedListEmpty(&_Children) ? FALSE : TRUE; } HINTERNET NextChild(VOID) { PLIST_ENTRY link = HeadOfSerializedList(&_Children); INET_ASSERT(link != (PLIST_ENTRY)&_Children.List.Flink); // // link points at _Siblings.Flink in the child object // HANDLE_OBJECT * pHandle; pHandle = CONTAINING_RECORD(link, HANDLE_OBJECT, _Siblings.Flink); // // return the pseudo handle of the child object // return pHandle->GetPseudoHandle(); } HINTERNET GetPseudoHandle(VOID) { return _Handle; } DWORD_PTR GetContext(VOID) { return _Context; } // // BUGBUG - rfirth 04/05/96 - remove virtual functions // // See similar BUGBUG in INTERNET_HANDLE_OBJECT // virtual HINTERNET GetInternetHandle(VOID) { return INET_INVALID_HANDLE_VALUE; } virtual HINTERNET GetHandle(VOID) { return INET_INVALID_HANDLE_VALUE; } virtual HINTERNET_HANDLE_TYPE GetHandleType(VOID) { return TypeGenericHandle; } virtual VOID SetHtml(VOID) { } virtual VOID SetHtmlState(HTML_STATE) { } virtual HTML_STATE GetHtmlState(VOID) { return HTML_STATE_INVALID; } virtual LPSTR GetUrl(VOID) { return NULL; } virtual VOID SetUrl(LPSTR Url) { UNREFERENCED_PARAMETER(Url); } virtual VOID SetDirEntry(LPSTR DirEntry) { UNREFERENCED_PARAMETER(DirEntry); } virtual LPSTR GetDirEntry(VOID) { return NULL; } DWORD IsValid(HINTERNET_HANDLE_TYPE ExpectedHandleType); DWORD GetStatus(VOID) { return _Status; } VOID SetParent(HINTERNET Handle, BOOL DeleteWithChild) { _Parent = (HANDLE_OBJECT *)Handle; _DeleteWithChild = DeleteWithChild; } HINTERNET GetParent() { return _Parent; } BOOL GetDeleteWithChild(VOID) { return _DeleteWithChild; } VOID SetObjectType(HINTERNET_HANDLE_TYPE Type) { _ObjectType = Type; } HINTERNET_HANDLE_TYPE GetObjectType(VOID) const { return _ObjectType; } void OnLastHandleDestroyed (void) { HttpFiltClose(); } virtual VOID AbortSocket(VOID) { } // // friend functions // // // these friend functions are here so that they can get access to _List for // CONTAINING_RECORD() // friend HINTERNET FindExistingConnectObject( IN HINTERNET hInternet, IN LPSTR lpHostName, IN INTERNET_PORT nPort, IN LPSTR lpszUserName, IN LPSTR lpszPassword, IN DWORD dwServiceType, IN DWORD dwFlags, IN DWORD_PTR dwContext ); friend INT FlushExistingConnectObjects( IN HINTERNET hInternet ); friend HANDLE_OBJECT * ContainingHandleObject( IN LPVOID lpAddress ); }; // The following enables unicode-receiving callbacks. VOID UnicodeStatusCallbackWrapper(IN HINTERNET hInternet, IN DWORD_PTR dwContext, IN DWORD dwInternetStatus, IN LPVOID lpvStatusInformation OPTIONAL, IN DWORD dwStatusInformationLength ); /*++ Class Description: This class defines the INTERNET_HANDLE_OBJECT. Private Member functions: None. Public Member functions: GetInternetHandle : Virtual function that gets the Internet handle value from the generic object handle. GetHandle : Virtual function that gets the service handle value from the generic object handle. --*/ class INTERNET_HANDLE_OBJECT : public HANDLE_OBJECT { private: BOOL _fExemptConnLimit; BOOL _fDisableTweener; // // Passport Auth package's "Session Handle" // PP_CONTEXT _PPContext; // // _INetHandle - BUGBUG - why is this still here? // // // BUGBUG - post-beta cleanup - remove // HINTERNET _INetHandle; // // _IsCopy - TRUE if this is part of a derived object handle (e.g. a // connect handle object) // // // BUGBUG - post-beta cleanup - combine into bitfield // BOOL _IsCopy; // // _UserAgent - name by why which the application wishes to be known to // HTTP servers. Provides the User-Agent header unless overridden by // specific User-Agent header from app // ICSTRING _UserAgent; // // _ProxyInfo - maintains the proxy server and bypass lists // PROXY_INFO * _ProxyInfo; // // _ProxyInfoResourceLock - must acquire for exclusive access in order to // modify the proxy info // RESOURCE_LOCK _ProxyInfoResourceLock; VOID AcquireProxyInfo(BOOL bExclusiveMode) { INET_ASSERT(!IsCopy()); _ProxyInfoResourceLock.Acquire(bExclusiveMode); } VOID ReleaseProxyInfo(VOID) { INET_ASSERT(!IsCopy()); _ProxyInfoResourceLock.Release(); } VOID SafeDeleteProxyInfo(VOID) { DEBUG_ENTER((DBG_OBJECTS, None, "SafeDeleteProxyInfo", "" )); if (_ProxyInfo != NULL) { AcquireProxyInfo(TRUE); if (!IsProxyGlobal()) { if (_ProxyInfo != NULL) { delete _ProxyInfo; } } _ProxyInfo = NULL; ReleaseProxyInfo(); } DEBUG_LEAVE(0); } // // _dwInternetOpenFlags - flags from InternetOpen() // // BUGBUG - there should only be ONE flags DWORD for all handles descended // from this one. This is it // Rename to just _Flags, or _OpenFlags // DWORD _dwInternetOpenFlags; #ifdef POST_BETA // // _Flags - contains all flags from all handle creation functions. Each // subsequent derived handle just OR's its flags into the base flags // DWORD _Flags; #endif // // _WinsockLoaded - TRUE if we managed to successfully load winsock // // // BUGBUG - post-beta cleanup - combine into bitfield // BOOL _WinsockLoaded; // // _pICSocket - pointer to ICSocket for new HTTP async code // ICSocket * _pICSocket; DWORD _dwBlockedOnError; DWORD _dwBlockedOnResult; LPVOID _lpBlockedResultData; CRITICAL_SECTION _UiCritSec; protected: // // _dwUiBlocked - count of handles blocked on a request waiting to show UI to the User // DWORD _dwUiBlocked; // // _dwBlockId - contains the ID that this handle is blocked on for the purpose of // showing UI to the user. // DWORD_PTR _dwBlockId; // // timout/retry/back-off values. The app can specify timeouts etc. at // various levels: global (DLL), Internet handle (from InternetOpen()) and // Connect handle (from InternetConnect()). The following fields are // inherited by INTERNET_CONNECT_HANDLE_OBJECT (and derived objects) // DWORD _ConnectTimeout; DWORD _ConnectRetries; DWORD _SendTimeout; DWORD _DataSendTimeout; DWORD _ReceiveTimeout; DWORD _DataReceiveTimeout; DWORD _FromCacheTimeout; DWORD _SocketSendBufferLength; DWORD _SocketReceiveBufferLength; // // _Async - TRUE if the InternetOpen() handle, and all handles descended // from it, support asynchronous I/O // // // BUGBUG - post-beta cleanup - get from flags // BOOL _Async; // // _DataAvailable - the number of bytes that can be read from this handle // (i.e. only protocol handles) immediately. This avoids a read request // being made asynchronously if it can be satisfied immediately // DWORD _DataAvailable; // // _EndOfFile - TRUE when we have received all data for this request. This // is used to avoid the API having to perform an extraneous read (possibly // asynchronously) just to discover that we reached end-of-file already // // // BUGBUG - post-beta cleanup - combine into bitfield // BOOL _EndOfFile; // // _StatusCallback - we now maintain callbacks on a per-handle basis. The // callback address comes from the parent handle or the DLL if this is an // InternetOpen() handle. The status callback can be changed for an // individual handle object using the ExchangeStatusCallback() method // (called from InternetSetStatusCallback()) // // // BUGBUG - this should go in HANDLE_OBJECT // INTERNET_STATUS_CALLBACK _StatusCallback; BOOL _StatusCallbackType; // // _PendingAsyncRequests - the number of pending async requests on this // handle object. While this is !0, an app cannot reset the callback // // // BUGBUG - RLF 03/16/98. _PendingAsyncRequests is no longer being modified // since fibers were removed. This count is used for precautionary // measure when changing a status callback on a handle that has // outstanding async requests. I am commenting-out all uses of this // and _AsyncClashTest for B1. Should be fixed or re-examined after // B1 // //LONG _PendingAsyncRequests; // // _AsyncClashTest - used with InterlockedIncrement() to ensure that only // one thread is modifying _PendingAsyncRequests // //LONG _AsyncClashTest; public: INTERNET_HANDLE_OBJECT( LPCSTR UserAgent, DWORD AccessMethod, LPSTR ProxyName, LPSTR ProxyBypass, DWORD Flags ); INTERNET_HANDLE_OBJECT(INTERNET_HANDLE_OBJECT *INetObj); virtual ~INTERNET_HANDLE_OBJECT(VOID); virtual HINTERNET GetInternetHandle(VOID); virtual HINTERNET GetHandle(VOID); void ExemptConnLimit(void) { _fExemptConnLimit = TRUE; } BOOL ConnLimitExempted(void) const { return _fExemptConnLimit; } // // BUGBUG - rfirth 04/05/96 - remove virtual functions // // For the most part, these functions aren't required to be // virtual. They should just be moved to the relevant handle type // (e.g. FTP_FILE_HANDLE_OBJECT). Even GetHandleType() is overkill. // Replacing with a method that just returns // HANDLE_OBJECT::_ObjectType would be sufficient // virtual HINTERNET_HANDLE_TYPE GetHandleType(VOID) { return TypeInternetHandle; } virtual VOID SetHtml(VOID) { } virtual VOID SetHtmlState(HTML_STATE) { } virtual HTML_STATE GetHtmlState(VOID) { return HTML_STATE_INVALID; } virtual LPSTR GetUrl(VOID) { return NULL; } virtual VOID SetUrl(LPSTR Url) { if (Url != NULL) { Url = (LPSTR)FREE_MEMORY(Url); INET_ASSERT(Url == NULL); } } virtual VOID SetDirEntry(LPSTR DirEntry) { UNREFERENCED_PARAMETER(DirEntry); } virtual LPSTR GetDirEntry(VOID) { return NULL; } PP_CONTEXT GetPPContext(void) const { return _PPContext; } void DisableTweener(void) { _fDisableTweener = TRUE; } void EnableTweener(void) { _fDisableTweener = FALSE; } BOOL TweenerDisabled(void) const { return _fDisableTweener; } BOOL IsCopy(VOID) const { return _IsCopy; } VOID LockPopupInfo(VOID) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::LockPopupInfo()\n", this )); EnterCriticalSection(&_UiCritSec); } VOID UnlockPopupInfo(VOID) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::UnlockPopupInfo()\n", this )); LeaveCriticalSection(&_UiCritSec); } VOID BlockOnUserInput(DWORD dwError, DWORD_PTR dwBlockId, LPVOID lpResultData) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::BlockOnUserInput(dwBlockId=%#x), _dwUiBlocked=%u\n", this, dwBlockId, _dwUiBlocked )); INET_ASSERT(!_dwUiBlocked); _dwBlockedOnError = dwError; _dwBlockedOnResult = ERROR_SUCCESS; _dwBlockId = dwBlockId; _lpBlockedResultData = lpResultData; _dwUiBlocked++; } VOID UnBlockOnUserInput(LPDWORD lpdwResultCode, LPVOID *lplpResultData) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::UnBlockOnUserInput() _dwBlockedOnResult=%u, _dwUiBlocked=%u\n", this, _dwBlockedOnResult, _dwUiBlocked )); INET_ASSERT(_dwUiBlocked); _dwUiBlocked--; *lpdwResultCode = _dwBlockedOnResult; *lplpResultData = _lpBlockedResultData; } VOID SetBlockedResultCode(DWORD dwResultCode) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::SetBlockedResultCode(result = %u)\n", this, dwResultCode )); INET_ASSERT(_dwUiBlocked); _dwBlockedOnResult = dwResultCode; } BOOL IsBlockedOnUserInput(VOID) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::IsBlockedOnUserInput() = %B\n", this, _dwUiBlocked )); return (BOOL) _dwUiBlocked; } VOID IncrementBlockedUiCount(VOID) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::IncrementBlockedUiCount()+1 = %u\n", this, (_dwUiBlocked+1) )); _dwUiBlocked++; } DWORD GetBlockedUiCount(VOID) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::GetBlockedUiCount() = %u\n", this, _dwUiBlocked )); INET_ASSERT(_dwUiBlocked); return _dwUiBlocked; } VOID ClearBlockedUiCount(VOID) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::ClearBlockedUiCount()\n", this )); INET_ASSERT(_dwUiBlocked); _dwUiBlocked = 0; } DWORD_PTR GetBlockId(VOID) { DEBUG_PRINT(THRDINFO, INFO, ("INTERNET_HANDLE_OBJECT[%#x]::GetBlockId() = %u\n", this, _dwBlockId )); INET_ASSERT(_dwUiBlocked); return _dwBlockId; } VOID GetUserAgent(LPSTR Buffer, LPDWORD BufferLength) { _UserAgent.CopyTo(Buffer, BufferLength); } LPSTR GetUserAgent(VOID) { return _UserAgent.StringAddress(); } LPSTR GetUserAgent(LPDWORD lpdwLength) { *lpdwLength = _UserAgent.StringLength(); return _UserAgent.StringAddress(); } VOID SetUserAgent(LPSTR lpszUserAgent) { INET_ASSERT(lpszUserAgent != NULL); _UserAgent = lpszUserAgent; } BOOL IsProxy(VOID) const { // // we can return this info without acquiring the critical section // return (_ProxyInfo != NULL) ? _ProxyInfo->IsProxySettingsConfigured() : FALSE; } BOOL IsProxyGlobal(VOID) const { return (_ProxyInfo == &GlobalProxyInfo) ? TRUE : FALSE; } VOID CheckGlobalProxyUpdated( VOID ); PROXY_INFO * GetProxyInfo(VOID) const { INET_ASSERT(!IsCopy()); return _ProxyInfo; } VOID SetProxyInfo(PROXY_INFO * ProxyInfo) { INET_ASSERT(!IsCopy()); _ProxyInfo = ProxyInfo; } VOID ResetProxyInfo(VOID) { INET_ASSERT(!IsCopy()); SetProxyInfo(NULL); } DWORD Refresh( IN DWORD dwInfoLevel ); DWORD SetProxyInfo( IN DWORD dwAccessType, IN LPCSTR lpszProxy OPTIONAL, IN LPCSTR lpszProxyBypass OPTIONAL ); DWORD GetProxyStringInfo( OUT LPVOID lpBuffer, IN OUT LPDWORD lpdwBufferLength ); DWORD GetProxyInfo( IN AUTO_PROXY_ASYNC_MSG **ppQueryForProxyInfo ); BOOL RedoSendRequest( IN OUT LPDWORD lpdwError, IN AUTO_PROXY_ASYNC_MSG *pQueryForProxyInfo, IN CServerInfo *pOriginServer, IN CServerInfo *pProxyServer ); VOID SetContext(DWORD_PTR NewContext) { _Context = NewContext; } VOID SetTimeout(DWORD TimeoutOption, DWORD TimeoutValue); DWORD GetTimeout(DWORD TimeoutOption); BOOL IsAsyncHandle(VOID) { return _Async; } VOID ResetAsync(VOID) { _Async = FALSE; } VOID SetAvailableDataLength(DWORD Amount) { INET_ASSERT((int)Amount >= 0); _DataAvailable = Amount; } DWORD AvailableDataLength(VOID) const { INET_ASSERT((int)_DataAvailable >= 0); return _DataAvailable; } BOOL IsDataAvailable(VOID) { INET_ASSERT((int)_DataAvailable >= 0); return (_DataAvailable != 0) ? TRUE : FALSE; } VOID ReduceAvailableDataLength(DWORD Amount) { // // why would Amount be > _DataAvailable? // if (Amount > _DataAvailable) { _DataAvailable = 0; } else { _DataAvailable -= Amount; } INET_ASSERT((int)_DataAvailable >= 0); } VOID IncreaseAvailableDataLength(DWORD Amount) { _DataAvailable += Amount; INET_ASSERT((int)_DataAvailable >= 0); } VOID SetEndOfFile(VOID) { _EndOfFile = TRUE; } VOID ResetEndOfFile(VOID) { _EndOfFile = FALSE; } BOOL IsEndOfFile(VOID) const { return _EndOfFile; } INTERNET_STATUS_CALLBACK GetStatusCallback(VOID) { return ((_StatusCallbackType==FALSE) ? _StatusCallback : UnicodeStatusCallbackWrapper); } INTERNET_STATUS_CALLBACK GetTrueStatusCallback(VOID) { return ((_StatusCallbackType==FALSE) ? NULL : _StatusCallback); } VOID ResetStatusCallback(VOID) { _StatusCallback = NULL; _StatusCallbackType = FALSE; } //VOID AcquireAsyncSpinLock(VOID); // //VOID ReleaseAsyncSpinLock(VOID); DWORD ExchangeStatusCallback(LPINTERNET_STATUS_CALLBACK lpStatusCallback, BOOL fType); //DWORD AddAsyncRequest(BOOL fNoCallbackOK); // //VOID RemoveAsyncRequest(VOID); // //DWORD GetAsyncRequestCount(VOID) { // // // // // it doesn't matter about locking this variable - it can change before // // we have returned it to the caller anyway // // // // return _PendingAsyncRequests; //} // random methods on flags DWORD GetInternetOpenFlags() { return _dwInternetOpenFlags; } #ifdef POST_BETA DWORD GetFlags(VOID) const { return _Flags; } VOID SetFlags(DWORD Flags) { _Flags |= Flags; } VOID ResetFlags(DWORD Flags) { _Flags &= ~Flags; } #endif VOID SetAbortHandle( IN ICSocket * pSocket ); ICSocket * GetAbortHandle(VOID) const { return _pICSocket; } VOID ResetAbortHandle( VOID ); virtual VOID AbortSocket( VOID ); DWORD CheckAutoProxyDownloaded(VOID) { DWORD error = ERROR_SUCCESS; if (IsProxyGlobal()) { AcquireProxyInfo(FALSE); if (! GlobalProxyInfo.IsAutoProxyDownloaded()) { error = GlobalProxyInfo.RefreshProxySettings(TRUE); } ReleaseProxyInfo(); } return error; } BOOL IsFromCacheTimeoutSet(VOID) const { return _FromCacheTimeout != (DWORD)-1; } }; // // prototypes // HANDLE_OBJECT * ContainingHandleObject( IN LPVOID lpAddress ); VOID CancelActiveSyncRequests( IN DWORD dwError ); #endif // _HINET_
23.151391
115
0.571878
[ "object" ]
1101651a81e27e907175e792002bb06b36cd699e
6,530
cpp
C++
examples/algorithms/writing_new/collect_indexes__writing_custom_loop.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
examples/algorithms/writing_new/collect_indexes__writing_custom_loop.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
examples/algorithms/writing_new/collect_indexes__writing_custom_loop.cpp
the-moisrex/eve
80b52663eefee11460abb0aedf4158a5067cf7dc
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== // // In this example we will have a look at the same problem as in writing_new/collect_indexes__complicated_real_example // but we will write a loop instead of using a zip with iota because it's usefult to understand. // #include <eve/algo/concepts.hpp> #include <eve/algo/preprocess_range.hpp> #include <eve/function/compress_store.hpp> #include <eve/function/load.hpp> #include <concepts> #include <type_traits> #include <vector> template < eve::algo::relaxed_range R, // relaxed_range is our version of the std::range // concept that supports things like aligned pointers, zip, etc. // --- typename P, // Predicate. Don't conceptify, since it's quite difficult (see below) // and does not seem that useful. // --- std::integral IdxType, // Index type, should be big enough to store any element's position // --- typename Alloc // To not have to deal with allocators ourselves, // We'll just allow you to pass a vector with any allocator. > void collect_indexes(R&& r, P p, std::vector<IdxType, Alloc>& res) { EVE_ASSERT((static_cast<std::size_t>(r.end() - r.begin()) <= std::numeric_limits<IdxType>::max()), "The output type is not big enough to hold potential indexes"); // Prepare the output in case it was not empty. res.clear(); // We have to do this everywhere in `algo`. // There is a requirement for `eve::load` that the pointer/iterator is to // somewheere in valid memory, even if we ignore everything. if (r.begin() == r.end()) return; // This converts the input to eve's understanding of a range: // unwraps vector::iterator to pointers, things like that. // This is also where all of our dealing with traits happen, // passing `consider_types<IdxType>` will make sure that we choose the cardinal (width) // appropriate for both range type and index type. auto processed = eve::algo::preprocess_range( eve::algo::traits{eve::algo::consider_types<IdxType>}, std::forward<R>(r) ); // Here we would normally use `for_each_iteration` but it's good to understand what's // happening inside. auto f = processed.begin(); auto l = processed.end(); using I = decltype(f); using N = eve::algo::iterator_cardinal_t<I>; // ^ Because this is the first place where we get the cardinal, // we couldn't specify the requirement on the predicate auto precise_l = f + ((l - f) / N{}()) * N{}(); // We are going to overallocate the output so that we can don't // have to store partial registers. res.resize(l - f + N{}()); IdxType* out = res.data(); // In a normal loop this would be i from for (i = 0; i != ...) // The lambda constructor will fill in (0, 1, 2, ...); eve::wide<IdxType, N> wide_i{[](int i, int) { return i; }}; while (f != precise_l) { auto test = p(eve::load(f)); // apply the predicate // Compress store is the working horse of `remove`. It get's values, mask and where to store. // Writes all of the elements, for which mask is true. // Returns a pointer to after the last stored. // `unsafe` refers to the fact that it's allowed to store up to the whole register, // as long as the first elements are fine. out = eve::unsafe(eve::compress_store)(wide_i, test, out); wide_i += N{}(); // ++i f += N{}(); // ++f } // Deal with tail if (f != l) { auto ignore = eve::keep_first(l - f); // elements after l should not be touched auto test = p(eve::load[ignore](f)); // This will safely load the partial register. // The last elements that correspond to after l will be garbage. // We have overallocated the output, but we still need to mask out garbage elements test = test && ignore.mask(eve::as(test)); out = eve::unsafe(eve::compress_store)(wide_i, test, out); } // Clean up the vector res.resize(out - res.data()); res.shrink_to_fit(); } // --------------------------------------------------- #include "test.hpp" #include <eve/algo/container/soa_vector.hpp> #include <eve/memory/aligned_allocator.hpp> #include "unit/algo/algo_test.hpp" TTS_CASE("collect_indexes, elements equal to 2") { std::vector<int> input = { 1, 1, 2, -3, 2, 10}; std::vector<unsigned> expected = { 2, 4 }; std::vector<unsigned> actual; collect_indexes(input, [](auto x) { return x == 2; }, actual); TTS_EQUAL(expected, actual); }; TTS_CASE("collect_indexes for objects") { using obj = kumi::tuple<int, double>; eve::algo::soa_vector<obj> objects {obj{1, 2.0}, obj{-1, 2.0}, obj{1, 1}}; std::vector<std::uint16_t> expected{0, 2}; std::vector<std::uint16_t> idxs; collect_indexes(objects, [](auto x) { return get<0>(x) > 0; }, idxs); TTS_EQUAL(idxs, expected); }; TTS_CASE("collect_indexes clears the result") { std::vector<int> input; std::vector<unsigned> expected; std::vector<unsigned> actual(65u); collect_indexes(input, [](auto x) { return x == 2; }, actual); TTS_EQUAL(expected, actual); }; // --------------- // push data through test struct collect_indexes_generic_test { std::vector<std::int64_t> expected; void init(auto*, auto* f, auto* l, auto*) { int count = 0; while (f != l) { if (count % 3 == 0) *f = 1; else *f = 0; ++f; } } void run(auto rng) { expected.clear(); for (auto* f = eve::algo::unalign(rng.begin()); f != rng.end(); ++f) { if (*f == 1) expected.push_back(f - rng.begin()); } std::vector<std::int64_t> actual; collect_indexes(rng, [](auto x) { return x == 1; }, actual); TTS_EQUAL(expected, actual); } void adjust(auto*, auto* f, auto* l, auto* page_end) const { *f = 1; if (l != page_end) *l = 1; } }; EVE_TEST_TYPES("Check collect indexes, lots", eve::test::scalar::all_types) <typename T>(eve::as<T>) { using tgt_t = eve::wide<T, eve::fixed<eve::expected_cardinal_v<std::int64_t>>>; algo_test::page_ends_test(eve::as<tgt_t>{}, collect_indexes_generic_test{}); };
34.188482
118
0.599694
[ "vector" ]
1108740980f2f73669641df435e2baadf0177462
6,783
cc
C++
src/kml/engine/location_util.cc
HellFighter/libkml
916a801ed3143ab82c07ec108bad271aa441da16
[ "BSD-3-Clause" ]
39
2015-04-02T06:29:58.000Z
2022-02-14T14:14:09.000Z
src/kml/engine/location_util.cc
HellFighter/libkml
916a801ed3143ab82c07ec108bad271aa441da16
[ "BSD-3-Clause" ]
116
2015-04-04T20:39:20.000Z
2022-02-15T12:05:00.000Z
src/kml/engine/location_util.cc
HellFighter/libkml
916a801ed3143ab82c07ec108bad271aa441da16
[ "BSD-3-Clause" ]
39
2015-04-04T21:49:00.000Z
2022-03-19T23:37:36.000Z
// Copyright 2008, Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // This file contains the implementation of location-related utility functions. #include "kml/engine/location_util.h" #include "kml/dom.h" #include "kml/engine/bbox.h" using kmlbase::Vec3; using kmldom::AbstractLatLonBoxPtr; using kmldom::ContainerPtr; using kmldom::CoordinatesPtr; using kmldom::FeaturePtr; using kmldom::GeometryPtr; using kmldom::LinearRingPtr; using kmldom::LineStringPtr; using kmldom::ModelPtr; using kmldom::MultiGeometryPtr; using kmldom::PhotoOverlayPtr; using kmldom::PlacemarkPtr; using kmldom::PointPtr; using kmldom::PolygonPtr; namespace kmlengine { bool GetCoordinatesBounds(const CoordinatesPtr& coordinates, Bbox* bbox) { if (!coordinates) { return false; } size_t num_coords = coordinates->get_coordinates_array_size(); if (bbox) { for (size_t i = 0; i < num_coords; ++i) { const Vec3& vec3 = coordinates->get_coordinates_array_at(i); bbox->ExpandLatLon(vec3.get_latitude(), vec3.get_longitude()); } } return num_coords != 0; } bool GetFeatureBounds(const FeaturePtr& feature, Bbox* bbox) { if (PlacemarkPtr placemark = kmldom::AsPlacemark(feature)) { return GetGeometryBounds(placemark->get_geometry(), bbox); } else if (PhotoOverlayPtr photooverlay = kmldom::AsPhotoOverlay(feature)) { return GetCoordinatesParentBounds(photooverlay->get_point(), bbox); } else if (ContainerPtr container = kmldom::AsContainer(feature)) { // TODO: unify feature hierarchy walking with public API for such size_t num_features = container->get_feature_array_size(); // for (size_t i = 0; i < num_features; ++num_features) { bool has_bounds = false; // Turns true on any Feature w/ bounds. for (size_t i = 0; i < num_features; ++i) { if (GetFeatureBounds(container->get_feature_array_at(i), bbox)) { has_bounds = true; } } return has_bounds; //} } // TODO: other GroundOverlay return false; } bool GetFeatureLatLon(const FeaturePtr& feature, double* lat, double* lon) { Bbox bbox; if (GetFeatureBounds(feature, &bbox)) { if (lat) { *lat = bbox.GetCenterLat(); } if (lon) { *lon = bbox.GetCenterLon(); } return true; } return false; } bool GetGeometryBounds(const GeometryPtr& geometry, Bbox* bbox) { if (!geometry) { return false; } // TODO: Arguably the bounds of a Geometry includes extrusion... if (PointPtr point = AsPoint(geometry)) { return GetCoordinatesParentBounds(point, bbox); } else if (LineStringPtr linestring = AsLineString(geometry)) { return GetCoordinatesParentBounds(linestring, bbox); } else if (LinearRingPtr linearring = AsLinearRing(geometry)) { return GetCoordinatesParentBounds(linearring, bbox); } else if (PolygonPtr polygon = AsPolygon(geometry)) { return polygon->has_outerboundaryis() && polygon->get_outerboundaryis()->has_linearring() && GetCoordinatesParentBounds( polygon->get_outerboundaryis()->get_linearring(), bbox); } else if (ModelPtr model = AsModel(geometry)) { return GetModelBounds(model, bbox); } else if (MultiGeometryPtr multigeometry = AsMultiGeometry(geometry)) { bool has_bounds = false; // Turns true on any Geometry w/ bounds. size_t size = multigeometry->get_geometry_array_size(); for (size_t i = 0; i < size; ++i) { if (GetGeometryBounds(multigeometry->get_geometry_array_at(i), bbox)) { has_bounds = true; } } return has_bounds; } return false; } bool GetGeometryLatLon(const GeometryPtr& geometry, double* lat, double* lon) { Bbox bbox; if (GetGeometryBounds(geometry, &bbox)) { if (lat) { *lat = bbox.GetCenterLat(); } if (lon) { *lon = bbox.GetCenterLon(); } return true; } return false; } bool GetPlacemarkLatLon(const PlacemarkPtr& placemark, double* lat, double* lon) { return GetGeometryLatLon(placemark->get_geometry(), lat, lon); } bool GetModelBounds(const ModelPtr& model, Bbox* bbox) { double lat, lon; if (GetModelLatLon(model, &lat, &lon)) { if (bbox) { bbox->ExpandLatLon(lat, lon); } return true; } return false; } bool GetModelLatLon(const ModelPtr& model, double* lat, double* lon) { if (model) { if (model->has_location()) { if (lat) { *lat = model->get_location()->get_latitude(); } if (lon) { *lon = model->get_location()->get_longitude(); } return true; } } return false; } bool GetPointLatLon(const PointPtr& point, double* lat, double* lon) { if (point) { if (CoordinatesPtr coordinates = point->get_coordinates()) { if (coordinates->get_coordinates_array_size() > 0) { Vec3 point = coordinates->get_coordinates_array_at(0); if (lat) { *lat = point.get_latitude(); } if (lon) { *lon = point.get_longitude(); } return true; } } } return false; } void GetCenter(const AbstractLatLonBoxPtr& allb, double* lat, double* lon) { if (!allb) { return; } if (lat) { *lat = (allb->get_north() + allb->get_south())/2.0; } if (lon) { *lon = (allb->get_east() + allb->get_west())/2.0; } } } // end namespace kmlengine
32.927184
80
0.682294
[ "geometry", "model" ]
110bdfea330d7c1ceac8b4310eb79a5b19af59ef
59,256
cpp
C++
src/alphabet.cpp
anyks/alm
e168ae3c2be39ff2349e266253dd43f4b237eddd
[ "MIT" ]
40
2020-02-17T19:36:19.000Z
2022-03-04T09:41:54.000Z
src/alphabet.cpp
anyks/alm
e168ae3c2be39ff2349e266253dd43f4b237eddd
[ "MIT" ]
1
2020-08-03T21:25:37.000Z
2020-08-04T22:04:26.000Z
src/alphabet.cpp
anyks/alm
e168ae3c2be39ff2349e266253dd43f4b237eddd
[ "MIT" ]
3
2020-05-22T14:10:59.000Z
2021-04-10T17:24:12.000Z
/** * author: Yuriy Lobarev * telegram: @forman * phone: +7(910)983-95-90 * email: forman@anyks.com * site: https://anyks.com */ #include <alphabet.hpp> // Устанавливаем шаблон функции template <typename T> /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void split(const wstring & str, const wstring & delim, T & v) noexcept { /** * trimFn Метод удаления пробелов вначале и конце текста * @param text текст для удаления пробелов * @return результат работы функции */ function <const wstring (const wstring &)> trimFn = [](const wstring & text) noexcept { // Получаем временный текст wstring tmp = text; // Выполняем удаление пробелов по краям tmp.erase(tmp.begin(), find_if_not(tmp.begin(), tmp.end(), [](wchar_t c){ return iswspace(c); })); tmp.erase(find_if_not(tmp.rbegin(), tmp.rend(), [](wchar_t c){ return iswspace(c); }).base(), tmp.end()); // Выводим результат return tmp; }; // Очищаем словарь v.clear(); // Получаем счётчики перебора size_t i = 0, j = str.find(delim); const size_t len = delim.length(); // Выполняем разбиение строк while(j != wstring::npos){ v.push_back(trimFn(str.substr(i, j - i))); i = ++j + (len - 1); j = str.find(delim, j); if(j == wstring::npos) v.push_back(trimFn(str.substr(i, str.length()))); } // Если слово передано а вектор пустой, тогда создаем вектори из 1-го элемента if(!str.empty() && v.empty()) v.push_back(trimFn(str)); } /** * cbegin Метод итератор начала списка * @return итератор */ const std::set <wchar_t>::const_iterator anyks::Alphabet::cbegin() const noexcept { // Выводим итератор return this->letters.cbegin(); } /** * cend Метод итератор конца списка * @return итератор */ const std::set <wchar_t>::const_iterator anyks::Alphabet::cend() const noexcept { // Выводим итератор return this->letters.cend(); } /** * crbegin Метод обратный итератор начала списка * @return итератор */ const std::set <wchar_t>::const_reverse_iterator anyks::Alphabet::crbegin() const noexcept { // Выводим итератор return this->letters.crbegin(); } /** * crend Метод обратный итератор конца списка * @return итератор */ const std::set <wchar_t>::const_reverse_iterator anyks::Alphabet::crend() const noexcept { // Выводим итератор return this->letters.crend(); } /** * get Метод получения алфавита языка * @return алфавит языка */ const string anyks::Alphabet::get() const noexcept { // Выводим результат return this->convert(this->alphabet); } /** * get Метод получения алфавита языка * @return алфавит языка */ const wstring & anyks::Alphabet::wget() const noexcept { // Выводим результат return this->alphabet; } /** * trim Метод удаления пробелов вначале и конце текста * @param text текст для удаления пробелов * @return результат работы функции */ const string anyks::Alphabet::trim(const string & text) const noexcept { // Получаем временный текст string tmp = text; // Выполняем удаление пробелов по краям tmp.erase(tmp.begin(), find_if_not(tmp.begin(), tmp.end(), [](char c){ return isspace(c); })); tmp.erase(find_if_not(tmp.rbegin(), tmp.rend(), [](char c){ return isspace(c); }).base(), tmp.end()); // Выводим результат return tmp; } /** * toLower Метод перевода русских букв в нижний регистр * @param str строка для перевода * @return строка в нижнем регистре */ const string anyks::Alphabet::toLower(const string & str) const noexcept { // Результат работы функции string result = str; // Если строка передана if(!str.empty()){ // Получаем временную строку wstring tmp = this->convert(result); // Выполняем приведение к нижнему регистру transform(tmp.begin(), tmp.end(), tmp.begin(), [](wchar_t c){ // Приводим к нижнему регистру каждую букву return towlower(c); }); // Конвертируем обратно result = this->convert(tmp); } // Выводим результат return result; } /** * toUpper Метод перевода русских букв в верхний регистр * @param str строка для перевода * @return строка в верхнем регистре */ const string anyks::Alphabet::toUpper(const string & str) const noexcept { // Результат работы функции string result = str; // Если строка передана if(!str.empty()){ // Получаем временную строку wstring tmp = this->convert(result); // Выполняем приведение к верхнему регистру transform(tmp.begin(), tmp.end(), tmp.begin(), [](wchar_t c){ // Приводим к верхнему регистру каждую букву return towupper(c); }); // Конвертируем обратно result = this->convert(tmp); } // Выводим результат return result; } /** * convert Метод конвертирования строки utf-8 в строку * @param str строка utf-8 для конвертирования * @return обычная строка */ const string anyks::Alphabet::convert(const wstring & str) const noexcept { // Результат работы функции string result = ""; // Если строка передана if(!str.empty()){ // Если используется BOOST #ifdef USE_BOOST_CONVERT // Объявляем конвертер using boost::locale::conv::utf_to_utf; // Выполняем конвертирование в utf-8 строку result = utf_to_utf <char> (str.c_str(), str.c_str() + str.size()); // Если нужно использовать стандартную библиотеку #else // Устанавливаем тип для конвертера UTF-8 using convert_type = codecvt_utf8 <wchar_t, 0x10ffff, little_endian>; // Объявляем конвертер wstring_convert <convert_type, wchar_t> conv; // wstring_convert <codecvt_utf8 <wchar_t>> conv; // Выполняем конвертирование в utf-8 строку result = conv.to_bytes(str); #endif } // Выводим результат return result; } /** * format Метод реализации функции формирования форматированной строки * @param format формат строки вывода * @param args передаваемые аргументы * @return сформированная строка */ const string anyks::Alphabet::format(const char * format, ...) const noexcept { // Результат работы функции string result = ""; // Если формат передан if(format != nullptr){ // Создаем список аргументов va_list args; // Создаем буфер char buffer[BUFFER_CHUNK]; // Заполняем буфер нулями memset(buffer, 0, sizeof(buffer)); // Устанавливаем начальный список аргументов va_start(args, format); // Выполняем запись в буфер const size_t size = vsprintf(buffer, format, args); // Завершаем список аргументов va_end(args); // Если размер не нулевой if(size > 0) result.assign(buffer, size); } // Выводим результат return result; } /** * toLower Метод перевода русских букв в нижний регистр * @param str строка для перевода * @return строка в нижнем регистре */ const char anyks::Alphabet::toLower(const char letter) const noexcept { // Результат работы функции char result = 0; // Если строка передана if(letter > 0){ // Строка для конвертации wstring str = L""; // Выполняем конвертирование в utf-8 строку const wchar_t c = this->convert(string{1, letter}).front(); // Формируем новую строку str.assign(1, towlower(c)); // Выполняем конвертирование в utf-8 строку result = this->convert(str).front(); } // Выводим результат return result; } /** * toUpper Метод перевода русских букв в верхний регистр * @param str строка для перевода * @return строка в верхнем регистре */ const char anyks::Alphabet::toUpper(const char letter) const noexcept { // Результат работы функции char result = 0; // Если строка передана if(letter > 0){ // Строка для конвертации wstring str = L""; // Выполняем конвертирование в utf-8 строку const wchar_t c = this->convert(string{1, letter}).front(); // Формируем новую строку str.assign(1, towupper(c)); // Выполняем конвертирование в utf-8 строку result = this->convert(str).front(); } // Выводим результат return result; } /** * toLower Метод перевода русских букв в нижний регистр * @param str строка для перевода * @return строка в нижнем регистре */ const wchar_t anyks::Alphabet::toLower(const wchar_t letter) const noexcept { // Результат работы функции wchar_t result = 0; // Если строка передана if(letter > 0) result = towlower(letter); // Выводим результат return result; } /** * toUpper Метод перевода русских букв в верхний регистр * @param str строка для перевода * @return строка в верхнем регистре */ const wchar_t anyks::Alphabet::toUpper(const wchar_t letter) const noexcept { // Результат работы функции wchar_t result = 0; // Если строка передана if(letter > 0) result = towupper(letter); // Выводим результат return result; } /** * trim Метод удаления пробелов вначале и конце текста * @param text текст для удаления пробелов * @return результат работы функции */ const wstring anyks::Alphabet::trim(const wstring & text) const noexcept { // Получаем временный текст wstring tmp = text; // Выполняем удаление пробелов по краям tmp.erase(tmp.begin(), find_if_not(tmp.begin(), tmp.end(), [this](wchar_t c){ return this->isSpace(c); })); tmp.erase(find_if_not(tmp.rbegin(), tmp.rend(), [this](wchar_t c){ return this->isSpace(c); }).base(), tmp.end()); // Выводим результат return tmp; } /** * convert Метод конвертирования строки в строку utf-8 * @param str строка для конвертирования * @return строка в utf-8 */ const wstring anyks::Alphabet::convert(const string & str) const noexcept { // Результат работы функции wstring result = L""; // Если строка передана if(!str.empty()){ // Если используется BOOST #ifdef USE_BOOST_CONVERT // Объявляем конвертер using boost::locale::conv::utf_to_utf; // Выполняем конвертирование в utf-8 строку result = utf_to_utf <wchar_t> (str.c_str(), str.c_str() + str.size()); // Если нужно использовать стандартную библиотеку #else // Объявляем конвертер // wstring_convert <codecvt_utf8 <wchar_t>> conv; wstring_convert <codecvt_utf8_utf16 <wchar_t, 0x10ffff, little_endian>> conv; // Выполняем конвертирование в utf-8 строку result = conv.from_bytes(str); #endif } // Выводим результат return result; } /** * toLower Метод перевода русских букв в нижний регистр * @param str строка для перевода * @return строка в нижнем регистре */ const wstring anyks::Alphabet::toLower(const wstring & str) const noexcept { // Результат работы функции wstring result = L""; // Если строка передана if(!str.empty()){ // Переходим по всем буквам слова и формируем новую строку for(auto & c : str) result.append(1, towlower(c)); } // Выводим результат return result; } /** * toUpper Метод перевода русских букв в верхний регистр * @param str строка для перевода * @return строка в верхнем регистре */ const wstring anyks::Alphabet::toUpper(const wstring & str) const noexcept { // Результат работы функции wstring result = L""; // Если строка передана if(!str.empty()){ // Переходим по всем буквам слова и формируем новую строку for(auto & c : str) result.append(1, towupper(c)); } // Выводим результат return result; } /** * arabic2Roman Метод перевода арабских чисел в римские * @param number арабское число от 1 до 4999 * @return римское число */ const wstring anyks::Alphabet::arabic2Roman(const u_int number) const noexcept { // Результат работы функции wstring result = L""; // Если число передано верное if((number >= 1) && (number <= 4999)){ // Копируем полученное число u_int n = number; // Вычисляем до тысяч result.append(this->numsSymbols.m[floor(n / 1000)]); // Уменьшаем диапазон n %= 1000; // Вычисляем до сотен result.append(this->numsSymbols.c[floor(n / 100)]); // Вычисляем до сотен n %= 100; // Вычисляем до десятых result.append(this->numsSymbols.x[floor(n / 10)]); // Вычисляем до сотен n %= 10; // Формируем окончательный результат result.append(this->numsSymbols.i[n]); } // Выводим результат return result; } /** * arabic2Roman Метод перевода арабских чисел в римские * @param word арабское число от 1 до 4999 * @return римское число */ const wstring anyks::Alphabet::arabic2Roman(const wstring & word) const noexcept { // Результат работы функции wstring result = L""; // Если слово передано if(!word.empty()){ // Преобразуем слово в число const u_int number = stoi(word); // Выполняем расчет result.assign(this->arabic2Roman(number)); } // Выводим результат return result; } /** * delPunctInWord Метод очистки текста от всех знаков препинаний * @param word слово для очистки * @return текст без запрещенных символов */ const wstring anyks::Alphabet::delPunctInWord(const wstring & word) const noexcept { // Результат работы функции wstring result = L""; // Если строка передана if(!word.empty()){ // Выполняем копирование строки result.assign(word); // Выполняем удаление всех знаков препинания result.erase(remove_if(result.begin(), result.end(), [this](const wchar_t c) noexcept { // Если это буква или цифра или дефис return ((this->allowedSymbols.count(c) < 1) && (c != L'\r') && (c != L'\n') && !iswalnum(c) && !iswspace(c)); }), result.end()); } // Выводим результат return result; } /** * delBrokenInWord Метод очистки текста от всех символов кроме разрешенных * @param word слово для очистки * @return текст без запрещенных символов */ const wstring anyks::Alphabet::delBrokenInWord(const wstring & word) const noexcept { // Результат работы функции wstring result = L""; // Если строка передана if(!word.empty()){ // Выполняем копирование строки result.assign(word); // Выполняем удаление всех знаков препинания result.erase(remove_if(result.begin(), result.end(), [this](const wchar_t c) noexcept { // Выполняем конвертацию символа const wchar_t letter = towlower(c); // Если это буква или цифра или дефис return ( (this->allowedSymbols.count(letter) < 1) && (letter != L'\r') && (letter != L'\n') && !iswspace(letter) && !this->check(letter) ); }), result.end()); } // Выводим результат return result; } /** * delHyphenInWord Метод удаления дефиса из слова * @param word слово в котором нужно удалить дефис * @return слово без дефиса */ const wstring anyks::Alphabet::delHyphenInWord(const wstring & word) const noexcept { // Результат работы функции wstring result = L""; // Если слово передано if(!word.empty()){ // Позиция пробела в слове size_t pos = 0; // Выполняем копирование строки result.assign(word); // Если дефис не найден тогда вывадим слово как оно есть while((pos = result.find(L"-", pos)) != wstring::npos){ // Выполняем удалени дефиса result.replace(pos, 1, L""); // Увеличиваем позицию pos++; } } // Выводим результат return result; } /** * replace Метод замены в тексте слово на другое слово * @param text текст в котором нужно произвести замену * @param word слово для поиска * @param alt слово на которое нужно произвести замену * @return результирующий текст */ const wstring anyks::Alphabet::replace(const wstring & text, const wstring & word, const wstring & alt) const noexcept { // Результат работы функции wstring result = move(text); // Если текст передан и искомое слово не равно слову для замены if(!result.empty() && !word.empty() && (word.compare(alt) != 0)){ // Позиция искомого текста size_t pos = 0; // Определяем текст на который нужно произвести замену const wstring & alternative = (!alt.empty() ? alt : L""); // Выполняем поиск всех слов while((pos = result.find(word, pos)) != wstring::npos){ // Выполняем замену текста result.replace(pos, word.length(), alternative); // Смещаем позицию на единицу pos++; } } // Выводим результат return result; } /** * errors Метод подсчета максимально-возможного количества ошибок в слове * @param word слово для расчёта * @return результат расчёта */ const u_short anyks::Alphabet::errors(const wstring & word) const noexcept { // Результат работы функции u_short result = 0; // Если слово передано if(!word.empty()){ // Получаем длину слова const size_t length = word.length(); // Выполняем расчёт количества ошибок разрешённых для данного слова result = (length >= 9 ? 4 : (length > 6 ? 3 : (length > 4 ? 2 : (length > 1 ? 1 : 0)))); } // Выводим результат return result; } /** * roman2Arabic Метод перевода римских цифр в арабские * @param word римское число * @return арабское число */ const u_short anyks::Alphabet::roman2Arabic(const wstring & word) const noexcept { // Результат работы функции u_short result = 0; // Если слово передано if(!word.empty()){ // Символ поиска wchar_t c, o; // Вспомогательные переменные u_int i = 0, v = 0, n = 0; // Получаем длину слова const size_t length = word.length(); // Если слово состоит всего из одной буквы if((length == 1) && (this->numsSymbols.roman.count(word.front()) < 1)) return result; // Если слово длиннее одной буквы else { // Переходим по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Проверяем является ли слово римским числом if(!(i == j ? (this->numsSymbols.roman.count(word.at(i)) > 0) : (this->numsSymbols.roman.count(word.at(i)) > 0) && (this->numsSymbols.roman.count(word.at(j)) > 0) )) return result; } } // Преобразовываем цифру M if(word.front() == L'm'){ for(n = 0; word[i] == L'm'; n++) i++; if(n > 4) return 0; v += n * 1000; } o = word[i]; // Преобразовываем букву D и C if((o == L'd') || (o == L'c')){ if((c = o) == L'd'){ i++; v += 500; } o = word[i + 1]; if((c == L'c') && (o == L'm')){ i += 2; v += 900; } else if((c == L'c') && (o == L'd')) { i += 2; v += 400; } else { for(n = 0; word[i] == L'c'; n++) i++; if(n > 4) return 0; v += n * 100; } } o = word[i]; // Преобразовываем букву L и X if((o == L'l') || (o == L'x')){ if((c = o) == L'l'){ i++; v += 50; } o = word[i + 1]; if((c == L'x') && (o == L'c')){ i += 2; v += 90; } else if((c == L'x') && (o == L'l')) { i += 2; v += 40; } else { for(n = 0; word[i] == L'x'; n++) i++; if(n > 4) return 0; v += n * 10; } } o = word[i]; // Преобразовываем букву V и I if((o == L'v') || (o == L'i')){ if((c = o) == L'v'){ i++; v += 5; } o = word[i + 1]; if((c == L'i') && (o == L'x')){ i += 2; v += 9; } else if((c == L'i') && (o == L'v')){ i += 2; v += 4; } else { for(n = 0; word[i] == L'i'; n++) i++; if(n > 4) return 0; v += n; } } // Формируем реузльтат result = (((word.length() == i) && (v >= 1) && (v <= 4999)) ? v : 0); } // Выводим результат return result; } /** * count Метод получения количества букв в словаре * @return количество букв в словаре */ const size_t anyks::Alphabet::count() const noexcept { // Выводим результат return this->letters.size(); } /** * setCase Метод запоминания регистра слова * @param pos позиция для установки регистра * @param cur текущее значение регистра в бинарном виде * @return позиция верхнего регистра в бинарном виде */ const size_t anyks::Alphabet::setCase(const size_t pos, const size_t cur) const noexcept { // Результат работы функции size_t result = cur; // Если позиция передана и длина слова тоже result += (1 << pos); // Выводим результат return result; } /** * countLetter Метод подсчета количества указанной буквы в слове * @param word слово в котором нужно подсчитать букву * @param letter букву которую нужно подсчитать * @return результат подсчёта */ const size_t anyks::Alphabet::countLetter(const wstring & word, const wchar_t letter) const noexcept { // Результат работы функции size_t result = 0; // Если слово и буква переданы if(!word.empty() && (letter > 0)){ // Ищем нашу букву size_t pos = 0; // Выполняем подсчет количества указанных букв в слове while((pos = word.find(letter, pos)) != wstring::npos){ // Считаем количество букв result++; // Увеличиваем позицию pos++; } } // Выводим результат return result; } /** * isAllowApostrophe Метод проверки разрешения апострофа * @return результат проверки */ const bool anyks::Alphabet::isAllowApostrophe() const noexcept { // Выводим результат проверки апострофа return this->apostrophe; } /** * isUrl Метод проверки соответствия слова url адресу * @param word слово для проверки * @return результат проверки */ const bool anyks::Alphabet::isUrl(const wstring & word) const noexcept { // Результат работы функции bool result = false; // Если слово передано if(!word.empty()){ // Выполняем парсинг uri адреса auto resUri = this->uri.parse(word); // Если ссылка найдена result = ((resUri.type != uri_t::types_t::null) && (resUri.type != uri_t::types_t::wrong)); } // Выводим результат return result; } /** * isMath Метод определения математических операий * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isMath(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Если слово передано if(letter > 0) result = ((this->letters.count(letter) < 1) && (this->mathSymbols.count(letter) > 0)); // Выводим результат return result; } /** * isAbbr Метод проверки слова на соответствие аббревиатуры * @param word слово для проверки * @return результат проверки */ const bool anyks::Alphabet::isAbbr(const wstring & word) const noexcept { // Результат работы функции bool result = false; // Если слово передано if(!word.empty() && (word.length() > 1) && (word.front() != L'-') && (word.back() != L'-')){ // Позиция пробела size_t pos = wstring::npos; // Ищем дефис в слове if((pos = word.find(L'-')) != wstring::npos){ // Если первая часть является числом if(this->isNumber(word.substr(0, pos))){ /** * isAllowedFn Метод проверки соответствия слова словарю * @param word слово для проверки * @return результат проверки */ auto isAllowedFn = [this](const wstring & word) noexcept { // Результат работы функции bool result = false; // Если слово передано if(!word.empty()){ // Длина слова const size_t length = word.length(); // Переводим слово в нижний регистр const wstring & tmp = this->toLower(word); // Если строка длиннее 1-го символа if(length > 1){ // Текущая буква wchar_t letter = 0; // Выполняем переход по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Получаем текущую букву letter = tmp.at(i); // Проверяем соответствует ли буква result = (this->letters.count(letter) > 0); // Проверяем вторую букву в слове if(result && (i != j)){ // Получаем текущую букву letter = tmp.at(j); // Проверяем соответствует ли буква result = (this->letters.count(letter) > 0); } // Если буква не соответствует, выходим if(!result) break; } // Если строка всего из одного символа } else result = (this->letters.count(tmp.front()) > 0); } // Выводим результат return result; }; // Получаем суффикс const wstring & suffix = this->toLower(word.substr(pos + 1)); // Если суффикс не является числом result = (!this->isNumber(suffix) && isAllowedFn(suffix)); } // Если это не дефис } else { // Переводим слово в нижний регистр const wstring & tmp = this->toLower(word); // Если первый символ является разрешённым if(this->letters.count(tmp.front()) > 0){ // Флаг найденой точки bool point = false; // Длина слова до точки u_short length = 1; // Текущая буква в слове wchar_t letter = 0; // Выполняем переход по всему слову for(size_t i = 1; i < tmp.length(); i++){ // Получаем текущую букву слова letter = tmp.at(i); // Если это не точка if((result = (letter == L'.'))){ // Сбрасываем длину слова length = 0; // Запоминаем что точка найдена point = true; // Если слово не прошло проверку } else if((length > 3) || (this->letters.count(letter) < 1)) { // Запоминаем, что результат не получен result = false; // Выходим из цикла break; // Увеличиваем количество обработанных букв } else if((result = true)) length++; } // Если точка не найдена, сбрасываем результат if(!point) result = false; } } } // Выводим результат return result; } /** * isUpper Метод проверки символ на верхний регистр * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isUpper(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Если слово передано if(letter > 0){ // Если код символа не изменился, значит регистр верхний result = (wint_t(letter) == towupper(letter)); } // Выводим результат return result; } /** * isLatian Метод проверки является ли строка латиницей * @param str строка для проверки * @return результат проверки */ const bool anyks::Alphabet::isLatian(const wstring & str) const noexcept { // Результат работы функции bool result = false; // Если строка передана if(!str.empty()){ // Длина слова const size_t length = str.length(); // Переводим слово в нижний регистр const wstring & tmp = this->toLower(str); // Если длина слова больше 1-го символа if(length > 1){ /** * checkFn Функция проверки на валидность символа * @param text текст для проверки * @param index индекс буквы в слове * @return результат проверки */ auto checkFn = [this](const wstring & text, const size_t index) noexcept { // Результат работы функции bool result = false; // Получаем текущую букву const wchar_t letter = text.at(index); // Если буква не первая и не последняя if((index > 0) && (index < (text.length() - 1))){ // Получаем предыдущую букву const wchar_t first = text.at(index - 1); // Получаем следующую букву const wchar_t second = text.at(index + 1); // Если это дефис result = ((letter == L'-') && (first != L'-') && (second != L'-')); // Если проверка не пройдена, проверяем на апостроф if(!result){ // Выполняем проверку на апостроф result = ( (letter == L'\'') && ((this->isAllowApostrophe() && ((first != L'\'') && (second != L'\''))) || ((this->latian.count(first) > 0) && (this->latian.count(second) > 0))) ); } // Если результат не получен if(!result) result = (this->latian.count(letter) > 0); // Выводим проверку как она есть } else result = (this->latian.count(letter) > 0); // Выводим результат return result; }; // Переходим по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Проверяем является ли слово латинским result = (i == j ? checkFn(tmp, i) : checkFn(tmp, i) && checkFn(tmp, j)); // Если слово не соответствует тогда выходим if(!result) break; } // Если символ всего один, проверяем его так } else result = (this->latian.count(tmp.front()) > 0); } // Выводим результат return result; } /** * isPunct Метод проверки является ли буква, знаком препинания * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isPunct(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Проверяем на знак пунктуации if(letter > 0) result = ((this->letters.count(letter) < 1) && (this->punctsSymbols.count(letter) > 0)); // Выводим результат return result; } /** * isSpace Метод проверки является ли буква, пробелом * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isSpace(const wchar_t letter) const noexcept { // Получаем код символа const u_short lid = letter; // Выводим результат return ((lid == 32) || (lid == 160) || (lid == 173) || (lid == 9)); } /** * isGreek Метод определения символа греческого алфавита * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isGreek(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Проверяем на греческий символ if(letter > 0) result = ((this->letters.count(letter) < 1) && (this->greekSymbols.count(letter) > 0)); // Выводим результат return result; } /** * isRoute Метод определения символов стрелок * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isRoute(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Проверяем на наличие стрелки if(letter > 0) result = ((this->letters.count(letter) < 1) && (this->routeSymbols.count(letter) > 0)); // Выводим результат return result; } /** * isNumber Метод проверки является ли слово числом * @param word слово для проверки * @return результат проверки */ const bool anyks::Alphabet::isNumber(const string & word) const noexcept { // Выполняем проверку return this->isNumber(this->convert(word)); } /** * isNumber Метод проверки является ли слово числом * @param word слово для проверки * @return результат проверки */ const bool anyks::Alphabet::isNumber(const wstring & word) const noexcept { // Результат работы функции bool result = false; // Если слово передана if(!word.empty()){ // Длина слова const size_t length = word.length(); // Если длина слова больше 1-го символа if(length > 1){ // Переходим по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Проверяем является ли слово арабским числом result = !( i == j ? (this->numsSymbols.arabs.count(word.at(i)) < 1) : (this->numsSymbols.arabs.count(word.at(i)) < 1) || (this->numsSymbols.arabs.count(word.at(j)) < 1) ); // Если слово не соответствует тогда выходим if(!result) break; } // Если символ всего один, проверяем его так } else result = (this->numsSymbols.arabs.count(word.front()) > 0); } // Выводим результат return result; } /** * isLetter Метод проверки на разрешённую букву * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isLetter(const wchar_t letter) const noexcept { // Выводим результат проверки return (this->alphabet.find(letter) != wstring::npos); } /** * isDecimal Метод проверки является ли слово дробным числом * @param word слово для проверки * @return результат проверки */ const bool anyks::Alphabet::isDecimal(const string & word) const noexcept { // Выводим результат проверки return this->isDecimal(this->convert(word)); } /** * isDecimal Метод проверки является ли слово дробным числом * @param word слово для проверки * @return результат проверки */ const bool anyks::Alphabet::isDecimal(const wstring & word) const noexcept { // Результат работы функции bool result = false; // Если слово передана if(!word.empty()){ // Длина слова const size_t length = word.length(); // Если длина слова больше 1-го символа if(length > 1){ // Текущая буква wchar_t letter = 0; // Начальная позиция поиска const u_short pos = ((word.front() == L'-') || (word.front() == L'+') ? 1 : 0); // Переходим по всем символам слова for(size_t i = pos; i < length; i++){ // Получаем текущую букву letter = word.at(i); // Если плавающая точка найдена if((letter == L'.') || (letter == L',')){ // Проверяем правые и левую части result = (this->isNumber(word.substr(pos, i)) && this->isNumber(word.substr(i + 1))); // Выходим из цикла break; } } } } // Выводим результат return result; } /** * isANumber Метод проверки является ли косвенно слово числом * @param word слово для проверки * @return результат проверки */ const bool anyks::Alphabet::isANumber(const wstring & word) const noexcept { // Результат работы функции bool result = false; // Если слово передано if(!word.empty()){ // Проверяем является ли слово числом result = this->isNumber(word); // Если не является то проверяем дальше if(!result){ // Длина слова const size_t length = word.length(); // Проверяем являются ли первая и последняя буква слова, числом result = (this->isNumber(wstring(1, word.front())) || this->isNumber(wstring(1, word.back()))); // Если оба варианта не сработали if(!result && (length > 2)){ // Первое слово wstring first = L""; // Переходим по всему списку for(size_t i = 1, j = length - 2; j > ((length / 2) - 1); i++, j--){ // Получаем первое слово first.assign(1, word.at(i)); // Проверяем является ли слово арабским числом result = (i == j ? this->isNumber(first) : this->isNumber(first) || this->isNumber(wstring(1, word[j]))); // Если хоть один символ является числом, выходим if(result) break; } } } } // Выводим результат return result; } /** * isAllowed Метод проверки соответствия слова словарю * @param word слово для проверки * @return результат проверки */ const bool anyks::Alphabet::isAllowed(const wstring & word) const noexcept { // Результат работы функции bool result = false; // Если слово передано if(!word.empty()){ // Длина слова const size_t length = word.length(); // Переводим слово в нижний регистр const wstring & tmp = this->toLower(word); // Если строка длиннее 1-го символа if(length > 1){ /** * checkFn Функция проверки на валидность символа * @param text текст для проверки * @param index индекс буквы в слове * @return результат проверки */ auto checkFn = [this](const wstring & text, const size_t index) noexcept { // Результат работы функции bool result = false; // Получаем текущую букву const wchar_t letter = text.at(index); // Если буква не первая и не последняя if((index > 0) && (index < (text.length() - 1))){ // Получаем предыдущую букву const wchar_t first = text.at(index - 1); // Получаем следующую букву const wchar_t second = text.at(index + 1); // Если это дефис result = ((letter == L'-') && (first != L'-') && (second != L'-')); // Если проверка не пройдена, проверяем на апостроф if(!result){ // Выполняем проверку на апостроф result = ( (letter == L'\'') && ((this->isAllowApostrophe() && ((first != L'\'') && (second != L'\''))) || ((this->latian.count(first) > 0) && (this->latian.count(second) > 0))) ); } // Если результат не получен if(!result) result = this->check(letter); // Выводим проверку как она есть } else result = this->check(letter); // Выводим результат return result; }; // Выполняем переход по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Проверяем является ли слово разрешённым result = (i == j ? checkFn(tmp, i) : checkFn(tmp, i) && checkFn(tmp, j)); // Если слово не соответствует тогда выходим if(!result) break; } // Если строка всего из одного символа } else result = this->check(tmp.front()); } // Выводим результат return result; } /** * isSpecial Метод определения спец-символа * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isSpecial(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Проверяем на спец-символ if(letter > 0) result = ((this->letters.count(letter) < 1) && (this->specialSymbols.count(letter) > 0)); // Выводим результат return result; } /** * isCurrency Метод определения символа валюты * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isCurrency(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Проверяем на наличие символа курсовой валюты if(letter > 0) result = ((this->letters.count(letter) < 1) && (this->currencySymbols.count(letter) > 0)); // Выводим результат return result; } /** * isPlayCards Метод определения символа игральных карт * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isPlayCards(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Проверяем на наличие символа игральной карты if(letter > 0) result = ((this->letters.count(letter) < 1) && (this->playCardsSymbols.count(letter) > 0)); // Выводим результат return result; } /** * isIsolation Метод определения знака изоляции (кавычки, скобки) * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::isIsolation(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Проверяем на наличие символа изоляции if(letter > 0) result = ((this->letters.count(letter) < 1) && (this->isolationSymbols.count(letter) > 0)); // Выводим результат return result; } /** * rest Метод исправления и детектирования слов со смешенными алфавитами * @param word слово для проверки и исправления * @return результат проверки */ const bool anyks::Alphabet::rest(wstring & word) const noexcept { // Результат работы функции bool result = false; // Если слово передано if(!word.empty() && (word.length() > 1)){ // Список остальных символов multimap <wchar_t, u_short> other; // Список латинских букв multimap <wchar_t, u_short> latian; // Список нормального алфавита multimap <wchar_t, u_short> normal; /** * setFn Метод установки полученной буквы * @param letter буква для установки * @param pos позиция буквы в слове */ auto setFn = [&other, &latian, &normal, this](const wchar_t letter, const u_short pos) noexcept { // Если это латинский алфавит if(this->checkLatian({letter})) latian.emplace(letter, pos); // Если это нормальная буква else if(!this->typeLatian && (this->letters.count(letter) > 0)) normal.emplace(letter, pos); // Иначе это другие символы else other.emplace(letter, pos); }; // Получаем длину слова const size_t length = word.length(); // Выполняем переход по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Если это центр слова if(i == j) setFn(word.at(i), i); // Если это разные стороны слова else { // Добавляем первое слово setFn(word.at(i), i); // Добавляем второе слово setFn(word.at(j), j); } } // Проверяем соответствует ли слово одному алфавиту result = (((normal.size() + other.size()) != length) && ((latian.size() + other.size()) != length)); // Если слово не соответствует алфавиту if(result && !this->substitutes.empty()){ // Если это предположительно это сломанное слово нормального алфавита if(!latian.empty() && (normal.size() >= latian.size())){ // Переходим по всему списку собранных латинских букв for(auto & item : latian){ // Выполняем поиск буквы в списке репласеров auto it = this->substitutes.find(item.first); // Если буква найдена if(it != this->substitutes.end()){ // Выполняем замену буквы в слове word.replace(item.second, 1, 1, it->second); } } // Если слово больше не латинское result = this->checkLatian(word); // Если это англоязычное слово } else if(!other.empty()) { // Переходим по всему списку собранных латинских букв for(auto & item : other){ // Выполняем поиск буквы в списке репласеров auto it = this->substitutes.find(item.first); // Если буква найдена if(it != this->substitutes.end()){ // Выполняем замену буквы в слове word.replace(item.second, 1, 1, it->second); } } // Если слово больше не латинское result = this->isLatian(word); } } } // Выводим результат return result; } /** * check Метод проверки соответствии буквы * @param letter буква для проверки * @return результат проверки */ const bool anyks::Alphabet::check(const wchar_t letter) const noexcept { // Результат работы функции bool result = false; // Результат проверки if(letter > 0){ // Если это не число, тогда выполняем проверку if(!(result = this->isNumber(wstring(1, letter)))){ // Выполняем проверку буквы result = (this->letters.count(letter) > 0); } } // Выводим результат return result; } /** * checkHome2 Метод проверки слова на Дом-2 * @param word слово для проверки * @return результат работы метода */ const bool anyks::Alphabet::checkHome2(const wstring & word) const noexcept { // Результат работы функции bool result = false; // Если слово передано, первая буква не является числом а последняя это число if(!word.empty() && !this->isNumber(wstring(1, word.front())) && this->isNumber(wstring(1, word.back()))){ // Позиция дефиса в слове size_t pos = 0; // Ищим дефис в слове if((pos = word.rfind(L"-")) != wstring::npos){ // Извлекаем суффикс слова const wstring & suffix = word.substr(pos + 1); // Если только суффикс является числом выводим результат result = (!this->isNumber(word.substr(0, pos)) && this->isNumber(suffix)); } } // Выводим результат return result; } /** * checkLatian Метод проверки наличия латинских символов в строке * @param str строка для проверки * @return результат проверки */ const bool anyks::Alphabet::checkLatian(const wstring & str) const noexcept { // Результат работы функции bool result = false; // Если строка передана if(!str.empty()){ // Длина слова const size_t length = str.length(); // Если длина слова больше 1-го символа if(length > 1){ // Переходим по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Проверяем является ли слово латинским result = (i == j ? (this->latian.count(str.at(i)) > 0) : (this->latian.count(str.at(i)) > 0) || (this->latian.count(str.at(j)) > 0)); // Если найдена хотя бы одна латинская буква тогда выходим if(result) break; } // Если символ всего один, проверяем его так } else result = (this->latian.count(str.front()) > 0); } // Выводим результат return result; } /** * checkHyphen Метод проверки наличия дефиса в строке * @param str строка для проверки * @return результат проверки */ const bool anyks::Alphabet::checkHyphen(const wstring & str) const noexcept { // Результат работы функции bool result = false; // Если строка передана if(!str.empty()){ // Длина слова const size_t length = str.length(); // Если длина слова больше 1-го символа if(length > 1){ // Переходим по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Проверяем является ли слово латинским result = (i == j ? (str.at(i) == L'-') : (str.at(i) == L'-') || (str.at(j) == L'-')); // Если найдена хотя бы одна латинская буква тогда выходим if(result) break; } // Если символ всего один, проверяем его так } else result = (str.front() == L'-'); } // Выводим результат return result; } /** * checkSimilars Метод проверки на симиляции букв с другими языками * @param str строка для проверки * @return результат проверки */ const bool anyks::Alphabet::checkSimilars(const wstring & str) const noexcept { // Результат работы функции bool result = false; // Если строка передана if(!str.empty() && !this->substitutes.empty()){ // Длина слова const size_t length = str.length(); // Если длина строки больше 1 if(length > 1){ /** * existFn Функция проверки на существование буквы * @param letter буква для проверки * @return результат проверки */ auto existFn = [this](const wchar_t letter) noexcept { // Результат работы функци bool result = false; // Если буква передана if(letter > 0){ // Выполняем проверку буквы result = ( (letter != L'-') && !this->isLatian({letter}) && !this->isNumber(wstring(1, letter)) && (this->letters.count(letter) > 0) ); } // Выводим результат return result; }; // Первое и второе слово bool first = false, second = false; // Переходим по всему слову for(size_t i = 0; i < length; i++){ // Если буква совпала if(this->substitutes.count(str.at(i)) > 0){ // Проверяем первую букву first = (i > 0 ? existFn(str.at(i - 1)) : false); // Проверяем следующую букву second = (i < (length - 1) ? existFn(str.at(i + 1)) : false); // Если первая или вторая буква сработали, выходим result = (((i == (length - 1)) && first) || ((i == 0) && second) || (first && second)); // Выходим из цикла if(result) break; } } } } // Выводим результат return result; } /** * getzones Метод извлечения списка пользовательских зон интернета * @return список доменных зон */ const std::set <wstring> & anyks::Alphabet::getzones() const noexcept { // Выводим список доменных зон интернета return this->uri.getZones(); } /** * getAllowed Метод извлечения списка разрешённых символов * @return список разрешённых символов */ const std::set <wchar_t> & anyks::Alphabet::getAllowed() const noexcept { // Выводим список разрешённых символов return this->allowedSymbols; } /** * getSubstitutes Метод извлечения букв для исправления слов из смешанных алфавитов * @param return список букв разных алфавитов соответствующих друг-другу */ const std::map <string, string> & anyks::Alphabet::getSubstitutes() const noexcept { // Выводим результат const static std::map <string, string> result; // Если список букв передан if(!this->substitutes.empty()){ // Переходим по всем буквам for(auto & item : this->substitutes){ // Добавляем букву в список const_cast <std::map <string, string> *> (&result)->emplace( this->convert(wstring{item.first}), this->convert(wstring{item.second}) ); } } // Выводим результат return result; } /** * urls Метод извлечения координат url адресов в строке * @param text текст для извлечения url адресов * @return список координат с url адресами */ const std::map <size_t, size_t> anyks::Alphabet::urls(const wstring & text) const noexcept { // Результат работы функции map <size_t, size_t> result; // Если текст передан if(!text.empty()){ // Позиция найденного uri адреса size_t pos = 0; // Выполням поиск ссылок в тексте while(pos < text.length()){ // Выполняем парсинг uri адреса auto resUri = this->uri.parse(text.substr(pos)); // Если ссылка найдена if(resUri.type != uri_t::types_t::null){ // Получаем данные слова const wstring & word = resUri.uri; // Если это не предупреждение if(resUri.type != uri_t::types_t::wrong){ // Если позиция найдена if((pos = text.find(word, pos)) != wstring::npos){ // Если в списке результатов найдены пустные значения, очищаем список if(result.count(wstring::npos) > 0) result.clear(); // Добавляем в список нашу ссылку result.insert({pos, pos + word.length()}); // Если ссылка не найдена в тексте, выходим } else break; } // Сдвигаем значение позиции pos += word.length(); // Если uri адрес больше не найден то выходим } else break; } } // Выводим результат return result; } /** * checkHypLat Метод поиска дефиса и латинского символа * @param str строка для проверки * @return результат проверки */ const pair <bool, bool> anyks::Alphabet::checkHypLat(const wstring & str) const noexcept { // Результат работы функции pair <bool, bool> result = {false, false}; // Если строка передана if(!str.empty()){ // Длина слова const size_t length = str.length(); // Если длина слова больше 1-го символа if(length > 1){ // Значение текущей буквы wchar_t letter = 0; // Переходим по всем буквам слова for(size_t i = 0, j = (length - 1); j > ((length / 2) - 1); i++, j--){ // Получаем значение текущей буквы letter = str.at(i); // Проверяем является ли слово латинским if(!result.first) result.first = (letter == L'-'); // Проверяем на латинский символ if(!result.first && !result.second) result.second = (this->latian.count(letter) > 0); // Проверяем вторую букву if((!result.first || !result.second) && (i != j)){ // Получаем значение текущей буквы letter = str.at(j); // Проверяем является ли слово латинским if(!result.first) result.first = (letter == L'-'); // Проверяем на латинский символ if(!result.first && !result.second) result.second = (this->latian.count(letter) > 0); } // Если найден и пробел и латинский символ if(result.first && result.second) break; } // Если символ всего один, проверяем его так } else { // Запоминаем найден ли дефис result.first = (str.front() == L'-'); // Если дефис не найден, проверяем на латинский символ if(!result.first) result.second = (this->latian.count(str.front()) > 0); } } // Выводим результат return result; } /** * clear Метод очистки собранных данных */ void anyks::Alphabet::clear() noexcept { // Алфавит латинских символов wstring alphabet = L""; // Переходим по всем буквам латинских символов for(auto & letter : this->latian){ // Формируем алфавит латинских символов alphabet.append(1, letter); } // Очищаем список похожих букв в разных алфавитах this->substitutes.clear(); // Формируем алфавит this->set(this->convert(alphabet)); } /** * switchAllowApostrophe Метод разрешения или запрещения апострофа как части слова */ void anyks::Alphabet::switchAllowApostrophe() noexcept { // Выполняем переключение разрешения использования апострофа this->apostrophe = !this->apostrophe; } /** * log Метод вывода текстовой информации в консоль или файл * @param format формат строки вывода * @param flag флаг типа логирования * @param filename адрес файла для вывода */ void anyks::Alphabet::log(const string & format, log_t flag, const char * filename, ...) const noexcept { // Если формат передан if(!format.empty()){ // Создаем список аргументов va_list args; // Строка результата string str = ""; // Создаем буфер char buffer[BUFFER_CHUNK]; // Заполняем буфер нулями memset(buffer, 0, sizeof(buffer)); // Устанавливаем начальный список аргументов va_start(args, filename); // Выполняем запись в буфер const size_t size = vsprintf(buffer, format.c_str(), args); // Завершаем список аргументов va_end(args); // Если размер не нулевой if(size > 0) str.assign(buffer, size); // Если строка получена if(!str.empty()){ // Проверяем является ли это переводом строки const bool isEnd = ((str.compare("\r\n") == 0) || (str.compare("\n") == 0)); // Формируем файловый поток ostream * file = (filename == nullptr ? nullptr : new ofstream(filename, ios::app)); // Формируем выходной поток ostream & out = (filename != nullptr ? * file : cout); // Определяем тип сообщения switch((u_short) flag){ // Выводим сообщение так-как оно есть case (u_short) log_t::null: out << this->format("%s", str.c_str()) << (!isEnd ? "\r\n" : ""); break; // Выводим информационное сообщение case (u_short) log_t::info: out << (filename != nullptr ? this->format("info: %s", str.c_str()) : this->format("\x1B[32m\x1B[1minfo:\x1B[0m %s", str.c_str())) << (!isEnd ? "\r\n" : ""); break; // Выводим сообщение об ошибке case (u_short) log_t::error: out << (filename != nullptr ? this->format("error: %s", str.c_str()) : this->format("\x1B[31m\x1B[1merror:\x1B[0m %s", str.c_str())) << (!isEnd ? "\r\n" : ""); break; // Выводим сообщение предупреждения case (u_short) log_t::warning: out << (filename != nullptr ? this->format("warning: %s", str.c_str()) : this->format("\x1B[35m\x1B[1mwarning:\x1B[0m %s", str.c_str())) << (!isEnd ? "\r\n" : ""); break; } // Если был создан файловый поток, удаляем память if(file != nullptr) delete file; } } } /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void anyks::Alphabet::split(const word_t & str, const word_t & delim, list <word_t> & v) const noexcept { // Выполняем сплит строки ::split(str, delim, v); } /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void anyks::Alphabet::split(const word_t & str, const word_t & delim, vector <word_t> & v) const noexcept { // Выполняем сплит строки ::split(str, delim, v); } /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void anyks::Alphabet::split(const wstring & str, const wstring & delim, list <wstring> & v) const noexcept { // Выполняем сплит строки ::split(str, delim, v); } /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void anyks::Alphabet::split(const wstring & str, const wstring & delim, vector <wstring> & v) const noexcept { // Выполняем сплит строки ::split(str, delim, v); } /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void anyks::Alphabet::split(const string & str, const string & delim, list <wstring> & v) const noexcept { // Выполняем сплит строки ::split(this->convert(str), this->convert(delim), v); } /** * split Метод разделения строк на составляющие * @param str строка для поиска * @param delim разделитель * @param v результирующий вектор */ void anyks::Alphabet::split(const string & str, const string & delim, vector <wstring> & v) const noexcept { // Выполняем сплит строки ::split(this->convert(str), this->convert(delim), v); } /** * add Метод добавления буквы в алфавит * @param letter буква для добавления */ void anyks::Alphabet::add(const wchar_t letter) noexcept { // Если буква передана и такой буквы еще нет if((letter > 0) && (this->letters.count(letter) < 1)){ // Добавляем букву в список if(!this->isNumber(wstring(1, letter)) && (this->allowedSymbols.count(letter) < 1) ) this->letters.emplace(letter); } } /** * set Метод добавления алфавита в словарь * @param alphabet алфавит символов для текущего языка */ void anyks::Alphabet::set(const string & alphabet) noexcept { // Удаляем список букв this->letters.clear(); // Запоминаем список букв if(!alphabet.empty()) this->alphabet = this->convert(alphabet); // Переходим по всем буквам алфавита for(auto & letter : this->alphabet){ // Добавляем буквы алфавита в список this->add(letter); } // Переходим по всем буквам алфавита for(auto & letter : this->alphabet){ // Если буква не является латинской - запоминаем, что это не латинский алфавит if(!(this->typeLatian = this->checkLatian({letter}))) break; } // Если список букв получен if(!this->alphabet.empty()) this->uri.setLetters(this->alphabet); } /** * setzone Метод установки пользовательской зоны * @param zone пользовательская зона */ void anyks::Alphabet::setzone(const string & zone) noexcept { // Если зона передана, устанавливаем её if(!zone.empty()) this->uri.setZone(this->convert(zone)); } /** * setzone Метод установки пользовательской зоны * @param zone пользовательская зона */ void anyks::Alphabet::setzone(const wstring & zone) noexcept { // Если зона передана, устанавливаем её if(!zone.empty()) this->uri.setZone(zone); } /** * setzones Метод установки списка пользовательских зон * @param zones список доменных зон интернета */ void anyks::Alphabet::setzones(const std::set <string> & zones) noexcept { // Устанавливаем список доменных зон if(!zones.empty()){ // Переходим по всему списку доменных зон for(auto & zone : zones) this->setzone(zone); } } /** * setzones Метод установки списка пользовательских зон * @param zones список доменных зон интернета */ void anyks::Alphabet::setzones(const std::set <wstring> & zones) noexcept { // Устанавливаем список доменных зон if(!zones.empty()) this->uri.setZones(zones); } /** * setlocale Метод установки локали * @param locale локализация приложения */ void anyks::Alphabet::setlocale(const string & locale) noexcept { // Устанавливаем локаль if(!locale.empty()){ // Создаём новую локаль std::locale loc(locale.c_str()); // Устанавливапм локализацию приложения ::setlocale(LC_CTYPE, locale.c_str()); ::setlocale(LC_COLLATE, locale.c_str()); // Устанавливаем локаль системы this->locale = std::locale::global(loc); } } /** * setSubstitutes Метод установки букв для исправления слов из смешанных алфавитов * @param letters список букв разных алфавитов соответствующих друг-другу */ void anyks::Alphabet::setSubstitutes(const std::map <string, string> & letters) noexcept { // Если список букв передан if(!letters.empty()){ // Очищаем текущий список букв this->substitutes.clear(); // Переходим по всем буквам for(auto & item : letters){ // Добавляем букву в список this->substitutes.emplace( this->convert(item.first).front(), this->convert(item.second).front() ); } } } /** * Alphabet Конструктор */ anyks::Alphabet::Alphabet() noexcept { // Устанавливаем локализацию системы this->setlocale(); // Переходим по всем буквам алфавита for(auto & letter : this->alphabet){ // Добавляем буквы в латинский алфавит this->latian.emplace(letter); } // Устанавливаем алфавит по умолчанию this->set(); } /** * Alphabet Конструктор * @param locale локализация приложения */ anyks::Alphabet::Alphabet(const string & locale) noexcept { // Устанавливаем локализацию системы this->setlocale(locale); // Переходим по всем буквам алфавита for(auto & letter : this->alphabet){ // Добавляем буквы в латинский алфавит this->latian.emplace(letter); } // Устанавливаем алфавит по умолчанию this->set(); } /** * Alphabet Конструктор * @param alphabet алфавит символов для текущего языка * @param locale локализация приложения */ anyks::Alphabet::Alphabet(const string & alphabet, const string & locale) noexcept { // Устанавливаем локализацию системы this->setlocale(locale); // Переходим по всем буквам алфавита for(auto & letter : this->alphabet){ // Добавляем буквы в латинский алфавит this->latian.emplace(letter); } // Если алфавит передан if(!alphabet.empty()) // Устанавливаем переданный алфавит this->set(alphabet); // Устанавливаем алфавит по умолчанию else this->set(); } /** * Оператор чтения из потока * @param is поток для чтения * @param word слово куда нужно считать данные из потока */ istream & anyks::operator >> (istream & is, wstring & word) noexcept { // Получаем строку string str = ""; // Считываем в строку значение is >> str; // Устанавливаем значение if(!str.empty()) word.assign(alphabet_t().convert(str)); // Выводим результат return is; } /** * Оператор вывода в поток из слова * @param os поток куда нужно вывести данные * @param word слово из которого нужно вывести данные */ ostream & anyks::operator << (ostream & os, const wstring & word) noexcept { // Записываем в поток os << alphabet_t().convert(word); // Выводим результат return os; }
31.943935
205
0.664709
[ "vector", "transform" ]
110d404a03a40b69e58b7d5eb805f8f3ba414925
9,485
cpp
C++
Samples/Win7Samples/multimedia/mediafoundation/DXVA_HD/video.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/multimedia/mediafoundation/DXVA_HD/video.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/multimedia/mediafoundation/DXVA_HD/video.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
////////////////////////////////////////////////////////////////////// // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // ////////////////////////////////////////////////////////////////////// #include <windows.h> #include <d3d9.h> #include "video.h" //------------------------------------------------------------------- // DrawColorBars // // Draw SMPTE colors bars to a Direct3D surface. // The surface format is assumed to be YUY2. //------------------------------------------------------------------- HRESULT DrawColorBars(IDirect3DSurface9 *pSurf, UINT width, UINT height) { HRESULT hr; // Draw the main stream (SMPTE color bars). D3DLOCKED_RECT lr; hr = pSurf->LockRect(&lr, NULL, D3DLOCK_NOSYSLOCK); if (FAILED(hr)) { return hr; } // YUY2 is two pixels per DWORD. const UINT dx = width / 2; // First row stripes. const UINT y1 = height * 2 / 3; FillRectangle(lr, dx * 0 / 7, 0, dx * 1 / 7, y1, RGBtoYUY2(RGB_WHITE_75pc)); FillRectangle(lr, dx * 1 / 7, 0, dx * 2 / 7, y1, RGBtoYUY2(RGB_YELLOW_75pc)); FillRectangle(lr, dx * 2 / 7, 0, dx * 3 / 7, y1, RGBtoYUY2(RGB_CYAN_75pc)); FillRectangle(lr, dx * 3 / 7, 0, dx * 4 / 7, y1, RGBtoYUY2(RGB_GREEN_75pc)); FillRectangle(lr, dx * 4 / 7, 0, dx * 5 / 7, y1, RGBtoYUY2(RGB_MAGENTA_75pc)); FillRectangle(lr, dx * 5 / 7, 0, dx * 6 / 7, y1, RGBtoYUY2(RGB_RED_75pc)); FillRectangle(lr, dx * 6 / 7, 0, dx * 7 / 7, y1, RGBtoYUY2(RGB_BLUE_75pc)); // Second row stripes. const UINT y2 = height * 3 / 4; FillRectangle(lr, dx * 0 / 7, y1, dx * 1 / 7, y2, RGBtoYUY2(RGB_BLUE_75pc)); FillRectangle(lr, dx * 1 / 7, y1, dx * 2 / 7, y2, RGBtoYUY2(RGB_BLACK)); FillRectangle(lr, dx * 2 / 7, y1, dx * 3 / 7, y2, RGBtoYUY2(RGB_MAGENTA_75pc)); FillRectangle(lr, dx * 3 / 7, y1, dx * 4 / 7, y2, RGBtoYUY2(RGB_BLACK)); FillRectangle(lr, dx * 4 / 7, y1, dx * 5 / 7, y2, RGBtoYUY2(RGB_CYAN_75pc)); FillRectangle(lr, dx * 5 / 7, y1, dx * 6 / 7, y2, RGBtoYUY2(RGB_BLACK)); FillRectangle(lr, dx * 6 / 7, y1, dx * 7 / 7, y2, RGBtoYUY2(RGB_WHITE_75pc)); // Third row stripes. const UINT y3 = height; FillRectangle(lr, dx * 0 / 28, y2, dx * 5 / 28, y3, RGBtoYUY2(RGB_I)); FillRectangle(lr, dx * 5 / 28, y2, dx * 10 / 28, y3, RGBtoYUY2(RGB_WHITE)); FillRectangle(lr, dx * 10 / 28, y2, dx * 15 / 28, y3, RGBtoYUY2(RGB_Q)); FillRectangle(lr, dx * 15 / 28, y2, dx * 20 / 28, y3, RGBtoYUY2(RGB_BLACK)); FillRectangle(lr, dx * 20 / 28, y2, dx * 16 / 21, y3, RGBtoYUY2(RGB_BLACK_n4pc)); FillRectangle(lr, dx * 16 / 21, y2, dx * 17 / 21, y3, RGBtoYUY2(RGB_BLACK)); FillRectangle(lr, dx * 17 / 21, y2, dx * 6 / 7, y3, RGBtoYUY2(RGB_BLACK_p4pc)); FillRectangle(lr, dx * 6 / 7, y2, dx * 7 / 7, y3, RGBtoYUY2(RGB_BLACK)); hr = pSurf->UnlockRect(); return hr; } //------------------------------------------------------------------- // LoadBitmapResourceToAYUVSurface // // Load a 24-bpp RGB bitmap resource onto a Direct3D surface. // The surface format is assumed to be AYUV. //------------------------------------------------------------------- HRESULT LoadBitmapResourceToAYUVSurface( IDirect3DSurface9 *pSurf, LONG width, // Surface width LONG height, // Surface height INT nIDBitmap, // Resource ID BYTE PixelAlphaValue // Per-pixel alpha value ) { HRESULT hr = S_OK; D3DLOCKED_RECT lr = { 0 }; HRSRC hrsrc = NULL; HGLOBAL hglob = NULL; // Load the bitmap resource. hrsrc = FindResource(NULL, MAKEINTRESOURCE(nIDBitmap), RT_BITMAP); if (hrsrc == NULL) { return HRESULT_FROM_WIN32(GetLastError()); } hglob = LoadResource(NULL,hrsrc); if (hglob == NULL) { return HRESULT_FROM_WIN32(GetLastError()); } // Get the bitmap bits. LPBITMAPINFOHEADER lpBitmap = (LPBITMAPINFOHEADER)LockResource(hglob); if (lpBitmap->biWidth != width || lpBitmap->biHeight != height) { hr = E_INVALIDARG; goto done; } // Lock the Direct3D surface. hr = pSurf->LockRect(&lr, NULL, D3DLOCK_NOSYSLOCK); if (FAILED(hr)) { goto done; } // Calculate source and target stride. // The source bitmap is bottom-up, the target image is top-down. LPBYTE lpBits = (LPBYTE)(lpBitmap + 1); LONG lSrcStride = -1 * ((lpBitmap->biWidth * 3 + 3) & ~3); BYTE *pSrc = (BYTE*)lpBits + (-lSrcStride * (lpBitmap->biHeight - 1)); BYTE* pDest = (BYTE*) lr.pBits; // Convert the RGB pixels to AYUV and write to the surface. for (LONG y = 0; y < lpBitmap->biHeight; y++) { RGBTRIPLE *pPel = (RGBTRIPLE*)pSrc; for (LONG x = 0; x < lpBitmap->biWidth; x++) { const D3DCOLOR rgb = D3DCOLOR_ARGB( PixelAlphaValue, pPel[x].rgbtRed, pPel[x].rgbtGreen, pPel[x].rgbtBlue ); ((DWORD*) pDest)[x] = RGBtoYUV(rgb); } pSrc += lSrcStride; pDest += lr.Pitch; } hr = pSurf->UnlockRect(); done: DeleteObject(hglob); return hr; } //------------------------------------------------------------------- // SetAYUVSurfacePixelAlpha // // Updates the per-pixel alpha values in an AYUV surface. //------------------------------------------------------------------- HRESULT SetAYUVSurfacePixelAlpha( IDirect3DSurface9 *pSurf, UINT width, UINT height, BYTE PixelAlphaValue ) { HRESULT hr; D3DLOCKED_RECT lr; hr = pSurf->LockRect(&lr, NULL, D3DLOCK_NOSYSLOCK); if (FAILED(hr)) { return hr; } BYTE* pDest = (BYTE*) lr.pBits; for (UINT y = 0; y < height; y++) { for (UINT x = 0; x < width; x++) { pDest[ x * 4 + 3 ] = PixelAlphaValue; } pDest += lr.Pitch; } hr = pSurf->UnlockRect(); return hr; } //------------------------------------------------------------------- // FillRectangle // // Fills a subrectangle in a Direct3D surface with a solid color. // // The caller must call LockSurface to lock the surface, and pass in // the D3DLOCKED_RECT structure. //------------------------------------------------------------------- void FillRectangle( D3DLOCKED_RECT& lr, const UINT sx, // Horizontal position const UINT sy, // Vertical position const UINT ex, // Horizontal extent. const UINT ey, // Vertical extent. const DWORD color ) { BYTE* p = (BYTE*) lr.pBits; p += lr.Pitch * sy; for (UINT y = sy; y < ey; y++, p += lr.Pitch) { for (UINT x = sx; x < ex; x++) { ((DWORD*) p)[x] = color; } } } //------------------------------------------------------------------- // ScaleRectangle // // Scales an input rectangle, using the following scaling factor: // // output = input * (dst / src) // //------------------------------------------------------------------- RECT ScaleRectangle(const RECT& input, const RECT& src, const RECT& dst) { RECT rect; UINT src_dx = src.right - src.left; UINT src_dy = src.bottom - src.top; UINT dst_dx = dst.right - dst.left; UINT dst_dy = dst.bottom - dst.top; // Scale the input rectangle by dst / src. rect.left = input.left * dst_dx / src_dx; rect.right = input.right * dst_dx / src_dx; rect.top = input.top * dst_dy / src_dy; rect.bottom = input.bottom * dst_dy / src_dy; return rect; } //------------------------------------------------------------------- // InflateRectBounded // // Resizes a rectangle by a specified amount, but clips the result // to a bounding rectangle. // // prc: The rectangle to resize. // cx, cy: Amount to increase or decrease the rectangle. // rcBound: Bounding rectangle. // //------------------------------------------------------------------- void InflateRectBounded(RECT *prc, LONG cx, LONG cy, const RECT& rcBound) { RECT rect = *prc; RECT intersect; InflateRect(&rect, cx, cy); IntersectRect(&intersect, &rect, &rcBound); if (!IsRectEmpty(&intersect)) { *prc = intersect; } } //------------------------------------------------------------------- // MoveRectBounded // // Moves a rectangle by a specified amount, but clips the result to // a bounding rectangle. // // prc: The rectangle to move. // cx, cy: Amount to move in the x and y directions. // rcBound: Bounding rectangle. // //------------------------------------------------------------------- void MoveRectBounded(RECT *prc, LONG cx, LONG cy, const RECT& rcBound) { RECT rect = *prc; RECT intersect; OffsetRect(&rect, cx, cy); IntersectRect(&intersect, &rect, &rcBound); if (EqualRect(&rect, &intersect)) { *prc = rect; } }
29.548287
86
0.506906
[ "solid" ]
110e41ee8527c64a9729b70e0ff3a06bba70b8d2
16,091
hh
C++
include/aleph/math/PiecewiseLinearFunction.hh
eudoxos/Aleph
874882c33a0e8429c74e567eb01525613fee0616
[ "MIT" ]
56
2019-04-24T22:11:15.000Z
2022-03-22T11:37:47.000Z
include/aleph/math/PiecewiseLinearFunction.hh
eudoxos/Aleph
874882c33a0e8429c74e567eb01525613fee0616
[ "MIT" ]
48
2016-11-30T09:37:13.000Z
2019-01-30T21:43:39.000Z
include/aleph/math/PiecewiseLinearFunction.hh
eudoxos/Aleph
874882c33a0e8429c74e567eb01525613fee0616
[ "MIT" ]
11
2019-05-02T11:54:31.000Z
2020-12-10T14:05:40.000Z
#ifndef ALEPH_MATH_PIECEWISE_LINEAR_FUNCTION_HH__ #define ALEPH_MATH_PIECEWISE_LINEAR_FUNCTION_HH__ #include <aleph/math/KahanSummation.hh> #include <functional> #include <iterator> #include <limits> #include <map> #include <set> #include <stdexcept> #include <vector> #include <cassert> #include <cmath> namespace aleph { namespace math { namespace detail { /** Performs linear interpolation between two points */ template <class D, class I> I lerp( D x, D x0, I y0, D x1, I y1 ) { return y0 + (y1-y0) * (x-x0) / (x1-x0); } } // namespace detail /** @class PiecewiseLinearFunction @brief Models a piecewise linear function A piecewise linear function is fully defined by a set of pairs of coordinates, specifying values in the *domain* and the *image* of the function. This class permits various arithmetical operations, such as addition and subtraction, with piecewise linear functions and provides a number of other common operations. @tparam D Type of the *domain* of the function @tparam I Type of the *image* of the function */ template <class D, class I = D> class PiecewiseLinearFunction { public: using Domain = D; using Image = I; /** Creates an empty piecewise linear function */ PiecewiseLinearFunction() = default; /** Creates a new piecewise linear function from a range of values. The values must consist of pairs that are convertible to double. Duplicates are not permitted and will result in an exception being thrown. @param begin Input iterator to begin of range @param end Input iterator to end of range */ template <class InputIterator> PiecewiseLinearFunction( InputIterator begin, InputIterator end ) { for( InputIterator it = begin; it != end; ++it ) { auto x = it->first; auto y = it->second; bool success = false; std::tie( std::ignore, success ) = _data.insert( std::make_pair(x,y) ); if( !success ) throw std::runtime_error( "Duplicate value pairs not permitted for piecewise linear functions" ); } // Inserts new points whenever the function intersects the x-axis in // order to ensure that the integration procedure works. if( !_data.empty() ) this->insertIntersectionPoints(); } // Evaluation -------------------------------------------------------- /** Evaluates the piecewise linear function at a certain position. The function must not be evaluated beyond its domain. This will result in zeroes. For every other evaluation point, the function performs interpolation between the nearest values. @param x Coordinate at which to evaluate the function @returns Interpolated y value */ Image operator()( Domain x ) const noexcept { auto range = _data.equal_range( x ); auto begin = range.first; auto end = range.second; // Beyond the domain if( begin == _data.end() || end == _data.begin() ) return Image(); // One of the stored values else if( begin->first == x ) return begin->second; // Interpolation required auto right = begin; auto left = std::prev( begin ); return detail::lerp( x, left->first, left->second, right->first, right->second ); } // Operations -------------------------------------------------------- /** Calculates the sum of two piecewise linear functions */ PiecewiseLinearFunction& operator+=( const PiecewiseLinearFunction& rhs ) noexcept { return this->apply( rhs, std::plus<Image>() ); } /** Calculates the sum of two piecewise linear functions */ PiecewiseLinearFunction operator+( const PiecewiseLinearFunction& rhs ) const noexcept { auto lhs = *this; lhs += rhs; return lhs; } /** Adds a given value to all points in the image of the function */ PiecewiseLinearFunction operator+( Image lambda ) const noexcept { auto f = *this; return f.apply( lambda, std::plus<Image>() ); } /** Adds a given value to all points in the image of the function */ PiecewiseLinearFunction& operator+=( Image lambda ) const noexcept { return this->apply( lambda, std::plus<Image>() ); } /** Calculates the difference of two piecewise linear functions */ PiecewiseLinearFunction& operator-=( const PiecewiseLinearFunction& rhs ) noexcept { return this->apply( rhs, std::minus<Image>() ); } /** Calculates the difference of two piecewise linear functions */ PiecewiseLinearFunction operator-( const PiecewiseLinearFunction& rhs ) const noexcept { auto lhs = *this; lhs -= rhs; return lhs; } /** Unary minus: negates all values in the image of the piecewise linear function */ PiecewiseLinearFunction operator-() const noexcept { PiecewiseLinearFunction f; for( auto&& pair : _data ) f._data.insert( std::make_pair( pair.first, -pair.second ) ); return f; } /** Subtracts a given value from all points in the image of the function */ PiecewiseLinearFunction operator-( Image lambda ) const noexcept { auto f = *this; return f.apply( lambda, std::minus<Image>() ); } /** Subtracts a given value from all points in the image of the function */ PiecewiseLinearFunction& operator-=( Image lambda ) const noexcept { return this->apply( lambda, std::minus<Image>() ); } /** Multiplies the given piecewise linear function with a scalar value */ PiecewiseLinearFunction& operator*=( Image lambda ) noexcept { for( auto&& pair : _data ) pair.second *= lambda; return *this; } /** Multiplies the given piecewise linear function with a scalar value */ PiecewiseLinearFunction operator*( Image lambda ) const noexcept { auto f = *this; f *= lambda; return f; } /** Divides the given step function by a scalar value */ PiecewiseLinearFunction& operator/=( I lambda ) { if( lambda == I() ) throw std::runtime_error( "Attempted division by zero" ); return this->operator*=( 1/lambda ); } /** Divides the given step function by a scalar value */ PiecewiseLinearFunction operator/( I lambda ) const noexcept { auto f = *this; f /= lambda; return f; } // Queries ----------------------------------------------------------- /** Copies the domain values to an output iterator */ template <class OutputIterator> void domain( OutputIterator result ) const noexcept { for( auto&& pair : _data ) *result++ = pair.first; } /** Copies the image values to an output iterator */ template <class OutputIterator> void image( OutputIterator result ) const noexcept { for( auto&& pair : _data ) *result++ = pair.second; } /** Compares two piecewise linear functions. The functions are considered to be *equal* when the take the same values for the same interval. This method will evaluate the functions over *all* points of the domain. @param rhs Other function to compare against @returns true if both functions are equal, regardless of whether one of the functions has a subdivided range of values. */ bool operator==( const PiecewiseLinearFunction& rhs ) const noexcept { std::set<Domain> domain; this->domain( std::inserter( domain, domain.begin() ) ); rhs.domain( std::inserter( domain, domain.begin() ) ); bool result = true; for( auto&& x : domain ) { auto y0 = this->operator()( x ); auto y1 = rhs( x ); if( y0 != y1 ) return false; } return result; } /** Negates the comparison between two functions */ bool operator!=( const PiecewiseLinearFunction& rhs ) const noexcept { return !this->operator==( rhs ); } // Transformations --------------------------------------------------- /** Calculates the absolute value of the function */ PiecewiseLinearFunction& abs() noexcept { for( auto&& pair : _data ) pair.second = std::abs( pair.second ); return *this; } /** Calculates the maximum (supremum) of the function */ Image max() const noexcept { if( _data.empty() ) return Image(); auto max = std::numeric_limits<Image>::lowest(); for( auto&& pair : _data ) max = std::max( max, pair.second ); return max; } /** Calculates the supremum (maximum) of the function */ Image sup() const noexcept { return this->max(); } /** Calculates the integral over the (absolute value of the) function, raised to the \f$p\f$-th power. */ Image integral( Image p = Image(1) ) const noexcept { if( _data.empty() ) return Image(); // The Kahan summation ensures that small parts of the integral do // not disappear amidst the remaining values. KahanSummation<Image> norm = Image(); auto previous = _data.begin(); auto current = std::next( _data.begin() ); while( current != _data.end() ) { // Coefficients of the line that connect the previous point and the current // point. auto x1 = previous->first; auto y1 = previous->second; auto x2 = current->first; auto y2 = current->second; auto m = (y2 - y1) / (x2 - x1); auto c = y1 - m * x1; // Evaluator for the integral. This is an application of Cavalieri's // quadrature formula. auto evaluator = [&]( Image x ) { // Horizontal segments if( m == Image() ) return std::pow( c, p ) * x; // Regular lines else return std::pow( m*x + c, p+1 ) / ( m * (p+1) ); }; auto integral = std::abs( evaluator( x2 ) - evaluator( x1 ) ); norm += integral; previous = current; ++current; } return std::pow( norm, 1/p ); } private: /** Applies a binary operation to the current piecewise linear function and a given scalar. This is tantamount to *broadcasting* the result to a function that is entirely constant over a range of values. The operation does not require conversions or merges of the *domain* or the *range* of the input because only a scalar is involved. */ template <class BinaryOperation> PiecewiseLinearFunction& apply( Image lambda, BinaryOperation operation ) { for( auto&& pair : _data ) pair.second = operation( pair.second, lambda ); return *this; } /** Applies a binary operation to the current piecewise linear function and another function. To this, the domains of *both* functions will be merged, and the operation will be applied to their values, with a suitable interpolation scheme in place. @param other Second piecewise linear function @param operation Operation to apply to both functions @returns Reference to modified piecewise linear function. The original piecewise linear function ceases to exist. */ template <class BinaryOperation> PiecewiseLinearFunction& apply( const PiecewiseLinearFunction& other, BinaryOperation operation ) { std::set<Domain> xValues; for( auto&& pair : _data ) xValues.insert( pair.first ); for( auto&& pair : other._data ) xValues.insert( pair.first ); // Oherwise, the loop below will turn in an infinite loop since or // the validity of the `current` iterator would have to be checked // before-hand. if( xValues.empty() ) return *this; // Intersection handling. This is required to ensure that the combination of // the two functions contains shared segments. { // This closure checks whether two line segments intersect. If this is the // case, the intersection point needs to be stored as an additional point // in the set of values. auto intersection = []( Domain x0, Image y0, Domain x1, Image y1, Domain x2, Image y2, Domain x3, Image y3 ) { auto s1x = x1 - x0; auto s1y = y1 - y0; auto s2x = x3 - x2; auto s2y = y3 - y2; auto s = ( -s1y * (x0-x2) + s1x * (y0-y2) ) / ( -s2x * s1y + s1x * s2y ); auto t = ( s2x * (y0-y2) - s2y * (x0-x2) ) / ( -s2x * s1y + s1x * s2y ); if( s >= 0 && s <= 1 && t >= 0 && t <= 1 ) return x0 + t * s1x; return x0; }; std::set<Domain> intersections; auto current = xValues.begin(); auto next = std::next( current ); for( ; next != xValues.end(); ) { auto x0 = *current; auto x1 = *next; auto y0 = this->operator()( x0 ); auto y1 = this->operator()( x1 ); auto y2 = other( x0 ); auto y3 = other( x1 ); auto x = intersection( x0, y0, x1, y1, x0, y2, x1, y3 ); if( x != x0 ) intersections.insert( x ); current = next; next = std::next( current ); } xValues.insert( intersections.begin(), intersections.end() ); } // Apply the operation to all points ------------------------------- std::map<Domain, Image> data; for( auto&& x : xValues ) { auto y1 = this->operator()( x ); auto y2 = other( x ); data.insert( std::make_pair( x, operation( y1, y2 ) ) ); } _data.swap( data ); return *this; } /** Checks the segments of the piecewise linear function for intersections with the x-axis. In these cases, a new point needs to be inserted into the list of function values. Else, the integration procedure will not work because a segment might be considered to have an area of zero. The following example illustrates this problem: \verbatim /\ / \ --------- \ / \/ \endverbatim If the intersection in the middle is not being counted as a point on the PL function, the area of the corresponding segment will be zero. This is not the desired and expected behaviour. */ void insertIntersectionPoints() { auto current = _data.begin(); auto next = std::next( current ); std::set<Domain> intersections; for( ; next != _data.end(); ) { auto x0 = current->first; auto y0 = current->second; auto x1 = next->first; auto y1 = next->second; // We do not need to check the other cases. If either one of the values is // zero, we already have an intersection. if( y0 * y1 < Image() ) { auto m = ( y1 - y0 ) / ( x1 - x0 ); auto c = y0 - m * x0; auto x = - c / m; intersections.insert( x ); } current = next; next = std::next( current ); } for( auto&& x : intersections ) _data.insert( std::make_pair( x, Image() ) ); } /** Maps values in the domain to values in the image */ std::map<Domain, Image> _data; }; } // namespace math } // namespace aleph /** Multiplies a given piecewise linear function by a scalar value */ template <class D, class I, class T> aleph::math::PiecewiseLinearFunction<D, I> operator*( T lambda, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { return f * lambda; } /** Divides a given piecewise linear function by a scalar value */ template <class D, class I, class T> aleph::math::PiecewiseLinearFunction<D, I> operator/( T lambda, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { return f / lambda; } /** Output operator of a piecewise linear function. Permits printing the function values to an *output stream* in order to permit their usage by other functions and/or programs. */ template <class D, class I> std::ostream& operator<<( std::ostream& o, const aleph::math::PiecewiseLinearFunction<D, I>& f ) { std::vector<D> X; std::vector<I> Y; f.domain( std::back_inserter(X) ); f.image ( std::back_inserter(Y) ); assert( X.size() == Y.size() ); for( std::size_t i = 0; i < X.size() && i < Y.size(); i++ ) o << X[i] << "\t" << Y[i] << "\n"; return o; } #endif
28.131119
154
0.616369
[ "vector" ]
111103b80a46b472dce5c44d828f91ad46663958
46,726
cxx
C++
inetcore/urlmon/mon/mpxbsc.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetcore/urlmon/mon/mpxbsc.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetcore/urlmon/mon/mpxbsc.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1996. // // File: MPXBSC.CXX // // Contents: Code to handle multiplexing multiple concurrent // IBindStatusCallback interfaces. // // Classes: CBSCHolder // // Functions: // // History: 01-04-96 JoeS (Joe Souza) Created // 01-15-96 JohannP (Johann Posch) Modified to new IBSC // //---------------------------------------------------------------------------- #include <mon.h> #include "mpxbsc.hxx" PerfDbgTag(tagCBSCHolder, "Urlmon", "Log CBSCHolder", DEB_BINDING); HRESULT GetObjectParam(IBindCtx *pbc, LPOLESTR pszKey, REFIID riid, IUnknown **ppUnk); //+--------------------------------------------------------------------------- // // Function: UrlMonInvokeExceptionFilterMSN // // Synopsis: // // Arguments: [lCode] -- // [lpep] -- // // Returns: // // History: 8-25-97 DanpoZ(Danpo Zhang) Created // // Notes: // //---------------------------------------------------------------------------- LONG UrlMonInvokeExceptionFilterMSN( DWORD lCode, LPEXCEPTION_POINTERS lpep ) { DEBUG_ENTER((DBG_CALLBACK, Int, "UrlMonInvokeExceptionFilterMSN", "%#x, %#x", lCode, lpep )); #if DBG == 1 DbgLog2(tagCBSCHolder, NULL, "Exception 0x%#x at address 0x%#x", lCode, lpep->ExceptionRecord->ExceptionAddress); DebugBreak(); #endif LONG exr = EXCEPTION_CONTINUE_EXECUTION; if( lCode == STATUS_ACCESS_VIOLATION ) { char achProgname[256]; achProgname[0] = 0; GetModuleFileNameA(NULL,achProgname,sizeof(achProgname)); if( StrStrI(achProgname, "msnviewr.exe") ) { exr = EXCEPTION_EXECUTE_HANDLER; } } DEBUG_LEAVE(exr); return exr; } //+--------------------------------------------------------------------------- // // Function: GetBSCHolder // // Synopsis: Returns a holder for IBindStatusCallback // // Arguments: [pBC] -- // [ppCBSHolder] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT GetBSCHolder(LPBC pBC, CBSCHolder **ppCBSHolder) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "GetBSCHolder", "%#x, %#x", pBC, ppCBSHolder )); PerfDbgLog(tagCBSCHolder, NULL, "+GetBSCHolder"); UrlMkAssert((ppCBSHolder != NULL)); HRESULT hr; CBSCHolder *pCBSCBHolder = NULL; hr = GetObjectParam(pBC, REG_BSCB_HOLDER, IID_IBindStatusCallbackHolder, (IUnknown **)&pCBSCBHolder); if (pCBSCBHolder == NULL) { pCBSCBHolder = new CBSCHolder; if (!pCBSCBHolder) { hr = E_OUTOFMEMORY; } else { hr = pBC->RegisterObjectParam(REG_BSCB_HOLDER, (IBindStatusCallback *) pCBSCBHolder); *ppCBSHolder = pCBSCBHolder; } } else { *ppCBSHolder = pCBSCBHolder; } PerfDbgLog1(tagCBSCHolder, NULL, "-GetBSCHolder (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } CBSCHolder::CBSCHolder(void) : _CRefs(), _cElements(0) { DEBUG_ENTER((DBG_CALLBACK, None, "CBSCHolder::CBSCHolder", "this=%#x", this )); _pCBSCNode = NULL; _fBindStarted = FALSE; _fBindStopped = FALSE; _fHttpNegotiate = FALSE; _fAuthenticate = FALSE; _fHttpNegotiate2 = FALSE; DEBUG_LEAVE(0); } CBSCHolder::~CBSCHolder(void) { DEBUG_ENTER((DBG_CALLBACK, None, "CBSCHolder::~CBSCHolder", "this=%#x", this )); CBSCNode *pNode, *pNextNode; pNode = _pCBSCNode; while (pNode) { pNextNode = pNode->GetNextNode(); delete pNode; pNode = pNextNode; } DEBUG_LEAVE(0); } STDMETHODIMP CBSCHolder::QueryInterface(REFIID riid, void **ppvObj) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IUnknown::QueryInterface", "this=%#x, %#x, %#x", this, &riid, ppvObj )); VDATEPTROUT(ppvObj, void *); VDATETHIS(this); HRESULT hr = NOERROR; PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::QueryInterface"); if ( (riid == IID_IUnknown) || (riid == IID_IBindStatusCallback) || (riid == IID_IBindStatusCallbackHolder) ) { // the holder is not marshalled!! *ppvObj = (void*)(IBindStatusCallback *) this; } else if (riid == IID_IServiceProvider) { *ppvObj = (void*)(IServiceProvider *) this; } else if (riid == IID_IHttpNegotiate) { *ppvObj = (void*)(IHttpNegotiate *) this; } else if (riid == IID_IHttpNegotiate2) { *ppvObj = (void*)(IHttpNegotiate2 *) this; } else if (riid == IID_IAuthenticate) { *ppvObj = (void*)(IAuthenticate *) this; } else { *ppvObj = NULL; hr = E_NOINTERFACE; } if (hr == NOERROR) { AddRef(); } PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::QueryInterface (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } STDMETHODIMP_(ULONG) CBSCHolder::AddRef(void) { DEBUG_ENTER((DBG_CALLBACK, Dword, "CBSCHolder::IUnknown::AddRef", "this=%#x", this )); LONG lRet = ++_CRefs; PerfDbgLog1(tagCBSCHolder, this, "CBSCHolder::AddRef (cRefs:%ld)", lRet); DEBUG_LEAVE(lRet); return lRet; } STDMETHODIMP_(ULONG) CBSCHolder::Release(void) { DEBUG_ENTER((DBG_CALLBACK, Dword, "CBSCHolder::IUnknown::Release", "this=%#x", this )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::Release"); UrlMkAssert((_CRefs > 0)); LONG lRet = --_CRefs; if (_CRefs == 0) { delete this; } PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::Release (cRefs:%ld)",lRet); DEBUG_LEAVE(lRet); return lRet; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::GetBindInfo // // Synopsis: // // Arguments: [grfBINDINFOF] -- // [pbindinfo] -- // // Returns: // // History: // // Notes: Only the first BSC which also receives data gets called // //---------------------------------------------------------------------------- HRESULT CBSCHolder::GetBindInfo(DWORD *grfBINDINFOF,BINDINFO * pbindinfo) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IBindStatusCallback::GetBindInfo", "this=%#x, %#x, %#x", this, grfBINDINFOF, pbindinfo )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::GetBindInfo"); HRESULT hr = E_FAIL; CBSCNode *pNode; pNode = _pCBSCNode; if (pNode && (pNode->GetFlags() & BSCO_GETBINDINFO)) { UrlMkAssert(( pbindinfo && (pbindinfo->cbSize == sizeof(BINDINFO)) )); DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IBindStatusCallback::GetBindInfo", "this=%#x, %#x, %#x", pNode->GetBSCB(), grfBINDINFOF, pbindinfo )); // We only call the first link for GetBindInfo. hr = pNode->GetBSCB()->GetBindInfo(grfBINDINFOF, pbindinfo); DEBUG_LEAVE(hr); } else { UrlMkAssert((FALSE && "Not IBSC node called on GetBindInfo")); } PerfDbgLog2(tagCBSCHolder, this, "-CBSCHolder::CallGetBindInfo (grfBINDINFOF:%lx, hr:%lx)", grfBINDINFOF, hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::OnStartBinding // // Synopsis: // // Arguments: [grfBINDINFOF] -- // [pib] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::OnStartBinding(DWORD grfBINDINFOF, IBinding * pib) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IBindStatusCallback::OnStartBinding", "this=%#x, %#x, %#x", this, grfBINDINFOF, pib )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::OnStartBinding"); VDATETHIS(this); HRESULT hr = E_FAIL; CBSCNode *pNode; BOOL fFirstNode = TRUE; _fBindStarted = TRUE; pNode = _pCBSCNode; while (pNode) { grfBINDINFOF = pNode->GetFlags(); if (fFirstNode) { grfBINDINFOF |= (BSCO_ONDATAAVAILABLE | BSCO_ONOBJECTAVAILABLE); } else { grfBINDINFOF &= ~(BSCO_ONDATAAVAILABLE | BSCO_ONOBJECTAVAILABLE); } DbgLog1(tagCBSCHolder, this, "CBSCHolder::OnStartBinding on (IBSC:%lx)", pNode->GetBSCB()); DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IBindStatusCallback::OnStartBinding", "this=%#x, %#x, %#x", pNode->GetBSCB(), grfBINDINFOF, pib )); hr = pNode->GetBSCB()->OnStartBinding(grfBINDINFOF, pib); DEBUG_LEAVE(hr); pNode = pNode->GetNextNode(); fFirstNode = FALSE; } // BUGBUG: hr is set to return code only from last node we called. // Is this what we want? // What if one of the earlier nodes failed? PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::OnStartBinding (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::OnProgress // // Synopsis: // // Arguments: [ULONG] -- // [ulProgressMax] -- // [ulStatusCode] -- // [szStatusText] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::OnProgress(ULONG ulProgress,ULONG ulProgressMax, ULONG ulStatusCode, LPCWSTR szStatusText) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IBindStatusCallback::OnProgress", "this=%#x, %#x, %#x, %#x, %.80wq", this, ulProgress, ulProgressMax, ulStatusCode, szStatusText )); PerfDbgLog4(tagCBSCHolder, this, "+CBSCHolder::OnProgress (StatusCode:%ld, StatusText:%ws, Progress:%ld, ProgressMax:%ld)", ulStatusCode, szStatusText?szStatusText:L"", ulProgress, ulProgressMax); VDATETHIS(this); HRESULT hr = NOERROR; CBSCNode *pNode; pNode = _pCBSCNode; while (pNode) { if (pNode->GetFlags() & BSCO_ONPROGRESS) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IBindStatusCallback::OnProgress", "this=%#x, %#x, %#x, %#x, %.80wq", pNode->GetBSCB(), ulProgress, ulProgressMax, ulStatusCode, szStatusText )); hr = pNode->GetBSCB()->OnProgress(ulProgress, ulProgressMax, ulStatusCode,szStatusText); DEBUG_LEAVE(hr); } pNode = pNode->GetNextNode(); } // BUGBUG: hr is set to return code only from last node we called. // Is this what we want? // What if one of the earlier nodes failed? PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::OnProgress (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::OnDataAvailable // // Synopsis: // // Arguments: [DWORD] -- // [FORMATETC] -- // [pformatetc] -- // [pstgmed] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::OnDataAvailable(DWORD grfBSC,DWORD dwSize,FORMATETC *pformatetc, STGMEDIUM *pstgmed) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IBindStatusCallback::OnDataAvailable", "this=%#x, %#x, %#x, %#x, %#x", this, grfBSC, dwSize, pformatetc, pstgmed )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::OnDataAvailable"); VDATETHIS(this); HRESULT hr = E_FAIL; CBSCNode *pNode; pNode = _pCBSCNode; if (pNode && (pNode->GetFlags() & BSCO_ONDATAAVAILABLE)) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IBindStatusCallback::OnDataAvailable", "this=%#x, %#x, %#x, %#x, %#x", pNode->GetBSCB(), grfBSC, dwSize, pformatetc, pstgmed )); hr = pNode->GetBSCB()->OnDataAvailable(grfBSC, dwSize, pformatetc, pstgmed); DEBUG_LEAVE(hr); //hr = NOERROR; //Trident BTS->BTO } PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::OnDataAvailable (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::OnObjectAvailable // // Synopsis: // // Arguments: [riid] -- // [punk] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::OnObjectAvailable(REFIID riid, IUnknown *punk) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IBindStatusCallback::OnObjectAvailable", "this=%#x, %#x, %#x", this, &riid, punk )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::OnObjectAvailable"); VDATETHIS(this); CBSCNode *pNode; pNode = _pCBSCNode; if (pNode && (pNode->GetFlags() & BSCO_ONOBJECTAVAILABLE)) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IBindStatusCallback::OnObjectAvailable", "this=%#x, %#x, %#x", pNode->GetBSCB(), &riid, punk )); HRESULT hr = pNode->GetBSCB()->OnObjectAvailable(riid, punk); DEBUG_LEAVE(hr); } PerfDbgLog(tagCBSCHolder, this, "-CBSCHolder::OnObjectAvailable (hr:0)"); DEBUG_LEAVE(NOERROR); return NOERROR; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::OnLowResource // // Synopsis: // // Arguments: [reserved] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::OnLowResource(DWORD reserved) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IBindStatusCallback::OnLowResource", "this=%#x, %#x", this, reserved )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::OnLowResource"); VDATETHIS(this); HRESULT hr = E_FAIL; CBSCNode *pNode; pNode = _pCBSCNode; while (pNode) { if (pNode->GetFlags() & BSCO_ONLOWRESOURCE) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IBindStatusCallback::OnLowResource", "this=%#x, %#x", pNode->GetBSCB(), reserved )); hr = pNode->GetBSCB()->OnLowResource(reserved); DEBUG_LEAVE(hr); } pNode = pNode->GetNextNode(); } // BUGBUG: hr is set to return code only from last node we called. // Is this what we want? // What if one of the earlier nodes failed? PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::OnLowResource (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::OnStopBinding // // Synopsis: // // Arguments: [LPCWSTR] -- // [szError] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::OnStopBinding(HRESULT hrRes,LPCWSTR szError) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IBindStatusCallback::OnStopBinding", "this=%#x, %#x, %.80wq", this, hrRes, szError )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::OnStopBinding"); HRESULT hr = E_FAIL; CBSCNode *pNode; CBSCNode *pNodeNext; DWORD dwFault; VDATETHIS(this); _fBindStopped = TRUE; // Allow consumer to remove node on OnStopBinding. pNode = _pCBSCNode; while (pNode) { // save the next node since this node // we using now might get deleted // by RevokeBindStatusCallback pNodeNext = pNode->GetNextNode(); pNode->SetLocalFlags(NODE_FLAG_REMOVEOK); PerfDbgLog2(tagCBSCHolder, this, "+CBSCHolder::OnStopBinding calling (Node:%lx, IBSC:%lx)", pNode,pNode->GetBSCB()); // IE4 bug #32739, the CBSC might no longer be there (MSN) _try { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IBindStatusCallback::OnStopBinding", "this=%#x, %#x, %.80wq", pNode->GetBSCB(), hrRes, szError )); hr = pNode->GetBSCB()->OnStopBinding(hrRes, szError); DEBUG_LEAVE(hr); } //_except(UrlMonInvokeExceptionFilterMSN(GetExceptionCode(), GetExceptionInformation())) __except(EXCEPTION_EXECUTE_HANDLER) { DEBUG_LEAVE(hr); #if DBG == 1 { dwFault = GetExceptionCode(); DbgLog1(tagCBSCHolder, this, "fault 0x%08x at OnStopBinding", dwFault); } #endif } #ifdef unix __endexcept #endif /* unix */ PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::OnStopBinding done (Node:%lx)", pNode); pNode = pNodeNext; } // Reset bind active flags. _fBindStarted = FALSE; _fBindStopped = FALSE; // BUGBUG: hr is set to return code only from last node we called. // Is this what we want? // What if one of the earlier nodes failed? PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::OnStopBinding (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::GetPriority // // Synopsis: // // Arguments: [pnPriority] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::GetPriority(LONG * pnPriority) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IBindStatusCallback::GetPriority", "this=%#x, %#x", this, pnPriority )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::GetPriority"); HRESULT hr = E_FAIL; CBSCNode *pNode; pNode = _pCBSCNode; if (pNode && (pNode->GetFlags() & BSCO_GETPRIORITY)) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IBindStatusCallback::GetPriority", "this=%#x, %#x", pNode->GetBSCB(), pnPriority )); hr = pNode->GetBSCB()->GetPriority(pnPriority); DEBUG_LEAVE(hr); } PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::GetPriority (hr:%lx)", hr); DEBUG_LEAVE(S_FALSE); return S_FALSE; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::QueryService // // Synopsis: // // Arguments: [rsid] -- // [iid] -- // [ppvObj] -- // // Returns: // // History: 4-05-96 JohannP (Johann Posch) Created // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::QueryService(REFGUID rsid, REFIID riid, void ** ppvObj) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IServiceProvider::QueryService", "this=%#x, %#x, %#x, %#x", this, &rsid, &riid, ppvObj )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::QueryService"); HRESULT hr = NOERROR; VDATETHIS(this); UrlMkAssert((ppvObj)); *ppvObj = 0; hr = ObtainService(rsid, riid, ppvObj); UrlMkAssert(( (hr == E_NOINTERFACE) || ((hr == NOERROR) && *ppvObj) )); PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::QueryService (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::BeginningTransaction // // Synopsis: // // Arguments: [szURL] -- // [szHeaders] -- // [dwReserved] -- // [pszAdditionalHeaders] -- // // Returns: // // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::BeginningTransaction(LPCWSTR szURL, LPCWSTR szHeaders, DWORD dwReserved, LPWSTR *pszAdditionalHeaders) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IHttpNegotiate::BeginningTransaction", "this=%#x, %.80wq, %.80wq, %#x, %#x", this, szURL, szHeaders, dwReserved, pszAdditionalHeaders )); PerfDbgLog2(tagCBSCHolder, this, "+CBSCHolder::BeginningTransaction (szURL:%ws, szHeaders:%ws)", szURL, XDBG(szHeaders,"")); VDATETHIS(this); HRESULT hr = NOERROR; CBSCNode *pNode; LPWSTR szTmp = NULL, szNew = NULL, szRunning = NULL; pNode = _pCBSCNode; UrlMkAssert((szURL)); while (pNode) { if (pNode->GetHttpNegotiate()) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IHttpNegotiate::BeginningTransaction", "this=%#x, %.80wq, %.80wq, %#x, %#x", pNode->GetHttpNegotiate(), szURL, szHeaders, dwReserved, pszAdditionalHeaders )); hr = pNode->GetHttpNegotiate()->BeginningTransaction(szURL, szHeaders, dwReserved, &szNew); DEBUG_LEAVE(hr); PerfDbgLog2(tagCBSCHolder, this, "CBSCHolder::BeginningTransaction (IHttpNegotiate:%lx, szNew:%ws)", pNode->GetHttpNegotiate(), XDBG(szNew,L"")); // shdocvw might return uninitialized hr, so we // should just check for szNew not NULL and reset hr if( hr != NOERROR && szNew != NULL ) { hr = NOERROR; } if (hr == NOERROR && szNew != NULL && szRunning != NULL) { szTmp = szRunning; szRunning = new WCHAR [wcslen(szTmp) + 1 + wcslen(szNew) + 1]; if (szRunning) { if (szTmp) { wcscpy(szRunning, szTmp); wcscat(szRunning, szNew); } else { wcscpy(szRunning, szNew); } } else { hr = E_OUTOFMEMORY; } delete szTmp; delete szNew; if (hr != NOERROR) { goto BegTransExit; } } else { szRunning = szNew; } } pNode = pNode->GetNextNode(); } *pszAdditionalHeaders = szRunning; BegTransExit: PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::BeginningTransaction (pszAdditionalHeaders:%ws)", (hr || !*pszAdditionalHeaders) ? L"":*pszAdditionalHeaders); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::OnResponse // // Synopsis: // // Arguments: [LPCWSTR] -- // [szResponseHeaders] -- // [LPWSTR] -- // [pszAdditionalRequestHeaders] -- // // Returns: // // History: 4-05-96 JohannP (Johann Posch) Created // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::OnResponse(DWORD dwResponseCode,LPCWSTR wzResponseHeaders, LPCWSTR wzRequestHeaders,LPWSTR *pszAdditionalRequestHeaders) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IHttpNegotiate::OnResponse", "this=%#x, %#x, %.80wq, %.80wq, %#x", this, dwResponseCode, wzResponseHeaders, wzRequestHeaders, pszAdditionalRequestHeaders )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::OnResponse"); VDATETHIS(this); HRESULT hr; CBSCNode *pNode; LPWSTR szTmp = NULL, szNew = NULL, szRunning = NULL; pNode = _pCBSCNode; hr = (IsStatusOk(dwResponseCode)) ? S_OK : S_FALSE; while (pNode) { if (pNode->GetHttpNegotiate()) { PerfDbgLog1(tagCBSCHolder, this, "+CBSCHolder::OnResponse on Node: %lx", pNode); DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IHttpNegotiate::OnResponse", "this=%#x, %#x, %.80wq, %.80wq, %#x", pNode->GetHttpNegotiate(), dwResponseCode, wzResponseHeaders, wzRequestHeaders, pszAdditionalRequestHeaders )); hr = pNode->GetHttpNegotiate()->OnResponse(dwResponseCode, wzResponseHeaders, wzRequestHeaders, &szNew); DEBUG_LEAVE(hr); PerfDbgLog2(tagCBSCHolder, this, "-CBSCHolder::OnResponse on Node: %lx, hr:%lx", pNode, hr); if (hr == NOERROR && szNew != NULL && szRunning != NULL) { szTmp = szRunning; szRunning = new WCHAR [wcslen(szTmp) + 1 + wcslen(szNew) + 1]; if (szRunning) { if (szTmp) { wcscpy(szRunning, szTmp); wcscat(szRunning, szNew); } else { wcscpy(szRunning, szNew); } } else { hr = E_OUTOFMEMORY; } delete szTmp; delete szNew; if (hr != NOERROR) { goto OnErrorExit; } } else { szRunning = szNew; } } pNode = pNode->GetNextNode(); } if (pszAdditionalRequestHeaders) { *pszAdditionalRequestHeaders = szRunning; } if (hr == E_NOTIMPL) { hr = NOERROR; } OnErrorExit: PerfDbgLog(tagCBSCHolder, this, "-CBSCHolder::OnResponse"); DEBUG_LEAVE(hr); return hr; } HRESULT CBSCHolder::GetRootSecurityId(BYTE* pbSecurityId, DWORD* cbSecurityId, DWORD_PTR dwReserved) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IHttpNegotiate2::GetRootSecurityId", "this=%#x, %#x, %#x, %#x", this, pbSecurityId, cbSecurityId, dwReserved )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::GetRootSecurityId"); VDATETHIS(this); HRESULT hr = E_FAIL; CBSCNode *pNode; pNode = _pCBSCNode; while (pNode) { if (pNode->GetHttpNegotiate2()) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IHttpNegotiate2::GetRootSecurityId", "this=%#x, %#x, %#x, %#x", pNode->GetHttpNegotiate2(), pbSecurityId, cbSecurityId, dwReserved )); hr = pNode->GetHttpNegotiate2()->GetRootSecurityId( pbSecurityId, cbSecurityId, dwReserved ); DEBUG_LEAVE(hr); if (SUCCEEDED(hr)) { break; } } pNode = pNode->GetNextNode(); } PerfDbgLog(tagCBSCHolder, this, "-CBSCHolder::Authenticate"); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::Authenticate // // Synopsis: // // Arguments: [phwnd] -- // [pszUsername] -- // [pszPassword] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::Authenticate(HWND* phwnd, LPWSTR *pszUsername, LPWSTR *pszPassword) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::IAuthenticate::Authenticate", "this=%#x, %#x, %#x, %#x", this, phwnd, pszUsername, pszPassword )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::Authenticate"); VDATETHIS(this); HRESULT hr = NOERROR; CBSCNode *pNode; pNode = _pCBSCNode; while (pNode) { if (pNode->GetAuthenticate()) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "EXTERNAL_CLIENT::IAuthenticate::Authenticate", "this=%#x, %#x, %#x, %#x", pNode->GetAuthenticate(), phwnd, pszUsername, pszPassword )); hr = pNode->GetAuthenticate()->Authenticate(phwnd, pszUsername, pszPassword); DEBUG_LEAVE(hr); if (hr == S_OK) { break; } } pNode = pNode->GetNextNode(); } PerfDbgLog(tagCBSCHolder, this, "-CBSCHolder::Authenticate"); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::AddNode // // Synopsis: // // Arguments: [pIBSC] -- // [grfFlags] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::AddNode(IBindStatusCallback *pIBSC, DWORD grfFlags) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::AddNode", "this=%#x, %#x, %#x", this, pIBSC, grfFlags )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::AddNode"); HRESULT hr = NOERROR; CLock lck(_mxs); CBSCNode *pFirstNode = _pCBSCNode; CBSCNode *pNode; CBSCNode *pNodeTmp; LPVOID pvLocal = NULL; // No new nodes allowed after binding has started. if (_fBindStarted) { hr = E_FAIL; goto AddNodeExit; } // Allocate memory for new pNode member. pNode = new CBSCNode(pIBSC, grfFlags); if (!pNode) { hr = E_OUTOFMEMORY; } else { // addref the IBSC pointer pIBSC->AddRef(); // QI for IServiceProvider - QI addref IBSC if (pIBSC->QueryInterface(IID_IServiceProvider, &pvLocal) == NOERROR) { pNode->SetServiceProvider((IServiceProvider *)pvLocal); } PerfDbgLog3(tagCBSCHolder, this, "CBSCHolder::AddNode (New Node:%lx, IBSC:%lx, IServiceProvider:%lx)", pNode, pNode->GetBSCB(), pvLocal); // If we have a node already if (pFirstNode) { if (pNode->GetFlags() & BSCO_ONDATAAVAILABLE) { // If the new node gets the data, link it first. pNode->SetNextNode(pFirstNode); _pCBSCNode = pNode; } else { // The new node does not get data, link it second in list. pNodeTmp = pFirstNode->GetNextNode(); pFirstNode->SetNextNode(pNode); pNode->SetNextNode(pNodeTmp); } } else { _pCBSCNode = pNode; } _cElements++; } AddNodeExit: PerfDbgLog2(tagCBSCHolder, this, "-CBSCHolder::AddNode (NewNode:%lx, hr:%lx)", pNode, hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::RemoveNode // // Synopsis: // // Arguments: [pIBSC] -- // // Returns: // // History: // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::RemoveNode(IBindStatusCallback *pIBSC) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::RemoveNode", "this=%#x, %#x", this, pIBSC )); PerfDbgLog1(tagCBSCHolder, this, "+CBSCHolder::RemoveNode (IBSC:%lx)", pIBSC); HRESULT hr = E_FAIL; CLock lck(_mxs); CBSCNode *pNextNode = NULL; CBSCNode *pPrevNode = _pCBSCNode; // If binding has started, removal of nodes not allowed until binding stops. if (_fBindStarted && !_fBindStopped) { UrlMkAssert((FALSE && "IBSC in use - can not be revoked")); goto RemoveNodeExit; } if (pPrevNode) { pNextNode = pPrevNode->GetNextNode(); } else { TransAssert((_cElements == 0)); hr = S_FALSE; goto RemoveNodeExit; } if (_pCBSCNode->GetBSCB() == pIBSC) { UrlMkAssert((_pCBSCNode->GetBSCB() == pIBSC)); if (!_fBindStarted || _pCBSCNode->CheckLocalFlags(NODE_FLAG_REMOVEOK)) { PerfDbgLog2(tagCBSCHolder, this, "CBSCHolder::RemoveNode (Delete Node:%lx, IBSC:%lx)", _pCBSCNode, _pCBSCNode->GetBSCB()); // release all obtained objects in the disdructor delete _pCBSCNode; _pCBSCNode = pNextNode; _cElements--; if (_cElements == 0) { hr = S_FALSE; } else { hr = S_OK; } } } else while (pNextNode) { PerfDbgLog2(tagCBSCHolder, this, "CBSCHolder::RemoveNode (pNextNode:%lx, pNextNode->pIBSC:%lx)",pNextNode,pNextNode->GetBSCB()); if (pNextNode->GetBSCB() == pIBSC && (!_fBindStarted || pNextNode->CheckLocalFlags(NODE_FLAG_REMOVEOK))) { //we found the Node if (pPrevNode) { pPrevNode->SetNextNode(pNextNode->GetNextNode()); } PerfDbgLog2(tagCBSCHolder, this, "CBSCHolder::RemoveNode (Delete Node:%lx, IBSC:%lx)", pNextNode,pNextNode->GetBSCB()); // release all obtained objects in the disdructor delete pNextNode; hr = S_OK; _cElements--; UrlMkAssert((_cElements > 0)); break; } else { pPrevNode = pNextNode; pNextNode = pNextNode->GetNextNode(); } UrlMkAssert((hr == S_OK && "Node not found")); } RemoveNodeExit: PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::RemoveNode (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::SetMainNode // // Synopsis: // // Arguments: [pIBSC] -- // [ppIBSCPrev] -- // // Returns: // // History: 5-08-96 JohannP (Johann Posch) Created // // Notes: // //---------------------------------------------------------------------------- HRESULT CBSCHolder::SetMainNode(IBindStatusCallback *pIBSC, IBindStatusCallback **ppIBSCPrev) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::SetMainNode", "this=%#x, %#x, #x", this, pIBSC, ppIBSCPrev )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::SetMainNode"); HRESULT hr = NOERROR; CLock lck(_mxs); CBSCNode *pFirstNode = _pCBSCNode; CBSCNode *pNode; CBSCNode *pNodeTmp; LPVOID pvLocal = NULL; // No new nodes allowed after binding has started. if (_fBindStarted) { hr = E_FAIL; goto GetFirsNodeExit; } if (pFirstNode) { IBindStatusCallback *pBSC = pFirstNode->GetBSCB(); // addref the node here and return it if (ppIBSCPrev) { pBSC->AddRef(); *ppIBSCPrev = pBSC; } hr = RemoveNode(pBSC); } pFirstNode = _pCBSCNode; // Allocate memory for new pNode member. pNode = new CBSCNode(pIBSC, BSCO_ALLONIBSC); if (!pNode) { hr = E_OUTOFMEMORY; } else { // addref the IBSC pointer pIBSC->AddRef(); hr = NOERROR; // QI for IServiceProvider - QI addref IBSC if (pIBSC->QueryInterface(IID_IServiceProvider, &pvLocal) == NOERROR) { pNode->SetServiceProvider((IServiceProvider *)pvLocal); } PerfDbgLog3(tagCBSCHolder, this, "CBSCHolder::SetMainNode (New Node:%lx, IBSC:%lx, IServiceProvider:%lx)", pNode, pNode->GetBSCB(), pvLocal); // If we have a node already if (pFirstNode) { if (pNode->GetFlags() & BSCO_ONDATAAVAILABLE) { // If the new node gets the data, link it first. pNode->SetNextNode(pFirstNode); _pCBSCNode = pNode; } else { // The new node does not get data, link it second in list. pNodeTmp = pFirstNode->GetNextNode(); pFirstNode->SetNextNode(pNode); pNode->SetNextNode(pNodeTmp); } } else { _pCBSCNode = pNode; } _cElements++; } GetFirsNodeExit: PerfDbgLog2(tagCBSCHolder, this, "-CBSCHolder::SetMainNode (NewNode:%lx, hr:%lx)", pNode, hr); DEBUG_LEAVE(hr); return hr; } //+--------------------------------------------------------------------------- // // Method: CBSCHolder::ObtainService // // Synopsis: Retrieves the requested service with QI and QueryService // for all nodes. The interfaces is addref'd and kept in the node. // // Arguments: [rsid] -- // [riid] -- // // Returns: // // History: 4-09-96 JohannP (Johann Posch) Created // // Notes: The obtained interfaces are released in the disdructor of the // CNode. // //---------------------------------------------------------------------------- HRESULT CBSCHolder::ObtainService(REFGUID rsid, REFIID riid, void ** ppvObj) { DEBUG_ENTER((DBG_CALLBACK, Hresult, "CBSCHolder::ObtainService", "this=%#x, %#x, #x, %#x", this, &rsid, &riid, ppvObj )); PerfDbgLog(tagCBSCHolder, this, "+CBSCHolder::ObtainService"); HRESULT hr = NOERROR; CBSCNode *pNode; VDATETHIS(this); LPVOID pvLocal = NULL; pNode = _pCBSCNode; // the old code was under the assumption that rsid was always the same // as riid. it checked riid when it should have been checking rsid, and it // always passed riid on in the place of rsid! All callers that I've // seen that use IID_IHttpNegotiate and IID_IAuthenticate pass the // same iid in both rsid and riid, so fixing this should be safe. if (rsid == IID_IHttpNegotiate) { *ppvObj = (void*)(IHttpNegotiate *) this; AddRef(); // loop once to get all interfaces if (!_fHttpNegotiate) { while (pNode) { if ( (pNode->GetBSCB()->QueryInterface(riid, &pvLocal) == NOERROR) || ( pNode->GetServiceProvider() && (pNode->GetHttpNegotiate() == NULL) && (pNode->GetServiceProvider()->QueryService(rsid, riid, &pvLocal)) == NOERROR) ) { // Note: the interface is addref'd by QI or QS pNode->SetHttpNegotiate((IHttpNegotiate *)pvLocal); } pNode = pNode->GetNextNode(); } _fHttpNegotiate = TRUE; } } else if (rsid == IID_IAuthenticate) { *ppvObj = (void*)(IAuthenticate *) this; AddRef(); if (!_fAuthenticate) { while (pNode) { if ( (pNode->GetBSCB()->QueryInterface(riid, &pvLocal) == NOERROR) || ( pNode->GetServiceProvider() && (pNode->GetAuthenticate() == NULL) && (pNode->GetServiceProvider()->QueryService(rsid, riid, &pvLocal)) == NOERROR) ) { // Note: the interface is addref'd by QI or QS pNode->SetAuthenticate((IAuthenticate *)pvLocal); } pNode = pNode->GetNextNode(); } _fAuthenticate = TRUE; } } else if (rsid == IID_IHttpNegotiate2) { *ppvObj = (void*)(IHttpNegotiate2 *) this; AddRef(); // loop once to get all interfaces if (!_fHttpNegotiate2) { while (pNode) { if ( (pNode->GetBSCB()->QueryInterface(riid, &pvLocal) == NOERROR) || ( pNode->GetServiceProvider() && (pNode->GetHttpNegotiate2() == NULL) && (pNode->GetServiceProvider()->QueryService(rsid, riid, &pvLocal)) == NOERROR) ) { // Note: the interface is addref'd by QI or QS pNode->SetHttpNegotiate2((IHttpNegotiate2 *)pvLocal); } pNode = pNode->GetNextNode(); } _fHttpNegotiate2 = TRUE; } } else { *ppvObj = NULL; hr = E_NOINTERFACE; while (pNode) { // old urlmon code did a QueryInterface on this object (CBSCHolder) // without regard to rsid. That's QueryService badness, but CINet // (and several other places) call QueryService using the same rsid/riid // (in this case IID_IHttpSecurity) and *expect* the below QI to pick // the interface off the BSCB. We should create an URLMON service id // that means "ask the BSCB for this interface" and use that... if ( (pNode->GetBSCB()->QueryInterface(riid, &pvLocal) == NOERROR) || (pNode->GetServiceProvider() && (pNode->GetServiceProvider()->QueryService(rsid, riid, &pvLocal)) == NOERROR) ) { *ppvObj = pvLocal; hr = NOERROR; // Note: the interface is addref'd by QI or QS // stop looking at other nodes for this service pNode = NULL; } if (pNode) { pNode = pNode->GetNextNode(); } } } PerfDbgLog1(tagCBSCHolder, this, "-CBSCHolder::ObtainService (hr:%lx)", hr); DEBUG_LEAVE(hr); return hr; }
28.526252
162
0.464731
[ "object" ]
11143fda5eeb9d376fc93d8b850d9df80c42cefa
2,342
cpp
C++
leetcode/30_days_challenge/2020_9_September/day4.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
1
2020-05-05T13:06:51.000Z
2020-05-05T13:06:51.000Z
leetcode/30_days_challenge/2020_9_September/day4.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
leetcode/30_days_challenge/2020_9_September/day4.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
/**************************************************** Date: Sept 4th link: https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/554/week-1-september-1st-september-7th/3448/ ****************************************************/ #include <iostream> #include <vector> #include <list> #include <algorithm> #include <string> #include <stack> #include <queue> #include <map> #include <unordered_map> #include <unordered_set> #include <cmath> #include <limits.h> using namespace std; /* Q: Partition Labels A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts. Example 1: Input: S = "ababcbacadefegdehijhklij" Output: [9,7,8] Explanation: The partition is "ababcbaca", "defegde", "hijhklij". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts. Note: S will have length in range [1, 500]. S will consist of lowercase English letters ('a' to 'z') only. */ class Solution { public: vector<int> partitionLabels(string S) { vector<int> freq(26, 0); for (int l : S) { freq[l - 'a']++; } int l = S.size(); vector<int> ans; vector<int> p; unordered_set<int> str; for (int i = 0; i < l; ++i) { int ch = S[i]; if (str.size() == 0 && i > 0) { if (p.size() > 0) { ans.push_back(i - p.back()); } else { ans.push_back(i); } p.push_back(i); } freq[ch - 'a']--; if (freq[ch - 'a'] == 0) { str.erase(ch); } else { str.insert(ch); } } if (p.size() > 0) { ans.push_back(l - p.back()); } else { ans.push_back(l); } return ans; } };
24.395833
125
0.474808
[ "vector" ]
11226e1f05b7bb66f1d91051ab8a156b7c543ed9
52,444
cpp
C++
admin/pchealth/client/common/fhclicfg/fhclicfg.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/pchealth/client/common/fhclicfg/fhclicfg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/pchealth/client/common/fhclicfg/fhclicfg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/****************************************************************************** Copyright (c) 2000 Microsoft Corporation Module Name: fhclicfg.cpp Abstract: Client configuration class Revision History: created derekm 03/31/00 ******************************************************************************/ #include "stdafx.h" #include "pfrcfg.h" #include <strsafe.h> // allow the configuration to be settable #define ENABLE_SRV_CONFIG_SETTING 1 ///////////////////////////////////////////////////////////////////////////// // tracing #ifdef THIS_FILE #undef THIS_FILE #endif static char __szTraceSourceFile[] = __FILE__; #define THIS_FILE __szTraceSourceFile ///////////////////////////////////////////////////////////////////////////// // defaults const EEnDis c_eedDefShowUI = eedEnabled; const EEnDis c_eedDefReport = eedEnabled; const EIncEx c_eieDefShutdown = eieExclude; const EEnDis c_eedDefShowUISrv = eedDisabled; const EEnDis c_eedDefReportSrv = eedDisabled; const EIncEx c_eieDefShutdownSrv = eieInclude; const EEnDis c_eedDefTextLog = eedDisabled; const EIncEx c_eieDefApps = eieInclude; const EIncEx c_eieDefKernel = eieInclude; const EIncEx c_eieDefMSApps = eieInclude; const EIncEx c_eieDefWinComp = eieInclude; const BOOL c_fForceQueue = FALSE; const BOOL c_fForceQueueSrv = TRUE; const DWORD c_cDefHangPipes = c_cMinPipes; const DWORD c_cDefFaultPipes = c_cMinPipes; const DWORD c_cDefMaxUserQueue = 10; #if defined(DEBUG) || defined(_DEBUG) const DWORD c_dwDefInternal = 1; #else const DWORD c_dwDefInternal = 0; #endif const WCHAR c_wszDefSrvI[] = L"officewatson"; const WCHAR c_wszDefSrvE[] = L"watson.microsoft.com"; ///////////////////////////////////////////////////////////////////////////// // utility // ************************************************************************** HRESULT AddToArray(SAppList &sal, SAppItem *psai) { USE_TRACING("AddToArray"); HRESULT hr = NOERROR; DWORD i = sal.cSlotsUsed; BOOL fUseFreedSlot = FALSE; // first, skim thru the array & see if there are any empty slots if (sal.cSlotsEmpty > 0 && sal.rgsai != NULL) { for (i = 0; i < sal.cSlotsUsed; i++) { if (sal.rgsai[i].wszApp == NULL) { sal.cSlotsEmpty--; fUseFreedSlot = TRUE; break; } } } // nope, see if we need to grow the array if (sal.cSlotsUsed >= sal.cSlots && fUseFreedSlot == FALSE) { SAppItem *rgsai = NULL; DWORD cSlots; if (sal.cSlots == 0) cSlots = 16; else cSlots = 2 * sal.cSlots; rgsai = (SAppItem *)MyAlloc(cSlots * sizeof(SAppItem)); VALIDATEEXPR(hr, (rgsai == NULL), E_OUTOFMEMORY); if (FAILED(hr)) goto done; if (sal.rgsai != NULL) { CopyMemory(rgsai, sal.rgsai, sal.cSlots * sizeof(SAppItem)); MyFree(sal.rgsai); } sal.rgsai = rgsai; sal.cSlots = cSlots; } // if we are appending, then gotta increase cSlotsUsed if (sal.cSlotsUsed == i) sal.cSlotsUsed++; sal.rgsai[i].dwState = psai->dwState; sal.rgsai[i].wszApp = psai->wszApp; done: return hr; } // ************************************************************************** BOOL ClearCPLDW(HKEY hkeyCPL) { DWORD dw; WCHAR wch = L'\0'; BOOL fCleared = FALSE; HKEY hkeyDW = NULL; if (hkeyCPL == NULL) return TRUE; // first, try deleting the key. If that succeeded or it doesn't exist, // then we're done. dw = RegDeleteKeyW(hkeyCPL, c_wszRKDW); if (dw == ERROR_SUCCESS || dw == ERROR_PATH_NOT_FOUND || dw == ERROR_FILE_NOT_FOUND) { fCleared = TRUE; goto done; } // Otherwise, need to open the key dw = RegOpenKeyExW(hkeyCPL, c_wszRKDW, 0, KEY_READ | KEY_WRITE, &hkeyDW); if (dw != ERROR_SUCCESS) goto done; // try to delete the file path value from it. dw = RegDeleteValueW(hkeyDW, c_wszRVDumpPath); if (dw == ERROR_SUCCESS || dw == ERROR_PATH_NOT_FOUND || dw == ERROR_FILE_NOT_FOUND) { fCleared = TRUE; goto done; } // ok, last try. Try to write an empty string to the value dw = RegSetValueExW(hkeyDW, c_wszRVDumpPath, 0, REG_SZ, (LPBYTE)&wch, sizeof(wch)); if (dw == ERROR_SUCCESS) { fCleared = TRUE; goto done; } done: if (hkeyDW != NULL) RegCloseKey(hkeyDW); return fCleared; } ///////////////////////////////////////////////////////////////////////////// // CPFFaultClientCfg- init & term // ************************************************************************** CPFFaultClientCfg::CPFFaultClientCfg() { OSVERSIONINFOEXW osvi; INIT_TRACING USE_TRACING("CPFFaultClientCfg::CPFFaultClientCfg"); InitializeCriticalSection(&m_cs); ZeroMemory(m_wszDump, sizeof(m_wszDump)); ZeroMemory(m_wszSrv, sizeof(m_wszSrv)); ZeroMemory(m_rgLists, sizeof(m_rgLists)); ZeroMemory(&osvi, sizeof(osvi)); osvi.dwOSVersionInfoSize = sizeof(osvi); GetVersionExW((OSVERSIONINFOW *)&osvi); if (osvi.wProductType == VER_NT_SERVER) { m_eieShutdown = c_eieDefShutdownSrv; m_fForceQueue = c_fForceQueueSrv; m_fSrv = TRUE; } else { m_eieShutdown = c_eieDefShutdown; m_fForceQueue = c_fForceQueue; m_fSrv = FALSE; } m_eedUI = c_eedDefShowUI; m_eedReport = c_eedDefReport; m_eieApps = c_eieDefApps; m_eedTextLog = c_eedDefTextLog; m_eieMS = c_eieDefMSApps; m_eieWin = c_eieDefWinComp; m_eieKernel = c_eieDefKernel; m_cFaultPipes = c_cDefFaultPipes; m_cHangPipes = c_cDefHangPipes; m_cMaxQueueItems = c_cDefMaxUserQueue; m_dwStatus = 0; m_dwDirty = 0; m_pbWinApps = NULL; m_fRead = FALSE; m_fRO = FALSE; } // ************************************************************************** CPFFaultClientCfg::~CPFFaultClientCfg(void) { this->Clear(); DeleteCriticalSection(&m_cs); } // ************************************************************************** void CPFFaultClientCfg::Clear(void) { USE_TRACING("CPFFaultClientCfg::Clear"); DWORD i; for(i = 0; i < epfltListCount; i++) { if (m_rgLists[i].hkey != NULL) RegCloseKey(m_rgLists[i].hkey); if (m_rgLists[i].rgsai != NULL) { DWORD iSlot; for (iSlot = 0; iSlot < m_rgLists[i].cSlotsUsed; iSlot++) { if (m_rgLists[i].rgsai[iSlot].wszApp != NULL) MyFree(m_rgLists[i].rgsai[iSlot].wszApp); } MyFree(m_rgLists[i].rgsai); } } ZeroMemory(m_wszDump, sizeof(m_wszDump)); ZeroMemory(m_wszSrv, sizeof(m_wszSrv)); ZeroMemory(m_rgLists, sizeof(m_rgLists)); if (m_fSrv) { m_eieShutdown = c_eieDefShutdownSrv; m_fForceQueue = c_fForceQueueSrv; } else { m_eieShutdown = c_eieDefShutdown; m_fForceQueue = c_fForceQueue; } m_eedUI = c_eedDefShowUI; m_eedReport = c_eedDefReport; m_eieApps = c_eieDefApps; m_eedTextLog = c_eedDefTextLog; m_eieMS = c_eieDefMSApps; m_eieWin = c_eieDefWinComp; m_eieKernel = c_eieDefKernel; m_cFaultPipes = c_cDefFaultPipes; m_cHangPipes = c_cDefHangPipes; m_cMaxQueueItems = c_cDefMaxUserQueue; m_dwStatus = 0; m_dwDirty = 0; m_pbWinApps = NULL; m_fRead = FALSE; m_fRO = FALSE; } ///////////////////////////////////////////////////////////////////////////// // CPFFaultClientCfg- exposed // ************************************************************************** HRESULT CPFFaultClientCfg::Read(EReadOptions ero) { USE_TRACING("CPFFaultClientCfg::Read"); CAutoUnlockCS aucs(&m_cs); HRESULT hr = NOERROR; WCHAR wch = L'\0', *wszDefSrv; DWORD cb, dw, i, cKeys = 0, iReport = 0, iShowUI = 0; DWORD dwOpt; HKEY rghkeyCfg[2], hkeyCfgDW = NULL, hkeyCPL = NULL; BOOL fHavePolicy = FALSE; // this will automatically unlock when the fn exits aucs.Lock(); dwOpt = (ero == eroCPRW) ? orkWantWrite : 0; this->Clear(); rghkeyCfg[0] = NULL; rghkeyCfg[1] = NULL; // if we open read-only, then we will also try to read from the policy // settings cuz they override the control panel settings. If the user // wants write access, then we don't bother cuz we don't support writing // to the policy keys via this object. // We use the RegOpenKeyEx function directly here cuz I don't want to // create the key if it doesn't exist (and that's what OpenRegKey will do) if (ero == eroPolicyRO) { TESTERR(hr, RegOpenKeyExW(HKEY_LOCAL_MACHINE, c_wszRPCfgPolicy, 0, KEY_READ | KEY_WOW64_64KEY, &rghkeyCfg[0])); if (SUCCEEDED(hr)) { cKeys = 1; fHavePolicy = TRUE; ErrorTrace(0, "policy found"); } } // open the control panel reg key TESTHR(hr, OpenRegKey(HKEY_LOCAL_MACHINE, c_wszRPCfg, 0, &rghkeyCfg[cKeys])); if (SUCCEEDED(hr)) { // need to check if a filepath exists in the DW control panel key. If // so, disable reporting & enable the UI (if reporting was enabled) if (ClearCPLDW(rghkeyCfg[cKeys]) == FALSE) m_dwStatus |= CPL_CORPPATH_SET; hkeyCPL = rghkeyCfg[cKeys]; cKeys++; } // if we couldn't open either key successfully, then we don't need to do // anything else. The call to 'this->Clear()' above has already set // all the values to their defaults. VALIDATEPARM(hr, (cKeys == 0)); if (FAILED(hr)) { hr = NOERROR; goto doneValidate; } // read in the report value cb = sizeof(m_eedReport); dw = c_eedDefReport; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVDoReport, NULL, (PBYTE)&m_eedReport, &cb, (PBYTE)&dw, sizeof(dw), &iReport)); if (FAILED(hr)) goto done; // read in the ui value cb = sizeof(m_eedUI); dw = c_eedDefShowUI; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVShowUI, NULL, (PBYTE)&m_eedUI, &cb, (PBYTE)&dw, sizeof(dw), &iShowUI)); if (FAILED(hr)) goto done; // set the policy info (note that the policy key is always set into // slot 0 of the array) if (fHavePolicy) { if (iReport == 0) m_dwStatus |= REPORT_POLICY; if (iShowUI == 0) m_dwStatus |= SHOWUI_POLICY; ErrorTrace(0, " iReport = %d, iShowUI = %d", iReport, iShowUI ); // if we used the default value for reporting (we didn't find the // 'report' value anywhere) then try to use the control panel settings // for the rest of the stuff. if (iReport == 2 && cKeys == 2) iReport = 1; // if THAT doesn't exist, just bail cuz all of the other values have // already been set to their defaults else if (iReport == 1 && cKeys == 1) goto doneValidate; // only use the key where we read the 'DoReport' value from. Don't care // what the other key has to say... if (iReport == 1) { HKEY hkeySwap = rghkeyCfg[0]; rghkeyCfg[0] = rghkeyCfg[1]; rghkeyCfg[1] = hkeySwap; ErrorTrace(0, "POLICY and CPL controls INVERTED!!!"); } cKeys = 1; } // read in the inclusion list value cb = sizeof(m_eieApps); dw = c_eieDefApps; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVAllNone, NULL, (PBYTE)&m_eieApps, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the inc MS value cb = sizeof(m_eieMS); dw = c_eieDefMSApps; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVIncMS, NULL, (PBYTE)&m_eieMS, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the inc Windows components cb = sizeof(m_eieWin); dw = c_eieDefWinComp; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVIncWinComp, NULL, (PBYTE)&m_eieWin, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the text log value cb = sizeof(m_eedTextLog); dw = c_eedDefTextLog; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVDoTextLog, NULL, (PBYTE)&m_eedTextLog, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the include kernel faults value cb = sizeof(m_eieKernel); dw = c_eieDefKernel; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVIncKernel, NULL, (PBYTE)&m_eieKernel, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the include shutdown errs value cb = sizeof(m_eieShutdown); dw = (m_fSrv) ? c_eieDefShutdownSrv : c_eieDefShutdown; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVIncShutdown, NULL, (PBYTE)&m_eieShutdown, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the # of fault pipes value cb = sizeof(m_cFaultPipes); dw = c_cDefFaultPipes; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVNumFaultPipe, NULL, (PBYTE)&m_cFaultPipes, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the # of hang pipes value cb = sizeof(m_cHangPipes); dw = c_cDefHangPipes; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVNumHangPipe, NULL, (PBYTE)&m_cHangPipes, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the max queue size value cb = sizeof(m_cMaxQueueItems); dw = c_cDefMaxUserQueue; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVMaxQueueSize, NULL, (PBYTE)&m_cMaxQueueItems, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // read in the force queue mode value cb = sizeof(m_fForceQueue); dw = (m_fSrv) ? c_fForceQueueSrv : c_fForceQueue; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVForceQueue, NULL, (PBYTE)&m_fForceQueue, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; #ifndef NOTRACE // in for debug builds... // this would remove our "security risk" registry entries... // read in whether to use the internal server or not cb = sizeof(m_dwUseInternal); dw = c_dwDefInternal; TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVInternalSrv, NULL, (PBYTE)&m_dwUseInternal, &cb, (PBYTE)&dw, sizeof(dw))); if (FAILED(hr)) goto done; // get the default server wszDefSrv = (WCHAR *)((m_dwUseInternal == 1) ? c_wszDefSrvI : c_wszDefSrvE); if (m_dwUseInternal == 1 && m_fSrv) { cb = sizeof(m_wszSrv); dw = (wcslen(wszDefSrv) + 1) * sizeof(WCHAR); TESTHR(hr, ReadRegEntry(rghkeyCfg, cKeys, c_wszRVDefSrv, NULL, (PBYTE)m_wszSrv, &cb, (PBYTE)wszDefSrv, dw)); if (FAILED(hr)) goto done; } else { StringCbCopyW(m_wszSrv, sizeof(m_wszSrv), wszDefSrv); } #endif // force to normal behavior. (old code is commented out above) m_dwUseInternal = 0; StringCbCopyW(m_wszSrv, sizeof(m_wszSrv), c_wszDefSrvE); // the dump path is stored in the DW reg key, so we need to try to // open it up. However, we only need this value if we're going // to go into headless mode if (m_eedReport == eedEnabled && m_eedUI == eedDisabled) { // if the cpl corp path is set, we can't let DW do any reporting... if ((m_dwStatus & REPORT_POLICY) == 0 && (m_dwStatus & CPL_CORPPATH_SET) != 0 && m_eedReport == eedEnabled) m_eedReport = eedDisabled; if (m_eedReport == eedEnabled) { TESTERR(hr, RegOpenKeyExW(rghkeyCfg[0], c_wszRKDW, 0, KEY_READ, &hkeyCfgDW)); if (SUCCEEDED(hr)) { // read in the dump path value cb = sizeof(m_wszDump); TESTHR(hr, ReadRegEntry(&hkeyCfgDW, 1, c_wszRVDumpPath, NULL, (PBYTE)m_wszDump, &cb, (PBYTE)&wch, sizeof(wch))); if (FAILED(hr)) goto done; } } } // it's ok if these fail. The code below will correctly deal with the // situation... TESTHR(hr, OpenRegKey(rghkeyCfg[0], c_wszRKExList, dwOpt, &m_rgLists[epfltExclude].hkey)); if (FAILED(hr)) m_rgLists[epfltExclude].hkey = NULL; TESTHR(hr, OpenRegKey(rghkeyCfg[0], c_wszRKIncList, dwOpt, &m_rgLists[epfltInclude].hkey)); if (FAILED(hr)) m_rgLists[epfltInclude].hkey = NULL; hr = NOERROR; doneValidate: // validate the data we've read and reset the values to defaults if they // are outside of the allowable range of values if (m_eedUI != eedEnabled && m_eedUI != eedDisabled && m_eedUI != eedEnabledNoCheck) m_eedUI = c_eedDefShowUI; if (m_eedReport != eedEnabled && m_eedReport != eedDisabled) m_eedReport = c_eedDefReport; if (m_eedTextLog != eedEnabled && m_eedTextLog != eedDisabled) m_eedTextLog = c_eedDefTextLog; if (m_eieApps != eieIncDisabled && m_eieApps != eieExDisabled && m_eieApps != eieInclude && m_eieApps != eieExclude) m_eieApps = c_eieDefApps; if (m_eieMS != eieInclude && m_eieMS != eieExclude) m_eieMS = c_eieDefMSApps; if (m_eieKernel != eieInclude && m_eieKernel != eieExclude) m_eieKernel = c_eieDefKernel; if (m_eieShutdown != eieInclude && m_eieShutdown != eieExclude) m_eieShutdown = (m_fSrv) ? c_eieDefShutdownSrv : c_eieDefShutdown; if (m_eieWin != eieInclude && m_eieWin != eieExclude) m_eieWin = c_eieDefWinComp; if (m_dwUseInternal != 1 && m_dwUseInternal != 0) m_dwUseInternal = c_dwDefInternal; if (m_cFaultPipes < c_cMinPipes) m_cFaultPipes = c_cMinPipes; else if (m_cFaultPipes > c_cMaxPipes) m_cFaultPipes = c_cMaxPipes; if (m_cHangPipes == c_cMinPipes) m_cHangPipes = c_cMinPipes; else if (m_cHangPipes > c_cMaxPipes) m_cHangPipes = c_cMaxPipes; if (m_cMaxQueueItems > c_cMaxQueue || m_cMaxQueueItems <= 0) m_cMaxQueueItems = c_cMaxQueue; if (m_fForceQueue != c_fForceQueue && m_fForceQueue != c_fForceQueueSrv) m_fForceQueue = (m_fSrv) ? c_fForceQueueSrv : c_fForceQueue; m_fRead = TRUE; m_fRO = (ero != eroCPRW); aucs.Unlock(); done: if (rghkeyCfg[0] != NULL) RegCloseKey(rghkeyCfg[0]); if (rghkeyCfg[1] != NULL) RegCloseKey(rghkeyCfg[1]); if (hkeyCfgDW != NULL) RegCloseKey(hkeyCfgDW); if (FAILED(hr)) this->Clear(); return hr; } #ifndef PFCLICFG_LITE // ************************************************************************** BOOL CPFFaultClientCfg::HasWriteAccess(void) { USE_TRACING("CPFFaultClientCfg::HasWriteAccess"); HRESULT hr = NOERROR; DWORD dwOpt = orkWantWrite; HKEY hkeyMain = NULL, hkey = NULL; // attempt to open all the keys we use for the control panal to see if we // have write access to them. We only do this for the control panal cuz // this class does not support writing out policy values, just reading // them... TESTHR(hr, OpenRegKey(HKEY_LOCAL_MACHINE, c_wszRPCfg, dwOpt, &hkeyMain)); if (FAILED(hr)) goto done; // RegCloseKey(hkey); // hkey = NULL; TESTHR(hr, OpenRegKey(hkeyMain, c_wszRKExList, dwOpt, &hkey)); if (FAILED(hr)) goto done; RegCloseKey(hkey); hkey = NULL; TESTHR(hr, OpenRegKey(hkeyMain, c_wszRKIncList, dwOpt, &hkey)); if (FAILED(hr)) goto done; done: if (hkeyMain != NULL) RegCloseKey(hkeyMain); if (hkey != NULL) RegCloseKey(hkey); return (SUCCEEDED(hr)); } // ************************************************************************** HRESULT CPFFaultClientCfg::Write(void) { USE_TRACING("CPFFaultClientCfg::Write"); CAutoUnlockCS aucs(&m_cs); HRESULT hr = NOERROR; DWORD dwOpt = orkWantWrite; HKEY hkeyCfg = NULL; // this will automatically unlock when the fn exits aucs.Lock(); if (m_fRO) { hr = E_ACCESSDENIED; goto done; } TESTHR(hr, OpenRegKey(HKEY_LOCAL_MACHINE, c_wszRPCfg, dwOpt, &hkeyCfg)); if (FAILED(hr)) goto done; // inclusion / exclusion list value if ((m_dwDirty & FHCC_ALLNONE) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVAllNone, 0, REG_DWORD, (PBYTE)&m_eieApps, sizeof(m_eieApps))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_ALLNONE; } // ms apps in except list value if ((m_dwDirty & FHCC_INCMS) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVIncMS, 0, REG_DWORD, (PBYTE)&m_eieMS, sizeof(m_eieMS))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_INCMS; } // ms apps in except list value if ((m_dwDirty & FHCC_WINCOMP) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVIncWinComp, 0, REG_DWORD, (PBYTE)&m_eieWin, sizeof(m_eieWin))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_WINCOMP; } // show UI value if ((m_dwDirty & FHCC_SHOWUI) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVShowUI, 0, REG_DWORD, (PBYTE)&m_eedUI, sizeof(m_eedUI))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_SHOWUI; } // do reporting value if ((m_dwDirty & FHCC_DOREPORT) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVDoReport, 0, REG_DWORD, (PBYTE)&m_eedReport, sizeof(m_eedReport))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_DOREPORT; } // include kernel faults value if ((m_dwDirty & FHCC_R0INCLUDE) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVIncKernel, 0, REG_DWORD, (PBYTE)&m_eieKernel, sizeof(m_eieKernel))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_R0INCLUDE; } // include shutdown value if ((m_dwDirty & FHCC_INCSHUTDOWN) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVIncShutdown, 0, REG_DWORD, (PBYTE)&m_eieShutdown, sizeof(m_eieShutdown))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_INCSHUTDOWN; } // # fault pipes value if ((m_dwDirty & FHCC_NUMFAULTPIPE) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVNumFaultPipe, 0, REG_DWORD, (PBYTE)&m_cFaultPipes, sizeof(m_cFaultPipes))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_NUMFAULTPIPE; } // # hang pipes value if ((m_dwDirty & FHCC_NUMHANGPIPE) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVNumHangPipe, 0, REG_DWORD, (PBYTE)&m_cHangPipes, sizeof(m_cHangPipes))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_NUMHANGPIPE; } // max user fault queue size value if ((m_dwDirty & FHCC_QUEUESIZE) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVMaxQueueSize, 0, REG_DWORD, (PBYTE)&m_cMaxQueueItems, sizeof(m_cMaxQueueItems))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_QUEUESIZE; } // default Server value if ((m_dwDirty & FHCC_DEFSRV) != 0) { DWORD cb; cb = wcslen(m_wszSrv) * sizeof(WCHAR); TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVDefSrv, 0, REG_DWORD, (PBYTE)m_wszSrv, cb)); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_DEFSRV; } // dump path value if ((m_dwDirty & FHCC_DUMPPATH) != 0) { DWORD cb; cb = wcslen(m_wszDump) * sizeof(WCHAR); TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVDumpPath, 0, REG_DWORD, (PBYTE)m_wszDump, cb)); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_DUMPPATH; } // force queue mode value if ((m_dwDirty & FHCC_FORCEQUEUE) != 0) { TESTERR(hr, RegSetValueExW(hkeyCfg, c_wszRVForceQueue, 0, REG_DWORD, (PBYTE)&m_fForceQueue, sizeof(m_fForceQueue))); if (FAILED(hr)) goto done; m_dwDirty &= ~FHCC_FORCEQUEUE; } aucs.Unlock(); done: if (hkeyCfg != NULL) RegCloseKey(hkeyCfg); return hr; } #endif // PFCLICFG_LITE // ************************************************************************** BOOL CPFFaultClientCfg::ShouldCollect(LPWSTR wszAppPath, BOOL *pfIsMSApp) { USE_TRACING("CPFFaultClientCfg::ShouldCollect"); CAutoUnlockCS aucs(&m_cs); HRESULT hr = NOERROR; WCHAR *pwszApp, wszName[MAX_PATH], wszAppPathLocal[MAX_PATH] = {0}; DWORD i, cb, dwChecked, dw, dwMS, dwType; BOOL fCollect = FALSE; if (wszAppPath == NULL) { if (GetModuleFileNameW(NULL, wszAppPathLocal, sizeofSTRW(wszAppPathLocal)-1) == 0) { goto done; } wszAppPathLocal[sizeofSTRW(wszAppPathLocal)-1]=0; wszAppPath = wszAppPathLocal; } if (pfIsMSApp != NULL) *pfIsMSApp = FALSE; aucs.Lock(); if (m_fRead == FALSE) { TESTHR(hr, this->Read()); if (FAILED(hr)) goto done; } // if we have reporting turned off or the 'programs' checkbox has been cleared // in the control panel, then we are definitely not reporting if (m_eedReport == eedDisabled || m_eieApps == eieExDisabled || m_eieApps == eieIncDisabled) { fCollect = FALSE; goto done; } // get a pointer to the app name for (pwszApp = wszAppPath + wcslen(wszAppPath); *pwszApp != L'\\' && pwszApp != wszAppPath; pwszApp--); if (*pwszApp == L'\\') pwszApp++; // are we collecting everything by default? if (m_eieApps == eieInclude) fCollect = TRUE; if (fCollect == FALSE || pfIsMSApp != NULL) { // nope, check if it's another Microsoft app... dwMS = IsMicrosoftApp(wszAppPath, NULL, 0); if (dwMS != 0 && pfIsMSApp != NULL) *pfIsMSApp = TRUE; // is it a windows component? if (m_eieWin == eieInclude && (dwMS & APP_WINCOMP) != 0) fCollect = TRUE; // is it a MS app? if (m_eieMS == eieInclude && (dwMS & APP_MSAPP) != 0) fCollect = TRUE; } // see if it's on the inclusion list (only need to do this if we aren't // already collecting). // Note that if the value is not a DWORD key or we get back an error // saying that we don't have enuf space to hold the data, we just assume // that it should be included. if (fCollect == FALSE && m_rgLists[epfltInclude].hkey != NULL) { cb = sizeof(dwChecked); dwType = REG_DWORD; dw = RegQueryValueExW(m_rgLists[epfltInclude].hkey, pwszApp, NULL, &dwType, (PBYTE)&dwChecked, &cb); if ((dw == ERROR_SUCCESS && (dwChecked == 1 || dwType != REG_DWORD)) || dw == ERROR_MORE_DATA) fCollect = TRUE; } // see if it's on the exclusion list (only need to do this if we are going // to collect something) // Note that if the value is not a DWORD key or we get back an error // saying that we don't have enuf space to hold the data, we just assume // that it should be excluded. if (fCollect && m_rgLists[epfltExclude].hkey != NULL) { cb = sizeof(dwChecked); dwType = REG_DWORD; dw = RegQueryValueExW(m_rgLists[epfltExclude].hkey, pwszApp, NULL, &dwType, (PBYTE)&dwChecked, &cb); if ((dw == ERROR_SUCCESS && (dwChecked == 1 || dwType != REG_DWORD)) || dw == ERROR_MORE_DATA) fCollect = FALSE; } done: return fCollect; } ///////////////////////////////////////////////////////////////////////////// // CPFFaultClientCfg- get properties // ************************************************************************** static inline LPCWSTR get_string(LPWSTR wszOut, LPWSTR wszSrc, int cchOut) { LPCWSTR wszRet; SetLastError(0); if (wszOut == NULL) { wszRet = wszSrc; } else { wszRet = wszOut; if (cchOut < lstrlenW(wszSrc)) { SetLastError(ERROR_INSUFFICIENT_BUFFER); return NULL; } StringCchCopyW(wszOut, cchOut, wszSrc); } return wszRet; } // ************************************************************************** LPCWSTR CPFFaultClientCfg::get_DumpPath(LPWSTR wsz, int cch) { USE_TRACING("CPFFaultClientCfg::get_DumpPath"); CAutoUnlockCS aucs(&m_cs); aucs.Lock(); return get_string(wsz, m_wszDump, cch); } // ************************************************************************** LPCWSTR CPFFaultClientCfg::get_DefaultServer(LPWSTR wsz, int cch) { USE_TRACING("CPFFaultClientCfg::get_DefaultServer"); CAutoUnlockCS aucs(&m_cs); aucs.Lock(); return get_string(wsz, m_wszSrv, cch); } #ifndef PFCLICFG_LITE ///////////////////////////////////////////////////////////////////////////// // CPFFaultClientCfg- set properties // ************************************************************************** BOOL CPFFaultClientCfg::set_DumpPath(LPCWSTR wsz) { USE_TRACING("CPFFaultClientCfg::set_DumpPath"); CAutoUnlockCS aucs(&m_cs); if (wsz == NULL || (wcslen(wsz) + 1) > sizeofSTRW(m_wszDump)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); StringCbCopyW(m_wszDump, sizeof(m_wszDump), wsz); m_dwDirty |= FHCC_DUMPPATH; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_DefaultServer(LPCWSTR wsz) { USE_TRACING("CPFFaultClientCfg::set_DefaultServer"); CAutoUnlockCS aucs(&m_cs); if (wsz == NULL || (wcslen(wsz) + 1) > sizeofSTRW(m_wszSrv)) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); StringCbCopyW(m_wszSrv, sizeof(m_wszSrv), wsz); m_dwDirty |= FHCC_DEFSRV; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_ShowUI(EEnDis eed) { USE_TRACING("CPFFaultClientCfg::set_ShowUI"); CAutoUnlockCS aucs(&m_cs); if (eed & ~1 && (DWORD)eed != 3) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_eedUI = eed; m_dwDirty |= FHCC_SHOWUI; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_DoReport(EEnDis eed) { USE_TRACING("CPFFaultClientCfg::set_DoReport"); CAutoUnlockCS aucs(&m_cs); if (eed & ~1) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_eedReport = eed; m_dwDirty |= FHCC_DOREPORT; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_AllOrNone(EIncEx eie) { USE_TRACING("CPFFaultClientCfg::set_AllOrNone"); CAutoUnlockCS aucs(&m_cs); if (eie & ~3) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_eieApps = eie; m_dwDirty |= FHCC_ALLNONE; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_IncMSApps(EIncEx eie) { USE_TRACING("CPFFaultClientCfg::set_IncMSApps"); CAutoUnlockCS aucs(&m_cs); if (eie & ~1) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_eieMS = eie; m_dwDirty |= FHCC_INCMS; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_IncWinComp(EIncEx eie) { USE_TRACING("CPFFaultClientCfg::set_IncWinComp"); CAutoUnlockCS aucs(&m_cs); if (eie & ~1) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_eieWin = eie; m_dwDirty |= FHCC_WINCOMP; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_IncKernel(EIncEx eie) { USE_TRACING("CPFFaultClientCfg::set_IncKernel"); CAutoUnlockCS aucs(&m_cs); if (eie & ~1) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_eieKernel = eie; m_dwDirty |= FHCC_R0INCLUDE; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_IncShutdown(EIncEx eie) { USE_TRACING("CPFFaultClientCfg::set_IncShutdown"); CAutoUnlockCS aucs(&m_cs); if (eie & ~1) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_eieShutdown = eie; m_dwDirty |= FHCC_INCSHUTDOWN; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_ForceQueueMode(BOOL fForceQueueMode) { USE_TRACING("CPFFaultClientCfg::set_IncKernel"); CAutoUnlockCS aucs(&m_cs); if (fForceQueueMode & ~1) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_fForceQueue = fForceQueueMode; m_dwDirty |= FHCC_FORCEQUEUE; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_NumFaultPipes(DWORD cPipes) { USE_TRACING("CPFFaultClientCfg::set_NumFaultPipes"); CAutoUnlockCS aucs(&m_cs); if (cPipes == 0 || cPipes > 8) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_cFaultPipes = cPipes; m_dwDirty |= FHCC_NUMFAULTPIPE; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_NumHangPipes(DWORD cPipes) { USE_TRACING("CPFFaultClientCfg::set_NumHangPipes"); CAutoUnlockCS aucs(&m_cs); if (cPipes == 0 || cPipes > 8) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_cHangPipes = cPipes; m_dwDirty |= FHCC_NUMHANGPIPE; return TRUE; } // ************************************************************************** BOOL CPFFaultClientCfg::set_MaxUserQueueSize(DWORD cItems) { USE_TRACING("CPFFaultClientCfg::set_MaxUserQueueSize"); CAutoUnlockCS aucs(&m_cs); if (cItems <= 0 || cItems > c_cMaxQueue) { SetLastError(ERROR_INVALID_PARAMETER); return FALSE; } aucs.Lock(); m_cMaxQueueItems = cItems; m_dwDirty |= FHCC_QUEUESIZE; return TRUE; } ///////////////////////////////////////////////////////////////////////////// // App lists // ************************************************************************** HRESULT CPFFaultClientCfg::InitList(EPFListType epflt) { USE_TRACING("CPFFaultClientCfg::get_IncListCount"); CAutoUnlockCS aucs(&m_cs); HRESULT hr = NOERROR; DWORD cItems = 0; VALIDATEPARM(hr, (epflt >= epfltListCount)); if (FAILED(hr)) goto done; aucs.Lock(); if (m_fRead == FALSE) { hr = E_FAIL; goto done;; } // if we've already initialized, then just clear the list out & return if ((m_rgLists[epflt].dwState & epfaaInitialized) != 0) { this->ClearChanges(epflt); m_rgLists[epflt].dwState &= ~epfaaInitialized; } if (m_rgLists[epflt].hkey != NULL) { TESTERR(hr, RegQueryInfoKeyW(m_rgLists[epflt].hkey, NULL, NULL, NULL, NULL, NULL, NULL, &m_rgLists[epflt].cItemsInReg, &m_rgLists[epflt].cchMaxVal, NULL, NULL, NULL)); if (FAILED(hr)) goto done; } else { m_rgLists[epflt].cItemsInReg = 0; m_rgLists[epflt].cchMaxVal = 0; } m_rgLists[epflt].dwState |= epfaaInitialized; done: return hr; } // ************************************************************************** HRESULT CPFFaultClientCfg::get_ListRegInfo(EPFListType epflt, DWORD *pcbMaxName, DWORD *pcApps) { USE_TRACING("CPFFaultClientCfg::get_ListRegInfo"); CAutoUnlockCS aucs(&m_cs); HRESULT hr = NOERROR; VALIDATEPARM(hr, (pcbMaxName == NULL || pcApps == NULL || epflt >= epfltListCount)); if (FAILED(hr)) goto done; aucs.Lock(); *pcbMaxName = 0; *pcApps = 0; if (m_fRead == FALSE || (m_rgLists[epflt].dwState & epfaaInitialized) == 0) { hr = E_FAIL; goto done; } *pcbMaxName = m_rgLists[epflt].cchMaxVal; *pcApps = m_rgLists[epflt].cItemsInReg; done: return hr; } // ************************************************************************** HRESULT CPFFaultClientCfg::get_ListRegApp(EPFListType epflt, DWORD iApp, LPWSTR wszApp, DWORD cchApp, DWORD *pdwChecked) { USE_TRACING("CPFFaultClientCfg::get_ListApp"); CAutoUnlockCS aucs(&m_cs); HRESULT hr = NOERROR; WCHAR wsz[MAX_PATH]; DWORD cchName, cbData, dw, dwType = 0; VALIDATEPARM(hr, (wszApp == NULL || pdwChecked == NULL || epflt >= epfltListCount)); if (FAILED(hr)) goto done; *wszApp = L'\0'; *pdwChecked = 0; aucs.Lock(); if (m_fRead == FALSE || (m_rgLists[epflt].dwState & epfaaInitialized) == 0) { hr = E_FAIL; goto done; } cchName = cchApp; cbData = sizeof(DWORD); dw = RegEnumValueW(m_rgLists[epflt].hkey, iApp, wszApp, &cchName, NULL, &dwType, (LPBYTE)pdwChecked, &cbData); if (dw != ERROR_SUCCESS && dw != ERROR_NO_MORE_ITEMS) { if (dw == ERROR_MORE_DATA) { dw = RegEnumValueW(m_rgLists[epflt].hkey, iApp, wszApp, &cchName, NULL, NULL, NULL, NULL); *pdwChecked = 1; } TESTERR(hr, dw); goto done; } if (dwType != REG_DWORD || (*pdwChecked != 1 && *pdwChecked != 0)) *pdwChecked = 1; if (dw == ERROR_NO_MORE_ITEMS) { hr = S_FALSE; goto done; } done: return hr; } // ************************************************************************** HRESULT CPFFaultClientCfg::add_ListApp(EPFListType epflt, LPCWSTR wszApp) { USE_TRACING("CPFFaultClientCfg::add_ListApp"); CAutoUnlockCS aucs(&m_cs); SAppItem sai; HRESULT hr = NOERROR; LPWSTR wszExe = NULL; DWORD dw = 0, i, cb; VALIDATEPARM(hr, (wszApp == NULL || epflt >= epfltListCount)); if (FAILED(hr)) goto done; aucs.Lock(); if (m_fRO == TRUE) { hr = E_ACCESSDENIED; goto done; } if (m_fRead == FALSE || (m_rgLists[epflt].dwState & epfaaInitialized) == 0) { hr = E_FAIL; goto done; } // first, check if it's already on the mod list for (i = 0; i < m_rgLists[epflt].cSlotsUsed; i++) { if (m_rgLists[epflt].rgsai[i].wszApp != NULL && _wcsicmp(m_rgLists[epflt].rgsai[i].wszApp, wszApp) == 0) { SETADD(m_rgLists[epflt].rgsai[i].dwState); SETCHECK(m_rgLists[epflt].rgsai[i].dwState); goto done; } } // add it to the list then... wszExe = (LPWSTR)MyAlloc(cb = ((wcslen(wszApp) + 1) * sizeof(WCHAR))); VALIDATEEXPR(hr, (wszExe == NULL), E_OUTOFMEMORY); if (FAILED(hr)) goto done; StringCbCopyW(wszExe, cb, wszApp); sai.wszApp = wszExe; SETADD(sai.dwState); SETCHECK(sai.dwState); TESTHR(hr, AddToArray(m_rgLists[epflt], &sai)); if (FAILED(hr)) goto done; wszExe = NULL; done: if (wszExe != NULL) MyFree(wszExe); return hr; } // ************************************************************************** HRESULT CPFFaultClientCfg::del_ListApp(EPFListType epflt, LPWSTR wszApp) { USE_TRACING("CPFFaultClientCfg::del_ListApp"); CAutoUnlockCS aucs(&m_cs); SAppItem sai; HRESULT hr = NOERROR; LPWSTR wszExe = NULL; DWORD i, cb; VALIDATEPARM(hr, (wszApp == NULL || epflt >= epfltListCount)); if (FAILED(hr)) goto done; aucs.Lock(); if (m_fRO == TRUE) { hr = E_ACCESSDENIED; goto done; } // first, check if it's already on the mod list for add for (i = 0; i < m_rgLists[epflt].cSlotsUsed; i++) { if (m_rgLists[epflt].rgsai[i].wszApp != NULL && _wcsicmp(m_rgLists[epflt].rgsai[i].wszApp, wszApp) == 0) { if (m_rgLists[epflt].rgsai[i].dwState & epfaaAdd) { // just set the wszApp field to NULL. we'll reuse it // on the next add to the array (if any) MyFree(m_rgLists[epflt].rgsai[i].wszApp); m_rgLists[epflt].rgsai[i].wszApp = NULL; m_rgLists[epflt].rgsai[i].dwState = 0; m_rgLists[epflt].cSlotsEmpty++; } else { SETDEL(m_rgLists[epflt].rgsai[i].dwState); } goto done; } } // add it to the list then... wszExe = (LPWSTR)MyAlloc(cb = ((wcslen(wszApp) + 1) * sizeof(WCHAR))); VALIDATEEXPR(hr, (wszExe == NULL), E_OUTOFMEMORY); if (FAILED(hr)) goto done; StringCbCopyW(wszExe, cb, wszApp); sai.wszApp = wszExe; SETDEL(sai.dwState); TESTHR(hr, AddToArray(m_rgLists[epflt], &sai)); if (FAILED(hr)) goto done; wszExe = NULL; done: if (wszExe != NULL) MyFree(wszExe); return hr; } // ************************************************************************** HRESULT CPFFaultClientCfg::mod_ListApp(EPFListType epflt, LPWSTR wszApp, DWORD dwChecked) { USE_TRACING("CPFFaultClientCfg::del_ListApp"); CAutoUnlockCS aucs(&m_cs); SAppItem sai; HRESULT hr = NOERROR; LPWSTR wszExe = NULL; DWORD i, cb; VALIDATEPARM(hr, (wszApp == NULL || epflt >= epfltListCount)); if (FAILED(hr)) goto done; aucs.Lock(); if (m_fRO == TRUE) { hr = E_ACCESSDENIED; goto done; } // first, check if it's already on the mod list for (i = 0; i < m_rgLists[epflt].cSlotsUsed; i++) { if (m_rgLists[epflt].rgsai[i].wszApp != NULL && _wcsicmp(m_rgLists[epflt].rgsai[i].wszApp, wszApp) == 0) { if (dwChecked == 0) { REMCHECK(m_rgLists[epflt].rgsai[i].dwState); } else { SETCHECK(m_rgLists[epflt].rgsai[i].dwState); } goto done; } } // add it to the list then... wszExe = (LPWSTR)MyAlloc(cb = ((wcslen(wszApp) + 1) * sizeof(WCHAR))); VALIDATEEXPR(hr, (wszExe == NULL), E_OUTOFMEMORY); if (FAILED(hr)) goto done; StringCbCopyW(wszExe, cb, wszApp); sai.wszApp = wszExe; sai.dwState = ((dwChecked == 0) ? epfaaRemCheck : epfaaSetCheck); TESTHR(hr, AddToArray(m_rgLists[epflt], &sai)); if (FAILED(hr)) goto done; wszExe = NULL; done: if (wszExe != NULL) MyFree(wszExe); return hr; } // ************************************************************************** HRESULT CPFFaultClientCfg::ClearChanges(EPFListType epflt) { USE_TRACING("CPFFaultClientCfg::ClearChanges"); CAutoUnlockCS aucs(&m_cs); HRESULT hr = NOERROR; DWORD i; VALIDATEPARM(hr, (epflt >= epfltListCount)); if (FAILED(hr)) goto done; aucs.Lock(); if (m_fRead == FALSE || (m_rgLists[epflt].dwState & epfaaInitialized) == 0) { hr = E_FAIL; goto done; } if (m_rgLists[epflt].rgsai == NULL) goto done; for(i = 0; i < m_rgLists[epflt].cSlotsUsed; i++) { m_rgLists[epflt].rgsai[i].dwState = 0; if (m_rgLists[epflt].rgsai[i].wszApp != NULL) { MyFree(m_rgLists[epflt].rgsai[i].wszApp); m_rgLists[epflt].rgsai[i].wszApp = NULL; } } m_rgLists[epflt].cSlotsUsed = 0; done: return hr; } // ************************************************************************** HRESULT CPFFaultClientCfg::CommitChanges(EPFListType epflt) { USE_TRACING("CPFFaultClientCfg::CommitChanges"); CAutoUnlockCS aucs(&m_cs); HRESULT hr = NOERROR; DWORD i, dw; VALIDATEPARM(hr, (epflt >= epfltListCount)); if (FAILED(hr)) goto done; aucs.Lock(); if (m_fRO == TRUE) { hr = E_ACCESSDENIED; goto done; } if (m_fRead == FALSE || (m_rgLists[epflt].dwState & epfaaInitialized) == 0) { hr = E_FAIL; goto done; } if (m_rgLists[epflt].hkey == NULL) { hr = E_ACCESSDENIED; goto done; } if (m_rgLists[epflt].rgsai == NULL) goto done; // don't need to compress the array. Since we always append & never // delete out of the array until a commit, once I hit an 'Add', anything // after that in the array MUST also be an 'Add'. for (i = 0; i < m_rgLists[epflt].cSlotsUsed; i++) { if (m_rgLists[epflt].rgsai[i].wszApp == NULL) { m_rgLists[epflt].rgsai[i].dwState = 0; continue; } if ((m_rgLists[epflt].rgsai[i].dwState & epfaaDelete) != 0) { dw = RegDeleteValueW(m_rgLists[epflt].hkey, m_rgLists[epflt].rgsai[i].wszApp); if (dw != ERROR_SUCCESS && dw != ERROR_FILE_NOT_FOUND) { TESTERR(hr, dw); goto done; } } else { DWORD dwChecked; dwChecked = (ISCHECKED(m_rgLists[epflt].rgsai[i].dwState)) ? 1 : 0; TESTERR(hr, RegSetValueExW(m_rgLists[epflt].hkey, m_rgLists[epflt].rgsai[i].wszApp, 0, REG_DWORD, (LPBYTE)&dwChecked, sizeof(DWORD))); if (FAILED(hr)) goto done; } MyFree(m_rgLists[epflt].rgsai[i].wszApp); m_rgLists[epflt].rgsai[i].wszApp = NULL; m_rgLists[epflt].rgsai[i].dwState = 0; } m_rgLists[epflt].cSlotsUsed = 0; done: return hr; } // ************************************************************************** BOOL CPFFaultClientCfg::IsOnList(EPFListType epflt, LPCWSTR wszApp) { USE_TRACING("CPFFaultClientCfg::IsOnList"); SAppList *psap; HRESULT hr = NOERROR; DWORD i; HKEY hkey = NULL; VALIDATEPARM(hr, (epflt >= epfltListCount || wszApp == NULL)); if (FAILED(hr)) goto done; if ((m_rgLists[epflt].dwState & epfaaInitialized) == 0) { hr = E_FAIL; goto done; } // first, check the mod list. This is because if we check the registry // first, we miss the case where the user just deleted it and it's // therefore sitting in the mod list hr = S_FALSE; for (i = 0; i < m_rgLists[epflt].cSlotsUsed; i++) { if (m_rgLists[epflt].rgsai[i].wszApp != NULL && _wcsicmp(m_rgLists[epflt].rgsai[i].wszApp, wszApp) == 0) { if ((m_rgLists[epflt].rgsai[i].dwState & epfaaDelete) == 0) hr = NOERROR; goto done; } } // next, check the registry. TESTERR(hr, RegQueryValueExW(m_rgLists[epflt].hkey, wszApp, NULL, NULL, NULL, NULL)); if (SUCCEEDED(hr)) goto done; done: return (hr == NOERROR); } #endif PFCLICFG_LITE
29.03876
111
0.51022
[ "object" ]
11246028f9fa088850f7a39f293780dce77c2c8a
7,094
cpp
C++
ugene/src/corelibs/U2View/src/ov_sequence/AnnotatedDNAViewFactory.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2View/src/ov_sequence/AnnotatedDNAViewFactory.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2View/src/ov_sequence/AnnotatedDNAViewFactory.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AnnotatedDNAViewFactory.h" #include "AnnotatedDNAView.h" #include "AnnotatedDNAViewTasks.h" #include "AnnotatedDNAViewState.h" #include "ADVConstants.h" #include <U2Core/AppContext.h> #include <U2Core/ProjectModel.h> #include <U2Core/DocumentModel.h> #include <U2Core/SelectionUtils.h> #include <U2Core/DocumentSelection.h> #include <U2Core/DNASequenceObject.h> #include <U2Core/AnnotationTableObject.h> #include <U2Core/GObjectTypes.h> #include <U2Core/GObjectRelationRoles.h> #include <U2Core/GObjectUtils.h> namespace U2 { /* TRANSLATOR U2::AnnotatedDNAView */ const GObjectViewFactoryId AnnotatedDNAViewFactory::ID(ANNOTATED_DNA_VIEW_FACTORY_ID); AnnotatedDNAViewFactory::AnnotatedDNAViewFactory() : GObjectViewFactory(ID, tr("Sequence view")) { } bool AnnotatedDNAViewFactory::canCreateView(const MultiGSelection& multiSelection) { //return true if //1. selection has loaded of unloaded DNA sequence object //2. selection has any object with SEQUENCE relation to DNA sequence object that is in the project //3. selection has document that have sequence object or object assosiated with sequence //1. QList<GObject*> selectedObjects = SelectionUtils::findObjects("", &multiSelection, UOF_LoadedAndUnloaded); QList<GObject*> selectedSequences = GObjectUtils::select(selectedObjects, GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded); if (!selectedSequences.isEmpty()) { return true; } //2. QList<GObject*> objectsWithSeqRelation = GObjectUtils::selectObjectsWithRelation(selectedObjects, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); if (!objectsWithSeqRelation.isEmpty()) { return true; } //3. const DocumentSelection* ds = qobject_cast<const DocumentSelection*>(multiSelection.findSelectionByType(GSelectionTypes::DOCUMENTS)); if (ds == NULL) { return false; } foreach(Document* doc, ds->getSelectedDocuments()) { if (!doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded).isEmpty()) { return true; } objectsWithSeqRelation = GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); if (!objectsWithSeqRelation.isEmpty()) { return true; } } return false; } Task* AnnotatedDNAViewFactory::createViewTask(const MultiGSelection& multiSelection, bool single /*=false*/) { Q_UNUSED(single); QList<GObject*> objectsToOpen = SelectionUtils::findObjects(GObjectTypes::SEQUENCE, &multiSelection, UOF_LoadedAndUnloaded); QList<GObject*> selectedObjects = SelectionUtils::findObjects("", &multiSelection, UOF_LoadedAndUnloaded); QList<GObject*> objectsWithSequenceRelation = GObjectUtils::selectObjectsWithRelation(selectedObjects, GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true); foreach(GObject* obj, objectsWithSequenceRelation) { if(!objectsToOpen.contains(obj)) { objectsToOpen.append(obj); } } //objectsToOpen.append(objectsWithSequenceRelation); const DocumentSelection* ds = qobject_cast<const DocumentSelection*>(multiSelection.findSelectionByType(GSelectionTypes::DOCUMENTS)); if (ds != NULL) { foreach(Document* doc, ds->getSelectedDocuments()) { /*objectsToOpen.append(doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded)); objectsToOpen.append(GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true));*/ foreach(GObject* obj, doc->findGObjectByType(GObjectTypes::SEQUENCE, UOF_LoadedAndUnloaded)) { if(!objectsToOpen.contains(obj)) { objectsToOpen.append(obj); } } foreach(GObject* obj, GObjectUtils::selectObjectsWithRelation(doc->getObjects(), GObjectTypes::SEQUENCE, GObjectRelationRole::SEQUENCE, UOF_LoadedAndUnloaded, true)) { if(!objectsToOpen.contains(obj)) { objectsToOpen.append(obj); } } } } OpenAnnotatedDNAViewTask* task = new OpenAnnotatedDNAViewTask(objectsToOpen); return task; } bool AnnotatedDNAViewFactory::isStateInSelection(const MultiGSelection& multiSelection, const QVariantMap& stateData) { AnnotatedDNAViewState state(stateData); if (!state.isValid()) { return false; } QList<GObjectReference> refs = state.getSequenceObjects(); assert(!refs.isEmpty()); foreach (const GObjectReference& ref, refs) { Document* doc = AppContext::getProject()->findDocumentByURL(ref.docUrl); if (doc == NULL) { //todo: accept to use invalid state removal routines of ObjectViewTask ??? return false; } //check that document is in selection QList<Document*> selectedDocs = SelectionUtils::getSelectedDocs(multiSelection); bool docIsSelected = selectedDocs.contains(doc); //check that object is in selection QList<GObject*> selectedObjects = SelectionUtils::getSelectedObjects(multiSelection); GObject* obj = doc->findGObjectByName(ref.objName); bool objIsSelected = obj!=NULL && selectedObjects.contains(obj); //check that object associated with sequence object is in selection bool refIsSelected = false; foreach (const GObject* selObject, selectedObjects) { GObjectReference selRef(selObject); if (ref == selRef) { refIsSelected = true; break; } } if (!docIsSelected && !objIsSelected && !refIsSelected) { return false; } } return true; } Task* AnnotatedDNAViewFactory::createViewTask(const QString& viewName, const QVariantMap& stateData) { return new OpenSavedAnnotatedDNAViewTask(viewName, stateData); } } // namespace
39.853933
137
0.691993
[ "object" ]
112957b0064bae2b883d5808e405c364008a8c59
16,711
hpp
C++
modules/swupdater/src/libifm3d_swupdater/swupdater_impl.hpp
Arag24/ifm3d
de345c12c54b02aae9a89120454902a29edccaf3
[ "Apache-2.0", "MIT" ]
null
null
null
modules/swupdater/src/libifm3d_swupdater/swupdater_impl.hpp
Arag24/ifm3d
de345c12c54b02aae9a89120454902a29edccaf3
[ "Apache-2.0", "MIT" ]
1
2020-05-15T19:50:56.000Z
2020-05-15T19:50:56.000Z
modules/swupdater/src/libifm3d_swupdater/swupdater_impl.hpp
Arag24/ifm3d
de345c12c54b02aae9a89120454902a29edccaf3
[ "Apache-2.0", "MIT" ]
1
2022-02-08T04:14:41.000Z
2022-02-08T04:14:41.000Z
/* * Copyright (C) 2019 ifm electronic, gmbh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __IFM3D_SWUPDATER_SWUPDATER_IMPL_H__ #define __IFM3D_SWUPDATER_SWUPDATER_IMPL_H__ #include <chrono> #include <string> #include <thread> #include <tuple> #include <vector> #include <curl/curl.h> #include <glog/logging.h> #include <ifm3d/camera/camera.h> #include <ifm3d/camera/err.h> #include <ifm3d/camera/logging.h> #include <ifm3d/contrib/nlohmann/json.hpp> namespace ifm3d { const std::string SWUPDATER_UPLOAD_URL_SUFFIX = "/handle_post_request"; const std::string SWUPDATER_REBOOT_URL_SUFFIX = "/reboot_to_live"; const std::string SWUPDATER_STATUS_URL_SUFFIX = "/getstatus.json"; const std::string SWUPDATER_CHECK_RECOVERY_URL_SUFFIX = "/id.lp"; const std::string SWUPDATER_RECOVERY_PORT = "8080"; const std::string SWUPDATER_FILENAME_HEADER = "X_FILENAME: swupdate.swu"; const std::string SWUPDATER_CONTENT_TYPE_HEADER = "Content-Type: application/octet-stream"; const int SWUPDATER_STATUS_IDLE = 0; const int SWUPDATER_STATUS_START = 1; const int SWUPDATER_STATUS_RUN = 2; const int SWUPDATER_STATUS_SUCCESS = 3; const int SWUPDATER_STATUS_FAILURE = 4; // Default timeout values for cURL transactions to the camera const long DEFAULT_CURL_CONNECT_TIMEOUT = 3; // seconds const long DEFAULT_CURL_TRANSACTION_TIMEOUT = 30; // seconds //============================================================ // Impl interface //============================================================ class SWUpdater::Impl { public: Impl(ifm3d::Camera::Ptr cam, const ifm3d::SWUpdater::FlashStatusCb& cb); ~Impl() = default; void RebootToRecovery(); bool WaitForRecovery(long timeout_millis); void RebootToProductive(); bool WaitForProductive(long timeout_millis); bool FlashFirmware( const std::vector<std::uint8_t>& bytes, long timeout_millis); private: ifm3d::Camera::Ptr cam_; ifm3d::SWUpdater::FlashStatusCb cb_; std::string upload_url_; std::string reboot_url_; std::string status_url_; std::string check_recovery_url_; bool CheckRecovery(); bool CheckProductive(); void UploadFirmware(const std::vector<std::uint8_t>& bytes, long timeout_millis); bool WaitForUpdaterStatus(int desired_state, long timeout_millis); std::tuple<int, std::string, int> GetUpdaterStatus(); /** * C-style static callbacks for libcurl */ static size_t StatusWriteCallbackIgnore(char *ptr, size_t size, size_t nmemb, void* userdata) { return size * nmemb; } static size_t StatusWriteCallback(char *ptr, size_t size, size_t nmemb, void* userdata) { std::string* body = static_cast<std::string*>(userdata); body->append(ptr, size * nmemb); return size * nmemb; } static int XferInfoCallback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { ifm3d::SWUpdater::Impl* swu = static_cast<ifm3d::SWUpdater::Impl*>(clientp); if (swu->cb_) { if (ultotal <= 0) { swu->cb_(0.0, ""); } else { float percentage_complete = (static_cast<float>(ulnow)/static_cast<float>(ultotal)); swu->cb_(percentage_complete, ""); } } if (ultotal > 0 && ulnow >= ultotal) { // Signal to 'abort' the transfer once all the data has been // transferred. This is a workaround to 'complete' the curl // transaction because the camera does not terminate the connection. return 1; } else { return 0; } } /** * RAII wrapper around libcurl's C API for performing a * transaction */ class CURLTransaction { public: CURLTransaction() { this->header_list_ = nullptr; this->curl_ = curl_easy_init(); if (!this->curl_) { throw ifm3d::error_t(IFM3D_CURL_ERROR); } } ~CURLTransaction() { curl_slist_free_all(this->header_list_); curl_easy_cleanup(this->curl_); } // disable copy/move semantics CURLTransaction(CURLTransaction&&) = delete; CURLTransaction& operator=(CURLTransaction&&) = delete; CURLTransaction(CURLTransaction&) = delete; CURLTransaction& operator=(const CURLTransaction&) = delete; /** * Wrapper for calling curl_easy_* APIs, and unified * error handling of return codes. */ template<typename F, typename... Args> void Call(F f, Args... args) { CURLcode retcode = f(this->curl_, args...); if (retcode != CURLE_OK) { switch (retcode) { case CURLE_COULDNT_CONNECT: throw ifm3d::error_t(IFM3D_RECOVERY_CONNECTION_ERROR); case CURLE_OPERATION_TIMEDOUT: throw ifm3d::error_t(IFM3D_CURL_TIMEOUT); case CURLE_ABORTED_BY_CALLBACK: throw ifm3d::error_t(IFM3D_CURL_ABORTED); default: throw ifm3d::error_t(IFM3D_CURL_ERROR); } } } void AddHeader(const char* str) { this->header_list_ = curl_slist_append(this->header_list_, str); if (!this->header_list_) { throw ifm3d::error_t(IFM3D_CURL_ERROR); } } void SetHeader() { this->Call(curl_easy_setopt, CURLOPT_HTTPHEADER, this->header_list_); } private: CURL* curl_; struct curl_slist* header_list_; }; }; // end: class SWUpdater::Impl } // end: namespace ifm3d //============================================================ // Impl -- Implementation Details //============================================================ //------------------------------------- // ctor //------------------------------------- ifm3d::SWUpdater::Impl::Impl(ifm3d::Camera::Ptr cam, const ifm3d::SWUpdater::FlashStatusCb& cb) : cam_(cam), cb_(cb), upload_url_("http://" + cam->IP() + ":" + SWUPDATER_RECOVERY_PORT + SWUPDATER_UPLOAD_URL_SUFFIX), reboot_url_("http://" + cam->IP() + ":" + SWUPDATER_RECOVERY_PORT + SWUPDATER_REBOOT_URL_SUFFIX), status_url_("http://" + cam->IP() + ":" + SWUPDATER_RECOVERY_PORT + SWUPDATER_STATUS_URL_SUFFIX), check_recovery_url_("http://" + cam->IP() + ":" + SWUPDATER_RECOVERY_PORT + SWUPDATER_CHECK_RECOVERY_URL_SUFFIX) { } //------------------------------------- // "Public" interface //------------------------------------- void ifm3d::SWUpdater::Impl::RebootToRecovery() { this->cam_->Reboot(ifm3d::Camera::boot_mode::RECOVERY); } bool ifm3d::SWUpdater::Impl::WaitForRecovery(long timeout_millis) { if (timeout_millis < 0) { return this->CheckRecovery(); } auto start = std::chrono::system_clock::now(); while (!this->CheckRecovery()) { if (timeout_millis > 0) { auto curr = std::chrono::system_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(curr-start); if (elapsed.count() > timeout_millis) { LOG(WARNING) << "Timed out waiting for recovery mode"; return false; } } } return true; } void ifm3d::SWUpdater::Impl::RebootToProductive() { auto c = std::make_unique<ifm3d::SWUpdater::Impl::CURLTransaction>(); c->Call(curl_easy_setopt, CURLOPT_URL, this->reboot_url_.c_str()); c->Call(curl_easy_setopt, CURLOPT_POST, true); c->Call(curl_easy_setopt, CURLOPT_POSTFIELDSIZE, 0); c->Call(curl_easy_setopt, CURLOPT_WRITEFUNCTION, &ifm3d::SWUpdater::Impl::StatusWriteCallbackIgnore); c->Call(curl_easy_setopt, CURLOPT_CONNECTTIMEOUT, ifm3d::DEFAULT_CURL_CONNECT_TIMEOUT); c->Call(curl_easy_setopt, CURLOPT_TIMEOUT, ifm3d::DEFAULT_CURL_TRANSACTION_TIMEOUT); c->Call(curl_easy_perform); } bool ifm3d::SWUpdater::Impl::WaitForProductive(long timeout_millis) { if (timeout_millis < 0) { return this->CheckProductive(); } auto start = std::chrono::system_clock::now(); while (!this->CheckProductive()) { if (timeout_millis > 0) { auto curr = std::chrono::system_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(curr-start); if (elapsed.count() > timeout_millis) { // timeout LOG(WARNING) << "Timed out waiting for productive mode"; return false; } } } return true; } bool ifm3d::SWUpdater::Impl::FlashFirmware( const std::vector<std::uint8_t>& bytes, long timeout_millis) { auto t_start = std::chrono::system_clock::now(); long remaining_time = timeout_millis; auto get_remaining_time = [&t_start, timeout_millis]() -> long { auto t_now = std::chrono::system_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(t_now - t_start); return timeout_millis - static_cast<long>(elapsed.count()); }; // Firmware updater must be in `idle` status prior to starting a firmware // upgrade. In some cases (firmware was flashed but the camera was not // rebooted, or the previous flash failed) the message queue must be // 'drained' so we query the status several times in quick succession. // // In practice, 10 iterations is sufficient. int retries = 0; while (!this->WaitForUpdaterStatus(SWUPDATER_STATUS_IDLE, -1)) { if (++retries >= 10) { throw ifm3d::error_t(IFM3D_SWUPDATE_BAD_STATE); } } remaining_time = get_remaining_time(); if (remaining_time <= 0) { return false; } this->UploadFirmware(bytes, remaining_time); remaining_time = get_remaining_time(); if (remaining_time <= 0) { return false; } return this->WaitForUpdaterStatus(SWUPDATER_STATUS_SUCCESS, remaining_time); } //------------------------------------- // "Private" helpers //------------------------------------- bool ifm3d::SWUpdater::Impl::CheckRecovery() { auto c = std::make_unique<ifm3d::SWUpdater::Impl::CURLTransaction>(); c->Call(curl_easy_setopt, CURLOPT_URL, this->check_recovery_url_.c_str()); c->Call(curl_easy_setopt, CURLOPT_NOBODY, true); c->Call(curl_easy_setopt, CURLOPT_CONNECTTIMEOUT, ifm3d::DEFAULT_CURL_CONNECT_TIMEOUT); c->Call(curl_easy_setopt, CURLOPT_TIMEOUT, ifm3d::DEFAULT_CURL_TRANSACTION_TIMEOUT); long status_code; try { c->Call(curl_easy_perform); c->Call(curl_easy_getinfo, CURLINFO_RESPONSE_CODE, &status_code); } catch(const ifm3d::error_t& e) { if (e.code() == IFM3D_RECOVERY_CONNECTION_ERROR || e.code() == IFM3D_CURL_TIMEOUT) { return false; } throw; } return status_code == 200; } bool ifm3d::SWUpdater::Impl::CheckProductive() { try { if (this->cam_->DeviceParameter("OperatingMode") != "") { return true; } } catch (const ifm3d::error_t& e) { // Rethrow unless the code is one that indicates the camera is not // currently reachable by XML-RPC (occurs during the reboot process) if (e.code() != IFM3D_XMLRPC_TIMEOUT && e.code() != IFM3D_XMLRPC_OBJ_NOT_FOUND) { throw; } } return false; } void ifm3d::SWUpdater::Impl::UploadFirmware( const std::vector<std::uint8_t>& bytes, long timeout_millis) { auto c = std::make_unique<ifm3d::SWUpdater::Impl::CURLTransaction>(); c->AddHeader(SWUPDATER_CONTENT_TYPE_HEADER.c_str()); c->AddHeader(SWUPDATER_FILENAME_HEADER.c_str()); c->SetHeader(); c->Call(curl_easy_setopt, CURLOPT_URL, this->upload_url_.c_str()); c->Call(curl_easy_setopt, CURLOPT_POST, 1); c->Call(curl_easy_setopt, CURLOPT_POSTFIELDSIZE, static_cast<long>(bytes.size())); c->Call(curl_easy_setopt, CURLOPT_POSTFIELDS, bytes.data()); c->Call(curl_easy_setopt, CURLOPT_WRITEFUNCTION, &ifm3d::SWUpdater::Impl::StatusWriteCallbackIgnore); c->Call(curl_easy_setopt, CURLOPT_CONNECTTIMEOUT, ifm3d::DEFAULT_CURL_CONNECT_TIMEOUT); c->Call(curl_easy_setopt, CURLOPT_TIMEOUT_MS, timeout_millis); // Workaround -- device does not close the connection after the firmware has // been transferred. Register an xfer callback and terminate the transaction // after all the data has been sent. c->Call(curl_easy_setopt, CURLOPT_XFERINFOFUNCTION, &ifm3d::SWUpdater::Impl::XferInfoCallback); c->Call(curl_easy_setopt, CURLOPT_XFERINFODATA, this); c->Call(curl_easy_setopt, CURLOPT_NOPROGRESS, 0); // `curl_easy_perform` will return CURLE_ABORTED_BY_CALLBACK // due to the above workaround. Handle and squash that error. try { c->Call(curl_easy_perform); } catch(const ifm3d::error_t& e) { if (e.code() != IFM3D_CURL_ABORTED) { throw; } } } bool ifm3d::SWUpdater::Impl::WaitForUpdaterStatus(int desired_status, long timeout_millis) { int status_id; int status_error; std::string status_message; if (timeout_millis < 0) { std::tie(status_id, std::ignore, std::ignore) = this->GetUpdaterStatus(); return status_id == desired_status; } auto start = std::chrono::system_clock::now(); do { if (timeout_millis > 0) { auto curr = std::chrono::system_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(curr-start); if (elapsed.count() > timeout_millis) { // timeout LOG(WARNING) << "Timed out waiting for updater status: " << desired_status; return false; } } std::tie(status_id, status_message, status_error) = this->GetUpdaterStatus(); if (status_message != "") { if (this->cb_) { this->cb_(1.0, status_message); } LOG(INFO) << "[" << status_id << "][" << status_error << "]: " << status_message; } if (status_id == SWUPDATER_STATUS_FAILURE) { // Work around a false positive condition if (status_message != "ERROR parser/parse_config.c : parse_cfg") { LOG(ERROR) << "SWUpdate failed with status: " << status_message; throw ifm3d::error_t(IFM3D_UPDATE_ERROR); } } std::this_thread::sleep_for(std::chrono::milliseconds(200)); } while (status_id != desired_status); return true; } std::tuple<int, std::string, int> ifm3d::SWUpdater::Impl::GetUpdaterStatus() { std::string status_string; int status_id; std::string status_message; int status_error; auto c = std::make_unique<ifm3d::SWUpdater::Impl::CURLTransaction>(); c->Call(curl_easy_setopt, CURLOPT_URL, this->status_url_.c_str()); c->Call(curl_easy_setopt, CURLOPT_WRITEFUNCTION, &ifm3d::SWUpdater::Impl::StatusWriteCallback); c->Call(curl_easy_setopt, CURLOPT_WRITEDATA, &status_string); c->Call(curl_easy_setopt, CURLOPT_CONNECTTIMEOUT, ifm3d::DEFAULT_CURL_CONNECT_TIMEOUT); c->Call(curl_easy_setopt, CURLOPT_TIMEOUT, ifm3d::DEFAULT_CURL_TRANSACTION_TIMEOUT); c->Call(curl_easy_perform); // Parse status auto json = nlohmann::json::parse(status_string.c_str()); status_id = std::stoi(json["Status"].get<std::string>()); status_error = std::stoi(json["Error"].get<std::string>()); status_message = json["Msg"]; return std::make_tuple(status_id, status_message, status_error); } #endif // __IFM3D_SWUPDATER_SWUPDATER_IMPL_H__
29.629433
79
0.614685
[ "vector" ]
112e32f3806d51fab764bc840986a4753bc9efd4
18,663
cc
C++
ash/fast_ink/fast_ink_host.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
ash/fast_ink/fast_ink_host.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
ash/fast_ink/fast_ink_host.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/fast_ink/fast_ink_host.h" #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <GLES2/gl2extchromium.h> #include <memory> #include "ash/public/cpp/ash_switches.h" #include "base/bind.h" #include "base/threading/thread_task_runner_handle.h" #include "cc/base/math_util.h" #include "cc/trees/layer_tree_frame_sink.h" #include "cc/trees/layer_tree_frame_sink_client.h" #include "components/viz/common/frame_timing_details.h" #include "components/viz/common/gpu/context_provider.h" #include "components/viz/common/hit_test/hit_test_region_list.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/quads/texture_draw_quad.h" #include "gpu/command_buffer/client/gpu_memory_buffer_manager.h" #include "gpu/command_buffer/client/shared_image_interface.h" #include "gpu/command_buffer/common/shared_image_usage.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #include "ui/aura/window_tree_host.h" #include "ui/gfx/geometry/dip_util.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/rect_conversions.h" #include "ui/gfx/geometry/size_conversions.h" #include "ui/gfx/gpu_memory_buffer.h" namespace fast_ink { // static gfx::Rect FastInkHost::BufferRectFromWindowRect( const gfx::Transform& window_to_buffer_transform, const gfx::Size& buffer_size, const gfx::Rect& window_rect) { gfx::Rect buffer_rect = cc::MathUtil::MapEnclosingClippedRect( window_to_buffer_transform, window_rect); // Buffer rect is not bigger than actual buffer. buffer_rect.Intersect(gfx::Rect(buffer_size)); return buffer_rect; } struct FastInkHost::Resource { Resource() = default; ~Resource() { // context_provider might be null in unit tests when ran with --mash // TODO(kaznacheev) Have MASH provide a context provider for tests // when https://crbug/772562 is fixed if (!context_provider) return; gpu::SharedImageInterface* sii = context_provider->SharedImageInterface(); DCHECK(!mailbox.IsZero()); sii->DestroySharedImage(sync_token, mailbox); } scoped_refptr<viz::ContextProvider> context_provider; gpu::Mailbox mailbox; gpu::SyncToken sync_token; bool damaged = true; }; class FastInkHost::LayerTreeFrameSinkHolder : public cc::LayerTreeFrameSinkClient, public aura::WindowObserver { public: LayerTreeFrameSinkHolder(FastInkHost* host, std::unique_ptr<cc::LayerTreeFrameSink> frame_sink) : host_(host), frame_sink_(std::move(frame_sink)) { frame_sink_->BindToClient(this); } ~LayerTreeFrameSinkHolder() override { if (frame_sink_) frame_sink_->DetachFromClient(); if (root_window_) root_window_->RemoveObserver(this); } LayerTreeFrameSinkHolder(const LayerTreeFrameSinkHolder&) = delete; LayerTreeFrameSinkHolder& operator=(const LayerTreeFrameSinkHolder&) = delete; // Delete frame sink after having reclaimed all exported resources. // Returns false if the it should be released instead of reset and it will // self destruct. // TODO(reveman): Find a better way to handle deletion of in-flight resources. // https://crbug.com/765763 bool DeleteWhenLastResourceHasBeenReclaimed() { if (last_frame_size_in_pixels_.IsEmpty()) { // Delete sink holder immediately if no frame has been submitted. DCHECK(exported_resources_.empty()); return true; } // Submit an empty frame to ensure that pending release callbacks will be // processed in a finite amount of time. viz::CompositorFrame frame; frame.metadata.begin_frame_ack.frame_id = viz::BeginFrameId(viz::BeginFrameArgs::kManualSourceId, viz::BeginFrameArgs::kStartingFrameNumber); frame.metadata.begin_frame_ack.has_damage = true; frame.metadata.device_scale_factor = last_frame_device_scale_factor_; frame.metadata.frame_token = ++next_frame_token_; auto pass = viz::CompositorRenderPass::Create(); pass->SetNew(viz::CompositorRenderPassId{1}, gfx::Rect(last_frame_size_in_pixels_), gfx::Rect(last_frame_size_in_pixels_), gfx::Transform()); frame.render_pass_list.push_back(std::move(pass)); frame_sink_->SubmitCompositorFrame(std::move(frame), /*hit_test_data_changed=*/true, /*show_hit_test_borders=*/false); // Delete sink holder immediately if not waiting for exported resources to // be reclaimed. if (exported_resources_.empty()) return true; // If we have exported resources to reclaim then extend the lifetime of // holder by deleting it later. // itself when the root window is removed or when all exported resources // have been reclaimed. root_window_ = host_->host_window()->GetRootWindow(); // This can be null during shutdown. if (!root_window_) return true; root_window_->AddObserver(this); host_ = nullptr; return false; } void SubmitCompositorFrame(viz::CompositorFrame frame, viz::ResourceId resource_id, std::unique_ptr<Resource> resource) { exported_resources_[resource_id] = std::move(resource); last_frame_size_in_pixels_ = frame.size_in_pixels(); last_frame_device_scale_factor_ = frame.metadata.device_scale_factor; frame.metadata.frame_token = ++next_frame_token_; frame_sink_->SubmitCompositorFrame(std::move(frame), /*hit_test_data_changed=*/true, /*show_hit_test_borders=*/false); } void DamageExportedResources() { for (auto& entry : exported_resources_) entry.second->damaged = true; } // Overridden from cc::LayerTreeFrameSinkClient: void SetBeginFrameSource(viz::BeginFrameSource* source) override {} base::Optional<viz::HitTestRegionList> BuildHitTestData() override { return {}; } void ReclaimResources( const std::vector<viz::ReturnedResource>& resources) override { if (delete_pending_) return; for (auto& entry : resources) { auto it = exported_resources_.find(entry.id); DCHECK(it != exported_resources_.end()); std::unique_ptr<Resource> resource = std::move(it->second); exported_resources_.erase(it); resource->sync_token = entry.sync_token; if (host_ && !entry.lost) host_->ReclaimResource(std::move(resource)); } if (root_window_ && exported_resources_.empty()) ScheduleDelete(); } void SetTreeActivationCallback(base::RepeatingClosure callback) override {} void DidReceiveCompositorFrameAck() override { if (host_) host_->DidReceiveCompositorFrameAck(); } void DidPresentCompositorFrame( uint32_t frame_token, const viz::FrameTimingDetails& details) override { if (host_) host_->DidPresentCompositorFrame(details.presentation_feedback); } void DidLoseLayerTreeFrameSink() override { exported_resources_.clear(); if (root_window_) ScheduleDelete(); } void OnDraw(const gfx::Transform& transform, const gfx::Rect& viewport, bool resourceless_software_draw, bool skip_draw) override {} void SetMemoryPolicy(const cc::ManagedMemoryPolicy& policy) override {} void SetExternalTilePriorityConstraints( const gfx::Rect& viewport_rect, const gfx::Transform& transform) override {} void OnWindowDestroying(aura::Window* window) override { root_window_->RemoveObserver(this); root_window_ = nullptr; frame_sink_->DetachFromClient(); frame_sink_.reset(); ScheduleDelete(); } private: void ScheduleDelete() { if (delete_pending_) return; delete_pending_ = true; base::ThreadTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); } FastInkHost* host_; std::unique_ptr<cc::LayerTreeFrameSink> frame_sink_; base::flat_map<viz::ResourceId, std::unique_ptr<Resource>> exported_resources_; viz::FrameTokenGenerator next_frame_token_; gfx::Size last_frame_size_in_pixels_; float last_frame_device_scale_factor_ = 1.0f; aura::Window* root_window_ = nullptr; bool delete_pending_ = false; }; FastInkHost::FastInkHost(aura::Window* host_window, const PresentationCallback& presentation_callback) : host_window_(host_window), presentation_callback_(presentation_callback) { // Take the root transform and apply this during buffer update instead of // leaving this up to the compositor. The benefit is that HW requirements // for being able to take advantage of overlays and direct scanout are // reduced significantly. Frames are submitted to the compositor with the // inverse transform to cancel out the transformation that would otherwise // be done by the compositor. window_to_buffer_transform_ = host_window_->GetHost()->GetRootTransform(); gfx::Rect bounds(host_window_->GetBoundsInScreen().size()); buffer_size_ = gfx::ToEnclosedRect(cc::MathUtil::MapClippedRect( window_to_buffer_transform_, gfx::RectF(bounds.width(), bounds.height()))) .size(); // Create a single GPU memory buffer. Content will be written into this // buffer without any buffering. The result is that we might be modifying // the buffer while it's being displayed. This provides minimal latency // but with potential tearing. Note that we have to draw into a temporary // surface and copy it into GPU memory buffer to avoid flicker. gpu_memory_buffer_ = aura::Env::GetInstance() ->context_factory() ->GetGpuMemoryBufferManager() ->CreateGpuMemoryBuffer(buffer_size_, SK_B32_SHIFT ? gfx::BufferFormat::RGBA_8888 : gfx::BufferFormat::BGRA_8888, gfx::BufferUsage::SCANOUT_CPU_READ_WRITE, gpu::kNullSurfaceHandle); LOG_IF(ERROR, !gpu_memory_buffer_) << "Failed to create GPU memory buffer"; if (ash::switches::ShouldClearFastInkBuffer()) { bool map_result = gpu_memory_buffer_->Map(); LOG_IF(ERROR, !map_result) << "Failed to map gpu buffer"; uint8_t* memory = static_cast<uint8_t*>(gpu_memory_buffer_->memory(0)); if (memory != nullptr) { gfx::Size size = gpu_memory_buffer_->GetSize(); int stride = gpu_memory_buffer_->stride(0); // Clear the buffer before usage, since it may be uninitialized. // (http://b/168735625) for (int i = 0; i < size.height(); ++i) memset(memory + i * stride, 0, size.width() * 4); } gpu_memory_buffer_->Unmap(); } frame_sink_holder_ = std::make_unique<LayerTreeFrameSinkHolder>( this, host_window_->CreateLayerTreeFrameSink()); } FastInkHost::~FastInkHost() { if (!frame_sink_holder_->DeleteWhenLastResourceHasBeenReclaimed()) frame_sink_holder_.release(); } void FastInkHost::UpdateSurface(const gfx::Rect& content_rect, const gfx::Rect& damage_rect, bool auto_refresh) { content_rect_ = content_rect; damage_rect_.Union(damage_rect); auto_refresh_ = auto_refresh; pending_compositor_frame_ = true; if (!damage_rect.IsEmpty()) { frame_sink_holder_->DamageExportedResources(); for (auto& resource : returned_resources_) resource->damaged = true; } if (!pending_compositor_frame_ack_) SubmitCompositorFrame(); } void FastInkHost::SubmitCompositorFrame() { TRACE_EVENT1("ui", "FastInkHost::SubmitCompositorFrame", "damage", damage_rect_.ToString()); float device_scale_factor = host_window_->layer()->device_scale_factor(); gfx::Size window_size_in_dip = host_window_->GetBoundsInScreen().size(); // TODO(crbug.com/1131619): Should this be ceil? Why do we choose floor? gfx::Size window_size_in_pixel = gfx::ToFlooredSize( gfx::ConvertSizeToPixels(window_size_in_dip, device_scale_factor)); gfx::Rect output_rect(window_size_in_pixel); gfx::Rect quad_rect; gfx::Rect damage_rect; // Continuously redraw the full output rectangle when in auto-refresh mode. // This is necessary in order to allow single buffered updates without having // buffer changes outside the contents area cause artifacts. if (auto_refresh_) { quad_rect = gfx::Rect(buffer_size_); damage_rect = gfx::Rect(output_rect); } else { // Use minimal quad and damage rectangles when auto-refresh mode is off. quad_rect = BufferRectFromWindowRect(window_to_buffer_transform_, buffer_size_, content_rect_); damage_rect = gfx::ToEnclosingRect( gfx::ConvertRectToPixels(damage_rect_, device_scale_factor)); damage_rect.Intersect(output_rect); pending_compositor_frame_ = false; } damage_rect_ = gfx::Rect(); std::unique_ptr<Resource> resource; // Reuse returned resource if available. if (!returned_resources_.empty()) { resource = std::move(returned_resources_.back()); returned_resources_.pop_back(); } // Create new resource if needed. if (!resource) resource = std::make_unique<Resource>(); if (resource->damaged) { // Acquire context provider for resource if needed. // Note: We make no attempts to recover if the context provider is later // lost. It is expected that this class is short-lived and requiring a // new instance to be created in lost context situations is acceptable and // keeps the code simple. if (!resource->context_provider) { resource->context_provider = aura::Env::GetInstance() ->context_factory() ->SharedMainThreadContextProvider(); if (!resource->context_provider) { LOG(ERROR) << "Failed to acquire a context provider"; return; } } gpu::SharedImageInterface* sii = resource->context_provider->SharedImageInterface(); if (resource->mailbox.IsZero()) { DCHECK(!resource->sync_token.HasData()); const uint32_t usage = gpu::SHARED_IMAGE_USAGE_DISPLAY | gpu::SHARED_IMAGE_USAGE_SCANOUT; gpu::GpuMemoryBufferManager* gmb_manager = aura::Env::GetInstance() ->context_factory() ->GetGpuMemoryBufferManager(); resource->mailbox = sii->CreateSharedImage( gpu_memory_buffer_.get(), gmb_manager, gfx::ColorSpace(), kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, usage); } else { sii->UpdateSharedImage(resource->sync_token, resource->mailbox); } resource->sync_token = sii->GenVerifiedSyncToken(); resource->damaged = false; } viz::TransferableResource transferable_resource; transferable_resource.id = id_generator_.GenerateNextId(); transferable_resource.format = viz::RGBA_8888; transferable_resource.filter = GL_LINEAR; transferable_resource.size = buffer_size_; transferable_resource.mailbox_holder = gpu::MailboxHolder( resource->mailbox, resource->sync_token, GL_TEXTURE_2D); // Use HW overlay if continuous updates are expected. transferable_resource.is_overlay_candidate = auto_refresh_; gfx::Transform target_to_buffer_transform(window_to_buffer_transform_); target_to_buffer_transform.Scale(1.f / device_scale_factor, 1.f / device_scale_factor); gfx::Transform buffer_to_target_transform; bool rv = target_to_buffer_transform.GetInverse(&buffer_to_target_transform); DCHECK(rv); const viz::CompositorRenderPassId kRenderPassId{1}; auto render_pass = viz::CompositorRenderPass::Create(); render_pass->SetNew(kRenderPassId, output_rect, damage_rect, buffer_to_target_transform); viz::SharedQuadState* quad_state = render_pass->CreateAndAppendSharedQuadState(); quad_state->SetAll( buffer_to_target_transform, /*quad_layer_rect=*/output_rect, /*visible_quad_layer_rect=*/output_rect, /*mask_filter_info=*/gfx::MaskFilterInfo(), /*clip_rect=*/gfx::Rect(), /*is_clipped=*/false, /*are_contents_opaque=*/false, /*opacity=*/1.f, /*blend_mode=*/SkBlendMode::kSrcOver, /*sorting_context_id=*/0); viz::CompositorFrame frame; // TODO(eseckler): FastInkHost should use BeginFrames and set the ack // accordingly. frame.metadata.begin_frame_ack = viz::BeginFrameAck::CreateManualAckWithDamage(); frame.metadata.device_scale_factor = device_scale_factor; viz::TextureDrawQuad* texture_quad = render_pass->CreateAndAppendDrawQuad<viz::TextureDrawQuad>(); float vertex_opacity[4] = {1.0f, 1.0f, 1.0f, 1.0f}; gfx::RectF uv_crop(quad_rect); uv_crop.Scale(1.f / buffer_size_.width(), 1.f / buffer_size_.height()); texture_quad->SetNew( quad_state, quad_rect, quad_rect, /*needs_blending=*/true, transferable_resource.id, /*premultiplied_alpha=*/true, uv_crop.origin(), uv_crop.bottom_right(), /*background_color=*/SK_ColorTRANSPARENT, vertex_opacity, /*y_flipped=*/false, /*nearest_neighbor=*/false, /*secure_output_only=*/false, gfx::ProtectedVideoType::kClear); texture_quad->set_resource_size_in_pixels(transferable_resource.size); frame.resource_list.push_back(transferable_resource); DCHECK(!pending_compositor_frame_ack_); pending_compositor_frame_ack_ = true; frame.render_pass_list.push_back(std::move(render_pass)); frame_sink_holder_->SubmitCompositorFrame( std::move(frame), transferable_resource.id, std::move(resource)); } void FastInkHost::SubmitPendingCompositorFrame() { if (pending_compositor_frame_ && !pending_compositor_frame_ack_) SubmitCompositorFrame(); } void FastInkHost::DidReceiveCompositorFrameAck() { pending_compositor_frame_ack_ = false; if (pending_compositor_frame_) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&FastInkHost::SubmitPendingCompositorFrame, weak_ptr_factory_.GetWeakPtr())); } } void FastInkHost::DidPresentCompositorFrame( const gfx::PresentationFeedback& feedback) { if (!presentation_callback_.is_null()) presentation_callback_.Run(feedback); } void FastInkHost::ReclaimResource(std::unique_ptr<Resource> resource) { returned_resources_.push_back(std::move(resource)); } } // namespace fast_ink
39.540254
80
0.70396
[ "geometry", "vector", "transform" ]
1136e8834c2888bf2a01890411d46594503f53d2
10,622
hpp
C++
process/bstats.hpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
process/bstats.hpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
process/bstats.hpp
CESNET/NEMEA-probe
c2c3cc3ba96e51bc241908b9b228ec3f2d73ef97
[ "BSD-3-Clause" ]
null
null
null
/** * \file bstats.hpp * \brief Plugin for parsing bstats traffic. * \author Karel Hynek <hynekkar@fit.cvut.cz> * \date 2020 */ /* * Copyright (C) 2020 CESNET * * LICENSE TERMS * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of the Company nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * ALTERNATIVELY, provided that this notice is retained in full, this * product may be distributed under the terms of the GNU General Public * License (GPL) version 2 or later, in which case the provisions * of the GPL apply INSTEAD OF those given above. * * This software is provided as is'', and any express or implied * warranties, including, but not limited to, the implied warranties of * merchantability and fitness for a particular purpose are disclaimed. * In no event shall the company or contributors be liable for any * direct, indirect, incidental, special, exemplary, or consequential * damages (including, but not limited to, procurement of substitute * goods or services; loss of use, data, or profits; or business * interruption) however caused and on any theory of liability, whether * in contract, strict liability, or tort (including negligence or * otherwise) arising in any way out of the use of this software, even * if advised of the possibility of such damage. * */ #ifndef IPXP_PROCESS_BSTATS_HPP #define IPXP_PROCESS_BSTATS_HPP #include <string> #include <cstring> #include <sstream> #include <vector> #ifdef WITH_NEMEA # include "fields.h" #endif #include <ipfixprobe/process.hpp> #include <ipfixprobe/flowifc.hpp> #include <ipfixprobe/packet.hpp> #include <ipfixprobe/ipfix-basiclist.hpp> #include <ipfixprobe/ipfix-elements.hpp> namespace ipxp { #define BSTATS_MAXELENCOUNT 15 // BURST CHARACTERISTIC #define MINIMAL_PACKETS_IN_BURST 3 // in packets #define MAXIMAL_INTERPKT_TIME 1000 // in miliseconds // maximal time between consecutive in-burst packets #define BSTATS_SOURCE 0 #define BSTATS_DEST 1 #define BSTATS_UNIREC_TEMPLATE "SBI_BRST_PACKETS,SBI_BRST_BYTES,SBI_BRST_TIME_START,SBI_BRST_TIME_STOP,\ DBI_BRST_PACKETS,DBI_BRST_BYTES,DBI_BRST_TIME_START,DBI_BRST_TIME_STOP" UR_FIELDS( uint32* SBI_BRST_BYTES, uint32* SBI_BRST_PACKETS, time* SBI_BRST_TIME_START, time* SBI_BRST_TIME_STOP, uint32* DBI_BRST_PACKETS, uint32* DBI_BRST_BYTES, time* DBI_BRST_TIME_START, time* DBI_BRST_TIME_STOP ) /** * \brief Flow record extension header for storing parsed BSTATS packets. */ struct RecordExtBSTATS : public RecordExt { typedef enum eHdrFieldID { SPkts = 1050, SBytes = 1051, SStart = 1052, SStop = 1053, DPkts = 1054, DBytes = 1055, DStart = 1056, DStop = 1057 } eHdrFieldID; static int REGISTERED_ID; uint16_t burst_count[2]; uint8_t burst_empty[2]; uint32_t brst_pkts[2][BSTATS_MAXELENCOUNT]; uint32_t brst_bytes[2][BSTATS_MAXELENCOUNT]; struct timeval brst_start[2][BSTATS_MAXELENCOUNT]; struct timeval brst_end[2][BSTATS_MAXELENCOUNT]; RecordExtBSTATS() : RecordExt(REGISTERED_ID) { memset(burst_count, 0, 2 * sizeof(uint16_t)); memset(burst_empty, 0, 2 * sizeof(uint8_t)); brst_pkts[BSTATS_DEST][0] = 0; brst_pkts[BSTATS_SOURCE][0] = 0; } #ifdef WITH_NEMEA virtual void fill_unirec(ur_template_t *tmplt, void *record) { ur_time_t ts_start, ts_stop; ur_array_allocate(tmplt, record, F_SBI_BRST_PACKETS, burst_count[BSTATS_SOURCE]); ur_array_allocate(tmplt, record, F_SBI_BRST_BYTES, burst_count[BSTATS_SOURCE]); ur_array_allocate(tmplt, record, F_SBI_BRST_TIME_START, burst_count[BSTATS_SOURCE]); ur_array_allocate(tmplt, record, F_SBI_BRST_TIME_STOP, burst_count[BSTATS_SOURCE]); ur_array_allocate(tmplt, record, F_DBI_BRST_PACKETS, burst_count[BSTATS_DEST]); ur_array_allocate(tmplt, record, F_DBI_BRST_BYTES, burst_count[BSTATS_DEST]); ur_array_allocate(tmplt, record, F_DBI_BRST_TIME_START, burst_count[BSTATS_DEST]); ur_array_allocate(tmplt, record, F_DBI_BRST_TIME_STOP, burst_count[BSTATS_DEST]); for (int i = 0; i < burst_count[BSTATS_SOURCE]; i++){ ts_start = ur_time_from_sec_usec(brst_start[BSTATS_SOURCE][i].tv_sec, brst_start[BSTATS_SOURCE][i].tv_usec); ts_stop = ur_time_from_sec_usec(brst_end[BSTATS_SOURCE][i].tv_sec, brst_end[BSTATS_SOURCE][i].tv_usec); ur_array_set(tmplt, record, F_SBI_BRST_PACKETS, i, brst_pkts[BSTATS_SOURCE][i]); ur_array_set(tmplt, record, F_SBI_BRST_BYTES, i, brst_bytes[BSTATS_SOURCE][i]); ur_array_set(tmplt, record, F_SBI_BRST_TIME_START, i, ts_start); ur_array_set(tmplt, record, F_SBI_BRST_TIME_STOP, i, ts_stop); } for (int i = 0; i < burst_count[BSTATS_DEST]; i++){ ts_start = ur_time_from_sec_usec(brst_start[BSTATS_DEST][i].tv_sec, brst_start[BSTATS_DEST][i].tv_usec); ts_stop = ur_time_from_sec_usec(brst_end[BSTATS_DEST][i].tv_sec, brst_end[BSTATS_DEST][i].tv_usec); ur_array_set(tmplt, record, F_DBI_BRST_PACKETS, i, brst_pkts[BSTATS_DEST][i]); ur_array_set(tmplt, record, F_DBI_BRST_BYTES, i, brst_bytes[BSTATS_DEST][i]); ur_array_set(tmplt, record, F_DBI_BRST_TIME_START, i, ts_start); ur_array_set(tmplt, record, F_DBI_BRST_TIME_STOP, i, ts_stop); } } const char *get_unirec_tmplt() const { return BSTATS_UNIREC_TEMPLATE; } #endif // ifdef WITH_NEMEA virtual int fill_ipfix(uint8_t *buffer, int size) { int32_t bufferPtr; IpfixBasicList basiclist; basiclist.hdrEnterpriseNum = IpfixBasicList::CesnetPEM; // Check sufficient size of buffer int req_size = 8 * basiclist.HeaderSize() /* sizes, times, flags, dirs */ + 2 * burst_count[BSTATS_SOURCE] * sizeof(uint32_t) /* bytes+sizes */ + 2 * burst_count[BSTATS_SOURCE] * sizeof(uint64_t) /* times_start + time_end */ + 2 * burst_count[BSTATS_DEST] * sizeof(uint32_t) /* bytes+sizes */ + 2 * burst_count[BSTATS_DEST] * sizeof(uint64_t) /* times_start + time_end */; if (req_size > size){ return -1; } // Fill buffer bufferPtr = basiclist.FillBuffer(buffer, brst_pkts[BSTATS_SOURCE], burst_count[BSTATS_SOURCE], (uint16_t) SPkts); bufferPtr += basiclist.FillBuffer(buffer + bufferPtr, brst_bytes[BSTATS_SOURCE], burst_count[BSTATS_SOURCE], (uint16_t) SBytes); bufferPtr += basiclist.FillBuffer(buffer + bufferPtr, brst_start[BSTATS_SOURCE], burst_count[BSTATS_SOURCE], (uint16_t) SStart); bufferPtr += basiclist.FillBuffer(buffer + bufferPtr, brst_end[BSTATS_SOURCE], burst_count[BSTATS_SOURCE], (uint16_t) SStop); bufferPtr += basiclist.FillBuffer(buffer + bufferPtr, brst_pkts[BSTATS_DEST], burst_count[BSTATS_DEST], (uint16_t) DPkts); bufferPtr += basiclist.FillBuffer(buffer + bufferPtr, brst_bytes[BSTATS_DEST], burst_count[BSTATS_DEST], (uint16_t) DBytes); bufferPtr += basiclist.FillBuffer(buffer + bufferPtr, brst_start[BSTATS_DEST], burst_count[BSTATS_DEST], (uint16_t) DStart); bufferPtr += basiclist.FillBuffer(buffer + bufferPtr, brst_end[BSTATS_DEST], burst_count[BSTATS_DEST], (uint16_t) DStop); return bufferPtr; } const char **get_ipfix_tmplt() const { static const char *ipfix_tmplt[] = { IPFIX_BSTATS_TEMPLATE(IPFIX_FIELD_NAMES) nullptr }; return ipfix_tmplt; } std::string get_text() const { std::ostringstream out; char dirs_c[2] = {'s', 'd'}; int dirs[2] = {BSTATS_SOURCE, BSTATS_DEST}; for (int j = 0; j < 2; j++) { int dir = dirs[j]; out << dirs_c[j] << "burstpkts=("; for (int i = 0; i < burst_count[dir]; i++) { out << brst_pkts[dir][i]; if (i != burst_count[dir] - 1) { out << ","; } } out << ")," << dirs_c[j] << "burstbytes=("; for (int i = 0; i < burst_count[dir]; i++) { out << brst_bytes[dir][i]; if (i != burst_count[dir] - 1) { out << ","; } } out << ")," << dirs_c[j] << "bursttime=("; for (int i = 0; i < burst_count[dir]; i++) { struct timeval start = brst_start[dir][i]; struct timeval end = brst_end[dir][i]; out << start.tv_sec << "." << start.tv_usec << "-" << end.tv_sec << "." << end.tv_usec; if (i != burst_count[dir] - 1) { out << ","; } } out << "),"; } return out.str(); } }; /** * \brief Flow cache plugin for parsing BSTATS packets. */ class BSTATSPlugin : public ProcessPlugin { public: BSTATSPlugin(); ~BSTATSPlugin(); void init(const char *params); void close(); OptionsParser *get_parser() const { return new OptionsParser("bstats", "Compute packet bursts stats"); } std::string get_name() const { return "bstats"; } RecordExt *get_ext() const { return new RecordExtBSTATS(); } ProcessPlugin *copy(); int pre_create(Packet &pkt); int post_create(Flow &rec, const Packet &pkt); int pre_update(Flow &rec, Packet &pkt); int post_update(Flow &rec, const Packet &pkt); void pre_export(Flow &rec); static const struct timeval min_packet_in_burst; private: void initialize_new_burst(RecordExtBSTATS *bstats_record, uint8_t direction, const Packet &pkt); void process_bursts(RecordExtBSTATS *bstats_record, uint8_t direction, const Packet &pkt); void update_record(RecordExtBSTATS *bstats_record, const Packet &pkt); bool isLastRecordBurst(RecordExtBSTATS *bstats_record, uint8_t direction); bool belogsToLastRecord(RecordExtBSTATS *bstats_record, uint8_t direction, const Packet &pkt); }; } #endif /* IPXP_PROCESS_BSTATS_HPP */
38.208633
120
0.677085
[ "vector" ]
1137b667fd7cea6cd404140ba6355107cd6da4e5
4,567
cc
C++
daily/day6.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
daily/day6.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
daily/day6.cc
snow-tyan/learn-cpp
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
[ "MulanPSL-1.0" ]
null
null
null
#include <math.h> #include <iostream> #include <string> #include <set> #include <map> #include <unordered_set> #include <vector> #include <queue> using namespace std; template <class T> void printMp(T &t) { typename T::const_iterator cit = t.begin(); for (; cit != t.end(); ++cit) { cout << cit->first << "-->" << cit->second << endl; } } template <class T> void print(T &t) { typename T::const_iterator cit = t.begin(); for (; cit != t.end(); ++cit) { cout << *cit << " "; } cout << endl; } void test0() { set<int> st = {1, 1, 1, 2, 3, 4, 5}; multiset<int> mst = {1, 1, 1, 2, 3, 4, 5}; auto ret = st.insert(6); if (ret.second) cout << "success" << endl; else cout << "failed" << endl; cout << st.count(1) << endl; cout << *st.find(1) << endl; cout << mst.count(1) << endl; auto it = mst.find(1); cout << *it << endl; ++it; cout << *it << endl; ++it; cout << *it << endl; ++it; cout << *it << endl; } void test1() { map<int, string> mp = { make_pair(1, "Beijing"), make_pair(2, "Shanghai"), make_pair(3, "Guangzhou"), make_pair(4, "Shenzhen"), }; mp.insert(make_pair(4, "Hangzhou")); //添加失败 printMp(mp); mp[4] = "Hangzhou"; //修改 printMp(mp); mp[5] = "Nanjing"; // 添加 printMp(mp); } void test2() { multimap<int, string> mp = { make_pair(1, "Beijing"), make_pair(2, "Shanghai"), make_pair(3, "Guangzhou"), make_pair(4, "Shenzhen"), }; mp.insert(make_pair(4, "Hangzhou")); printMp(mp); } void test3() { vector<int> nums = {5, 7, 3, 4, 1, 9, 8, 6, 2}; unordered_set<int> unst(nums.begin(), nums.end()); print(unst); } class Point { public: Point() = default; Point(int ix, int iy) : _ix(ix), _iy(iy) {} double getDistance() const { return sqrt(_ix * _ix + _iy * _iy); } int getX() const { return _ix; } int getY() const { return _iy; } friend ostream &operator<<(ostream &os, const Point &pt); private: int _ix = 0; int _iy = 0; }; ostream &operator<<(ostream &os, const Point &pt) { return os << "(" << pt._ix << "," << pt._iy << ")"; } bool operator==(const Point &pt1, const Point &pt2) { return pt1.getX() == pt2.getX() && pt1.getY() == pt2.getY(); } namespace std { template <> struct hash<Point> //实现hash函数 { size_t operator()(const Point &pt) const { return (pt.getX() * pt.getX() - 1) ^ (pt.getY() * pt.getY() - 1); } }; } // namespace std //使用自己的Hash struct PointHasher { size_t operator()(const Point &pt) const { return (pt.getX() * pt.getX() - 1) ^ (pt.getY() * pt.getY() - 1); } }; //使用自己的比较规则 struct PointEqual { bool operator()(const Point &pt1, const Point &pt2) const { return pt1.getX() == pt2.getX() && pt1.getY() == pt2.getY(); } }; void test4() { unordered_set<Point, PointHasher, PointEqual> unst{ Point(1, 1), Point(2, 2), Point(3, 3), Point(), }; print(unst); } void test5() { vector<int> nums = {5, 7, 3, 4, 1, 9, 8, 6, 2}; priority_queue<int> pque(nums.begin(), nums.end()); //默认小于符号比较,大顶堆 while (!pque.empty()) { cout << pque.top() << " "; pque.pop(); } cout << endl; } void test6() { vector<int> nums = {5, 7, 3, 4, 1, 9, 8, 6, 2}; priority_queue<int> pque; for (auto it = nums.begin(); it != nums.end(); ++it) { pque.push(*it); } while (!pque.empty()) { cout << pque.top() << " "; pque.pop(); } cout << endl; } struct PointCompare { bool operator()(const Point &pt1, const Point &pt2) const { return pt1.getDistance() < pt2.getDistance(); //小于符号 大顶堆;大于符号,小顶堆 } }; void test7() //自定义类型 { vector<Point> vpt = {Point(1, 1), Point(1, 2), Point(2, 1), Point(2, 2), Point(3, 3), Point()}; priority_queue<Point, vector<Point>, PointCompare> pqpt(vpt.begin(), vpt.end()); while (!pqpt.empty()) { cout << pqpt.top() << " "; pqpt.pop(); } cout << endl; } void test8() { unordered_set<int> unset(100); // 人为指定桶数量 for (int i = 0; i < 20; ++i) { unset.insert(i*i); cout << unset.size() << " " << unset.bucket_count() << endl; } } int main() { // test0(); // test1(); // test2(); // test3(); // test4(); // test5(); // test6(); // test7(); test8(); return 0; }
20.388393
99
0.506678
[ "vector" ]
113fdaba633b9e9ce3b5f6267e080f2ded926c7e
28,879
cpp
C++
src/openms_gui/source/VISUAL/TOPPViewIdentificationViewBehavior.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
src/openms_gui/source/VISUAL/TOPPViewIdentificationViewBehavior.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
src/openms_gui/source/VISUAL/TOPPViewIdentificationViewBehavior.cpp
mrurik/OpenMS
3bf48247423dc28a7df7b12b72fbc7751965c321
[ "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2016. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Timo Sachsenberg $ // -------------------------------------------------------------------------- #include <OpenMS/CHEMISTRY/IsotopeDistribution.h> #include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h> #include <OpenMS/VISUAL/Spectrum1DWidget.h> #include <OpenMS/VISUAL/TOPPViewIdentificationViewBehavior.h> #include <OpenMS/VISUAL/ANNOTATION/Annotation1DItem.h> #include <OpenMS/VISUAL/ANNOTATION/Annotation1DDistanceItem.h> #include <OpenMS/VISUAL/ANNOTATION/Annotation1DPeakItem.h> #include <OpenMS/VISUAL/ANNOTATION/Annotation1DCaret.h> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/CHEMISTRY/Residue.h> #include <OpenMS/FILTERING/ID/IDFilter.h> #include <QtGui/QMessageBox> #include <QtCore/QString> using namespace OpenMS; using namespace std; namespace OpenMS { TOPPViewIdentificationViewBehavior::TOPPViewIdentificationViewBehavior(TOPPViewBase * parent) : tv_(parent) { } void TOPPViewIdentificationViewBehavior::showSpectrumAs1D(int index) { // basic behavior 1 const LayerData & layer = tv_->getActiveCanvas()->getCurrentLayer(); ExperimentSharedPtrType exp_sptr = layer.getPeakData(); if (layer.type == LayerData::DT_PEAK) { // open new 1D widget with the current default parameters Spectrum1DWidget* w = new Spectrum1DWidget(tv_->getSpectrumParameters(1), (QWidget *)tv_->getWorkspace()); // add data if (!w->canvas()->addLayer(exp_sptr, layer.filename) || (Size)index >= w->canvas()->getCurrentLayer().getPeakData()->size()) { return; } w->canvas()->activateSpectrum(index); // set relative (%) view of visible area w->canvas()->setIntensityMode(SpectrumCanvas::IM_SNAP); // for MS1 spectra set visible area to visible area in 2D view. UInt ms_level = w->canvas()->getCurrentLayer().getCurrentSpectrum().getMSLevel(); if (ms_level == 1) { // set visible area to visible area in 2D view SpectrumCanvas::AreaType a = tv_->getActiveCanvas()->getVisibleArea(); w->canvas()->setVisibleArea(a); } String caption = layer.name; w->canvas()->setLayerName(w->canvas()->activeLayerIndex(), caption); tv_->showSpectrumWidgetInWindow(w, caption); // special behavior const vector<PeptideIdentification>& pi = w->canvas()->getCurrentLayer().getCurrentSpectrum().getPeptideIdentifications(); if (!pi.empty()) { // mass fingerprint annotation of name etc if (ms_level == 1) addPeakAnnotations_(pi); PeptideHit hit; if (IDFilter().getBestHit(pi, false, hit)) { addTheoreticalSpectrumLayer_(hit); } else { LOG_ERROR << "Spectrum has no hits" << std::endl; } } tv_->updateLayerBar(); tv_->updateViewBar(); tv_->updateFilterBar(); tv_->updateMenu(); } else if (layer.type == LayerData::DT_CHROMATOGRAM) { } } void TOPPViewIdentificationViewBehavior::addPeakAnnotations_(const std::vector<PeptideIdentification>& ph) { // called anew for every click on a spectrum LayerData& current_layer = tv_->getActive1DWidget()->canvas()->getCurrentLayer(); if (current_layer.getCurrentSpectrum().empty()) { LOG_WARN << "Spectrum is empty! Nothing to annotate!" << std::endl; } // mass precision to match a peak's m/z to a feature m/z // m/z values of features are usually an average over multiple scans... double ppm = 0.5; std::vector<QColor> cols; cols.push_back(Qt::blue); cols.push_back(Qt::green); cols.push_back(Qt::red); cols.push_back(Qt::gray); cols.push_back(Qt::darkYellow); if (!current_layer.getCurrentSpectrum().isSorted()) { QMessageBox::warning(tv_, "Error", "The spectrum is not sorted! Aborting!"); return; } for (std::vector<PeptideIdentification>::const_iterator it = ph.begin(); it!= ph.end(); ++it) { if (!it->hasMZ()) continue; double mz = it->getMZ(); Size peak_idx = current_layer.getCurrentSpectrum().findNearest(mz); // m/z fits ? if ( abs(mz - current_layer.getCurrentSpectrum()[peak_idx].getMZ()) / mz * 1e6 > ppm) continue; double peak_int = current_layer.getCurrentSpectrum()[peak_idx].getIntensity(); Annotation1DCaret* first_dit(0); // we could have many many hits for different compounds which have the exact same sum formula... so first group by sum formula std::map<String, StringList> formula_to_names; for (std::vector< PeptideHit >::const_iterator ith = it->getHits().begin(); ith!= it->getHits().end(); ++ith) { if (ith->metaValueExists("identifier") && ith->metaValueExists("chemical_formula")) { String name = ith->getMetaValue("identifier"); if (name.length() > 20) { name = name.substr(0, 17) + "..."; } formula_to_names[ith->getMetaValue("chemical_formula")].push_back(name); } else { StringList msg; if (!ith->metaValueExists("identifier")) msg.push_back("identifier"); if (!ith->metaValueExists("chemical_formula")) msg.push_back("chemical_formula"); LOG_WARN << "Missing meta-value(s): " << ListUtils::concatenate(msg, ", ") << ". Cannot annotate!\n"; } } // assemble annotation (each formula gets a paragraph) String text = "<html><body>"; Size i(0); for (std::map<String, StringList>::iterator ith = formula_to_names.begin(); ith!= formula_to_names.end(); ++ith) { if (++i >= 4) { // at this point, this is the 4th entry.. which we don't show any more... text += String("<b><span style=\"color:") + cols[i].name() + "\">..." + Size(std::distance(formula_to_names.begin(), formula_to_names.end()) - 4 + 1) + " more</span></b><br>"; break; } text += String("<b><span style=\"color:") + cols[i].name() + "\">" + ith->first + "</span></b><br>\n"; // carets for isotope profile EmpiricalFormula ef(ith->first); IsotopeDistribution id = ef.getIsotopeDistribution(3); // three isotopes at most double int_factor = peak_int / id.begin()->second; Annotation1DCaret::PositionsType points; Size itic(0); for (IsotopeDistribution::ConstIterator iti = id.begin(); iti != id.end(); ++iti) { points.push_back(Annotation1DCaret::PointType(mz + itic*Constants::C13C12_MASSDIFF_U, iti->second * int_factor)); ++itic; } Annotation1DCaret* ditem = new Annotation1DCaret(points, QString(), cols[i]); ditem->setSelected(false); temporary_annotations_.push_back(ditem); // for removal (no ownership) current_layer.getCurrentAnnotations().push_front(ditem); // for visualization (ownership) if (first_dit==0) first_dit = ditem; // remember first item (we append the text, when ready) // list of compound names (shorten if required) if (ith->second.size() > 3) { Size s = ith->second.size(); ith->second[3] = String("...") + (s-3) + " more"; ith->second.resize(4); } text += " - " + ListUtils::concatenate(ith->second, "<br> - ") + "<br>\n"; } text += "</body></html>"; if (first_dit!=0) { first_dit->setRichText(text.toQString()); } } } void TOPPViewIdentificationViewBehavior::activate1DSpectrum(int index) { Spectrum1DWidget * widget_1D = tv_->getActive1DWidget(); widget_1D->canvas()->activateSpectrum(index); const LayerData & current_layer = widget_1D->canvas()->getCurrentLayer(); if (current_layer.type == LayerData::DT_PEAK) { UInt ms_level = current_layer.getCurrentSpectrum().getMSLevel(); if (ms_level == 2) // show theoretical spectrum with automatic alignment { vector<PeptideIdentification> pi = current_layer.getCurrentSpectrum().getPeptideIdentifications(); if (!pi.empty()) { PeptideHit hit; if (IDFilter().getBestHit(pi, false, hit)) addTheoreticalSpectrumLayer_(hit); else LOG_ERROR << "Spectrum has no hits\n"; } } else if (ms_level == 1) // show precursor locations { const vector<PeptideIdentification>& pi = current_layer.getCurrentSpectrum().getPeptideIdentifications(); addPeakAnnotations_(pi); vector<Precursor> precursors; // collect all MS2 spectra precursor till next MS1 spectrum is encountered for (Size i = index + 1; i < current_layer.getPeakData()->size(); ++i) { if ((*current_layer.getPeakData())[i].getMSLevel() == 1) { break; } // skip MS2 without precursor if ((*current_layer.getPeakData())[i].getPrecursors().empty()) { continue; } // there should be only one precursor per MS2 spectrum. vector<Precursor> pcs = (*current_layer.getPeakData())[i].getPrecursors(); copy(pcs.begin(), pcs.end(), back_inserter(precursors)); } addPrecursorLabels1D_(precursors); } } // end DT_PEAK else if (current_layer.type == LayerData::DT_CHROMATOGRAM) { } } void TOPPViewIdentificationViewBehavior::addPrecursorLabels1D_(const vector<Precursor> & pcs) { LayerData & current_layer = tv_->getActive1DWidget()->canvas()->getCurrentLayer(); if (current_layer.type == LayerData::DT_PEAK) { const SpectrumType& spectrum = current_layer.getCurrentSpectrum(); for (vector<Precursor>::const_iterator it = pcs.begin(); it != pcs.end(); ++it) { // determine start and stop of isolation window double isolation_window_lower_mz = it->getMZ() - it->getIsolationWindowLowerOffset(); double isolation_window_upper_mz = it->getMZ() + it->getIsolationWindowUpperOffset(); // determine maximum peak intensity in isolation window SpectrumType::const_iterator vbegin = spectrum.MZBegin(isolation_window_lower_mz); SpectrumType::const_iterator vend = spectrum.MZEnd(isolation_window_upper_mz); double max_intensity = (numeric_limits<double>::min)(); for (; vbegin != vend; ++vbegin) { if (vbegin->getIntensity() > max_intensity) { max_intensity = vbegin->getIntensity(); } } // DPosition<2> precursor_position = DPosition<2>(it->getMZ(), max_intensity); DPosition<2> lower_position = DPosition<2>(isolation_window_lower_mz, max_intensity); DPosition<2> upper_position = DPosition<2>(isolation_window_upper_mz, max_intensity); Annotation1DDistanceItem * item = new Annotation1DDistanceItem(QString::number(it->getCharge()), lower_position, upper_position); // add additional tick at precursor target position (e.g. to show if isolation window is assymetric) vector<double> ticks; ticks.push_back(it->getMZ()); item->setTicks(ticks); item->setSelected(false); temporary_annotations_.push_back(item); // for removal (no ownership) current_layer.getCurrentAnnotations().push_front(item); // for visualisation (ownership) } } else if (current_layer.type == LayerData::DT_CHROMATOGRAM) { } } /// Behavior for activate1DSpectrum void TOPPViewIdentificationViewBehavior::activate1DSpectrum(std::vector<int, std::allocator<int> >) { } void TOPPViewIdentificationViewBehavior::removeTemporaryAnnotations_(Size spectrum_index) { #ifdef DEBUG_IDENTIFICATION_VIEW cout << "removePrecursorLabels1D_ " << spectrum_index << endl; #endif // Delete annotations added by IdentificationView (but not user added annotations) LayerData & current_layer = tv_->getActive1DWidget()->canvas()->getCurrentLayer(); const vector<Annotation1DItem *> & cas = temporary_annotations_; Annotations1DContainer & las = current_layer.getAnnotations(spectrum_index); for (vector<Annotation1DItem *>::const_iterator it = cas.begin(); it != cas.end(); ++it) { Annotations1DContainer::iterator i = find(las.begin(), las.end(), *it); if (i != las.end()) { delete(*i); las.erase(i); } } temporary_annotations_.clear(); } void TOPPViewIdentificationViewBehavior::addTheoreticalSpectrumLayer_(const PeptideHit & ph) { SpectrumCanvas * current_canvas = tv_->getActive1DWidget()->canvas(); LayerData & current_layer = current_canvas->getCurrentLayer(); SpectrumType & current_spectrum = current_layer.getCurrentSpectrum(); AASequence aa_sequence = ph.getSequence(); // get measured spectrum indices and spectrum Size current_spectrum_layer_index = current_canvas->activeLayerIndex(); Size current_spectrum_index = current_layer.getCurrentSpectrumIndex(); const Param & tv_params = tv_->getParameters(); RichPeakSpectrum rich_spec; TheoreticalSpectrumGenerator generator; Param p; p.setValue("add_metainfo", "true", "Adds the type of peaks as metainfo to the peaks, like y8+, [M-H2O+2H]++"); p.setValue("max_isotope", tv_params.getValue("preferences:idview:max_isotope"), "Number of isotopic peaks"); p.setValue("add_losses", tv_params.getValue("preferences:idview:add_losses"), "Adds common losses to those ion expect to have them, only water and ammonia loss is considered"); p.setValue("add_isotopes", tv_params.getValue("preferences:idview:add_isotopes"), "If set to 1 isotope peaks of the product ion peaks are added"); p.setValue("add_abundant_immonium_ions", tv_params.getValue("preferences:idview:add_abundant_immonium_ions"), "Add most abundant immonium ions"); p.setValue("a_intensity", current_spectrum.getMaxInt() * (double)tv_params.getValue("preferences:idview:a_intensity"), "Intensity of the a-ions"); p.setValue("b_intensity", current_spectrum.getMaxInt() * (double)tv_params.getValue("preferences:idview:b_intensity"), "Intensity of the b-ions"); p.setValue("c_intensity", current_spectrum.getMaxInt() * (double)tv_params.getValue("preferences:idview:c_intensity"), "Intensity of the c-ions"); p.setValue("x_intensity", current_spectrum.getMaxInt() * (double)tv_params.getValue("preferences:idview:x_intensity"), "Intensity of the x-ions"); p.setValue("y_intensity", current_spectrum.getMaxInt() * (double)tv_params.getValue("preferences:idview:y_intensity"), "Intensity of the y-ions"); p.setValue("z_intensity", current_spectrum.getMaxInt() * (double)tv_params.getValue("preferences:idview:z_intensity"), "Intensity of the z-ions"); p.setValue("relative_loss_intensity", tv_params.getValue("preferences:idview:relative_loss_intensity"), "Intensity of loss ions, in relation to the intact ion intensity"); generator.setParameters(p); try { Int max_charge = max(1, ph.getCharge()); // at least generate charge 1 if no charge (0) is annotated // generate mass ladder for each charge state for (Int charge = 1; charge <= max_charge; ++charge) { if (tv_params.getValue("preferences:idview:show_a_ions").toBool()) // "A-ions" { generator.addPeaks(rich_spec, aa_sequence, Residue::AIon, charge); } if (tv_params.getValue("preferences:idview:show_b_ions").toBool()) // "B-ions" { generator.addPeaks(rich_spec, aa_sequence, Residue::BIon, charge); } if (tv_params.getValue("preferences:idview:show_c_ions").toBool()) // "C-ions" { generator.addPeaks(rich_spec, aa_sequence, Residue::CIon, charge); } if (tv_params.getValue("preferences:idview:show_x_ions").toBool()) // "X-ions" { generator.addPeaks(rich_spec, aa_sequence, Residue::XIon, charge); } if (tv_params.getValue("preferences:idview:show_y_ions").toBool()) // "Y-ions" { generator.addPeaks(rich_spec, aa_sequence, Residue::YIon, charge); } if (tv_params.getValue("preferences:idview:show_z_ions").toBool()) // "Z-ions" { generator.addPeaks(rich_spec, aa_sequence, Residue::ZIon, charge); } if (tv_params.getValue("preferences:idview:show_precursor").toBool()) // "Precursor" { generator.addPrecursorPeaks(rich_spec, aa_sequence, charge); } } if (tv_params.getValue("preferences:idview:add_abundant_immonium_ions").toBool()) // "abundant Immonium-ions" { generator.addAbundantImmoniumIons(rich_spec); } } catch (Exception::BaseException & e) { QMessageBox::warning(tv_, "Error", QString("Spectrum generation failed! (") + e.what() + "). Please report this to the developers (specify what input you used)!"); return; } // convert rich spectrum to simple spectrum PeakSpectrum new_spec; for (RichPeakSpectrum::Iterator it = rich_spec.begin(); it != rich_spec.end(); ++it) { new_spec.push_back(static_cast<Peak1D>(*it)); } PeakMap new_exp; new_exp.addSpectrum(new_spec); ExperimentSharedPtrType new_exp_sptr(new PeakMap(new_exp)); FeatureMapSharedPtrType f_dummy(new FeatureMapType()); ConsensusMapSharedPtrType c_dummy(new ConsensusMapType()); vector<PeptideIdentification> p_dummy; // Block update events for identification widget tv_->getSpectraIdentificationViewWidget()->ignore_update = true; String layer_caption = aa_sequence.toString().toQString() + QString(" (identification view)"); tv_->addData(f_dummy, c_dummy, p_dummy, new_exp_sptr, LayerData::DT_CHROMATOGRAM, false, false, false, "", layer_caption.toQString()); // get layer index of new layer Size theoretical_spectrum_layer_index = tv_->getActive1DWidget()->canvas()->activeLayerIndex(); // kind of a hack to check whether adding the layer was successful if (current_spectrum_layer_index != theoretical_spectrum_layer_index) { // Ensure theoretical spectrum is drawn as dashed sticks tv_->setDrawMode1D(Spectrum1DCanvas::DM_PEAKS); tv_->getActive1DWidget()->canvas()->setCurrentLayerPeakPenStyle(Qt::DashLine); // Add ion names as annotations to the theoretical spectrum for (RichPeakSpectrum::Iterator it = rich_spec.begin(); it != rich_spec.end(); ++it) { if (it->getMetaValue("IonName") != DataValue::EMPTY) { DPosition<2> position = DPosition<2>(it->getMZ(), it->getIntensity()); QString s(((string)it->getMetaValue("IonName")).c_str()); if (s.at(0) == 'y') { Annotation1DItem * item = new Annotation1DPeakItem(position, s, Qt::darkRed); item->setSelected(false); tv_->getActive1DWidget()->canvas()->getCurrentLayer().getCurrentAnnotations().push_front(item); } else if (s.at(0) == 'b') { Annotation1DItem * item = new Annotation1DPeakItem(position, s, Qt::darkGreen); item->setSelected(false); tv_->getActive1DWidget()->canvas()->getCurrentLayer().getCurrentAnnotations().push_front(item); } } } // remove theoretical and activate real data layer and spectrum tv_->getActive1DWidget()->canvas()->changeVisibility(theoretical_spectrum_layer_index, false); tv_->getActive1DWidget()->canvas()->activateLayer(current_spectrum_layer_index); tv_->getActive1DWidget()->canvas()->getCurrentLayer().setCurrentSpectrumIndex(current_spectrum_index); // zoom to maximum visible area in real data (as theoretical might be much larger and therefor squeezes the interesting part) DRange<2> visible_area = tv_->getActive1DWidget()->canvas()->getVisibleArea(); double min_mz = tv_->getActive1DWidget()->canvas()->getCurrentLayer().getCurrentSpectrum().getMin()[0]; double max_mz = tv_->getActive1DWidget()->canvas()->getCurrentLayer().getCurrentSpectrum().getMax()[0]; double delta_mz = max_mz - min_mz; visible_area.setMin(min_mz - 0.1 * delta_mz); visible_area.setMax(max_mz + 0.1 * delta_mz); tv_->getActive1DWidget()->canvas()->setVisibleArea(visible_area); // spectra alignment Param param; double tolerance = tv_params.getValue("preferences:idview:tolerance"); param.setValue("tolerance", tolerance, "Defines the absolute (in Da) or relative (in ppm) tolerance in the alignment"); tv_->getActive1DWidget()->performAlignment(current_spectrum_layer_index, theoretical_spectrum_layer_index, param); std::vector<std::pair<Size, Size> > aligned_peak_indices = tv_->getActive1DWidget()->canvas()->getAlignedPeaksIndices(); // annotate original spectrum with ions and sequence for (Size i = 0; i != aligned_peak_indices.size(); ++i) { PeakIndex pi(current_spectrum_index, aligned_peak_indices[i].first); QString s(((string)rich_spec[aligned_peak_indices[i].second].getMetaValue("IonName")).c_str()); QString ion_nr_string = s; if (s.at(0) == 'y') { ion_nr_string.replace("y", ""); ion_nr_string.replace("+", ""); Size ion_number = ion_nr_string.toUInt(); s.append("\n"); // extract peptide ion sequence QString aa_ss; for (Size j = aa_sequence.size() - 1; j >= aa_sequence.size() - ion_number; --j) { const Residue & r = aa_sequence.getResidue(j); aa_ss.append(r.getOneLetterCode().toQString()); if (r.getModification() != "") { aa_ss.append("*"); } } s.append(aa_ss); Annotation1DItem * item = tv_->getActive1DWidget()->canvas()->addPeakAnnotation(pi, s, Qt::darkRed); temporary_annotations_.push_back(item); } else if (s.at(0) == 'b') { ion_nr_string.replace("b", ""); ion_nr_string.replace("+", ""); UInt ion_number = ion_nr_string.toUInt(); s.append("\n"); // extract peptide ion sequence AASequence aa_subsequence = aa_sequence.getSubsequence(0, ion_number); QString aa_ss = aa_subsequence.toString().toQString(); // shorten modifications "(MODNAME)" to "*" aa_ss.replace(QRegExp("[(].*[)]"), "*"); // append to label s.append(aa_ss); Annotation1DItem * item = tv_->getActive1DWidget()->canvas()->addPeakAnnotation(pi, s, Qt::darkGreen); // save label for later removal temporary_annotations_.push_back(item); } else { s.append("\n"); Annotation1DItem * item = tv_->getActive1DWidget()->canvas()->addPeakAnnotation(pi, s, Qt::black); // save label for later removal temporary_annotations_.push_back(item); } } tv_->updateLayerBar(); tv_->getSpectraIdentificationViewWidget()->ignore_update = false; } } void TOPPViewIdentificationViewBehavior::deactivate1DSpectrum(int spectrum_index) { LayerData & current_layer = tv_->getActive1DWidget()->canvas()->getCurrentLayer(); int ms_level = (*current_layer.getPeakData())[spectrum_index].getMSLevel(); removeTemporaryAnnotations_(spectrum_index); if (ms_level == 2) { removeTheoreticalSpectrumLayer_(); } // the next line is meant to be disabled to allow switching between spectra without loosing the current view range (to compare across spectra) // tv_->getActive1DWidget()->canvas()->resetZoom(); } void TOPPViewIdentificationViewBehavior::removeTheoreticalSpectrumLayer_() { Spectrum1DWidget * spectrum_widget_1D = tv_->getActive1DWidget(); if (spectrum_widget_1D) { Spectrum1DCanvas * canvas_1D = spectrum_widget_1D->canvas(); // Find the automatically generated layer with theoretical spectrum and remove it and the associated alignment. // before activating the next normal spectrum Size lc = canvas_1D->getLayerCount(); for (Size i = 0; i != lc; ++i) { String ln = canvas_1D->getLayerName(i); if (ln.hasSubstring("(identification view)")) { canvas_1D->removeLayer(i); canvas_1D->resetAlignment(); tv_->updateLayerBar(); break; } } } } void TOPPViewIdentificationViewBehavior::activateBehavior() { Spectrum1DWidget* w = tv_->getActive1DWidget(); if ( w == 0) { return; } SpectrumCanvas * current_canvas = w->canvas(); LayerData & current_layer = current_canvas->getCurrentLayer(); SpectrumType & current_spectrum = current_layer.getCurrentSpectrum(); // find first MS2 spectrum with peptide identification and set current spectrum to it if (current_spectrum.getMSLevel() == 1) // no fragment spectrum { for (Size i = 0; i < current_layer.getPeakData()->size(); ++i) { UInt ms_level = (*current_layer.getPeakData())[i].getMSLevel(); const vector<PeptideIdentification> peptide_ids = (*current_layer.getPeakData())[i].getPeptideIdentifications(); Size peptide_ids_count = peptide_ids.size(); if (ms_level != 2 || peptide_ids_count == 0) // skip non ms2 spectra and spectra with no identification { continue; } current_layer.setCurrentSpectrumIndex(i); break; } } } void TOPPViewIdentificationViewBehavior::deactivateBehavior() { // remove precusor labels, theoretical spectra and trigger repaint if (tv_->getActive1DWidget() != 0) { removeTemporaryAnnotations_(tv_->getActive1DWidget()->canvas()->getCurrentLayer().getCurrentSpectrumIndex()); removeTheoreticalSpectrumLayer_(); tv_->getActive1DWidget()->canvas()->repaint(); } } void TOPPViewIdentificationViewBehavior::setVisibleArea1D(double l, double h) { if (tv_->getActive1DWidget() != 0) { DRange<2> range = tv_->getActive1DWidget()->canvas()->getVisibleArea(); range.setMinX(l); range.setMaxX(h); tv_->getActive1DWidget()->canvas()->setVisibleArea(range); tv_->getActive1DWidget()->canvas()->repaint(); } } }
42.720414
185
0.642647
[ "vector" ]
11405e97b8dde23b95d6f6103f7bb82c5cc8d145
7,422
cpp
C++
shared/XrSceneLib/ControllerObject.cpp
CodeReclaimers/OpenXR-MixedReality
47a9ab92e1435b2566708452924d4d96689178c0
[ "MIT" ]
174
2020-03-10T18:30:02.000Z
2022-03-14T07:11:08.000Z
shared/XrSceneLib/ControllerObject.cpp
CodeReclaimers/OpenXR-MixedReality
47a9ab92e1435b2566708452924d4d96689178c0
[ "MIT" ]
28
2020-04-06T15:14:40.000Z
2022-03-26T00:27:45.000Z
shared/XrSceneLib/ControllerObject.cpp
CodeReclaimers/OpenXR-MixedReality
47a9ab92e1435b2566708452924d4d96689178c0
[ "MIT" ]
60
2020-03-25T04:01:52.000Z
2022-03-28T14:40:10.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include <Pbr/GltfLoader.h> #include <SampleShared/Trace.h> #include "PbrModelObject.h" #include "ControllerObject.h" #include "Context.h" using namespace DirectX; using namespace std::literals::chrono_literals; namespace { struct ControllerModel { XrControllerModelKeyMSFT Key = 0; std::shared_ptr<Pbr::Model> PbrModel; std::vector<Pbr::NodeIndex_t> NodeIndices; std::vector<XrControllerModelNodePropertiesMSFT> NodeProperties; std::vector<XrControllerModelNodeStateMSFT> NodeStates; }; std::unique_ptr<ControllerModel> LoadControllerModel(engine::Context& context, XrControllerModelKeyMSFT modelKey) { std::unique_ptr<ControllerModel> model = std::make_unique<ControllerModel>(); model->Key = modelKey; // Load the controller model as GLTF binary stream using two call idiom uint32_t bufferSize = 0; CHECK_XRCMD(context.Extensions.xrLoadControllerModelMSFT(context.Session.Handle, modelKey, 0, &bufferSize, nullptr)); auto modelBuffer = std::make_unique<byte[]>(bufferSize); CHECK_XRCMD( context.Extensions.xrLoadControllerModelMSFT(context.Session.Handle, modelKey, bufferSize, &bufferSize, modelBuffer.get())); model->PbrModel = Gltf::FromGltfBinary(context.PbrResources, modelBuffer.get(), bufferSize); // Read the controller model properties with two call idiom XrControllerModelPropertiesMSFT properties{XR_TYPE_CONTROLLER_MODEL_PROPERTIES_MSFT}; properties.nodeCapacityInput = 0; CHECK_XRCMD(context.Extensions.xrGetControllerModelPropertiesMSFT(context.Session.Handle, modelKey, &properties)); model->NodeProperties.resize(properties.nodeCountOutput, {XR_TYPE_CONTROLLER_MODEL_NODE_PROPERTIES_MSFT}); properties.nodeProperties = model->NodeProperties.data(); properties.nodeCapacityInput = static_cast<uint32_t>(model->NodeProperties.size()); CHECK_XRCMD(context.Extensions.xrGetControllerModelPropertiesMSFT(context.Session.Handle, modelKey, &properties)); // Compute the index of each node reported by runtime to be animated. // The order of m_nodeIndices exactly matches the order of the nodes properties and states. model->NodeIndices.resize(model->NodeProperties.size(), Pbr::NodeIndex_npos); for (size_t i = 0; i < model->NodeProperties.size(); ++i) { const auto& nodeProperty = model->NodeProperties[i]; const std::string_view parentNodeName = nodeProperty.parentNodeName; if (const auto parentNodeIndex = model->PbrModel->FindFirstNode(parentNodeName)) { if (const auto targetNodeIndex = model->PbrModel->FindFirstNode(nodeProperty.nodeName, *parentNodeIndex)) { model->NodeIndices[i] = *targetNodeIndex; } } } return model; } // Update transforms of nodes for the animatable parts in the controller model void UpdateControllerParts(engine::Context& context, ControllerModel& model) { XrControllerModelStateMSFT modelState{XR_TYPE_CONTROLLER_MODEL_STATE_MSFT}; modelState.nodeCapacityInput = 0; CHECK_XRCMD(context.Extensions.xrGetControllerModelStateMSFT(context.Session.Handle, model.Key, &modelState)); model.NodeStates.resize(modelState.nodeCountOutput, {XR_TYPE_CONTROLLER_MODEL_STATE_MSFT}); modelState.nodeCapacityInput = static_cast<uint32_t>(model.NodeStates.size()); modelState.nodeStates = model.NodeStates.data(); CHECK_XRCMD(context.Extensions.xrGetControllerModelStateMSFT(context.Session.Handle, model.Key, &modelState)); assert(model.NodeStates.size() == model.NodeIndices.size()); const size_t end = std::min(model.NodeStates.size(), model.NodeIndices.size()); for (size_t i = 0; i < end; i++) { const Pbr::NodeIndex_t nodeIndex = model.NodeIndices[i]; if (nodeIndex != Pbr::NodeIndex_npos) { Pbr::Node& node = model.PbrModel->GetNode(nodeIndex); node.SetTransform(xr::math::LoadXrPose(model.NodeStates[i].nodePose)); } } } struct ControllerObject : engine::PbrModelObject { ControllerObject(engine::Context& context, XrPath controllerUserPath); ~ControllerObject(); void Update(engine::Context& context, const engine::FrameTime& frameTime) override; private: const bool m_extensionSupported; const XrPath m_controllerUserPath; std::unique_ptr<ControllerModel> m_model; std::future<std::unique_ptr<ControllerModel>> m_modelLoadingTask; }; ControllerObject::ControllerObject(engine::Context& context, XrPath controllerUserPath) : m_extensionSupported(context.Extensions.SupportsControllerModel) , m_controllerUserPath(controllerUserPath) { } ControllerObject::~ControllerObject() { // Wait for model loading task to complete before dtor complete because it captures the scene context. if (m_modelLoadingTask.valid()) { m_modelLoadingTask.wait(); } } void ControllerObject::Update(engine::Context& context, const engine::FrameTime& frameTime) { if (!m_extensionSupported) { return; // The current runtime doesn't support controller model extension. } XrControllerModelKeyStateMSFT controllerModelKeyState{XR_TYPE_CONTROLLER_MODEL_KEY_STATE_MSFT}; CHECK_XRCMD(context.Extensions.xrGetControllerModelKeyMSFT(context.Session.Handle, m_controllerUserPath, &controllerModelKeyState)); // If a new valid model key is returned, reload the model into cache asynchronizely const bool modelKeyValid = controllerModelKeyState.modelKey != XR_NULL_CONTROLLER_MODEL_KEY_MSFT; if (modelKeyValid && (m_model == nullptr || m_model->Key != controllerModelKeyState.modelKey)) { // Avoid two background tasks running together. The new one will start in future update after the old one is finished. if (!m_modelLoadingTask.valid()) { m_modelLoadingTask = std::async(std::launch::async, [&, modelKey = controllerModelKeyState.modelKey]() { return LoadControllerModel(context, modelKey); }); } } // If controller model loading task is completed, get the result model and apply it to rendering. if (m_modelLoadingTask.valid() && m_modelLoadingTask.wait_for(0s) == std::future_status::ready) { try { m_model = m_modelLoadingTask.get(); // future.valid() is reset to false after get() } catch (...) { sample::Trace("Unexpected failure loading controller model"); } if (m_model) { SetModel(m_model->PbrModel); } } // If controller model is already loaded, update all node transforms if (m_model != nullptr) { UpdateControllerParts(context, *m_model); } } } // namespace namespace engine { std::shared_ptr<engine::PbrModelObject> CreateControllerObject(Context& context, XrPath controllerUserPath) { return std::make_shared<ControllerObject>(context, controllerUserPath); } } // namespace engine
48.194805
140
0.691727
[ "vector", "model" ]
114363edfaf7b216499ce0e82b11c58b1be29e43
547
cpp
C++
Array/Container With Most Water.cpp
kunal-j10/My-DSA
290e56599f10d80756aa714066ee498feff58bb7
[ "MIT" ]
2
2022-01-02T07:14:16.000Z
2022-01-02T15:43:30.000Z
Array/Container With Most Water.cpp
kunal-j10/My-DSA
290e56599f10d80756aa714066ee498feff58bb7
[ "MIT" ]
null
null
null
Array/Container With Most Water.cpp
kunal-j10/My-DSA
290e56599f10d80756aa714066ee498feff58bb7
[ "MIT" ]
1
2021-08-17T15:31:59.000Z
2021-08-17T15:31:59.000Z
class Solution { public: int maxArea(vector<int>& height) { int n=height.size(); int maxArea=0; int area; for(int i=0,j=n-1;i<j;) { if(height[i]>=height[j]) { area = (j-i)*height[j]; j--; } else { area = (j-i)*height[i]; i++; } if(area>=maxArea) maxArea=area; } return maxArea; } };
20.259259
39
0.318099
[ "vector" ]
114600868cf9f351055160e002d45a7851078693
563
cpp
C++
course/CPPLearning/exp/exp6/task63.cpp
JimouChen/algorithm-competition-training
d08bfd33e94239201c720ac83f93f07eff723b5b
[ "MIT" ]
1
2020-09-02T16:12:53.000Z
2020-09-02T16:12:53.000Z
course/CPPLearning/exp/exp6/task63.cpp
JimouChen/algorithm-competition-training
d08bfd33e94239201c720ac83f93f07eff723b5b
[ "MIT" ]
null
null
null
course/CPPLearning/exp/exp6/task63.cpp
JimouChen/algorithm-competition-training
d08bfd33e94239201c720ac83f93f07eff723b5b
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; class Shape { public: virtual void display() = 0; }; class Rectangle : public Shape { public: virtual void display(); }; void Rectangle::display() { cout << "shape is rectangle" << endl; } class Circle : public Shape { public: virtual void display(); }; void Circle::display() { cout << "shape is circle" << endl; } int main() { Shape *shape; Rectangle rectangle; Circle circle; shape = &rectangle; shape->display(); shape = &circle; shape->display(); return 0; }
14.815789
41
0.616341
[ "shape" ]
1149f91aec720227dfff6f6e0980725d6c7d26d2
1,102
cpp
C++
labelButton.cpp
Coderec/QuickPanel
777eaee128dff37ef511072e0483fe9f1501fbc0
[ "Apache-2.0" ]
null
null
null
labelButton.cpp
Coderec/QuickPanel
777eaee128dff37ef511072e0483fe9f1501fbc0
[ "Apache-2.0" ]
null
null
null
labelButton.cpp
Coderec/QuickPanel
777eaee128dff37ef511072e0483fe9f1501fbc0
[ "Apache-2.0" ]
null
null
null
#include "labelButton.h" #include <QApplication> int labelButton::NUM=0; labelButton::labelButton(QWidget *parent) : QToolButton(parent) { NUM++; buttonList = new QList<myButton*>(); setStyleSheet("background-color: rgba(255, 255, 255, 150)"); setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed); setAcceptDrops(true); connect(this,SIGNAL(clicked()),this,SLOT(ifClicked())); } QList<myButton *> *labelButton::getButtonList() { return buttonList; } labelButton::~labelButton(){ delete buttonList; NUM--; } void labelButton::contextMenuEvent(QContextMenuEvent *e) { emit createMenu(e->globalPos(),this); } void labelButton::dragEnterEvent(QDragEnterEvent *e) { QTimer::singleShot(500, this, SLOT(onTimeOut())); } void labelButton::onTimeOut() { QRect rect = QRect(QWidget::mapFromParent(this->geometry().topLeft()),this->size()); if(rect.contains(QWidget::mapFromGlobal(cursor().pos()))) emit this->clicked(); //when drag to this label,open this label } void labelButton::ifClicked() { emit toClicked(this); }
23.446809
88
0.686933
[ "geometry" ]
114b7edd7fe586cb8b1f97b42adc22e4a0b6224f
1,181
hpp
C++
src/sdk/REGlobals.hpp
muhopensores/RE2-Mod-Framework
0def991b598a83a488c0be1bcf78df81e265b8b6
[ "MIT" ]
1
2020-07-17T23:16:56.000Z
2020-07-17T23:16:56.000Z
src/sdk/REGlobals.hpp
muhopensores/RE2-Mod-Framework
0def991b598a83a488c0be1bcf78df81e265b8b6
[ "MIT" ]
null
null
null
src/sdk/REGlobals.hpp
muhopensores/RE2-Mod-Framework
0def991b598a83a488c0be1bcf78df81e265b8b6
[ "MIT" ]
null
null
null
#pragma once #include <mutex> #include <unordered_map> #include <unordered_set> #include "ReClass.hpp" // A list of globals in the RE engine (singletons?) class REGlobals { public: REGlobals(); virtual ~REGlobals() {}; const auto& getObjectsSet() const { return m_objects; } const auto& getObjects() const { return m_objectList; } // Equivalent REManagedObject* get(std::string_view name); REManagedObject* operator[](std::string_view name); template <typename T> T* get(std::string_view name) { return (T*)get(name); } // Lock a mutex and then refresh the map. void safeRefresh(); private: void refreshMap(); // Class name to object like "app.foo.bar" -> 0xDEADBEEF std::unordered_map<std::string, REManagedObject**> m_objectMap; // Raw list of objects (for if the type hasn't been fully initialized, we need to refresh the map) std::unordered_set<REManagedObject**> m_objects; std::vector<REManagedObject**> m_objectList; // List of objects we've already logged std::unordered_set<REManagedObject**> m_acknowledgedObjects; std::mutex m_mapMutex{}; };
24.102041
102
0.670618
[ "object", "vector" ]
114e7a204d19b9b3075adeb26e57aeda911d257d
1,328
hpp
C++
Include/Polar-Math/Transform.hpp
PolarToCartesian/Polar-Lib
ec564a93c0577e017d2c99426112df35788318e8
[ "MIT" ]
null
null
null
Include/Polar-Math/Transform.hpp
PolarToCartesian/Polar-Lib
ec564a93c0577e017d2c99426112df35788318e8
[ "MIT" ]
null
null
null
Include/Polar-Math/Transform.hpp
PolarToCartesian/Polar-Lib
ec564a93c0577e017d2c99426112df35788318e8
[ "MIT" ]
null
null
null
#ifndef __POLAR__FILE_TRANSFORM_HPP #define __POLAR__FILE_TRANSFORM_HPP #include <Polar-Math/Matrix.hpp> namespace PL { struct Transform { private: Vec4f32 m_rotation; Vec4f32 m_translation; Mat4x4f32 m_transform = Mat4x4f32::MakeIdentity(); public: Transform() = default; [[nodiscard]] inline Vec4f32 GetRotation() const noexcept { return this->m_rotation; } [[nodiscard]] inline Vec4f32 GetTranslation() const noexcept { return this->m_translation; } inline void SetRotation (const Vec4f32 &rotation) noexcept { this->m_rotation = rotation; } inline void SetTranslation(const Vec4f32 &translation) noexcept { this->m_translation = translation; } inline void Rotate (const Vec4f32 &delta) noexcept { this->m_rotation += delta; } inline void Translate(const Vec4f32 &delta) noexcept { this->m_translation += delta; } [[nodiscard]] inline Mat4x4f32 GetTransform() const noexcept { return this->m_transform; } [[nodiscard]] inline Mat4x4f32 GetTransposedTransform() const noexcept { return Mat4x4f32::MakeTransposed(this->m_transform); } inline void CalculateTransform() noexcept { this->m_transform = Mat4x4f32::MakeTranslation(this->m_translation); } }; // struct Transform }; // namespace PL #endif // __POLAR__FILE_TRANSFORM_HPP
35.891892
129
0.726657
[ "transform" ]
114eb6d880d2be431036e855688a48a17142f8dc
16,169
cc
C++
pagespeed/system/apr_mem_cache_test.cc
crowell/modpagespeed_tmp
d2c063875d819c46c2d88a5ddb70578cae2a5909
[ "Apache-2.0" ]
null
null
null
pagespeed/system/apr_mem_cache_test.cc
crowell/modpagespeed_tmp
d2c063875d819c46c2d88a5ddb70578cae2a5909
[ "Apache-2.0" ]
null
null
null
pagespeed/system/apr_mem_cache_test.cc
crowell/modpagespeed_tmp
d2c063875d819c46c2d88a5ddb70578cae2a5909
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: jmarantz@google.com (Joshua Marantz) // Unit-test the memcache interface. #include "pagespeed/system/apr_mem_cache.h" #include <cstddef> #include "apr_pools.h" #include "pagespeed/apache/apr_timer.h" #include "pagespeed/kernel/base/basictypes.h" #include "pagespeed/kernel/base/google_message_handler.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/md5_hasher.h" #include "pagespeed/kernel/base/mock_hasher.h" #include "pagespeed/kernel/base/mock_timer.h" #include "pagespeed/kernel/base/null_mutex.h" #include "pagespeed/kernel/base/null_statistics.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/shared_string.h" #include "pagespeed/kernel/base/string.h" #include "pagespeed/kernel/base/string_util.h" #include "pagespeed/kernel/base/timer.h" #include "pagespeed/kernel/cache/cache_spammer.h" #include "pagespeed/kernel/cache/cache_test_base.h" #include "pagespeed/kernel/cache/fallback_cache.h" #include "pagespeed/kernel/cache/lru_cache.h" #include "pagespeed/kernel/util/platform.h" #include "pagespeed/kernel/util/simple_stats.h" namespace net_instaweb { namespace { const int kTestValueSizeThreshold = 200; const size_t kLRUCacheSize = 3 * kTestValueSizeThreshold; const size_t kJustUnderThreshold = kTestValueSizeThreshold - 100; const size_t kLargeWriteSize = kTestValueSizeThreshold + 1; const size_t kHugeWriteSize = 2 * kTestValueSizeThreshold; } // namespace class AprMemCacheTest : public CacheTestBase { protected: AprMemCacheTest() : timer_(new NullMutex, MockTimer::kApr_5_2010_ms), lru_cache_(new LRUCache(kLRUCacheSize)), thread_system_(Platform::CreateThreadSystem()), statistics_(thread_system_.get()) { AprMemCache::InitStats(&statistics_); } static void SetUpTestCase() { apr_initialize(); atexit(apr_terminate); } // Establishes a connection to a memcached instance; either one // on localhost:$MEMCACHED_PORT or, if non-empty, the one in // server_spec_. bool ConnectToMemcached(bool use_md5_hasher) { // See install/run_program_with_memcached.sh where this environment // variable is established during development testing flows. if (server_spec_.empty()) { const char* kPortString = getenv("MEMCACHED_PORT"); if (kPortString == NULL) { LOG(ERROR) << "AprMemCache tests are skipped because env var " << "$MEMCACHED_PORT is not set. Set that to the port " << "number where memcached is running to enable the " << "tests. See install/run_program_with_memcached.sh"; // Does not fail the test. return false; } server_spec_ = StrCat("localhost:", kPortString); } Hasher* hasher = &mock_hasher_; if (use_md5_hasher) { hasher = &md5_hasher_; } servers_.reset(new AprMemCache(server_spec_, 5, hasher, &statistics_, &timer_, &handler_)); cache_.reset(new FallbackCache(servers_.get(), lru_cache_.get(), kTestValueSizeThreshold, &handler_)); // apr_memcache actually lazy-connects to memcached, it seems, so // if we fail the Connect call then something is truly broken. To // make sure memcached is actually up, we have to make an API // call, such as GetStatus. GoogleString buf; return servers_->Connect() && servers_->GetStatus(&buf); } // Attempts to initialize the connection to memcached. It reports a // test failure if there is a memcached configuration specified in // server_spec_ or via $MEMCACHED_PORT, but we fail to connect to it. // // Consider three scenarios: // // Scenario Test-status Return-value // -------------------------------------------------------------------- // server_spec_ empty OK false // server_spec_ non-empty, memcached ok OK true // server_spec_ non-empty, memcached fail FAILURE false // // This helps developers ensure that the memcached interface works, without // requiring people who build & run tests to start up memcached. bool InitMemcachedOrSkip(bool use_md5_hasher) { bool initialized = ConnectToMemcached(use_md5_hasher); EXPECT_TRUE(initialized || server_spec_.empty()) << "Please start memcached on " << server_spec_; return initialized; } virtual CacheInterface* Cache() { return cache_.get(); } GoogleMessageHandler handler_; MD5Hasher md5_hasher_; MockHasher mock_hasher_; MockTimer timer_; scoped_ptr<LRUCache> lru_cache_; scoped_ptr<AprMemCache> servers_; scoped_ptr<FallbackCache> cache_; scoped_ptr<ThreadSystem> thread_system_; SimpleStats statistics_; GoogleString server_spec_; }; // Simple flow of putting in an item, getting it, deleting it. TEST_F(AprMemCacheTest, PutGetDelete) { if (!InitMemcachedOrSkip(true)) { return; } CheckPut("Name", "Value"); CheckGet("Name", "Value"); CheckNotFound("Another Name"); CheckPut("Name", "NewValue"); CheckGet("Name", "NewValue"); cache_->Delete("Name"); CheckNotFound("Name"); EXPECT_EQ(0, lru_cache_->size_bytes()) << "fallback not used."; } TEST_F(AprMemCacheTest, MultiGet) { if (!InitMemcachedOrSkip(true)) { return; } TestMultiGet(); EXPECT_EQ(0, lru_cache_->size_bytes()) << "fallback not used."; } TEST_F(AprMemCacheTest, MultiGetWithoutServer) { server_spec_ = "localhost:99999"; ASSERT_FALSE(ConnectToMemcached(true)) << "localhost:99999 should not exist"; Callback* n0 = AddCallback(); Callback* not_found = AddCallback(); Callback* n1 = AddCallback(); IssueMultiGet(n0, "n0", not_found, "not_found", n1, "n1"); WaitAndCheckNotFound(n0); WaitAndCheckNotFound(not_found); WaitAndCheckNotFound(n1); } TEST_F(AprMemCacheTest, BasicInvalid) { if (!InitMemcachedOrSkip(true)) { return; } // Check that we honor callback veto on validity. CheckPut("nameA", "valueA"); CheckPut("nameB", "valueB"); CheckGet("nameA", "valueA"); CheckGet("nameB", "valueB"); set_invalid_value("valueA"); CheckNotFound("nameA"); CheckGet("nameB", "valueB"); EXPECT_EQ(0, lru_cache_->size_bytes()) << "fallback not used."; } TEST_F(AprMemCacheTest, SizeTest) { if (!InitMemcachedOrSkip(true)) { return; } for (int x = 0; x < 10; ++x) { for (int i = kJustUnderThreshold/2; i < kJustUnderThreshold - 10; ++i) { GoogleString value(i, 'a'); GoogleString key = StrCat("big", IntegerToString(i)); CheckPut(key, value); CheckGet(key, value); } } EXPECT_EQ(0, lru_cache_->size_bytes()) << "fallback not used."; } TEST_F(AprMemCacheTest, StatsTest) { if (!InitMemcachedOrSkip(true)) { return; } GoogleString buf; ASSERT_TRUE(servers_->GetStatus(&buf)); EXPECT_TRUE(buf.find("memcached server localhost:") != GoogleString::npos); EXPECT_TRUE(buf.find(" pid ") != GoogleString::npos); EXPECT_TRUE(buf.find("\nbytes_read: ") != GoogleString::npos); EXPECT_TRUE(buf.find("\ncurr_connections: ") != GoogleString::npos); EXPECT_TRUE(buf.find("\ntotal_items: ") != GoogleString::npos); EXPECT_EQ(0, lru_cache_->size_bytes()) << "fallback not used."; } TEST_F(AprMemCacheTest, HashCollision) { if (!InitMemcachedOrSkip(false)) { return; } CheckPut("N1", "V1"); CheckGet("N1", "V1"); // Since we are using a mock hasher, which always returns "0", the // put on "N2" will overwrite "N1" in memcached due to hash // collision. CheckPut("N2", "V2"); CheckGet("N2", "V2"); CheckNotFound("N1"); EXPECT_EQ(0, lru_cache_->size_bytes()) << "fallback not used."; } TEST_F(AprMemCacheTest, JustUnderThreshold) { if (!InitMemcachedOrSkip(true)) { return; } const GoogleString kValue(kJustUnderThreshold, 'a'); const char kKey[] = "just_under_threshold"; CheckPut(kKey, kValue); CheckGet(kKey, kValue); EXPECT_EQ(0, lru_cache_->size_bytes()) << "fallback not used."; } // Basic operation with huge values, only one of which will fit // in the fallback cache at a time. TEST_F(AprMemCacheTest, HugeValue) { if (!InitMemcachedOrSkip(true)) { return; } const GoogleString kValue(kHugeWriteSize, 'a'); const char kKey1[] = "large1"; CheckPut(kKey1, kValue); CheckGet(kKey1, kValue); EXPECT_LE(kHugeWriteSize, lru_cache_->size_bytes()); // Now put in another large value, causing the 1st to get evicted from // the fallback cache. const char kKey2[] = "large2"; CheckPut(kKey2, kValue); CheckGet(kKey2, kValue); CheckNotFound(kKey1); // Finally, delete the second value explicitly. Note that value will be // in the fallback cache, but we will not be able to get to it because // we've removed the sentinal from memcached. CheckGet(kKey2, kValue); cache_->Delete(kKey2); CheckNotFound(kKey2); } TEST_F(AprMemCacheTest, LargeValueMultiGet) { if (!InitMemcachedOrSkip(true)) { return; } const GoogleString kLargeValue1(kLargeWriteSize, 'a'); const char kKey1[] = "large1"; CheckPut(kKey1, kLargeValue1); CheckGet(kKey1, kLargeValue1); EXPECT_EQ(kLargeWriteSize + STATIC_STRLEN(kKey1), lru_cache_->size_bytes()); const char kSmallKey[] = "small"; const char kSmallValue[] = "value"; CheckPut(kSmallKey, kSmallValue); const GoogleString kLargeValue2(kLargeWriteSize, 'b'); const char kKey2[] = "large2"; CheckPut(kKey2, kLargeValue2); CheckGet(kKey2, kLargeValue2); EXPECT_LE(2 * kLargeWriteSize, lru_cache_->size_bytes()) << "Checks that both large values were written to the fallback cache"; Callback* large1 = AddCallback(); Callback* small = AddCallback(); Callback* large2 = AddCallback(); IssueMultiGet(large1, kKey1, small, kSmallKey, large2, kKey2); WaitAndCheck(large1, kLargeValue1); WaitAndCheck(small, "value"); WaitAndCheck(large2, kLargeValue2); } TEST_F(AprMemCacheTest, MultiServerFallback) { if (!InitMemcachedOrSkip(true)) { return; } // Make another connection to the same memcached, but with a different // fallback cache. LRUCache lru_cache2(kLRUCacheSize); FallbackCache mem_cache2(servers_.get(), &lru_cache2, kTestValueSizeThreshold, &handler_); // Now when we store a large object from server1, and fetch it from // server2, we will get a miss because they do not share fallback caches.. // But then we can re-store it and fetch it from either server. const GoogleString kLargeValue(kLargeWriteSize, 'a'); const char kKey1[] = "large1"; CheckPut(kKey1, kLargeValue); CheckGet(kKey1, kLargeValue); // The fallback caches are not shared, so we get a miss from mem_cache2. CheckNotFound(&mem_cache2, kKey1); CheckPut(&mem_cache2, kKey1, kLargeValue); CheckGet(&mem_cache2, kKey1, kLargeValue); CheckGet(cache_.get(), kKey1, kLargeValue); } TEST_F(AprMemCacheTest, KeyOver64kDropped) { if (!InitMemcachedOrSkip(true)) { return; } // We set our testing byte thresholds too low to trigger the case where // the key-value encoding fails, so make an alternate fallback cache // with a threshold over 64k. // Make another connection to the same memcached, but with a different // fallback cache. const int kBigLruSize = 1000000; const int kThreshold = 200000; // fits key and small value. LRUCache lru_cache2(kLRUCacheSize); FallbackCache mem_cache2(servers_.get(), &lru_cache2, kThreshold, &handler_); const GoogleString kKey(kBigLruSize, 'a'); CheckPut(&mem_cache2, kKey, "value"); CheckNotFound(&mem_cache2, kKey.c_str()); } // Even keys that are over the *value* threshold can be stored in and // retrieved from the fallback cache. This is because we don't even // store the key in memcached. // // Note: we do not expect to see ridiculously large keys; we are just // testing for corner cases here. TEST_F(AprMemCacheTest, LargeKeyOverThreshold) { if (!InitMemcachedOrSkip(true)) { return; } const GoogleString kKey(kLargeWriteSize, 'a'); const char kValue[] = "value"; CheckPut(kKey, kValue); CheckGet(kKey, kValue); EXPECT_EQ(kKey.size() + STATIC_STRLEN(kValue), lru_cache_->size_bytes()); } TEST_F(AprMemCacheTest, HealthCheck) { if (!InitMemcachedOrSkip(true)) { return; } const int kNumIters = 5; // Arbitrary number of repetitions. for (int i = 0; i < kNumIters; ++i) { for (int j = 0; j < AprMemCache::kMaxErrorBurst; ++j) { EXPECT_TRUE(servers_->IsHealthy()); servers_->RecordError(); } EXPECT_FALSE(servers_->IsHealthy()); timer_.AdvanceMs(AprMemCache::kHealthCheckpointIntervalMs - 1); EXPECT_FALSE(servers_->IsHealthy()); timer_.AdvanceMs(2); } EXPECT_TRUE(servers_->IsHealthy()); } TEST_F(AprMemCacheTest, ThreadSafe) { if (!InitMemcachedOrSkip(true)) { return; } GoogleString large_pattern(kLargeWriteSize, 'a'); large_pattern += "%d"; CacheSpammer::RunTests(5 /* num_threads */, 200 /* num_iters */, 10 /* num_inserts */, false, true, large_pattern.c_str(), servers_.get(), thread_system_.get()); } // Tests that a very low timeout out value causes a simple Get to fail. // Warning: if this turns out to be flaky then just delete it; it will // have served its purpose. // // Update 12/9/12: this test is flaky on slow machines. This test should // only be run interactively to check on timeout behavior. To run it, // set environemnt variable (APR_MEMCACHE_TIMEOUT_TEST). TEST_F(AprMemCacheTest, OneMicrosecondGet) { if (getenv("APR_MEMCACHE_TIMEOUT_TEST") == NULL) { LOG(WARNING) << "Skipping flaky test AprMemCacheTest.OneMicrosecond, set " << "$APR_MEMCACHE_TIMEOUT_TEST to run it"; return; } if (!InitMemcachedOrSkip(true)) { return; } // With the default timeout, do a Put, which will work. CheckPut("Name", "Value"); CheckGet("Name", "Value"); // Set the timeout insanely low and now watch the fetch fail. servers_->set_timeout_us(1); CheckNotFound("Name"); EXPECT_EQ(1, statistics_.GetVariable("memcache_timeouts")->Get()); } TEST_F(AprMemCacheTest, OneMicrosecondPut) { if (getenv("APR_MEMCACHE_TIMEOUT_TEST") == NULL) { LOG(WARNING) << "Skipping flaky test AprMemCacheTest.OneMicrosecond, set " << "$APR_MEMCACHE_TIMEOUT_TEST to run it"; return; } if (!InitMemcachedOrSkip(true)) { return; } // With the default timeout, do a Put, which will work. CheckPut("Name", "Value"); CheckGet("Name", "Value"); // Set the timeout insanely low and now watch the fetch fail. servers_->set_timeout_us(1); CheckPut("Name", "Value"); EXPECT_EQ(1, statistics_.GetVariable("memcache_timeouts")->Get()); } TEST_F(AprMemCacheTest, OneMicrosecondDelete) { if (getenv("APR_MEMCACHE_TIMEOUT_TEST") == NULL) { LOG(WARNING) << "Skipping flaky test AprMemCacheTest.OneMicrosecond, set " << "$APR_MEMCACHE_TIMEOUT_TEST to run it"; return; } if (!InitMemcachedOrSkip(true)) { return; } // With the default timeout, do a Put, which will work. CheckPut("Name", "Value"); CheckGet("Name", "Value"); // Set the timeout insanely low and now watch the fetch fail. servers_->set_timeout_us(1); CheckDelete("Name"); EXPECT_EQ(1, statistics_.GetVariable("memcache_timeouts")->Get()); } } // namespace net_instaweb
32.79716
79
0.685942
[ "object" ]
114f92fa73ac7bfd04d5b28ef3b05d2c4852d99f
1,542
cpp
C++
ims/src/v2/model/GlanceAddImageMemberRequestBody.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
ims/src/v2/model/GlanceAddImageMemberRequestBody.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
ims/src/v2/model/GlanceAddImageMemberRequestBody.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/ims/v2/model/GlanceAddImageMemberRequestBody.h" namespace HuaweiCloud { namespace Sdk { namespace Ims { namespace V2 { namespace Model { GlanceAddImageMemberRequestBody::GlanceAddImageMemberRequestBody() { member_ = ""; memberIsSet_ = false; } GlanceAddImageMemberRequestBody::~GlanceAddImageMemberRequestBody() = default; void GlanceAddImageMemberRequestBody::validate() { } web::json::value GlanceAddImageMemberRequestBody::toJson() const { web::json::value val = web::json::value::object(); if(memberIsSet_) { val[utility::conversions::to_string_t("member")] = ModelBase::toJson(member_); } return val; } bool GlanceAddImageMemberRequestBody::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("member"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("member")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setMember(refVal); } } return ok; } std::string GlanceAddImageMemberRequestBody::getMember() const { return member_; } void GlanceAddImageMemberRequestBody::setMember(const std::string& value) { member_ = value; memberIsSet_ = true; } bool GlanceAddImageMemberRequestBody::memberIsSet() const { return memberIsSet_; } void GlanceAddImageMemberRequestBody::unsetmember() { memberIsSet_ = false; } } } } } }
18.804878
97
0.692607
[ "object", "model" ]
1150f06439ed55542274aae1407e7c87953b819b
1,671
cpp
C++
compute_samples/tests/test_cl_unified_shared_memory/src/test_set_kernel_arg_mem.cpp
maximd33/compute-samples
b16a666b76b43c2a7bd1671edc563b45e978f1a7
[ "MIT" ]
75
2018-03-19T16:06:11.000Z
2022-02-10T11:10:17.000Z
compute_samples/tests/test_cl_unified_shared_memory/src/test_set_kernel_arg_mem.cpp
maximd33/compute-samples
b16a666b76b43c2a7bd1671edc563b45e978f1a7
[ "MIT" ]
10
2019-04-17T04:52:55.000Z
2021-04-19T22:20:07.000Z
compute_samples/tests/test_cl_unified_shared_memory/src/test_set_kernel_arg_mem.cpp
maximd33/compute-samples
b16a666b76b43c2a7bd1671edc563b45e978f1a7
[ "MIT" ]
17
2018-03-15T01:48:55.000Z
2022-02-10T11:10:17.000Z
/* * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "test_cl_unified_shared_memory/common.hpp" #include "test_harness/test_harness.hpp" namespace compute = boost::compute; namespace { const std::vector<compute::usm_type> set_kernel_arg_memory_types = { compute::usm_type::host, compute::usm_type::device, compute::usm_type::shared, compute::usm_type::unknown}; class clSetKernelArgMemPointerINTELWithAllocationCountRegionCountOffsetsAndMemoryTypes : public CopyKernelTest {}; HWTEST_P( clSetKernelArgMemPointerINTELWithAllocationCountRegionCountOffsetsAndMemoryTypes, GivenCopyKernelThenExpectedOutputIsReturned) { kernel_.set_arg_mem_ptr(0, destination_->get() + destination_offset_); kernel_.set_arg_mem_ptr(1, source_->get() + source_offset_); kernel_.set_arg(2, sizeof(uint8_t)); compute::command_queue queue = compute::system::default_queue(); queue.enqueue_1d_range_kernel(kernel_, 0, region_count_, 0); queue.finish(); const std::vector<uint8_t> actual = destination_->read(region_count_, destination_offset_); EXPECT_EQ(reference_, actual); } const std::vector<CopyKernelCombination> set_kernel_arg_offsets = { {256, 256, 0, 0}, {256, 128, 128, 0}, {256, 128, 0, 128}}; INSTANTIATE_TEST_SUITE_P( Offsets, clSetKernelArgMemPointerINTELWithAllocationCountRegionCountOffsetsAndMemoryTypes, ::testing::Combine(::testing::ValuesIn(set_kernel_arg_offsets), ::testing::ValuesIn(set_kernel_arg_memory_types), ::testing::ValuesIn(set_kernel_arg_memory_types)), copy_kernel_test_name_suffix); } // namespace
32.764706
85
0.752244
[ "vector" ]
115ffac34e8958d56c7ce96473b054754a0d2cbd
5,848
cxx
C++
applications/rtkforwardprojections/rtkforwardprojections.cxx
GabrieleBelotti/RTK
15dd2573887181a78dd9d3e5337578dd6645bb59
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
applications/rtkforwardprojections/rtkforwardprojections.cxx
GabrieleBelotti/RTK
15dd2573887181a78dd9d3e5337578dd6645bb59
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
applications/rtkforwardprojections/rtkforwardprojections.cxx
GabrieleBelotti/RTK
15dd2573887181a78dd9d3e5337578dd6645bb59
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/*========================================================================= * * Copyright RTK Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "rtkforwardprojections_ggo.h" #include "rtkGgoFunctions.h" #include "rtkThreeDCircularProjectionGeometryXMLFile.h" #include "rtkJosephForwardProjectionImageFilter.h" #include "rtkJosephForwardAttenuatedProjectionImageFilter.h" #include "rtkZengForwardProjectionImageFilter.h" #ifdef RTK_USE_CUDA # include "rtkCudaForwardProjectionImageFilter.h" #endif #include <itkImageFileReader.h> #include <itkImageFileWriter.h> int main(int argc, char * argv[]) { GGO(rtkforwardprojections, args_info); using OutputPixelType = float; constexpr unsigned int Dimension = 3; #ifdef RTK_USE_CUDA using OutputImageType = itk::CudaImage<OutputPixelType, Dimension>; #else using OutputImageType = itk::Image<OutputPixelType, Dimension>; #endif // Geometry if (args_info.verbose_flag) std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::flush; rtk::ThreeDCircularProjectionGeometry::Pointer geometry; TRY_AND_EXIT_ON_ITK_EXCEPTION(geometry = rtk::ReadGeometry(args_info.geometry_arg)); if (args_info.verbose_flag) std::cout << " done." << std::endl; // Create a stack of empty projection images using ConstantImageSourceType = rtk::ConstantImageSource<OutputImageType>; ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New(); rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkforwardprojections>(constantImageSource, args_info); // Adjust size according to geometry ConstantImageSourceType::SizeType sizeOutput; sizeOutput[0] = constantImageSource->GetSize()[0]; sizeOutput[1] = constantImageSource->GetSize()[1]; sizeOutput[2] = geometry->GetGantryAngles().size(); constantImageSource->SetSize(sizeOutput); // Input reader if (args_info.verbose_flag) std::cout << "Reading input volume " << args_info.input_arg << "..." << std::endl; OutputImageType::Pointer inputVolume; TRY_AND_EXIT_ON_ITK_EXCEPTION(inputVolume = itk::ReadImage<OutputImageType>(args_info.input_arg)) OutputImageType::Pointer attenuationMap; if (args_info.attenuationmap_given) { if (args_info.verbose_flag) std::cout << "Reading attenuation map " << args_info.attenuationmap_arg << "..." << std::endl; // Read an existing image to initialize the attenuation map attenuationMap = itk::ReadImage<OutputImageType>(args_info.attenuationmap_arg); } // Create forward projection image filter if (args_info.verbose_flag) std::cout << "Projecting volume..." << std::endl; rtk::ForwardProjectionImageFilter<OutputImageType, OutputImageType>::Pointer forwardProjection; switch (args_info.fp_arg) { case (fp_arg_Joseph): forwardProjection = rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType>::New(); break; case (fp_arg_JosephAttenuated): forwardProjection = rtk::JosephForwardAttenuatedProjectionImageFilter<OutputImageType, OutputImageType>::New(); break; case (fp_arg_Zeng): forwardProjection = rtk::ZengForwardProjectionImageFilter<OutputImageType, OutputImageType>::New(); break; case (fp_arg_CudaRayCast): #ifdef RTK_USE_CUDA forwardProjection = rtk::CudaForwardProjectionImageFilter<OutputImageType, OutputImageType>::New(); dynamic_cast<rtk::CudaForwardProjectionImageFilter<OutputImageType, OutputImageType> *>( forwardProjection.GetPointer()) ->SetStepSize(args_info.step_arg); #else std::cerr << "The program has not been compiled with cuda option" << std::endl; return EXIT_FAILURE; #endif break; default: std::cerr << "Unhandled --method value." << std::endl; return EXIT_FAILURE; } forwardProjection->SetInput(constantImageSource->GetOutput()); forwardProjection->SetInput(1, inputVolume); if (args_info.attenuationmap_given) forwardProjection->SetInput(2, attenuationMap); if (args_info.sigmazero_given && args_info.fp_arg == fp_arg_Zeng) dynamic_cast<rtk::ZengForwardProjectionImageFilter<OutputImageType, OutputImageType> *>( forwardProjection.GetPointer()) ->SetSigmaZero(args_info.sigmazero_arg); if (args_info.alphapsf_given && args_info.fp_arg == fp_arg_Zeng) dynamic_cast<rtk::ZengForwardProjectionImageFilter<OutputImageType, OutputImageType> *>( forwardProjection.GetPointer()) ->SetAlpha(args_info.alphapsf_arg); forwardProjection->SetGeometry(geometry); if (!args_info.lowmem_flag) { TRY_AND_EXIT_ON_ITK_EXCEPTION(forwardProjection->Update()) } // Write if (args_info.verbose_flag) std::cout << "Writing... " << std::endl; using WriterType = itk::ImageFileWriter<OutputImageType>; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(args_info.output_arg); writer->SetInput(forwardProjection->GetOutput()); if (args_info.lowmem_flag) { writer->SetNumberOfStreamDivisions(sizeOutput[2]); } TRY_AND_EXIT_ON_ITK_EXCEPTION(writer->Update()) return EXIT_SUCCESS; }
39.513514
117
0.719562
[ "geometry" ]
11604d5e7d7ec7a6d687afd26a45326b8a64d8df
6,074
cc
C++
src/libtools/crosscorrelate.cc
vaidyanathanms/votca.tools
62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4
[ "Apache-2.0" ]
null
null
null
src/libtools/crosscorrelate.cc
vaidyanathanms/votca.tools
62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4
[ "Apache-2.0" ]
null
null
null
src/libtools/crosscorrelate.cc
vaidyanathanms/votca.tools
62f9070f6b65c5bfd1227d61cddd2c5c29bcb8d4
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <votca/tools/crosscorrelate.h> #include <votca_config.h> #ifndef NOFFTW #include <fftw3.h> #endif namespace votca { namespace tools { /** \todo clean implementation!!! */ void CrossCorrelate::AutoCorrelate(DataCollection<double>::selection *data, bool average) { #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCorrelate is not compiled-in due to disabling of FFTW -recompile Votca Tools with FFTW3 support "); #else size_t N = (*data)[0].size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft, ifft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &(*data)[0][0], tmp, FFTW_ESTIMATE); ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0], FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(size_t i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } fftw_execute(ifft); /*double m=0; for(int i=0; i<N; i++) { _corrfunc[i] = 0; m+=(*data)[0][i]; } m=m/(double)N; for(int i=0;i<N; i++) for(int j=0; j<N-i-1; j++) _corrfunc[i]+=((*data)[0][j]-m)*((*data)[0][(i+j)]-m); */ double d = _corrfunc[0]; for(size_t i=0; i<N; i++) _corrfunc[i] = _corrfunc[i]/d; //cout << *data << endl; fftw_destroy_plan(fft); fftw_destroy_plan(ifft); fftw_free(tmp); #endif } void CrossCorrelate::AutoFourier(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoFourier is not compiled-in due to disabling of FFTW -recompile Votca Tools with FFTW3 support "); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(size_t i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } // copy the real component of temp to the _corrfunc vector for(size_t i=0; i<N; i++){ _corrfunc[i] = tmp[i][0]; } fftw_destroy_plan(fft); fftw_free(tmp); #endif } void CrossCorrelate::FFTOnly(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::FFTOnly is not compiled-in due to disabling of FFTW -recompile Votca Tools with FFTW3 support "); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); fftw_execute(fft); // copy the real component of temp to the _corrfunc vector for(size_t i=0; i<N/2+1; i++){ _corrfunc[i] = tmp[i][0]; } fftw_destroy_plan(fft); fftw_free(tmp); #endif } void CrossCorrelate::DCTOnly(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::DCTOnly is not compiled-in due to disabling of FFTW -recompile Votca Tools with FFTW3 support "); #else size_t N = ivec.size(); _corrfunc.resize(N); vector <double> tmp; tmp.resize(N); fftw_plan fft; // do real to real discrete cosine trafo fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE); fftw_execute(fft); // store results for(size_t i=0; i<N; i++){ _corrfunc[i] = tmp[i]; } fftw_destroy_plan(fft); #endif } void CrossCorrelate::AutoCosine(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCosine is not compiled-in due to disabling of FFTW -recompile Votca Tools with FFTW3 support "); #else size_t N = ivec.size(); _corrfunc.resize(N); vector <double> tmp; tmp.resize(N); fftw_plan fft; // do real to real discrete cosine trafo fft = fftw_plan_r2r_1d(N, &ivec[0], &tmp[0], FFTW_REDFT10, FFTW_ESTIMATE); fftw_execute(fft); // compute autocorrelation tmp[0] = 0; for(size_t i=1; i<N; i++) { tmp[i] = tmp[i]*tmp[i]; } // store results for(size_t i=0; i<N; i++){ _corrfunc[i] = tmp[i]; } fftw_destroy_plan(fft); #endif } void CrossCorrelate::AutoCorr(vector <double>& ivec){ #ifdef NOFFTW throw std::runtime_error("CrossCorrelate::AutoCorr is not compiled-in due to disabling of FFTW -recompile Votca Tools with FFTW3 support "); #else size_t N = ivec.size(); _corrfunc.resize(N); fftw_complex *tmp; fftw_plan fft, ifft; tmp = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * (N/2+1)); fft = fftw_plan_dft_r2c_1d(N, &ivec[0], tmp, FFTW_ESTIMATE); ifft = fftw_plan_dft_c2r_1d(N, tmp, &_corrfunc[0], FFTW_ESTIMATE); fftw_execute(fft); tmp[0][0] = tmp[0][1] = 0; for(size_t i=1; i<N/2+1; i++) { tmp[i][0] = tmp[i][0]*tmp[i][0] + tmp[i][1]*tmp[i][1]; tmp[i][1] = 0; } fftw_execute(ifft); double d = _corrfunc[0]; for(size_t i=0; i<N; i++) _corrfunc[i] = _corrfunc[i]/d; fftw_destroy_plan(fft); fftw_destroy_plan(ifft); fftw_free(tmp); #endif } }}
27.484163
149
0.612117
[ "vector" ]
11646d0b76ba08c92b3f837ac1debd996f49b3c9
6,499
cpp
C++
src/util/piped_process.cpp
jezhiggins/cbmc
be17ef4790b821375e485fc485b50bd9be690609
[ "BSD-4-Clause" ]
null
null
null
src/util/piped_process.cpp
jezhiggins/cbmc
be17ef4790b821375e485fc485b50bd9be690609
[ "BSD-4-Clause" ]
null
null
null
src/util/piped_process.cpp
jezhiggins/cbmc
be17ef4790b821375e485fc485b50bd9be690609
[ "BSD-4-Clause" ]
null
null
null
/// \file piped_process.cpp /// Subprocess communication with pipes. /// \author Diffblue Ltd. #ifdef _WIN32 // Windows includes go here #else # include <fcntl.h> // library for fcntl function # include <poll.h> // library for poll function # include <signal.h> // library for kill function # include <unistd.h> // library for read/write/sleep/etc. functions #endif #ifdef _WIN32 // Unimplemented on windows for now... #else # include <cstring> // library for strerror function (on linux) # include <iostream> # include <vector> # include "exception_utils.h" # include "invariant.h" # include "narrow.h" # include "optional.h" # include "piped_process.h" # include "string_utils.h" # define BUFSIZE 2048 piped_processt::piped_processt(const std::vector<std::string> commandvec) { # ifdef _WIN32 UNIMPLEMENTED_FEATURE("Pipe IPC on windows.") # else if(pipe(pipe_input) == -1) { throw system_exceptiont("Input pipe creation failed"); } if(pipe(pipe_output) == -1) { throw system_exceptiont("Output pipe creation failed"); } // Default state process_state = statet::NOT_CREATED; if(fcntl(pipe_output[0], F_SETFL, O_NONBLOCK) < 0) { throw system_exceptiont("Setting pipe non-blocking failed"); } // Create a new process for the child that will execute the // command and receive information via pipes. child_process_id = fork(); if(child_process_id == 0) { // child process here // Close pipes that will be used by the parent so we do // not have our own copies and conflicts. close(pipe_input[1]); close(pipe_output[0]); // Duplicate pipes so we have the ones we need. dup2(pipe_input[0], STDIN_FILENO); dup2(pipe_output[1], STDOUT_FILENO); dup2(pipe_output[1], STDERR_FILENO); // Create a char** for the arguments (all the contents of commandvec // except the first element, i.e. the command itself). char **args = reinterpret_cast<char **>(malloc((commandvec.size()) * sizeof(char *))); // Add all the arguments to the args array of char *. unsigned long i = 0; while(i < commandvec.size()) { args[i] = strdup(commandvec[i].c_str()); i++; } args[i] = NULL; execvp(commandvec[0].c_str(), args); // The args variable will be handled by the OS if execvp succeeds, but // if execvp fails then we should free it here (just in case the runtime // error below continues execution.) while(i > 0) { i--; free(args[i]); } free(args); // Only reachable if execvp failed // Note that here we send to std::cerr since we are in the child process // here and this is received by the parent process. std::cerr << "Launching " << commandvec[0] << " failed with error: " << std::strerror(errno) << std::endl; abort(); } else { // parent process here // Close pipes to be used by the child process close(pipe_input[0]); close(pipe_output[1]); // Get stream for sending to the child process command_stream = fdopen(pipe_input[1], "w"); process_state = statet::CREATED; } # endif } piped_processt::~piped_processt() { # ifdef _WIN32 UNIMPLEMENTED_FEATURE("Pipe IPC on windows: piped_processt constructor") # else // Close the parent side of the remaining pipes fclose(command_stream); // Note that the above will call close(pipe_input[1]); close(pipe_output[0]); // Send signal to the child process to terminate kill(child_process_id, SIGTERM); # endif } piped_processt::send_responset piped_processt::send(const std::string &message) { # ifdef _WIN32 UNIMPLEMENTED_FEATURE("Pipe IPC on windows: send()") # else if(process_state != statet::CREATED) { return send_responset::ERROR; } // send message to solver process int send_status = fputs(message.c_str(), command_stream); fflush(command_stream); if(send_status == EOF) { return send_responset::FAILED; } return send_responset::SUCCEEDED; # endif } std::string piped_processt::receive() { # ifdef _WIN32 UNIMPLEMENTED_FEATURE("Pipe IPC on windows: receive()") # else INVARIANT( process_state == statet::CREATED, "Can only receive() from a fully initialised process"); std::string response = std::string(""); int nbytes; char buff[BUFSIZE]; while(true) { nbytes = read(pipe_output[0], buff, BUFSIZE); INVARIANT( nbytes < BUFSIZE, "More bytes cannot be read at a time, than the size of the buffer"); switch(nbytes) { case -1: // Nothing more to read in the pipe return response; case 0: // Pipe is closed. process_state = statet::STOPPED; return response; default: // Read some bytes, append them to the response and continue response.append(buff, nbytes); } } UNREACHABLE; # endif } std::string piped_processt::wait_receive() { // can_receive(PIPED_PROCESS_INFINITE_TIMEOUT) waits an ubounded time until // there is some data can_receive(PIPED_PROCESS_INFINITE_TIMEOUT); return receive(); } piped_processt::statet piped_processt::get_status() { return process_state; } bool piped_processt::can_receive(optionalt<std::size_t> wait_time) { # ifdef _WIN32 UNIMPLEMENTED_FEATURE( "Pipe IPC on windows: can_receive(optionalt<std::size_t> wait_time)") # else // unwrap the optional argument here const int timeout = wait_time ? narrow<int>(*wait_time) : -1; struct pollfd fds // NOLINT { pipe_output[0], POLLIN, 0 }; nfds_t nfds = POLLIN; const int ready = poll(&fds, nfds, timeout); switch(ready) { case -1: // Error case // Further error handling could go here process_state = statet::ERROR; // fallthrough intended case 0: // Timeout case // Do nothing for timeout and error fallthrough, default function behaviour // is to return false. break; default: // Found some events, check for POLLIN if(fds.revents & POLLIN) { // we can read from the pipe here return true; } // Some revent we did not ask for or check for, can't read though. } return false; # endif } bool piped_processt::can_receive() { return can_receive(0); } void piped_processt::wait_receivable(int wait_time) { # ifdef _WIN32 UNIMPLEMENTED_FEATURE("Pipe IPC on windows: wait_stopped(int wait_time)") # else while(process_state == statet::CREATED && !can_receive(0)) { usleep(wait_time); } # endif } #endif
24.711027
79
0.670565
[ "vector" ]
1165dba8d4dc18484ffe3e50b81400a359dfe947
11,154
cpp
C++
DiligentCore/Graphics/GraphicsEngineOpenGL/src/FBOCache.cpp
Romanovich1311/DEngine-pcsx4
65d28b15e9428d77963de95412aaceeb5930d29d
[ "Apache-2.0" ]
15
2021-07-03T17:20:50.000Z
2022-03-20T23:39:09.000Z
DiligentCore/Graphics/GraphicsEngineOpenGL/src/FBOCache.cpp
Romanovich1311/DEngine-pcsx4
65d28b15e9428d77963de95412aaceeb5930d29d
[ "Apache-2.0" ]
1
2021-08-09T15:10:17.000Z
2021-09-30T06:47:04.000Z
DiligentCore/Graphics/GraphicsEngineOpenGL/src/FBOCache.cpp
Romanovich1311/DEngine-pcsx4
65d28b15e9428d77963de95412aaceeb5930d29d
[ "Apache-2.0" ]
9
2021-07-21T10:53:59.000Z
2022-03-03T10:27:33.000Z
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "pch.h" #include "FBOCache.hpp" #include "RenderDeviceGLImpl.hpp" #include "TextureBaseGL.hpp" #include "GLContextState.hpp" namespace Diligent { bool FBOCache::FBOCacheKey::operator==(const FBOCacheKey& Key) const { if (Hash != 0 && Key.Hash != 0 && Hash != Key.Hash) return false; if (NumRenderTargets != Key.NumRenderTargets) return false; for (Uint32 rt = 0; rt < NumRenderTargets; ++rt) { if (RTIds[rt] != Key.RTIds[rt]) return false; if (RTIds[rt]) { if (!(RTVDescs[rt] == Key.RTVDescs[rt])) return false; } } if (DSId != Key.DSId) return false; if (DSId) { if (!(DSVDesc == Key.DSVDesc)) return false; } return true; } std::size_t FBOCache::FBOCacheKeyHashFunc::operator()(const FBOCacheKey& Key) const { if (Key.Hash == 0) { std::hash<TextureViewDesc> TexViewDescHasher; Key.Hash = 0; HashCombine(Key.Hash, Key.NumRenderTargets); for (Uint32 rt = 0; rt < Key.NumRenderTargets; ++rt) { HashCombine(Key.Hash, Key.RTIds[rt]); if (Key.RTIds[rt]) HashCombine(Key.Hash, TexViewDescHasher(Key.RTVDescs[rt])); } HashCombine(Key.Hash, Key.DSId); if (Key.DSId) HashCombine(Key.Hash, TexViewDescHasher(Key.DSVDesc)); } return Key.Hash; } FBOCache::FBOCache() { m_Cache.max_load_factor(0.5f); m_TexIdToKey.max_load_factor(0.5f); } FBOCache::~FBOCache() { VERIFY(m_Cache.empty(), "FBO cache is not empty. Are there any unreleased objects?"); VERIFY(m_TexIdToKey.empty(), "TexIdToKey cache is not empty."); } void FBOCache::OnReleaseTexture(ITexture* pTexture) { ThreadingTools::LockHelper CacheLock(m_CacheLockFlag); auto* pTexGL = ValidatedCast<TextureBaseGL>(pTexture); // Find all FBOs that this texture used in auto EqualRange = m_TexIdToKey.equal_range(pTexGL->GetUniqueID()); for (auto It = EqualRange.first; It != EqualRange.second; ++It) { m_Cache.erase(It->second); } m_TexIdToKey.erase(EqualRange.first, EqualRange.second); } const GLObjectWrappers::GLFrameBufferObj& FBOCache::GetFBO(Uint32 NumRenderTargets, TextureViewGLImpl* ppRTVs[], TextureViewGLImpl* pDSV, GLContextState& ContextState) { // Pop null render targets from the end of the list while (NumRenderTargets > 0 && ppRTVs[NumRenderTargets - 1] == nullptr) --NumRenderTargets; VERIFY(NumRenderTargets != 0 || pDSV != nullptr, "At least one render target or a depth-stencil buffer must be provided"); // Lock the cache ThreadingTools::LockHelper CacheLock(m_CacheLockFlag); // Construct the key FBOCacheKey Key; VERIFY(NumRenderTargets < MAX_RENDER_TARGETS, "Too many render targets are being set"); NumRenderTargets = std::min(NumRenderTargets, MAX_RENDER_TARGETS); Key.NumRenderTargets = NumRenderTargets; for (Uint32 rt = 0; rt < NumRenderTargets; ++rt) { auto* pRTView = ppRTVs[rt]; if (pRTView == nullptr) continue; auto* pColorTexGL = pRTView->GetTexture<TextureBaseGL>(); pColorTexGL->TextureMemoryBarrier( GL_FRAMEBUFFER_BARRIER_BIT, // Reads and writes via framebuffer object attachments after the // barrier will reflect data written by shaders prior to the barrier. // Additionally, framebuffer writes issued after the barrier will wait // on the completion of all shader writes issued prior to the barrier. ContextState); Key.RTIds[rt] = pColorTexGL->GetUniqueID(); Key.RTVDescs[rt] = pRTView->GetDesc(); } if (pDSV) { auto* pDepthTexGL = pDSV->GetTexture<TextureBaseGL>(); pDepthTexGL->TextureMemoryBarrier(GL_FRAMEBUFFER_BARRIER_BIT, ContextState); Key.DSId = pDepthTexGL->GetUniqueID(); Key.DSVDesc = pDSV->GetDesc(); } // Try to find FBO in the map auto It = m_Cache.find(Key); if (It != m_Cache.end()) { return It->second; } else { // Create a new FBO GLObjectWrappers::GLFrameBufferObj NewFBO(true); ContextState.BindFBO(NewFBO); // Initialize the FBO for (Uint32 rt = 0; rt < NumRenderTargets; ++rt) { if (auto* pRTView = ppRTVs[rt]) { const auto& RTVDesc = pRTView->GetDesc(); auto* pColorTexGL = pRTView->GetTexture<TextureBaseGL>(); pColorTexGL->AttachToFramebuffer(RTVDesc, GL_COLOR_ATTACHMENT0 + rt); } } if (pDSV != nullptr) { const auto& DSVDesc = pDSV->GetDesc(); auto* pDepthTexGL = pDSV->GetTexture<TextureBaseGL>(); GLenum AttachmentPoint = 0; if (DSVDesc.Format == TEX_FORMAT_D32_FLOAT || DSVDesc.Format == TEX_FORMAT_D16_UNORM) { #ifdef _DEBUG { const auto GLTexFmt = pDepthTexGL->GetGLTexFormat(); VERIFY(GLTexFmt == GL_DEPTH_COMPONENT32F || GLTexFmt == GL_DEPTH_COMPONENT16, "Inappropriate internal texture format (", GLTexFmt, ") for depth attachment. GL_DEPTH_COMPONENT32F or GL_DEPTH_COMPONENT16 is expected"); } #endif AttachmentPoint = GL_DEPTH_ATTACHMENT; } else if (DSVDesc.Format == TEX_FORMAT_D32_FLOAT_S8X24_UINT || DSVDesc.Format == TEX_FORMAT_D24_UNORM_S8_UINT) { #ifdef _DEBUG { const auto GLTexFmt = pDepthTexGL->GetGLTexFormat(); VERIFY(GLTexFmt == GL_DEPTH24_STENCIL8 || GLTexFmt == GL_DEPTH32F_STENCIL8, "Inappropriate internal texture format (", GLTexFmt, ") for depth-stencil attachment. GL_DEPTH24_STENCIL8 or GL_DEPTH32F_STENCIL8 is expected"); } #endif AttachmentPoint = GL_DEPTH_STENCIL_ATTACHMENT; } else { UNEXPECTED(GetTextureFormatAttribs(DSVDesc.Format).Name, " is not valid depth-stencil view format"); } pDepthTexGL->AttachToFramebuffer(DSVDesc, AttachmentPoint); } // We now need to set mapping between shader outputs and // color attachments. This largely redundant step is performed // by glDrawBuffers() // clang-format off static const GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5, GL_COLOR_ATTACHMENT6, GL_COLOR_ATTACHMENT7, GL_COLOR_ATTACHMENT8, GL_COLOR_ATTACHMENT9, GL_COLOR_ATTACHMENT10, GL_COLOR_ATTACHMENT11, GL_COLOR_ATTACHMENT12, GL_COLOR_ATTACHMENT13, GL_COLOR_ATTACHMENT14, GL_COLOR_ATTACHMENT15 }; // clang-format on // The state set by glDrawBuffers() is part of the state of the framebuffer. // So it can be set up once and left it set. glDrawBuffers(NumRenderTargets, DrawBuffers); CHECK_GL_ERROR("Failed to set draw buffers via glDrawBuffers()"); GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (Status != GL_FRAMEBUFFER_COMPLETE) { const Char* StatusString = "Unknown"; switch (Status) { // clang-format off case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: StatusString = "GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: StatusString = "GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER: StatusString = "GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER: StatusString = "GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"; break; case GL_FRAMEBUFFER_UNSUPPORTED: StatusString = "GL_FRAMEBUFFER_UNSUPPORTED"; break; case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: StatusString = "GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE"; break; case GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS: StatusString = "GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS"; break; // clang-format on } LOG_ERROR("Framebuffer is incomplete. FB status: ", StatusString); UNEXPECTED("Framebuffer is incomplete"); } auto NewElems = m_Cache.emplace(std::make_pair(Key, std::move(NewFBO))); // New element must be actually inserted VERIFY(NewElems.second, "New element was not inserted"); if (Key.DSId != 0) m_TexIdToKey.insert(std::make_pair(Key.DSId, Key)); for (Uint32 rt = 0; rt < NumRenderTargets; ++rt) { if (Key.RTIds[rt] != 0) m_TexIdToKey.insert(std::make_pair(Key.RTIds[rt], Key)); } return NewElems.first->second; } } } // namespace Diligent
39.136842
136
0.607764
[ "render", "object" ]
116788d7cdbcb9c9b09997e283997a2dc52fd0c6
3,464
hpp
C++
src/include/libc_common.hpp
hobama/maat
3f0a7d3ef90fff3f1c465d0ae155488b245981b4
[ "MIT" ]
2
2020-03-23T06:47:19.000Z
2021-03-07T21:14:24.000Z
src/include/libc_common.hpp
hobama/maat
3f0a7d3ef90fff3f1c465d0ae155488b245981b4
[ "MIT" ]
null
null
null
src/include/libc_common.hpp
hobama/maat
3f0a7d3ef90fff3f1c465d0ae155488b245981b4
[ "MIT" ]
null
null
null
#ifndef ENV_LIBC_COMMON_H #define ENV_LIBC_COMMON_H #include "environment.hpp" #include "exception.hpp" #include "linux_x86.hpp" #include <vector> #include <cstdlib> #include <sstream> #include <ctime> /* ============================================== * Util functions * ============================================= */ /* Read a concrete C string into buffer * addr is the address of the string * max_len is the length of the buffer where to put the concrete string * len is set to the length of the string * is_tainted is set to True if one byte at least was tainted in the string */ bool _mem_read_c_string_and_taint(SymbolicEngine& sym, addr_t addr, char* buffer, int& len, unsigned int max_len, bool& is_tainted); bool _mem_read_c_string(SymbolicEngine& sym, addr_t addr, char* buffer, int& len, unsigned int max_len); #define SPEC_NONE 0 #define SPEC_UNSUPPORTED 1 #define SPEC_INT32 2 #define SPEC_STRING 3 #define SPEC_CHAR 4 #define SPEC_HEX32 5 // Int on hex format /* Tries to parse a format specifier in string format at index 'index'. * If successful, index is modified to the last char of the specifier */ int _get_specifier(char* format, int format_len, int& index, char* spec, int spec_max_len ); bool _get_format_string(SymbolicEngine& sym, char* format, int len, string& res); /* input: size of expressions must be 8 (a byte) */ bool _is_whitespace(char c); bool _is_terminating(char c); bool _read_format_string(SymbolicEngine& sym, char* format, int len, vector<Expr> input, int& param_parsed); /* non_implemented callback : raise an exception for unimplemented functions */ EnvCallbackReturn _simu_libc_common_not_implemented(SymbolicEngine& sym, vector<Expr> args); /* ============================================== * Linux X86 libc functions * ============================================= */ EnvCallbackReturn _simu_libc_common_abort(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_atoi(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_calloc(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_exit(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_fflush(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_free(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_getenv(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_getpagesize(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_malloc(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_memset(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_memcpy(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_puts(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_printf(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_rand(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_scanf(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_sprintf(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_srand(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_strcpy(SymbolicEngine& sym, vector<Expr> args); EnvCallbackReturn _simu_libc_common_strlen(SymbolicEngine& sym, vector<Expr> args); #endif
47.452055
132
0.757794
[ "vector" ]
11679cebdbb2b337fc27cd7b0986f6a9c3662271
520
cpp
C++
AtCoder/iroha2019-day1/d/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
AtCoder/iroha2019-day1/d/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
1
2021-10-19T08:47:23.000Z
2022-03-07T05:23:56.000Z
AtCoder/iroha2019-day1/d/main.cpp
H-Tatsuhiro/Com_Pro-Cpp
fd79f7821a76b11f4a6f83bbb26a034db577a877
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { int n, x, y; cin >> n >> x >> y; vector<int> c(n, 0); for (int i = 0; i < n; i++) cin >> c[i]; sort(c.begin(), c.end()); reverse(c.begin(), c.end()); int a = x, b = y; for (int i = 0; i < n; i++) { if (i % 2 == 0) a += c[i]; else b += c[i]; } if (a > b) cout << "Takahashi" << endl; else if (a < b) cout << "Aoki" << endl; else cout << "Draw" << endl; }
26
58
0.463462
[ "vector" ]
1173d005550eaeea69eb8efd7ef8d49c92b63e37
43,476
cc
C++
mysql-server/router/src/mysql_protocol/tests/test_classic_protocol_message.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/router/src/mysql_protocol/tests/test_classic_protocol_message.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/router/src/mysql_protocol/tests/test_classic_protocol_message.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mysqlrouter/classic_protocol_codec_message.h" #include <list> #include <vector> #include <gtest/gtest.h> #include "test_classic_protocol_codec.h" // string_literals are supposed to solve the same problem, but they are broken // on dev-studio 12.6 #define S(x) std::string((x), sizeof(x) - 1) // server::AuthMethodSwitch namespace classic_protocol { namespace message { namespace server { std::ostream &operator<<(std::ostream &os, const AuthMethodSwitch &v) { os << v.auth_method() << ", " << v.auth_method_data(); return os; } } // namespace server } // namespace message } // namespace classic_protocol using CodecMessageServerAuthMethodSwitchTest = CodecTest<classic_protocol::message::server::AuthMethodSwitch>; TEST_P(CodecMessageServerAuthMethodSwitchTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerAuthMethodSwitchTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::server::AuthMethodSwitch> codec_message_server_authmethodswitch_param[] = { {"4_0", {}, {}, {0xfe}}, {"5_6", {"mysql_native_password", S("zQg4i6oNy6=rHN/>-b)A\0")}, classic_protocol::capabilities::plugin_auth, {0xfe, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x5f, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x00, 0x7a, 0x51, 0x67, 0x34, 0x69, 0x36, 0x6f, 0x4e, 0x79, 0x36, 0x3d, 0x72, 0x48, 0x4e, 0x2f, 0x3e, 0x2d, 0x62, 0x29, 0x41, 0x00}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageServerAuthMethodSwitchTest, ::testing::ValuesIn(codec_message_server_authmethodswitch_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // server::AuthMethodData namespace classic_protocol { namespace message { namespace server { std::ostream &operator<<(std::ostream &os, const AuthMethodData &v) { os << static_cast<uint16_t>(v.packet_type()) << ", " << v.auth_method_data(); return os; } } // namespace server } // namespace message } // namespace classic_protocol using CodecMessageServerAuthMethodDataTest = CodecTest<classic_protocol::message::server::AuthMethodData>; TEST_P(CodecMessageServerAuthMethodDataTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerAuthMethodDataTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::server::AuthMethodData> codec_message_server_authmethoddata_param[] = { {"auth_fast_ack", {0x03, ""}, {}, {0x03}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageServerAuthMethodDataTest, ::testing::ValuesIn(codec_message_server_authmethoddata_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // server::Ok using CodecMessageServerOkTest = CodecTest<classic_protocol::message::server::Ok>; TEST_P(CodecMessageServerOkTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerOkTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::server::Ok> codec_message_server_ok_param[] = { {"3_23", {1, 3, 0, 0}, {}, {0x00, 0x01, 0x03}}, {"4_0", {1, 3, classic_protocol::status::autocommit, 0}, classic_protocol::capabilities::transactions, {0x00, 0x01, 0x03, 0x02, 0x00}}, {"4_1", {1, 3, classic_protocol::status::autocommit, 4}, classic_protocol::capabilities::protocol_41, {0x00, 0x01, 0x03, 0x02, 0x00, 0x04, 0x00}}, {"with_session_state_info", {1, 3, classic_protocol::status::autocommit | classic_protocol::status::session_state_changed, 4, {}, // no message {S("\0\16\nautocommit\2ON")}}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::session_track, {0x00, 0x01, 0x03, 0x02, 0x40, 0x04, 0x00, 0x00, 0x10, 0x00, 0x0e, 0x0a, 'a', 'u', 't', 'o', 'c', 'o', 'm', 'm', 'i', 't', 0x02, 'O', 'N'}}, {"with_session_state_info_and_message", {1, 3, classic_protocol::status::in_transaction | classic_protocol::status::no_index_used | classic_protocol::status::session_state_changed, 4, "Rows matched: 0 Changed: 0 Warnings: 0", {S("\5\t\10I___Ws__")}}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::session_track, {0x00, 0x01, 0x03, '!', 0x40, 0x04, 0x00, '(', 'R', 'o', 'w', 's', ' ', 'm', 'a', 't', 'c', 'h', 'e', 'd', ':', ' ', '0', ' ', ' ', 'C', 'h', 'a', 'n', 'g', 'e', 'd', ':', ' ', '0', ' ', ' ', 'W', 'a', 'r', 'n', 'i', 'n', 'g', 's', ':', ' ', '0', '\v', 0x05, '\t', 0x08, 'I', '_', '_', '_', 'W', 's', '_', '_'}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageServerOkTest, ::testing::ValuesIn(codec_message_server_ok_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // server::Eof using CodecMessageServerEofTest = CodecTest<classic_protocol::message::server::Eof>; TEST_P(CodecMessageServerEofTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerEofTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::server::Eof> codec_eof_param[] = { {"3_23", {}, {}, {0xfe}}, {"4_1", {classic_protocol::status::more_results_exist | classic_protocol::status::autocommit, 1}, classic_protocol::capabilities::protocol_41, {0xfe, 0x01, 0x00, 0x0a, 0x00}}, {"5_7", {classic_protocol::status::autocommit, 1}, classic_protocol::capabilities::text_result_with_session_tracking | classic_protocol::capabilities::protocol_41, {0xfe, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageServerEofTest, ::testing::ValuesIn(codec_eof_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // server::Error namespace classic_protocol { namespace message { namespace server { std::ostream &operator<<(std::ostream &os, Error const &v) { os << v.error_code() << ", " << v.sql_state() << ", " << v.message(); return os; } } // namespace server } // namespace message } // namespace classic_protocol using CodecMessageServerErrorTest = CodecTest<classic_protocol::message::server::Error>; TEST_P(CodecMessageServerErrorTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerErrorTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::server::Error> codec_message_server_error_param[] = { {"3_23", {1096, "No tables used", ""}, {}, {0xff, 0x48, 0x04, 'N', 'o', ' ', 't', 'a', 'b', 'l', 'e', 's', ' ', 'u', 's', 'e', 'd'}}, {"4_1", {1096, "No tables used", "HY000"}, classic_protocol::capabilities::protocol_41, {0xff, 0x48, 0x04, 0x23, 'H', 'Y', '0', '0', '0', 'N', 'o', ' ', 't', 'a', 'b', 'l', 'e', 's', ' ', 'u', 's', 'e', 'd'}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageServerErrorTest, ::testing::ValuesIn(codec_message_server_error_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // server::Greeting using CodecMessageServerGreetingTest = CodecTest<classic_protocol::message::server::Greeting>; TEST_P(CodecMessageServerGreetingTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerGreetingTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::server::Greeting> codec_message_server_greeting_param[] = { {"3_20_protocol_9", {0x09, "5.6.4-m7-log", 2646, "RB3vz&Gr", 0x0, 0x0, 0x0, ""}, {}, {0x09, 0x35, 0x2e, 0x36, 0x2e, 0x34, 0x2d, 0x6d, 0x37, 0x2d, 0x6c, 0x6f, 0x67, 0x00, 0x56, 0x0a, 0x00, 0x00, 0x52, 0x42, 0x33, 0x76, 0x7a, 0x26, 0x47, 0x72, 0x00}}, {"3_21_31", {0x0a, "3.21.31", 1, "-8pMne/X", 0b0000'0000'0000'1100, 0x0, 0x0, ""}, {}, {'\n', '3', '.', '2', '1', '.', '3', '1', '\0', '\1', '\0', '\0', '\0', '-', '8', 'p', 'M', 'n', 'e', '/', 'X', '\0', '\xc', '\0'}}, {"3_23_49", {0x0a, "3.23.49a", 1, "-8pMne/X", 0b0000'0000'0010'1100, classic_protocol::collation::Latin1SwedishCi, classic_protocol::status::autocommit, ""}, {}, {'\n', '3', '.', '2', '3', '.', '4', '9', 'a', '\0', '\1', '\0', '\0', '\0', '-', '8', 'p', 'M', 'n', 'e', '/', 'X', '\0', ',', '\0', '\10', '\2', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'}}, {"4_0_24", {0x0a, "4.0.24", 1, "v;`PR,\"d", 0b0010'0000'0010'1100, classic_protocol::collation::Latin1SwedishCi, classic_protocol::status::autocommit, ""}, {}, {'\n', '4', '.', '0', '.', '2', '4', '\0', '\1', '\0', '\0', '\0', 'v', ';', '`', 'P', 'R', ',', '"', 'd', '\0', ',', ' ', '\10', '\2', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'}}, {"5_6_4", {0x0a, "5.6.4-m7-log", 2646, S("RB3vz&Gr+yD&/ZZ305ZG\0"), 0xc00fffff, 0x8, 0x02, "mysql_native_password"}, {}, {0x0a, 0x35, 0x2e, 0x36, 0x2e, 0x34, 0x2d, 0x6d, 0x37, 0x2d, 0x6c, 0x6f, 0x67, 0x00, 0x56, 0x0a, 0x00, 0x00, 0x52, 0x42, 0x33, 0x76, 0x7a, 0x26, 0x47, 0x72, 0x00, 0xff, 0xff, 0x08, 0x02, 0x00, 0x0f, 0xc0, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x79, 0x44, 0x26, 0x2f, 0x5a, 0x5a, 0x33, 0x30, 0x35, 0x5a, 0x47, 0x00, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x5f, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x00}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageServerGreetingTest, ::testing::ValuesIn(codec_message_server_greeting_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); using CodecMessageServerGreetingFailTest = CodecFailTest<classic_protocol::message::server::Greeting>; TEST_P(CodecMessageServerGreetingFailTest, decode) { test_decode(GetParam()); } CodecFailParam codec_message_server_greeting_fail_param[] = { {"too_short", { '\n', // protocol '3', '.', '2', '1', '.', '3', '1', 0, // version 1, 0, 0, 0, // packet-size '-', '8', 'p', 'M', 'n', 'e', '/', 'X', 0, // auth-method-data 0xc // fail: missing 2nd byte }, {}, classic_protocol::codec_errc::not_enough_input}, {"empty", {}, {}, classic_protocol::codec_errc::not_enough_input}, {"unknown_protocol_8", {8}, {}, classic_protocol::codec_errc::invalid_input}, {"unknown_protocol_11", {11}, {}, classic_protocol::codec_errc::invalid_input}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageServerGreetingFailTest, ::testing::ValuesIn(codec_message_server_greeting_fail_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // server::ColumMeta using CodecMessageServerColumnMetaTest = CodecTest<classic_protocol::message::server::ColumnMeta>; TEST_P(CodecMessageServerColumnMetaTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerColumnMetaTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::server::ColumnMeta> codec_message_server_columnmeta_param[] = { {"3_21", {{}, {}, {}, {}, "1", {}, 0x0, 1, classic_protocol::field_type::LongLong, 0x0001, 0x1f}, {}, { 0, // table 1, '1', // column 3, 0x1, 0x0, 0x0, // column-length 1, 0x8, // type 2, 0x1, 0x1f // flags_and_decimal }}, {"3_23", {{}, {}, {}, {}, "1", {}, 0x0, 1, classic_protocol::field_type::LongLong, 0x0001, 0x1f}, classic_protocol::capabilities::long_flag, { 0, // table 1, '1', // column 3, 0x1, 0x0, 0x0, // column-length 1, 0x8, // type 3, 0x1, 0x0, 0x1f // flags_and_decimal }}, {"4_1", {"def", "", "", "", "@@version_comment", "", 0xff, 112, classic_protocol::field_type::VarString, 0x0000, 0x1f}, classic_protocol::capabilities::protocol_41, {3, 'd', 'e', 'f', // catalog 0, // schema 0, // table 0, // orig_table 17, '@', '@', 'v', 'e', 'r', 's', 'i', 'o', 'n', '_', 'c', 'o', 'm', 'm', 'e', 'n', 't', // name 0, // orig_name 12, // other.length 0xff, 0, // other.collation 'p', 0, 0, 0, // other.column_length 0xfd, // other.type 0, 0, // other.flags 0x1f, // other.decimals 0, 0}}}; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageServerColumnMetaTest, ::testing::ValuesIn(codec_message_server_columnmeta_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // server::Row using CodecMessageServerRowTest = CodecTest<classic_protocol::message::server::Row>; TEST_P(CodecMessageServerRowTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerRowTest, decode) { test_decode(GetParam()); } using namespace std::string_literals; const CodecParam<classic_protocol::message::server::Row> codec_message_server_row_param[] = { {"abc_def", {{"abc"s, "def"s}}, {}, {0x03, 'a', 'b', 'c', 0x03, 'd', 'e', 'f'}}, {"null_null", {{stdx::make_unexpected(), stdx::make_unexpected()}}, {}, {0xfb, 0xfb}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageServerRowTest, ::testing::ValuesIn(codec_message_server_row_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // server::StmtRow using CodecMessageServerStmtRowTest = CodecTest<classic_protocol::message::server::StmtRow>; TEST_P(CodecMessageServerStmtRowTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageServerStmtRowTest, decode) { test_decode(GetParam(), std::vector<classic_protocol::field_type::value_type>{ classic_protocol::field_type::VarString}); } // client::Quit using CodecMessageClientQuitTest = CodecTest<classic_protocol::message::client::Quit>; TEST_P(CodecMessageClientQuitTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientQuitTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::Quit> codec_message_client_quit_param[] = { {"1", {}, {}, {0x01}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageClientQuitTest, ::testing::ValuesIn(codec_message_client_quit_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::InitSchema using CodecMessageClientInitSchemaTest = CodecTest<classic_protocol::message::client::InitSchema>; TEST_P(CodecMessageClientInitSchemaTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientInitSchemaTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::InitSchema> codec_message_client_initschema_param[] = { {"schema", {"schema"}, {}, {0x02, 's', 'c', 'h', 'e', 'm', 'a'}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageClientInitSchemaTest, ::testing::ValuesIn(codec_message_client_initschema_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::Query using CodecMessageClientQueryTest = CodecTest<classic_protocol::message::client::Query>; TEST_P(CodecMessageClientQueryTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientQueryTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::Query> codec_message_client_query_param[] = { {"do_1", {"DO 1"}, {}, {0x03, 'D', 'O', ' ', '1'}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageClientQueryTest, ::testing::ValuesIn(codec_message_client_query_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::Ping using CodecMessageClientPingTest = CodecTest<classic_protocol::message::client::Ping>; TEST_P(CodecMessageClientPingTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientPingTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::Ping> codec_ping_param[] = { {"ping", {}, {}, {0x0e}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageClientPingTest, ::testing::ValuesIn(codec_ping_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::Statistics using CodecMessageClientStatisticsTest = CodecTest<classic_protocol::message::client::Statistics>; TEST_P(CodecMessageClientStatisticsTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientStatisticsTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::Statistics> codec_message_client_statistics_param[] = { {"1", {}, {}, {0x09}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageClientStatisticsTest, ::testing::ValuesIn(codec_message_client_statistics_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::ResetConnection using CodecMessageClientResetConnectionTest = CodecTest<classic_protocol::message::client::ResetConnection>; TEST_P(CodecMessageClientResetConnectionTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientResetConnectionTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::ResetConnection> codec_message_client_resetconnection_param[] = { {"1", {}, {}, {0x1f}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageClientResetConnectionTest, ::testing::ValuesIn(codec_message_client_resetconnection_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::StmtPrepare using CodecMessageClientStmtPrepareTest = CodecTest<classic_protocol::message::client::StmtPrepare>; TEST_P(CodecMessageClientStmtPrepareTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientStmtPrepareTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::StmtPrepare> codec_message_client_prepstmt_param[] = { {"do_1", {"DO 1"}, {}, {0x16, 'D', 'O', ' ', '1'}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageClientStmtPrepareTest, ::testing::ValuesIn(codec_message_client_prepstmt_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::StmtParamAppendData using CodecMessageClientStmtParamAppendDataTest = CodecTest<classic_protocol::message::client::StmtParamAppendData>; TEST_P(CodecMessageClientStmtParamAppendDataTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientStmtParamAppendDataTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::StmtParamAppendData> codec_message_client_stmtparamappenddata_param[] = { {"append_stmt_1_param_1_abc", {1, 1, "abc"}, {}, {0x18, 1, 0, 0, 0, 1, 0, 'a', 'b', 'c'}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageClientStmtParamAppendDataTest, ::testing::ValuesIn(codec_message_client_stmtparamappenddata_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::StmtExecute // namespace classic_protocol { namespace message { namespace client { std::ostream &operator<<(std::ostream &os, const StmtExecute &v) { os << "StmtExecute: " << "\n"; os << " stmt_id: " << v.statement_id() << "\n"; os << " flags: " << v.flags().to_string() << "\n"; os << " iteration_count: " << v.iteration_count() << "\n"; os << " new_params_bound: " << v.new_params_bound() << "\n"; os << " types: " << "\n"; for (auto const &t : v.types()) { os << " - " << static_cast<uint16_t>(t) << "\n"; } os << " values: " << "\n"; for (auto const &field : v.values()) { if (field) { os << " - string{" << field.value().size() << "}\n"; } else { os << " - NULL\n"; } } return os; } } // namespace client } // namespace message } // namespace classic_protocol using CodecMessageClientStmtExecuteTest = CodecTest<classic_protocol::message::client::StmtExecute>; TEST_P(CodecMessageClientStmtExecuteTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientStmtExecuteTest, decode) { test_decode(GetParam(), [](uint32_t /* statement_id */) { return 1; }); } const CodecParam<classic_protocol::message::client::StmtExecute> codec_stmt_execute_param[] = { {"exec_stmt", {1, 0x00, 1, true, {classic_protocol::field_type::Varchar}, {{"foo"}}}, {}, {0x17, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0f, 0x00, 0x03, 0x66, 0x6f, 0x6f}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageClientStmtExecuteTest, ::testing::ValuesIn(codec_stmt_execute_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::StmtClose using CodecMessageClientStmtCloseTest = CodecTest<classic_protocol::message::client::StmtClose>; TEST_P(CodecMessageClientStmtCloseTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientStmtCloseTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::StmtClose> codec_stmt_close_param[] = { {"close_stmt_1", {1}, {}, {0x19, 0x01, 0x00, 0x00, 0x00}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageClientStmtCloseTest, ::testing::ValuesIn(codec_stmt_close_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::StmtReset using CodecMessageClientStmtResetTest = CodecTest<classic_protocol::message::client::StmtReset>; TEST_P(CodecMessageClientStmtResetTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientStmtResetTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::StmtReset> codec_stmt_reset_param[] = { {"reset_stmt_1", {1}, {}, {0x1a, 0x01, 0x00, 0x00, 0x00}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageClientStmtResetTest, ::testing::ValuesIn(codec_stmt_reset_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::StmtSetOption using CodecMessageClientStmtSetOptionTest = CodecTest<classic_protocol::message::client::StmtSetOption>; TEST_P(CodecMessageClientStmtSetOptionTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientStmtSetOptionTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::StmtSetOption> codec_stmt_set_option_param[] = { {"set_option_stmt_1", {1}, {}, {0x1b, 0x01, 0x00}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageClientStmtSetOptionTest, ::testing::ValuesIn(codec_stmt_set_option_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::StmtFetch using CodecMessageClientStmtFetchTest = CodecTest<classic_protocol::message::client::StmtFetch>; TEST_P(CodecMessageClientStmtFetchTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientStmtFetchTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::StmtFetch> codec_stmt_fetch_param[] = { {"fetch_stmt_1", {1, 2}, {}, {0x1c, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00}}, }; INSTANTIATE_TEST_SUITE_P(Spec, CodecMessageClientStmtFetchTest, ::testing::ValuesIn(codec_stmt_fetch_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::Greeting namespace classic_protocol { namespace message { namespace client { std::ostream &operator<<(std::ostream &os, const Greeting &v) { os << "Greeting: " << "\n"; os << " schema: " << v.schema() << "\n"; os << " username: " << v.username() << "\n"; os << " auth_method_name: " << v.auth_method_name() << "\n"; os << " max_packet_size: " << v.max_packet_size() << "\n"; os << " capabilities: " << v.capabilities().to_string() << "\n"; return os; } } // namespace client } // namespace message } // namespace classic_protocol using CodecMessageClientGreetingTest = CodecTest<classic_protocol::message::client::Greeting>; TEST_P(CodecMessageClientGreetingTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientGreetingTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::Greeting> codec_message_client_greeting_param[] = { {"5_6_6", {0x001ea285, 1 << 30, 0x8, "root", S("\"Py\xA2\x12\xD4\xE8\x82\xE5\xB3\xF4\x1A\x97uk\xC8\xBE\xDB" "\x9F\x80"), "", "mysql_native_password", "\x3" "_os" "\t" "debian6.0" "\f" "_client_name" "\b" "libmysql" "\x4" "_pid" "\x5" "22344" "\xF" "_client_version" "\b" "5.6.6-m9" "\t" "_platform" "\x6" "x86_64" "\x3" "foo" "\x3" "bar"}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::secure_connection | classic_protocol::capabilities::plugin_auth | classic_protocol::capabilities::connect_attributes, { 0x85, 0xa2, 0x1e, 0x00, // caps 0x00, 0x00, 0x00, 0x40, // max-packet-size 0x08, // collation 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // filler 0x72, 0x6f, 0x6f, 0x74, 0x00, // username 0x14, 0x22, 0x50, 0x79, 0xa2, 0x12, 0xd4, 0xe8, 0x82, 0xe5, 0xb3, 0xf4, 0x1a, 0x97, 0x75, 0x6b, 0xc8, 0xbe, 0xdb, 0x9f, 0x80, // auth-method-data 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x5f, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x00, // auth-method 0x61, 0x03, '_', 'o', 's', 0x09, 'd', 'e', 'b', 'i', 'a', 'n', '6', '.', '0', 0x0c, 0x5f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x08, 0x6c, 0x69, 0x62, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x04, 0x5f, 0x70, 0x69, 0x64, 0x05, 0x32, 0x32, 0x33, 0x34, 0x34, 0x0f, 0x5f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x08, 0x35, 0x2e, 0x36, 0x2e, 0x36, 0x2d, 0x6d, 0x39, 0x09, 0x5f, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x06, 0x78, 0x38, 0x36, 0x5f, 0x36, 0x34, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72 // connect-attributes }}, {"5_5_8", {0x000fa68d, 1 << 24, 0x8, "pam", "\xAB\t\xEE\xF6\xBC\xB1" "2>a\x14" "8e\xC0\x99\x1D\x95}u\xD4G", "test", "mysql_native_password", ""}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::secure_connection | classic_protocol::capabilities::connect_with_schema | classic_protocol::capabilities::plugin_auth | classic_protocol::capabilities::connect_attributes, { 0x8d, 0xa6, 0x0f, 0x00, // caps 0x00, 0x00, 0x00, 0x01, // max-packet-size 0x08, // collation 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 23 fillers 'p', 'a', 'm', '\0', // username 0x14, 0xab, 0x09, 0xee, 0xf6, 0xbc, 0xb1, 0x32, 0x3e, 0x61, 0x14, 0x38, 0x65, 0xc0, 0x99, 0x1d, 0x95, 0x7d, 0x75, 0xd4, 0x47, // auth-method-data 0x74, 0x65, 0x73, 0x74, '\0', // schema 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x5f, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, '\0' // auth-method }}, {"4_1_22", {0x3a685, 1 << 24, 0x8, "root", "U3\xEFk!S\xED\x1\xDB\xBA\x87\xDD\xC6\xD0" "8pq\x18('", "", "", ""}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::secure_connection, { 0x85, 0xa6, 0x03, 0x00, // caps 0x00, 0x00, 0x00, 0x01, // max-packet-size 0x08, // collation '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', // filler 'r', 'o', 'o', 't', '\0', // username 0x14, 'U', '3', 0xef, 'k', '!', 'S', 0xed, 0x01, 0xdb, 0xba, 0x87, 0xdd, 0xc6, 0xd0, '8', 'p', 'q', 0x18, '(', '\'' // auth-method-data }}, {"3_23_58", {0x2405, 0, 0, "root", "H]^CSVY[", "", "", ""}, {}, {'\5', '$', 0, 0, 0, 'r', 'o', 'o', 't', 0, 'H', ']', '^', 'C', 'S', 'V', 'Y', '['}}, {"3_23_58_with_schema", {0x240d, 0, 0, "root", "H]^CSVY[", "foobar", "", ""}, classic_protocol::capabilities::connect_with_schema, { 0x0d, 0x24, // caps 0x00, 0x00, 0x00, // max-packet-size 'r', 'o', 'o', 't', '\0', // username 'H', ']', '^', 'C', 'S', 'V', 'Y', '[', '\0', // auth-method-data 'f', 'o', 'o', 'b', 'a', 'r' // schema }}, {"8_0_17_ssl", {0b0000'0001'1111'1111'1010'1110'0000'0101, 1 << 24, 0xff, "", "", "", {}, {}}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::ssl, { 0x05, 0xae, 0xff, 0x01, // caps 0x00, 0x00, 0x00, 0x01, // max-packet-size 0xff, // collation 0x00, 0x00, 0x00, 0x00, // 23 fillers 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00, 0x00, // 0x00, 0x00, 0x00 // }}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageClientGreetingTest, ::testing::ValuesIn(codec_message_client_greeting_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); // client::ChangeUser namespace classic_protocol { namespace message { namespace client { std::ostream &operator<<(std::ostream &os, const ChangeUser &v) { os << "ChangeUser: " << "\n"; os << " schema: " << v.schema() << "\n"; os << " username: " << v.username() << "\n"; os << " auth_method_name: " << v.auth_method_name() << "\n"; return os; } } // namespace client } // namespace message } // namespace classic_protocol using CodecMessageClientChangeUserTest = CodecTest<classic_protocol::message::client::ChangeUser>; TEST_P(CodecMessageClientChangeUserTest, encode) { test_encode(GetParam()); } TEST_P(CodecMessageClientChangeUserTest, decode) { test_decode(GetParam()); } const CodecParam<classic_protocol::message::client::ChangeUser> codec_message_client_changeuser_param [] = { {"5_6_6", {"root", S("\"Py\xA2\x12\xD4\xE8\x82\xE5\xB3\xF4\x1A\x97uk\xC8\xBE\xDB" "\x9F\x80"), "", 0x08, "mysql_native_password", "\x3" "_os" "\t" "debian6.0" "\f" "_client_name" "\b" "libmysql" "\x4" "_pid" "\x5" "22344" "\xF" "_client_version" "\b" "5.6.6-m9" "\t" "_platform" "\x6" "x86_64" "\x3" "foo" "\x3" "bar"}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::secure_connection | classic_protocol::capabilities::plugin_auth | classic_protocol::capabilities::connect_attributes, { 0x11, // cmd-byte 0x72, 0x6f, 0x6f, 0x74, 0x00, // username 0x14, 0x22, 0x50, 0x79, 0xa2, 0x12, 0xd4, 0xe8, 0x82, 0xe5, 0xb3, 0xf4, 0x1a, 0x97, 0x75, 0x6b, 0xc8, 0xbe, 0xdb, 0x9f, 0x80, // auth-method-data 0x00, // schema 0x08, 0x00, // collation 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x5f, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x00, // auth-method-name 0x61, 0x03, '_', 'o', 's', 0x09, 'd', 'e', 'b', 'i', 'a', 'n', '6', '.', '0', 0x0c, 0x5f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x08, 0x6c, 0x69, 0x62, 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x04, 0x5f, 0x70, 0x69, 0x64, 0x05, 0x32, 0x32, 0x33, 0x34, 0x34, 0x0f, 0x5f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x08, 0x35, 0x2e, 0x36, 0x2e, 0x36, 0x2d, 0x6d, 0x39, 0x09, 0x5f, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x06, 0x78, 0x38, 0x36, 0x5f, 0x36, 0x34, 0x03, 0x66, 0x6f, 0x6f, 0x03, 0x62, 0x61, 0x72 // connect-attributes }}, {"5_5_8", {"pam", "\xAB\t\xEE\xF6\xBC\xB1" "2>a\x14" "8e\xC0\x99\x1D\x95}u\xD4G", "test", 0x08, "mysql_native_password", ""}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::secure_connection | classic_protocol::capabilities::connect_with_schema | classic_protocol::capabilities::plugin_auth | classic_protocol::capabilities::connect_attributes, { 0x11, // cmd-byte 'p', 'a', 'm', '\0', // username 0x14, 0xab, 0x09, 0xee, 0xf6, 0xbc, 0xb1, 0x32, 0x3e, 0x61, 0x14, 0x38, 0x65, 0xc0, 0x99, 0x1d, 0x95, 0x7d, 0x75, 0xd4, 0x47, // auth-method-data 0x74, 0x65, 0x73, 0x74, '\0', // schema 0x08, 0x00, // collation 0x6d, 0x79, 0x73, 0x71, 0x6c, 0x5f, 0x6e, 0x61, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, '\0', // auth-method-name 0x00, // attributes }}, {"4_1_22", {"root", "U3\xEFk!S\xED\x1\xDB\xBA\x87\xDD\xC6\xD0" "8pq\x18('", "", 0x08, "", ""}, classic_protocol::capabilities::protocol_41 | classic_protocol::capabilities::secure_connection, { 0x11, // cmd-byte 'r', 'o', 'o', 't', '\0', // username 0x14, 'U', '3', 0xef, 'k', '!', 'S', 0xed, 0x01, 0xdb, 0xba, 0x87, 0xdd, 0xc6, 0xd0, '8', 'p', 'q', 0x18, '(', '\'', // auth-method-data '\0', // schema 0x08, 0x00, // collation }}, {"3_23_58", {"root", "H]^CSVY[", "", 0, "", ""}, {}, { 0x11, // cmd-byte 'r', 'o', 'o', 't', '\0', // username 'H', ']', '^', 'C', 'S', 'V', 'Y', '[', '\0', // auth-method-data '\0', // schema }}, {"3_23_58_with_schema", {"root", "H]^CSVY[", "foobar", 0, "", ""}, {}, // caps don't matter here { 0x11, // cmd-byte 'r', 'o', 'o', 't', '\0', // username 'H', ']', '^', 'C', 'S', 'V', 'Y', '[', '\0', // auth-method-data 'f', 'o', 'o', 'b', 'a', 'r', '\0', // schema }}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageClientChangeUserTest, ::testing::ValuesIn(codec_message_client_changeuser_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); using namespace std::string_literals; const CodecParam<classic_protocol::message::server::StmtRow> codec_message_server_stmtrow_param[] = { {"abc_def", {{classic_protocol::field_type::VarString}, {"foobar"s}}, {}, {0x00, 0x00, 0x06, 'f', 'o', 'o', 'b', 'a', 'r'}}, {"null", {{classic_protocol::field_type::VarString}, {stdx::make_unexpected()}}, {}, {0x00, 0x04}}, }; INSTANTIATE_TEST_SUITE_P( Spec, CodecMessageServerStmtRowTest, ::testing::ValuesIn(codec_message_server_stmtrow_param), [](auto const &test_param_info) { return test_param_info.param.test_name; }); TEST(ClassicProto, Decode_NulTermString_multiple_chunks) { std::list<std::vector<uint8_t>> read_storage{{'8', '0'}, {'1', 0x00, 'f'}}; std::list<net::const_buffer> read_bufs; for (auto const &b : read_storage) { read_bufs.push_back(net::buffer(b)); } const auto res = classic_protocol::Codec<classic_protocol::wire::NulTermString>::decode( read_bufs, {}); ASSERT_TRUE(res); // the \0 is consumed too, but not part of the output EXPECT_EQ(res->first, 3 + 1); EXPECT_EQ(res->second.value(), "801"); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
38.611012
90
0.541839
[ "vector" ]
1177888657e199377bffbe0ad412f96ef45b0dc2
2,498
cpp
C++
src/tool/main.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
22
2016-10-05T12:19:01.000Z
2022-01-23T09:14:41.000Z
src/tool/main.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
23
2017-05-08T15:02:39.000Z
2021-11-03T16:43:39.000Z
src/tool/main.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
12
2017-06-07T23:51:09.000Z
2022-01-04T13:06:21.000Z
#include "cli/cli.h" #include "cli/settingsProcessing.h" #include "preprocessing/preprocessing.h" #include "reachability/analysis.h" #include "typedefs.h" #include <hypro/datastructures/reachability/PreprocessingInformation.h> #include <hypro/datastructures/reachability/Settings.h> #include <hypro/parser/antlr4-flowstar/ParserWrapper.h> #include <hypro/types.h> #include <hypro/util/logging/Logger.h> #include <hypro/util/type_handling/plottype_enums.h> using namespace hydra; using namespace hypro; int main( int argc, char const* argv[] ) { // parse command line arguments START_BENCHMARK_OPERATION( "Parsing" ); auto options = hydra::handleCMDArguments( argc, argv ); // parse model file COUT( "Passed model file: " << options["model"].as<std::string>() << std::endl ); auto [automaton, reachSettings] = hypro::parseFlowstarFile<hydra::Number>( options["model"].as<std::string>() ); // perform preprocessing auto preprocessingInformation = hydra::preprocessing::preprocess( automaton, reachSettings ); // combine parsed settings and cli flags auto settings = hydra::processSettings( reachSettings, options ); EVALUATE_BENCHMARK_RESULT( "Parsing" ); // run reachability analysis START_BENCHMARK_OPERATION( "Verification" ); auto result = hydra::reachability::analyze( automaton, settings, preprocessingInformation ); EVALUATE_BENCHMARK_RESULT( "Verification" ); // call to plotting. START_BENCHMARK_OPERATION( "Plotting" ); auto const& plotSettings = settings.plotting(); auto& plt = Plotter<Number>::getInstance(); for ( std::size_t pic = 0; pic < plotSettings.plotDimensions.size(); ++pic ) { assert( plotSettings.plotDimensions[pic].size() == 2 ); std::cout << "Prepare plot " << "(" << pic + 1 << "/" << plotSettings.plotDimensions.size() << ") for dimensions " << plotSettings.plotDimensions[pic].front() << ", " << plotSettings.plotDimensions[pic].back() << "." << std::endl; plt.setFilename( plotSettings.plotFileNames[pic] ); std::size_t segmentCount = 0; for ( const auto& segment : result.plotData ) { std::cout << "\r" << segmentCount++ << "/" << result.plotData.size() << "..." << std::flush; plt.addObject( reduceToDimensions( segment.sets.projectOn( plotSettings.plotDimensions[pic] ).vertices(), plotSettings.plotDimensions[pic] ) ); } plt.plot2d( plotSettings.plottingFileType ); // writes to .plt file for pdf creation } EVALUATE_BENCHMARK_RESULT( "Plotting" ); PRINT_STATS(); return 0; }
37.848485
207
0.714972
[ "model" ]
11812570b4fd417ada922b44999cd7c4ce1fb577
8,857
cpp
C++
module_overlap/main.cpp
Frangou-Lab/module-overlap
c31f15e267c6ed00f1dd783d89518dc6ea60dc12
[ "Apache-2.0" ]
null
null
null
module_overlap/main.cpp
Frangou-Lab/module-overlap
c31f15e267c6ed00f1dd783d89518dc6ea60dc12
[ "Apache-2.0" ]
null
null
null
module_overlap/main.cpp
Frangou-Lab/module-overlap
c31f15e267c6ed00f1dd783d89518dc6ea60dc12
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Frangou Lab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Help.hpp" #include "OverlapCalculator.hpp" #include <libgene/file/TxtFile.hpp> #include <libgene/file/sequence/SequenceFile.hpp> #include <libgene/utils/Tokenizer.hpp> #include <libgene/utils/StringUtils.hpp> #include <libgene/def/Flags.hpp> #include <iostream> #include <vector> #include <set> #include <string> #include <utility> std::vector<std::string> GetModuleList(std::unique_ptr<SequenceFile>& input_file, char delimiter) { std::vector<std::string> module_list; SequenceRecord input_record; while (!(input_record = input_file->Read()).Empty()) { Tokenizer splitter(delimiter); splitter.SetText(input_record.seq); splitter.ReadNext(); module_list.push_back(splitter.GetNextToken()); } input_file->ResetFilePointer(); return module_list; } int main(int argc, const char *argv[]) { ArgumentsParser arguments(argc, argv); if (arguments.input_file_path.empty()) { fprintf(stderr, "No input file provided. Terminating\n"); return 1; } std::unique_ptr<SequenceFile> input_file; try { auto flags = std::make_unique<CommandLineFlags>(); flags->SetSetting(Flags::kInputFormat, "txt"); input_file = SequenceFile::FileWithName(arguments.input_file_path, flags, OpenMode::Read); } catch (std::runtime_error err) { if (!input_file) { fprintf(stderr, "File \'%s\' couldn't be opened. Either it doesn't\ exist, or you don't have permissions to read it.\n", arguments.input_file_path.c_str()); return 1; } } size_t dot_position = arguments.input_file_path.find('.'); std::string extension = utils::GetExtension(arguments.input_file_path); if (extension != "csvc" && extension != "tsvc") { // Force the output file to be interpreted as a 'columns-defined' file. extension += 'c'; } if (arguments.output_file_path.empty()) arguments.output_file_path = arguments.input_file_path.substr(0, dot_position); else { int64_t dot_position = arguments.output_file_path.rfind('.'); if (dot_position != std::string::npos) arguments.output_file_path.erase(dot_position); } std::string overlap_file = arguments.output_file_path + "-overlap" + "." + extension; std::string percentage_overlap_file = arguments.output_file_path + "-percentage_overlap" + "." + extension; std::string non_overlap_file = arguments.output_file_path + "-non_overlap" + "." + extension; char delimiter = ','; if (extension == "tsv" || extension == "tsvc") { delimiter = '\t'; } auto module_list = GetModuleList(input_file, delimiter); std::unique_ptr<SequenceFile> percentage_overlap_out_file; std::unique_ptr<SequenceFile> gene_overlap_out_file; std::unique_ptr<SequenceFile> non_overlap_out_file; auto CheckFileExistence = [&arguments](const std::string& file_path) { if (!arguments.override_output) { FILE *test_out_file = fopen(file_path.c_str(), "wx"); if (test_out_file == nullptr) { fprintf(stdout, "File \'%s\' already exists. Do you wish to override it? [Y/n] ", file_path.c_str()); char response; std::cin >> response; if (std::tolower(response) != 'y') { fprintf(stderr, "Skipping file \'%s\'\n", file_path.c_str()); exit(1); } } else fclose(test_out_file); } }; CheckFileExistence(percentage_overlap_file); CheckFileExistence(overlap_file); CheckFileExistence(non_overlap_file); auto OpenFileForWriting = [](const std::string& file_path) { auto flags = std::make_unique<CommandLineFlags>(); flags->SetSetting(Flags::kOutputFormat, "txt"); std::unique_ptr<SequenceFile> out_file; if (!(out_file = SequenceFile::FileWithName(file_path, flags, OpenMode::Write))) { fprintf(stderr, "Couldn't open the output file \'%s\'\n", file_path.c_str()); exit(1); } return out_file; }; percentage_overlap_out_file = OpenFileForWriting(percentage_overlap_file); gene_overlap_out_file = OpenFileForWriting(overlap_file); non_overlap_out_file = OpenFileForWriting(non_overlap_file); // Write header to output file. SequenceRecord header; header.seq = "Module"; for (int i = 0; i < module_list.size(); ++i) { header.seq += delimiter; header.seq += module_list[i]; } percentage_overlap_out_file->Write(header); gene_overlap_out_file->Write(header); non_overlap_out_file->Write(header); // A pair represents a module: module name and its gene set. std::vector<std::pair<std::string, std::set<std::string>>> modules; SequenceRecord input_record; while (!(input_record = input_file->Read()).Empty()) { Tokenizer splitter(delimiter); splitter.SetText(input_record.seq); splitter.ReadNext(); std::string module_name = splitter.GetNextToken(); std::set<std::string> gene_set; while (splitter.ReadNext()) { gene_set.insert(splitter.GetNextToken()); } modules.push_back({std::move(module_name), std::move(gene_set)}); } for (int i = 0; i < modules.size(); ++i) { SequenceRecord overlap_record; SequenceRecord overlap_percentage_record; SequenceRecord non_overlap_record; overlap_record.seq += modules[i].first; overlap_percentage_record.seq += modules[i].first; non_overlap_record.seq += modules[i].first; for (int j = 0; j < modules.size(); ++j) { overlap_record.seq += delimiter; overlap_percentage_record.seq += delimiter; non_overlap_record.seq += delimiter; if (i == j) continue; // Overlap reporting auto overlap = GetIntersection(modules[i].second, modules[j].second); overlap_record.seq += "\""; for (const std::string& gene : overlap) { if (gene.empty()) // I don't know why empty 'genes' sometimes end up in this vector. Fix later? continue; overlap_record.seq += gene; overlap_record.seq += delimiter; } // Erase the last delimiter if (overlap.size() > 1) overlap_record.seq.erase(overlap_record.seq.size() - 1); overlap_record.seq += "\""; // Overlap percentage reporting double percentage = GetIntersectionPercentage(modules[i].second.size(), modules[j].second.size(), overlap.size() - 1); overlap_percentage_record.seq += std::to_string(percentage); // Non-overlap reporting auto non_overlap = GetDifference(modules[i].second, modules[j].second); non_overlap_record.seq += "\""; for (const std::string& gene : non_overlap) { if (gene.empty()) { continue; } non_overlap_record.seq += gene; non_overlap_record.seq += delimiter; } // Erase the last delimiter if (non_overlap.size() > 1) non_overlap_record.seq.erase(non_overlap_record.seq.size() - 1); non_overlap_record.seq += "\""; } gene_overlap_out_file->Write(overlap_record); percentage_overlap_out_file->Write(overlap_percentage_record); non_overlap_out_file->Write(non_overlap_record); } fprintf(stdout, "The output files are located in \n\t%s\n\t%s\n\t%s\n", percentage_overlap_file.c_str(), overlap_file.c_str(), non_overlap_file.c_str()); return 0; }
37.689362
130
0.600316
[ "vector" ]
1182b3d7d9e5b48fe3827ac8f99c28130123b55d
15,198
cpp
C++
src/window.cpp
diegomacario/Animation-Experiments
42b4c1205607226fac306136d941d2387463519a
[ "MIT" ]
4
2020-12-13T16:55:50.000Z
2021-04-17T03:12:55.000Z
src/window.cpp
diegomacario/Animation-Experiments
42b4c1205607226fac306136d941d2387463519a
[ "MIT" ]
null
null
null
src/window.cpp
diegomacario/Animation-Experiments
42b4c1205607226fac306136d941d2387463519a
[ "MIT" ]
null
null
null
#include "imgui/imgui.h" #include "imgui/imgui_impl_glfw.h" #include "imgui/imgui_impl_opengl3.h" #include <iostream> #include "window.h" #ifdef __EMSCRIPTEN__ #include <emscripten/emscripten.h> EM_JS(int, getCanvasWidth, (), { return window.innerWidth; }); EM_JS(int, getCanvasHeight, (), { return window.innerHeight; }); EM_JS(float, getBrowserScrollWheelSensitivity, (), { if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) { return -1.0; } else { return -0.02; } }); #endif Window::Window(const std::string& title) : mWindow(nullptr) , mWidthOfWindowInPix(0) , mHeightOfWindowInPix(0) , mWidthOfFramebufferInPix(0) , mHeightOfFramebufferInPix(0) , mTitle(title) #ifndef __EMSCRIPTEN__ , mIsFullScreen(false) #endif , mKeys() , mProcessedKeys() , mMouseMoved(false) , mFirstCursorPosCallback(true) , mLastCursorXPos(0.0) , mLastCursorYPos(0.0) , mCursorXOffset(0.0) , mCursorYOffset(0.0) , mScrollWheelMoved(false) , mScrollYOffset(0.0) #ifdef __EMSCRIPTEN__ , mScrollWheelSensitivity(0.0f) #endif #ifndef __EMSCRIPTEN__ , mMultisampleFBO(0) , mMultisampleTexture(0) , mMultisampleRBO(0) , mNumOfSamples(1) #endif { } Window::~Window() { #ifndef __EMSCRIPTEN__ glDeleteFramebuffers(1, &mMultisampleFBO); glDeleteTextures(1, &mMultisampleTexture); glDeleteRenderbuffers(1, &mMultisampleRBO); #endif ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); if (mWindow) { glfwTerminate(); mWindow = nullptr; } } bool Window::initialize() { if (!glfwInit()) { std::cout << "Error - Window::initialize - Failed to initialize GLFW" << "\n"; return false; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); #ifdef __EMSCRIPTEN__ glfwWindowHint(GLFW_SAMPLES, 8); #endif #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif int width, height; #ifdef __EMSCRIPTEN__ width = getCanvasWidth(); height = getCanvasHeight(); mScrollWheelSensitivity = getBrowserScrollWheelSensitivity(); #else width = 1280; height = 720; #endif mWindow = glfwCreateWindow(width, height, mTitle.c_str(), nullptr, nullptr); if (!mWindow) { std::cout << "Error - Window::initialize - Failed to create the GLFW window" << "\n"; glfwTerminate(); mWindow = nullptr; return false; } glfwMakeContextCurrent(mWindow); enableCursor(true); #ifndef __EMSCRIPTEN__ if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Error - Window::initialize - Failed to load pointers to OpenGL functions using GLAD" << "\n"; glfwTerminate(); mWindow = nullptr; return false; } #endif glEnable(GL_CULL_FACE); glfwGetFramebufferSize(mWindow, &mWidthOfFramebufferInPix, &mHeightOfFramebufferInPix); #ifndef __EMSCRIPTEN__ if (!configureAntiAliasingSupport()) { std::cout << "Error - Window::initialize - Failed to configure anti aliasing support" << "\n"; glfwTerminate(); mWindow = nullptr; return false; } #endif setInputCallbacks(); updateBufferAndViewportSizes(mWidthOfFramebufferInPix, mHeightOfFramebufferInPix); // Initialize ImGui // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; io.IniFilename = nullptr; // Setup Dear ImGui style ImGui::StyleColorsDark(); // Setup Platform/Renderer bindings ImGui_ImplGlfw_InitForOpenGL(mWindow, true); #ifdef __EMSCRIPTEN__ ImGui_ImplOpenGL3_Init("#version 300 es"); #else ImGui_ImplOpenGL3_Init("#version 330 core"); #endif return true; } bool Window::shouldClose() const { int windowShouldClose = glfwWindowShouldClose(mWindow); if (windowShouldClose == 0) { return false; } else { return true; } } void Window::setShouldClose(bool shouldClose) { glfwSetWindowShouldClose(mWindow, shouldClose); } void Window::swapBuffers() { glfwSwapBuffers(mWindow); } void Window::pollEvents() { glfwPollEvents(); } unsigned int Window::getWidthOfWindowInPix() const { return mWidthOfWindowInPix; } unsigned int Window::getHeightOfWindowInPix() const { return mHeightOfWindowInPix; } unsigned int Window::getWidthOfFramebufferInPix() const { return mWidthOfFramebufferInPix; } unsigned int Window::getHeightOfFramebufferInPix() const { return mHeightOfFramebufferInPix; } #ifndef __EMSCRIPTEN__ bool Window::isFullScreen() const { return mIsFullScreen; } void Window::setFullScreen(bool fullScreen) { if (fullScreen) { const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); mWidthOfWindowInPix = mode->width; mHeightOfWindowInPix = mode->height; glfwSetWindowMonitor(mWindow, glfwGetPrimaryMonitor(), 0, 0, mWidthOfWindowInPix, mHeightOfWindowInPix, GLFW_DONT_CARE); } else { mWidthOfWindowInPix = 1280; mHeightOfWindowInPix = 720; glfwSetWindowMonitor(mWindow, NULL, 20, 50, mWidthOfWindowInPix, mHeightOfWindowInPix, GLFW_DONT_CARE); } mIsFullScreen = fullScreen; } #endif bool Window::keyIsPressed(int key) const { return mKeys.test(key); } bool Window::keyHasBeenProcessed(int key) const { return mProcessedKeys.test(key); } void Window::setKeyAsProcessed(int key) { mProcessedKeys.set(key); } bool Window::mouseMoved() const { return mMouseMoved; } void Window::resetMouseMoved() { mMouseMoved = false; } void Window::resetFirstMove() { mFirstCursorPosCallback = true; } float Window::getCursorXOffset() const { return mCursorXOffset; } float Window::getCursorYOffset() const { return mCursorYOffset; } void Window::enableCursor(bool enable) { glfwSetInputMode(mWindow, GLFW_CURSOR, enable ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED); } bool Window::isMouseButtonPressed(int button) { if (glfwGetMouseButton(mWindow, button) == GLFW_PRESS) { return true; } return false; } bool Window::scrollWheelMoved() const { return mScrollWheelMoved; } void Window::resetScrollWheelMoved() { mScrollWheelMoved = false; } float Window::getScrollYOffset() const { return mScrollYOffset; } void Window::setInputCallbacks() { glfwSetWindowUserPointer(mWindow, this); auto framebufferSizeCallback = [](GLFWwindow* window, int width, int height) { static_cast<Window*>(glfwGetWindowUserPointer(window))->framebufferSizeCallback(window, width, height); }; auto keyCallback = [](GLFWwindow* window, int key, int scancode, int action, int mods) { static_cast<Window*>(glfwGetWindowUserPointer(window))->keyCallback(window, key, scancode, action, mods); }; auto cursorPosCallback = [](GLFWwindow* window, double xPos, double yPos) { static_cast<Window*>(glfwGetWindowUserPointer(window))->cursorPosCallback(window, xPos, yPos); }; auto scrollCallback = [](GLFWwindow* window, double xOffset, double yOffset) { static_cast<Window*>(glfwGetWindowUserPointer(window))->scrollCallback(window, xOffset, yOffset); }; glfwSetFramebufferSizeCallback(mWindow, framebufferSizeCallback); glfwSetKeyCallback(mWindow, keyCallback); glfwSetCursorPosCallback(mWindow, cursorPosCallback); glfwSetScrollCallback(mWindow, scrollCallback); } void Window::framebufferSizeCallback(GLFWwindow* window, int width, int height) { updateBufferAndViewportSizes(width, height); } void Window::keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key != -1) { if (action == GLFW_PRESS) { mKeys.set(key); } else if (action == GLFW_RELEASE) { mKeys.reset(key); } mProcessedKeys.reset(key); } } void Window::cursorPosCallback(GLFWwindow* window, double xPos, double yPos) { if (mFirstCursorPosCallback) { mLastCursorXPos = xPos; mLastCursorYPos = yPos; mFirstCursorPosCallback = false; } // TODO: Ideally this function would tell the camera to update its position based on the offsets. // I'm going to make the camera ask the window if it should update its position. Is there a better way to do this? mCursorXOffset = static_cast<float>(xPos - mLastCursorXPos); mCursorYOffset = static_cast<float>(mLastCursorYPos - yPos); // Reversed since the Y-coordinates of the mouse go from the bottom to the top mLastCursorXPos = xPos; mLastCursorYPos = yPos; mMouseMoved = true; } void Window::scrollCallback(GLFWwindow* window, double xOffset, double yOffset) { // TODO: Ideally this function would tell the camera to update its FOVY based on the Y offset. // I'm going to make the camera ask the window if it should update its FOVY. Is there a better way to do this? mScrollYOffset = static_cast<float>(yOffset); #ifdef __EMSCRIPTEN__ mScrollYOffset *= mScrollWheelSensitivity; #endif mScrollWheelMoved = true; } #ifndef __EMSCRIPTEN__ bool Window::configureAntiAliasingSupport() { if (!createMultisampleFramebuffer()) { return false; } return true; } bool Window::createMultisampleFramebuffer() { // Configure a framebuffer object to store raw multisample renders glGenFramebuffers(1, &mMultisampleFBO); glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFBO); // Create a multisample texture and use it as a color attachment glGenTextures(1, &mMultisampleTexture); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mMultisampleTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, mNumOfSamples, GL_RGB, mWidthOfFramebufferInPix, mHeightOfFramebufferInPix, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, mMultisampleTexture, 0); // Create a multisample renderbuffer object and use it as a depth attachment glGenRenderbuffers(1, &mMultisampleRBO); glBindRenderbuffer(GL_RENDERBUFFER, mMultisampleRBO); glRenderbufferStorageMultisample(GL_RENDERBUFFER, mNumOfSamples, GL_DEPTH_COMPONENT, mWidthOfFramebufferInPix, mHeightOfFramebufferInPix); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mMultisampleRBO); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cout << "Error - Window::configureAntiAliasingSupport - Multisample framebuffer is not complete" << "\n"; return false; } glBindFramebuffer(GL_FRAMEBUFFER, 0); return true; } void Window::clearAndBindMultisampleFramebuffer() { glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFBO); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Window::generateAntiAliasedImage() { glBindFramebuffer(GL_READ_FRAMEBUFFER, mMultisampleFBO); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); glBlitFramebuffer(0, 0, mWidthOfFramebufferInPix, mHeightOfFramebufferInPix, 0, 0, mWidthOfFramebufferInPix, mHeightOfFramebufferInPix, GL_COLOR_BUFFER_BIT, GL_NEAREST); // TODO: Should this be GL_LINEAR? } void Window::resizeFramebuffers() { glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mMultisampleTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, mNumOfSamples, GL_RGB, mWidthOfFramebufferInPix, mHeightOfFramebufferInPix, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); glBindRenderbuffer(GL_RENDERBUFFER, mMultisampleRBO); glRenderbufferStorageMultisample(GL_RENDERBUFFER, mNumOfSamples, GL_DEPTH_COMPONENT, mWidthOfFramebufferInPix, mHeightOfFramebufferInPix); glBindRenderbuffer(GL_RENDERBUFFER, 0); } void Window::setNumberOfSamples(unsigned int numOfSamples) { mNumOfSamples = numOfSamples; glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, mMultisampleTexture); glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, mNumOfSamples, GL_RGB, mWidthOfFramebufferInPix, mHeightOfFramebufferInPix, GL_TRUE); glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0); glBindRenderbuffer(GL_RENDERBUFFER, mMultisampleRBO); glRenderbufferStorageMultisample(GL_RENDERBUFFER, mNumOfSamples, GL_DEPTH_COMPONENT, mWidthOfFramebufferInPix, mHeightOfFramebufferInPix); glBindRenderbuffer(GL_RENDERBUFFER, 0); } #endif #ifdef __EMSCRIPTEN__ void Window::updateWindowDimensions(int width, int height) { mWidthOfWindowInPix = width; mHeightOfWindowInPix = height; glfwSetWindowSize(mWindow, width, height); } #endif void Window::updateBufferAndViewportSizes(int widthOfFramebufferInPix, int heightOfFramebufferInPix) { mWidthOfFramebufferInPix = widthOfFramebufferInPix; mHeightOfFramebufferInPix = heightOfFramebufferInPix; glfwGetWindowSize(mWindow, &mWidthOfWindowInPix, &mHeightOfWindowInPix); #ifndef __EMSCRIPTEN__ resizeFramebuffers(); // Clear the multisample framebuffer glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFBO); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindFramebuffer(GL_FRAMEBUFFER, 0); #endif float aspectRatioOfScene = 1280.0f / 720.0f; int lowerLeftCornerOfViewportXInPix, lowerLeftCornerOfViewportYInPix, widthOfViewportInPix, heightOfViewportInPix; // Let's say we want to use the width of the window for the viewport // What height would we need to keep the aspect ratio of the scene? float requiredHeight = mWidthOfFramebufferInPix * (1.0f / aspectRatioOfScene); // If the required height is greater than the height of the window, then we use the height of the window for the viewport if (requiredHeight > mHeightOfFramebufferInPix) { // What width would we need to keep the aspect ratio of the scene? float requiredWidth = mHeightOfFramebufferInPix * aspectRatioOfScene; if (requiredWidth > mWidthOfFramebufferInPix) { std::cout << "Error - Window::updateBufferAndViewportSizes - Couldn't calculate dimensions that preserve the aspect ratio of the scene" << '\n'; } else { float widthOfTheTwoVerticalBars = mWidthOfFramebufferInPix - requiredWidth; lowerLeftCornerOfViewportXInPix = static_cast<int>(widthOfTheTwoVerticalBars / 2.0f); lowerLeftCornerOfViewportYInPix = 0; widthOfViewportInPix = static_cast<int>(requiredWidth); heightOfViewportInPix = mHeightOfFramebufferInPix; } } else { float heightOfTheTwoHorizontalBars = mHeightOfFramebufferInPix - requiredHeight; lowerLeftCornerOfViewportXInPix = 0; lowerLeftCornerOfViewportYInPix = static_cast<int>(heightOfTheTwoHorizontalBars / 2.0f); widthOfViewportInPix = mWidthOfFramebufferInPix; heightOfViewportInPix = static_cast<int>(requiredHeight); } glScissor(lowerLeftCornerOfViewportXInPix, lowerLeftCornerOfViewportYInPix, widthOfViewportInPix, heightOfViewportInPix); glViewport(lowerLeftCornerOfViewportXInPix, lowerLeftCornerOfViewportYInPix, widthOfViewportInPix, heightOfViewportInPix); }
27.383784
207
0.74194
[ "object" ]
11843492000198998baf5b342c06dfff8a9f8efc
16,163
cpp
C++
informedkd/src/Sampler/MonteCarloSampler.cpp
dqyi11/InformedSampling-ompl
94dc30e0f9d3df304c0ba6e36acfa8c71e2fc823
[ "BSD-3-Clause" ]
null
null
null
informedkd/src/Sampler/MonteCarloSampler.cpp
dqyi11/InformedSampling-ompl
94dc30e0f9d3df304c0ba6e36acfa8c71e2fc823
[ "BSD-3-Clause" ]
null
null
null
informedkd/src/Sampler/MonteCarloSampler.cpp
dqyi11/InformedSampling-ompl
94dc30e0f9d3df304c0ba6e36acfa8c71e2fc823
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, University of Toronto * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the University of Toronto nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Authors: Cole Gulino, Daqing Yi, Oren Salzman, and Rohan Thakker */ #include "Sampler/MonteCarloSampler.h" // Standard library functions #include <math.h> /* exp, tanh, log */ #include <limits> #include <algorithm> #include "Dimt/Params.h" namespace { void print_out_states3(const Eigen::VectorXd &state) { std::cout << "[ "; for (uint i = 0; i < state.size(); i++) { std::cout << state[i] << " "; } std::cout << " ]" << std::endl; } // Verbose constant const bool VERBOSE = true; /// /// Sigmoid function /// /// @param x Input /// @param a Controls shape of sigmoid /// @param c Controls shape of sigmoid /// @return Output of sigmoid function /// inline double sigmoid(const double &x, const double &a = 200, const double &c = 0) { return 1 / (1 + exp(-a * (x - c))); } } // namespace namespace ompl { namespace base { bool LangevinSampler::sampleInLevelSet(Eigen::VectorXd& sample) { return false; } /// /// Function to determine if any of the joint limits are violated /// @param sample Sample to check /// @return Boolean that is true if any are in violation /// bool MonteCarloSampler::anyDimensionInViolation(const Eigen::VectorXd &sample) const { const std::tuple<Eigen::VectorXd, Eigen::VectorXd> limits = getStateLimits(); const auto min_vals = std::get<0>(limits); const auto max_vals = std::get<1>(limits); for (uint i = 0; i < sample.size(); i++) { if (sample[i] > max_vals[i] or sample[i] < min_vals[i]) { return true; } } return false; } /// /// Get the energy of the state from the cost function /// /// @param curr_state Current state to get the energy for /// @return Energy of the function /// double MonteCarloSampler::getEnergy(const Eigen::VectorXd &curr_state) const { const double cost = getCost(curr_state); // double E_grad = tanh(cost); const double E_grad = log(1 + log(1 + cost)); const double E_informed = 100 * sigmoid(cost - getLevelSet()); double E_region = 0; std::tuple<Eigen::VectorXd, Eigen::VectorXd> limits = getStateLimits(); for (int i = 0; i < curr_state.size(); i++) { E_region += 100 * sigmoid(std::get<0>(limits)(i) - curr_state(i)); // Lower Limits E_region += 100 * sigmoid(curr_state(i) - std::get<1>(limits)(i)); // Higher Limits } return E_region + E_grad + E_informed; //return E_grad + E_informed; } double MonteCarloSampler::getEnergy(double cost) const { const double E_grad = log(1 + log(1 + cost)); const double E_informed = 100 * sigmoid(cost - getLevelSet()); return E_grad + E_informed; } double MonteCarloSampler::getEnergyGradient(double cost) const { static const double costStep = 0.0001; double energy1 = getEnergy(cost); double energy2 = getEnergy(cost + costStep); return (energy2 - energy1) / costStep; } Eigen::VectorXd MonteCarloSampler::getGradient(const Eigen::VectorXd &curr_state) { /* Eigen::VectorXd grad = MyInformedSampler::getGradient(curr_state); double cost = getCost(curr_state); double energyGrad = getEnergyGradient(cost); return energyGrad * grad; */ return MyInformedSampler::getGradient(curr_state); } /// /// Get the probability of the state from the cost function /// /// @param energy Energy of the state /// @return Probability of the state /// double MonteCarloSampler::getProb(const double energy) const { return exp(-energy); } // // Get the probability of the state from the cost function // // @param curr_state Current state to get the energy for // @return Probability of the state // double MonteCarloSampler::getProb(const Eigen::VectorXd &curr_state) const { return exp(-MonteCarloSampler::getEnergy(curr_state)); } // // Surf down the cost function to get to the levelset // // @param alpha Learning rate // @return Path to the level set // Eigen::VectorXd MonteCarloSampler::gradDescent(const double alpha) { // If the number of steps reaches some threshold, start over const double thresh = 20; Eigen::VectorXd start = MonteCarloSampler::getRandomSample(); double cost = getCost(start); double prev_cost = cost; int steps = 0; while (cost > getLevelSet()) { Eigen::VectorXd grad = getGradient(start); start = start - alpha * grad; cost = getCost(start); if (VERBOSE) std::cout << cost << std::endl; steps++; // if(steps > thresh || cost > prev_cost) if (steps > thresh || cost > 10 * getLevelSet() || grad.norm() < 0.001) { if (VERBOSE) std::cout << "Restarting!" << std::endl; // recursing gives segfaults so just change the start position instead // return grad_descent(alpha); start = MonteCarloSampler::getRandomSample(); steps = 0; } prev_cost = cost; } return start; } // // Get a normal random vector for the momentum // // @return A vector of momentum sampled from a random distribution // Eigen::VectorXd MonteCarloSampler::sampleNormal(const double mean, const double sigma) { int size = getSpaceDimension(); Eigen::VectorXd sample(size); for (int i = 0; i < size; i++) { sample(i) = normRndGnr_.sample(mean, sigma); } return sample; } // // HMCSampler // bool HMCSampler::sampleInLevelSet(Eigen::VectorXd& sample) { // last sample Eigen::VectorXd q = Eigen::VectorXd(getStartState().size()); double sampleCost = std::numeric_limits<double>::infinity(); q << lastSample_; const int maxTrialNum = 10; int currentTrialNum = 0; std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); std::chrono::high_resolution_clock::time_point t2 = t1; std::chrono::high_resolution_clock::duration timeElapsed; double timeElapsedDouble = 0.0; bool inLevelSet = true; do { if (timeElapsedDouble > timelimit_) { inLevelSet = false; break; } currentTrialNum++; if( currentTrialNum > maxTrialNum ) { currentTrialNum = 0; currentStep_ = -1; } if (getCurrentStep() < 0) { Eigen::VectorXd start = getRandomSample(); q = findSolutionInLevelSet(start, getLevelSet()); } // Make a half step for momentum at the beginning Eigen::VectorXd grad = getGradient(q); //if (VERBOSE) // std::cout << "Got the gradient" << std::endl; /* // Ensure that the gradient isn't two large while (grad.maxCoeff() > 1e2) { if (VERBOSE) std::cout << "WARNING: Gradient too high" << std::endl; Eigen::VectorXd start = getRandomSample(); q = findSolutionInLevelSet(start, getLevelSet()); grad = getGradient(q); } */ updateCurrentStep(); // Sample the momentum and set up the past and current state and momentum Eigen::VectorXd q_last = q; Eigen::VectorXd p = MonteCarloSampler::sampleNormal(0, getSigma()); Eigen::VectorXd p_last = p; //if (VERBOSE) // std::cout << "Sampled the momentum" << std::endl; p = p - getEpsilon() * grad / 2; // Alternate Full steps for q and p for (int i = 0; i < getL(); i++) { grad = getGradient(q); q = q + getEpsilon() * p; if (i != getL()) p = p - getEpsilon() * grad; } //if (VERBOSE) // std::cout << "Integrated Along momentum" << std::endl; // Make a half step for momentum at the end grad = getGradient(q); p = p - getEpsilon() * grad / 2; // Negate the momentum at the end of the traj to make proposal // symmetric p = -p; // Evaluate potential and kinetic energies at start and end of traj double U_last = getEnergy(q_last); double K_last = p_last.norm() / 2; double U_proposed = getEnergy(q); double K_proposed = p_last.norm() / 2; //if (VERBOSE) // std::cout << "Got energies" << std::endl; // Accept or reject the state at the end of trajectory double alpha = std::min(1.0, std::exp(U_last - U_proposed + K_last - K_proposed)); if (uniRndGnr_.sample() > alpha) { q = q_last; } t2 = std::chrono::high_resolution_clock::now(); timeElapsed = t2-t1; timeElapsedDouble = std::chrono::duration_cast<std::chrono::seconds>(timeElapsed).count(); } while(!isInLevelSet(q, sampleCost) ); if(inLevelSet) { numAcceptedSamples_++; } else { numRejectedSamples_++; } sample << q, sampleCost; lastSample_ << q; if (getCurrentStep() >= getSteps()) { updateCurrentStep(-1); } //std::cout << "ACCEPTED " << numAcceptedSamples_ << " REJECTED " << numRejectedSamples_ << std::endl; return inLevelSet; } bool MCMCSampler::sampleInLevelSet(Eigen::VectorXd& sample) { // last sample Eigen::VectorXd q = Eigen::VectorXd(getStartState().size()); double sampleCost = std::numeric_limits<double>::infinity(); q << lastSample_; const int maxTrialNum = 10; int currentTrialNum = 0; std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); std::chrono::high_resolution_clock::time_point t2 = t1; std::chrono::high_resolution_clock::duration timeElapsed; double timeElapsedDouble = 0.0; bool inLevelSet = true; do { if (timeElapsedDouble > timelimit_) { inLevelSet = false; break; } currentTrialNum++; if( currentTrialNum > maxTrialNum ) { currentTrialNum = 0; currentStep_ = -1; } if (getCurrentStep() < 0) { Eigen::VectorXd start = getRandomSample(); q = findSolutionInLevelSet(start, getLevelSet()); } // Make a half step for momentum at the beginning Eigen::VectorXd grad = getGradient(q); //if (VERBOSE) // std::cout << "Got the gradient" << std::endl; /* // Ensure that the gradient isn't two large while (grad.maxCoeff() > 1e2) { if (VERBOSE) std::cout << "WARNING: Gradient too high" << std::endl; Eigen::VectorXd start = getRandomSample(); q = findSolutionInLevelSet(start, getLevelSet()); grad = getGradient(q); }*/ updateCurrentStep(); Eigen::VectorXd q_proposed = q + sampleNormal(0, getSigma()); double prob_proposed = getProb(q_proposed); double prob_before = getProb(q); // if(prob_proposed / prob_before >= rand_uni() and // // !any_dimensions_in_violation(q_proposed)) if (prob_proposed / prob_before >= uniRndGnr_.sample()) { q = q_proposed; } t2 = std::chrono::high_resolution_clock::now(); timeElapsed = t2-t1; timeElapsedDouble = std::chrono::duration_cast<std::chrono::seconds>(timeElapsed).count(); } while(!isInLevelSet(q, sampleCost) ); if(inLevelSet) { numAcceptedSamples_++; } else { numRejectedSamples_++; } sample << q, sampleCost; lastSample_ << q; if (getCurrentStep() >= getSteps()) { updateCurrentStep(-1); } return inLevelSet; } } // base } // ompl
34.389362
115
0.511044
[ "shape", "vector" ]
118a8a8e0670ba478464e98c9118015a9a23e186
17,175
cpp
C++
openstudiocore/src/model/SiteWaterMainsTemperature.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/model/SiteWaterMainsTemperature.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
openstudiocore/src/model/SiteWaterMainsTemperature.cpp
bobzabcik/OpenStudio
858321dc0ad8d572de15858d2ae487b029a8d847
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2013, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <model/SiteWaterMainsTemperature.hpp> #include <model/SiteWaterMainsTemperature_Impl.hpp> #include <model/Schedule.hpp> #include <model/Schedule_Impl.hpp> #include <model/Model.hpp> #include <model/Model_Impl.hpp> #include <model/Site.hpp> #include <model/Site_Impl.hpp> #include <utilities/idf/ValidityReport.hpp> #include <utilities/idd/IddKey.hpp> #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_Site_WaterMainsTemperature_FieldEnums.hxx> #include <utilities/core/Assert.hpp> namespace openstudio { namespace model { namespace detail { SiteWaterMainsTemperature_Impl::SiteWaterMainsTemperature_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ModelObject_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == SiteWaterMainsTemperature::iddObjectType()); } SiteWaterMainsTemperature_Impl::SiteWaterMainsTemperature_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ModelObject_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == SiteWaterMainsTemperature::iddObjectType()); } SiteWaterMainsTemperature_Impl::SiteWaterMainsTemperature_Impl(const SiteWaterMainsTemperature_Impl& other, Model_Impl* model, bool keepHandle) : ModelObject_Impl(other,model,keepHandle) {} boost::optional<ParentObject> SiteWaterMainsTemperature_Impl::parent() const { boost::optional<Site> result = this->model().getOptionalUniqueModelObject<Site>(); return boost::optional<ParentObject>(result); } const std::vector<std::string>& SiteWaterMainsTemperature_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType SiteWaterMainsTemperature_Impl::iddObjectType() const { return SiteWaterMainsTemperature::iddObjectType(); } std::vector<ScheduleTypeKey> SiteWaterMainsTemperature_Impl::getScheduleTypeKeys(const Schedule& schedule) const { std::vector<ScheduleTypeKey> result; UnsignedVector fieldIndices = getSourceIndices(schedule.handle()); UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end()); if (std::find(b,e,OS_Site_WaterMainsTemperatureFields::TemperatureScheduleName) != e) { result.push_back(ScheduleTypeKey("SiteWaterMainsTemperature","Temperature")); } return result; } std::string SiteWaterMainsTemperature_Impl::calculationMethod() const { boost::optional<std::string> value = getString(OS_Site_WaterMainsTemperatureFields::CalculationMethod,true); OS_ASSERT(value); return value.get(); } boost::optional<Schedule> SiteWaterMainsTemperature_Impl::temperatureSchedule() const { return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_Site_WaterMainsTemperatureFields::TemperatureScheduleName); } boost::optional<double> SiteWaterMainsTemperature_Impl::annualAverageOutdoorAirTemperature() const { return getDouble(OS_Site_WaterMainsTemperatureFields::AnnualAverageOutdoorAirTemperature,true); } OSOptionalQuantity SiteWaterMainsTemperature_Impl::getAnnualAverageOutdoorAirTemperature(bool returnIP) const { OptionalDouble value = annualAverageOutdoorAirTemperature(); return getQuantityFromDouble(OS_Site_WaterMainsTemperatureFields::AnnualAverageOutdoorAirTemperature, value, returnIP); } boost::optional<double> SiteWaterMainsTemperature_Impl::maximumDifferenceInMonthlyAverageOutdoorAirTemperatures() const { return getDouble(OS_Site_WaterMainsTemperatureFields::MaximumDifferenceInMonthlyAverageOutdoorAirTemperatures,true); } OSOptionalQuantity SiteWaterMainsTemperature_Impl::getMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(bool returnIP) const { OptionalDouble value = maximumDifferenceInMonthlyAverageOutdoorAirTemperatures(); return getQuantityFromDouble(OS_Site_WaterMainsTemperatureFields::MaximumDifferenceInMonthlyAverageOutdoorAirTemperatures, value, returnIP); } bool SiteWaterMainsTemperature_Impl::setCalculationMethod(std::string calculationMethod) { bool result = setString(OS_Site_WaterMainsTemperatureFields::CalculationMethod, calculationMethod); return result; } bool SiteWaterMainsTemperature_Impl::setTemperatureSchedule(Schedule& schedule) { bool result = setSchedule(OS_Site_WaterMainsTemperatureFields::TemperatureScheduleName, "SiteWaterMainsTemperature", "Temperature", schedule); if (result) { result = setCalculationMethod("Schedule"); OS_ASSERT(result); } return result; } void SiteWaterMainsTemperature_Impl::resetTemperatureSchedule() { bool result = setString(OS_Site_WaterMainsTemperatureFields::TemperatureScheduleName, ""); OS_ASSERT(result); } void SiteWaterMainsTemperature_Impl::setAnnualAverageOutdoorAirTemperature(boost::optional<double> annualAverageOutdoorAirTemperature) { bool result(false); if (annualAverageOutdoorAirTemperature) { result = setDouble(OS_Site_WaterMainsTemperatureFields::AnnualAverageOutdoorAirTemperature, annualAverageOutdoorAirTemperature.get()); if (result) { result = setCalculationMethod("Correlation"); OS_ASSERT(result); } } else { resetAnnualAverageOutdoorAirTemperature(); result = true; } OS_ASSERT(result); } bool SiteWaterMainsTemperature_Impl::setAnnualAverageOutdoorAirTemperature(const OSOptionalQuantity& annualAverageOutdoorAirTemperature) { bool result(false); OptionalDouble value; if (annualAverageOutdoorAirTemperature.isSet()) { value = getDoubleFromQuantity(OS_Site_WaterMainsTemperatureFields::AnnualAverageOutdoorAirTemperature,annualAverageOutdoorAirTemperature.get()); if (value) { setAnnualAverageOutdoorAirTemperature(value); result = true; } } else { setAnnualAverageOutdoorAirTemperature(value); result = true; } return result; } void SiteWaterMainsTemperature_Impl::resetAnnualAverageOutdoorAirTemperature() { bool result = setString(OS_Site_WaterMainsTemperatureFields::AnnualAverageOutdoorAirTemperature, ""); OS_ASSERT(result); } bool SiteWaterMainsTemperature_Impl::setMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(boost::optional<double> maximumDifferenceInMonthlyAverageOutdoorAirTemperatures) { bool result(false); if (maximumDifferenceInMonthlyAverageOutdoorAirTemperatures) { result = setDouble(OS_Site_WaterMainsTemperatureFields::MaximumDifferenceInMonthlyAverageOutdoorAirTemperatures, maximumDifferenceInMonthlyAverageOutdoorAirTemperatures.get()); if (result) { result = setCalculationMethod("Correlation"); OS_ASSERT(result); } } else { resetMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(); result = true; } return result; } bool SiteWaterMainsTemperature_Impl::setMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(const OSOptionalQuantity& maximumDifferenceInMonthlyAverageOutdoorAirTemperatures) { bool result(false); OptionalDouble value; if (maximumDifferenceInMonthlyAverageOutdoorAirTemperatures.isSet()) { value = getDoubleFromQuantity(OS_Site_WaterMainsTemperatureFields::MaximumDifferenceInMonthlyAverageOutdoorAirTemperatures,maximumDifferenceInMonthlyAverageOutdoorAirTemperatures.get()); if (value) { result = setMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(value); } } else { result = setMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(value); } return result; } void SiteWaterMainsTemperature_Impl::resetMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures() { bool result = setString(OS_Site_WaterMainsTemperatureFields::MaximumDifferenceInMonthlyAverageOutdoorAirTemperatures, ""); OS_ASSERT(result); } void SiteWaterMainsTemperature_Impl::populateValidityReport(ValidityReport& report,bool checkNames) const { // Inherit lower-level errors ModelObject_Impl::populateValidityReport(report,checkNames); if (report.level() > StrictnessLevel::Draft) { boost::optional<IddKey> key = iddObject().getField(OS_Site_WaterMainsTemperatureFields::CalculationMethod).get().getKey(calculationMethod()); OS_ASSERT(key); if (key->name() == "Schedule") { if (!temperatureSchedule()) { report.insertError(DataError(OS_Site_WaterMainsTemperatureFields::TemperatureScheduleName, getObject<ModelObject>(), DataErrorType::NullAndRequired)); } } else { // Correlation if (!annualAverageOutdoorAirTemperature()) { report.insertError(DataError(OS_Site_WaterMainsTemperatureFields::AnnualAverageOutdoorAirTemperature, getObject<ModelObject>(), DataErrorType::NullAndRequired)); } if (!maximumDifferenceInMonthlyAverageOutdoorAirTemperatures()) { report.insertError(DataError(OS_Site_WaterMainsTemperatureFields::MaximumDifferenceInMonthlyAverageOutdoorAirTemperatures, getObject<ModelObject>(), DataErrorType::NullAndRequired)); } } } } std::vector<std::string> SiteWaterMainsTemperature_Impl::calculationMethodValues() const { return SiteWaterMainsTemperature::calculationMethodValues(); } openstudio::OSOptionalQuantity SiteWaterMainsTemperature_Impl::annualAverageOutdoorAirTemperature_SI() const { return getAnnualAverageOutdoorAirTemperature(false); } openstudio::OSOptionalQuantity SiteWaterMainsTemperature_Impl::annualAverageOutdoorAirTemperature_IP() const { return getAnnualAverageOutdoorAirTemperature(true); } openstudio::OSOptionalQuantity SiteWaterMainsTemperature_Impl::maximumDifferenceInMonthlyAverageOutdoorAirTemperatures_SI() const { return getMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(false); } openstudio::OSOptionalQuantity SiteWaterMainsTemperature_Impl::maximumDifferenceInMonthlyAverageOutdoorAirTemperatures_IP() const { return getMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(true); } boost::optional<ModelObject> SiteWaterMainsTemperature_Impl::temperatureScheduleAsModelObject() const { OptionalModelObject result; OptionalSchedule intermediate = temperatureSchedule(); if (intermediate) { result = *intermediate; } return result; } bool SiteWaterMainsTemperature_Impl::setTemperatureScheduleAsModelObject(const boost::optional<ModelObject>& modelObject) { if (modelObject) { OptionalSchedule intermediate = modelObject->optionalCast<Schedule>(); if (intermediate) { Schedule schedule(*intermediate); return setTemperatureSchedule(schedule); } else { return false; } } else { resetTemperatureSchedule(); } return true; } } // detail SiteWaterMainsTemperature::SiteWaterMainsTemperature(const Model& model) : ModelObject(SiteWaterMainsTemperature::iddObjectType(),model) { OS_ASSERT(getImpl<detail::SiteWaterMainsTemperature_Impl>()); bool ok = setCalculationMethod("Schedule"); OS_ASSERT(ok); } IddObjectType SiteWaterMainsTemperature::iddObjectType() { IddObjectType result(IddObjectType::OS_Site_WaterMainsTemperature); return result; } std::vector<std::string> SiteWaterMainsTemperature::calculationMethodValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Site_WaterMainsTemperatureFields::CalculationMethod); } std::vector<std::string> SiteWaterMainsTemperature::validCalculationMethodValues() { return SiteWaterMainsTemperature::calculationMethodValues(); } std::string SiteWaterMainsTemperature::calculationMethod() const { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->calculationMethod(); } boost::optional<Schedule> SiteWaterMainsTemperature::temperatureSchedule() const { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->temperatureSchedule(); } boost::optional<double> SiteWaterMainsTemperature::annualAverageOutdoorAirTemperature() const { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->annualAverageOutdoorAirTemperature(); } OSOptionalQuantity SiteWaterMainsTemperature::getAnnualAverageOutdoorAirTemperature(bool returnIP) const { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->getAnnualAverageOutdoorAirTemperature(returnIP); } boost::optional<double> SiteWaterMainsTemperature::maximumDifferenceInMonthlyAverageOutdoorAirTemperatures() const { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->maximumDifferenceInMonthlyAverageOutdoorAirTemperatures(); } OSOptionalQuantity SiteWaterMainsTemperature::getMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(bool returnIP) const { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->getMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(returnIP); } bool SiteWaterMainsTemperature::setCalculationMethod(std::string calculationMethod) { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->setCalculationMethod(calculationMethod); } bool SiteWaterMainsTemperature::setTemperatureSchedule(Schedule& schedule) { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->setTemperatureSchedule(schedule); } void SiteWaterMainsTemperature::resetTemperatureSchedule() { getImpl<detail::SiteWaterMainsTemperature_Impl>()->resetTemperatureSchedule(); } void SiteWaterMainsTemperature::setAnnualAverageOutdoorAirTemperature(double annualAverageOutdoorAirTemperature) { getImpl<detail::SiteWaterMainsTemperature_Impl>()->setAnnualAverageOutdoorAirTemperature(annualAverageOutdoorAirTemperature); } bool SiteWaterMainsTemperature::setAnnualAverageOutdoorAirTemperature(const Quantity& annualAverageOutdoorAirTemperature) { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->setAnnualAverageOutdoorAirTemperature(annualAverageOutdoorAirTemperature); } void SiteWaterMainsTemperature::resetAnnualAverageOutdoorAirTemperature() { getImpl<detail::SiteWaterMainsTemperature_Impl>()->resetAnnualAverageOutdoorAirTemperature(); } bool SiteWaterMainsTemperature::setMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(double maximumDifferenceInMonthlyAverageOutdoorAirTemperatures) { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->setMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(maximumDifferenceInMonthlyAverageOutdoorAirTemperatures); } bool SiteWaterMainsTemperature::setMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(const Quantity& maximumDifferenceInMonthlyAverageOutdoorAirTemperatures) { return getImpl<detail::SiteWaterMainsTemperature_Impl>()->setMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(maximumDifferenceInMonthlyAverageOutdoorAirTemperatures); } void SiteWaterMainsTemperature::resetMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures() { getImpl<detail::SiteWaterMainsTemperature_Impl>()->resetMaximumDifferenceInMonthlyAverageOutdoorAirTemperatures(); } /// @cond SiteWaterMainsTemperature::SiteWaterMainsTemperature(boost::shared_ptr<detail::SiteWaterMainsTemperature_Impl> impl) : ModelObject(impl) {} /// @endcond } // model } // openstudio
44.494819
193
0.746841
[ "vector", "model" ]
1196c84abf3c8c7101a35a53b08f5de58c6cea6d
1,040
cpp
C++
back tracking/132 Palindrome Partitioning II.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
back tracking/132 Palindrome Partitioning II.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
back tracking/132 Palindrome Partitioning II.cpp
CoderQuinnYoung/leetcode
6ea15c68124b16824bab9ed2e0e5a40c72eb3db1
[ "BSD-3-Clause" ]
null
null
null
// // 132 Palindrome Partitioning II.cpp // Leetcode // // Created by Quinn on 2020/11/1. // Copyright © 2020 Quinn. All rights reserved. // #include <string> #include <vector> using namespace std; class Solution { public: int minCut(string s) { int n = s.length(); s = ' ' + s; vector<vector<bool>> g(n + 1, vector<bool>(n + 1)); vector<int> f(n + 1, 1e9); for (int j = 1; j <= n; j++) { for (int i = 1; i <= j; i++) { if (i == j) { g[i][j] = true; } else if (s[i] == s[j]) { if(i + 1 > j - 1 || g[i + 1][j - 1]) g[i][j] = true; } } } f[0] = 0; for (int j = 1; j <= n; j++) { for (int i = 1; i <= j; i ++) { if (g[i][j]) { f[j] = min(f[j], f[i - 1] + 1); } } } return f[n] - 1; } };
23.111111
59
0.330769
[ "vector" ]
119a8a9e63b32c07a2a2dfffbddb0ec12407a5b0
7,023
cpp
C++
src/morphology.cpp
barbarabenato/libFL_finalproject
d671a69781722efd46477b0a9ea4b9d611a7bfad
[ "MIT" ]
null
null
null
src/morphology.cpp
barbarabenato/libFL_finalproject
d671a69781722efd46477b0a9ea4b9d611a7bfad
[ "MIT" ]
null
null
null
src/morphology.cpp
barbarabenato/libFL_finalproject
d671a69781722efd46477b0a9ea4b9d611a7bfad
[ "MIT" ]
5
2017-03-18T00:32:00.000Z
2019-03-24T05:58:43.000Z
// // Created by deangeli on 3/15/17. // #include "morphology.h" Image *dilate(Image *image, AdjacencyRelation *AdjRel){ Image* dilatedImage = createImage(image->nx,image->ny,1); dilatedImage->scalingFactor = image->scalingFactor; #pragma omp parallel for for (int p=0; p < image->numberPixels; p++) { dilatedImage->channel[0][p] = image->channel[0][p]; int pixelX = (p%image->nx); int pixelY = (p/image->ny); for (int i=0; i < AdjRel->n; i++) { int adjacentX = pixelX + AdjRel->dx[i]; int adjacentY = pixelY + AdjRel->dy[i]; if(isValidPixelCoordinate(image,adjacentX,adjacentY)){ int adjacentIndex = (adjacentY*image->nx)+adjacentX; if(image->channel[0][adjacentIndex] > dilatedImage->channel[0][p]){ dilatedImage->channel[0][p] = image->channel[0][adjacentIndex]; } } } } return(dilatedImage); } Image *erode(Image *image, AdjacencyRelation *AdjRel){ Image* erodedImage = createImage(image->nx,image->ny,1); erodedImage->scalingFactor = image->scalingFactor; #pragma omp parallel for for (int p=0; p < image->numberPixels; p++) { //iftVoxel u = iftGetVoxelCoord(img,p); erodedImage->channel[0][p] = image->channel[0][p]; int pixelX = (p%image->nx); int pixelY = (p/image->nx); for (int i=0; i < AdjRel->n; i++) { int adjacentX = pixelX + AdjRel->dx[i]; int adjacentY = pixelY + AdjRel->dy[i]; if(isValidPixelCoordinate(image,adjacentX,adjacentY)){ int adjacentIndex = (adjacentY*image->nx)+adjacentX; if(image->channel[0][adjacentIndex] < erodedImage->channel[0][p]){ erodedImage->channel[0][p] = image->channel[0][adjacentIndex]; } } } } return erodedImage; } Image *open(Image *image, AdjacencyRelation *AdjRel){ Image* outputImage = NULL; Image* erodedImage = NULL; erodedImage = erode(image,AdjRel); outputImage = dilate(erodedImage,AdjRel); destroyImage(&erodedImage); return outputImage; } Image *close(Image *image, AdjacencyRelation *AdjRel){ Image* outputImage = NULL; Image* dilatedImage = NULL; dilatedImage = dilate(image,AdjRel); outputImage = erode(dilatedImage,AdjRel); destroyImage(&dilatedImage); return outputImage; } Image *topHat(Image *image,AdjacencyRelation *AdjRel){ Image* outputImage = NULL; Image* openedImage = open(image,AdjRel); outputImage = imageSubtraction(image,openedImage,false); destroyImage(&openedImage); return outputImage; } Image *bottomHat(Image *image,AdjacencyRelation *AdjRel){ Image* outputImage = NULL; Image* closedImage = close(image,AdjRel); outputImage = imageSubtraction(closedImage,image,false); destroyImage(&closedImage); return outputImage; } Image *morphologicGradient(Image *image,AdjacencyRelation *AdjRel){ Image* outputImage = NULL; Image* dilatedImage = dilate(image,AdjRel); Image* erodedImage = erode(image,AdjRel); outputImage = imageSubtraction(dilatedImage,erodedImage,false); destroyImage(&dilatedImage); destroyImage(&erodedImage); return outputImage; } Image* transformAdjacencyRelation2Image(AdjacencyRelation *adjRel,int nx,int ny,int centerX,int centerY){ Image* image = createImage(nx,ny,1); image->scalingFactor = 255; int coordinateX = 0; int coordinateY = 0; int index; for (int i = 0; i < adjRel->n; ++i) { coordinateX = adjRel->dx[i] + centerX; coordinateY = adjRel->dy[i] + centerY; index = (coordinateY*nx) + coordinateX; if(isValidPixelCoordinate(image,coordinateX,coordinateY)){ image->channel[0][index] = image->scalingFactor; } } return image; } AdjacencyRelation* transformImage2AdjacencyRelation(Image *image, float thresholding,int centerX,int centerY){ int counter = 0; for (int p = 0; p < image->numberPixels; ++p) { if(image->channel[0][p] > thresholding){ counter++; } } AdjacencyRelation *adjacencyRelation = createAdjacencyRelation(counter); int k = 0; for (int p = 0; p < image->numberPixels; ++p) { if(image->channel[0][p] > thresholding) { int dx = (p % image->nx); int dy = (p / image->nx); dx -= centerX; dy -= centerY; if (abs(dx) > adjacencyRelation->maxDx) { adjacencyRelation->maxDx = abs(dx); } if (abs(dy) > adjacencyRelation->maxDy) { adjacencyRelation->maxDy = abs(dy); } int k_copy; k_copy = k; k++; adjacencyRelation->dx[k_copy] = dx; adjacencyRelation->dy[k_copy] = dy; } } return adjacencyRelation; } AdjacencyRelation* dilate(AdjacencyRelation *adjacencyRelation1, AdjacencyRelation *adjacencyRelation2){ int nx = ((adjacencyRelation1->maxDx*2 + 1) + (adjacencyRelation2->maxDx*2 + 1)) - 1; int ny = ((adjacencyRelation1->maxDy*2 + 1) + (adjacencyRelation2->maxDy*2 + 1)) -1; int centerX = nx/2; int centerY = ny/2; Image* imageStructElement = transformAdjacencyRelation2Image(adjacencyRelation2,nx,ny,centerX,centerY); Image* imageDilated = dilate(imageStructElement,adjacencyRelation1); AdjacencyRelation* adjacencyRelationDilated = transformImage2AdjacencyRelation(imageDilated, imageDilated->scalingFactor/2,centerX,centerY); destroyImage(&imageStructElement); destroyImage(&imageDilated); return adjacencyRelationDilated; } FeatureVector *getMorphologicalPdf(Image *image, AdjacencyRelation* adjacencyRelation, int k_times){ FeatureVector *featureVector = NULL; if(k_times < 0){ return featureVector; } featureVector = createFeatureVector(k_times+1); featureVector->features[0] = 0; float v0 = sumUpAllPixelsValues(image,true); v0 += 0.00000001;//somo isso para evitar divisao por zero float vk = 0; float feature = 0; Image* openedImage = NULL; AdjacencyRelation* currentStructorElement = copyAdjcencyRelation(adjacencyRelation); AdjacencyRelation* auxStructorElement = NULL; for (int i = 1; i <= k_times; ++i) { openedImage = open(image,currentStructorElement); vk = sumUpAllPixelsValues(openedImage,true); feature = 1 - (vk/v0); featureVector->features[i] = feature; auxStructorElement = dilate(adjacencyRelation,currentStructorElement); destroyAdjacencyRelation(&currentStructorElement); currentStructorElement = auxStructorElement; destroyImage(&openedImage); } destroyAdjacencyRelation(&currentStructorElement); //destroyAdjacencyRelation(&auxStructorElement); //FeatureVector *vector = createFeatureVector(featureVector,k); return featureVector; }
32.971831
144
0.643884
[ "vector" ]
119f39d671c00d36fc34f4081142bbfb24b19858
1,442
cpp
C++
src/nexus/common/sleep_profile.cpp
dengwxn/nexuslb
4b19116f09fad414bd40538de0105eb728fc4b51
[ "BSD-3-Clause" ]
6
2021-07-01T23:03:28.000Z
2022-02-07T03:24:42.000Z
src/nexus/common/sleep_profile.cpp
dengwxn/nexuslb
4b19116f09fad414bd40538de0105eb728fc4b51
[ "BSD-3-Clause" ]
null
null
null
src/nexus/common/sleep_profile.cpp
dengwxn/nexuslb
4b19116f09fad414bd40538de0105eb728fc4b51
[ "BSD-3-Clause" ]
2
2021-04-06T11:09:35.000Z
2021-04-13T06:59:34.000Z
#include "nexus/common/sleep_profile.h" #include <glog/logging.h> #include <cstring> #include <optional> #include <vector> #include "nexus/common/util.h" namespace nexus { SleepProfile::SleepProfile(int slope_us, int intercept_us, int preprocess_us, int postprocess_us) : slope_us_(slope_us), intercept_us_(intercept_us), preprocess_us_(preprocess_us), postprocess_us_(postprocess_us) {} std::optional<SleepProfile> SleepProfile::Parse(const std::string& framework) { if (MatchPrefix(framework)) { auto param_str = framework.substr(strlen(kPrefix)); std::vector<std::string> params; SplitString(param_str, ',', &params); std::vector<int> p; for (const auto& param : params) { try { int num = std::stoi(param); p.push_back(num); } catch (...) { LOG(ERROR) << "Bad parameter for SleepProfile. Cannot parse int from string \"" << param << "\"."; } } if (p.size() != 4) { LOG(ERROR) << "Bad parameter for SleepModel. Got " << p.size() << " parameters. Expected format: " << kPrefix << "slope_us,intercept_us,preprocess_us,postprocess_us"; } return SleepProfile(p[0], p[1], p[2], p[3]); } return std::nullopt; } bool SleepProfile::MatchPrefix(const std::string& framework) { return framework.rfind(kPrefix, 0) == 0; } } // namespace nexus
28.27451
80
0.615811
[ "vector" ]
11a0050c948eb24ecc0194d2429317ffe56063c4
1,237
cpp
C++
1679B.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
1679B.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
1679B.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <string> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #include <set> #define fi first #define se second #define pb push_back #define mp make_pair #define pii pair<int,int> #define pdd pair<double,double> #define LL long long #define PI 2*acos(0.0) #define EPS 1e-9 #define INF 1e9 using namespace std; int N, Q, a[200020]; int flashNum, lastFlashTurn; int lastFlashed[200020]; LL total; int main() { scanf("%d %d", &N, &Q); total = 0LL; for(int i = 1; i <= N; i++) { scanf("%d", &a[i]); total += (LL) a[i]; } lastFlashTurn = -1; memset(lastFlashed, 0, sizeof(lastFlashed)); for(int q = 1; q <= Q; q++) { int type; scanf("%d", &type); int i, x; switch(type) { case 1: scanf("%d %d", &i, &x); if(lastFlashed[i] < lastFlashTurn) { total -= (LL) flashNum; lastFlashed[i] = lastFlashTurn; } else total -= (LL) a[i]; total += (LL) x; a[i] = x; break; case 2: scanf("%d", &x); lastFlashTurn = q; total = (LL) x * (LL) N; flashNum = x; break; } printf("%I64d\n", total); } return 0; }
16.493333
45
0.594988
[ "vector" ]
11a732d572449d6bb04bfb7d0cab223c1235f403
4,791
hpp
C++
src/System.hpp
georgbrown/wrapd-2d
1f7d0659582297f97212c83c67dca81948ed70f7
[ "MIT" ]
4
2021-07-27T23:11:25.000Z
2022-02-17T06:18:26.000Z
src/System.hpp
georgbrown/wrapd-2d
1f7d0659582297f97212c83c67dca81948ed70f7
[ "MIT" ]
null
null
null
src/System.hpp
georgbrown/wrapd-2d
1f7d0659582297f97212c83c67dca81948ed70f7
[ "MIT" ]
3
2021-07-28T02:36:37.000Z
2022-02-08T06:27:26.000Z
// Copyright (c) 2021 George E. Brown and Rahul Narain // // WRAPD uses the MIT License (https://opensource.org/licenses/MIT) // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is furnished // to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // By George E. Brown (https://www-users.cse.umn.edu/~brow2327/) #ifndef SRC_SYSTEM_HPP_ #define SRC_SYSTEM_HPP_ #include <vector> #include <memory> #include <unordered_map> #include "TriElements.hpp" #include "Settings.hpp" namespace wrapd { class ConstraintSet { public: std::unordered_map<int, math::Vec2> m_pins; // index -> location }; class System { public: inline int num_all_verts() const { return m_X.rows(); } // Access and modifiy positions inline const math::MatX2 X() const { return m_X; } inline const math::MatX2& X_init() const { return m_X_init; } inline void X(const math::MatX2& val) { m_X = val; } template<int DIM> inline void X(int idx, math::Mat<DIM, 2> seg) { m_X.segment<DIM, 2>(idx, 0) = seg; } template<int DIM> inline const math::Mat<DIM, 2> X(int idx) { return m_X.segment<DIM, 2>(idx, 0); } // Adds nodes to the Solver. // Returns the current total number of nodes after insert. inline int add_nodes( const math::MatX2 &X, const math::MatX2 &X_init) { const int n_verts = X.rows(); const int prev_n = m_X.rows(); const int size = prev_n + n_verts; m_X.conservativeResize(size, 2); m_X_init.conservativeResize(size, 2); for (int i = 0; i < n_verts; ++i) { int idx = prev_n + i; m_X.row(idx) = X.row(i); m_X_init.row(idx) = X_init.row(i); } return (prev_n + n_verts); } System(const Settings &settings); void set_pins( const std::vector<int> &inds, const std::vector<math::Vec2> &points); std::shared_ptr<ConstraintSet> constraint_set(); int num_tri_elements() const { if (m_tri_elements.get() == nullptr) { return 0; } else { return m_tri_elements->num_elements(); } } bool possibly_update_weights(double gamma); void midupdate_WtW(const math::MatX2 &curr_x); void midupdate_WtW(); int get_WtW(math::Triplets &triplets); std::vector<double> get_distortion() const; math::MatX2 get_b(); void get_A(math::Triplets &triplets); void update_A(math::SpMat &A); double penalty_energy(bool lagged_s, bool lagged_u) const; int inversion_count() const; void unaware_local_update(bool update_candidate_weights); double rotaware_local_update(bool update_candidate_weights); std::shared_ptr<TriElements>& tri_elements() { return m_tri_elements; } void update_fix_cache(const math::MatX2& x_fix); void update_defo_cache(const math::MatX2& x_free, bool compute_polar_data); void initialize_dual_vars(const math::MatX2& X); void advance_dual_vars(); double potential_energy() const; // as a function of x double potential_gradnorm() const; // as a function of x double dual_objective() const; // as a function of either Z or S void set_initial_deformation() { m_X = m_X_init; } double global_obj_value(const math::MatX2 &x_free); double global_obj_grad(const math::MatX2 &x_free, math::MatX2 &grad); void global_obj_grad(math::MatX2 &grad); protected: const Settings m_settings; std::shared_ptr<TriElements> m_tri_elements; std::shared_ptr<ConstraintSet> m_constraints; private: math::MatX2 m_X; // node positions math::MatX2 m_X_init; // node positions, initial std::vector<math::Vec3i> m_tri_free_inds; }; } // namespace wrapd #endif // SRC_SYSTEM_HPP_
29.94375
86
0.670424
[ "vector" ]
11aab8d6155bf27aaf24bc0b1ac9f9775a19f1ff
8,380
cc
C++
third_party/webrtc/src/chromium/src/ipc/mojo/ipc_message_pipe_reader.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
8
2016-02-08T11:59:31.000Z
2020-05-31T15:19:54.000Z
third_party/webrtc/src/chromium/src/ipc/mojo/ipc_message_pipe_reader.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
1
2021-05-05T11:11:31.000Z
2021-05-05T11:11:31.000Z
third_party/webrtc/src/chromium/src/ipc/mojo/ipc_message_pipe_reader.cc
bopopescu/webrtc-streaming-node
727a441204344ff596401b0253caac372b714d91
[ "MIT" ]
7
2016-02-09T09:28:14.000Z
2020-07-25T19:03:36.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ipc/mojo/ipc_message_pipe_reader.h" #include <stdint.h> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/location.h" #include "base/logging.h" #include "base/single_thread_task_runner.h" #include "base/thread_task_runner_handle.h" #include "ipc/mojo/async_handle_waiter.h" #include "ipc/mojo/ipc_channel_mojo.h" namespace IPC { namespace internal { MessagePipeReader::MessagePipeReader(mojo::ScopedMessagePipeHandle handle, MessagePipeReader::Delegate* delegate) : pipe_(handle.Pass()), handle_copy_(pipe_.get().value()), delegate_(delegate), async_waiter_( new AsyncHandleWaiter(base::Bind(&MessagePipeReader::PipeIsReady, base::Unretained(this)))), pending_send_error_(MOJO_RESULT_OK) { } MessagePipeReader::~MessagePipeReader() { DCHECK(thread_checker_.CalledOnValidThread()); // The pipe should be closed before deletion. CHECK(!IsValid()); } void MessagePipeReader::Close() { DCHECK(thread_checker_.CalledOnValidThread()); async_waiter_.reset(); pipe_.reset(); OnPipeClosed(); } void MessagePipeReader::CloseWithError(MojoResult error) { DCHECK(thread_checker_.CalledOnValidThread()); OnPipeError(error); Close(); } void MessagePipeReader::CloseWithErrorIfPending() { DCHECK(thread_checker_.CalledOnValidThread()); MojoResult pending_error = base::subtle::NoBarrier_Load(&pending_send_error_); if (pending_error == MOJO_RESULT_OK) return; // NOTE: This races with Send(), and therefore the value of // pending_send_error() can change. CloseWithError(pending_error); return; } void MessagePipeReader::CloseWithErrorLater(MojoResult error) { DCHECK_NE(error, MOJO_RESULT_OK); // NOTE: No assumptions about the value of |pending_send_error_| or whether or // not the error has been signaled can be made. If Send() is called // immediately before Close() and errors, it's possible for the error to not // be signaled. base::subtle::NoBarrier_Store(&pending_send_error_, error); } bool MessagePipeReader::Send(scoped_ptr<Message> message) { TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"), "MessagePipeReader::Send", message->flags(), TRACE_EVENT_FLAG_FLOW_OUT); std::vector<MojoHandle> handles; MojoResult result = MOJO_RESULT_OK; result = ChannelMojo::ReadFromMessageAttachmentSet(message.get(), &handles); if (result == MOJO_RESULT_OK) { result = MojoWriteMessage(handle(), message->data(), static_cast<uint32_t>(message->size()), handles.empty() ? nullptr : &handles[0], static_cast<uint32_t>(handles.size()), MOJO_WRITE_MESSAGE_FLAG_NONE); } if (result != MOJO_RESULT_OK) { std::for_each(handles.begin(), handles.end(), &MojoClose); // We cannot call CloseWithError() here as Send() is protected by // ChannelMojo's lock and CloseWithError() could re-enter ChannelMojo. We // cannot call CloseWithError() also because Send() can be called from // non-UI thread while OnPipeError() expects to be called on IO thread. CloseWithErrorLater(result); return false; } return true; } void MessagePipeReader::OnMessageReceived() { Message message(data_buffer().empty() ? "" : &data_buffer()[0], static_cast<uint32_t>(data_buffer().size())); std::vector<MojoHandle> handle_buffer; TakeHandleBuffer(&handle_buffer); MojoResult write_result = ChannelMojo::WriteToMessageAttachmentSet(handle_buffer, &message); if (write_result != MOJO_RESULT_OK) { CloseWithError(write_result); return; } TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"), "MessagePipeReader::OnMessageReceived", message.flags(), TRACE_EVENT_FLAG_FLOW_IN); delegate_->OnMessageReceived(message); } void MessagePipeReader::OnPipeClosed() { DCHECK(thread_checker_.CalledOnValidThread()); if (!delegate_) return; delegate_->OnPipeClosed(this); delegate_ = nullptr; } void MessagePipeReader::OnPipeError(MojoResult error) { DCHECK(thread_checker_.CalledOnValidThread()); if (!delegate_) return; delegate_->OnPipeError(this); } MojoResult MessagePipeReader::ReadMessageBytes() { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(handle_buffer_.empty()); uint32_t num_bytes = static_cast<uint32_t>(data_buffer_.size()); uint32_t num_handles = 0; MojoResult result = MojoReadMessage(pipe_.get().value(), num_bytes ? &data_buffer_[0] : nullptr, &num_bytes, nullptr, &num_handles, MOJO_READ_MESSAGE_FLAG_NONE); data_buffer_.resize(num_bytes); handle_buffer_.resize(num_handles); if (result == MOJO_RESULT_RESOURCE_EXHAUSTED) { // MOJO_RESULT_RESOURCE_EXHAUSTED was asking the caller that // it needs more bufer. So we re-read it with resized buffers. result = MojoReadMessage(pipe_.get().value(), num_bytes ? &data_buffer_[0] : nullptr, &num_bytes, num_handles ? &handle_buffer_[0] : nullptr, &num_handles, MOJO_READ_MESSAGE_FLAG_NONE); } DCHECK(0 == num_bytes || data_buffer_.size() == num_bytes); DCHECK(0 == num_handles || handle_buffer_.size() == num_handles); return result; } void MessagePipeReader::ReadAvailableMessages() { DCHECK(thread_checker_.CalledOnValidThread()); while (pipe_.is_valid()) { MojoResult read_result = ReadMessageBytes(); if (read_result == MOJO_RESULT_SHOULD_WAIT) break; if (read_result != MOJO_RESULT_OK) { DLOG(WARNING) << "Pipe got error from ReadMessage(). Closing: " << read_result; OnPipeError(read_result); Close(); break; } OnMessageReceived(); } } void MessagePipeReader::ReadMessagesThenWait() { DCHECK(thread_checker_.CalledOnValidThread()); while (true) { ReadAvailableMessages(); if (!pipe_.is_valid()) break; // |Wait()| is safe to call only after all messages are read. // If can fail with |MOJO_RESULT_ALREADY_EXISTS| otherwise. // Also, we don't use MOJO_HANDLE_SIGNAL_WRITABLE here, expecting buffer in // MessagePipe. MojoResult result = async_waiter_->Wait(pipe_.get().value(), MOJO_HANDLE_SIGNAL_READABLE); // If the result is |MOJO_RESULT_ALREADY_EXISTS|, there could be messages // that have been arrived after the last |ReadAvailableMessages()|. // We have to consume then and retry in that case. if (result != MOJO_RESULT_ALREADY_EXISTS) { if (result != MOJO_RESULT_OK) { LOG(ERROR) << "Failed to wait on the pipe. Result is " << result; OnPipeError(result); Close(); } break; } } } void MessagePipeReader::PipeIsReady(MojoResult wait_result) { DCHECK(thread_checker_.CalledOnValidThread()); CloseWithErrorIfPending(); if (!IsValid()) { // There was a pending error and it closed the pipe. // We cannot do the work anymore. return; } if (wait_result != MOJO_RESULT_OK) { if (wait_result != MOJO_RESULT_ABORTED) { // FAILED_PRECONDITION happens every time the peer is dead so // it isn't worth polluting the log message. LOG_IF(WARNING, wait_result != MOJO_RESULT_FAILED_PRECONDITION) << "Pipe got error from the waiter. Closing: " << wait_result; OnPipeError(wait_result); } Close(); return; } ReadMessagesThenWait(); } void MessagePipeReader::DelayedDeleter::operator()( MessagePipeReader* ptr) const { ptr->Close(); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(&DeleteNow, ptr)); } } // namespace internal } // namespace IPC
34.065041
80
0.656563
[ "vector" ]
11ac28a2d64a48a4615079b78426526cf6c30d66
956
cpp
C++
C++/demnsPoly/main.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
1
2020-07-04T12:45:50.000Z
2020-07-04T12:45:50.000Z
C++/demnsPoly/main.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
1
2020-08-08T02:23:46.000Z
2020-08-08T02:47:56.000Z
C++/demnsPoly/main.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
null
null
null
//program to demonstrate polymorphism base class shape and derived classes rectangle and circle #include<iostream> using namespace std; class Shape { public: virtual float area()=0; virtual float perimeter()=0; }; class Rectangle:public Shape { private: float length; float breadth; public: Rectangle(int l=1,int b=1){ length=1; breadth=b; } float area(){ return length*breadth; } float perimeter(){ return 2*(length+breadth); } }; class Circle:public Shape { private: float radius; public: Circle(float r) { radius=r; } float area() { return 3.1425*radius*radius; } float perimeter(){ return 2*3.1425*radius; } }; int main() { Shape *s=new Rectangle(10,5); cout<<"Area of Rectangle "<<s->area()<<endl; cout<<"Perimeter of Rectangle "<<s->perimeter()<<endl; s=new Circle(10); cout<<"Area of Circle "<<s->area()<<endl; cout<<"Perimeter of Circle "<<s->perimeter()<<endl; }
16.77193
95
0.648536
[ "shape" ]
11aca101b3849b979bced2be5d0008be7e9b22eb
19,149
cpp
C++
Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp
CStudios15/o3de
9dc85000a3ec1a6c6633d718f5c455ab11a46818
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp
CStudios15/o3de
9dc85000a3ec1a6c6633d718f5c455ab11a46818
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp
CStudios15/o3de
9dc85000a3ec1a6c6633d718f5c455ab11a46818
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Multiplayer/IMultiplayer.h> #include <Multiplayer/IMultiplayerTools.h> #include <Multiplayer/INetworkSpawnableLibrary.h> #include <Multiplayer/MultiplayerConstants.h> #include <MultiplayerSystemComponent.h> #include <PythonEditorEventsBus.h> #include <Editor/MultiplayerEditorSystemComponent.h> #include <Source/AutoGen/Multiplayer.AutoPackets.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/Console/IConsole.h> #include <AzCore/Console/ILogger.h> #include <AzCore/Interface/Interface.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Utils/Utils.h> #include <AzNetworking/Framework/INetworking.h> #include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h> #include <Atom/RPI.Public/RPISystemInterface.h> namespace Multiplayer { using namespace AzNetworking; AZ_CVAR(bool, editorsv_enabled, false, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Whether Editor launching a local server to connect to is supported"); AZ_CVAR(bool, editorsv_launch, true, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Whether Editor should launch a server when the server address is localhost"); AZ_CVAR(AZ::CVarFixedString, editorsv_process, "", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The server executable that should be run. Empty to use the current project's ServerLauncher"); AZ_CVAR(AZ::CVarFixedString, editorsv_serveraddr, AZ::CVarFixedString(LocalHost), nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The address of the server to connect to"); AZ_CVAR(AZ::CVarFixedString, editorsv_rhi_override, "", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Override the default rendering hardware interface (rhi) when launching the Editor server. For example, you may be running an Editor using 'dx12', but want to launch a headless server using 'null'. If empty the server will launch using the same rhi as the Editor."); AZ_CVAR_EXTERNED(uint16_t, editorsv_port); ////////////////////////////////////////////////////////////////////////// void PyEnterGameMode() { editorsv_enabled = true; editorsv_launch = true; AzToolsFramework::EditorLayerPythonRequestBus::Broadcast(&AzToolsFramework::EditorLayerPythonRequestBus::Events::EnterGameMode); } bool PyIsInGameMode() { // If the network entity manager is tracking at least 1 entity then the editor has connected and the autonomous player exists and is being replicated. if (const INetworkEntityManager* networkEntityManager = AZ::Interface<INetworkEntityManager>::Get()) { return networkEntityManager->GetEntityCount() > 0; } AZ_Warning("MultiplayerEditorSystemComponent", false, "PyIsInGameMode returning false; NetworkEntityManager has not been created yet.") return false; } void PythonEditorFuncs::Reflect(AZ::ReflectContext* context) { if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context)) { // This will create static python methods in the 'azlmbr.multiplayer' module // Note: The methods will be prefixed with the class name, PythonEditorFuncs // Example Hydra Python: azlmbr.multiplayer.PythonEditorFuncs_enter_game_mode() behaviorContext->Class<PythonEditorFuncs>() ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) ->Attribute(AZ::Script::Attributes::Module, "multiplayer") ->Method("enter_game_mode", PyEnterGameMode, nullptr, "Enters the editor game mode and launches/connects to the server launcher.") ->Method("is_in_game_mode", PyIsInGameMode, nullptr, "Queries if it's in the game mode and the server has finished connecting and the default network player has spawned.") ; } } void MultiplayerEditorSystemComponent::Reflect(AZ::ReflectContext* context) { if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<MultiplayerEditorSystemComponent, AZ::Component>() ->Version(1); } // Reflect Python Editor Functions if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context)) { // This will add the MultiplayerPythonEditorBus into the 'azlmbr.multiplayer' module behaviorContext->EBus<MultiplayerEditorLayerPythonRequestBus>("MultiplayerPythonEditorBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) ->Attribute(AZ::Script::Attributes::Module, "multiplayer") ->Event("EnterGameMode", &MultiplayerEditorLayerPythonRequestBus::Events::EnterGameMode) ->Event("IsInGameMode", &MultiplayerEditorLayerPythonRequestBus::Events::IsInGameMode) ; } } void MultiplayerEditorSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { required.push_back(AZ_CRC_CE("MultiplayerService")); } void MultiplayerEditorSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC_CE("MultiplayerEditorService")); } void MultiplayerEditorSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC_CE("MultiplayerEditorService")); } MultiplayerEditorSystemComponent::MultiplayerEditorSystemComponent() : m_serverAcceptanceReceivedHandler([this](){OnServerAcceptanceReceived();}) { ; } void MultiplayerEditorSystemComponent::Activate() { AzFramework::GameEntityContextEventBus::Handler::BusConnect(); AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); MultiplayerEditorServerRequestBus::Handler::BusConnect(); AZ::Interface<IMultiplayer>::Get()->AddServerAcceptanceReceivedHandler(m_serverAcceptanceReceivedHandler); } void MultiplayerEditorSystemComponent::Deactivate() { AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); AzFramework::GameEntityContextEventBus::Handler::BusDisconnect(); MultiplayerEditorServerRequestBus::Handler::BusDisconnect(); } void MultiplayerEditorSystemComponent::NotifyRegisterViews() { AZ_Assert(m_editor == nullptr, "NotifyRegisterViews occurred twice!"); m_editor = nullptr; AzToolsFramework::EditorRequests::Bus::BroadcastResult(m_editor, &AzToolsFramework::EditorRequests::GetEditor); m_editor->RegisterNotifyListener(this); } void MultiplayerEditorSystemComponent::OnEditorNotifyEvent(EEditorNotifyEvent event) { switch (event) { case eNotify_OnQuit: AZ_Warning("Multiplayer Editor", m_editor != nullptr, "Multiplayer Editor received On Quit without an Editor pointer."); if (m_editor) { m_editor->UnregisterNotifyListener(this); m_editor = nullptr; } [[fallthrough]]; case eNotify_OnEndGameMode: // Kill the configured server if it's active if (m_serverProcess) { m_serverProcess->TerminateProcess(0); m_serverProcess = nullptr; } if (INetworkInterface* editorNetworkInterface = AZ::Interface<INetworking>::Get()->RetrieveNetworkInterface(AZ::Name(MpEditorInterfaceName))) { editorNetworkInterface->Disconnect(m_editorConnId, AzNetworking::DisconnectReason::TerminatedByClient); } if (auto console = AZ::Interface<AZ::IConsole>::Get(); console) { console->PerformCommand("disconnect"); } AZ::Interface<INetworkEntityManager>::Get()->ClearAllEntities(); // Rebuild the library to clear temporary in-memory spawnable assets AZ::Interface<INetworkSpawnableLibrary>::Get()->BuildSpawnablesList(); break; } } AzFramework::ProcessWatcher* LaunchEditorServer() { // Assemble the server's path AZ::CVarFixedString serverProcess = editorsv_process; AZ::IO::FixedMaxPath serverPath; if (serverProcess.empty()) { // If enabled but no process name is supplied, try this project's ServerLauncher serverProcess = AZ::Utils::GetProjectName() + ".ServerLauncher"; serverPath = AZ::Utils::GetExecutableDirectory(); serverPath /= serverProcess + AZ_TRAIT_OS_EXECUTABLE_EXTENSION; } else { serverPath = serverProcess; } // Start the configured server if it's available AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; // Open the server launcher using the same rhi as the editor (or launch with the override rhi) AZ::Name server_rhi = AZ::RPI::RPISystemInterface::Get()->GetRenderApiName(); if (!static_cast<AZ::CVarFixedString>(editorsv_rhi_override).empty()) { server_rhi = static_cast<AZ::CVarFixedString>(editorsv_rhi_override); } processLaunchInfo.m_commandlineParameters = AZStd::string::format( R"("%s" --project-path "%s" --editorsv_isDedicated true --sv_defaultPlayerSpawnAsset "%s" --rhi "%s")", serverPath.c_str(), AZ::Utils::GetProjectPath().c_str(), static_cast<AZ::CVarFixedString>(sv_defaultPlayerSpawnAsset).c_str(), server_rhi.GetCStr() ); processLaunchInfo.m_showWindow = true; processLaunchInfo.m_processPriority = AzFramework::ProcessPriority::PROCESSPRIORITY_NORMAL; // Launch the Server AzFramework::ProcessWatcher* outProcess = AzFramework::ProcessWatcher::LaunchProcess( processLaunchInfo, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE); AZ_Error( "MultiplayerEditor", processLaunchInfo.m_launchResult != AzFramework::ProcessLauncher::ProcessLaunchResult::PLR_MissingFile, "LaunchEditorServer failed! The ServerLauncher binary is missing! (%s) Please build server launcher.", serverPath.c_str()) return outProcess; } void MultiplayerEditorSystemComponent::OnGameEntitiesStarted() { auto prefabEditorEntityOwnershipInterface = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get(); if (!prefabEditorEntityOwnershipInterface) { AZ_Error("MultiplayerEditor", prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface unavailable"); } // BeginGameMode and Prefab Processing have completed at this point IMultiplayerTools* mpTools = AZ::Interface<IMultiplayerTools>::Get(); if (editorsv_enabled && mpTools != nullptr) { const AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& assetData = prefabEditorEntityOwnershipInterface->GetPlayInEditorAssetData(); AZStd::vector<uint8_t> buffer; AZ::IO::ByteContainerStream byteStream(&buffer); // Serialize Asset information and AssetData into a potentially large buffer for (const auto& asset : assetData) { AZ::Data::AssetId assetId = asset.GetId(); AZStd::string assetHint = asset.GetHint(); uint32_t hintSize = aznumeric_cast<uint32_t>(assetHint.size()); byteStream.Write(sizeof(AZ::Data::AssetId), reinterpret_cast<void*>(&assetId)); byteStream.Write(sizeof(uint32_t), reinterpret_cast<void*>(&hintSize)); byteStream.Write(assetHint.size(), assetHint.data()); AZ::Utils::SaveObjectToStream(byteStream, AZ::DataStream::ST_BINARY, asset.GetData(), asset.GetData()->GetType()); } const AZ::CVarFixedString remoteAddress = editorsv_serveraddr; if (editorsv_launch) { if (LocalHost != remoteAddress) { AZ_Warning( "MultiplayerEditor", false, "Launching EditorServer skipped because incompatible cvars. editorsv_launch=true, meaning you want to launch an editor-server on this machine, but the editorsv_serveraddr is %s instead of the local address (127.0.0.1). " "Please either set editorsv_launch=false and keep the remote editor-server, or set editorsv_launch=true and editorsv_serveraddr=127.0.0.1.", remoteAddress.c_str()) return; } // Begin listening for MPEditor packets before we launch the editor-server. // The editor-server will send us (the editor) an "EditorServerReadyForLevelData" packet to let us know it's ready to receive data. INetworkInterface* editorNetworkInterface = AZ::Interface<INetworking>::Get()->RetrieveNetworkInterface(AZ::Name(MpEditorInterfaceName)); AZ_Assert(editorNetworkInterface, "MP Editor Network Interface was unregistered before Editor could connect."); editorNetworkInterface->Listen(editorsv_port); // Launch the editor-server m_serverProcess = LaunchEditorServer(); } else { // Editorsv_launch=false, so we're expecting an editor-server already exists. // Connect to the editor-server and then send the EditorServerLevelData packet. INetworkInterface* editorNetworkInterface = AZ::Interface<INetworking>::Get()->RetrieveNetworkInterface(AZ::Name(MpEditorInterfaceName)); AZ_Assert(editorNetworkInterface, "MP Editor Network Interface was unregistered before Editor could connect.") m_editorConnId = editorNetworkInterface->Connect(AzNetworking::IpAddress(remoteAddress.c_str(), editorsv_port, AzNetworking::ProtocolType::Tcp)); if (m_editorConnId == AzNetworking::InvalidConnectionId) { AZ_Warning( "MultiplayerEditor", false, "Editor multiplayer game-mode failed! Could not connect to an editor-server. editorsv_launch is false so we're assuming you're running your own editor-server at editorsv_serveraddr(%s) on editorsv_port(%i). " "Either set editorsv_launch=true so the editor launches an editor-server for you, or launch your own editor-server by hand before entering game-mode. Remember editor-servers must use editorsv_isDedicated=true.", remoteAddress.c_str(), static_cast<uint16_t>(editorsv_port)) return; } SendEditorServerLevelDataPacket(editorNetworkInterface->GetConnectionSet().GetConnection(m_editorConnId)); } } } void MultiplayerEditorSystemComponent::OnGameEntitiesReset() { } void MultiplayerEditorSystemComponent::OnServerAcceptanceReceived() { // We're now accepting the connection to the EditorServer. // In normal game clients SendReadyForEntityUpdates will be enabled once the appropriate level's root spawnable is loaded, // but since we're in Editor, we're already in the level. AZ::Interface<IMultiplayer>::Get()->SendReadyForEntityUpdates(true); } void MultiplayerEditorSystemComponent::SendEditorServerLevelDataPacket(AzNetworking::IConnection* connection) { const auto prefabEditorEntityOwnershipInterface = AZ::Interface<AzToolsFramework::PrefabEditorEntityOwnershipInterface>::Get(); if (!prefabEditorEntityOwnershipInterface) { AZ_Error("MultiplayerEditor", prefabEditorEntityOwnershipInterface != nullptr, "PrefabEditorEntityOwnershipInterface unavailable") return; } AZ_Printf("MultiplayerEditor", "Editor is sending the editor-server the level data packet.") const AZStd::vector<AZ::Data::Asset<AZ::Data::AssetData>>& assetData = prefabEditorEntityOwnershipInterface->GetPlayInEditorAssetData(); AZStd::vector<uint8_t> buffer; AZ::IO::ByteContainerStream byteStream(&buffer); // Serialize Asset information and AssetData into a potentially large buffer for (const auto& asset : assetData) { AZ::Data::AssetId assetId = asset.GetId(); AZStd::string assetHint = asset.GetHint(); auto hintSize = aznumeric_cast<uint32_t>(assetHint.size()); byteStream.Write(sizeof(AZ::Data::AssetId), reinterpret_cast<void*>(&assetId)); byteStream.Write(sizeof(uint32_t), reinterpret_cast<void*>(&hintSize)); byteStream.Write(assetHint.size(), assetHint.data()); AZ::Utils::SaveObjectToStream(byteStream, AZ::DataStream::ST_BINARY, asset.GetData(), asset.GetData()->GetType()); } // Spawnable library needs to be rebuilt since now we have newly registered in-memory spawnable assets AZ::Interface<INetworkSpawnableLibrary>::Get()->BuildSpawnablesList(); // Read the buffer into EditorServerLevelData packets until we've flushed the whole thing byteStream.Seek(0, AZ::IO::GenericStream::SeekMode::ST_SEEK_BEGIN); while (byteStream.GetCurPos() < byteStream.GetLength()) { MultiplayerEditorPackets::EditorServerLevelData editorServerLevelDataPacket; auto& outBuffer = editorServerLevelDataPacket.ModifyAssetData(); // Size the packet's buffer appropriately size_t readSize = outBuffer.GetCapacity(); const size_t byteStreamSize = byteStream.GetLength() - byteStream.GetCurPos(); if (byteStreamSize < readSize) { readSize = byteStreamSize; } outBuffer.Resize(readSize); byteStream.Read(readSize, outBuffer.GetBuffer()); // If we've run out of buffer, mark that we're done if (byteStream.GetCurPos() == byteStream.GetLength()) { editorServerLevelDataPacket.SetLastUpdate(true); } connection->SendReliablePacket(editorServerLevelDataPacket); } } void MultiplayerEditorSystemComponent::EnterGameMode() { PyEnterGameMode(); } bool MultiplayerEditorSystemComponent::IsInGameMode() { return PyIsInGameMode(); } }
48.725191
274
0.671053
[ "vector", "3d" ]
11ae209b699904d95976577d330b6401b519d8d7
6,277
cc
C++
Analyses/src/ReadTrackerSteps_module.cc
michaelmackenzie/Offline
57bcd11d499af77ed0619deeddace51ed2b0b097
[ "Apache-2.0" ]
null
null
null
Analyses/src/ReadTrackerSteps_module.cc
michaelmackenzie/Offline
57bcd11d499af77ed0619deeddace51ed2b0b097
[ "Apache-2.0" ]
26
2019-11-08T09:56:55.000Z
2020-09-09T17:25:33.000Z
Analyses/src/ReadTrackerSteps_module.cc
ryuwd/Offline
92957f111425910274df61dbcbd2bad76885f993
[ "Apache-2.0" ]
null
null
null
// // example Plugin to read Tracker Step data and create ntuples // // Original author KLG // //#include <cmath> #include <iostream> #include <string> #include <iomanip> // CLHEP includes #include "CLHEP/Units/SystemOfUnits.h" // Mu2e includes #include "Offline/ConditionsService/inc/ConditionsHandle.hh" #include "Offline/GeometryService/inc/GeomHandle.hh" #include "Offline/TrackerGeom/inc/Tracker.hh" #include "Offline/MCDataProducts/inc/GenParticleCollection.hh" #include "Offline/MCDataProducts/inc/SimParticleCollection.hh" #include "Offline/MCDataProducts/inc/StepPointMCCollection.hh" // root includes #include "TH1F.h" #include "TNtuple.h" #include "TTree.h" // Framework includes #include "art/Framework/Core/EDAnalyzer.h" #include "art/Framework/Principal/Event.h" #include "art/Framework/Principal/Run.h" #include "art/Framework/Core/ModuleMacros.h" #include "art_root_io/TFileService.h" #include "art/Framework/Principal/Handle.h" #include "cetlib_except/exception.h" #include "fhiclcpp/ParameterSet.h" #include "messagefacility/MessageLogger/MessageLogger.h" using namespace std; using CLHEP::Hep3Vector; using CLHEP::keV; namespace mu2e { class ReadTrackerSteps : public art::EDAnalyzer { public: explicit ReadTrackerSteps(fhicl::ParameterSet const& pset); virtual ~ReadTrackerSteps() {} virtual void beginJob(); void analyze(const art::Event& e); private: // debug output llevel int _diagLevel; // Module label of the module that made the hits. std::string _hitMakerModuleLabel; // Control printed output. int _nAnalyzed; int _maxFullPrint; // Pointers to histograms, ntuples. TH1F* _hNtset; TH1F* _hNtsetH; TNtuple* _nttts; // Name of the TS StepPoint collection std::string _tsStepPoints; }; ReadTrackerSteps::ReadTrackerSteps(fhicl::ParameterSet const& pset) : art::EDAnalyzer(pset), // Run time parameters _diagLevel(pset.get<int>("diagLevel",0)), _hitMakerModuleLabel(pset.get<string>("hitMakerModuleLabel","g4run")), _nAnalyzed(0), _maxFullPrint(pset.get<int>("maxFullPrint",5)), _hNtset(0), _hNtsetH(0), _nttts(0), _tsStepPoints(pset.get<string>("tsStepPoints","trackerDS")) {} void ReadTrackerSteps::beginJob(){ // Get access to the TFile service. art::ServiceHandle<art::TFileService> tfs; _hNtset = tfs->make<TH1F>( "hNtset ", "Number/ID of the detector with step", 50, 0., 50. ); _hNtsetH = tfs->make<TH1F>( "hNtsetH", "Number of steps", 50, 0., 50. ); // Create an ntuple. _nttts = tfs->make<TNtuple>( "nttts", "Tracker steps ntuple", "evt:trk:sid:pdg:time:x:y:z:px:py:pz:" "g4bl_time"); } void ReadTrackerSteps::analyze(const art::Event& event) { ++_nAnalyzed; if (_diagLevel>1 ) { cout << "ReadTrackerSteps::" << __func__ << setw(4) << " called for event " << event.id().event() << " hitMakerModuleLabel " << _hitMakerModuleLabel << " tsStepPoints " << _tsStepPoints << endl; } art::ServiceHandle<GeometryService> geom; if (!geom->hasElement<Tracker>()) { mf::LogError("Geom") << "Skipping ReadTrackerSteps::analyze due to lack of tracker\n"; return; } // Access detector geometry information // Get a handle to the hits created by G4. art::Handle<StepPointMCCollection> hitsHandle; event.getByLabel(_hitMakerModuleLabel, _tsStepPoints, hitsHandle); if (!hitsHandle.isValid() ) { mf::LogError("Hits") << " Skipping ReadTrackerSteps::analyze due to problems with hits\n"; return; } StepPointMCCollection const& hits = *hitsHandle; unsigned int const nhits = hits.size(); if (_diagLevel>0 && nhits>0 ) { cout << "ReadTrackerSteps::" << __func__ << " Number of TS hits: " <<setw(4) << nhits << endl; } art::Handle<SimParticleCollection> simParticles; event.getByLabel(_hitMakerModuleLabel, simParticles); bool haveSimPart = simParticles.isValid(); if ( haveSimPart ) haveSimPart = !(simParticles->empty()); // Fill histograms & ntuple // Fill histogram with number of hits per event. _hNtsetH->Fill(nhits); float nt[_nttts->GetNvar()]; // Loop over all TS hits. for ( size_t i=0; i<nhits; ++i ){ // Alias, used for readability. const StepPointMC& hit = (hits)[i]; // Get the hit information. int did = hit.volumeId(); // Fill histogram with the detector numbers _hNtset->Fill(did); const CLHEP::Hep3Vector& pos = hit.position(); const CLHEP::Hep3Vector& mom = hit.momentum(); // Get track info SimParticleCollection::key_type trackId = hit.trackId(); int pdgId = 0; if ( haveSimPart ){ if( !simParticles->has(trackId) ) { pdgId = 0; } else { SimParticle const& sim = simParticles->at(trackId); pdgId = sim.pdgId(); } } // Fill the ntuple. nt[0] = event.id().event(); nt[1] = trackId.asInt(); nt[2] = did; nt[3] = pdgId; nt[4] = hit.time(); nt[5] = pos.x(); nt[6] = pos.y(); nt[7] = pos.z(); nt[8] = mom.x(); nt[9] = mom.y(); nt[10] = mom.z(); nt[11] = hit.properTime(); _nttts->Fill(nt); if ( _nAnalyzed < _maxFullPrint){ cout << "ReadTrackerSteps::" << __func__ << ": TS hit: " << setw(8) << event.id().event() << " | " << setw(4) << hit.volumeId() << " | " << setw(6) << pdgId << " | " << setw(8) << hit.time() << " | " << setw(8) << mom.mag() << " | " << pos << endl; } } // end loop over hits. } } // end namespace mu2e using mu2e::ReadTrackerSteps; DEFINE_ART_MODULE(ReadTrackerSteps);
25.938017
77
0.58324
[ "geometry" ]
11ae492d544ba979af5a8ea6e6a741ec4c4bb2cf
3,623
hpp
C++
dev/restinio/impl/ioctx_on_thread_pool.hpp
Lord-Kamina/restinio
00133ac4154626ec094697370d2dbe4ce01727f8
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
dev/restinio/impl/ioctx_on_thread_pool.hpp
Lord-Kamina/restinio
00133ac4154626ec094697370d2dbe4ce01727f8
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
dev/restinio/impl/ioctx_on_thread_pool.hpp
Lord-Kamina/restinio
00133ac4154626ec094697370d2dbe4ce01727f8
[ "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
#pragma once #include <thread> #include <restinio/asio_include.hpp> #include <restinio/exception.hpp> namespace restinio { namespace impl { /*! * \brief A class for holding actual instance of Asio's io_context. * * \note * This class is intended to be used as template argument for * ioctx_on_thread_pool_t template. * * \since * v.0.4.2 */ class own_io_context_for_thread_pool_t { asio_ns::io_context m_ioctx; public: own_io_context_for_thread_pool_t() {} //! Get access to io_context object. auto & io_context() noexcept { return m_ioctx; } }; /*! * \brief A class for holding a reference to external Asio's io_context. * * \note * This class is intended to be used as template argument for * ioctx_on_thread_pool_t template. * * \since * v.0.4.2 */ class external_io_context_for_thread_pool_t { asio_ns::io_context & m_ioctx; public: //! Initializing constructor. external_io_context_for_thread_pool_t( //! External io_context to be used. asio_ns::io_context & ioctx ) : m_ioctx{ ioctx } {} //! Get access to io_context object. auto & io_context() noexcept { return m_ioctx; } }; /*! * Helper class for creating io_context and running it * (via `io_context::run()`) on a thread pool. * * \note class is not thread-safe (except `io_context()` method). * Expected usage scenario is to start and stop it on the same thread. * * \tparam Io_Context_Holder A type which actually holds io_context object * or a reference to an external io_context object. */ template< typename Io_Context_Holder > class ioctx_on_thread_pool_t { public: ioctx_on_thread_pool_t( const ioctx_on_thread_pool_t & ) = delete; ioctx_on_thread_pool_t( ioctx_on_thread_pool_t && ) = delete; template< typename... Io_Context_Holder_Ctor_Args > ioctx_on_thread_pool_t( // Pool size. //FIXME: better to use not_null from gsl. std::size_t pool_size, // Optional arguments for Io_Context_Holder instance. Io_Context_Holder_Ctor_Args && ...ioctx_holder_args ) : m_ioctx_holder{ std::forward<Io_Context_Holder_Ctor_Args>(ioctx_holder_args)... } , m_pool( pool_size ) , m_status( status_t::stopped ) {} // Makes sure the pool is stopped. ~ioctx_on_thread_pool_t() { if( started() ) { stop(); wait(); } } void start() { if( started() ) { throw exception_t{ "io_context_with_thread_pool is already started" }; } try { std::generate( begin( m_pool ), end( m_pool ), [this]{ return std::thread{ [this] { auto work{ asio_ns::make_work_guard( m_ioctx_holder.io_context() ) }; m_ioctx_holder.io_context().run(); } }; } ); // When all thread started successfully // status can be changed. m_status = status_t::started; } catch( const std::exception & ) { io_context().stop(); for( auto & t : m_pool ) if( t.joinable() ) t.join(); } } void stop() { if( started() ) { io_context().stop(); } } void wait() { if( started() ) { for( auto & t : m_pool ) t.join(); // When all threads are stopped status can be changed. m_status = status_t::stopped; } } bool started() const noexcept { return status_t::started == m_status; } asio_ns::io_context & io_context() noexcept { return m_ioctx_holder.io_context(); } private: enum class status_t : std::uint8_t { stopped, started }; Io_Context_Holder m_ioctx_holder; std::vector< std::thread > m_pool; status_t m_status; }; } /* namespace impl */ } /* namespace restinio */
20.016575
74
0.661054
[ "object", "vector" ]
11b01681202eca2312340dedea268b2b43563a55
79,647
cc
C++
components/sync_bookmarks/bookmark_remote_updates_handler_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
components/sync_bookmarks/bookmark_remote_updates_handler_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
components/sync_bookmarks/bookmark_remote_updates_handler_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync_bookmarks/bookmark_remote_updates_handler.h" #include <memory> #include <string> #include <utility> #include "base/guid.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/test/test_bookmark_client.h" #include "components/favicon/core/test/mock_favicon_service.h" #include "components/sync/base/client_tag_hash.h" #include "components/sync/base/hash_util.h" #include "components/sync/base/model_type.h" #include "components/sync/base/unique_position.h" #include "components/sync/driver/sync_driver_switches.h" #include "components/sync/model/conflict_resolution.h" #include "components/sync/protocol/unique_position.pb.h" #include "components/sync_bookmarks/bookmark_model_merger.h" #include "components/sync_bookmarks/bookmark_specifics_conversions.h" #include "components/sync_bookmarks/switches.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::ASCIIToUTF16; using testing::_; using testing::ElementsAre; using testing::Eq; using testing::IsNull; using testing::NotNull; namespace sync_bookmarks { namespace { // The parent tag for children of the root entity. Entities with this parent are // referred to as top level entities. const char kRootParentId[] = "0"; const char kBookmarksRootId[] = "root_id"; const char kBookmarkBarId[] = "bookmark_bar_id"; const char kBookmarkBarTag[] = "bookmark_bar"; const char kMobileBookmarksId[] = "synced_bookmarks_id"; const char kMobileBookmarksTag[] = "synced_bookmarks"; const char kOtherBookmarksId[] = "other_bookmarks_id"; const char kOtherBookmarksTag[] = "other_bookmarks"; // Fork of enum RemoteBookmarkUpdateError. enum class ExpectedRemoteBookmarkUpdateError { kConflictingTypes = 0, kInvalidSpecifics = 1, kInvalidUniquePosition = 2, kPermanentNodeCreationAfterMerge = 3, kMissingParentEntity = 4, kMissingParentNode = 5, kMissingParentEntityInConflict = 6, kMissingParentNodeInConflict = 7, kCreationFailure = 8, kUnexpectedGuid = 9, kParentNotFolder = 10, kGuidChangedForTrackedServerId = 11, kMaxValue = kGuidChangedForTrackedServerId, }; // |node| must not be nullptr. sync_pb::BookmarkMetadata CreateNodeMetadata( const bookmarks::BookmarkNode* node, const std::string& server_id) { sync_pb::BookmarkMetadata bookmark_metadata; bookmark_metadata.set_id(node->id()); bookmark_metadata.mutable_metadata()->set_server_id(server_id); bookmark_metadata.mutable_metadata()->set_client_tag_hash( syncer::ClientTagHash::FromUnhashed(syncer::BOOKMARKS, node->guid().AsLowercaseString()) .value()); return bookmark_metadata; } sync_pb::BookmarkMetadata CreateNodeMetadata( const bookmarks::BookmarkNode* node, const std::string& server_id, const syncer::UniquePosition& unique_position) { sync_pb::BookmarkMetadata bookmark_metadata = CreateNodeMetadata(node, server_id); *bookmark_metadata.mutable_metadata()->mutable_unique_position() = unique_position.ToProto(); return bookmark_metadata; } sync_pb::BookmarkModelMetadata CreateMetadataForPermanentNodes( const bookmarks::BookmarkModel* bookmark_model) { sync_pb::BookmarkModelMetadata model_metadata; model_metadata.mutable_model_type_state()->set_initial_sync_done(true); model_metadata.set_bookmarks_full_title_reuploaded(true); *model_metadata.add_bookmarks_metadata() = CreateNodeMetadata(bookmark_model->bookmark_bar_node(), /*server_id=*/kBookmarkBarId); *model_metadata.add_bookmarks_metadata() = CreateNodeMetadata(bookmark_model->mobile_node(), /*server_id=*/kMobileBookmarksId); *model_metadata.add_bookmarks_metadata() = CreateNodeMetadata(bookmark_model->other_node(), /*server_id=*/kOtherBookmarksId); return model_metadata; } syncer::UpdateResponseData CreateUpdateResponseData( const std::string& server_id, const std::string& parent_id, const base::GUID& guid, const std::string& title, bool is_deletion, int version, const syncer::UniquePosition& unique_position) { syncer::EntityData data; data.id = server_id; data.parent_id = parent_id; data.unique_position = unique_position.ToProto(); data.originator_client_item_id = guid.AsLowercaseString(); // EntityData would be considered a deletion if its specifics hasn't been set. if (!is_deletion) { sync_pb::BookmarkSpecifics* bookmark_specifics = data.specifics.mutable_bookmark(); bookmark_specifics->set_guid(guid.AsLowercaseString()); bookmark_specifics->set_legacy_canonicalized_title(title); bookmark_specifics->set_full_title(title); } data.is_folder = true; syncer::UpdateResponseData response_data; response_data.entity = std::move(data); response_data.response_version = version; return response_data; } // Overload that assign a random position. Should only be used when position // is not relevant. syncer::UpdateResponseData CreateUpdateResponseData( const std::string& server_id, const std::string& parent_id, const base::GUID& guid, bool is_deletion, int version = 0) { return CreateUpdateResponseData(server_id, parent_id, guid, /*title=*/server_id, is_deletion, version, syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix())); } syncer::UpdateResponseData CreateBookmarkRootUpdateData() { syncer::EntityData data; data.id = syncer::ModelTypeToRootTag(syncer::BOOKMARKS); data.parent_id = kRootParentId; data.server_defined_unique_tag = syncer::ModelTypeToRootTag(syncer::BOOKMARKS); data.specifics.mutable_bookmark(); syncer::UpdateResponseData response_data; response_data.entity = std::move(data); // Similar to what's done in the loopback_server. response_data.response_version = 0; return response_data; } syncer::UpdateResponseData CreatePermanentFolderUpdateData( const std::string& id, const std::string& tag) { syncer::EntityData data; data.id = id; data.parent_id = "root_id"; data.server_defined_unique_tag = tag; data.specifics.mutable_bookmark(); syncer::UpdateResponseData response_data; response_data.entity = std::move(data); // Similar to what's done in the loopback_server. response_data.response_version = 0; return response_data; } syncer::UpdateResponseDataList CreatePermanentFoldersUpdateData() { syncer::UpdateResponseDataList updates; updates.push_back( CreatePermanentFolderUpdateData(kBookmarkBarId, kBookmarkBarTag)); updates.push_back( CreatePermanentFolderUpdateData(kOtherBookmarksId, kOtherBookmarksTag)); updates.push_back( CreatePermanentFolderUpdateData(kMobileBookmarksId, kMobileBookmarksTag)); return updates; } class BookmarkRemoteUpdatesHandlerWithInitialMergeTest : public testing::Test { public: BookmarkRemoteUpdatesHandlerWithInitialMergeTest() : bookmark_model_(bookmarks::TestBookmarkClient::CreateModel()), tracker_(SyncedBookmarkTracker::CreateEmpty(sync_pb::ModelTypeState())), updates_handler_(bookmark_model_.get(), &favicon_service_, tracker_.get()) { BookmarkModelMerger(CreatePermanentFoldersUpdateData(), bookmark_model_.get(), &favicon_service_, tracker_.get()) .Merge(); } bookmarks::BookmarkModel* bookmark_model() { return bookmark_model_.get(); } SyncedBookmarkTracker* tracker() { return tracker_.get(); } favicon::MockFaviconService* favicon_service() { return &favicon_service_; } BookmarkRemoteUpdatesHandler* updates_handler() { return &updates_handler_; } private: std::unique_ptr<bookmarks::BookmarkModel> bookmark_model_; std::unique_ptr<SyncedBookmarkTracker> tracker_; testing::NiceMock<favicon::MockFaviconService> favicon_service_; BookmarkRemoteUpdatesHandler updates_handler_; }; TEST(BookmarkRemoteUpdatesHandlerReorderUpdatesTest, ShouldIgnoreRootNodes) { syncer::UpdateResponseDataList updates; updates.push_back(CreateBookmarkRootUpdateData()); std::vector<const syncer::UpdateResponseData*> ordered_updates = BookmarkRemoteUpdatesHandler::ReorderUpdatesForTest(&updates); // Root node update should be filtered out. EXPECT_THAT(ordered_updates.size(), Eq(0U)); } TEST(BookmarkRemoteUpdatesHandlerReorderUpdatesTest, ShouldReorderParentsUpdateBeforeChildrenAndBothBeforeDeletions) { // Prepare creation updates to build this structure: // bookmark_bar // |- node0 // |- node1 // |- node2 // and another sub hierarchy under node3 that won't receive any update. // node4 // |- node5 // and a deletion for node6 under node3. // Constuct the updates list to have deletion first, and then all creations in // reverse shuffled order (from child to parent). std::vector<std::string> ids; for (int i = 0; i < 7; i++) { ids.push_back("node" + base::NumberToString(i)); } // Construct updates list syncer::UpdateResponseDataList updates; updates.push_back( CreateUpdateResponseData(/*server_id=*/ids[6], /*parent_id=*/ids[3], /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/true)); updates.push_back( CreateUpdateResponseData(/*server_id=*/ids[5], /*parent_id=*/ids[4], /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); updates.push_back( CreateUpdateResponseData(/*server_id=*/ids[2], /*parent_id=*/ids[1], /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); updates.push_back( CreateUpdateResponseData(/*server_id=*/ids[1], /*parent_id=*/ids[0], /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); updates.push_back( CreateUpdateResponseData(/*server_id=*/ids[4], /*parent_id=*/ids[3], /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); updates.push_back( CreateUpdateResponseData(/*server_id=*/ids[0], /*parent_id=*/kBookmarksRootId, /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); std::vector<const syncer::UpdateResponseData*> ordered_updates = BookmarkRemoteUpdatesHandler::ReorderUpdatesForTest(&updates); // No update should be dropped. ASSERT_THAT(ordered_updates.size(), Eq(6U)); // Updates should be ordered such that parent node update comes first, and // deletions come last. // node4 --> node5 --> node0 --> node1 --> node2 --> node6. // This is test is over verifying since the order requirements are // within subtrees only. (e.g it doesn't matter whether node1 comes before or // after node4). However, it's implemented this way for simplicity. EXPECT_THAT(ordered_updates[0]->entity.id, Eq(ids[4])); EXPECT_THAT(ordered_updates[1]->entity.id, Eq(ids[5])); EXPECT_THAT(ordered_updates[2]->entity.id, Eq(ids[0])); EXPECT_THAT(ordered_updates[3]->entity.id, Eq(ids[1])); EXPECT_THAT(ordered_updates[4]->entity.id, Eq(ids[2])); EXPECT_THAT(ordered_updates[5]->entity.id, Eq(ids[6])); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldProcessRandomlyOrderedCreations) { // Prepare creation updates to construct this structure: // bookmark_bar // |- node0 // |- node1 // |- node2 const std::string kId0 = "id0"; const std::string kId1 = "id1"; const std::string kId2 = "id2"; // Constuct the updates list to have creations randomly ordered. syncer::UpdateResponseDataList updates; updates.push_back( CreateUpdateResponseData(/*server_id=*/kId2, /*parent_id=*/kId1, /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); updates.push_back( CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); updates.push_back( CreateUpdateResponseData(/*server_id=*/kId1, /*parent_id=*/kId0, /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // All nodes should be tracked including the "bookmark bar", "other // bookmarks" node and "mobile bookmarks". EXPECT_THAT(tracker()->TrackedEntitiesCountForTest(), Eq(6U)); // All nodes should have been added to the model. const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(1u)); EXPECT_THAT(bookmark_bar_node->children().front()->GetTitle(), Eq(ASCIIToUTF16(kId0))); ASSERT_THAT(bookmark_bar_node->children().front()->children().size(), Eq(1u)); const bookmarks::BookmarkNode* grandchild = bookmark_bar_node->children().front()->children().front().get(); EXPECT_THAT(grandchild->GetTitle(), Eq(ASCIIToUTF16(kId1))); ASSERT_THAT(grandchild->children().size(), Eq(1u)); EXPECT_THAT(grandchild->children().front()->GetTitle(), Eq(ASCIIToUTF16(kId2))); EXPECT_THAT(grandchild->children().front()->children().size(), Eq(0u)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldProcessRandomlyOrderedDeletions) { // Prepare creation updates to construct this structure: // bookmark_bar // |- node0 // |- node1 // |- node2 const std::string kId0 = "id0"; const std::string kId1 = "id1"; const std::string kId2 = "id2"; const base::GUID kGuid0 = base::GUID::GenerateRandomV4(); const base::GUID kGuid1 = base::GUID::GenerateRandomV4(); const base::GUID kGuid2 = base::GUID::GenerateRandomV4(); // Construct the updates list to create that structure syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid0, /*is_deletion=*/false)); updates.push_back(CreateUpdateResponseData(/*server_id=*/kId1, /*parent_id=*/kId0, /*guid=*/kGuid1, /*is_deletion=*/false)); updates.push_back(CreateUpdateResponseData(/*server_id=*/kId2, /*parent_id=*/kId1, /*guid=*/kGuid2, /*is_deletion=*/false)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // All nodes should be tracked including the "bookmark bar", "other // bookmarks" node and "mobile bookmarks". ASSERT_THAT(tracker()->TrackedEntitiesCountForTest(), Eq(6U)); // Construct the updates list to have random deletions order. updates.clear(); updates.push_back(CreateUpdateResponseData(/*server_id=*/kId1, /*parent_id=*/kId0, /*guid=*/kGuid1, /*is_deletion=*/true, /*version=*/1)); updates.push_back(CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarksRootId, /*guid=*/kGuid0, /*is_deletion=*/true, /*version=*/1)); updates.push_back(CreateUpdateResponseData(/*server_id=*/kId2, /*parent_id=*/kId1, /*guid=*/kGuid2, /*is_deletion=*/true, /*version=*/1)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // |tracker| should have only permanent nodes now. EXPECT_THAT(tracker()->TrackedEntitiesCountForTest(), Eq(3U)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldProcessDeletionWithServerIdOnly) { const std::string kId0 = "id0"; const base::GUID kGuid0 = base::GUID::GenerateRandomV4(); // Construct the updates list to create that structure syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid0, /*is_deletion=*/false)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // The node should be tracked including the "bookmark bar", "other // bookmarks" node and "mobile bookmarks". ASSERT_THAT(tracker()->TrackedEntitiesCountForTest(), Eq(4U)); // Construct the updates list with one minimalistic deletion (server ID only). updates.clear(); updates.emplace_back(); updates.back().entity.id = kId0; updates.back().response_version = 1; ASSERT_TRUE(updates.back().entity.is_deleted()); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // |tracker| should have only permanent nodes now. EXPECT_THAT(tracker()->TrackedEntitiesCountForTest(), Eq(3U)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldIgnoreRemoteCreationWithInvalidGuidInSpecifics) { const std::string kId = "id"; const std::string kTitle = "title"; const syncer::UniquePosition kPosition = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UpdateResponseDataList updates; // Create update with an invalid GUID. updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID(), /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/kPosition)); base::HistogramTester histogram_tester; updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); EXPECT_THAT(tracker()->GetEntityForSyncId(kId), IsNull()); histogram_tester.ExpectBucketCount( "Sync.ProblematicServerSideBookmarks", /*sample=*/ExpectedRemoteBookmarkUpdateError::kInvalidSpecifics, /*expected_count=*/1); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldIgnoreRemoteCreationWithUnexpectedGuidInSpecifics) { const std::string kId = "id"; const std::string kTitle = "title"; const syncer::UniquePosition kPosition = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UpdateResponseDataList updates; // Create update with empty GUID. updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/kPosition)); // Override the originator client item ID to mimic a mismatch. updates.back().entity.originator_client_item_id = base::GUID::GenerateRandomV4().AsLowercaseString(); base::HistogramTester histogram_tester; updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); EXPECT_THAT(tracker()->GetEntityForSyncId(kId), IsNull()); histogram_tester.ExpectBucketCount( "Sync.ProblematicServerSideBookmarks", /*sample=*/ExpectedRemoteBookmarkUpdateError::kUnexpectedGuid, /*expected_count=*/1); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldIgnoreMisbehavingServerWithRemoteGuidUpdate) { const std::string kId = "id"; const std::string kTitle = "title"; const base::GUID kOldGuid = base::GUID::GenerateRandomV4(); const base::GUID kNewGuid = base::GUID::GenerateRandomV4(); const syncer::UniquePosition kPosition = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UpdateResponseDataList updates; // Create update with GUID. updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kOldGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/kPosition)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); ASSERT_THAT(tracker()->GetEntityForSyncId(kId), NotNull()); // Push an update for the same entity with a new GUID. Note that this is a // protocol violation, because |originator_client_item_id| cannot have changed // for a given server ID. updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kNewGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); base::HistogramTester histogram_tester; updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // The GUID should not have been updated. const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(1u)); EXPECT_THAT(bookmark_bar_node->children().front()->guid(), Eq(kOldGuid)); histogram_tester.ExpectBucketCount( "Sync.ProblematicServerSideBookmarks", /*sample=*/ ExpectedRemoteBookmarkUpdateError::kGuidChangedForTrackedServerId, /*expected_count=*/1); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldKeepOldGUIDUponRemoteUpdateWithoutGUID) { const std::string kId = "id"; const std::string kTitle = "title"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); const syncer::UniquePosition kPosition = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UpdateResponseDataList updates; // Create update with GUID. updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/kPosition)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); ASSERT_THAT(tracker()->GetEntityForSyncId(kId), NotNull()); // Push an update for the same entity with no GUID. updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID(), /*title=*/kTitle, /*is_deletion=*/false, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // The GUID should not have been updated. const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(1u)); EXPECT_THAT(bookmark_bar_node->children().front()->guid(), Eq(kGuid)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldPositionRemoteCreations) { // Prepare creation updates to construct this structure: // bookmark_bar // |- node0 // |- node1 // |- node2 const std::string kId0 = "id0"; const std::string kId1 = "id1"; const std::string kId2 = "id2"; syncer::UniquePosition pos0 = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UniquePosition pos1 = syncer::UniquePosition::After( pos0, syncer::UniquePosition::RandomSuffix()); syncer::UniquePosition pos2 = syncer::UniquePosition::After( pos1, syncer::UniquePosition::RandomSuffix()); // Constuct the updates list to have creations randomly ordered. syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kId2, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*title=*/kId2, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/pos2)); updates.push_back( CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*title=*/kId0, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/pos0)); updates.push_back(CreateUpdateResponseData( /*server_id=*/kId1, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*title=*/kId1, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/pos1)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // All nodes should have been added to the model in the correct order. const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(3u)); EXPECT_THAT(bookmark_bar_node->children()[0]->GetTitle(), Eq(ASCIIToUTF16(kId0))); EXPECT_THAT(bookmark_bar_node->children()[1]->GetTitle(), Eq(ASCIIToUTF16(kId1))); EXPECT_THAT(bookmark_bar_node->children()[2]->GetTitle(), Eq(ASCIIToUTF16(kId2))); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldPositionRemoteMovesToTheLeft) { // Start with structure: // bookmark_bar // |- node0 // |- node1 // |- node2 // |- node3 // |- node4 std::vector<std::string> ids; std::vector<base::GUID> guids; std::vector<syncer::UniquePosition> positions; syncer::UniquePosition position = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UpdateResponseDataList updates; for (int i = 0; i < 5; i++) { ids.push_back("node" + base::NumberToString(i)); guids.push_back(base::GUID::GenerateRandomV4()); position = syncer::UniquePosition::After( position, syncer::UniquePosition::RandomSuffix()); positions.push_back(position); updates.push_back(CreateUpdateResponseData( /*server_id=*/ids[i], /*parent_id=*/kBookmarkBarId, /*guid=*/guids[i], /*title=*/ids[i], /*is_deletion=*/false, /*version=*/0, /*unique_position=*/positions[i])); } updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); EXPECT_THAT(bookmark_bar_node->children().size(), Eq(5u)); // Change it to this structure by moving node3 after node1. // bookmark_bar // |- node0 // |- node1 // |- node3 // |- node2 // |- node4 updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/ids[3], /*parent_id=*/kBookmarkBarId, /*guid=*/guids[3], /*title=*/ids[3], /*is_deletion=*/false, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::Between(positions[1], positions[2], syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // Model should have been updated. ASSERT_THAT(bookmark_bar_node->children().size(), Eq(5u)); EXPECT_THAT(bookmark_bar_node->children()[2]->GetTitle(), Eq(ASCIIToUTF16(ids[3]))); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldPositionRemoteMovesToTheRight) { // Start with structure: // bookmark_bar // |- node0 // |- node1 // |- node2 // |- node3 // |- node4 std::vector<std::string> ids; std::vector<base::GUID> guids; std::vector<syncer::UniquePosition> positions; syncer::UniquePosition position = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UpdateResponseDataList updates; for (int i = 0; i < 5; i++) { ids.push_back("node" + base::NumberToString(i)); guids.push_back(base::GUID::GenerateRandomV4()); position = syncer::UniquePosition::After( position, syncer::UniquePosition::RandomSuffix()); positions.push_back(position); updates.push_back(CreateUpdateResponseData( /*server_id=*/ids[i], /*parent_id=*/kBookmarkBarId, /*guid=*/guids[i], /*title=*/ids[i], /*is_deletion=*/false, /*version=*/0, /*unique_position=*/positions[i])); } updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); EXPECT_THAT(bookmark_bar_node->children().size(), Eq(5u)); // Change it to this structure by moving node1 after node3. // bookmark_bar // |- node0 // |- node2 // |- node3 // |- node1 // |- node4 updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/ids[1], /*parent_id=*/kBookmarkBarId, /*guid=*/guids[1], /*title=*/ids[1], /*is_deletion=*/false, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::Between(positions[3], positions[4], syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // Model should have been updated. ASSERT_THAT(bookmark_bar_node->children().size(), Eq(5u)); EXPECT_THAT(bookmark_bar_node->children()[3]->GetTitle(), Eq(ASCIIToUTF16(ids[1]))); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldPositionRemoteReparenting) { // Start with structure: // bookmark_bar // |- node0 // |- node1 // |- node2 // |- node3 // |- node4 std::vector<std::string> ids; std::vector<base::GUID> guids; std::vector<syncer::UniquePosition> positions; syncer::UniquePosition position = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UpdateResponseDataList updates; for (int i = 0; i < 5; i++) { ids.push_back("node" + base::NumberToString(i)); guids.push_back(base::GUID::GenerateRandomV4()); position = syncer::UniquePosition::After( position, syncer::UniquePosition::RandomSuffix()); positions.push_back(position); updates.push_back(CreateUpdateResponseData( /*server_id=*/ids[i], /*parent_id=*/kBookmarkBarId, /*guid=*/guids[i], /*title=*/ids[i], /*is_deletion=*/false, /*version=*/0, /*unique_position=*/positions[i])); } updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); EXPECT_THAT(bookmark_bar_node->children().size(), Eq(5u)); // Change it to this structure by moving node4 under node1. // bookmark_bar // |- node0 // |- node1 // |- node4 // |- node2 // |- node3 updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/ids[4], /*parent_id=*/ids[1], /*guid=*/guids[4], /*title=*/ids[4], /*is_deletion=*/false, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // Model should have been updated. ASSERT_THAT(bookmark_bar_node->children().size(), Eq(4u)); ASSERT_THAT(bookmark_bar_node->children()[1]->children().size(), Eq(1u)); EXPECT_THAT(bookmark_bar_node->children()[1]->children()[0]->GetTitle(), Eq(ASCIIToUTF16(ids[4]))); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldIgnoreNodeIfParentIsNotFolder) { // Prepare creation updates to construct this structure: // bookmark_bar // |- node0 (is_folder=false) // |- node1 const std::string kParentId = "parent_id"; const std::string kChildId = "child_id"; const std::string kTitle = "Title"; const GURL kUrl("http://www.url.com"); syncer::UpdateResponseDataList updates; syncer::EntityData data; data.id = kParentId; data.parent_id = kBookmarkBarId; data.unique_position = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()) .ToProto(); sync_pb::BookmarkSpecifics* bookmark_specifics = data.specifics.mutable_bookmark(); bookmark_specifics->set_guid( base::GUID::GenerateRandomV4().AsLowercaseString()); // Use the server id as the title for simplicity. bookmark_specifics->set_legacy_canonicalized_title(kTitle); bookmark_specifics->set_url(kUrl.spec()); data.is_folder = false; data.originator_client_item_id = bookmark_specifics->guid(); syncer::UpdateResponseData response_data; response_data.entity = std::move(data); // Similar to what's done in the loopback_server. response_data.response_version = 0; updates.push_back(std::move(response_data)); updates.push_back(CreateUpdateResponseData( /*server_id=*/kChildId, /*parent_id=*/kParentId, /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); base::HistogramTester histogram_tester; updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_EQ(bookmark_bar_node->children().size(), 1U); EXPECT_TRUE(bookmark_bar_node->children()[0]->children().empty()); histogram_tester.ExpectBucketCount( "Sync.ProblematicServerSideBookmarks", /*sample=*/ExpectedRemoteBookmarkUpdateError::kParentNotFolder, /*expected_count=*/1); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldMergeFaviconUponRemoteCreationsWithFavicon) { // Prepare creation updates to construct this structure: // bookmark_bar // |- node0 const std::string kTitle = "Title"; const GURL kUrl("http://www.url.com"); const GURL kIconUrl("http://www.icon-url.com"); syncer::UpdateResponseDataList updates; syncer::EntityData data; data.id = "server_id"; data.parent_id = kBookmarkBarId; data.unique_position = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()) .ToProto(); sync_pb::BookmarkSpecifics* bookmark_specifics = data.specifics.mutable_bookmark(); bookmark_specifics->set_guid( base::GUID::GenerateRandomV4().AsLowercaseString()); // Use the server id as the title for simplicity. bookmark_specifics->set_legacy_canonicalized_title(kTitle); bookmark_specifics->set_url(kUrl.spec()); bookmark_specifics->set_icon_url(kIconUrl.spec()); bookmark_specifics->set_favicon("PNG"); data.is_folder = false; data.originator_client_item_id = bookmark_specifics->guid(); syncer::UpdateResponseData response_data; response_data.entity = std::move(data); // Similar to what's done in the loopback_server. response_data.response_version = 0; updates.push_back(std::move(response_data)); EXPECT_CALL(*favicon_service(), AddPageNoVisitForBookmark(kUrl, base::UTF8ToUTF16(kTitle))); EXPECT_CALL(*favicon_service(), MergeFavicon(kUrl, kIconUrl, _, _, _)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldDeleteFaviconUponRemoteCreationsWithoutFavicon) { // Prepare creation updates to construct this structure: // bookmark_bar // |- node0 const std::string kTitle = "Title"; const GURL kUrl("http://www.url.com"); syncer::UpdateResponseDataList updates; syncer::EntityData data; data.id = "server_id"; data.parent_id = kBookmarkBarId; data.unique_position = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()) .ToProto(); sync_pb::BookmarkSpecifics* bookmark_specifics = data.specifics.mutable_bookmark(); bookmark_specifics->set_guid( base::GUID::GenerateRandomV4().AsLowercaseString()); // Use the server id as the title for simplicity. bookmark_specifics->set_legacy_canonicalized_title(kTitle); bookmark_specifics->set_url(kUrl.spec()); data.is_folder = false; data.originator_client_item_id = bookmark_specifics->guid(); syncer::UpdateResponseData response_data; response_data.entity = std::move(data); // Similar to what's done in the loopback_server. response_data.response_version = 0; updates.push_back(std::move(response_data)); EXPECT_CALL(*favicon_service(), DeleteFaviconMappings(ElementsAre(kUrl), favicon_base::IconType::kFavicon)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); } // This tests the case when a local creation is successfully committed to the // server but the commit respone isn't received for some reason. Further updates // to that entity should update the sync id in the tracker. TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldUpdateSyncIdWhenRecevingUpdateForNewlyCreatedLocalNode) { const std::string kCacheGuid = "generated_id"; const base::GUID kBookmarkGuid = base::GUID::GenerateRandomV4(); const std::string kOriginatorClientItemId = kBookmarkGuid.AsLowercaseString(); const std::string kSyncId = "server_id"; const int64_t kServerVersion = 1000; const base::Time kModificationTime(base::Time::Now() - base::TimeDelta::FromSeconds(1)); sync_pb::ModelTypeState model_type_state; model_type_state.set_initial_sync_done(true); const sync_pb::UniquePosition unique_position; sync_pb::EntitySpecifics specifics; sync_pb::BookmarkSpecifics* bookmark_specifics = specifics.mutable_bookmark(); bookmark_specifics->set_guid( base::GUID::GenerateRandomV4().AsLowercaseString()); bookmark_specifics->set_legacy_canonicalized_title("Title"); bookmarks::BookmarkNode node(/*id=*/1, kBookmarkGuid, GURL()); // Track a sync entity (similar to what happens after a local creation). The // |originator_client_item_id| is used a temp sync id and mark the entity that // it needs to be committed.. const SyncedBookmarkTracker::Entity* entity = tracker()->Add(&node, /*sync_id=*/kOriginatorClientItemId, kServerVersion, kModificationTime, unique_position, specifics); tracker()->IncrementSequenceNumber(entity); ASSERT_THAT(tracker()->GetEntityForSyncId(kOriginatorClientItemId), Eq(entity)); // Now receive an update with the actual server id. syncer::UpdateResponseDataList updates; syncer::EntityData data; data.id = kSyncId; data.originator_client_item_id = kOriginatorClientItemId; // Set the other required fields. data.unique_position = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()) .ToProto(); data.specifics = specifics; data.specifics.mutable_bookmark()->set_guid(kOriginatorClientItemId); data.is_folder = true; syncer::UpdateResponseData response_data; response_data.entity = std::move(data); // Similar to what's done in the loopback_server. response_data.response_version = 0; updates.push_back(std::move(response_data)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // The sync id in the tracker should have been updated. EXPECT_THAT(tracker()->GetEntityForSyncId(kOriginatorClientItemId), IsNull()); EXPECT_THAT(tracker()->GetEntityForSyncId(kSyncId), Eq(entity)); EXPECT_THAT(entity->metadata()->server_id(), Eq(kSyncId)); EXPECT_THAT(entity->bookmark_node(), Eq(&node)); } // Same as above for bookmarks created with client tags. TEST_F( BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldUpdateSyncIdWhenRecevingUpdateForNewlyCreatedLocalNodeWithClientTag) { base::test::ScopedFeatureList override_features; override_features.InitAndEnableFeature( switches::kSyncUseClientTagForBookmarkCommits); const std::string kBookmarkGuid = base::GUID::GenerateRandomV4().AsLowercaseString(); const std::string kSyncId = "server_id"; const int64_t kServerVersion = 1000; const base::Time kModificationTime(base::Time::Now() - base::TimeDelta::FromSeconds(1)); sync_pb::ModelTypeState model_type_state; model_type_state.set_initial_sync_done(true); const sync_pb::UniquePosition unique_position; sync_pb::EntitySpecifics specifics; sync_pb::BookmarkSpecifics* bookmark_specifics = specifics.mutable_bookmark(); bookmark_specifics->set_guid(kBookmarkGuid); bookmark_specifics->set_legacy_canonicalized_title("Title"); bookmarks::BookmarkNode node( /*id=*/1, base::GUID::ParseLowercase(kBookmarkGuid), GURL()); // Track a sync entity (similar to what happens after a local creation). The // |originator_client_item_id| is used a temp sync id and mark the entity that // it needs to be committed.. const SyncedBookmarkTracker::Entity* entity = tracker()->Add(&node, /*sync_id=*/kBookmarkGuid, kServerVersion, kModificationTime, unique_position, specifics); tracker()->IncrementSequenceNumber(entity); ASSERT_THAT(tracker()->GetEntityForSyncId(kBookmarkGuid), Eq(entity)); // Now receive an update with the actual server id. syncer::UpdateResponseDataList updates; syncer::EntityData data; data.id = kSyncId; data.client_tag_hash = syncer::ClientTagHash::FromUnhashed(syncer::BOOKMARKS, kBookmarkGuid); // Set the other required fields. data.unique_position = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()) .ToProto(); data.specifics = specifics; data.specifics.mutable_bookmark()->set_guid(kBookmarkGuid); data.is_folder = true; syncer::UpdateResponseData response_data; response_data.entity = std::move(data); // Similar to what's done in the loopback_server. response_data.response_version = 0; updates.push_back(std::move(response_data)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // The sync id in the tracker should have been updated. EXPECT_THAT(tracker()->GetEntityForSyncId(kBookmarkGuid), IsNull()); EXPECT_THAT(tracker()->GetEntityForSyncId(kSyncId), Eq(entity)); EXPECT_THAT(entity->metadata()->server_id(), Eq(kSyncId)); EXPECT_THAT(entity->bookmark_node(), Eq(&node)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldRecommitWhenEncryptionIsOutOfDate) { sync_pb::ModelTypeState model_type_state; model_type_state.set_encryption_key_name("encryption_key_name"); tracker()->set_model_type_state(model_type_state); const std::string kId0 = "id0"; syncer::UpdateResponseDataList updates; syncer::UpdateResponseData response_data = CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false); response_data.encryption_key_name = "out_of_date_encryption_key_name"; updates.push_back(std::move(response_data)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); ASSERT_THAT(tracker()->GetEntityForSyncId(kId0), NotNull()); EXPECT_THAT(tracker()->GetEntityForSyncId(kId0)->IsUnsynced(), Eq(true)); } // Tests that recommit will be initiated in case when there is a local tombstone // and server's update has out of date encryption. TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldRecommitWhenEncryptionIsOutOfDateOnConflict) { const std::string kId0 = "id0"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); sync_pb::ModelTypeState model_type_state; model_type_state.set_encryption_key_name("encryption_key_name"); tracker()->set_model_type_state(model_type_state); // Create a new node and remove it locally. syncer::UpdateResponseDataList updates; syncer::UpdateResponseData response_data = CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*is_deletion=*/false, /*version=*/0); response_data.encryption_key_name = "encryption_key_name"; updates.push_back(std::move(response_data)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId0); ASSERT_THAT(entity, NotNull()); ASSERT_THAT(entity->bookmark_node(), NotNull()); ASSERT_THAT(entity->bookmark_node()->guid(), Eq(kGuid)); bookmark_model()->Remove(entity->bookmark_node()); tracker()->MarkDeleted(entity); tracker()->IncrementSequenceNumber(entity); // Process an update with outdated encryption. This should cause a conflict // and the remote version must be applied. Local tombstone entity will be // removed during processing conflict. updates.clear(); response_data = CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*is_deletion=*/false, /*version=*/1); response_data.encryption_key_name = "out_of_date_encryption_key_name"; updates.push_back(std::move(response_data)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // |entity| may be deleted here while processing update during conflict // resolution. entity = tracker()->GetEntityForSyncId(kId0); ASSERT_THAT(entity, NotNull()); EXPECT_THAT(entity->IsUnsynced(), Eq(true)); EXPECT_THAT(entity->bookmark_node(), NotNull()); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldRecommitWhenGotNewEncryptionRequirements) { const std::string kId0 = "id0"; syncer::UpdateResponseDataList updates; updates.push_back( CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*is_deletion=*/false)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); ASSERT_THAT(tracker()->GetEntityForSyncId(kId0), NotNull()); EXPECT_THAT(tracker()->GetEntityForSyncId(kId0)->IsUnsynced(), Eq(false)); updates_handler()->Process(syncer::UpdateResponseDataList(), /*got_new_encryption_requirements=*/true); EXPECT_THAT(tracker()->GetEntityForSyncId(kId0)->IsUnsynced(), Eq(true)); // Permanent nodes shouldn't be committed. They are only created on the server // and synced down. EXPECT_THAT(tracker()->GetEntityForSyncId(kBookmarkBarId)->IsUnsynced(), Eq(false)); } TEST_F( BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldNotRecommitWhenEncryptionKeyNameMistmatchWithConflictWithDeletions) { sync_pb::ModelTypeState model_type_state; model_type_state.set_encryption_key_name("encryption_key_name"); tracker()->set_model_type_state(model_type_state); // Create the bookmark with same encryption key name. const std::string kId = "id"; const std::string kTitle = "title"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); syncer::UpdateResponseDataList updates; syncer::UpdateResponseData response_data = CreateUpdateResponseData(/*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*is_deletion=*/false); response_data.encryption_key_name = "encryption_key_name"; updates.push_back(std::move(response_data)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // The bookmark has been added and tracked. const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(1u)); const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); // Remove the bookmark from the local bookmark model. bookmark_model()->Remove(bookmark_bar_node->children().front().get()); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(0u)); // Mark the entity as deleted locally. tracker()->MarkDeleted(entity); tracker()->IncrementSequenceNumber(entity); ASSERT_THAT(tracker()->GetEntityForSyncId(kId)->IsUnsynced(), Eq(true)); // Push a remote deletion for the same entity with an out of date encryption // key name. updates.clear(); syncer::UpdateResponseData response_data2 = CreateUpdateResponseData(/*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*is_deletion=*/true); response_data2.encryption_key_name = "out_of_date_encryption_key_name"; // Increment the server version to make sure the update isn't discarded as // reflection. response_data2.response_version++; updates.push_back(std::move(response_data2)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // There should have been conflict, and it should have been resolved by // removing local entity since both changes are deletions. EXPECT_THAT(tracker()->GetEntityForSyncId(kId), IsNull()); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldNotRecommitUptoDateEntitiesWhenGotNewEncryptionRequirements) { const std::string kId0 = "id0"; const base::GUID kGuid0 = base::GUID::GenerateRandomV4(); syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid0, /*is_deletion=*/false)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); ASSERT_THAT(tracker()->GetEntityForSyncId(kId0), NotNull()); EXPECT_THAT(tracker()->GetEntityForSyncId(kId0)->IsUnsynced(), Eq(false)); // Push another update to for the same entity. syncer::UpdateResponseData response_data = CreateUpdateResponseData(/*server_id=*/kId0, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid0, /*is_deletion=*/false); // Increment the server version to make sure the update isn't discarded as // reflection. response_data.response_version++; syncer::UpdateResponseDataList new_updates; new_updates.push_back(std::move(response_data)); updates_handler()->Process(new_updates, /*got_new_encryption_requirements=*/true); EXPECT_THAT(tracker()->GetEntityForSyncId(kId0)->IsUnsynced(), Eq(false)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldResolveConflictBetweenLocalAndRemoteDeletionsByMatchingThem) { const std::string kId = "id"; const std::string kTitle = "title"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); ASSERT_THAT(entity->IsUnsynced(), Eq(false)); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(1u)); // Remove the bookmark from the local bookmark model. bookmark_model()->Remove(bookmark_bar_node->children().front().get()); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(0u)); // Mark the entity as deleted locally. tracker()->MarkDeleted(entity); tracker()->IncrementSequenceNumber(entity); ASSERT_THAT(entity->IsUnsynced(), Eq(true)); // Push a remote deletion for the same entity. updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/std::string(), /*is_deletion=*/true, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // There should have been conflict, and it should have been resolved by // removing local entity since both changes. EXPECT_THAT(tracker()->GetEntityForSyncId(kId), IsNull()); // Make sure the bookmark hasn't been resurrected. EXPECT_THAT(bookmark_bar_node->children().size(), Eq(0u)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldResolveConflictBetweenLocalUpdateAndRemoteDeletionWithLocal) { const std::string kId = "id"; const std::string kTitle = "title"; syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); ASSERT_THAT(entity->IsUnsynced(), Eq(false)); // Mark the entity as modified locally. tracker()->IncrementSequenceNumber(entity); ASSERT_THAT(entity->IsUnsynced(), Eq(true)); // Push a remote deletion for the same entity. updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*title=*/std::string(), /*is_deletion=*/true, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // There should have been conflict, and it should have been resolved with the // local version that will be committed later. ASSERT_THAT(tracker()->GetEntityForSyncId(kId), Eq(entity)); EXPECT_THAT(entity->IsUnsynced(), Eq(true)); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); EXPECT_THAT(bookmark_bar_node->children().size(), Eq(1u)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldResolveConflictBetweenLocalDeletionAndRemoteUpdateByRemote) { const std::string kId = "id"; const std::string kTitle = "title"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); ASSERT_THAT(entity->bookmark_node(), NotNull()); ASSERT_THAT(entity->bookmark_node()->guid(), Eq(kGuid)); ASSERT_THAT(entity->IsUnsynced(), Eq(false)); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(1u)); // Remove the bookmark from the local bookmark model. bookmark_model()->Remove(bookmark_bar_node->children().front().get()); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(0u)); // Mark the entity as deleted locally. tracker()->MarkDeleted(entity); tracker()->IncrementSequenceNumber(entity); ASSERT_THAT(entity->IsUnsynced(), Eq(true)); // Push an update for the same entity. updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // There should have been conflict, and it should have been resolved with the // remote version. The implementation may or may not reuse |entity|, so let's // look it up again. entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); EXPECT_THAT(entity->IsUnsynced(), Eq(false)); EXPECT_THAT(entity->metadata()->is_deleted(), Eq(false)); // The bookmark should have been resurrected. EXPECT_THAT(bookmark_bar_node->children().size(), Eq(1u)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldResolveConflictBetweenLocalAndRemoteUpdatesWithMatchingThem) { const std::string kId = "id"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); const std::string kTitle = "title"; const syncer::UniquePosition kPosition = syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()); syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/kPosition)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); ASSERT_THAT(entity->IsUnsynced(), Eq(false)); // Mark the entity as modified locally. tracker()->IncrementSequenceNumber(entity); ASSERT_THAT(entity->IsUnsynced(), Eq(true)); // Push an update for the same entity with the same information. updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/1, /*unique_position=*/kPosition)); updates_handler()->Process(updates, /*got_new_encryption_requirements=*/false); // There should have been conflict but both local and remote updates should // match. The conflict should have been resolved. ASSERT_THAT(tracker()->GetEntityForSyncId(kId), Eq(entity)); EXPECT_THAT(entity->IsUnsynced(), Eq(false)); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldResolveConflictBetweenLocalAndRemoteUpdatesWithRemote) { const std::string kId = "id"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); const std::string kTitle = "title"; const std::string kNewRemoteTitle = "remote title"; syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); BookmarkRemoteUpdatesHandler updates_handler(bookmark_model(), favicon_service(), tracker()); updates_handler.Process(updates, /*got_new_encryption_requirements=*/false); const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); ASSERT_THAT(entity->IsUnsynced(), Eq(false)); // Mark the entity as modified locally. tracker()->IncrementSequenceNumber(entity); ASSERT_THAT(entity->IsUnsynced(), Eq(true)); // Push an update for the same entity with a new title. updates.clear(); updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kNewRemoteTitle, /*is_deletion=*/false, /*version=*/1, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates_handler.Process(updates, /*got_new_encryption_requirements=*/false); // There should have been conflict, and it should have been resolved with the // remote version. ASSERT_THAT(tracker()->GetEntityForSyncId(kId), Eq(entity)); EXPECT_THAT(entity->IsUnsynced(), Eq(false)); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_THAT(bookmark_bar_node->children().size(), Eq(1u)); EXPECT_THAT(bookmark_bar_node->children().front()->GetTitle(), Eq(ASCIIToUTF16(kNewRemoteTitle))); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldReuploadOnEmptyGuidOnUpdateWithSameSpecifics) { const std::string kServerId = "server_id"; base::test::ScopedFeatureList override_features; override_features.InitAndEnableFeature( switches::kSyncReuploadBookmarksUponMatchingData); syncer::UpdateResponseDataList updates; updates.push_back( CreateUpdateResponseData(kServerId, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), "Title", /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); ASSERT_TRUE(updates.back().entity.specifics.bookmark().has_full_title()); BookmarkRemoteUpdatesHandler(bookmark_model(), favicon_service(), tracker()) .Process(updates, /*got_new_encryption_requirements=*/false); const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kServerId); ASSERT_THAT(entity, NotNull()); ASSERT_FALSE(entity->IsUnsynced()); // Mimic the case when there is another update but without GUID in the // original specifics. updates.back().entity.is_bookmark_guid_in_specifics_preprocessed = true; updates.back().response_version++; BookmarkRemoteUpdatesHandler(bookmark_model(), favicon_service(), tracker()) .Process(updates, /*got_new_encryption_requirements=*/false); EXPECT_TRUE(entity->IsUnsynced()); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldIncrementSequenceNumberOnConflict) { base::test::ScopedFeatureList override_features; override_features.InitAndEnableFeature( switches::kSyncReuploadBookmarkFullTitles); const std::string kId = "id"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); const std::string kTitle = "title"; const std::string kNewTitle = "New title"; syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates.back().entity.specifics.mutable_bookmark()->clear_full_title(); { BookmarkRemoteUpdatesHandler updates_handler(bookmark_model(), favicon_service(), tracker()); updates_handler.Process(updates, /*got_new_encryption_requirements=*/false); } const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); EXPECT_TRUE(entity->IsUnsynced()); // Check reupload on conflict with new title. updates.back() .entity.specifics.mutable_bookmark() ->set_legacy_canonicalized_title(kNewTitle); updates.back().response_version++; { BookmarkRemoteUpdatesHandler updates_handler(bookmark_model(), favicon_service(), tracker()); updates_handler.Process(updates, /*got_new_encryption_requirements=*/false); } const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_EQ(1u, bookmark_bar_node->children().size()); const bookmarks::BookmarkNode* node = bookmark_bar_node->children().front().get(); EXPECT_EQ(base::UTF16ToUTF8(node->GetTitle()), kNewTitle); EXPECT_TRUE(entity->IsUnsynced()); // Check reupload on conflict when specifics matches. updates.back().response_version++; { BookmarkRemoteUpdatesHandler updates_handler(bookmark_model(), favicon_service(), tracker()); updates_handler.Process(updates, /*got_new_encryption_requirements=*/false); } ASSERT_EQ(1u, bookmark_bar_node->children().size()); EXPECT_EQ(bookmark_bar_node->children().front().get(), node); EXPECT_EQ(base::UTF16ToUTF8(node->GetTitle()), kNewTitle); EXPECT_TRUE(entity->IsUnsynced()); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldIncrementSequenceNumberOnUpdate) { base::test::ScopedFeatureList override_features; override_features.InitAndEnableFeature( switches::kSyncReuploadBookmarkFullTitles); const std::string kId = "id"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); const std::string kTitle = "title"; const std::string kRemoteTitle = "New title"; syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kTitle, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates.back().entity.specifics.mutable_bookmark()->set_full_title(kTitle); { BookmarkRemoteUpdatesHandler updates_handler(bookmark_model(), favicon_service(), tracker()); updates_handler.Process(updates, /*got_new_encryption_requirements=*/false); } const SyncedBookmarkTracker::Entity* entity = tracker()->GetEntityForSyncId(kId); ASSERT_THAT(entity, NotNull()); ASSERT_FALSE(entity->IsUnsynced()); // Check reupload on conflict. updates.back() .entity.specifics.mutable_bookmark() ->set_legacy_canonicalized_title(kRemoteTitle); updates.back().entity.specifics.mutable_bookmark()->clear_full_title(); updates.back().response_version++; { BookmarkRemoteUpdatesHandler updates_handler(bookmark_model(), favicon_service(), tracker()); updates_handler.Process(updates, /*got_new_encryption_requirements=*/false); } const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); ASSERT_EQ(1u, bookmark_bar_node->children().size()); const bookmarks::BookmarkNode* node = bookmark_bar_node->children().front().get(); EXPECT_EQ(node->GetTitle(), base::UTF8ToUTF16(kRemoteTitle)); EXPECT_TRUE(entity->IsUnsynced()); } TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldReuploadBookmarkOnEmptyGuid) { base::test::ScopedFeatureList override_features; override_features.InitAndEnableFeature( switches::kSyncReuploadBookmarkFullTitles); const std::string kFolder1Title = "folder1"; const std::string kFolder2Title = "folder2"; const std::string kFolder1Id = "Folder1Id"; const std::string kFolder2Id = "Folder2Id"; syncer::UpdateResponseDataList updates; updates.push_back(CreateUpdateResponseData( /*server_id=*/kFolder1Id, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*title=*/kFolder1Title, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); // Remove GUID field for the first item only. updates.back().entity.is_bookmark_guid_in_specifics_preprocessed = true; updates.push_back(CreateUpdateResponseData( /*server_id=*/kFolder2Id, /*parent_id=*/kBookmarkBarId, /*guid=*/base::GUID::GenerateRandomV4(), /*title=*/kFolder2Title, /*is_deletion=*/false, /*version=*/0, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); ASSERT_FALSE( updates.back().entity.is_bookmark_guid_in_specifics_preprocessed); updates_handler()->Process(std::move(updates), /*got_new_encryption_requirements=*/false); const SyncedBookmarkTracker::Entity* entity1 = tracker()->GetEntityForSyncId(kFolder1Id); const SyncedBookmarkTracker::Entity* entity2 = tracker()->GetEntityForSyncId(kFolder2Id); ASSERT_THAT(entity1, NotNull()); ASSERT_THAT(entity2, NotNull()); EXPECT_TRUE(entity1->IsUnsynced()); EXPECT_FALSE(entity2->IsUnsynced()); } // Tests that the reflection which doesn't have GUID in specifics will be // reuploaded. TEST_F(BookmarkRemoteUpdatesHandlerWithInitialMergeTest, ShouldReuploadBookmarkOnEmptyGuidForReflection) { base::test::ScopedFeatureList override_features; override_features.InitAndEnableFeature( switches::kSyncReuploadBookmarkFullTitles); const std::string kFolderTitle = "folder"; const std::string kFolderId = "FolderId"; const base::GUID kGuid = base::GUID::GenerateRandomV4(); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model()->bookmark_bar_node(); const bookmarks::BookmarkNode* node = bookmark_model()->AddFolder( bookmark_bar_node, /*index=*/0, base::UTF8ToUTF16(kFolderTitle), /*meta_info=*/nullptr, kGuid); sync_pb::BookmarkModelMetadata model_metadata = CreateMetadataForPermanentNodes(bookmark_model()); sync_pb::BookmarkMetadata* node_metadata = model_metadata.add_bookmarks_metadata(); *node_metadata = CreateNodeMetadata(node, kFolderId, syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix())); const int64_t server_version = node_metadata->metadata().server_version(); std::unique_ptr<SyncedBookmarkTracker> tracker = SyncedBookmarkTracker::CreateFromBookmarkModelAndMetadata( bookmark_model(), std::move(model_metadata)); ASSERT_THAT(tracker, NotNull()); ASSERT_EQ(4u, tracker->GetAllEntities().size()); const SyncedBookmarkTracker::Entity* entity = tracker->GetEntityForSyncId(kFolderId); ASSERT_THAT(entity, NotNull()); ASSERT_FALSE(entity->IsUnsynced()); syncer::UpdateResponseDataList updates; // Create an update with the same server version as local entity has. This // will simulate processing of reflection. updates.push_back(CreateUpdateResponseData( /*server_id=*/kFolderId, /*parent_id=*/kBookmarkBarId, /*guid=*/kGuid, /*title=*/kFolderTitle, /*is_deletion=*/false, /*version=*/server_version, /*unique_position=*/ syncer::UniquePosition::InitialPosition( syncer::UniquePosition::RandomSuffix()))); updates.back().entity.is_bookmark_guid_in_specifics_preprocessed = true; BookmarkRemoteUpdatesHandler updates_handler( bookmark_model(), favicon_service(), tracker.get()); updates_handler.Process(std::move(updates), /*got_new_encryption_requirements=*/false); ASSERT_EQ(entity, tracker->GetEntityForSyncId(kFolderId)); EXPECT_TRUE(entity->IsUnsynced()); } TEST(BookmarkRemoteUpdatesHandlerTest, ShouldComputeRightChildNodeIndexForEmptyParent) { const std::string suffix = syncer::UniquePosition::RandomSuffix(); const syncer::UniquePosition pos1 = syncer::UniquePosition::InitialPosition(suffix); std::unique_ptr<bookmarks::BookmarkModel> bookmark_model = bookmarks::TestBookmarkClient::CreateModel(); std::unique_ptr<SyncedBookmarkTracker> tracker = SyncedBookmarkTracker::CreateFromBookmarkModelAndMetadata( bookmark_model.get(), CreateMetadataForPermanentNodes(bookmark_model.get())); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model->bookmark_bar_node(); // Should always return 0 for any UniquePosition in the initial state. EXPECT_EQ(0u, BookmarkRemoteUpdatesHandler::ComputeChildNodeIndexForTest( bookmark_bar_node, pos1.ToProto(), tracker.get())); } TEST(BookmarkRemoteUpdatesHandlerTest, ShouldComputeRightChildNodeIndex) { std::unique_ptr<bookmarks::BookmarkModel> bookmark_model = bookmarks::TestBookmarkClient::CreateModel(); const bookmarks::BookmarkNode* bookmark_bar_node = bookmark_model->bookmark_bar_node(); const std::string suffix = syncer::UniquePosition::RandomSuffix(); const syncer::UniquePosition pos1 = syncer::UniquePosition::InitialPosition(suffix); const syncer::UniquePosition pos2 = syncer::UniquePosition::After(pos1, suffix); const syncer::UniquePosition pos3 = syncer::UniquePosition::After(pos2, suffix); // Create 3 nodes using remote update. const bookmarks::BookmarkNode* node1 = bookmark_model->AddFolder( bookmark_bar_node, /*index=*/0, /*title=*/std::u16string()); const bookmarks::BookmarkNode* node2 = bookmark_model->AddFolder( bookmark_bar_node, /*index=*/1, /*title=*/std::u16string()); const bookmarks::BookmarkNode* node3 = bookmark_model->AddFolder( bookmark_bar_node, /*index=*/2, /*title=*/std::u16string()); sync_pb::BookmarkModelMetadata model_metadata = CreateMetadataForPermanentNodes(bookmark_model.get()); *model_metadata.add_bookmarks_metadata() = CreateNodeMetadata(node1, "folder1_id", pos1); *model_metadata.add_bookmarks_metadata() = CreateNodeMetadata(node2, "folder2_id", pos2); *model_metadata.add_bookmarks_metadata() = CreateNodeMetadata(node3, "folder3_id", pos3); std::unique_ptr<SyncedBookmarkTracker> tracker = SyncedBookmarkTracker::CreateFromBookmarkModelAndMetadata( bookmark_model.get(), std::move(model_metadata)); // Check for the same position as existing bookmarks have. In practice this // shouldn't happen. EXPECT_EQ(1u, BookmarkRemoteUpdatesHandler::ComputeChildNodeIndexForTest( bookmark_bar_node, pos1.ToProto(), tracker.get())); EXPECT_EQ(2u, BookmarkRemoteUpdatesHandler::ComputeChildNodeIndexForTest( bookmark_bar_node, pos2.ToProto(), tracker.get())); EXPECT_EQ(3u, BookmarkRemoteUpdatesHandler::ComputeChildNodeIndexForTest( bookmark_bar_node, pos3.ToProto(), tracker.get())); EXPECT_EQ(0u, BookmarkRemoteUpdatesHandler::ComputeChildNodeIndexForTest( bookmark_bar_node, syncer::UniquePosition::Before(pos1, suffix).ToProto(), tracker.get())); EXPECT_EQ(1u, BookmarkRemoteUpdatesHandler::ComputeChildNodeIndexForTest( bookmark_bar_node, syncer::UniquePosition::Between(/*before=*/pos1, /*after=*/pos2, suffix) .ToProto(), tracker.get())); EXPECT_EQ(2u, BookmarkRemoteUpdatesHandler::ComputeChildNodeIndexForTest( bookmark_bar_node, syncer::UniquePosition::Between(/*before=*/pos2, /*after=*/pos3, suffix) .ToProto(), tracker.get())); EXPECT_EQ(3u, BookmarkRemoteUpdatesHandler::ComputeChildNodeIndexForTest( bookmark_bar_node, syncer::UniquePosition::After(pos3, suffix).ToProto(), tracker.get())); } } // namespace } // namespace sync_bookmarks
39.803598
80
0.675581
[ "vector", "model" ]
11bea5f040d3b3beef81e63e664c32a8a9cd7cb2
7,817
hpp
C++
libs/storage/test/core/merkle/generate_tree.hpp
NilFoundation/crypto3-fil-proofs
1fd78ad608278a1ed62fb29b0a077347b74a55f1
[ "MIT" ]
null
null
null
libs/storage/test/core/merkle/generate_tree.hpp
NilFoundation/crypto3-fil-proofs
1fd78ad608278a1ed62fb29b0a077347b74a55f1
[ "MIT" ]
4
2021-09-06T13:07:46.000Z
2021-11-16T12:38:09.000Z
libs/storage/test/core/merkle/generate_tree.hpp
NilFoundation/crypto3-fil-proofs
1fd78ad608278a1ed62fb29b0a077347b74a55f1
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------// // MIT License // // Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation> // Copyright (c) 2020-2021 Nikita Kaskov <nemo@nil.foundation> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //---------------------------------------------------------------------------// #ifndef FILECOIN_TEST_STORAGE_PROOFS_CORE_MERKLE_GENERATE_TREE_HPP #define FILECOIN_TEST_STORAGE_PROOFS_CORE_MERKLE_GENERATE_TREE_HPP #include <vector> #include <boost/filesystem.hpp> #include <boost/optional.hpp> #include <nil/filecoin/storage/proofs/core/sector.hpp> namespace nil { namespace filecoin { namespace merkletree { namespace detail { template<typename MerkleTreeType> std::size_t get_base_tree_leafs(std::size_t base_tree_size) { return get_merkle_tree_leafs(base_tree_size, MerkleTreeType::base_arity); } template<typename MerkleTreeType, typename UniformRandomGenerator> std::tuple<std::vector<std::uint8_t>, MerkleTreeType> generate_base_tree(UniformRandomGenerator &rng, std::size_t nodes, boost::optional<const boost::filesystem::path &> temp_path) { const auto elements = (0..nodes).map(| _ | typename MerkleTreeType::hash_type::digest_type::random(rng)).collect::<Vec<_>>(); std::vector<std::uint8_t> data; for (el : elements) { data.extend_from_slice(el); } if (temp_path) { std::uint64_t id = rng.gen(); boost::filesystem::path replica_path = temp_path.join(std::format("replica-path-{}", id)); StoreConfig config(*temp_path, std::format("test-lc-tree-{}", id), default_rows_to_discard(nodes, MerkleTreeType::base_arity)); auto tree = MerkleTreeWrapper::try_from_iter_with_config(elements.iter().map(| v | (Ok(*v))), config).unwrap(); // Write out the replica data. auto f = std::fs::File::create(&replica_path).unwrap(); f.write_all(&data).unwrap(); // Beware: evil dynamic downcasting RUST MAGIC down below. use std::any::Any; if (const auto Some(lc_tree) = Any::downcast_mut::<merkle::MerkleTree <typename MerkleTreeType::hash_type::digest_type, <typename MerkleTreeType::hash_type>::Function, merkletree::store::LevelCacheStore <typename MerkleTreeType::hash_type::digest_type, std::fs::File, >, MerkleTreeType::base_arity, MerkleTreeType::sub_tree_arity, MerkleTreeType::top_tree_arity, >, > (tree.inner) ) { lc_tree.set_external_reader_path(&replica_path).unwrap(); } (data, tree) } else { (data, MerkleTreeWrapper::try_from_iter(elements.iter().map(| v | Ok(*v))).unwrap()) } } template<typename MerkleTreeType, typename UniformRandomGenerator> std::tuple<std::vector<std::uint8_t>, MerkleTreeType> generate_sub_tree(UniformRandomGenerator &rng, std::size_t nodes, boost::optional<const boost::filesystem::path &> temp_path) { std::size_t base_tree_count = MerkleTreeType::sub_tree_arity; std::size_t base_tree_size = nodes / base_tree_count; std::vector<MerkleTreeType> trees(base_tree_count); std::vector<std::uint8_t> data; for (int i = 0; i < base_tree_count) { const auto(inner_data, tree) = generate_base_tree<UniformRandomGenerator, MerkleTreeType>(rng, base_tree_size, temp_path); trees.push_back(tree); data.extend(inner_data); } return std::make_tuple(data, trees); } } // namespace detail /// Only used for testing, but can't cfg-test it as that stops exports. template<typename MerkleTreeType, typename UniformRandomGenerator = boost::random::mt19937> std::tuple<std::vector<std::uint8_t>, MerkleTreeType> generate_tree(UniformRandomGenerator &rng, std::size_t nodes, boost::optional<const boost::filesystem::path &> temp_path) { std::size_t sub_tree_arity = MerkleTreeType::sub_tree_arity; std::size_t top_tree_arity = MerkleTreeType::top_tree_arity; if (top_tree_arity > 0) { BOOST_ASSERT_MSG(sub_tree_arity != 0, "malformed tree with TopTreeArity > 0 and SubTreeARity == 0"); std::vector<MerkleTreeType> sub_trees(top_tree_arity); std::vector<std::uint8_t> data; for (int i = 0; i < top_tree_arity; i++) { const auto(inner_data, tree) = generate_sub_tree< UniformRandomGenerator, MerkleTreeWrapper<typename MerkleTreeType::hash_type, MerkleTreeType::Store, MerkleTreeType::base_arity, MerkleTreeType::sub_tree_arity, typenum::U0>>(rng, nodes / top_tree_arity, temp_path.clone()); sub_trees.push(tree); data.extend(inner_data); } return std::make_tuple(data, MerkleTreeWrapper::from_sub_trees(sub_trees)); } else if (sub_tree_arity > 0) { return generate_sub_tree<UniformRandomGenerator, MerkleTreeType>(rng, nodes, temp_path); } else { return generate_base_tree<UniformRandomGenerator, MerkleTreeType>(rng, nodes, temp_path); } } } // namespace merkletree } // namespace filecoin } // namespace nil #endif // FILECOIN_TEST_STORAGE_PROOFS_CORE_MERKLE_GENERATE_TREE_HPP
52.113333
132
0.551234
[ "vector" ]
11c84ced08d51033a329385c84e4f20f5fdd62d8
21,185
cpp
C++
src/core/ObjectFactory.cpp
khangthk/ShellAnything
864d6940e024f30e4276782349e45b81e3feae2a
[ "MIT" ]
null
null
null
src/core/ObjectFactory.cpp
khangthk/ShellAnything
864d6940e024f30e4276782349e45b81e3feae2a
[ "MIT" ]
null
null
null
src/core/ObjectFactory.cpp
khangthk/ShellAnything
864d6940e024f30e4276782349e45b81e3feae2a
[ "MIT" ]
null
null
null
/********************************************************************************** * MIT License * * Copyright (c) 2018 Antoine Beauchamp * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *********************************************************************************/ #include "ObjectFactory.h" #include "Configuration.h" #include "Menu.h" #include "Validator.h" #include "ActionClipboard.h" #include "ActionExecute.h" #include "ActionStop.h" #include "ActionFile.h" #include "ActionPrompt.h" #include "ActionProperty.h" #include "ActionOpen.h" #include "ActionMessage.h" #include "rapidassist/strings.h" #include "rapidassist/unicode.h" using namespace tinyxml2; namespace shellanything { static const std::string NODE_MENU = "menu"; static const std::string NODE_ICON = "icon"; static const std::string NODE_VALIDITY = "validity"; static const std::string NODE_VISIBILITY = "visibility"; static const std::string NODE_DEFAULTSETTINGS = "default"; static const std::string NODE_ACTION_CLIPBOARD = "clipboard"; static const std::string NODE_ACTION_EXEC = "exec"; static const std::string NODE_ACTION_STOP = "stop"; static const std::string NODE_ACTION_FILE = "file"; static const std::string NODE_ACTION_PROMPT = "prompt"; static const std::string NODE_ACTION_PROPERTY = "property"; static const std::string NODE_ACTION_OPEN = "open"; static const std::string NODE_ACTION_MESSAGE = "message"; ObjectFactory::ObjectFactory() { } ObjectFactory::~ObjectFactory() { } ObjectFactory & ObjectFactory::GetInstance() { static ObjectFactory _instance; return _instance; } typedef std::vector<const XMLElement *> ElementPtrList; ElementPtrList GetChildNodes(const XMLElement* element, const std::string & name) { ElementPtrList elements; if (!element) return elements; const XMLElement* current = element->FirstChildElement(name.c_str()); while (current) { //found a new node elements.push_back(current); //next node current = current->NextSiblingElement(name.c_str()); } return elements; } bool ParseAttribute(const XMLElement* element, const char * attr_name, bool is_optional, bool allow_empty_values, std::string & attr_value, std::string & error) { if (element == NULL) { error = "XMLElement is NULL"; return false; } attr_value = ""; const XMLAttribute * attr_node = element->FindAttribute(attr_name); if (is_optional && !attr_node) { //failed parsing but its not an error return false; } else if (!attr_node) { error = "Node '" + std::string(element->Name()) + "' at line " + ra::strings::ToString(element->GetLineNum()) + " is missing attribute '" + std::string(attr_name) + "'."; return false; } attr_value = attr_node->Value(); if (!allow_empty_values && attr_value.empty()) { error = "Node '" + std::string(element->Name()) + "' at line " + ra::strings::ToString(element->GetLineNum()) + " have attribute '" + std::string(attr_name) + "' value empty."; return false; } return true; } bool ParseAttribute(const XMLElement* element, const char * attr_name, bool is_optional, bool allow_empty_values, int & attr_value, std::string & error) { std::string str_value; if (!ParseAttribute(element, attr_name, is_optional, allow_empty_values, str_value, error)) return false; //error is already set //convert string to int int int_value = -1; if (!ra::strings::Parse(str_value, int_value)) { //failed parsing error << "Failed parsing attribute '" << attr_name << "' of node '" << element->Name() << "'."; return false; } //valid attr_value = int_value; return true; } Validator * ObjectFactory::ParseValidator(const tinyxml2::XMLElement * element, std::string & error) { if (element == NULL) { error = "XMLElement is NULL"; return NULL; } if (NODE_VALIDITY != element->Name() && NODE_VISIBILITY != element->Name() && NODE_ACTION_STOP != element->Name()) { error = "Node '" + std::string(element->Name()) + "' at line " + ra::strings::ToString(element->GetLineNum()) + " is not a <validity> or <visibility> node"; return NULL; } Validator * validator = new Validator(); //parse class std::string class_; if (ParseAttribute(element, "class", true, true, class_, error)) { if (!class_.empty()) { validator->SetClass(class_); } } //parse pattern std::string pattern; if (ParseAttribute(element, "pattern", true, true, pattern, error)) { if (!pattern.empty()) { validator->SetPattern(pattern); } } //parse exprtk std::string exprtk; if (ParseAttribute(element, "exprtk", true, true, exprtk, error)) { if (!exprtk.empty()) { validator->SetExprtk(exprtk); } } //parse maxfiles int maxfiles = -1; if (ParseAttribute(element, "maxfiles", true, true, maxfiles, error)) { validator->SetMaxFiles(maxfiles); } //parse maxfolders int maxfolders = -1; if (ParseAttribute(element, "maxfolders", true, true, maxfolders, error)) { validator->SetMaxDirectories(maxfolders); } //parse fileextensions std::string fileextensions; if (ParseAttribute(element, "fileextensions", true, true, fileextensions, error)) { if (!fileextensions.empty()) { validator->SetFileExtensions(fileextensions); } } //parse exists std::string exists; if (ParseAttribute(element, "exists", true, true, exists, error)) { if (!exists.empty()) { validator->SetFileExists(exists); } } //parse properties std::string properties; if (ParseAttribute(element, "properties", true, true, properties, error)) { if (!properties.empty()) { validator->SetProperties(properties); } } //parse inverse std::string inverse; if (ParseAttribute(element, "inverse", true, true, inverse, error)) { if (!inverse.empty()) { validator->SetInserve(inverse); } } //parse istrue std::string istrue; if (ParseAttribute(element, "istrue", true, true, istrue, error)) { if (!istrue.empty()) { validator->SetIsTrue(istrue); } } //parse isfalse std::string isfalse; if (ParseAttribute(element, "isfalse", true, true, isfalse, error)) { if (!isfalse.empty()) { validator->SetIsFalse(isfalse); } } //parse isempty std::string isempty; if (ParseAttribute(element, "isempty", true, true, isempty, error)) { if (!isempty.empty()) { validator->SetIsEmpty(isempty); } } //success return validator; } Action * ObjectFactory::ParseAction(const XMLElement* element, std::string & error) { if (element == NULL) { error = "XMLElement is NULL"; return NULL; } //temporary parsed attribute values std::string tmp_str; int tmp_int = -1; if (NODE_ACTION_CLIPBOARD == element->Name()) { ActionClipboard * action = new ActionClipboard(); //parse value tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "value", false, true, tmp_str, error)) { action->SetValue(tmp_str); } //done parsing return action; } else if (NODE_ACTION_EXEC == element->Name()) { ActionExecute * action = new ActionExecute(); //parse path tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "path", false, true, tmp_str, error)) { action->SetPath(tmp_str); } //parse arguments tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "arguments", true, true, tmp_str, error)) { action->SetArguments(tmp_str); } //parse basedir tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "basedir", true, true, tmp_str, error)) { action->SetBaseDir(tmp_str); } //parse verb tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "verb", true, true, tmp_str, error)) { action->SetVerb(tmp_str); } //done parsing return action; } else if (NODE_ACTION_STOP == element->Name()) { ActionStop* action = new ActionStop(); //parse like a Validator Validator* validator = ObjectFactory::GetInstance().ParseValidator(element, error); if (validator == NULL) { delete action; return NULL; } action->SetValidator(validator); //done parsing return action; } else if (NODE_ACTION_FILE == element->Name()) { ActionFile * action = new ActionFile(); //parse path tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "path", false, true, tmp_str, error)) { action->SetPath(tmp_str); } //parse text const char * text = element->GetText(); if (text) { action->SetText(text); } //parse encoding tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "encoding", true, true, tmp_str, error)) { action->SetEncoding(tmp_str); } //done parsing return action; } else if (NODE_ACTION_PROMPT == element->Name()) { ActionPrompt * action = new ActionPrompt(); //parse name tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "name", false, true, tmp_str, error)) { action->SetName(tmp_str); } //parse title tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "title", false, true, tmp_str, error)) { action->SetTitle(tmp_str); } //parse default tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "default", true, true, tmp_str, error)) { action->SetDefault(tmp_str); } //parse type tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "type", true, true, tmp_str, error)) { action->SetType(tmp_str); } //parse valueyes tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "valueyes", true, true, tmp_str, error)) { action->SetValueYes(tmp_str); } //parse valueno tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "valueno", true, true, tmp_str, error)) { action->SetValueNo(tmp_str); } //done parsing return action; } else if (NODE_ACTION_PROPERTY == element->Name()) { ActionProperty * action = new ActionProperty(); //parse name tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "name", false, true, tmp_str, error)) { action->SetName(tmp_str); } //parse value tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "value", true, true, tmp_str, error)) { action->SetValue(tmp_str); } //parse exprtk tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "exprtk", true, true, tmp_str, error)) { action->SetExprtk(tmp_str); } //done parsing return action; } else if (NODE_ACTION_OPEN == element->Name()) { ActionOpen * action = new ActionOpen(); //parse path tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "path", false, true, tmp_str, error)) { action->SetPath(tmp_str); } //done parsing return action; } else if (NODE_ACTION_MESSAGE == element->Name()) { ActionMessage * action = new ActionMessage(); //parse title tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "title", false, true, tmp_str, error)) { action->SetTitle(tmp_str); } //parse caption tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "caption", false, true, tmp_str, error)) { action->SetCaption(tmp_str); } //parse icon tmp_str = ""; tmp_int = -1; if (ParseAttribute(element, "icon", true, true, tmp_str, error)) { action->SetIcon(tmp_str); } //done parsing return action; } else { error = "Node '" + std::string(element->Name()) + "' at line " + ra::strings::ToString(element->GetLineNum()) + " is an unknown type."; return NULL; } //invalid return NULL; } Menu * ObjectFactory::ParseMenu(const XMLElement* element, std::string & error) { if (element == NULL) { error = "XMLElement is NULL"; return NULL; } std::string xml_name = element->Name(); if (xml_name != NODE_MENU) { error = "Node '" + std::string(element->Name()) + "' at line " + ra::strings::ToString(element->GetLineNum()) + " is an unknown type."; return NULL; } //at this step the <menu> is valid Menu * menu = new Menu(); //parse separator std::string menu_separator; bool have_separator = ParseAttribute(element, "separator", true, true, menu_separator, error); bool separator_parsed = false; if (have_separator) { //try to parse this menu separator as a boolean bool is_horizontal_separator = false; separator_parsed = ra::strings::Parse(menu_separator, is_horizontal_separator); if (separator_parsed && is_horizontal_separator) { menu->SetSeparator(true); return menu; } //try to parse as a string menu_separator = ra::strings::Lowercase(menu_separator); if (menu_separator == "horizontal") { menu->SetSeparator(true); return menu; } else if (menu_separator == "vertical" || menu_separator == "column") { menu->SetColumnSeparator(true); return menu; } } //parse name std::string menu_name; if (!ParseAttribute(element, "name", false, false, menu_name, error)) { delete menu; return NULL; } menu->SetName(menu_name); //parse description std::string menu_desc; if (!ParseAttribute(element, "description", true, true, menu_desc, error)) { menu->SetDescription(menu_desc); } //parse icon std::string icon_path; if (ParseAttribute(element, "icon", true, true, icon_path, error)) { Icon icon; icon.SetPath(icon_path); menu->SetIcon(icon); } //parse maxlength std::string maxlength_str; if (ParseAttribute(element, "maxlength", true, true, maxlength_str, error)) { int maxlength = 0; if (ra::strings::Parse(maxlength_str, maxlength) && maxlength > 0) { menu->SetNameMaxLength(maxlength); } } ElementPtrList elements; //temporary xml element containers //find <validity> node under <menu> elements = GetChildNodes(element, NODE_VALIDITY); for(size_t i=0; i<elements.size(); i++) { Validator * validator = ObjectFactory::GetInstance().ParseValidator(elements[i], error); if (validator == NULL) { delete menu; return NULL; } //add the new validator menu->AddValidity(validator); } //find <visibility> node under <menu> elements = GetChildNodes(element, NODE_VISIBILITY); for(size_t i=0; i<elements.size(); i++) { Validator * validator = ObjectFactory::GetInstance().ParseValidator(elements[i], error); if (validator == NULL) { delete menu; return NULL; } //add the new validator menu->AddVisibility(validator); } //find <actions> node under <menu> const XMLElement* xml_actions = element->FirstChildElement("actions"); if (xml_actions) { //actions must be read in order. //find <clipboard>, <exec>, <prompt>, <property> or <open> nodes under <actions> const XMLElement* xml_action = xml_actions->FirstChildElement(); while (xml_action) { //found a new action node Action * action = ObjectFactory::GetInstance().ParseAction(xml_action, error); if (action == NULL) { delete menu; return NULL; } //add the new action node menu->AddAction(action); //next action node xml_action = xml_action->NextSiblingElement(); } } //find <menu> node under <menu> elements = GetChildNodes(element, NODE_MENU); for(size_t i=0; i<elements.size(); i++) { Menu * submenu = ObjectFactory::GetInstance().ParseMenu(elements[i], error); if (submenu == NULL) { delete menu; return NULL; } menu->AddMenu(submenu); } //find <icon> node under <menu> elements = GetChildNodes(element, "icon"); for(size_t i=0; i<elements.size(); i++) { Icon icon; if (!ObjectFactory::GetInstance().ParseIcon(elements[i], icon, error)) { //failed icon parsing delete menu; return NULL; } menu->SetIcon(icon); } return menu; } bool ObjectFactory::ParseIcon(const tinyxml2::XMLElement * element, Icon & icon, std::string & error) { if (element == NULL) { error = "XMLElement is NULL"; return false; } std::string xml_name = element->Name(); if (xml_name != NODE_ICON) { error = "Node '" + std::string(element->Name()) + "' at line " + ra::strings::ToString(element->GetLineNum()) + " is an unknown type."; return NULL; } //parse path std::string icon_path; bool hasPath = ParseAttribute(element, "path", true, true, icon_path, error); //parse fileextension std::string icon_fileextension; bool hasFileExtension = ParseAttribute(element, "fileextension", true, true, icon_fileextension, error); if (!hasPath && !hasFileExtension) { //failed parsing return false; } Icon result; if (hasPath) result.SetPath(icon_path); if (hasFileExtension) result.SetFileExtension(icon_fileextension); //parse index int icon_index = -1; if (ParseAttribute(element, "index", true, true, icon_index, error)) { result.SetIndex(icon_index); } //success icon = result; return true; } DefaultSettings * ObjectFactory::ParseDefaults(const XMLElement* element, std::string & error) { if (element == NULL) { error = "XMLElement is NULL"; return NULL; } std::string xml_name = element->Name(); if (xml_name != NODE_DEFAULTSETTINGS) { error = "Node '" + std::string(element->Name()) + "' at line " + ra::strings::ToString(element->GetLineNum()) + " is an unknown type."; return NULL; } DefaultSettings * defaults = new DefaultSettings(); ElementPtrList elements; //temporary xml element containers //find <property> node under <default> elements = GetChildNodes(element, NODE_ACTION_PROPERTY); for(size_t i=0; i<elements.size(); i++) { const tinyxml2::XMLElement * element = elements[i]; //found a new action node Action * abstract_action = ObjectFactory::GetInstance().ParseAction(element, error); if (abstract_action) { //filter out all type of actions except ActionProperty actions ActionProperty * property_action = dynamic_cast<ActionProperty *>(abstract_action); if (property_action != NULL) { //add the new action node defaults->AddAction(property_action); } else { delete abstract_action; } } } //do not return a DefaultSettings instance if empty. if (defaults->GetActions().empty()) { delete defaults; return NULL; } return defaults; } } //namespace shellanything
26.18665
182
0.597309
[ "vector" ]
11cdad95174dd2855b543605d42349d8f48298fd
14,182
cpp
C++
fmi.cpp
jltsiren/bwt-merge
273a716f8e3070c65922bf62eca932a85d5be5eb
[ "MIT" ]
23
2015-07-16T12:26:52.000Z
2020-05-31T23:23:13.000Z
fmi.cpp
jltsiren/bwt-merge
273a716f8e3070c65922bf62eca932a85d5be5eb
[ "MIT" ]
3
2015-11-09T16:05:07.000Z
2019-06-24T15:00:05.000Z
fmi.cpp
jltsiren/bwt-merge
273a716f8e3070c65922bf62eca932a85d5be5eb
[ "MIT" ]
4
2015-12-06T20:49:51.000Z
2019-06-20T17:40:07.000Z
/* Copyright (c) 2015 Genome Research Ltd. Author: Jouni Siren <jouni.siren@iki.fi> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stack> #include "fmi.h" namespace bwtmerge { //------------------------------------------------------------------------------ FMI::FMI() { } FMI::FMI(const FMI& source) { this->copy(source); } FMI::FMI(FMI&& source) { *this = std::move(source); } FMI::~FMI() { } void FMI::copy(const FMI& source) { this->bwt = source.bwt; this->alpha = source.alpha; } void FMI::swap(FMI& source) { if(this != &source) { this->bwt.swap(source.bwt); this->alpha.swap(source.alpha); } } FMI& FMI::operator=(const FMI& source) { if(this != &source) { this->copy(source); } return *this; } FMI& FMI::operator=(FMI&& source) { if(this != &source) { this->bwt = std::move(source.bwt); this->alpha = std::move(source.alpha); } return *this; } FMI::size_type FMI::serialize(std::ostream& out, sdsl::structure_tree_node* v, std::string name) const { sdsl::structure_tree_node* child = sdsl::structure_tree::add_child(v, name, sdsl::util::class_name(*this)); size_type written_bytes = 0; written_bytes += this->bwt.serialize(out, child, "bwt"); written_bytes += this->alpha.serialize(out, child, "alpha"); sdsl::structure_tree::add_size(child, written_bytes); return written_bytes; } void FMI::load(std::istream& in) { this->bwt.load(in); this->alpha.load(in); } //------------------------------------------------------------------------------ template<> void FMI::serialize<NativeFormat>(const std::string& filename) const { std::ofstream out(filename.c_str(), std::ios_base::binary); if(!out) { std::cerr << "FMI::serialize(): Cannot open output file " << filename << std::endl; return; } this->serialize(out); out.close(); } template<> void FMI::load<NativeFormat>(const std::string& filename) { std::ifstream in(filename.c_str(), std::ios_base::binary); if(!in) { std::cerr << "FMI::load(): Cannot open input file " << filename << std::endl; std::exit(EXIT_FAILURE); } this->load(in); in.close(); } //------------------------------------------------------------------------------ struct MergeBuffer { typedef RLArray<BlockArray> buffer_type; typedef RLArray<BlockArray>::run_type run_type; MergeParameters parameters; std::mutex buffer_lock; std::vector<buffer_type> merge_buffers; std::mutex ra_lock; RankArray ra; size_type ra_values, ra_bytes; size_type size; MergeBuffer(size_type _size, const MergeParameters& _parameters) : parameters(_parameters), merge_buffers(_parameters.merge_buffers), ra_values(0), ra_bytes(0), size(_size) { } ~MergeBuffer() {} void write(buffer_type& buffer) { if(buffer.empty()) { return; } std::string filename; size_type buffer_values = buffer.values(), buffer_bytes = buffer.bytes(); { std::lock_guard<std::mutex> lock(this->ra_lock); filename = tempFile(this->parameters.tempPrefix()); this->ra.filenames.push_back(filename); this->ra.run_counts.push_back(buffer.size()); this->ra.value_counts.push_back(buffer.values()); } buffer.write(filename); buffer.clear(); #ifdef VERBOSE_STATUS_INFO double ra_done, ra_gb; #endif { std::lock_guard<std::mutex> lock(this->ra_lock); this->ra_values += buffer_values; this->ra_bytes += buffer_bytes + sizeof(size_type); #ifdef VERBOSE_STATUS_INFO ra_done = (100.0 * this->ra_values) / this->size; ra_gb = inGigabytes(this->ra_bytes); #endif } #ifdef VERBOSE_STATUS_INFO { std::lock_guard<std::mutex> lock(Parallel::stderr_access); std::cerr << "buildRA(): Thread " << std::this_thread::get_id() << ": Added the values to the rank array" << std::endl; std::cerr << "buildRA(): " << ra_done << "% done; RA size " << ra_gb << " GB" << std::endl; } #endif } void flush() { for(size_type i = 1; i < this->merge_buffers.size(); i++) { this->merge_buffers[i] = buffer_type(this->merge_buffers[i], this->merge_buffers[i - 1]); } #ifdef VERBOSE_STATUS_INFO { std::lock_guard<std::mutex> lock(Parallel::stderr_access); std::cerr << "buildRA(): Flushing " << this->merge_buffers[this->merge_buffers.size() - 1].values() << " values to disk" << std::endl; } #endif this->write(this->merge_buffers[this->merge_buffers.size() - 1]); } }; void mergeRA(MergeBuffer& mb, MergeBuffer::buffer_type& thread_buffer, std::vector<MergeBuffer::run_type>& run_buffer, bool force) { MergeBuffer::buffer_type temp_buffer(run_buffer); run_buffer.clear(); thread_buffer = MergeBuffer::buffer_type(thread_buffer, temp_buffer); if(!force && thread_buffer.bytes() < mb.parameters.thread_buffer_size) { return; } #ifdef VERBOSE_STATUS_INFO { std::lock_guard<std::mutex> lock(Parallel::stderr_access); std::cerr << "buildRA(): Thread " << std::this_thread::get_id() << ": Adding " << thread_buffer.values() << " values to the merge buffer" << std::endl; } #endif for(size_type i = 0; i < mb.merge_buffers.size(); i++) { bool done = false; { std::lock_guard<std::mutex> lock(mb.buffer_lock); if(mb.merge_buffers[i].empty()) { thread_buffer.swap(mb.merge_buffers[i]); done = true; } else { temp_buffer.swap(mb.merge_buffers[i]); } } if(done) { #ifdef VERBOSE_STATUS_INFO std::lock_guard<std::mutex> lock(Parallel::stderr_access); std::cerr << "buildRA(): Thread " << std::this_thread::get_id() << ": Added the values to buffer " << i << std::endl; #endif return; } thread_buffer = MergeBuffer::buffer_type(thread_buffer, temp_buffer); } mb.write(thread_buffer); } //------------------------------------------------------------------------------ struct MergePosition { size_type a_pos; range_type b_range; MergePosition() : a_pos(0), b_range(0, 0) {} MergePosition(size_type a, size_type b) : a_pos(a), b_range(b, b) {} MergePosition(size_type pos, range_type range) : a_pos(pos), b_range(range) {} MergePosition(size_type pos, size_type sp, size_type ep) : a_pos(pos), b_range(sp, ep) {} }; void buildRA(ParallelLoop& loop, const FMI& a, const FMI& b, MergeBuffer& mb) { while(true) { range_type sequence_range = loop.next(); if(Range::empty(sequence_range)) { return; } MergeBuffer::buffer_type thread_buffer; std::vector<MergeBuffer::run_type> run_buffer; run_buffer.reserve(mb.parameters.run_buffer_size); std::stack<MergePosition> positions; BWT::ranks_type a_pos, b_sp, b_ep; BWT::rank_ranges_type b_range; positions.push(MergePosition(a.sequences(), sequence_range)); while(!(positions.empty())) { MergePosition curr = positions.top(); positions.pop(); run_buffer.push_back(MergeBuffer::run_type(curr.a_pos, Range::length(curr.b_range))); if(run_buffer.size() >= mb.parameters.run_buffer_size) { mergeRA(mb, thread_buffer, run_buffer, false); } if(Range::length(curr.b_range) == 1) { range_type pred = b.LF(curr.b_range.first); if(pred.second != 0) { positions.push(MergePosition(a.LF(curr.a_pos, pred.second), pred.first)); } } else if(Range::length(curr.b_range) <= FMI::SHORT_RANGE) { b.LF(curr.b_range, b_range); for(size_type c = 1; c < b.alpha.sigma; c++) { if(!(Range::empty(b_range[c]))) { positions.push(MergePosition(a.LF(curr.a_pos, c), b_range[c])); } } } else { a.LF(curr.a_pos, a_pos); b.LF(curr.b_range, b_sp, b_ep); for(size_type c = 1; c < b.alpha.sigma; c++) { if(b_sp[c] <= b_ep[c]) { positions.push(MergePosition(a_pos[c], b_sp[c], b_ep[c])); } } } } mergeRA(mb, thread_buffer, run_buffer, true); #ifdef VERBOSE_STATUS_INFO { std::lock_guard<std::mutex> lock(Parallel::stderr_access); std::cerr << "buildRA(): Thread " << std::this_thread::get_id() << ": Finished block " << sequence_range << std::endl; } #endif } } FMI::FMI(FMI& a, FMI& b, MergeParameters parameters) { if(a.alpha != b.alpha) { std::cerr << "FMI::FMI(): Cannot merge BWTs with different alphabets" << std::endl; std::exit(EXIT_FAILURE); } #ifdef VERBOSE_STATUS_INFO std::cerr << "bwt_merge: " << a.sequences() << " sequences of total length " << a.size() << std::endl; std::cerr << "bwt_merge: Adding " << b.sequences() << " sequences of total length " << b.size() << std::endl; std::cerr << "bwt_merge: Memory usage before merging: " << inGigabytes(memoryUsage()) << " GB" << std::endl; double start = readTimer(); #endif std::vector<range_type> bounds = getBounds(range_type(0, b.sequences() - 1), parameters.sequence_blocks); MergeBuffer mb(b.size(), parameters); { ParallelLoop loop(0, b.sequences(), parameters.sequence_blocks, parameters.threads); loop.execute(buildRA, std::ref(a), std::ref(b), std::ref(mb)); } mb.flush(); #ifdef VERBOSE_STATUS_INFO double seconds = readTimer() - start; std::cerr << "bwt_merge: RA built in " << seconds << " seconds" << std::endl; std::cerr << "bwt_merge: Memory usage with RA: " << inGigabytes(memoryUsage()) << " GB" << std::endl; #endif this->bwt = BWT(a.bwt, b.bwt, mb.ra); this->alpha = a.alpha; for(size_type c = 0; c <= this->alpha.sigma; c++) { this->alpha.C[c] += b.alpha.C[c]; } } //------------------------------------------------------------------------------ void serialize(const FMI& fmi, const std::string& filename, const std::string& format) { if(format == NativeFormat::tag) { fmi.serialize<NativeFormat>(filename); } else if(format == PlainFormatD::tag) { fmi.serialize<PlainFormatD>(filename); } else if(format == PlainFormatS::tag) { fmi.serialize<PlainFormatS>(filename); } else if(format == RFMFormat::tag) { fmi.serialize<RFMFormat>(filename); } else if(format == SDSLFormat::tag) { fmi.serialize<SDSLFormat>(filename); } else if(format == RopeFormat::tag) { fmi.serialize<RopeFormat>(filename); } else if(format == SGAFormat::tag) { fmi.serialize<SGAFormat>(filename); } else { std::cerr << "serialize(): Invalid BWT format: " << format << std::endl; std::exit(EXIT_FAILURE); } } void load(FMI& fmi, const std::string& filename, const std::string& format) { if(format == NativeFormat::tag) { fmi.load<NativeFormat>(filename); } else if(format == PlainFormatD::tag) { fmi.load<PlainFormatD>(filename); } else if(format == PlainFormatS::tag) { fmi.load<PlainFormatS>(filename); } else if(format == RFMFormat::tag) { fmi.load<RFMFormat>(filename); } else if(format == SDSLFormat::tag) { fmi.load<SDSLFormat>(filename); } else if(format == RopeFormat::tag) { fmi.load<RopeFormat>(filename); } else if(format == SGAFormat::tag) { fmi.load<SGAFormat>(filename); } else { std::cerr << "load(): Invalid BWT format: " << format << std::endl; std::exit(EXIT_FAILURE); } } //------------------------------------------------------------------------------ const std::string MergeParameters::DEFAULT_TEMP_DIR = "."; const std::string MergeParameters::TEMP_FILE_PREFIX = ".bwtmerge"; MergeParameters::MergeParameters() : run_buffer_size(RUN_BUFFER_SIZE), thread_buffer_size(THREAD_BUFFER_SIZE), merge_buffers(MERGE_BUFFERS), threads(Parallel::max_threads), sequence_blocks(threads * BLOCKS_PER_THREAD), temp_dir(DEFAULT_TEMP_DIR) { } void MergeParameters::sanitize() { this->threads = Range::bound(this->threads, 1, Parallel::max_threads); this->sequence_blocks = std::max(this->sequence_blocks, (size_type)1); this->threads = std::min(this->threads, this->sequence_blocks); } void MergeParameters::setTemp(const std::string& directory) { if(directory.length() == 0) { this->temp_dir = DEFAULT_TEMP_DIR; } else if(directory[directory.length() - 1] != '/') { this->temp_dir = directory; } else { this->temp_dir = directory.substr(0, directory.length() - 1); } } std::string MergeParameters::tempPrefix() const { return this->temp_dir + '/' + TEMP_FILE_PREFIX; } std::ostream& operator<< (std::ostream& stream, const MergeParameters& parameters) { stream << "Run buffers: " << inMegabytes(parameters.run_buffer_size * sizeof(MergeParameters::run_type)) << " MB" << std::endl; stream << "Thread buffers: " << inMegabytes(parameters.thread_buffer_size) << " MB" << std::endl; stream << "Merge buffers: " << parameters.merge_buffers << std::endl; stream << "Threads: " << parameters.threads << std::endl; stream << "Sequence blocks: " << parameters.sequence_blocks << std::endl; stream << "Temp directory: " << parameters.temp_dir << std::endl; return stream; } //------------------------------------------------------------------------------ } // namespace bwtmerge
28.364
111
0.626146
[ "vector" ]
11ce4b0987e186f767c55481abc26a57186eeb02
4,700
cc
C++
struct2tensor/ops/decode_proto_map_op.cc
jay90099/struct2tensor
47d651757efa27586bf75f991b2174d8173a750b
[ "Apache-2.0" ]
30
2019-10-07T21:31:44.000Z
2022-03-30T17:11:44.000Z
struct2tensor/ops/decode_proto_map_op.cc
jay90099/struct2tensor
47d651757efa27586bf75f991b2174d8173a750b
[ "Apache-2.0" ]
2
2020-03-23T20:48:14.000Z
2021-04-16T15:05:33.000Z
struct2tensor/ops/decode_proto_map_op.cc
jay90099/struct2tensor
47d651757efa27586bf75f991b2174d8173a750b
[ "Apache-2.0" ]
30
2019-07-16T13:01:53.000Z
2022-03-01T22:04:36.000Z
/* Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" using ::tensorflow::Status; using ::tensorflow::shape_inference::InferenceContext; REGISTER_OP("DecodeProtoMapV2") .Input("serialized_map_entries: string") .Input("map_entries_parent_indices: int64") .Input("backing_string: num_backing_string * string") .Attr("num_backing_string: int >= 0 = 0") .Attr("message_type: string") .Attr("keys: list(string) >= 0") .Attr("num_keys: int") .Attr("output_type: type") .Attr("descriptor_literal: string") .Output("values: num_keys * output_type") .Output("indices: num_keys * int64") .SetShapeFn([](InferenceContext* c) { int num_keys; TF_RETURN_IF_ERROR(c->GetAttr("num_keys", &num_keys)); for (int i = 0; i < 2 * num_keys; ++i) { c->set_output(i, c->Vector(c->UnknownDim())); } return Status::OK(); }) .Doc(R"doc( An op to decode serialized protobuf map entries with given keys into Tensors. `serialized_map_entries`: on wire, a protobuf map is encoded into repeated map entries where each entry is a submessage that contains a "key" and a "value" field. This input Tensor should be a vector containing all such submessages from the maps to be decoded in serialized form. `map_entries_parent_indices`: this op supports decoding multiple logical maps. this Tensor should have the same shape as `serialized_map_entries`. map_entries_parent_indices[i] == j means serialized_map_entries[i] came from the j-th logical map. `backing_string`: a list of string tensors which back string_views in `serialized_map_entries`, if any. This is an optimization to prevent alloc/dealloc of subtree serialized protos tensors. This input is not functionally used other than to keep the backing string alive in memory. If provided, serialized sub-messages decoded by this op will be string_views pointing to `serialize_map_entries` (which might also be a string_view). `num_backing_string`: The number of backing_string inputs. Default to 0 and can be empty to allow backward compatility. `message_type`: fully qualified name of the map entry submessage. (e.g. some.package.SomeMapMapEntry). `keys`: keys to look up from the map. If the map's keys are integers, then these string attributes are parsed as integers in decimal. If the map's keys are booleans, then only "0" and "1" are expected. `num_keys`: Number of `keys`. `output_type`: the DataType of the output value tensor. Note that for each map value type, there is only one corresponding DataType. The op will enforce it in the runtime. `descriptor_literal`: a Serialized proto2.FileDescriptorSet proto that contains the FileDescriptor of the map entry proto. `values`: there are `num_keys` Tensors corresponds to this output port. Each contains the decoded values for a key specified in `keys`. `indices`: there are `num_keys` Tensors corresponds to this output port. indices[i][j] == k means values[i][j] was decoded from the k-th logical map ( see `map_entries_parent_indices`) The OP might raise DataLoss if any of the serialized map entries is corrupted. It might also raise InvalidArgumentError if the attributes are not expected. )doc"); // See DecodeProtoMapV2. DecodeProtoMap omits `backing_string` and // `num_backing_string` and does not support string_views for // intermediate serialized proto outputs. REGISTER_OP("DecodeProtoMap") .Input("serialized_map_entries: string") .Input("map_entries_parent_indices: int64") .Attr("message_type: string") .Attr("keys: list(string) >= 0") .Attr("num_keys: int") .Attr("output_type: type") .Attr("descriptor_literal: string") .Output("values: num_keys * output_type") .Output("indices: num_keys * int64") .SetShapeFn([](InferenceContext* c) { int num_keys; TF_RETURN_IF_ERROR(c->GetAttr("num_keys", &num_keys)); for (int i = 0; i < 2 * num_keys; ++i) { c->set_output(i, c->Vector(c->UnknownDim())); } return Status::OK(); });
41.59292
80
0.725319
[ "shape", "vector" ]
11d3e4f499bd4b483407d5eddd7f32fc4468f59f
140,810
cxx
C++
panda/src/egg2pg/eggLoader.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/egg2pg/eggLoader.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/egg2pg/eggLoader.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: eggLoader.cxx // Created by: drose (26Feb02) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "pandabase.h" #include "eggLoader.h" #include "eggRenderState.h" #include "egg_parametrics.h" #include "config_egg2pg.h" #include "config_egg.h" #include "nodePath.h" #include "renderState.h" #include "transformState.h" #include "texturePool.h" #include "billboardEffect.h" #include "decalEffect.h" #include "colorAttrib.h" #include "textureAttrib.h" #include "materialPool.h" #include "geomNode.h" #include "geomVertexFormat.h" #include "geomVertexArrayFormat.h" #include "geomVertexData.h" #include "geomVertexWriter.h" #include "geom.h" #include "geomTriangles.h" #include "geomTristrips.h" #include "geomTrifans.h" #include "geomLines.h" #include "geomLinestrips.h" #include "geomPoints.h" #include "geomPatches.h" #include "sequenceNode.h" #include "switchNode.h" #include "portalNode.h" #include "occluderNode.h" #include "polylightNode.h" #include "lodNode.h" #include "modelNode.h" #include "modelRoot.h" #include "string_utils.h" #include "eggPrimitive.h" #include "eggPatch.h" #include "eggPoint.h" #include "eggLine.h" #include "eggTextureCollection.h" #include "eggNurbsCurve.h" #include "eggNurbsSurface.h" #include "eggGroupNode.h" #include "eggGroup.h" #include "eggPolygon.h" #include "eggTriangleStrip.h" #include "eggTriangleFan.h" #include "eggBin.h" #include "eggTable.h" #include "eggBinner.h" #include "eggVertexPool.h" #include "pt_EggTexture.h" #include "characterMaker.h" #include "character.h" #include "animBundleMaker.h" #include "animBundleNode.h" #include "selectiveChildNode.h" #include "collisionNode.h" #include "collisionSphere.h" #include "collisionInvSphere.h" #include "collisionTube.h" #include "collisionPlane.h" #include "collisionPolygon.h" #include "collisionFloorMesh.h" #include "collisionBox.h" #include "parametricCurve.h" #include "nurbsCurve.h" #include "nurbsCurveInterface.h" #include "nurbsCurveEvaluator.h" #include "nurbsSurfaceEvaluator.h" #include "ropeNode.h" #include "sheetNode.h" #include "look_at.h" #include "configVariableString.h" #include "transformBlendTable.h" #include "transformBlend.h" #include "sparseArray.h" #include "bitArray.h" #include "thread.h" #include "uvScrollNode.h" #include "textureStagePool.h" #include "cmath.h" #include <ctype.h> #include <algorithm> // This class is used in make_node(EggBin *) to sort LOD instances in // order by switching distance. class LODInstance { public: LODInstance(EggNode *egg_node); bool operator < (const LODInstance &other) const { return _d->_switch_in < other._d->_switch_in; } EggNode *_egg_node; const EggSwitchConditionDistance *_d; }; LODInstance:: LODInstance(EggNode *egg_node) { nassertv(egg_node != NULL); _egg_node = egg_node; // We expect this egg node to be an EggGroup with an LOD // specification. That's what the EggBinner collected together, // after all. EggGroup *egg_group = DCAST(EggGroup, egg_node); nassertv(egg_group->has_lod()); const EggSwitchCondition &sw = egg_group->get_lod(); // For now, this is the only kind of switch condition there is. _d = DCAST(EggSwitchConditionDistance, &sw); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// EggLoader:: EggLoader() { // We need to enforce whatever coordinate system the user asked for. _data = new EggData; _data->set_coordinate_system(egg_coordinate_system); _error = false; _dynamic_override = false; _dynamic_override_char_maker = NULL; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::Constructor // Access: Public // Description: The EggLoader constructor makes a copy of the EggData // passed in. //////////////////////////////////////////////////////////////////// EggLoader:: EggLoader(const EggData *data) : _data(new EggData(*data)) { _error = false; _dynamic_override = false; _dynamic_override_char_maker = NULL; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::build_graph // Access: Public // Description: //////////////////////////////////////////////////////////////////// void EggLoader:: build_graph() { _deferred_nodes.clear(); // Expand all of the ObjectType flags before we do anything else; // that might prune out large portions of the scene. if (!expand_all_object_types(_data)) { return; } // Now, load up all of the textures. load_textures(); // Clean up the vertices. _data->clear_connected_shading(); _data->remove_unused_vertices(true); _data->get_connected_shading(); _data->unify_attributes(true, egg_flat_shading, true); // Now we need to get the connected shading again, since in unifying // the attributes we may have made vertices suddenly become // identical to each other, thereby connecting more primitives than // before. _data->clear_connected_shading(); _data->remove_unused_vertices(true); _data->get_connected_shading(); // Sequences and switches have special needs. Make sure that // primitives parented directly to a sequence or switch are sorted // into sub-groups first, to prevent them being unified into a // single polyset. separate_switches(_data); if (egg_emulate_bface) { emulate_bface(_data); } // Then bin up the polysets and LOD nodes. _data->remove_invalid_primitives(true); EggBinner binner(*this); binner.make_bins(_data); // ((EggGroupNode *)_data)->write(cerr, 0); // Now build up the scene graph. _root = new ModelRoot(_data->get_egg_filename(), _data->get_egg_timestamp()); EggGroupNode::const_iterator ci; for (ci = _data->begin(); ci != _data->end(); ++ci) { make_node(*ci, _root); } reparent_decals(); start_sequences(); apply_deferred_nodes(_root, DeferredNodeProperty()); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::reparent_decals // Access: Public // Description: For each node representing a decal base geometry // (i.e. a node corresponding to an EggGroup with the // decal flag set), move all of its nested geometry // directly below the GeomNode representing the group. //////////////////////////////////////////////////////////////////// void EggLoader:: reparent_decals() { ExtraNodes::const_iterator di; for (di = _decals.begin(); di != _decals.end(); ++di) { PandaNode *node = (*di); nassertv(node != (PandaNode *)NULL); // The NodePath interface is best for this. NodePath parent(node); // First, search for the GeomNode. NodePath geom_parent; int num_children = parent.get_num_children(); for (int i = 0; i < num_children; i++) { NodePath child = parent.get_child(i); if (child.node()->is_of_type(GeomNode::get_class_type())) { if (!geom_parent.is_empty()) { // Oops, too many GeomNodes. egg2pg_cat.error() << "Decal onto " << parent.node()->get_name() << " uses base geometry with multiple GeomNodes.\n"; _error = true; } geom_parent = child; } } if (geom_parent.is_empty()) { // No children were GeomNodes. egg2pg_cat.error() << "Ignoring decal onto " << parent.node()->get_name() << "; no geometry within group.\n"; _error = true; } else { // Now reparent all of the non-GeomNodes to this node. We have // to be careful so we don't get lost as we self-modify this // list. int i = 0; while (i < num_children) { NodePath child = parent.get_child(i); if (child.node()->is_of_type(GeomNode::get_class_type())) { i++; } else { child.reparent_to(geom_parent); num_children--; } } // Finally, set the DecalEffect on the base geometry. geom_parent.node()->set_effect(DecalEffect::make()); } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::start_sequences // Access: Public // Description: Starts all of the SequenceNodes we created looping. // We have to wait until the entire graph is built up to // do this, because the SequenceNode needs its full set // of children before it can know how many frames to // loop. //////////////////////////////////////////////////////////////////// void EggLoader:: start_sequences() { ExtraNodes::const_iterator ni; for (ni = _sequences.begin(); ni != _sequences.end(); ++ni) { SequenceNode *node = DCAST(SequenceNode, (*ni)); node->loop(true); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_polyset // Access: Public // Description: Creates a polyset--that is, a Geom--from the // primitives that have already been grouped into a bin. // If transform is non-NULL, it represents the transform // to apply to the vertices (instead of the default // transform based on the bin's position within the // hierarchy). //////////////////////////////////////////////////////////////////// void EggLoader:: make_polyset(EggBin *egg_bin, PandaNode *parent, const LMatrix4d *transform, bool is_dynamic, CharacterMaker *character_maker) { if (egg_bin->empty()) { // If there are no children--no primitives--never mind. return; } // We know that all of the primitives in the bin have the same // render state, so we can get that information from the first // primitive. EggGroupNode::const_iterator ci = egg_bin->begin(); nassertv(ci != egg_bin->end()); CPT(EggPrimitive) first_prim = DCAST(EggPrimitive, (*ci)); nassertv(first_prim != (EggPrimitive *)NULL); const EggRenderState *render_state; DCAST_INTO_V(render_state, first_prim->get_user_data(EggRenderState::get_class_type())); if (render_state->_hidden && egg_suppress_hidden) { // Eat this polyset. return; } // Generate an optimal vertex pool (or multiple vertex pools, if we // have a lot of vertex) for the polygons within just the bin. Each // EggVertexPool translates directly to an optimal GeomVertexData // structure. EggVertexPools vertex_pools; egg_bin->rebuild_vertex_pools(vertex_pools, (unsigned int)egg_max_vertices, false); if (egg_mesh) { // If we're using the mesher, mesh now. egg_bin->mesh_triangles(render_state->_flat_shaded ? EggGroupNode::T_flat_shaded : 0); } else { // If we're not using the mesher, at least triangulate any // higher-order polygons we might have. egg_bin->triangulate_polygons(EggGroupNode::T_polygon | EggGroupNode::T_convex); } // Now that we've meshed, apply the per-prim attributes onto the // vertices, so we can copy them to the GeomVertexData. egg_bin->apply_first_attribute(false); egg_bin->post_apply_flat_attribute(false); //egg_bin->write(cerr, 0); PT(GeomNode) geom_node; // Now iterate through each EggVertexPool. Normally, there's only // one, but if we have a really big mesh, it might have been split // into multiple vertex pools (to keep each one within the // egg_max_vertices constraint). EggVertexPools::iterator vpi; for (vpi = vertex_pools.begin(); vpi != vertex_pools.end(); ++vpi) { EggVertexPool *vertex_pool = (*vpi); vertex_pool->remove_unused_vertices(); // vertex_pool->write(cerr, 0); bool has_overall_color; LColor overall_color; vertex_pool->check_overall_color(has_overall_color, overall_color); if (!egg_flat_colors) { // If flat colors aren't allowed, then we don't care whether // there is an overall color. In that case, treat all vertex // pools as if they contain a combination of multiple colors. has_overall_color = false; } PT(TransformBlendTable) blend_table; if (is_dynamic) { // Dynamic vertex pools will require a TransformBlendTable to // indicate how the vertices are to be animated. blend_table = make_blend_table(vertex_pool, egg_bin, character_maker); // Now that we've created the blend table, we can re-order the // vertices in the pool to efficiently group vertices together // that will share the same transform matrix. (We have to // re-order them before we create primitives, below, because // this will change the vertex index numbers.) vertex_pool->sort_by_external_index(); } // Create a handful of GeomPrimitives corresponding to the various // types of primitives that reference this vertex pool. UniquePrimitives unique_primitives; Primitives primitives; for (ci = egg_bin->begin(); ci != egg_bin->end(); ++ci) { EggPrimitive *egg_prim; DCAST_INTO_V(egg_prim, (*ci)); if (egg_prim->get_pool() == vertex_pool) { make_primitive(render_state, egg_prim, unique_primitives, primitives, has_overall_color, overall_color); } } if (!primitives.empty()) { LMatrix4d mat; if (transform != NULL) { mat = (*transform); } else { mat = egg_bin->get_vertex_to_node(); } // Now convert this vertex pool to a GeomVertexData. PT(GeomVertexData) vertex_data = make_vertex_data(render_state, vertex_pool, egg_bin, mat, blend_table, is_dynamic, character_maker, has_overall_color); nassertv(vertex_data != (GeomVertexData *)NULL); // And create a Geom to hold the primitives. PT(Geom) geom = new Geom(vertex_data); // Add each new primitive to the Geom. Primitives::const_iterator pi; for (pi = primitives.begin(); pi != primitives.end(); ++pi) { PT(GeomPrimitive) primitive = (*pi); if (primitive->is_indexed()) { // Since we may have over-allocated while we were filling up // the primitives, down-allocate now. primitive->reserve_num_vertices(primitive->get_num_vertices()); } geom->add_primitive(primitive); } // vertex_data->write(cerr); // geom->write(cerr); // render_state->_state->write(cerr, 0); // Create a new GeomNode if we haven't already. if (geom_node == (GeomNode *)NULL) { // Now, is our parent node a GeomNode, or just an ordinary // PandaNode? If it's a GeomNode, we can add the new Geom directly // to our parent; otherwise, we need to create a new node. if (parent->is_geom_node() && !render_state->_hidden) { geom_node = DCAST(GeomNode, parent); } else { geom_node = new GeomNode(egg_bin->get_name()); if (render_state->_hidden) { parent->add_stashed(geom_node); } else { parent->add_child(geom_node); } } } CPT(RenderState) geom_state = render_state->_state; if (has_overall_color) { if (!overall_color.almost_equal(LColor(1.0f, 1.0f, 1.0f, 1.0f))) { geom_state = geom_state->add_attrib(ColorAttrib::make_flat(overall_color), -1); } } else { geom_state = geom_state->add_attrib(ColorAttrib::make_vertex(), -1); } geom_node->add_geom(geom, geom_state); } } if (geom_node != (GeomNode *)NULL && egg_show_normals) { // Create some more geometry to visualize each normal. for (vpi = vertex_pools.begin(); vpi != vertex_pools.end(); ++vpi) { EggVertexPool *vertex_pool = (*vpi); show_normals(vertex_pool, geom_node); } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_transform // Access: Public // Description: Creates a TransformState object corresponding to the // indicated EggTransform. //////////////////////////////////////////////////////////////////// CPT(TransformState) EggLoader:: make_transform(const EggTransform *egg_transform) { // We'll build up the transform componentwise, so we preserve any // componentwise properties of the egg transform. CPT(TransformState) ts = TransformState::make_identity(); int num_components = egg_transform->get_num_components(); for (int i = 0; i < num_components; i++) { switch (egg_transform->get_component_type(i)) { case EggTransform::CT_translate2d: { LVecBase2 trans2d(LCAST(PN_stdfloat, egg_transform->get_component_vec2(i))); LVecBase3 trans3d(trans2d[0], trans2d[1], 0.0f); ts = TransformState::make_pos(trans3d)->compose(ts); } break; case EggTransform::CT_translate3d: { LVecBase3 trans3d(LCAST(PN_stdfloat, egg_transform->get_component_vec3(i))); ts = TransformState::make_pos(trans3d)->compose(ts); } break; case EggTransform::CT_rotate2d: { LRotation rot(LVector3(0.0f, 0.0f, 1.0f), (PN_stdfloat)egg_transform->get_component_number(i)); ts = TransformState::make_quat(rot)->compose(ts); } break; case EggTransform::CT_rotx: { LRotation rot(LVector3(1.0f, 0.0f, 0.0f), (PN_stdfloat)egg_transform->get_component_number(i)); ts = TransformState::make_quat(rot)->compose(ts); } break; case EggTransform::CT_roty: { LRotation rot(LVector3(0.0f, 1.0f, 0.0f), (PN_stdfloat)egg_transform->get_component_number(i)); ts = TransformState::make_quat(rot)->compose(ts); } break; case EggTransform::CT_rotz: { LRotation rot(LVector3(0.0f, 0.0f, 1.0f), (PN_stdfloat)egg_transform->get_component_number(i)); ts = TransformState::make_quat(rot)->compose(ts); } break; case EggTransform::CT_rotate3d: { LRotation rot(LCAST(PN_stdfloat, egg_transform->get_component_vec3(i)), (PN_stdfloat)egg_transform->get_component_number(i)); ts = TransformState::make_quat(rot)->compose(ts); } break; case EggTransform::CT_scale2d: { LVecBase2 scale2d(LCAST(PN_stdfloat, egg_transform->get_component_vec2(i))); LVecBase3 scale3d(scale2d[0], scale2d[1], 1.0f); ts = TransformState::make_scale(scale3d)->compose(ts); } break; case EggTransform::CT_scale3d: { LVecBase3 scale3d(LCAST(PN_stdfloat, egg_transform->get_component_vec3(i))); ts = TransformState::make_scale(scale3d)->compose(ts); } break; case EggTransform::CT_uniform_scale: { PN_stdfloat scale = (PN_stdfloat)egg_transform->get_component_number(i); ts = TransformState::make_scale(scale)->compose(ts); } break; case EggTransform::CT_matrix3: { LMatrix3 m(LCAST(PN_stdfloat, egg_transform->get_component_mat3(i))); LMatrix4 mat4(m(0, 0), m(0, 1), 0.0, m(0, 2), m(1, 0), m(1, 1), 0.0, m(1, 2), 0.0, 0.0, 1.0, 0.0, m(2, 0), m(2, 1), 0.0, m(2, 2)); ts = TransformState::make_mat(mat4)->compose(ts); } break; case EggTransform::CT_matrix4: { LMatrix4 mat4(LCAST(PN_stdfloat, egg_transform->get_component_mat4(i))); ts = TransformState::make_mat(mat4)->compose(ts); } break; case EggTransform::CT_invalid: nassertr(false, ts); break; } } if (ts->components_given()) { return ts; } // Finally, we uniquify all the matrix-based TransformStates we // create by complete matrix value. The TransformState class // doesn't normally go this far, because of the cost of this // additional uniquification step, but this is the egg loader so we // don't mind spending a little bit of extra time here to get a more // optimal result. TransformStates::iterator tsi = _transform_states.insert(TransformStates::value_type(ts->get_mat(), ts)).first; return (*tsi).second; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::show_normals // Access: Private // Description: In the presence of egg-show-normals, generate some // additional geometry to represent the normals, // tangents, and binormals of each vertex. //////////////////////////////////////////////////////////////////// void EggLoader:: show_normals(EggVertexPool *vertex_pool, GeomNode *geom_node) { PT(GeomPrimitive) primitive = new GeomLines(Geom::UH_static); CPT(GeomVertexFormat) format = GeomVertexFormat::get_v3cp(); PT(GeomVertexData) vertex_data = new GeomVertexData(vertex_pool->get_name(), format, Geom::UH_static); GeomVertexWriter vertex(vertex_data, InternalName::get_vertex()); GeomVertexWriter color(vertex_data, InternalName::get_color()); EggVertexPool::const_iterator vi; for (vi = vertex_pool->begin(); vi != vertex_pool->end(); ++vi) { EggVertex *vert = (*vi); LPoint3d pos = vert->get_pos3(); if (vert->has_normal()) { vertex.add_data3d(pos); vertex.add_data3d(pos + vert->get_normal() * egg_normal_scale); color.add_data4(1.0f, 0.0f, 0.0f, 1.0f); color.add_data4(1.0f, 0.0f, 0.0f, 1.0f); primitive->add_next_vertices(2); primitive->close_primitive(); } // Also look for tangents and binormals in each texture coordinate // set. EggVertex::const_uv_iterator uvi; for (uvi = vert->uv_begin(); uvi != vert->uv_end(); ++uvi) { EggVertexUV *uv_obj = (*uvi); if (uv_obj->has_tangent()) { vertex.add_data3d(pos); vertex.add_data3d(pos + uv_obj->get_tangent() * egg_normal_scale); color.add_data4(0.0f, 1.0f, 0.0f, 1.0f); color.add_data4(0.0f, 1.0f, 0.0f, 1.0f); primitive->add_next_vertices(2); primitive->close_primitive(); } if (uv_obj->has_binormal()) { vertex.add_data3d(pos); vertex.add_data3d(pos + uv_obj->get_binormal() * egg_normal_scale); color.add_data4(0.0f, 0.0f, 1.0f, 1.0f); color.add_data4(0.0f, 0.0f, 1.0f, 1.0f); primitive->add_next_vertices(2); primitive->close_primitive(); } } } PT(Geom) geom = new Geom(vertex_data); geom->add_primitive(primitive); geom_node->add_geom(geom); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_nurbs_curve // Access: Private // Description: //////////////////////////////////////////////////////////////////// void EggLoader:: make_nurbs_curve(EggNurbsCurve *egg_curve, PandaNode *parent, const LMatrix4d &mat) { if (egg_load_old_curves) { // Make a NurbsCurve instead of a RopeNode (old interface). make_old_nurbs_curve(egg_curve, parent, mat); return; } assert(parent != NULL); assert(!parent->is_geom_node()); PT(NurbsCurveEvaluator) nurbs = ::make_nurbs_curve(egg_curve, mat); if (nurbs == (NurbsCurveEvaluator *)NULL) { _error = true; return; } /* switch (egg_curve->get_curve_type()) { case EggCurve::CT_xyz: curve->set_curve_type(PCT_XYZ); break; case EggCurve::CT_hpr: curve->set_curve_type(PCT_HPR); break; case EggCurve::CT_t: curve->set_curve_type(PCT_T); break; default: break; } */ PT(RopeNode) rope = new RopeNode(egg_curve->get_name()); rope->set_curve(nurbs); // Respect the subdivision values in the egg file, if any. if (egg_curve->get_subdiv() != 0) { int subdiv_per_segment = (int)((egg_curve->get_subdiv() + 0.5) / nurbs->get_num_segments()); rope->set_num_subdiv(max(subdiv_per_segment, 1)); } const EggRenderState *render_state; DCAST_INTO_V(render_state, egg_curve->get_user_data(EggRenderState::get_class_type())); if (render_state->_hidden && egg_suppress_hidden) { // Eat this primitive. return; } rope->set_state(render_state->_state); rope->set_uv_mode(RopeNode::UV_parametric); if (egg_curve->has_vertex_color()) { // If the curve had individual vertex color, enable it. rope->set_use_vertex_color(true); } else if (egg_curve->has_color()) { // Otherwise, if the curve has overall color, apply it. rope->set_attrib(ColorAttrib::make_flat(egg_curve->get_color())); } parent->add_child(rope); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_old_nurbs_curve // Access: Private // Description: This deprecated interface creates a NurbsCurve object // for the EggNurbsCurve entry. It will eventually be // removed in favor of the above, which creates a // RopeNode. //////////////////////////////////////////////////////////////////// void EggLoader:: make_old_nurbs_curve(EggNurbsCurve *egg_curve, PandaNode *parent, const LMatrix4d &mat) { assert(parent != NULL); assert(!parent->is_geom_node()); PT(ParametricCurve) curve; curve = new NurbsCurve; NurbsCurveInterface *nurbs = curve->get_nurbs_interface(); nassertv(nurbs != (NurbsCurveInterface *)NULL); if (egg_curve->get_order() < 1 || egg_curve->get_order() > 4) { egg2pg_cat.error() << "Invalid NURBSCurve order for " << egg_curve->get_name() << ": " << egg_curve->get_order() << "\n"; _error = true; return; } nurbs->set_order(egg_curve->get_order()); EggPrimitive::const_iterator pi; for (pi = egg_curve->begin(); pi != egg_curve->end(); ++pi) { nurbs->append_cv(LCAST(PN_stdfloat, (*pi)->get_pos4() * mat)); } int num_knots = egg_curve->get_num_knots(); if (num_knots != nurbs->get_num_knots()) { egg2pg_cat.error() << "Invalid NURBSCurve number of knots for " << egg_curve->get_name() << ": got " << num_knots << " knots, expected " << nurbs->get_num_knots() << "\n"; _error = true; return; } for (int i = 0; i < num_knots; i++) { nurbs->set_knot(i, egg_curve->get_knot(i)); } switch (egg_curve->get_curve_type()) { case EggCurve::CT_xyz: curve->set_curve_type(PCT_XYZ); break; case EggCurve::CT_hpr: curve->set_curve_type(PCT_HPR); break; case EggCurve::CT_t: curve->set_curve_type(PCT_T); break; default: break; } curve->set_name(egg_curve->get_name()); if (!curve->recompute()) { egg2pg_cat.error() << "Invalid NURBSCurve " << egg_curve->get_name() << "\n"; _error = true; return; } parent->add_child(curve); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_nurbs_surface // Access: Private // Description: //////////////////////////////////////////////////////////////////// void EggLoader:: make_nurbs_surface(EggNurbsSurface *egg_surface, PandaNode *parent, const LMatrix4d &mat) { assert(parent != NULL); assert(!parent->is_geom_node()); PT(NurbsSurfaceEvaluator) nurbs = ::make_nurbs_surface(egg_surface, mat); if (nurbs == (NurbsSurfaceEvaluator *)NULL) { _error = true; return; } PT(SheetNode) sheet = new SheetNode(egg_surface->get_name()); sheet->set_surface(nurbs); // Respect the subdivision values in the egg file, if any. if (egg_surface->get_u_subdiv() != 0) { int u_subdiv_per_segment = (int)((egg_surface->get_u_subdiv() + 0.5) / nurbs->get_num_u_segments()); sheet->set_num_u_subdiv(max(u_subdiv_per_segment, 1)); } if (egg_surface->get_v_subdiv() != 0) { int v_subdiv_per_segment = (int)((egg_surface->get_v_subdiv() + 0.5) / nurbs->get_num_v_segments()); sheet->set_num_v_subdiv(max(v_subdiv_per_segment, 1)); } const EggRenderState *render_state; DCAST_INTO_V(render_state, egg_surface->get_user_data(EggRenderState::get_class_type())); if (render_state->_hidden && egg_suppress_hidden) { // Eat this primitive. return; } sheet->set_state(render_state->_state); if (egg_surface->has_vertex_color()) { // If the surface had individual vertex color, enable it. sheet->set_use_vertex_color(true); } else if (egg_surface->has_color()) { // Otherwise, if the surface has overall color, apply it. sheet->set_attrib(ColorAttrib::make_flat(egg_surface->get_color())); } parent->add_child(sheet); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::load_textures // Access: Private // Description: //////////////////////////////////////////////////////////////////// void EggLoader:: load_textures() { // First, collect all the textures that are referenced. EggTextureCollection tc; tc.find_used_textures(_data); EggTextureCollection::iterator ti; for (ti = tc.begin(); ti != tc.end(); ++ti) { PT_EggTexture egg_tex = (*ti); TextureDef def; if (load_texture(def, egg_tex)) { // Now associate the pointers, so we'll be able to look up the // Texture pointer given an EggTexture pointer, later. _textures[egg_tex] = def; } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::load_texture // Access: Private // Description: //////////////////////////////////////////////////////////////////// bool EggLoader:: load_texture(TextureDef &def, EggTexture *egg_tex) { // Check to see if we should reduce the number of channels in // the texture. int wanted_channels = 0; bool wanted_alpha = false; switch (egg_tex->get_format()) { case EggTexture::F_red: case EggTexture::F_green: case EggTexture::F_blue: case EggTexture::F_alpha: case EggTexture::F_luminance: wanted_channels = 1; wanted_alpha = false; break; case EggTexture::F_luminance_alpha: case EggTexture::F_luminance_alphamask: wanted_channels = 2; wanted_alpha = true; break; case EggTexture::F_rgb: case EggTexture::F_rgb12: case EggTexture::F_rgb8: case EggTexture::F_rgb5: case EggTexture::F_rgb332: wanted_channels = 3; wanted_alpha = false; break; case EggTexture::F_rgba: case EggTexture::F_rgbm: case EggTexture::F_rgba12: case EggTexture::F_rgba8: case EggTexture::F_rgba4: case EggTexture::F_rgba5: wanted_channels = 4; wanted_alpha = true; break; case EggTexture::F_unspecified: wanted_alpha = egg_tex->has_alpha_filename(); } // Since some properties of the textures are inferred from the // texture files themselves (if the properties are not explicitly // specified in the egg file), then we add the textures as // dependents for the egg file. if (_record != (BamCacheRecord *)NULL) { _record->add_dependent_file(egg_tex->get_fullpath()); if (egg_tex->has_alpha_filename() && wanted_alpha) { _record->add_dependent_file(egg_tex->get_alpha_fullpath()); } } // By convention, the egg loader will preload the simple texture images. LoaderOptions options; if (egg_preload_simple_textures) { options.set_texture_flags(options.get_texture_flags() | LoaderOptions::TF_preload_simple); } if (!egg_ignore_filters && !egg_ignore_mipmaps) { switch (egg_tex->get_minfilter()) { case EggTexture::FT_nearest: case EggTexture::FT_linear: case EggTexture::FT_unspecified: break; case EggTexture::FT_nearest_mipmap_nearest: case EggTexture::FT_linear_mipmap_nearest: case EggTexture::FT_nearest_mipmap_linear: case EggTexture::FT_linear_mipmap_linear: options.set_texture_flags(options.get_texture_flags() | LoaderOptions::TF_generate_mipmaps); } } if (egg_tex->get_multiview()) { options.set_texture_flags(options.get_texture_flags() | LoaderOptions::TF_multiview); if (egg_tex->has_num_views()) { options.set_texture_num_views(egg_tex->get_num_views()); } } PT(Texture) tex; switch (egg_tex->get_texture_type()) { case EggTexture::TT_unspecified: case EggTexture::TT_1d_texture: options.set_texture_flags(options.get_texture_flags() | LoaderOptions::TF_allow_1d); // Fall through. case EggTexture::TT_2d_texture: if (egg_tex->has_alpha_filename() && wanted_alpha) { tex = TexturePool::load_texture(egg_tex->get_fullpath(), egg_tex->get_alpha_fullpath(), wanted_channels, egg_tex->get_alpha_file_channel(), egg_tex->get_read_mipmaps(), options); } else { tex = TexturePool::load_texture(egg_tex->get_fullpath(), wanted_channels, egg_tex->get_read_mipmaps(), options); } break; case EggTexture::TT_3d_texture: tex = TexturePool::load_3d_texture(egg_tex->get_fullpath(), egg_tex->get_read_mipmaps(), options); break; case EggTexture::TT_cube_map: tex = TexturePool::load_cube_map(egg_tex->get_fullpath(), egg_tex->get_read_mipmaps(), options); break; } if (tex == (Texture *)NULL) { return false; } // Record the original filenames in the textures (as loaded from the // egg file). These filenames will be written back to the bam file // if the bam file is written out. tex->set_filename(egg_tex->get_filename()); if (egg_tex->has_alpha_filename() && wanted_alpha) { tex->set_alpha_filename(egg_tex->get_alpha_filename()); } // See if there is some egg data hanging on the texture. In // particular, the TxaFileFilter might have left that here for us. TypedReferenceCount *aux = tex->get_aux_data("egg"); if (aux != (TypedReferenceCount *)NULL && aux->is_of_type(EggTexture::get_class_type())) { EggTexture *aux_egg_tex = DCAST(EggTexture, aux); if (aux_egg_tex->get_alpha_mode() != EggTexture::AM_unspecified) { egg_tex->set_alpha_mode(aux_egg_tex->get_alpha_mode()); } if (aux_egg_tex->get_format() != EggTexture::F_unspecified) { egg_tex->set_format(aux_egg_tex->get_format()); } if (aux_egg_tex->get_minfilter() != EggTexture::FT_unspecified) { egg_tex->set_minfilter(aux_egg_tex->get_minfilter()); } if (aux_egg_tex->get_magfilter() != EggTexture::FT_unspecified) { egg_tex->set_magfilter(aux_egg_tex->get_magfilter()); } if (aux_egg_tex->has_anisotropic_degree()) { egg_tex->set_anisotropic_degree(aux_egg_tex->get_anisotropic_degree()); } } apply_texture_attributes(tex, egg_tex); // Make a texture stage for the texture. PT(TextureStage) stage = make_texture_stage(egg_tex); def._texture = DCAST(TextureAttrib, TextureAttrib::make())->add_on_stage(stage, tex); def._stage = stage; def._egg_tex = egg_tex; return true; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::apply_texture_attributes // Access: Private // Description: //////////////////////////////////////////////////////////////////// void EggLoader:: apply_texture_attributes(Texture *tex, const EggTexture *egg_tex) { if (egg_tex->get_compression_mode() != EggTexture::CM_default) { tex->set_compression(convert_compression_mode(egg_tex->get_compression_mode())); } SamplerState sampler; EggTexture::WrapMode wrap_u = egg_tex->determine_wrap_u(); EggTexture::WrapMode wrap_v = egg_tex->determine_wrap_v(); EggTexture::WrapMode wrap_w = egg_tex->determine_wrap_w(); if (wrap_u != EggTexture::WM_unspecified) { sampler.set_wrap_u(convert_wrap_mode(wrap_u)); } if (wrap_v != EggTexture::WM_unspecified) { sampler.set_wrap_v(convert_wrap_mode(wrap_v)); } if (wrap_w != EggTexture::WM_unspecified) { sampler.set_wrap_w(convert_wrap_mode(wrap_w)); } if (egg_tex->has_border_color()) { sampler.set_border_color(egg_tex->get_border_color()); } switch (egg_tex->get_minfilter()) { case EggTexture::FT_nearest: sampler.set_minfilter(SamplerState::FT_nearest); break; case EggTexture::FT_linear: if (egg_ignore_filters) { egg2pg_cat.warning() << "Ignoring minfilter request\n"; sampler.set_minfilter(SamplerState::FT_nearest); } else { sampler.set_minfilter(SamplerState::FT_linear); } break; case EggTexture::FT_nearest_mipmap_nearest: if (egg_ignore_filters) { egg2pg_cat.warning() << "Ignoring minfilter request\n"; sampler.set_minfilter(SamplerState::FT_nearest); } else if (egg_ignore_mipmaps) { egg2pg_cat.warning() << "Ignoring mipmap request\n"; sampler.set_minfilter(SamplerState::FT_nearest); } else { sampler.set_minfilter(SamplerState::FT_nearest_mipmap_nearest); } break; case EggTexture::FT_linear_mipmap_nearest: if (egg_ignore_filters) { egg2pg_cat.warning() << "Ignoring minfilter request\n"; sampler.set_minfilter(SamplerState::FT_nearest); } else if (egg_ignore_mipmaps) { egg2pg_cat.warning() << "Ignoring mipmap request\n"; sampler.set_minfilter(SamplerState::FT_linear); } else { sampler.set_minfilter(SamplerState::FT_linear_mipmap_nearest); } break; case EggTexture::FT_nearest_mipmap_linear: if (egg_ignore_filters) { egg2pg_cat.warning() << "Ignoring minfilter request\n"; sampler.set_minfilter(SamplerState::FT_nearest); } else if (egg_ignore_mipmaps) { egg2pg_cat.warning() << "Ignoring mipmap request\n"; sampler.set_minfilter(SamplerState::FT_nearest); } else { sampler.set_minfilter(SamplerState::FT_nearest_mipmap_linear); } break; case EggTexture::FT_linear_mipmap_linear: if (egg_ignore_filters) { egg2pg_cat.warning() << "Ignoring minfilter request\n"; sampler.set_minfilter(SamplerState::FT_nearest); } else if (egg_ignore_mipmaps) { egg2pg_cat.warning() << "Ignoring mipmap request\n"; sampler.set_minfilter(SamplerState::FT_linear); } else { sampler.set_minfilter(SamplerState::FT_linear_mipmap_linear); } break; case EggTexture::FT_unspecified: break; } switch (egg_tex->get_magfilter()) { case EggTexture::FT_nearest: case EggTexture::FT_nearest_mipmap_nearest: case EggTexture::FT_nearest_mipmap_linear: sampler.set_magfilter(SamplerState::FT_nearest); break; case EggTexture::FT_linear: case EggTexture::FT_linear_mipmap_nearest: case EggTexture::FT_linear_mipmap_linear: if (egg_ignore_filters) { egg2pg_cat.warning() << "Ignoring magfilter request\n"; sampler.set_magfilter(SamplerState::FT_nearest); } else { sampler.set_magfilter(SamplerState::FT_linear); } break; case EggTexture::FT_unspecified: break; } if (egg_tex->has_anisotropic_degree()) { sampler.set_anisotropic_degree(egg_tex->get_anisotropic_degree()); } if (egg_tex->has_min_lod()) { sampler.set_min_lod(egg_tex->get_min_lod()); } if (egg_tex->has_max_lod()) { sampler.set_max_lod(egg_tex->get_max_lod()); } if (egg_tex->has_lod_bias()) { sampler.set_lod_bias(egg_tex->get_lod_bias()); } tex->set_default_sampler(sampler); if (tex->get_num_components() == 1) { switch (egg_tex->get_format()) { case EggTexture::F_red: tex->set_format(Texture::F_red); break; case EggTexture::F_green: tex->set_format(Texture::F_green); break; case EggTexture::F_blue: tex->set_format(Texture::F_blue); break; case EggTexture::F_alpha: tex->set_format(Texture::F_alpha); break; case EggTexture::F_luminance: tex->set_format(Texture::F_luminance); break; case EggTexture::F_unspecified: break; default: egg2pg_cat.warning() << "Ignoring inappropriate format " << egg_tex->get_format() << " for 1-component texture " << egg_tex->get_name() << "\n"; } } else if (tex->get_num_components() == 2) { switch (egg_tex->get_format()) { case EggTexture::F_luminance_alpha: tex->set_format(Texture::F_luminance_alpha); break; case EggTexture::F_luminance_alphamask: tex->set_format(Texture::F_luminance_alphamask); break; case EggTexture::F_unspecified: break; default: egg2pg_cat.warning() << "Ignoring inappropriate format " << egg_tex->get_format() << " for 2-component texture " << egg_tex->get_name() << "\n"; } } else if (tex->get_num_components() == 3) { switch (egg_tex->get_format()) { case EggTexture::F_rgb: tex->set_format(Texture::F_rgb); break; case EggTexture::F_rgb12: if (tex->get_component_width() >= 2) { // Only do this if the component width supports it. tex->set_format(Texture::F_rgb12); } else { egg2pg_cat.warning() << "Ignoring inappropriate format " << egg_tex->get_format() << " for 8-bit texture " << egg_tex->get_name() << "\n"; } break; case EggTexture::F_rgb8: case EggTexture::F_rgba8: // We'll quietly accept RGBA8 for a 3-component texture, since // flt2egg generates these for 3-component as well as for // 4-component textures. tex->set_format(Texture::F_rgb8); break; case EggTexture::F_rgb5: tex->set_format(Texture::F_rgb5); break; case EggTexture::F_rgb332: tex->set_format(Texture::F_rgb332); break; case EggTexture::F_unspecified: break; default: egg2pg_cat.warning() << "Ignoring inappropriate format " << egg_tex->get_format() << " for 3-component texture " << egg_tex->get_name() << "\n"; } } else if (tex->get_num_components() == 4) { switch (egg_tex->get_format()) { case EggTexture::F_rgba: tex->set_format(Texture::F_rgba); break; case EggTexture::F_rgbm: tex->set_format(Texture::F_rgbm); break; case EggTexture::F_rgba12: if (tex->get_component_width() >= 2) { // Only do this if the component width supports it. tex->set_format(Texture::F_rgba12); } else { egg2pg_cat.warning() << "Ignoring inappropriate format " << egg_tex->get_format() << " for 8-bit texture " << egg_tex->get_name() << "\n"; } break; case EggTexture::F_rgba8: tex->set_format(Texture::F_rgba8); break; case EggTexture::F_rgba4: tex->set_format(Texture::F_rgba4); break; case EggTexture::F_rgba5: tex->set_format(Texture::F_rgba5); break; case EggTexture::F_unspecified: break; default: egg2pg_cat.warning() << "Ignoring inappropriate format " << egg_tex->get_format() << " for 4-component texture " << egg_tex->get_name() << "\n"; } } switch (egg_tex->get_quality_level()) { case EggTexture::QL_unspecified: case EggTexture::QL_default: tex->set_quality_level(Texture::QL_default); break; case EggTexture::QL_fastest: tex->set_quality_level(Texture::QL_fastest); break; case EggTexture::QL_normal: tex->set_quality_level(Texture::QL_normal); break; case EggTexture::QL_best: tex->set_quality_level(Texture::QL_best); break; } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::convert_compression_mode // Access: Private // Description: Returns the Texture::CompressionMode enum // corresponding to the EggTexture::CompressionMode. // Returns CM_default if the compression mode is // unspecified. //////////////////////////////////////////////////////////////////// Texture::CompressionMode EggLoader:: convert_compression_mode(EggTexture::CompressionMode compression_mode) const { switch (compression_mode) { case EggTexture::CM_off: return Texture::CM_off; case EggTexture::CM_on: return Texture::CM_on; case EggTexture::CM_fxt1: return Texture::CM_fxt1; case EggTexture::CM_dxt1: return Texture::CM_dxt1; case EggTexture::CM_dxt2: return Texture::CM_dxt2; case EggTexture::CM_dxt3: return Texture::CM_dxt3; case EggTexture::CM_dxt4: return Texture::CM_dxt4; case EggTexture::CM_dxt5: return Texture::CM_dxt5; case EggTexture::CM_default: return Texture::CM_default; } egg2pg_cat.warning() << "Unexpected texture compression flag: " << (int)compression_mode << "\n"; return Texture::CM_default; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::convert_wrap_mode // Access: Private // Description: Returns the SamplerState::WrapMode enum corresponding to // the EggTexture::WrapMode. Returns WM_repeat if the // wrap mode is unspecified. //////////////////////////////////////////////////////////////////// SamplerState::WrapMode EggLoader:: convert_wrap_mode(EggTexture::WrapMode wrap_mode) const { switch (wrap_mode) { case EggTexture::WM_clamp: return SamplerState::WM_clamp; case EggTexture::WM_repeat: return SamplerState::WM_repeat; case EggTexture::WM_mirror: return SamplerState::WM_mirror; case EggTexture::WM_mirror_once: return SamplerState::WM_mirror_once; case EggTexture::WM_border_color: return SamplerState::WM_border_color; case EggTexture::WM_unspecified: return SamplerState::WM_repeat; } egg2pg_cat.warning() << "Unexpected texture wrap flag: " << (int)wrap_mode << "\n"; return SamplerState::WM_repeat; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_texture_stage // Access: Private // Description: Creates a TextureStage object suitable for rendering // the indicated texture. //////////////////////////////////////////////////////////////////// PT(TextureStage) EggLoader:: make_texture_stage(const EggTexture *egg_tex) { // If the egg texture specifies any relevant TextureStage // properties, or if it is multitextured on top of anything else, it // gets its own texture stage; otherwise, it gets the default // texture stage. if (!egg_tex->has_stage_name() && !egg_tex->has_uv_name() && !egg_tex->has_color() && (egg_tex->get_env_type() == EggTexture::ET_unspecified || egg_tex->get_env_type() == EggTexture::ET_modulate) && egg_tex->get_combine_mode(EggTexture::CC_rgb) == EggTexture::CM_unspecified && egg_tex->get_combine_mode(EggTexture::CC_alpha) == EggTexture::CM_unspecified && !egg_tex->has_priority() && egg_tex->get_multitexture_sort() == 0 && !egg_tex->get_saved_result()) { return TextureStage::get_default(); } PT(TextureStage) stage = new TextureStage(egg_tex->get_stage_name()); switch (egg_tex->get_env_type()) { case EggTexture::ET_modulate: stage->set_mode(TextureStage::M_modulate); break; case EggTexture::ET_decal: stage->set_mode(TextureStage::M_decal); break; case EggTexture::ET_blend: stage->set_mode(TextureStage::M_blend); break; case EggTexture::ET_replace: stage->set_mode(TextureStage::M_replace); break; case EggTexture::ET_add: stage->set_mode(TextureStage::M_add); break; case EggTexture::ET_blend_color_scale: stage->set_mode(TextureStage::M_blend_color_scale); break; case EggTexture::ET_modulate_glow: stage->set_mode(TextureStage::M_modulate_glow); break; case EggTexture::ET_modulate_gloss: stage->set_mode(TextureStage::M_modulate_gloss); break; case EggTexture::ET_normal: stage->set_mode(TextureStage::M_normal); break; case EggTexture::ET_normal_height: stage->set_mode(TextureStage::M_normal_height); break; case EggTexture::ET_glow: stage->set_mode(TextureStage::M_glow); break; case EggTexture::ET_gloss: stage->set_mode(TextureStage::M_gloss); break; case EggTexture::ET_height: stage->set_mode(TextureStage::M_height); break; case EggTexture::ET_selector: stage->set_mode(TextureStage::M_selector); break; case EggTexture::ET_normal_gloss: stage->set_mode(TextureStage::M_normal_gloss); break; case EggTexture::ET_unspecified: break; } switch (egg_tex->get_combine_mode(EggTexture::CC_rgb)) { case EggTexture::CM_replace: stage->set_combine_rgb(get_combine_mode(egg_tex, EggTexture::CC_rgb), get_combine_source(egg_tex, EggTexture::CC_rgb, 0), get_combine_operand(egg_tex, EggTexture::CC_rgb, 0)); break; case EggTexture::CM_modulate: case EggTexture::CM_add: case EggTexture::CM_add_signed: case EggTexture::CM_subtract: case EggTexture::CM_dot3_rgb: case EggTexture::CM_dot3_rgba: stage->set_combine_rgb(get_combine_mode(egg_tex, EggTexture::CC_rgb), get_combine_source(egg_tex, EggTexture::CC_rgb, 0), get_combine_operand(egg_tex, EggTexture::CC_rgb, 0), get_combine_source(egg_tex, EggTexture::CC_rgb, 1), get_combine_operand(egg_tex, EggTexture::CC_rgb, 1)); break; case EggTexture::CM_interpolate: stage->set_combine_rgb(get_combine_mode(egg_tex, EggTexture::CC_rgb), get_combine_source(egg_tex, EggTexture::CC_rgb, 0), get_combine_operand(egg_tex, EggTexture::CC_rgb, 0), get_combine_source(egg_tex, EggTexture::CC_rgb, 1), get_combine_operand(egg_tex, EggTexture::CC_rgb, 1), get_combine_source(egg_tex, EggTexture::CC_rgb, 2), get_combine_operand(egg_tex, EggTexture::CC_rgb, 2)); break; case EggTexture::CM_unspecified: break; } switch (egg_tex->get_combine_mode(EggTexture::CC_alpha)) { case EggTexture::CM_replace: stage->set_combine_alpha(get_combine_mode(egg_tex, EggTexture::CC_alpha), get_combine_source(egg_tex, EggTexture::CC_alpha, 0), get_combine_operand(egg_tex, EggTexture::CC_alpha, 0)); break; case EggTexture::CM_modulate: case EggTexture::CM_add: case EggTexture::CM_add_signed: case EggTexture::CM_subtract: stage->set_combine_alpha(get_combine_mode(egg_tex, EggTexture::CC_alpha), get_combine_source(egg_tex, EggTexture::CC_alpha, 0), get_combine_operand(egg_tex, EggTexture::CC_alpha, 0), get_combine_source(egg_tex, EggTexture::CC_alpha, 1), get_combine_operand(egg_tex, EggTexture::CC_alpha, 1)); break; case EggTexture::CM_interpolate: stage->set_combine_alpha(get_combine_mode(egg_tex, EggTexture::CC_alpha), get_combine_source(egg_tex, EggTexture::CC_alpha, 0), get_combine_operand(egg_tex, EggTexture::CC_alpha, 0), get_combine_source(egg_tex, EggTexture::CC_alpha, 1), get_combine_operand(egg_tex, EggTexture::CC_alpha, 1), get_combine_source(egg_tex, EggTexture::CC_alpha, 2), get_combine_operand(egg_tex, EggTexture::CC_alpha, 2)); break; case EggTexture::CM_unspecified: case EggTexture::CM_dot3_rgb: case EggTexture::CM_dot3_rgba: break; } if (egg_tex->has_uv_name()) { PT(InternalName) name = InternalName::get_texcoord_name(egg_tex->get_uv_name()); stage->set_texcoord_name(name); } if (egg_tex->has_rgb_scale()) { stage->set_rgb_scale(egg_tex->get_rgb_scale()); } if (egg_tex->has_alpha_scale()) { stage->set_alpha_scale(egg_tex->get_alpha_scale()); } stage->set_saved_result(egg_tex->get_saved_result()); stage->set_sort(egg_tex->get_multitexture_sort() * 10); if (egg_tex->has_priority()) { stage->set_sort(egg_tex->get_priority()); } if (egg_tex->has_color()) { stage->set_color(egg_tex->get_color()); } return TextureStagePool::get_stage(stage); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::separate_switches // Access: Private // Description: Walks the tree recursively, looking for EggPrimitives // that are children of sequence or switch nodes. If // any are found, they are moved within their own group // to protect them from being flattened with their // neighbors. //////////////////////////////////////////////////////////////////// void EggLoader:: separate_switches(EggNode *egg_node) { bool parent_has_switch = false; if (egg_node->is_of_type(EggGroup::get_class_type())) { EggGroup *egg_group = DCAST(EggGroup, egg_node); parent_has_switch = egg_group->get_switch_flag(); } if (egg_node->is_of_type(EggGroupNode::get_class_type())) { EggGroupNode *egg_group = DCAST(EggGroupNode, egg_node); EggGroupNode::iterator ci; ci = egg_group->begin(); while (ci != egg_group->end()) { EggGroupNode::iterator cnext; cnext = ci; ++cnext; PT(EggNode) child = (*ci); if (parent_has_switch && child->is_of_type(EggPrimitive::get_class_type())) { // Move this child under a new node. PT(EggGroup) new_group = new EggGroup(child->get_name()); egg_group->replace(ci, new_group.p()); new_group->add_child(child); } separate_switches(child); ci = cnext; } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::emulate_bface // Access: Private // Description: Looks for EggPolygons with a bface flag applied to // them. Any such polygons are duplicated into a pair // of back-to-back polygons, and the bface flag is // removed. //////////////////////////////////////////////////////////////////// void EggLoader:: emulate_bface(EggNode *egg_node) { if (egg_node->is_of_type(EggGroupNode::get_class_type())) { EggGroupNode *egg_group = DCAST(EggGroupNode, egg_node); PT(EggGroupNode) dup_prims = new EggGroupNode; EggGroupNode::iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { PT(EggNode) child = (*ci); if (child->is_of_type(EggPolygon::get_class_type())) { EggPolygon *poly = DCAST(EggPolygon, child); if (poly->get_bface_flag()) { poly->set_bface_flag(false); PT(EggPolygon) dup_poly = new EggPolygon(*poly); dup_poly->reverse_vertex_ordering(); if (dup_poly->has_normal()) { dup_poly->set_normal(-dup_poly->get_normal()); } // Also reverse the normal on any vertices. EggPolygon::iterator vi; for (vi = dup_poly->begin(); vi != dup_poly->end(); ++vi) { EggVertex *vertex = (*vi); if (vertex->has_normal()) { EggVertex dup_vertex(*vertex); dup_vertex.set_normal(-dup_vertex.get_normal()); EggVertex *new_vertex = vertex->get_pool()->create_unique_vertex(dup_vertex); if (new_vertex != vertex) { new_vertex->copy_grefs_from(*vertex); dup_poly->replace(vi, new_vertex); } } } dup_prims->add_child(dup_poly); } } emulate_bface(child); } // Now that we've iterated through all the children, add in any // duplicated polygons we generated. egg_group->steal_children(*dup_prims); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_node // Access: Private // Description: //////////////////////////////////////////////////////////////////// PandaNode *EggLoader:: make_node(EggNode *egg_node, PandaNode *parent) { if (egg_node->is_of_type(EggBin::get_class_type())) { return make_node(DCAST(EggBin, egg_node), parent); } else if (egg_node->is_of_type(EggGroup::get_class_type())) { return make_node(DCAST(EggGroup, egg_node), parent); } else if (egg_node->is_of_type(EggTable::get_class_type())) { return make_node(DCAST(EggTable, egg_node), parent); } else if (egg_node->is_of_type(EggGroupNode::get_class_type())) { return make_node(DCAST(EggGroupNode, egg_node), parent); } return (PandaNode *)NULL; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_node (EggBin) // Access: Private // Description: //////////////////////////////////////////////////////////////////// PandaNode *EggLoader:: make_node(EggBin *egg_bin, PandaNode *parent) { // An EggBin might mean an LOD node (i.e. a parent of one or more // EggGroups with LOD specifications), or it might mean a polyset // node (a parent of one or more similar EggPrimitives). switch (egg_bin->get_bin_number()) { case EggBinner::BN_polyset: case EggBinner::BN_patches: make_polyset(egg_bin, parent, NULL, _dynamic_override, _dynamic_override_char_maker); return NULL; case EggBinner::BN_lod: return make_lod(egg_bin, parent); case EggBinner::BN_nurbs_surface: { nassertr(!egg_bin->empty(), NULL); EggNode *child = egg_bin->get_first_child(); EggNurbsSurface *egg_nurbs; DCAST_INTO_R(egg_nurbs, child, NULL); const LMatrix4d &mat = egg_nurbs->get_vertex_to_node(); make_nurbs_surface(egg_nurbs, parent, mat); } return NULL; case EggBinner::BN_nurbs_curve: { nassertr(!egg_bin->empty(), NULL); EggNode *child = egg_bin->get_first_child(); EggNurbsCurve *egg_nurbs; DCAST_INTO_R(egg_nurbs, child, NULL); const LMatrix4d &mat = egg_nurbs->get_vertex_to_node(); make_nurbs_curve(egg_nurbs, parent, mat); } return NULL; case EggBinner::BN_none: break; } // Shouldn't get here. return (PandaNode *)NULL; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_lod // Access: Private // Description: //////////////////////////////////////////////////////////////////// PandaNode *EggLoader:: make_lod(EggBin *egg_bin, PandaNode *parent) { PT(LODNode) lod_node = LODNode::make_default_lod(egg_bin->get_name()); pvector<LODInstance> instances; EggGroup::const_iterator ci; for (ci = egg_bin->begin(); ci != egg_bin->end(); ++ci) { LODInstance instance(*ci); instances.push_back(instance); } // Now that we've created all of our children, put them in the // proper order and tell the LOD node about them. sort(instances.begin(), instances.end()); if (!instances.empty()) { // Set up the LOD node's center. All of the children should have // the same center, because that's how we binned them. lod_node->set_center(LCAST(PN_stdfloat, instances[0]._d->_center)); } for (size_t i = 0; i < instances.size(); i++) { // Create the children in the proper order within the scene graph. const LODInstance &instance = instances[i]; make_node(instance._egg_node, lod_node); // All of the children should have the same center, because that's // how we binned them. nassertr(lod_node->get_center().almost_equal (LCAST(PN_stdfloat, instance._d->_center), 0.01), NULL); // Tell the LOD node about this child's switching distances. lod_node->add_switch(instance._d->_switch_in, instance._d->_switch_out); } _groups[egg_bin] = lod_node; return create_group_arc(egg_bin, parent, lod_node); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_node (EggGroup) // Access: Private // Description: //////////////////////////////////////////////////////////////////// PandaNode *EggLoader:: make_node(EggGroup *egg_group, PandaNode *parent) { PT(PandaNode) node = NULL; if (egg_group->get_dart_type() != EggGroup::DT_none) { // A group with the <Dart> flag set means to create a character. bool structured = (egg_group->get_dart_type() == EggGroup::DT_structured); CharacterMaker char_maker(egg_group, *this, structured); node = char_maker.make_node(); if(structured) { //we're going to generate the rest of the children normally //except we'll be making dynamic geometry _dynamic_override = true; _dynamic_override_char_maker = &char_maker; EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { make_node(*ci, node); } _dynamic_override_char_maker = NULL; _dynamic_override = false; } } else if (egg_group->get_cs_type() != EggGroup::CST_none) { // A collision group: create collision geometry. node = new CollisionNode(egg_group->get_name()); make_collision_solids(egg_group, egg_group, (CollisionNode *)node.p()); // Transform all of the collision solids into local space. node->xform(LCAST(PN_stdfloat, egg_group->get_vertex_to_node())); if ((egg_group->get_collide_flags() & EggGroup::CF_keep) != 0) { // If we also specified to keep the geometry, continue the // traversal. In this case, we create a new PandaNode to be the // parent of the visible geometry and the collision geometry. PandaNode *combined = new PandaNode(""); parent->add_child(combined); combined->add_child(node); node = combined; EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { make_node(*ci, combined); } } node = create_group_arc(egg_group, parent, node); return node; } else if (egg_group->get_portal_flag()) { // Create a portal instead of a regular polyset. Scan the // children of this node looking for a polygon, similar to the // collision polygon case, above. PortalNode *pnode = new PortalNode(egg_group->get_name()); node = pnode; set_portal_polygon(egg_group, pnode); if (pnode->get_num_vertices() == 0) { egg2pg_cat.warning() << "Portal " << egg_group->get_name() << " has no vertices!\n"; } } else if (egg_group->get_occluder_flag()) { // Create an occluder instead of a regular polyset. Scan the // children of this node looking for a polygon, the same as the // portal polygon case, above. OccluderNode *pnode = new OccluderNode(egg_group->get_name()); node = pnode; set_occluder_polygon(egg_group, pnode); if (pnode->get_num_vertices() == 0) { egg2pg_cat.warning() << "Occluder " << egg_group->get_name() << " has no vertices!\n"; } } else if (egg_group->get_polylight_flag()) { // Create a polylight instead of a regular polyset. // use make_sphere to get the center, radius and color //egg2pg_cat.debug() << "polylight node\n"; LPoint3 center; LColor color; PN_stdfloat radius; if (!make_sphere(egg_group, EggGroup::CF_none, center, radius, color)) { egg2pg_cat.warning() << "Polylight " << egg_group->get_name() << " make_sphere failed!\n"; } PolylightNode *pnode = new PolylightNode(egg_group->get_name()); pnode->set_pos(center); pnode->set_color(color); pnode->set_radius(radius); pnode->xform(LCAST(PN_stdfloat, egg_group->get_vertex_to_node())); node = pnode; } else if (egg_group->get_switch_flag()) { if (egg_group->get_switch_fps() != 0.0) { // Create a sequence node. node = new SequenceNode(egg_group->get_name()); ((SequenceNode *)node.p())->set_frame_rate(egg_group->get_switch_fps()); _sequences.insert(node); } else { // Create a switch node. node = new SwitchNode(egg_group->get_name()); } EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { make_node(*ci, node); } } else if (egg_group->has_scrolling_uvs()) { node = new UvScrollNode(egg_group->get_name(), egg_group->get_scroll_u(), egg_group->get_scroll_v(), egg_group->get_scroll_w(), egg_group->get_scroll_r()); EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { make_node(*ci, node); } } else if (egg_group->get_model_flag() || egg_group->has_dcs_type()) { // A model or DCS flag; create a model node. node = new ModelNode(egg_group->get_name()); switch (egg_group->get_dcs_type()) { case EggGroup::DC_net: DCAST(ModelNode, node)->set_preserve_transform(ModelNode::PT_net); break; case EggGroup::DC_no_touch: DCAST(ModelNode, node)->set_preserve_transform(ModelNode::PT_no_touch); break; case EggGroup::DC_local: case EggGroup::DC_default: DCAST(ModelNode, node)->set_preserve_transform(ModelNode::PT_local); break; case EggGroup::DC_none: case EggGroup::DC_unspecified: break; } EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { make_node(*ci, node); } } else { // A normal group; just create a normal node, and traverse. But // if all of the children of this group are polysets, anticipate // this for the benefit of smaller grouping, and create a single // GeomNode for all of the children. bool all_polysets = false; bool any_hidden = false; // We don't want to ever create a GeomNode under a "decal" flag, // since that can confuse the decal reparenting. if (!egg_group->determine_decal()) { check_for_polysets(egg_group, all_polysets, any_hidden); } if (all_polysets && !any_hidden) { node = new GeomNode(egg_group->get_name()); } else { node = new PandaNode(egg_group->get_name()); } EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { make_node(*ci, node); } } if (node == (PandaNode *)NULL) { return NULL; } // Associate any instances with this node. int num_group_refs = egg_group->get_num_group_refs(); for (int gri = 0; gri < num_group_refs; ++gri) { EggGroup *group_ref = egg_group->get_group_ref(gri); Groups::const_iterator gi = _groups.find(group_ref); if (gi != _groups.end()) { PandaNode *node_ref = (*gi).second; node->add_child(node_ref); } } _groups[egg_group] = node; return create_group_arc(egg_group, parent, node); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::create_group_arc // Access: Private // Description: Creates the arc parenting a new group to the scene // graph, and applies any relevant attribs to the // arc according to the EggGroup node that inspired the // group. //////////////////////////////////////////////////////////////////// PandaNode *EggLoader:: create_group_arc(EggGroup *egg_group, PandaNode *parent, PandaNode *node) { parent->add_child(node); // If the group had a transform, apply it to the node. if (egg_group->has_transform()) { CPT(TransformState) transform = make_transform(egg_group); node->set_transform(transform); node->set_prev_transform(transform); } // If the group has a billboard flag, apply that. switch (egg_group->get_billboard_type()) { case EggGroup::BT_point_camera_relative: node->set_effect(BillboardEffect::make_point_eye()); break; case EggGroup::BT_point_world_relative: node->set_effect(BillboardEffect::make_point_world()); break; case EggGroup::BT_axis: node->set_effect(BillboardEffect::make_axis()); break; case EggGroup::BT_none: break; } if (egg_group->get_decal_flag()) { if (egg_ignore_decals) { egg2pg_cat.error() << "Ignoring decal flag on " << egg_group->get_name() << "\n"; _error = true; } // If the group has the "decal" flag set, it means that all of the // descendant groups will be decaled onto the geometry within // this group. This means we'll need to reparent things a bit // afterward. _decals.insert(node); } // Copy all the tags from the group onto the node. EggGroup::TagData::const_iterator ti; for (ti = egg_group->tag_begin(); ti != egg_group->tag_end(); ++ti) { node->set_tag((*ti).first, (*ti).second); } if (egg_group->get_blend_mode() != EggGroup::BM_unspecified && egg_group->get_blend_mode() != EggGroup::BM_none) { // Apply a ColorBlendAttrib to the group. ColorBlendAttrib::Mode mode = get_color_blend_mode(egg_group->get_blend_mode()); ColorBlendAttrib::Operand a = get_color_blend_operand(egg_group->get_blend_operand_a()); ColorBlendAttrib::Operand b = get_color_blend_operand(egg_group->get_blend_operand_b()); LColor color = egg_group->get_blend_color(); node->set_attrib(ColorBlendAttrib::make(mode, a, b, color)); } // If the group specified some property that should propagate down // to the leaves, we have to remember this node and apply the // property later, after we've created the actual geometry. DeferredNodeProperty def; if (egg_group->has_collide_mask()) { def._from_collide_mask = egg_group->get_collide_mask(); def._into_collide_mask = egg_group->get_collide_mask(); def._flags |= DeferredNodeProperty::F_has_from_collide_mask | DeferredNodeProperty::F_has_into_collide_mask; } if (egg_group->has_from_collide_mask()) { def._from_collide_mask = egg_group->get_from_collide_mask(); def._flags |= DeferredNodeProperty::F_has_from_collide_mask; } if (egg_group->has_into_collide_mask()) { def._into_collide_mask = egg_group->get_into_collide_mask(); def._flags |= DeferredNodeProperty::F_has_into_collide_mask; } if (def._flags != 0) { _deferred_nodes[node] = def; } return node; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_node (EggTable) // Access: Private // Description: //////////////////////////////////////////////////////////////////// PandaNode *EggLoader:: make_node(EggTable *egg_table, PandaNode *parent) { if (egg_table->get_table_type() != EggTable::TT_bundle) { // We only do anything with bundles. Isolated tables are treated // as ordinary groups. return make_node(DCAST(EggGroupNode, egg_table), parent); } // It's an actual bundle, so make an AnimBundle from it and its // descendants. AnimBundleMaker bundle_maker(egg_table); AnimBundleNode *node = bundle_maker.make_node(); parent->add_child(node); return node; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_node (EggGroupNode) // Access: Private // Description: //////////////////////////////////////////////////////////////////// PandaNode *EggLoader:: make_node(EggGroupNode *egg_group, PandaNode *parent) { PandaNode *node = new PandaNode(egg_group->get_name()); EggGroupNode::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { make_node(*ci, node); } parent->add_child(node); return node; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::check_for_polysets // Access: Private // Description: Sets all_polysets true if all of the children of this // node represent a polyset. Sets any_hidden true if // any of those polysets are flagged hidden. //////////////////////////////////////////////////////////////////// void EggLoader:: check_for_polysets(EggGroup *egg_group, bool &all_polysets, bool &any_hidden) { all_polysets = (!egg_group->empty()); any_hidden = false; EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { if ((*ci)->is_of_type(EggBin::get_class_type())) { EggBin *egg_bin = DCAST(EggBin, (*ci)); if (egg_bin->get_bin_number() == EggBinner::BN_polyset) { // We know that all of the primitives in the bin have the same // render state, so we can get that information from the first // primitive. EggGroup::const_iterator bci = egg_bin->begin(); nassertv(bci != egg_bin->end()); const EggPrimitive *first_prim; DCAST_INTO_V(first_prim, (*bci)); const EggRenderState *render_state; DCAST_INTO_V(render_state, first_prim->get_user_data(EggRenderState::get_class_type())); if (render_state->_hidden) { any_hidden = true; } } else { all_polysets = false; return; } } else if ((*ci)->is_of_type(EggGroup::get_class_type())) { // Other kinds of children, like vertex pools, comments, // textures, etc., are ignored; but groups indicate more nodes, // so if we find a nested group it means we're not all polysets. all_polysets = false; return; } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_vertex_data // Access: Private // Description: Creates a GeomVertexData structure from the vertex // pool, for the indicated transform space. If a // GeomVertexData has already been created for this // transform, just returns it. //////////////////////////////////////////////////////////////////// PT(GeomVertexData) EggLoader:: make_vertex_data(const EggRenderState *render_state, EggVertexPool *vertex_pool, EggNode *primitive_home, const LMatrix4d &transform, TransformBlendTable *blend_table, bool is_dynamic, CharacterMaker *character_maker, bool ignore_color) { VertexPoolTransform vpt; vpt._vertex_pool = vertex_pool; vpt._bake_in_uvs = render_state->_bake_in_uvs; vpt._transform = transform; VertexPoolData::iterator di; di = _vertex_pool_data.find(vpt); if (di != _vertex_pool_data.end()) { return (*di).second; } PT(GeomVertexArrayFormat) array_format = new GeomVertexArrayFormat; array_format->add_column (InternalName::get_vertex(), vertex_pool->get_num_dimensions(), Geom::NT_stdfloat, Geom::C_point); if (vertex_pool->has_normals()) { array_format->add_column (InternalName::get_normal(), 3, Geom::NT_stdfloat, Geom::C_normal); } if (!ignore_color) { // Let's not use Direct3D-style colors on platforms where we only // have OpenGL anyway. #ifdef _WIN32 array_format->add_column(InternalName::get_color(), 1, Geom::NT_packed_dabc, Geom::C_color); #else array_format->add_column(InternalName::get_color(), 4, Geom::NT_uint8, Geom::C_color); #endif } vector_string uv_names, uvw_names, tbn_names; vertex_pool->get_uv_names(uv_names, uvw_names, tbn_names); vector_string::const_iterator ni; for (ni = uv_names.begin(); ni != uv_names.end(); ++ni) { string name = (*ni); PT(InternalName) iname = InternalName::get_texcoord_name(name); if (find(uvw_names.begin(), uvw_names.end(), name) != uvw_names.end()) { // This one actually represents 3-d texture coordinates. array_format->add_column (iname, 3, Geom::NT_stdfloat, Geom::C_texcoord); } else { array_format->add_column (iname, 2, Geom::NT_stdfloat, Geom::C_texcoord); } } for (ni = tbn_names.begin(); ni != tbn_names.end(); ++ni) { string name = (*ni); PT(InternalName) iname_t = InternalName::get_tangent_name(name); PT(InternalName) iname_b = InternalName::get_binormal_name(name); array_format->add_column (iname_t, 3, Geom::NT_stdfloat, Geom::C_vector); array_format->add_column (iname_b, 3, Geom::NT_stdfloat, Geom::C_vector); } vector_string aux_names; vertex_pool->get_aux_names(aux_names); for (ni = aux_names.begin(); ni != aux_names.end(); ++ni) { string name = (*ni); PT(InternalName) iname = InternalName::make(name); array_format->add_column (iname, 4, Geom::NT_stdfloat, Geom::C_other); } PT(GeomVertexFormat) temp_format = new GeomVertexFormat(array_format); PT(SliderTable) slider_table; string name = _data->get_egg_filename().get_basename_wo_extension(); if (is_dynamic) { // If it's a dynamic object, we need a TransformBlendTable and // maybe a SliderTable, and additional columns in the vertex data: // one that indexes into the blend table per vertex, and also // one for each different type of morph delta. // Tell the format that we're setting it up for Panda-based // animation. GeomVertexAnimationSpec animation; animation.set_panda(); temp_format->set_animation(animation); PT(GeomVertexArrayFormat) anim_array_format = new GeomVertexArrayFormat; anim_array_format->add_column (InternalName::get_transform_blend(), 1, Geom::NT_uint16, Geom::C_index); temp_format->add_array(anim_array_format); pmap<string, BitArray> slider_names; EggVertexPool::const_iterator vi; for (vi = vertex_pool->begin(); vi != vertex_pool->end(); ++vi) { EggVertex *vertex = (*vi); EggMorphVertexList::const_iterator mvi; for (mvi = vertex->_dxyzs.begin(); mvi != vertex->_dxyzs.end(); ++mvi) { slider_names[(*mvi).get_name()].set_bit(vertex->get_index()); record_morph(anim_array_format, character_maker, (*mvi).get_name(), InternalName::get_vertex(), 3); } if (vertex->has_normal()) { EggMorphNormalList::const_iterator mni; for (mni = vertex->_dnormals.begin(); mni != vertex->_dnormals.end(); ++mni) { slider_names[(*mni).get_name()].set_bit(vertex->get_index()); record_morph(anim_array_format, character_maker, (*mni).get_name(), InternalName::get_normal(), 3); } } if (!ignore_color && vertex->has_color()) { EggMorphColorList::const_iterator mci; for (mci = vertex->_drgbas.begin(); mci != vertex->_drgbas.end(); ++mci) { slider_names[(*mci).get_name()].set_bit(vertex->get_index()); record_morph(anim_array_format, character_maker, (*mci).get_name(), InternalName::get_color(), 4); } } EggVertex::const_uv_iterator uvi; for (uvi = vertex->uv_begin(); uvi != vertex->uv_end(); ++uvi) { EggVertexUV *egg_uv = (*uvi); string name = egg_uv->get_name(); bool has_w = (find(uvw_names.begin(), uvw_names.end(), name) != uvw_names.end()); PT(InternalName) iname = InternalName::get_texcoord_name(name); EggMorphTexCoordList::const_iterator mti; for (mti = egg_uv->_duvs.begin(); mti != egg_uv->_duvs.end(); ++mti) { slider_names[(*mti).get_name()].set_bit(vertex->get_index()); record_morph(anim_array_format, character_maker, (*mti).get_name(), iname, has_w ? 3 : 2); } } } if (!slider_names.empty()) { // If we have any sliders at all, create a table for them. slider_table = new SliderTable; pmap<string, BitArray>::iterator si; for (si = slider_names.begin(); si != slider_names.end(); ++si) { PT(VertexSlider) slider = character_maker->egg_to_slider((*si).first); slider_table->add_slider(slider, (*si).second); } } // We'll also assign the character name to the vertex data, so it // will show up in PStats. name = character_maker->get_name(); } temp_format->maybe_align_columns_for_animation(); CPT(GeomVertexFormat) format = GeomVertexFormat::register_format(temp_format); // Now create a new GeomVertexData using the indicated format. It // is actually correct to create it with UH_static even though it // represents a dynamic object, because the vertex data itself won't // be changing--just the result of applying the animation is // dynamic. PT(GeomVertexData) vertex_data = new GeomVertexData(name, format, Geom::UH_static); vertex_data->reserve_num_rows(vertex_pool->size()); vertex_data->set_transform_blend_table(blend_table); if (slider_table != (SliderTable *)NULL) { vertex_data->set_slider_table(SliderTable::register_table(slider_table)); } // And fill in the data from the vertex pool. EggVertexPool::const_iterator vi; for (vi = vertex_pool->begin(); vi != vertex_pool->end(); ++vi) { GeomVertexWriter gvw(vertex_data); EggVertex *vertex = (*vi); gvw.set_row(vertex->get_index()); gvw.set_column(InternalName::get_vertex()); gvw.add_data4d(vertex->get_pos4() * transform); if (is_dynamic) { EggMorphVertexList::const_iterator mvi; for (mvi = vertex->_dxyzs.begin(); mvi != vertex->_dxyzs.end(); ++mvi) { const EggMorphVertex &morph = (*mvi); CPT(InternalName) delta_name = InternalName::get_morph(InternalName::get_vertex(), morph.get_name()); gvw.set_column(delta_name); gvw.add_data3d(morph.get_offset() * transform); } } if (vertex->has_normal()) { gvw.set_column(InternalName::get_normal()); LNormald orig_normal = vertex->get_normal(); LNormald transformed_normal = normalize(orig_normal * transform); gvw.add_data3d(transformed_normal); if (is_dynamic) { EggMorphNormalList::const_iterator mni; for (mni = vertex->_dnormals.begin(); mni != vertex->_dnormals.end(); ++mni) { const EggMorphNormal &morph = (*mni); CPT(InternalName) delta_name = InternalName::get_morph(InternalName::get_normal(), morph.get_name()); gvw.set_column(delta_name); LNormald morphed_normal = orig_normal + morph.get_offset(); LNormald transformed_morphed_normal = normalize(morphed_normal * transform); LVector3d delta = transformed_morphed_normal - transformed_normal; gvw.add_data3d(delta); } } } if (!ignore_color && vertex->has_color()) { gvw.set_column(InternalName::get_color()); gvw.add_data4(vertex->get_color()); if (is_dynamic) { EggMorphColorList::const_iterator mci; for (mci = vertex->_drgbas.begin(); mci != vertex->_drgbas.end(); ++mci) { const EggMorphColor &morph = (*mci); CPT(InternalName) delta_name = InternalName::get_morph(InternalName::get_color(), morph.get_name()); gvw.set_column(delta_name); gvw.add_data4(morph.get_offset()); } } } EggVertex::const_uv_iterator uvi; for (uvi = vertex->uv_begin(); uvi != vertex->uv_end(); ++uvi) { EggVertexUV *egg_uv = (*uvi); LTexCoord3d orig_uvw = egg_uv->get_uvw(); LTexCoord3d uvw = egg_uv->get_uvw(); string name = egg_uv->get_name(); PT(InternalName) iname = InternalName::get_texcoord_name(name); gvw.set_column(iname); BakeInUVs::const_iterator buv = render_state->_bake_in_uvs.find(iname); if (buv != render_state->_bake_in_uvs.end()) { // If we are to bake in a texture matrix, do so now. uvw = uvw * (*buv).second->get_transform3d(); } gvw.set_data3d(uvw); if (is_dynamic) { EggMorphTexCoordList::const_iterator mti; for (mti = egg_uv->_duvs.begin(); mti != egg_uv->_duvs.end(); ++mti) { const EggMorphTexCoord &morph = (*mti); CPT(InternalName) delta_name = InternalName::get_morph(iname, morph.get_name()); gvw.set_column(delta_name); LTexCoord3d duvw = morph.get_offset(); if (buv != render_state->_bake_in_uvs.end()) { LTexCoord3d new_uvw = orig_uvw + duvw; duvw = (new_uvw * (*buv).second->get_transform3d()) - uvw; } gvw.add_data3d(duvw); } } // Also add the tangent and binormal, if present. if (egg_uv->has_tangent() && egg_uv->has_binormal()) { PT(InternalName) iname = InternalName::get_tangent_name(name); gvw.set_column(iname); if (gvw.has_column()) { LVector3d tangent = egg_uv->get_tangent(); LVector3d binormal = egg_uv->get_binormal(); gvw.add_data3d(tangent); gvw.set_column(InternalName::get_binormal_name(name)); gvw.add_data3d(binormal); } } } EggVertex::const_aux_iterator auxi; for (auxi = vertex->aux_begin(); auxi != vertex->aux_end(); ++auxi) { EggVertexAux *egg_aux = (*auxi); LVecBase4d aux = egg_aux->get_aux(); string name = egg_aux->get_name(); PT(InternalName) iname = InternalName::make(name); gvw.set_column(iname); gvw.set_data4d(aux); } if (is_dynamic) { int table_index = vertex->get_external_index(); gvw.set_column(InternalName::get_transform_blend()); gvw.set_data1i(table_index); } } bool inserted = _vertex_pool_data.insert (VertexPoolData::value_type(vpt, vertex_data)).second; nassertr(inserted, vertex_data); Thread::consider_yield(); return vertex_data; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_blend_table // Access: Private // Description: //////////////////////////////////////////////////////////////////// PT(TransformBlendTable) EggLoader:: make_blend_table(EggVertexPool *vertex_pool, EggNode *primitive_home, CharacterMaker *character_maker) { PT(TransformBlendTable) blend_table; blend_table = new TransformBlendTable; blend_table->set_rows(SparseArray::lower_on(vertex_pool->size())); EggVertexPool::const_iterator vi; for (vi = vertex_pool->begin(); vi != vertex_pool->end(); ++vi) { EggVertex *vertex = (*vi); // Figure out the transforms affecting this particular vertex. TransformBlend blend; if (vertex->gref_size() == 0) { // If the vertex has no explicit membership, it belongs right // where it is. PT(VertexTransform) vt = character_maker->egg_to_transform(primitive_home); nassertr(vt != (VertexTransform *)NULL, NULL); blend.add_transform(vt, 1.0f); } else { // If the vertex does have an explicit membership, ignore its // parentage and assign it where it wants to be. double quantize = egg_vertex_membership_quantize; EggVertex::GroupRef::const_iterator gri; for (gri = vertex->gref_begin(); gri != vertex->gref_end(); ++gri) { EggGroup *egg_joint = (*gri); double membership = egg_joint->get_vertex_membership(vertex); if (quantize != 0.0) { membership = cfloor(membership / quantize + 0.5) * quantize; } PT(VertexTransform) vt = character_maker->egg_to_transform(egg_joint); nassertr(vt != (VertexTransform *)NULL, NULL); blend.add_transform(vt, membership); } } if (egg_vertex_max_num_joints >= 0) { blend.limit_transforms(egg_vertex_max_num_joints); } blend.normalize_weights(); int table_index = blend_table->add_blend(blend); // We take advantage of the "external index" field of the // EggVertex to temporarily store the transform blend index. vertex->set_external_index(table_index); } return blend_table; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::record_morph // Access: Private // Description: //////////////////////////////////////////////////////////////////// void EggLoader:: record_morph(GeomVertexArrayFormat *array_format, CharacterMaker *character_maker, const string &morph_name, InternalName *column_name, int num_components) { PT(InternalName) delta_name = InternalName::get_morph(column_name, morph_name); if (!array_format->has_column(delta_name)) { array_format->add_column (delta_name, num_components, Geom::NT_stdfloat, Geom::C_morph_delta); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_primitive // Access: Private // Description: Creates a GeomPrimitive corresponding to the // indicated EggPrimitive, and adds it to the set. //////////////////////////////////////////////////////////////////// void EggLoader:: make_primitive(const EggRenderState *render_state, EggPrimitive *egg_prim, EggLoader::UniquePrimitives &unique_primitives, EggLoader::Primitives &primitives, bool has_overall_color, const LColor &overall_color) { PT(GeomPrimitive) primitive; if (egg_prim->is_of_type(EggPolygon::get_class_type())) { if (egg_prim->size() == 3) { primitive = new GeomTriangles(Geom::UH_static); } } else if (egg_prim->is_of_type(EggTriangleStrip::get_class_type())) { primitive = new GeomTristrips(Geom::UH_static); } else if (egg_prim->is_of_type(EggTriangleFan::get_class_type())) { primitive = new GeomTrifans(Geom::UH_static); } else if (egg_prim->is_of_type(EggLine::get_class_type())) { if (egg_prim->size() == 2) { primitive = new GeomLines(Geom::UH_static); } else { primitive = new GeomLinestrips(Geom::UH_static); } } else if (egg_prim->is_of_type(EggPoint::get_class_type())) { primitive = new GeomPoints(Geom::UH_static); } else if (egg_prim->is_of_type(EggPatch::get_class_type())) { int num_vertices = egg_prim->size(); primitive = new GeomPatches(num_vertices, Geom::UH_static); } if (primitive == (GeomPrimitive *)NULL) { // Don't know how to make this kind of primitive. egg2pg_cat.warning() << "Ignoring " << egg_prim->get_type() << "\n"; return; } if (render_state->_flat_shaded) { primitive->set_shade_model(GeomPrimitive::SM_flat_first_vertex); } else if (egg_prim->get_shading() == EggPrimitive::S_overall) { primitive->set_shade_model(GeomPrimitive::SM_uniform); } else { primitive->set_shade_model(GeomPrimitive::SM_smooth); } // Insert the primitive into the set, but if we already have a // primitive of that type, reset the pointer to that one instead. PrimitiveUnifier pu(primitive); pair<UniquePrimitives::iterator, bool> result = unique_primitives.insert(UniquePrimitives::value_type(pu, primitive)); if (result.second) { // This was the first primitive of this type. Store it. primitives.push_back(primitive); if (egg2pg_cat.is_debug()) { egg2pg_cat.debug() << "First primitive of type " << primitive->get_type() << ": " << primitive << "\n"; } } GeomPrimitive *orig_prim = (*result.first).second; // Make sure we don't try to put more than egg_max_indices into any // one GeomPrimitive. if (orig_prim->get_num_vertices() + egg_prim->size() <= (unsigned int)egg_max_indices) { primitive = orig_prim; } else if (orig_prim != primitive) { // If the old primitive is full, keep the new primitive from now // on. (*result.first).second = primitive; if (egg2pg_cat.is_debug()) { egg2pg_cat.debug() << "Next primitive of type " << primitive->get_type() << ": " << primitive << "\n"; } primitives.push_back(primitive); } // Now add the vertices. EggPrimitive::const_iterator vi; for (vi = egg_prim->begin(); vi != egg_prim->end(); ++vi) { primitive->add_vertex((*vi)->get_index()); } primitive->close_primitive(); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::set_portal_polygon // Access: Private // Description: Defines the PortalNode from the first polygon found // within this group. //////////////////////////////////////////////////////////////////// void EggLoader:: set_portal_polygon(EggGroup *egg_group, PortalNode *pnode) { pnode->clear_vertices(); PT(EggPolygon) poly = find_first_polygon(egg_group); if (poly != (EggPolygon *)NULL) { LMatrix4d mat = poly->get_vertex_to_node(); EggPolygon::const_iterator vi; for (vi = poly->begin(); vi != poly->end(); ++vi) { LVertexd vert = (*vi)->get_pos3() * mat; pnode->add_vertex(LCAST(PN_stdfloat, vert)); } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::set_occluder_polygon // Access: Private // Description: Defines the OccluderNode from the first polygon found // within this group. //////////////////////////////////////////////////////////////////// void EggLoader:: set_occluder_polygon(EggGroup *egg_group, OccluderNode *pnode) { PT(EggPolygon) poly = find_first_polygon(egg_group); if (poly != (EggPolygon *)NULL) { if (poly->size() != 4) { egg2pg_cat.error() << "Invalid number of vertices for " << egg_group->get_name() << "\n"; } else { LMatrix4d mat = poly->get_vertex_to_node(); EggPolygon::const_iterator vi; LPoint3d v0 = (*poly)[0]->get_pos3() * mat; LPoint3d v1 = (*poly)[1]->get_pos3() * mat; LPoint3d v2 = (*poly)[2]->get_pos3() * mat; LPoint3d v3 = (*poly)[3]->get_pos3() * mat; pnode->set_vertices(LCAST(PN_stdfloat, v0), LCAST(PN_stdfloat, v1), LCAST(PN_stdfloat, v2), LCAST(PN_stdfloat, v3)); if (poly->get_bface_flag()) { pnode->set_double_sided(true); } } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::find_first_polygon // Access: Private // Description: Returns the first EggPolygon found at or below the // indicated node. //////////////////////////////////////////////////////////////////// PT(EggPolygon) EggLoader:: find_first_polygon(EggGroup *egg_group) { // Does this group have any polygons? EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { if ((*ci)->is_of_type(EggPolygon::get_class_type())) { // Yes! Return the polygon. return DCAST(EggPolygon, (*ci)); } } // Well, the group had no polygons; look for a child group that // does. for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { if ((*ci)->is_of_type(EggGroup::get_class_type())) { EggGroup *child_group = DCAST(EggGroup, *ci); PT(EggPolygon) found = find_first_polygon(child_group); if (found != (EggPolygon *)NULL) { return found; } } } // We got nothing. return NULL; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_sphere // Access: Private // Description: Creates a single generic Sphere corresponding // to the polygons associated with this group. // This sphere is used by make_collision_sphere and // Polylight sphere. It could be used for other spheres. //////////////////////////////////////////////////////////////////// bool EggLoader:: make_sphere(EggGroup *egg_group, EggGroup::CollideFlags flags, LPoint3 &center, PN_stdfloat &radius, LColor &color) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); if (geom_group != (EggGroup *)NULL) { // Collect all of the vertices. pset<EggVertex *> vertices; EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPrimitive::get_class_type())) { EggPrimitive *prim = DCAST(EggPrimitive, *ci); EggPrimitive::const_iterator pi; for (pi = prim->begin(); pi != prim->end(); ++pi) { vertices.insert(*pi); } } } // Now average together all of the vertices to get a center. int num_vertices = 0; LPoint3d d_center(0.0, 0.0, 0.0); pset<EggVertex *>::const_iterator vi; for (vi = vertices.begin(); vi != vertices.end(); ++vi) { EggVertex *vtx = (*vi); d_center += vtx->get_pos3(); num_vertices++; } if (num_vertices > 0) { d_center /= (double)num_vertices; //egg2pg_cat.debug() << "make_sphere d_center: " << d_center << "\n"; // And the furthest vertex determines the radius. double radius2 = 0.0; for (vi = vertices.begin(); vi != vertices.end(); ++vi) { EggVertex *vtx = (*vi); LPoint3d p3 = vtx->get_pos3(); LVector3d v = p3 - d_center; radius2 = max(radius2, v.length_squared()); } center = LCAST(PN_stdfloat, d_center); radius = sqrtf(radius2); //egg2pg_cat.debug() << "make_sphere radius: " << radius << "\n"; vi = vertices.begin(); EggVertex *clr_vtx = (*vi); color = clr_vtx->get_color(); return true; } } return false; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_box // Access: Private // Description: Creates a single generic Box corresponding // to the polygons associated with this group. // This box is used by make_collision_box. //////////////////////////////////////////////////////////////////// bool EggLoader:: make_box(EggGroup *egg_group, EggGroup::CollideFlags flags, LPoint3 &min_p, LPoint3 &max_p, LColor &color) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); if (geom_group != (EggGroup *)NULL) { // Collect all of the vertices. pset<EggVertex *> vertices; EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPrimitive::get_class_type())) { EggPrimitive *prim = DCAST(EggPrimitive, *ci); EggPrimitive::const_iterator pi; for (pi = prim->begin(); pi != prim->end(); ++pi) { vertices.insert(*pi); } } } // Now find the min/max points pset<EggVertex *>::const_iterator vi; vi = vertices.begin(); if (vi == vertices.end()) { // No vertices, no bounding box. min_p.set(0, 0, 0); max_p.set(0, 0, 0); return false; } EggVertex *vertex = (*vi); LVertexd min_pd = vertex->get_pos3(); LVertexd max_pd = min_pd; color = vertex->get_color(); for (++vi; vi != vertices.end(); ++vi) { vertex = (*vi); const LVertexd &pos = vertex->get_pos3(); min_pd.set(min(min_pd[0], pos[0]), min(min_pd[1], pos[1]), min(min_pd[2], pos[2])); max_pd.set(max(max_pd[0], pos[0]), max(max_pd[1], pos[1]), max(max_pd[2], pos[2])); } min_p = LCAST(PN_stdfloat, min_pd); max_p = LCAST(PN_stdfloat, max_pd); return (min_pd != max_pd); } return false; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_solids // Access: Private // Description: Creates CollisionSolids corresponding to the // collision geometry indicated at the given node and // below. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_solids(EggGroup *start_group, EggGroup *egg_group, CollisionNode *cnode) { if (egg_group->get_cs_type() != EggGroup::CST_none) { start_group = egg_group; } switch (start_group->get_cs_type()) { case EggGroup::CST_none: // No collision flags; do nothing. Don't even traverse further. return; case EggGroup::CST_plane: make_collision_plane(egg_group, cnode, start_group->get_collide_flags()); break; case EggGroup::CST_polygon: make_collision_polygon(egg_group, cnode, start_group->get_collide_flags()); break; case EggGroup::CST_polyset: make_collision_polyset(egg_group, cnode, start_group->get_collide_flags()); break; case EggGroup::CST_sphere: make_collision_sphere(egg_group, cnode, start_group->get_collide_flags()); break; case EggGroup::CST_box: make_collision_box(egg_group, cnode, start_group->get_collide_flags()); break; case EggGroup::CST_inv_sphere: make_collision_inv_sphere(egg_group, cnode, start_group->get_collide_flags()); break; case EggGroup::CST_tube: make_collision_tube(egg_group, cnode, start_group->get_collide_flags()); break; case EggGroup::CST_floor_mesh: make_collision_floor_mesh(egg_group, cnode, start_group->get_collide_flags()); break; } if ((start_group->get_collide_flags() & EggGroup::CF_descend) != 0) { // Now pick up everything below. EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { if ((*ci)->is_of_type(EggGroup::get_class_type())) { make_collision_solids(start_group, DCAST(EggGroup, *ci), cnode); } } } else { egg2pg_cat.warning() << "Using <Collide> without 'descend' is deprecated. 'descend' " << "will become the default in a future version of Panda3D.\n"; } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_plane // Access: Private // Description: Creates a single CollisionPlane corresponding // to the first polygon associated with this group. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_plane(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); if (geom_group != (EggGroup *)NULL) { EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPolygon::get_class_type())) { CollisionPlane *csplane = create_collision_plane(DCAST(EggPolygon, *ci), egg_group); if (csplane != (CollisionPlane *)NULL) { apply_collision_flags(csplane, flags); cnode->add_solid(csplane); return; } } else if ((*ci)->is_of_type(EggCompositePrimitive::get_class_type())) { EggCompositePrimitive *comp = DCAST(EggCompositePrimitive, *ci); PT(EggGroup) temp_group = new EggGroup; if (comp->triangulate_into(temp_group)) { make_collision_plane(temp_group, cnode, flags); return; } } } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_floor_mesh // Access: Private // Description: Creates a single CollisionPolygon corresponding // to the first polygon associated with this group. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_floor_mesh(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); if (geom_group != (EggGroup *)NULL) { create_collision_floor_mesh(cnode, geom_group,flags); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_polygon // Access: Private // Description: Creates a single CollisionPolygon corresponding // to the first polygon associated with this group. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_polygon(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); if (geom_group != (EggGroup *)NULL) { EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPolygon::get_class_type())) { create_collision_polygons(cnode, DCAST(EggPolygon, *ci), egg_group, flags); } else if ((*ci)->is_of_type(EggCompositePrimitive::get_class_type())) { EggCompositePrimitive *comp = DCAST(EggCompositePrimitive, *ci); PT(EggGroup) temp_group = new EggGroup; if (comp->triangulate_into(temp_group)) { make_collision_polygon(temp_group, cnode, flags); return; } } } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_polyset // Access: Private // Description: Creates a series of CollisionPolygons corresponding // to the polygons associated with this group. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_polyset(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); if (geom_group != (EggGroup *)NULL) { EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPolygon::get_class_type())) { create_collision_polygons(cnode, DCAST(EggPolygon, *ci), egg_group, flags); } else if ((*ci)->is_of_type(EggCompositePrimitive::get_class_type())) { EggCompositePrimitive *comp = DCAST(EggCompositePrimitive, *ci); PT(EggGroup) temp_group = new EggGroup; if (comp->triangulate_into(temp_group)) { make_collision_polyset(temp_group, cnode, flags); } } } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_sphere // Access: Private // Description: Creates a single CollisionSphere corresponding // to the polygons associated with this group. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_sphere(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { LPoint3 center; PN_stdfloat radius; LColor dummycolor; if (make_sphere(egg_group, flags, center, radius, dummycolor)) { CollisionSphere *cssphere = new CollisionSphere(center, radius); apply_collision_flags(cssphere, flags); cnode->add_solid(cssphere); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_box // Access: Private // Description: Creates a single CollisionBox corresponding // to the polygons associated with this group. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_box(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { LPoint3 min_p; LPoint3 max_p; LColor dummycolor; if (make_box(egg_group, flags, min_p, max_p, dummycolor)) { CollisionBox *csbox = new CollisionBox(min_p, max_p); apply_collision_flags(csbox, flags); cnode->add_solid(csbox); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_inv_sphere // Access: Private // Description: Creates a single CollisionInvSphere corresponding // to the polygons associated with this group. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_inv_sphere(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { LPoint3 center; PN_stdfloat radius; LColor dummycolor; if (make_sphere(egg_group, flags, center, radius, dummycolor)) { CollisionInvSphere *cssphere = new CollisionInvSphere(center, radius); apply_collision_flags(cssphere, flags); cnode->add_solid(cssphere); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::make_collision_tube // Access: Private // Description: Creates a single CollisionTube corresponding // to the polygons associated with this group. //////////////////////////////////////////////////////////////////// void EggLoader:: make_collision_tube(EggGroup *egg_group, CollisionNode *cnode, EggGroup::CollideFlags flags) { EggGroup *geom_group = find_collision_geometry(egg_group, flags); if (geom_group != (EggGroup *)NULL) { // Collect all of the vertices. pset<EggVertex *> vertices; EggGroup::const_iterator ci; for (ci = geom_group->begin(); ci != geom_group->end(); ++ci) { if ((*ci)->is_of_type(EggPrimitive::get_class_type())) { EggPrimitive *prim = DCAST(EggPrimitive, *ci); EggPrimitive::const_iterator pi; for (pi = prim->begin(); pi != prim->end(); ++pi) { vertices.insert(*pi); } } } // Now store the 3-d values in a vector for convenient access (and // also determine the centroid). We compute this in node space. size_t num_vertices = vertices.size(); if (num_vertices != 0) { pvector<LPoint3d> vpos; vpos.reserve(num_vertices); LPoint3d center(0.0, 0.0, 0.0); pset<EggVertex *>::const_iterator vi; for (vi = vertices.begin(); vi != vertices.end(); ++vi) { EggVertex *vtx = (*vi); const LPoint3d &pos = vtx->get_pos3(); vpos.push_back(pos); center += pos; } center /= (double)num_vertices; // Now that we have the centroid, we have to try to figure out // the cylinder's major axis. Start by finding a point farthest // from the centroid. size_t i; double radius2 = 0.0; LPoint3d far_a = center; for (i = 0; i < num_vertices; i++) { double dist2 = (vpos[i] - center).length_squared(); if (dist2 > radius2) { radius2 = dist2; far_a = vpos[i]; } } // The point we have found above, far_a, must be one one of the // endcaps. Now find another point, far_b, that is the farthest // from far_a. This will be a point on the other endcap. radius2 = 0.0; LPoint3d far_b = center; for (i = 0; i < num_vertices; i++) { double dist2 = (vpos[i] - far_a).length_squared(); if (dist2 > radius2) { radius2 = dist2; far_b = vpos[i]; } } // Now we have far_a and far_b, one point on each endcap. // However, these points are not necessarily centered on the // endcaps, so we haven't figured out the cylinder's axis yet // (the line between far_a and far_b will probably pass through // the cylinder at an angle). // So we still need to determine the full set of points in each // endcap. To do this, we pass back through the set of points, // categorizing each point into either "endcap a" or "endcap b". // We also leave a hefty chunk of points in the middle // uncategorized; this helps prevent us from getting a little // bit lopsided with points near the middle that may appear to // be closer to the wrong endcap. LPoint3d cap_a_center(0.0, 0.0, 0.0); LPoint3d cap_b_center(0.0, 0.0, 0.0); int num_a = 0; int num_b = 0; // This is the threshold length; points farther away from the // center than this are deemed to be in one endcap or the other. double center_length = (far_a - far_b).length() / 4.0; double center_length2 = center_length * center_length; for (i = 0; i < num_vertices; i++) { double dist2 = (vpos[i] - center).length_squared(); if (dist2 > center_length2) { // This point is farther away from the center than // center_length; therefore it belongs in an endcap. double dist_a2 = (vpos[i] - far_a).length_squared(); double dist_b2 = (vpos[i] - far_b).length_squared(); if (dist_a2 < dist_b2) { // It's in endcap a. cap_a_center += vpos[i]; num_a++; } else { // It's in endcap b. cap_b_center += vpos[i]; num_b++; } } } if (num_a > 0 && num_b > 0) { cap_a_center /= (double)num_a; cap_b_center /= (double)num_b; // Now we finally have the major axis of the cylinder. LVector3d axis = cap_b_center - cap_a_center; axis.normalize(); // If the axis is *almost* parallel with a major axis, assume // it is meant to be exactly parallel. if (IS_THRESHOLD_ZERO(axis[0], 0.01)) { axis[0] = 0.0; } if (IS_THRESHOLD_ZERO(axis[1], 0.01)) { axis[1] = 0.0; } if (IS_THRESHOLD_ZERO(axis[2], 0.01)) { axis[2] = 0.0; } axis.normalize(); // Transform all of the points so that the major axis is along // the Y axis, and the origin is the center. This is very // similar to the CollisionTube's idea of its canonical // orientation (although not exactly the same, since it is // centered on the origin instead of having point_a on the // origin). It makes it easier to determine the length and // radius of the cylinder. LMatrix4d mat; look_at(mat, axis, LVector3d(0.0, 0.0, 1.0), CS_zup_right); mat.set_row(3, center); LMatrix4d inv_mat; inv_mat.invert_from(mat); for (i = 0; i < num_vertices; i++) { vpos[i] = vpos[i] * inv_mat; } double max_radius2 = 0.0; // Now determine the radius. for (i = 0; i < num_vertices; i++) { LVector2d v(vpos[i][0], vpos[i][2]); double radius2 = v.length_squared(); if (radius2 > max_radius2) { max_radius2 = radius2; } } // And with the radius, we can determine the length. We need // to know the radius first because we want the round endcaps // to enclose all points. double min_y = 0.0; double max_y = 0.0; for (i = 0; i < num_vertices; i++) { LVector2d v(vpos[i][0], vpos[i][2]); double radius2 = v.length_squared(); if (vpos[i][1] < min_y) { // Adjust the Y pos to account for the point's distance // from the axis. double factor = sqrt(max_radius2 - radius2); min_y = min(min_y, vpos[i][1] + factor); } else if (vpos[i][1] > max_y) { double factor = sqrt(max_radius2 - radius2); max_y = max(max_y, vpos[i][1] - factor); } } double length = max_y - min_y; double radius = sqrt(max_radius2); // Finally, we have everything we need to define the cylinder. LVector3d half = axis * (length / 2.0); LPoint3d point_a = center - half; LPoint3d point_b = center + half; CollisionTube *cstube = new CollisionTube(LCAST(PN_stdfloat, point_a), LCAST(PN_stdfloat, point_b), radius); apply_collision_flags(cstube, flags); cnode->add_solid(cstube); } } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::apply_collision_flags // Access: Private // Description: Does funny stuff to the CollisionSolid as // appropriate, based on the settings of the given // CollideFlags. //////////////////////////////////////////////////////////////////// void EggLoader:: apply_collision_flags(CollisionSolid *solid, EggGroup::CollideFlags flags) { if ((flags & EggGroup::CF_intangible) != 0) { solid->set_tangible(false); } if ((flags & EggGroup::CF_level) != 0) { solid->set_effective_normal(LVector3::up()); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::find_collision_geometry // Access: Private // Description: Looks for the node, at or below the indicated node, // that contains the associated collision geometry. //////////////////////////////////////////////////////////////////// EggGroup *EggLoader:: find_collision_geometry(EggGroup *egg_group, EggGroup::CollideFlags flags) { if ((flags & EggGroup::CF_descend) != 0) { // If we have the "descend" instruction, we'll get to it when we // get to it. Don't worry about it now. return egg_group; } // Does this group have any polygons? EggGroup::const_iterator ci; for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { if ((*ci)->is_of_type(EggPolygon::get_class_type())) { // Yes! Use this group. return egg_group; } } // Well, the group had no polygons; look for a child group that has // the same collision type. for (ci = egg_group->begin(); ci != egg_group->end(); ++ci) { if ((*ci)->is_of_type(EggGroup::get_class_type())) { EggGroup *child_group = DCAST(EggGroup, *ci); if (child_group->get_cs_type() == egg_group->get_cs_type()) { return child_group; } } } // We got nothing. return NULL; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::create_collision_plane // Access: Private // Description: Creates a single CollisionPlane from the indicated // EggPolygon. //////////////////////////////////////////////////////////////////// CollisionPlane *EggLoader:: create_collision_plane(EggPolygon *egg_poly, EggGroup *parent_group) { if (!egg_poly->cleanup()) { egg2pg_cat.info() << "Ignoring degenerate collision plane in " << parent_group->get_name() << "\n"; return NULL; } if (!egg_poly->is_planar()) { egg2pg_cat.warning() << "Non-planar polygon defining collision plane in " << parent_group->get_name() << "\n"; } pvector<LVertex> vertices; if (!egg_poly->empty()) { EggPolygon::const_iterator vi; vi = egg_poly->begin(); LVertexd vert = (*vi)->get_pos3(); vertices.push_back(LCAST(PN_stdfloat, vert)); LVertexd last_vert = vert; ++vi; while (vi != egg_poly->end()) { vert = (*vi)->get_pos3(); if (!vert.almost_equal(last_vert)) { vertices.push_back(LCAST(PN_stdfloat, vert)); } last_vert = vert; ++vi; } } if (vertices.size() < 3) { return NULL; } LPlane plane(vertices[0], vertices[1], vertices[2]); return new CollisionPlane(plane); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::create_collision_polygons // Access: Private // Description: Creates one or more CollisionPolygons from the // indicated EggPolygon, and adds them to the indicated // CollisionNode. //////////////////////////////////////////////////////////////////// void EggLoader:: create_collision_polygons(CollisionNode *cnode, EggPolygon *egg_poly, EggGroup *parent_group, EggGroup::CollideFlags flags) { PT(EggGroup) group = new EggGroup; if (!egg_poly->triangulate_into(group, false)) { egg2pg_cat.info() << "Ignoring degenerate collision polygon in " << parent_group->get_name() << "\n"; return; } if (group->size() != 1) { egg2pg_cat.info() << "Triangulating concave or non-planar collision polygon in " << parent_group->get_name() << "\n"; } EggGroup::iterator ci; for (ci = group->begin(); ci != group->end(); ++ci) { EggPolygon *poly = DCAST(EggPolygon, *ci); pvector<LVertex> vertices; if (!poly->empty()) { EggPolygon::const_iterator vi; vi = poly->begin(); LVertexd vert = (*vi)->get_pos3(); vertices.push_back(LCAST(PN_stdfloat, vert)); LVertexd last_vert = vert; ++vi; while (vi != poly->end()) { vert = (*vi)->get_pos3(); if (!vert.almost_equal(last_vert)) { vertices.push_back(LCAST(PN_stdfloat, vert)); } last_vert = vert; ++vi; } } if (vertices.size() >= 3) { const LVertex *vertices_begin = &vertices[0]; const LVertex *vertices_end = vertices_begin + vertices.size(); PT(CollisionPolygon) cspoly = new CollisionPolygon(vertices_begin, vertices_end); if (cspoly->is_valid()) { apply_collision_flags(cspoly, flags); cnode->add_solid(cspoly); } } } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::create_collision_floor_mesh // Access: Private // Description: Creates a CollisionFloorMesh from the // indicated EggPolygons, and adds it to the indicated // CollisionNode. //////////////////////////////////////////////////////////////////// void EggLoader:: create_collision_floor_mesh(CollisionNode *cnode, EggGroup *parent_group, EggGroup::CollideFlags flags) { PT(EggGroup) group = new EggGroup; EggVertexPool pool("floorMesh"); pool.local_object(); EggGroup::const_iterator egi; for (egi = parent_group->begin(); egi != parent_group->end(); ++egi) { if ((*egi)->is_of_type(EggPolygon::get_class_type())) { EggPolygon * poly = DCAST(EggPolygon, *egi); if (!poly->triangulate_into(group, false)) { egg2pg_cat.info() << "Ignoring degenerate collision polygon in " << parent_group->get_name() << "\n"; return; } } } if(group->size() == 0) { egg2pg_cat.info() << "empty collision solid\n"; return; } PT(CollisionFloorMesh) cm = new CollisionFloorMesh; pvector<CollisionFloorMesh::TriangleIndices> triangles; EggGroup::iterator ci; for (ci = group->begin(); ci != group->end(); ++ci) { EggPolygon *poly = DCAST(EggPolygon, *ci); if (poly->get_num_vertices() == 3) { CollisionFloorMesh::TriangleIndices tri; //generate a shared vertex triangle from the vertex pool tri.p1=pool.create_unique_vertex(*poly->get_vertex(0))->get_index(); tri.p2=pool.create_unique_vertex(*poly->get_vertex(1))->get_index(); tri.p3=pool.create_unique_vertex(*poly->get_vertex(2))->get_index(); triangles.push_back(tri); } else if (poly->get_num_vertices() == 4) { //this is a case that really shouldn't happen, but appears to be required //-split up the quad int 2 tris. CollisionFloorMesh::TriangleIndices tri; CollisionFloorMesh::TriangleIndices tri2; //generate a shared vertex triangle from the vertex pool tri.p1=pool.create_unique_vertex(*poly->get_vertex(0))->get_index(); tri.p2=pool.create_unique_vertex(*poly->get_vertex(1))->get_index(); tri.p3=pool.create_unique_vertex(*poly->get_vertex(2))->get_index(); triangles.push_back(tri); //generate a shared vertex triangle from the vertex pool tri2.p1=tri.p1; tri2.p2=tri.p3; tri2.p3=pool.create_unique_vertex(*poly->get_vertex(3))->get_index(); triangles.push_back(tri2); } } //Now we have a set of triangles, and a pool PT(CollisionFloorMesh) csfloor = new CollisionFloorMesh; EggVertexPool::const_iterator vi; for (vi = pool.begin(); vi != pool.end(); vi++) { csfloor->add_vertex(LCAST(PN_stdfloat,(*vi)->get_pos3())); } pvector<CollisionFloorMesh::TriangleIndices>::iterator ti; for (ti = triangles.begin(); ti != triangles.end(); ti++) { CollisionFloorMesh::TriangleIndices triangle = *ti; csfloor->add_triangle(triangle.p1, triangle.p2, triangle.p3); } cnode->add_solid(csfloor); } //////////////////////////////////////////////////////////////////// // Function: EggLoader::apply_deferred_nodes // Access: Private // Description: Walks back over the tree and applies the // DeferredNodeProperties that were saved up along the // way. //////////////////////////////////////////////////////////////////// void EggLoader:: apply_deferred_nodes(PandaNode *node, const DeferredNodeProperty &prop) { DeferredNodeProperty next_prop(prop); // Do we have a DeferredNodeProperty associated with this node? DeferredNodes::const_iterator dni; dni = _deferred_nodes.find(node); if (dni != _deferred_nodes.end()) { const DeferredNodeProperty &def = (*dni).second; next_prop.compose(def); } // Now apply the accumulated state to the node. next_prop.apply_to_node(node); int num_children = node->get_num_children(); for (int i = 0; i < num_children; i++) { apply_deferred_nodes(node->get_child(i), next_prop); } } //////////////////////////////////////////////////////////////////// // Function: EggLoader::expand_all_object_types // Access: Private // Description: Walks the hierarchy and calls expand_object_types() // on each node, to expand all of the ObjectType // definitions in the file at once. Also prunes any // nodes that are flagged "backstage". // // The return value is true if this node should be kept, // false if it should be pruned. //////////////////////////////////////////////////////////////////// bool EggLoader:: expand_all_object_types(EggNode *egg_node) { if (egg_node->is_of_type(EggGroup::get_class_type())) { EggGroup *egg_group = DCAST(EggGroup, egg_node); if (egg_group->get_num_object_types() != 0) { pset<string> expanded; pvector<string> expanded_history; if (!expand_object_types(egg_group, expanded, expanded_history)) { return false; } } } // Now recurse on children, and we might prune children from this // list as we go. if (egg_node->is_of_type(EggGroupNode::get_class_type())) { EggGroupNode *egg_group_node = DCAST(EggGroupNode, egg_node); EggGroupNode::const_iterator ci; ci = egg_group_node->begin(); while (ci != egg_group_node->end()) { EggGroupNode::const_iterator cnext = ci; ++cnext; if (!expand_all_object_types(*ci)) { // Prune this child. egg_group_node->erase(ci); } ci = cnext; } } return true; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::expand_object_types // Access: Private // Description: Recursively expands the group's ObjectType string(s). // It's recursive because an ObjectType string might // itself expand to another ObjectType string, which is // allowed; but we don't want to get caught in a cycle. // // The return value is true if the object type is // expanded and the node is valid, or false if the node // should be ignored (e.g. ObjectType "backstage"). //////////////////////////////////////////////////////////////////// bool EggLoader:: expand_object_types(EggGroup *egg_group, const pset<string> &expanded, const pvector<string> &expanded_history) { int num_object_types = egg_group->get_num_object_types(); // First, copy out the object types so we can recursively modify the // list. vector_string object_types; int i; for (i = 0; i < num_object_types; i++) { object_types.push_back(egg_group->get_object_type(i)); } egg_group->clear_object_types(); for (i = 0; i < num_object_types; i++) { string object_type = object_types[i]; pset<string> new_expanded(expanded); // Check for a cycle. if (!new_expanded.insert(object_type).second) { egg2pg_cat.error() << "Cycle in ObjectType expansions:\n"; pvector<string>::const_iterator pi; for (pi = expanded_history.begin(); pi != expanded_history.end(); ++pi) { egg2pg_cat.error(false) << (*pi) << " -> "; } egg2pg_cat.error(false) << object_type << "\n"; _error = true; } else { // No cycle; continue. pvector<string> new_expanded_history(expanded_history); new_expanded_history.push_back(object_type); if (!do_expand_object_type(egg_group, new_expanded, new_expanded_history, object_type)) { // Ignorable group; stop here. return false; } } } return true; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::do_expand_object_types // Access: Private // Description: Further implementation of expand_object_types(). //////////////////////////////////////////////////////////////////// bool EggLoader:: do_expand_object_type(EggGroup *egg_group, const pset<string> &expanded, const pvector<string> &expanded_history, const string &object_type) { // Try to find the egg syntax that the given objecttype is // shorthand for. First, look in the config file. ConfigVariableString egg_object_type ("egg-object-type-" + downcase(object_type), ""); string egg_syntax = egg_object_type; if (!egg_object_type.has_value()) { // It wasn't defined in a config file. Maybe it's built in? if (cmp_nocase_uh(object_type, "barrier") == 0) { egg_syntax = "<Collide> { Polyset descend }"; } else if (cmp_nocase_uh(object_type, "solidpoly") == 0) { egg_syntax = "<Collide> { Polyset descend solid }"; } else if (cmp_nocase_uh(object_type, "turnstile") == 0) { egg_syntax = "<Collide> { Polyset descend turnstile }"; } else if (cmp_nocase_uh(object_type, "sphere") == 0) { egg_syntax = "<Collide> { Sphere descend }"; } else if (cmp_nocase_uh(object_type, "tube") == 0) { egg_syntax = "<Collide> { Tube descend }"; } else if (cmp_nocase_uh(object_type, "trigger") == 0) { egg_syntax = "<Collide> { Polyset descend intangible }"; } else if (cmp_nocase_uh(object_type, "trigger_sphere") == 0) { egg_syntax = "<Collide> { Sphere descend intangible }"; } else if (cmp_nocase_uh(object_type, "eye_trigger") == 0) { egg_syntax = "<Collide> { Polyset descend intangible center }"; } else if (cmp_nocase_uh(object_type, "bubble") == 0) { egg_syntax = "<Collide> { Sphere keep descend }"; } else if (cmp_nocase_uh(object_type, "ghost") == 0) { egg_syntax = "<Scalar> collide-mask { 0 }"; } else if (cmp_nocase_uh(object_type, "dcs") == 0) { egg_syntax = "<DCS> { 1 }"; } else if (cmp_nocase_uh(object_type, "model") == 0) { egg_syntax = "<Model> { 1 }"; } else if (cmp_nocase_uh(object_type, "none") == 0) { // ObjectType "none" is a special case, meaning nothing in particular. return true; } else if (cmp_nocase_uh(object_type, "backstage") == 0) { // Ignore "backstage" geometry. return false; } else { egg2pg_cat.error() << "Unknown ObjectType " << object_type << "\n"; _error = true; egg2pg_cat.debug() << "returning true\n"; return true; } } if (!egg_syntax.empty()) { if (!egg_group->parse_egg(egg_syntax)) { egg2pg_cat.error() << "Error while parsing definition for ObjectType " << object_type << "\n"; _error = true; } else { // Now we've parsed the object type syntax, which might have // added more object types. Recurse if necessary. if (egg_group->get_num_object_types() != 0) { if (!expand_object_types(egg_group, expanded, expanded_history)) { return false; } } } } return true; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::get_combine_mode // Access: Private, Static // Description: Extracts the combine_mode from the given egg texture, // and returns its corresponding TextureStage value. //////////////////////////////////////////////////////////////////// TextureStage::CombineMode EggLoader:: get_combine_mode(const EggTexture *egg_tex, EggTexture::CombineChannel channel) { switch (egg_tex->get_combine_mode(channel)) { case EggTexture::CM_unspecified: // fall through case EggTexture::CM_modulate: return TextureStage::CM_modulate; case EggTexture::CM_replace: return TextureStage::CM_replace; case EggTexture::CM_add: return TextureStage::CM_add; case EggTexture::CM_add_signed: return TextureStage::CM_add_signed; case EggTexture::CM_interpolate: return TextureStage::CM_interpolate; case EggTexture::CM_subtract: return TextureStage::CM_subtract; case EggTexture::CM_dot3_rgb: return TextureStage::CM_dot3_rgb; case EggTexture::CM_dot3_rgba: return TextureStage::CM_dot3_rgba; }; return TextureStage::CM_undefined; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::get_combine_source // Access: Private, Static // Description: Extracts the combine_source from the given egg texture, // and returns its corresponding TextureStage value. //////////////////////////////////////////////////////////////////// TextureStage::CombineSource EggLoader:: get_combine_source(const EggTexture *egg_tex, EggTexture::CombineChannel channel, int n) { switch (egg_tex->get_combine_source(channel, n)) { case EggTexture::CS_unspecified: // The default source if it is unspecified is based on the // parameter index. switch (n) { case 0: return TextureStage::CS_previous; case 1: return TextureStage::CS_texture; case 2: return TextureStage::CS_constant; } // Otherwise, fall through case EggTexture::CS_texture: return TextureStage::CS_texture; case EggTexture::CS_constant: return TextureStage::CS_constant; case EggTexture::CS_primary_color: return TextureStage::CS_primary_color; case EggTexture::CS_previous: return TextureStage::CS_previous; case EggTexture::CS_constant_color_scale: return TextureStage::CS_constant_color_scale; case EggTexture::CS_last_saved_result: return TextureStage::CS_last_saved_result; }; return TextureStage::CS_undefined; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::get_combine_operand // Access: Private, Static // Description: Extracts the combine_operand from the given egg texture, // and returns its corresponding TextureStage value. //////////////////////////////////////////////////////////////////// TextureStage::CombineOperand EggLoader:: get_combine_operand(const EggTexture *egg_tex, EggTexture::CombineChannel channel, int n) { switch (egg_tex->get_combine_operand(channel, n)) { case EggTexture::CS_unspecified: if (channel == EggTexture::CC_rgb) { // The default operand for RGB is src_color, except for the // third parameter, which defaults to src_alpha. return n < 2 ? TextureStage::CO_src_color : TextureStage::CO_src_alpha; } else { // The default operand for alpha is always src_alpha. return TextureStage::CO_src_alpha; } case EggTexture::CO_src_color: return TextureStage::CO_src_color; case EggTexture::CO_one_minus_src_color: return TextureStage::CO_one_minus_src_color; case EggTexture::CO_src_alpha: return TextureStage::CO_src_alpha; case EggTexture::CO_one_minus_src_alpha: return TextureStage::CO_one_minus_src_alpha; }; return TextureStage::CO_undefined; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::get_color_blend_mode // Access: Private, Static // Description: Converts the EggGroup's BlendMode to the // corresponding ColorBlendAttrib::Mode value. //////////////////////////////////////////////////////////////////// ColorBlendAttrib::Mode EggLoader:: get_color_blend_mode(EggGroup::BlendMode mode) { switch (mode) { case EggGroup::BM_unspecified: case EggGroup::BM_none: return ColorBlendAttrib::M_none; case EggGroup::BM_add: return ColorBlendAttrib::M_add; case EggGroup::BM_subtract: return ColorBlendAttrib::M_subtract; case EggGroup::BM_inv_subtract: return ColorBlendAttrib::M_inv_subtract; case EggGroup::BM_min: return ColorBlendAttrib::M_min; case EggGroup::BM_max: return ColorBlendAttrib::M_max; } return ColorBlendAttrib::M_none; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::get_color_blend_operand // Access: Private, Static // Description: Converts the EggGroup's BlendOperand to the // corresponding ColorBlendAttrib::Operand value. //////////////////////////////////////////////////////////////////// ColorBlendAttrib::Operand EggLoader:: get_color_blend_operand(EggGroup::BlendOperand operand) { switch (operand) { case EggGroup::BO_zero: return ColorBlendAttrib::O_zero; case EggGroup::BO_unspecified: case EggGroup::BO_one: return ColorBlendAttrib::O_one; case EggGroup::BO_incoming_color: return ColorBlendAttrib::O_incoming_color; case EggGroup::BO_one_minus_incoming_color: return ColorBlendAttrib::O_one_minus_incoming_color; case EggGroup::BO_fbuffer_color: return ColorBlendAttrib::O_fbuffer_color; case EggGroup::BO_one_minus_fbuffer_color: return ColorBlendAttrib::O_one_minus_fbuffer_color; case EggGroup::BO_incoming_alpha: return ColorBlendAttrib::O_incoming_alpha; case EggGroup::BO_one_minus_incoming_alpha: return ColorBlendAttrib::O_one_minus_incoming_alpha; case EggGroup::BO_fbuffer_alpha: return ColorBlendAttrib::O_fbuffer_alpha; case EggGroup::BO_one_minus_fbuffer_alpha: return ColorBlendAttrib::O_one_minus_fbuffer_alpha; case EggGroup::BO_constant_color: return ColorBlendAttrib::O_constant_color; case EggGroup::BO_one_minus_constant_color: return ColorBlendAttrib::O_one_minus_constant_color; case EggGroup::BO_constant_alpha: return ColorBlendAttrib::O_constant_alpha; case EggGroup::BO_one_minus_constant_alpha: return ColorBlendAttrib::O_one_minus_constant_alpha; case EggGroup::BO_incoming_color_saturate: return ColorBlendAttrib::O_incoming_color_saturate; case EggGroup::BO_color_scale: return ColorBlendAttrib::O_color_scale; case EggGroup::BO_one_minus_color_scale: return ColorBlendAttrib::O_one_minus_color_scale; case EggGroup::BO_alpha_scale: return ColorBlendAttrib::O_alpha_scale; case EggGroup::BO_one_minus_alpha_scale: return ColorBlendAttrib::O_one_minus_alpha_scale; } return ColorBlendAttrib::O_zero; } //////////////////////////////////////////////////////////////////// // Function: EggLoader::VertexPoolTransform::operator < // Access: Public // Description: //////////////////////////////////////////////////////////////////// bool EggLoader::VertexPoolTransform:: operator < (const EggLoader::VertexPoolTransform &other) const { if (_vertex_pool != other._vertex_pool) { return _vertex_pool < other._vertex_pool; } int compare = _transform.compare_to(other._transform, 0.001); if (compare != 0) { return compare < 0; } if (_bake_in_uvs.size() != other._bake_in_uvs.size()) { return _bake_in_uvs.size() < other._bake_in_uvs.size(); } BakeInUVs::const_iterator ai, bi; ai = _bake_in_uvs.begin(); bi = other._bake_in_uvs.begin(); while (ai != _bake_in_uvs.end()) { nassertr(bi != other._bake_in_uvs.end(), false); if ((*ai) != (*bi)) { return (*ai) < (*bi); } ++ai; ++bi; } nassertr(bi == other._bake_in_uvs.end(), false); return false; }
34.343902
159
0.613564
[ "mesh", "geometry", "render", "object", "vector", "model", "transform", "3d", "solid" ]
11da520b45694ec0644ad684d9c6c07384634f89
12,841
cc
C++
power_manager/powerd/system/ambient_light_sensor_manager_mojo.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
power_manager/powerd/system/ambient_light_sensor_manager_mojo.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
power_manager/powerd/system/ambient_light_sensor_manager_mojo.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "power_manager/powerd/system/ambient_light_sensor_manager_mojo.h" #include <algorithm> #include <utility> #include <base/bind.h> #include <base/check.h> #include <base/check_op.h> #include <base/logging.h> #include "power_manager/common/power_constants.h" #include "power_manager/common/prefs.h" #include "power_manager/common/util.h" namespace power_manager { namespace system { AmbientLightSensorInterface* AmbientLightSensorManagerMojo::GetSensorForInternalBacklight() { return lid_sensor_.sensor; } AmbientLightSensorInterface* AmbientLightSensorManagerMojo::GetSensorForKeyboardBacklight() { return base_sensor_.sensor; } AmbientLightSensorManagerMojo::AmbientLightSensorManagerMojo( PrefsInterface* prefs, SensorServiceHandler* sensor_service_handler) : SensorServiceHandlerObserver(sensor_service_handler) { prefs->GetInt64(kHasAmbientLightSensorPref, &num_sensors_); if (num_sensors_ <= 0) return; CHECK(prefs->GetBool(kAllowAmbientEQ, &allow_ambient_eq_)) << "Failed to read pref " << kAllowAmbientEQ; if (num_sensors_ == 1) { sensors_.push_back(std::make_unique<AmbientLightSensor>()); lid_sensor_.sensor = base_sensor_.sensor = sensors_[0].get(); return; } sensors_.push_back(std::make_unique<AmbientLightSensor>()); lid_sensor_.sensor = sensors_[0].get(); sensors_.push_back(std::make_unique<AmbientLightSensor>()); base_sensor_.sensor = sensors_[1].get(); } AmbientLightSensorManagerMojo::~AmbientLightSensorManagerMojo() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sensors_.clear(); lights_.clear(); } bool AmbientLightSensorManagerMojo::HasColorSensor() { for (const auto& sensor : sensors_) { if (sensor->IsColorSensor()) return true; } return false; } void AmbientLightSensorManagerMojo::OnNewDeviceAdded( int32_t iio_device_id, const std::vector<cros::mojom::DeviceType>& types) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (num_sensors_ <= 0) return; if (std::find(types.begin(), types.end(), cros::mojom::DeviceType::LIGHT) == types.end()) { // Not a light sensor. Ignoring this device. return; } if (lights_.find(iio_device_id) != lights_.end()) { // Has already added this device. return; } auto& light = lights_[iio_device_id]; sensor_service_handler_->GetDevice(iio_device_id, light.remote.BindNewPipeAndPassReceiver()); light.remote.set_disconnect_with_reason_handler( base::BindOnce(&AmbientLightSensorManagerMojo::OnSensorDeviceDisconnect, base::Unretained(this), iio_device_id)); if (num_sensors_ == 1) { light.remote->GetAttributes( std::vector<std::string>{cros::mojom::kDeviceName}, base::BindOnce(&AmbientLightSensorManagerMojo::GetNameCallback, base::Unretained(this), iio_device_id)); } else { // num_sensors_ >= 2 light.remote->GetAttributes( std::vector<std::string>{cros::mojom::kDeviceName, cros::mojom::kLocation}, base::BindOnce( &AmbientLightSensorManagerMojo::GetNameAndLocationCallback, base::Unretained(this), iio_device_id)); } } void AmbientLightSensorManagerMojo::SensorServiceConnected() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (num_sensors_ <= 0) return; bool need_device_ids = false; if (num_sensors_ == 1) { if (lid_sensor_.iio_device_id.has_value()) { // Use the original device. SetSensorDeviceMojo(&lid_sensor_, allow_ambient_eq_); auto& light = lights_[lid_sensor_.iio_device_id.value()]; if (!light.name.has_value() || light.name.value().compare(kCrosECLightName) != 0) { // Even though this device is not cros-ec-light, cros-ec-light may // exist, so we will still look for cros-ec-light later. need_device_ids = true; } } else { need_device_ids = true; } } else { // num_sensors_ >= 2 // The two cros-ec-lights on lid and base should exist. Therefore, the // potential existing acpi-als is ignored. if (lid_sensor_.iio_device_id.has_value()) SetSensorDeviceMojo(&lid_sensor_, allow_ambient_eq_); else need_device_ids = true; if (base_sensor_.iio_device_id.has_value()) SetSensorDeviceMojo(&base_sensor_, /*allow_ambient_eq=*/false); else need_device_ids = true; } } void AmbientLightSensorManagerMojo::SensorServiceDisconnected() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); ResetSensorService(); } void AmbientLightSensorManagerMojo::ResetSensorService() { for (auto& sensor : sensors_) sensor->SetDelegate(nullptr); for (auto& light : lights_) light.second.remote.reset(); } void AmbientLightSensorManagerMojo::ResetStates() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); for (auto& sensor : sensors_) sensor->SetDelegate(nullptr); lid_sensor_.iio_device_id = base_sensor_.iio_device_id = base::nullopt; lights_.clear(); QueryDevices(); } void AmbientLightSensorManagerMojo::QueryDevices() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); sensor_service_handler_->RemoveObserver(this); sensor_service_handler_->AddObserver(this); } void AmbientLightSensorManagerMojo::OnSensorDeviceDisconnect( int32_t id, uint32_t custom_reason_code, const std::string& description) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); const auto reason = static_cast<cros::mojom::SensorDeviceDisconnectReason>( custom_reason_code); LOG(WARNING) << "OnSensorDeviceDisconnect: " << id << ", reason: " << reason << ", description: " << description; switch (reason) { case cros::mojom::SensorDeviceDisconnectReason::IIOSERVICE_CRASHED: ResetSensorService(); break; case cros::mojom::SensorDeviceDisconnectReason::DEVICE_REMOVED: if (lid_sensor_.iio_device_id == id || base_sensor_.iio_device_id == id) { // Reset usages & states, and restart the mojo devices initialization. ResetStates(); } else { // This light sensor is not in use. lights_.erase(id); } break; } } void AmbientLightSensorManagerMojo::GetNameCallback( int32_t id, const std::vector<base::Optional<std::string>>& values) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_EQ(num_sensors_, 1); auto& light = lights_[id]; DCHECK(light.remote.is_bound()); if (values.empty()) { LOG(ERROR) << "Sensor values doesn't contain the name attribute."; light.ignored = true; light.remote.reset(); return; } if (values.size() != 1) { LOG(WARNING) << "Sensor values contain more than the name attribute. Size: " << values.size(); } light.name = values[0]; if (light.name.has_value() && light.name.value().compare(kCrosECLightName) == 0) { LOG(INFO) << "Using ALS with id: " << id << ", name: " << light.name.value(); lid_sensor_.iio_device_id = base_sensor_.iio_device_id = id; auto delegate = AmbientLightSensorDelegateMojo::Create( id, std::move(light.remote), allow_ambient_eq_); lid_sensor_.sensor->SetDelegate(std::move(delegate)); // Found cros-ec-light. Other devices are not needed. AllDevicesFound(); return; } // Not cros-ec-light if (!light.name.has_value() || light.name.value().compare(kAcpiAlsName) != 0) { LOG(WARNING) << "Unexpected or empty light name: " << light.name.value_or(""); } if (lid_sensor_.iio_device_id.has_value()) { VLOG(1) << "Already have another light sensor with name: " << lights_[lid_sensor_.iio_device_id.value()].name.value_or(""); light.ignored = true; light.remote.reset(); return; } LOG(INFO) << "Using ALS with id: " << id << ", name: " << light.name.value_or("null"); lid_sensor_.iio_device_id = id; auto delegate = AmbientLightSensorDelegateMojo::Create( id, std::move(light.remote), allow_ambient_eq_); lid_sensor_.sensor->SetDelegate(std::move(delegate)); } void AmbientLightSensorManagerMojo::GetNameAndLocationCallback( int32_t id, const std::vector<base::Optional<std::string>>& values) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_GE(num_sensors_, 2); auto& light = lights_[id]; DCHECK(light.remote.is_bound()); if (values.size() < 2) { LOG(ERROR) << "Sensor is missing name or location attribute."; light.ignored = true; light.remote.reset(); return; } if (values.size() > 2) { LOG(WARNING) << "Sensor values contain more than name and location attribute. Size: " << values.size(); } light.name = values[0]; if (!light.name.has_value() || light.name.value().compare(kCrosECLightName) != 0) { LOG(ERROR) << "Not " << kCrosECLightName << ", sensor name: " << light.name.value_or(""); light.ignored = true; light.remote.reset(); return; } const base::Optional<std::string>& location = values[1]; if (!location.has_value()) { LOG(WARNING) << "Sensor doesn't have the location attribute: " << id; SetSensorDeviceAtLocation(id, SensorLocation::UNKNOWN); return; } if (location.value() == cros::mojom::kLocationLid) { SetSensorDeviceAtLocation(id, SensorLocation::LID); } else if (location.value() == cros::mojom::kLocationBase) { SetSensorDeviceAtLocation(id, SensorLocation::BASE); } else { LOG(ERROR) << "Invalid sensor " << id << ", location: " << location.value(); SetSensorDeviceAtLocation(id, SensorLocation::UNKNOWN); } } void AmbientLightSensorManagerMojo::SetSensorDeviceAtLocation( int32_t id, SensorLocation location) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_GE(num_sensors_, 2); auto& light = lights_[id]; DCHECK(!light.location.has_value() || light.location == location); light.location = location; if (location == SensorLocation::LID && (!lid_sensor_.iio_device_id.has_value() || lid_sensor_.iio_device_id.value() == id)) { LOG(INFO) << "Using Lid ALS with id: " << id; lid_sensor_.iio_device_id = id; auto delegate = AmbientLightSensorDelegateMojo::Create( id, std::move(light.remote), allow_ambient_eq_); lid_sensor_.sensor->SetDelegate(std::move(delegate)); } else if (location == SensorLocation::BASE && (!base_sensor_.iio_device_id.has_value() || base_sensor_.iio_device_id.value() == id)) { LOG(INFO) << "Using Base ALS with id: " << id; base_sensor_.iio_device_id = id; auto delegate = AmbientLightSensorDelegateMojo::Create( id, std::move(light.remote), /*enable_color_support=*/false); // BASE sensor is not expected to be // used for AEQ. base_sensor_.sensor->SetDelegate(std::move(delegate)); } if (lid_sensor_.iio_device_id.has_value() && base_sensor_.iio_device_id.has_value()) { // Has found the two cros-ec-lights. Don't need other devices. AllDevicesFound(); } light.remote.reset(); } void AmbientLightSensorManagerMojo::AllDevicesFound() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Remove and ignore remaining remotes as they're not needed anymore. for (auto& light : lights_) { if (!light.second.remote.is_bound()) continue; light.second.ignored = true; light.second.remote.reset(); } // Don't need to wait for other devices. sensor_service_handler_->RemoveObserver(this); } void AmbientLightSensorManagerMojo::SetSensorDeviceMojo(Sensor* sensor, bool allow_ambient_eq) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(sensor->iio_device_id.has_value()); mojo::Remote<cros::mojom::SensorDevice> sensor_device_remote; sensor_service_handler_->GetDevice( sensor->iio_device_id.value(), sensor_device_remote.BindNewPipeAndPassReceiver()); sensor_device_remote.set_disconnect_with_reason_handler( base::BindOnce(&AmbientLightSensorManagerMojo::OnSensorDeviceDisconnect, base::Unretained(this), sensor->iio_device_id.value())); std::unique_ptr<AmbientLightSensorDelegateMojo> delegate = AmbientLightSensorDelegateMojo::Create(sensor->iio_device_id.value(), std::move(sensor_device_remote), allow_ambient_eq); sensor->sensor->SetDelegate(std::move(delegate)); } } // namespace system } // namespace power_manager
32.345088
80
0.685461
[ "vector" ]
11dd795f61ec43046745cb6ae6dfb78c4a9a6653
4,244
cc
C++
cpp/core/core.cc
jjacap/nearby-connections
fa64c35e241bfa17b6e38d70ba86efcec5db75a2
[ "Apache-2.0" ]
null
null
null
cpp/core/core.cc
jjacap/nearby-connections
fa64c35e241bfa17b6e38d70ba86efcec5db75a2
[ "Apache-2.0" ]
null
null
null
cpp/core/core.cc
jjacap/nearby-connections
fa64c35e241bfa17b6e38d70ba86efcec5db75a2
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "core/core.h" #include <cassert> #include <vector> #include "core/options.h" #include "platform/public/count_down_latch.h" #include "platform/public/logging.h" #include "absl/time/clock.h" namespace location { namespace nearby { namespace connections { constexpr absl::Duration Core::kWaitForDisconnect; Core::~Core() { CountDownLatch latch(1); router_.ClientDisconnecting( &client_, { .result_cb = [&latch](Status) { latch.CountDown(); }, }); if (!latch.Await(kWaitForDisconnect).result()) { NEARBY_LOG(FATAL, "Unable to shutdown"); } } void Core::StartAdvertising(absl::string_view service_id, ConnectionOptions options, ConnectionRequestInfo info, ResultCallback callback) { assert(!service_id.empty()); assert(options.strategy.IsValid()); router_.StartAdvertising(&client_, service_id, options, info, callback); } void Core::StopAdvertising(const ResultCallback callback) { router_.StopAdvertising(&client_, callback); } void Core::StartDiscovery(absl::string_view service_id, ConnectionOptions options, DiscoveryListener listener, ResultCallback callback) { assert(!service_id.empty()); assert(options.strategy.IsValid()); router_.StartDiscovery(&client_, service_id, options, listener, callback); } void Core::InjectEndpoint(absl::string_view service_id, OutOfBandConnectionMetadata metadata, ResultCallback callback) { router_.InjectEndpoint(&client_, service_id, metadata, callback); } void Core::StopDiscovery(ResultCallback callback) { router_.StopDiscovery(&client_, callback); } void Core::RequestConnection(absl::string_view endpoint_id, ConnectionRequestInfo info, ConnectionOptions options, ResultCallback callback) { assert(!endpoint_id.empty()); router_.RequestConnection(&client_, endpoint_id, info, options, callback); } void Core::AcceptConnection(absl::string_view endpoint_id, PayloadListener listener, ResultCallback callback) { assert(!endpoint_id.empty()); router_.AcceptConnection(&client_, endpoint_id, listener, callback); } void Core::RejectConnection(absl::string_view endpoint_id, ResultCallback callback) { assert(!endpoint_id.empty()); router_.RejectConnection(&client_, endpoint_id, callback); } void Core::InitiateBandwidthUpgrade(absl::string_view endpoint_id, ResultCallback callback) { router_.InitiateBandwidthUpgrade(&client_, endpoint_id, callback); } void Core::SendPayload(absl::Span<const std::string> endpoint_ids, Payload payload, ResultCallback callback) { assert(payload.GetType() != Payload::Type::kUnknown); assert(!endpoint_ids.empty()); router_.SendPayload(&client_, endpoint_ids, std::move(payload), callback); } void Core::CancelPayload(std::int64_t payload_id, ResultCallback callback) { assert(payload_id != 0); router_.CancelPayload(&client_, payload_id, callback); } void Core::DisconnectFromEndpoint(absl::string_view endpoint_id, ResultCallback callback) { assert(!endpoint_id.empty()); router_.DisconnectFromEndpoint(&client_, endpoint_id, callback); } void Core::StopAllEndpoints(ResultCallback callback) { router_.StopAllEndpoints(&client_, callback); } } // namespace connections } // namespace nearby } // namespace location
32.396947
80
0.685674
[ "vector" ]
11dfef094e3f9a53a3002badfb5aa6bb41d0d52f
1,809
cpp
C++
GRUT Engine/src/Scene/Scene.cpp
lggmonclar/GRUT
b7d06fd314141395b54a86122374f4f955f653cf
[ "MIT" ]
2
2019-02-14T03:20:59.000Z
2019-03-12T01:34:59.000Z
GRUT Engine/src/Scene/Scene.cpp
lggmonclar/GRUT
b7d06fd314141395b54a86122374f4f955f653cf
[ "MIT" ]
null
null
null
GRUT Engine/src/Scene/Scene.cpp
lggmonclar/GRUT
b7d06fd314141395b54a86122374f4f955f653cf
[ "MIT" ]
null
null
null
#include "grutpch.h" #include "Scene.h" #include "Core/Jobs/JobManager.h" #include "Scene/SceneManager.h" #include "Core/Parallelism/FrameParams.h" #include "Components/Rendering/Light.h" namespace GRUT { ObjectHandle<Scene> Scene::GetCurrent() { return SceneManager::Instance().m_currentScene; } ObjectHandle<GameObject> Scene::CreateGameObject() { auto gameObject = SceneManager::Instance().AllocateGameObject(); gameObject->Initialize(gameObject); gameObject->scene = m_handle; m_rootObjects.push_back(gameObject); return gameObject; } void Scene::ScheduleGameObjectDestruction(ObjectHandle<GameObject> p_gameObject) { m_objectsScheduledForDeletion.push_back(p_gameObject); } void Scene::DestroyScheduledGameObjects() { for (auto& obj : m_objectsScheduledForDeletion) { m_rootObjects.erase(std::remove(m_rootObjects.begin(), m_rootObjects.end(), obj)); obj->DestroyComponents(); SceneManager::Instance().FreeGameObject(&(*obj)); } m_objectsScheduledForDeletion.clear(); } void Scene::FixedUpdate(float p_deltaTime) { for (auto& obj : m_rootObjects) { obj->FixedUpdate(p_deltaTime); } } std::vector<std::weak_ptr<Job>> Scene::Update(FrameParams& p_prevFrame, FrameParams& p_currFrame) { std::vector<std::weak_ptr<Job>> updateJobs; for (auto& obj : m_rootObjects) { updateJobs.push_back(JobManager::Instance().KickJob([&]() { obj->Update(p_currFrame.deltaTime); })); } return updateJobs; } void Scene::UpdateLightSourceList(ObjectHandle<Light> p_handle, LightType p_type) { } }
34.788462
103
0.638474
[ "vector" ]
11e048ff348a442fe73d513ccab98fafb78a9aa8
6,763
cpp
C++
concurrency_control/row_tcm.cpp
c5h11oh/Sundial
972af0a93797dd05203ddefd9d546b8401da65c6
[ "0BSD" ]
24
2018-09-15T10:35:21.000Z
2021-07-12T06:17:54.000Z
concurrency_control/row_tcm.cpp
c5h11oh/Sundial
972af0a93797dd05203ddefd9d546b8401da65c6
[ "0BSD" ]
3
2019-10-14T02:57:21.000Z
2022-02-17T19:53:46.000Z
concurrency_control/row_tcm.cpp
c5h11oh/Sundial
972af0a93797dd05203ddefd9d546b8401da65c6
[ "0BSD" ]
10
2018-12-20T18:34:47.000Z
2020-10-06T13:49:30.000Z
#include "row.h" #include "txn.h" #include "row_tcm.h" #include "manager.h" #include "tcm_manager.h" #if CC_ALG == TCM Row_TCM::Row_TCM() { _row = NULL; pthread_mutex_init(&_latch, NULL); _lock_type = LOCK_NONE; _max_num_waits = g_max_num_waits; _upgrading_txn = NULL; } Row_TCM::Row_TCM(row_t * row) : Row_TCM() { _row = row; } void Row_TCM::latch() { pthread_mutex_lock( &_latch ); } void Row_TCM::unlatch() { pthread_mutex_unlock( &_latch ); } void Row_TCM::init(row_t * row) { _row = row; pthread_mutex_init(&_latch, NULL); _lock_type = LOCK_NONE; _max_num_waits = g_max_num_waits; } RC Row_TCM::lock_get(LockType type, TxnManager * txn, char * data) { RC rc = RCOK; latch(); for (set<LockHolder, CompareHolder>::iterator it = _locking_set.begin(); it != _locking_set.end(); it ++) { TCMManager * holder = it->manager; TCMManager * requester = (TCMManager *)txn->get_cc_manager(); // Garbage Collection if (holder->state == TxnManager::COMMITTED && holder->early < glob_manager->get_gc_ts()) { _locking_set.erase(it); continue; } bool both_latched = false; while (!both_latched) { if (requester->try_latch()) { if (holder->try_latch()) { both_latched = true; } else requester->unlatch(); } } if (it->type == LOCK_SH && type == LOCK_EX) rc = adjust_timestamps_rw(holder, requester); else if (it->type == LOCK_EX && type == LOCK_SH) rc = adjust_timestamps_wr(holder, requester); else if (it->type == LOCK_EX && type == LOCK_EX) rc = adjust_timestamps_ww(holder, requester); requester->unlatch(); holder->unlatch(); if (rc == ABORT) { goto finish; } } // The request didn't abort, add it to the locking_set _locking_set.insert( LockHolder{ (TCMManager *)txn->get_cc_manager(), type } ); // TODO. Right now, we do not model multiple data versions here // but instead just read the current data. // For YCSB, this is OK. memcpy(data, _row->get_data(), _row->get_tuple_size()); finish: unlatch(); return rc; } RC Row_TCM::lock_release(TxnManager * txn, RC rc) { latch(); bool released = false; for (std::set<LockHolder>::iterator it = _locking_set.begin(); it != _locking_set.end(); it ++) { if (it->manager == txn->get_cc_manager()) { _locking_set.erase( it ); released = true; break; } } assert(released); unlatch(); return RCOK; } RC Row_TCM::adjust_timestamps_rw(TCMManager * holder, TCMManager * requester) { RC rc = RCOK; if (!requester->end && !holder->end) { uint64_t new_time = glob_manager->get_current_time(); holder->late = new_time; holder->end = true; requester->early = new_time; } else if (!requester->end && holder->end) { if (holder->late > requester->early) requester->early = holder->late; } else if (requester->end && !holder->end) { if (requester->late > holder->early) { requester->early = requester->late - 1; holder->late = requester->late - 1; holder->end = true; } else { rc = ABORT; } } else { if (requester->early > holder->late) {} else if (requester->early <= holder->late && holder->late <= requester->late) { requester->early = holder->late; } else if (holder->early <= requester->late && requester->late <= holder->late) { if (holder->state == TxnManager::RUNNING) { uint64_t new_time = requester->late - 1; holder->late = new_time; requester->early = new_time; } } else rc = ABORT; } return rc; } RC Row_TCM::adjust_timestamps_wr(TCMManager * holder, TCMManager * requester) { if (!requester->end && !holder->end) { uint64_t new_time = glob_manager->get_current_time(); holder->early = new_time; requester->late = new_time; requester->end = true; } else if (!requester->end && holder->end) { if (requester->early > holder->late) { if (holder->state == TxnManager::RUNNING) holder->try_abort(); } else { uint64_t new_time = holder->late - 1; requester->late = new_time; requester->end = true; holder->early = new_time; } } else if (requester->end && !holder->end) { if (requester->late < holder->early) holder->early = requester->late; } else { if (requester->early < holder->late) { if (holder->state == TxnManager::RUNNING) holder->try_abort(); } else if (requester->early <= holder->late && holder->late <= requester->late) { uint64_t new_time = holder->late - 1; requester->late = new_time; holder->early = new_time; } else if (holder->early <= requester->late && requester->late <= holder->late) holder->early = requester->late; } return RCOK; } RC Row_TCM::adjust_timestamps_ww(TCMManager * holder, TCMManager * requester) { RC rc = RCOK; if (!requester->end && !holder->end) { uint64_t new_time = glob_manager->get_current_time(); requester->early = new_time; holder->late = new_time; holder->end = true; rc = ABORT; } else if (!requester->end and holder->end) { if (requester->early < holder->late) requester->early = holder->late; if (holder->state == TxnManager::RUNNING) { rc = ABORT; } } else if (requester->end && !holder->end) { if (requester->late > holder->early) { uint64_t new_time = requester->late - 1; holder->late = new_time; holder->end = true; requester->early = new_time; rc = ABORT; } else rc = ABORT; } else { if (requester->early > holder->late) rc = ABORT; else if (requester->early <= holder->late && holder->late <= requester->late) { requester->early = holder->late; rc = ABORT; } else if (holder->early <= requester->late && requester->late <= holder->late) { requester->early = requester->late - 1; holder->late = requester->late - 1; rc = ABORT; } else rc = ABORT; } return rc; } #endif
29.404348
98
0.548277
[ "model" ]
11e166ce5a15bc967225a88a4a2ac45c5059c746
22,983
cpp
C++
src/classic/SxVDW.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
src/classic/SxVDW.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
src/classic/SxVDW.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The ab-initio based multiscale library // // S / P H I / n X // // Copyright: Max-Planck-Institute for Iron Research // 40237 Duesseldorf, Germany // // Contact: https://sxlib.mpie.de // Authors: see sphinx/AUTHORS // License: see sphinx/LICENSE // // --------------------------------------------------------------------------- // Authors: Lars Ismer (ismer@fhi-berlin.mpg.de) // Michael Ashton (ashton@mpie.de) #include <SxVDW.h> #include <SxElemDB.h> SxVDW::SxVDW () { //SVN_HEAD; } SxVDW::SxVDW (const SxAtomicStructure &t, const SxSymbolTable *table) { int i; SxAtomicStructure tau; SxParser parser; SxParser::Table elemTable = parser.read ("species/elements.sx"); SxElemDB elemDB(elemTable); tau.copy(t); nAtoms = t.nTlAtoms; superCell = tau.cell; //---workaround: will be solved if connected to sxatomicstructure if (superCell.absSqr().sum() < 1e-10) { superCell (0, 0) = superCell(1, 1) = superCell(2, 2) = 100; } coord = SxArray<SxVector3<Double> > (nAtoms); species = SxArray<SxString> (nAtoms); polarizability = SxArray<double> (nAtoms); C6 = SxArray<double> (nAtoms); vdwRadius = SxArray<double> (nAtoms); SxSpeciesData speciesData = SxSpeciesData(table->topLevel()); for (i = 0; i < nAtoms; i++) { coord(i) = tau.ref (i); species(i) = speciesData.chemName(tau.getISpecies (i)); polarizability(i) = elemDB.getPolarizability(species(i)); C6(i) = elemDB.getC6(species(i)); vdwRadius(i) = elemDB.getVdwRadius(species(i)); } energyContrib = SxArray<double> (nAtoms); dist = SxArray<SxList<double> > (nAtoms); expTerm = SxArray<SxList<double> > (nAtoms); neighbours = SxArray<SxList<int> > (nAtoms); supercellIds = SxArray<SxList<int> > (nAtoms); sNeighbours = SxArray<SxList<int> > (nAtoms); sSupercellIds = SxArray<SxList<int> > (nAtoms); borderCrossers = SxArray<SxList<int> > (27); output = false; Forces = SxArray<SxVector3<Double> > (nAtoms); SxSymbolTable *vdwGroup = table -> getGroup ("vdwCorrection"); correctionType = vdwGroup -> get("correctionType") -> toString (); if (vdwGroup -> contains("combinationRule")) { combinationRule = vdwGroup -> get("combinationRule") -> toString (); } else combinationRule = SxString("Default"); if (vdwGroup -> contains("damping")) { damping = vdwGroup -> get("damping") -> toString (); } else damping = SxString("Fermi"); } SxVDW::~SxVDW () { // empty } int SxVDW::getnAtoms() { return nAtoms; } void SxVDW::resize (SxList<SxList<SxVector3<Double> > > tauarr, SxList<SxString> speciesNameList, SxMatrix3<Double> aMat) { int i, j; int counter; nAtoms = 0; for (i = 0; i < tauarr.getSize (); i++) { nAtoms += (int)tauarr(i).getSize (); } superCell = aMat; coord = SxArray<SxVector3<Double> > (nAtoms); species = SxArray<SxString> (nAtoms); counter = 0; for (i = 0; i < tauarr.getSize (); i++) { for (j = 0; j < tauarr(i).getSize (); j++) { species(counter) = speciesNameList(i); counter++; } } energyContrib = SxArray<double> (nAtoms); dist = SxArray<SxList<double> > (nAtoms); expTerm = SxArray<SxList<double> > (nAtoms); neighbours = SxArray<SxList<int> > (nAtoms); supercellIds = SxArray<SxList<int> > (nAtoms); sNeighbours = SxArray<SxList<int> > (nAtoms); sSupercellIds = SxArray<SxList<int> > (nAtoms); borderCrossers = SxArray<SxList<int> > (27); output = false; Forces = SxArray<SxVector3<Double> > (nAtoms); } void SxVDW::updateHybridisation () { int i; for (i = 0; i < nAtoms; i++) { if ( (species(i) == SxString ("C")) || (species(i).contains(SxString("C_")))) { if (neighbours(i).getSize() == 3) { species(i) = SxString("C_sp2"); } if (neighbours(i).getSize() == 4) { species(i) = SxString("C_sp3"); } if ( (neighbours(i).getSize () < 3) || (neighbours(i).getSize () > 4) ) { cout << "NgVDW: WARNING !!!!!!!: The Hybridisation of the " << "Carbon Atom with id " << i << " is neither sp2 nor sp3 " << "is treated as sp3" << endl; cout << "Check atomic basis and supercell geometry !!!" << endl; species(i) = SxString("C_sp3"); } } } } void SxVDW::update (SxArray<SxVector3<Double > > newcoord) { if (output) cout << " ---- Updating Coords" << endl; updateCoord (newcoord); //printParameters(); //printCoord(); //printSpecies (); if (output) cout << " ---- Updating Border Crossers" << endl; updateBorderCrossers(); if (output) cout << " ---- Updating Neighbourhood and Distances" << endl; updateNeighbours (SxString ("covalentCutoff")); //printNeighbours (); updateHybridisation (); //printSpecies (); updateNeighbours (SxString ("vdwCutoff")); //printNeighbours(); //updateSecondNeighbours(); } SxVector3<Double> SxVDW::getLatticeVec(int supercellId) { int a1Coeff, a2Coeff, a3Coeff; int help = supercellId/9; a1Coeff = a2Coeff = a3Coeff = 0; if (help == 0) a1Coeff = 0; if (help == 1) a1Coeff = 1; if (help == 2) a1Coeff = -1; supercellId = supercellId - help*9; help = supercellId/3; if (help == 0) a2Coeff = 0; if (help == 1) a2Coeff = 1; if (help == 2) a2Coeff = -1; supercellId = supercellId - help*3; help = supercellId; if (help == 0) a3Coeff = 0; if (help == 1) a3Coeff = 1; if (help == 2) a3Coeff = -1; //cout << "Supercell: " << a1Coeff // << " " << a2Coeff << " " << a3Coeff << endl; SxVector3 <Double> returnValue = a1Coeff*superCell(0) + a2Coeff*superCell(1) + a3Coeff*superCell(2); //cout << returnValue << endl; return returnValue; } double SxVDW::getDist (int i, int j, int supercellId) { SxVector3<Double> distVec; distVec = coord(i) - coord(j) - getLatticeVec(supercellId); return sqrt (distVec(0)*distVec(0) + distVec(1)*distVec(1) + distVec(2)*distVec(2)); } void SxVDW::updateCoord (SxArray<SxVector3<Double> > newcoord) { for ( int i = 0; i < nAtoms; i++) { coord(i) = newcoord(i); } } void SxVDW::updateBorderCrossers () { double maxDist = getParam("a", 0, 0); //double length, projection; int j, i, superCellId; //int a0Flip, a1Flip, a2Flip; //SxArray<int> acoeff(3); // comment 20.02.2003: not so sure about the following comment // only works for orthorombic supercells, but easy to generalize bool smallSuperCell = false; smallSuperCell = true; //-- should be placed elsewhere (Initialisiation) for (j = 0; j < 3; j++) { if (sqrt(superCell(j).absSqr().sum ()) < 2.*maxDist) smallSuperCell = true; } // This caused a crash. for (superCellId = 0; superCellId < 27; superCellId++) { borderCrossers(superCellId).resize(0); } for (i = 0; i < nAtoms; i++) { if (smallSuperCell) { for (superCellId = 0; superCellId < 27; superCellId++) { borderCrossers(superCellId).append(i); } } else { //--- did not work, so commented out (has importance for efficience) /* acoeff(0) = acoeff(1) = acoeff(2) = 0; for (j = 0; j < 3; j++) { lenth = sqrt(superCell(j).absSqr ()); projection = ( superCell(j)(0)*coord(i)(0) + superCell(j)(1)*coord(i)(1) + superCell(j)(2)*coord(i)(2) ) /length; if (projection < maxDist) { acoeff(j) = 1; } else { if ((length - projection) < maxDist) { acoeff(j) = -1; } else { acoeff(j) = 0; } } } for (a0Flip = 0; abs(a0Flip) < 2 ; a0Flip += acoeff(0)) { for (a1Flip = 0; abs(a1Flip) < 2 ; a1Flip += acoeff(1)) { for (a2Flip = 0; abs(a2Flip) < 2; a2Flip += acoeff(2)) { //cout << a0Flip << " " << a1Flip << " " << a2Flip << endl; superCellId = 9*(a0Flip*(3*a0Flip - 1)/2) + 3*(a1Flip*(3*a1Flip - 1)/2) + (a2Flip*(3*a2Flip - 1)/2); borderCrossers(superCellId).append (i); if (acoeff(2) == 0) a2Flip = 2; } if (acoeff(1) == 0) a1Flip = 2; } if (acoeff(0) == 0) a0Flip = 2; } */ } } } void SxVDW::updateNeighbours (SxString modus) { double distance; SxList<int>::Iterator itBC; neighbours = SxArray<SxList<int> > (nAtoms); dist = SxArray<SxList<double> > (nAtoms); supercellIds = SxArray<SxList<int> > (nAtoms); int i, j, supercells; /* for (supercells = 0; supercells < 27; supercells++) { cout << endl << "Border Crossers in cell" << getLatticeVec (supercells) << endl; for ( itBC = borderCrossers (supercells).begin(); itBC != borderCrossers (supercells).end(); ++itBC) { j = *itBC; cout << j << " "; } cout << endl; } */ for (i = 0; i < nAtoms; i++) { dist(i). resize (0); neighbours(i). resize (0); supercellIds(i). resize (0); for (supercells = 0 ; supercells < 27; supercells++) { if (supercells == 0) { for (j = 0; j < nAtoms; j++) { if ( ((i != j)) && ((distance = getDist(i, j, supercells)) < getParam (modus, i , j))) { neighbours(i).append (j); dist(i).append (distance); supercellIds(i).append (supercells); } } } else { for ( itBC = borderCrossers (supercells).begin(); itBC != borderCrossers (supercells).end(); ++itBC) { j = *itBC; if ((distance = getDist(i, j, supercells)) < getParam (modus, i , j)) { neighbours(i).append (j); dist(i).append (distance); supercellIds(i).append (supercells); } } } } } } double SxVDW::getDampingFunction (double R, double Rij) { double fd = 0.; double s6 = getParam("s6", 0, 0); double d = getParam("d", 0, 0); double sR = getParam("sR", 0, 0); double vdwCutoff = getParam("vdwCutoff", 0, 0); // Fermi damping with cutoff (set by default to~ 100 Bohr) if (R < vdwCutoff) { fd = s6 / (1 + exp(-d * (R / (sR * Rij) - 1))); } return fd; } double SxVDW::getDampingDerivative (double R, double Rij) { double fdprime = 0.; double s6 = getParam("cdamp", 0, 0); double d = getParam("beta", 0, 0); double sR = getParam("dstar", 0, 0); double vdwCutoff = getParam("vdwCutoff", 0, 0); double scale = 1.0 / (sR * Rij); double x = R * scale; double chi = exp(-d * (x - 1.0)); // Again fermi damping with a cutoff, vdwCutoff if (R < vdwCutoff) { fdprime = d * scale * chi / ::pow(1.0 + chi, 2); } return fdprime; } /* double SxVDW::getDampingSecondDerivative (double R, double Rm) { double fd, e, ePrime, ePrimePrime, a; double cdamp = getParam("cdamp", 0, 0); double beta = getParam("beta", 0, 0); double dstar = getParam("dstar", 0, 0); fd = e = ePrime = ePrimePrime = a = 0.; if (correctionType == SxString("WTYang_I")) { e = exp(-cdamp*(::pow( (R/Rm), 3.))); ePrime = -e*cdamp*3.*R*R/Rm/Rm/Rm; fd = 12*cdamp*R/Rm/Rm/Rm*(1.-e)*e + 6.*cdamp*R*R/Rm/Rm/Rm*(ePrime - 2.*e*ePrime); } if (correctionType == SxString("WTYang_II")) { e = exp(-beta*(R/Rm - 1.)); fd = - ::pow((beta/Rm), 2.)*e/(1. + e)/(1. + e)*(1. - 2*e/(1 + e)); } if (correctionType.contains("Elstner")) { a = dstar/::pow (Rm, 7.); e = exp(-dstar*(::pow( (R/Rm), 7.))); ePrime = -7.*a*::pow(R, 6.)*e; ePrimePrime = 49.*a*a*::pow(R, 12.)*e - 42*a*::pow(R, 5.)*e; fd = -(4.*ePrimePrime * ::pow((1 - e), 3.) - 12*ePrime*ePrime*(::pow((1-e), 2))); } return fd; } */ void SxVDW::compute () { // update attributes "totalEnergy" (double) and // "Forces" (SxArray<SxVector3<Double>>) int i, j, neighj; double R, Rij, C6ij, fd, fdPrime, derivative; // Reset vdW energy to 0 totalEnergy = 0.; for (i = 0; i < nAtoms; i++) { // Reset force array for atom i to 0 for (int j = 0; j < 3; j++) { Forces(i)(j) = 0; } for (j = 0; j < neighbours(i).getSize (); j++) { R = dist(i)(j); neighj = neighbours(i)(j); Rij = getRij (i, neighj); C6ij = getC6ij (i, neighj); fd = getDampingFunction (R, Rij); fdPrime = getDampingDerivative (R, Rij); // Update Energy totalEnergy += -fd*C6ij/(::pow(R, 6.))/2.; // Update Forces derivative = fdPrime * C6ij/::pow(R, 6.) - 6. * fd * C6ij/::pow(R, 7.); Forces(i) += derivative * (coord(i) - coord(neighj) - getLatticeVec (supercellIds(i)(j))) / R; } } } double SxVDW::getTotalEnergy () { double R, Rij, fd, eVDW, C6ij; int i, j, neighj; eVDW = 0.; for (i = 0; i < nAtoms; i++) { for (j = 0; j < neighbours(i).getSize (); j++) { R = dist(i)(j); neighj = neighbours(i)(j); Rij = getRij (i, neighj); C6ij = getC6ij (i, neighj); fd = getDampingFunction (R, Rij); eVDW += -fd * C6ij/(::pow(R, 6.))/2.; } } return eVDW; } SxVector3<Double> SxVDW::getForceOnAtom (int i) { SxVector3<Double> returnValue; double R, Rij, C6ij, fd, fdPrime, derivative; int neighj; returnValue(0) = 0.; returnValue(1) = 0.; returnValue(2) = 0.; //cout << "Atom "<< i << endl; for (int j = 0; j < neighbours(i).getSize (); j++) { //if (neighbours (i)(j)) { neighj = neighbours(i)(j); //cout << "Bonding Partner: " << neighj << endl;; R = dist(i)(j); Rij = getRij(i, neighj); C6ij = getC6ij(i, neighj); fdPrime = getDampingDerivative (R, Rij); fd = getDampingFunction (R, Rij); derivative = fdPrime*C6ij/::pow(R, 6.) - 6.*fd*C6ij/::pow(R, 7.); returnValue += derivative * (coord(i) - coord(neighj) - getLatticeVec (supercellIds(i)(j))) / dist(i)(j); //} } return returnValue; } void SxVDW::updateForces () { for (int i = 0; i < nAtoms; i++) { for (int j = 0; j < 3; j++) { Forces(i)(j) = 0; } } for (int i = 0; i < nAtoms; i++) { Forces(i) = getForceOnAtom (i); } } SxArray<SxVector3<Double> > SxVDW::getForces () { totalEnergy = 0.; if (output) cout << "...2 Body Contributions..." << endl; //updateForces (); compute (); // inherently updates Forces return Forces; } bool SxVDW::areNeighbors (int atom1, int atom2) { int i; bool isNeighbor = false; for (i = 0; i < neighbours(atom1).getSize (); i++) { if (atom2 == neighbours(atom1)(i)) { isNeighbor = true; i = (int)neighbours(atom1).getSize (); } } return isNeighbor; } int SxVDW::getNeighborIndex (int atom1, int atom2) { int i; int neighbor = 0; for (i = 0; i < neighbours(atom1).getSize (); i++) { if (atom2 == neighbours(atom1)(i)) { neighbor = i; i = (int)neighbours(atom1).getSize (); } } return neighbor; } /* SxMatrix3<Double> SxVDW::getInteraction (int atom1, int atom2, int neighborIndex) { SxMatrix3<Double> returnValue; SxMatrix3<Double> dtwor; SxMatrix3<Double> twodr; int i, j; SxVector3<Double> coord1, coord2, deltaCoord; coord1 = coord(atom1); coord2 = coord(atom2); double dg, g, fd, fdP, fdPP; double R = dist(atom1)(neighborIndex); double Rij = getRij (atom1, atom2); double C6ij = getC6ij (atom1, atom2); deltaCoord = coord1 - coord2 - getLatticeVec (supercellIds(atom1)(neighborIndex)); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { if (i == j) { dtwor(i, j) = -1/R + ::pow((deltaCoord(i)), 2.)/::pow(R, 3.); } else { dtwor(i, j) = (deltaCoord(i))* ( deltaCoord(j)) /::pow(R, 3.); } } } for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { twodr(i, j) = - (deltaCoord(i)) *(deltaCoord(j))/::pow(R, 2.); } } fd = getDampingFunction (R, Rij); fdP = getDampingDerivative (R, Rij); fdPP = getDampingSecondDerivative (R, Rij); g = fdP*C6/::pow(R, 6.) - 6.*fd*C6/::pow(R, 7.); dg = fdPP*C6/::pow(R, 6.) - 12.*fdP*C6/::pow(R, 7.) + 42.*fd*C6/::pow(R, 8.); returnValue = twodr*dg + dtwor*g; //cout << g << endl; //cout << returnValue << endl << endl; return returnValue; } SxMatrix<Double> SxVDW::getHessian () { int i, j, k, l; int size = nAtoms*3; SxMatrix<Double> returnValue (size, size); SxMatrix3<Double> interaction; returnValue.set (0.); for (k = 0; k < 3; k++) { for (l = 0; l < 3; l++) { interaction(k)(l) = 0.; } } for (i = 0; i < nAtoms; i++) { for (j = 0; j < nAtoms; j++) { interaction = interaction*0.; if (i == j) { for (k = 0; k < neighbours(i).getSize (); k++) { if (i != neighbours(i)(k)) { interaction = interaction + getInteraction(i, neighbours(i)(k), k); } } } else { if (areNeighbors (i, j)) { for (k = 0; k < neighbours(i).getSize (); k++) { if ( neighbours(i)(k) == j ){ interaction = interaction - getInteraction(i, j, k); //interaction = (-1.)*interaction; } } } else { interaction = 0.*interaction; } } for (k = 0; k < 3; k++) { for (l = 0; l < 3; l++) { returnValue(3*i + k, 3*j +l) = interaction(k, l); } } } } return returnValue; } SxMatrix<Double> SxVDW::getNumericalHessian (double dx) { int i, j, k, l; SxArray<SxVector3<Double> > undevCoord (nAtoms); SxArray<SxVector3<Double> > devCoord (nAtoms); SxArray<SxVector3<Double> > devForcesLeft(nAtoms); SxArray<SxVector3<Double> > devForcesRight(nAtoms); SxMatrix<Double> hessian (nAtoms*3, nAtoms*3); //update(coord); //undevForces = getForces(); for (i = 0; i < nAtoms; i++) { undevCoord(i) = coord(i); devCoord(i) = coord(i); } for (i = 0; i < nAtoms; i++) { cout << "Atom " << i << " of " << nAtoms << endl; for (j = 0; j < 3; j++) { devCoord(i)(j) += dx; update(devCoord); devForcesRight = getForces (); devCoord(i)(j) -= 2.*dx; update(devCoord); devForcesLeft = getForces (); devCoord(i)(j) += dx; for (k = 0; k < nAtoms; k++) { for (l = 0; l < 3; l++) { hessian(i*3 + j, k*3 +l) = -(devForcesRight(k)(l) - devForcesLeft(k)(l))/2./dx; } } } } update(undevCoord); return hessian; } */ SxArray<SxVector3<Double> > SxVDW::getNumericalForces (double dx) { SxArray<SxVector3<Double> > forces (nAtoms); SxArray<SxVector3<Double> > dummy (nAtoms); SxArray<SxVector3<Double> > undevCoord (nAtoms); SxArray<SxVector3<Double> > devCoord (nAtoms); double undevEnergy; update(coord); totalEnergy = getTotalEnergy (); undevEnergy = totalEnergy; for (int i = 0; i < nAtoms; i++) { undevCoord(i) = coord(i); devCoord(i) = coord(i); } for (int i = 0; i < nAtoms; i++) { cout << "Atom " << i << " of " << nAtoms << endl; for (int j = 0; j < 3; j++) { forces(i)(j) = 0.; devCoord(i)(j) += dx; update(devCoord); totalEnergy = getTotalEnergy (); forces(i)(j) -= (totalEnergy - undevEnergy)/dx/2.; devCoord(i)(j) -= 2.*dx; update(devCoord); totalEnergy = getTotalEnergy(); forces(i)(j) += (totalEnergy - undevEnergy)/dx/2.; devCoord(i)(j) += dx; } } totalEnergy = undevEnergy; return forces; } double SxVDW::getRij (int atom1, int atom2) { /* Return the combined vdw radius of atom1 and atom2. If the TS correction is chosen, this value is modified according to each atom's Hirshfeld volume ratio. */ double Ri = vdwRadius(atom1); double Rj = vdwRadius(atom2); if (correctionType == SxString("TS")) { Ri = Ri * getVolumeFraction(atom1); Rj = Rj * getVolumeFraction(atom2); } double Rij = Ri + Rj; return Rij; } double SxVDW::getC6ij (int atom1, int atom2) { /* Return the combined C6 dispersion coefficient between atom1 and atom2. If the TS correction is chosen, this value is modified according to each atom's Hirshfeld volume ratio. */ double C6i, C6j, C6ij, alphai, alphaj; C6i = C6(atom1); C6j = C6(atom2); alphai = polarizability(atom1); alphaj = polarizability(atom2); if (correctionType == SxString("TS")) { double nui = getVolumeFraction(atom1); double nuj = getVolumeFraction(atom2); C6i = C6i * ::pow(nui, 2); C6j = C6j * ::pow(nuj, 2); alphai = alphai * nui; alphaj = alphaj * nuj; } if (correctionType == SxString("TS") or combinationRule == SxString("Tang")) { // from Tang,K. T. Phys. Rev. 1969, 177, 108 C6ij = (2 * C6i*C6j / ( C6j * alphai / alphaj + C6i * alphaj / alphai ) ); } else if (combinationRule == SxString("GB")) { // from Gould & Bucko (https://arxiv.org/pdf/1604.02751.pdf) page 18 double alphaij = ::pow ( alphai * alphaj, 0.5 ); C6ij = 1.43 * ::pow (alphaij, 1.45); } else C6ij = ::pow (C6(atom1) * C6(atom2), 0.5); // Default return C6ij; } double SxVDW::getVolumeFraction(int atom) { /* Return the ratio between the Hirshfeld volume of the atom in its present environment and its volume as a free atom. */ double nu = 1; // TODO: we need to get Hirshfeld volume of the atom // and the volume of the free atom from a lookup table. // Pseudo-code: // double nu = getHirshfeldVolume(atom) / freeAtomicVolume(atom); return nu; } double SxVDW::getParam (SxString name, int atom1, int atom2) { if (name == SxString ("covalentCutoff")) { return 3.0; } if (name == SxString ("vdwCutoff")) { return 94.5; // 50 Angstroms, but in Bohr } if (name == SxString ("cdamp")) return 3.54; if (name == SxString ("dstar")) return 3.00; if (name == SxString ("C6ij")) { return getC6ij(atom1, atom2); } if (name == SxString ("beta")) return 23.0; if (name == SxString ("epsilon")) return 1.; if (name == SxString ("lamda")) return 21.0; if (name == SxString ("sigma")) return 1.; if (name == SxString ("gamma")) return 1.2; if (name == SxString ("constant")) return 21.0; if (name == SxString ("s6")) return 0.75; if (name == SxString ("d")) return 20.0; if (name == SxString ("sR")) return 1.0; return 1.; } void SxVDW::printParameters () { cout << "\nEmpirical Potential" << endl; cout << "\nNrOfAtoms " << nAtoms << endl; cout << "Omega" << superCell.determinant() << endl; } void SxVDW::printCoord () { cout << "\nCoordinates: \n"; for (int i = 0; i < nAtoms; i++) { cout << coord(i) << endl; } } void SxVDW::printSpecies () { cout << "\nCoordinates: \n"; for (int i = 0; i < nAtoms; i++) { cout << species(i) << endl; } } void SxVDW::printNeighbours () { for (int i = 0; i < nAtoms; i++) { cout << "Atom " << i << " has "<< neighbours(i).getSize() << " neighbours: "; for (int j = 0; j < neighbours(i).getSize(); j++) { /* if (neighbours(i)(j) == 1) cout << j << " "; } */ cout << neighbours(i)(j) << " "; } cout << endl; } }
25.035948
103
0.561807
[ "geometry" ]
11e587e603dec989aa49bc63590ff68134daa662
2,065
cpp
C++
two-pointers/3-A.cpp
forestLoop/Learning-ITMO-Academy-Pilot-Course
b70ea387cb6a7c26871d99ecf7109fd8f0237c3e
[ "MIT" ]
6
2021-07-04T08:47:48.000Z
2022-01-12T09:34:20.000Z
two-pointers/3-A.cpp
forestLoop/Learning-ITMO-Academy-Pilot-Course
b70ea387cb6a7c26871d99ecf7109fd8f0237c3e
[ "MIT" ]
null
null
null
two-pointers/3-A.cpp
forestLoop/Learning-ITMO-Academy-Pilot-Course
b70ea387cb6a7c26871d99ecf7109fd8f0237c3e
[ "MIT" ]
2
2021-11-24T12:18:58.000Z
2022-02-06T00:18:51.000Z
// A. Looped Playlist // https://codeforces.com/edu/course/2/lesson/9/3/practice/contest/307094/problem/A #include <iostream> #include <numeric> #include <vector> // Time: O(N) // Space: O(1) std::pair<int, unsigned long long> find_songs_to_listen(const std::vector<int> &songs, unsigned long long threshold) { // be careful! you have to static_cast to unsigned long long to avoid overflow const unsigned long long sum = std::accumulate(songs.begin(), songs.end(), static_cast<unsigned long long>(0)); const unsigned long long times = threshold / sum, songs_size = songs.size(); threshold %= sum; if (threshold == 0) { return {0, times * songs_size}; } unsigned long long current_cnt = 0, current_sum = 0, best_cnt = -1; int best_start = 0; for (int current_start = 0; current_start < songs_size; ++current_start) { while (current_sum > threshold) { current_sum -= songs[(current_start + current_cnt - 1) % songs_size]; --current_cnt; } while (current_sum < threshold) { current_sum += songs[(current_start + current_cnt) % songs_size]; ++current_cnt; } if (current_cnt < best_cnt) { best_cnt = current_cnt; best_start = current_start; } // move to the next song current_sum -= songs[current_start]; --current_cnt; } return {best_start, best_cnt + times * songs_size}; } int main() { int n; unsigned long long p; while (std::cin >> n >> p) { std::vector<int> songs(n); for (int i = 0; i < n; ++i) { std::cin >> songs[i]; } const auto to_listen = find_songs_to_listen(songs, p); // counts from 1 rather than 0, so we need to add 1 to the result std::cout << to_listen.first + 1 << " " << to_listen.second << std::endl; } return 0; } static const auto speedup = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return nullptr; }();
33.852459
118
0.602906
[ "vector" ]
eb2622d2b7319683efd036e9ff43809c6d59a1ec
1,413
cpp
C++
cpp/571-580/Out of Boundary Paths.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/571-580/Out of Boundary Paths.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/571-580/Out of Boundary Paths.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
class Solution { bool inBox(int i, int j, int m, int n) { if (i < 0 || j < 0 || i >= m || j >= n) return false; return true; } long get(int i, int j, int k, vector<vector<vector<long>>>& dp, int m, int n) { if (!inBox(j, k, m, n)) return 0; return dp[i][j][k]; } int coeff(int i, int j, int m, int n) { int coe = 0; if (!inBox(i, j - 1, m, n)) coe++; if (!inBox(i, j + 1, m, n)) coe++; if (!inBox(i - 1, j, m, n)) coe++; if (!inBox(i + 1, j, m, n)) coe++; return coe; } public: int findPaths(int m, int n, int N, int i, int j) { if (N == 0) return 0; vector<vector<vector<long>>> dp(N + 1, vector<vector<long>>(m, vector<long>(n, 0))); dp[0][i][j] = 1; long result = 1 * coeff(i, j, m, n); for (int i = 1; i < N; i++) { for (int j = 0; j < m; j++) { for (int k = 0; k < n; k++) { dp[i][j][k] = (get(i - 1, j - 1, k, dp , m, n) + get(i - 1, j + 1, k, dp , m, n) + get(i - 1, j, k - 1, dp , m, n) + get(i - 1, j, k + 1, dp , m, n)) % 1000000007; result += coeff(j, k, m, n) * dp[i][j][k]; result %= 1000000007; } } } return result; } };
32.113636
92
0.370134
[ "vector" ]
eb2720f7fe38a7dc5a249c88e3bc991f55189aa2
83,096
cpp
C++
src/gui/renderer.cpp
SCIInstitute/SCI-Solver_Peridynamic
b0b6b82151bbfdea5365bca156b449ca671cddc1
[ "MIT" ]
14
2018-02-01T08:26:26.000Z
2021-12-18T11:37:26.000Z
src/gui/renderer.cpp
SCIInstitute/SCI-Solver_Peridynamic
b0b6b82151bbfdea5365bca156b449ca671cddc1
[ "MIT" ]
null
null
null
src/gui/renderer.cpp
SCIInstitute/SCI-Solver_Peridynamic
b0b6b82151bbfdea5365bca156b449ca671cddc1
[ "MIT" ]
4
2018-05-30T05:11:34.000Z
2021-05-08T09:06:29.000Z
//------------------------------------------------------------------------------------------ // // // Created on: 2/20/2015 // Author: Nghia Truong // //------------------------------------------------------------------------------------------ #include "renderer.h" Renderer::Renderer(QWidget* parent, int viewportID) : QOpenGLWidget(parent), bAllocatedMemory(false), bInitializedScene(false), bTextureAnisotropicFiltering(true), // enabledClipYZPlane(false), iboBackground(QOpenGLBuffer::IndexBuffer), iboGround(QOpenGLBuffer::IndexBuffer), iboBox(QOpenGLBuffer::IndexBuffer), cubeObject(NULL), planeObject(NULL), specialKeyPressed(Renderer::NO_KEY), mouseButtonPressed(Renderer::NO_BUTTON), currentFloorTexture(NO_FLOOR), currentEnvironmentTexture(NO_ENVIRONMENT_TEXTURE), translation_(0.0f, 0.0f, 0.0f), translationLag_(0.0f, 0.0f, 0.0f), rotation_(0.0f, 0.0f, 0.0f), rotationLag_(0.0f, 0.0f, 0.0f), zooming_(0.0f), cameraPosition_(DEFAULT_CAMERA_POSITION), cameraFocus_(DEFAULT_CAMERA_FOCUS), cameraUpDirection_(0.0f, 1.0f, 0.0f), currentMouseTransTarget(TRANSFORM_CAMERA), currentParticleViewMode(SPHERES_VIEW), currentParticleColorMode(COLOR_PARTICLE_TYPE), imageOutputPath(""), enabledImageOutput(false), pausedImageOutput(false), bHideInvisibleParticles(false), outputImage(NULL), viewportID_(viewportID) { retinaScale = devicePixelRatio();; isParticlesReady = false; num_sph_particles_ = 0; num_pd_particles_ = 0; num_particles_ = 0; particleRandomColors = NULL; particleRampColors = NULL; particleSimulationColors = NULL; } //------------------------------------------------------------------------------------------ QSize Renderer::sizeHint() const { return QSize(1800, 1000); } //------------------------------------------------------------------------------------------ QSize Renderer::minimumSizeHint() const { return QSize(50, 50); } //------------------------------------------------------------------------------------------ void Renderer::mousePressEvent(QMouseEvent* _event) { lastMousePos = QVector2D(_event->localPos()); if(_event->button() == Qt::RightButton) { mouseButtonPressed = RIGHT_BUTTON; } else { mouseButtonPressed = LEFT_BUTTON; } } //------------------------------------------------------------------------------------------ void Renderer::mouseMoveEvent(QMouseEvent* _event) { QVector2D mouseMoved = QVector2D(_event->localPos()) - lastMousePos; switch(specialKeyPressed) { case Renderer::NO_KEY: { if(mouseButtonPressed == RIGHT_BUTTON) { translation_.setX(translation_.x() + mouseMoved.x() / 50.0f); translation_.setY(translation_.y() - mouseMoved.y() / 50.0f); } else { rotation_.setX(rotation_.x() - mouseMoved.x() / 5.0f); rotation_.setY(rotation_.y() - mouseMoved.y() / 5.0f); QPointF center = QPointF(0.5 * width(), 0.5 * height()); QPointF escentricity = _event->localPos() - center; escentricity.setX(escentricity.x() / center.x()); escentricity.setY(escentricity.y() / center.y()); rotation_.setZ(rotation_.z() - (mouseMoved.x()*escentricity.y() - mouseMoved.y() * escentricity.x()) / 5.0f); } } break; case Renderer::SHIFT_KEY: { if(mouseButtonPressed == RIGHT_BUTTON) { QVector2D dir = mouseMoved.normalized(); zooming_ += mouseMoved.length() * dir.x() / 500.0f; } else { rotation_.setX(rotation_.x() + mouseMoved.x() / 5.0f); rotation_.setZ(rotation_.z() + mouseMoved.y() / 5.0f); } } break; case Renderer::CTRL_KEY: break; } lastMousePos = QVector2D(_event->localPos()); update(); } //------------------------------------------------------------------------------------------ void Renderer::mouseReleaseEvent(QWheelEvent* _event) { mouseButtonPressed = NO_BUTTON; } //------------------------------------------------------------------------------------------ void Renderer::wheelEvent(QWheelEvent* _event) { if(!_event->angleDelta().isNull()) { zooming_ += (_event->angleDelta().x() + _event->angleDelta().y()) / 500.0f; } update(); } //------------------------------------------------------------------------------------------ void Renderer::allocateMemory(int num_sph_particles, int num_pd_particles, float sph_particle_radius, float pd_particle_radius) { if(!isValid()) { return; } makeCurrent(); num_sph_particles_ = num_sph_particles; num_pd_particles_ = num_pd_particles; num_particles_ = num_sph_particles + num_pd_particles; sph_particle_radius_ = sph_particle_radius; pd_particle_radius_ = pd_particle_radius; // qDebug() << num_sph_particles << num_pd_particles; // qDebug() << sph_particle_radius << pd_particle_radius; if(vboParticles.isCreated()) { vboParticles.destroy(); } vboParticles.create(); vboParticles.bind(); vboParticles.allocate(num_particles_ * (sizeof(real_t) * (4 + 3) // 4: coordinate, 3: color + sizeof(int))); // activity variable vboParticles.release(); initParticlesRandomColors(); initParticlesRampColors(); if(particleSimulationColors) { delete[] particleSimulationColors; } particleSimulationColors = new GLREAL[num_particles_ * 3]; setParticleColorMode(currentParticleColorMode); initParticlesVAO(PROGRAM_POINT_SPHERE_VIEW); // initParticlesVAO(PROGRAM_SURFACE_VIEW); doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::setSPHParticleColor(float r, float g, float b) { if(!isValid()) { return; } pointSphereSPHMaterial.setDiffuse(QVector4D(r, g, b, 1.0f)); makeCurrent(); glBindBuffer(GL_UNIFORM_BUFFER, UBOPointSphereSPHMaterial); glBufferData(GL_UNIFORM_BUFFER, pointSphereSPHMaterial.getStructSize(), &pointSphereSPHMaterial, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::setPDParticleColor(float _r, float g, float b) { if(!isValid()) { return; } pointSpherePDMaterial.setDiffuse(QVector4D(_r, g, b, 1.0f)); makeCurrent(); glBindBuffer(GL_UNIFORM_BUFFER, UBOPointSpherePDMaterial); glBufferData(GL_UNIFORM_BUFFER, pointSpherePDMaterial.getStructSize(), &pointSpherePDMaterial, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::setSurfaceDiffuseColor(float r, float g, float b) { if(!isValid()) { return; } surfaceMaterial.setDiffuse(QVector4D(r, g, b, 1.0f)); makeCurrent(); glBindBuffer(GL_UNIFORM_BUFFER, UBOSurfaceMaterial); glBufferData(GL_UNIFORM_BUFFER, surfaceMaterial.getStructSize(), NULL, GL_STREAM_DRAW); glBufferSubData(GL_UNIFORM_BUFFER, 0, surfaceMaterial.getStructSize(), &surfaceMaterial); glBindBuffer(GL_UNIFORM_BUFFER, 0); doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::keyPressEvent(QKeyEvent* _event) { switch(_event->key()) { case Qt::Key_Shift: specialKeyPressed = Renderer::SHIFT_KEY; break; case Qt::Key_Plus: { zooming_ -= 0.1f; } break; case Qt::Key_Minus: { zooming_ += 0.1f; } break; case Qt::Key_Up: { translation_ += QVector3D(0.0f, 0.5f, 0.0f); } break; case Qt::Key_Down: { translation_ -= QVector3D(0.0f, 0.5f, 0.0f); } break; case Qt::Key_Left: { translation_ -= QVector3D(0.5f, 0.0f, 0.0f); } break; case Qt::Key_Right: { translation_ += QVector3D(0.5f, 0.0f, 0.0f); } break; // case Qt::Key_X: // rotation-= QVector3D(0.0f, 3.0f, 0.0f); // break; default: QOpenGLWidget::keyPressEvent(_event); } } //------------------------------------------------------------------------------------------ void Renderer::keyReleaseEvent(QKeyEvent*) { specialKeyPressed = Renderer::NO_KEY; } //------------------------------------------------------------------------------------------ void Renderer::initializeGL() { initializeOpenGLFunctions(); glEnable (GL_DEPTH_TEST); glClearColor(0.8f, 0.8f, 0.8f, 1.0f); checkOpenGLVersion(); if(!bInitializedScene) { initScene(); bInitializedScene = true; } } //------------------------------------------------------------------------------------------ void Renderer::resizeGL(int w, int h) { projectionMatrix.setToIdentity(); projectionMatrix.perspective(45, (float)w / (float)h, 0.1f, 10000.0f); glBindBuffer(GL_UNIFORM_BUFFER, UBOMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 3 * SIZE_OF_MAT4, SIZE_OF_MAT4, projectionMatrix.constData()); glBindBuffer(GL_UNIFORM_BUFFER, 0); // prepare output image if(outputImage) { delete outputImage; } outputImage = new QImage(w, h, QImage::Format_ARGB32); } //------------------------------------------------------------------------------------------ void Renderer::paintGL() { if(!bInitializedScene) { return; } QVector3D cameraPosOld = cameraPosition_; QVector3D cameraFocusOld = cameraFocus_; switch(currentMouseTransTarget) { case TRANSFORM_CAMERA: { translateCamera(); rotateCamera(); } break; case TRANSFORM_LIGHT: { translateLight(); } break; } updateCamera(); float camDiff = (cameraPosOld - cameraPosition_).lengthSquared() + (cameraFocusOld - cameraFocus_).lengthSquared(); if(camDiff > 1e-5) { emit cameraChanged(cameraPosition_, cameraFocus_, cameraUpDirection_); } // render scene renderScene(); } //------------------------------------------------------------------------------------------ void Renderer::setCamera(QVector3D cameraPos, QVector3D cameraFocus, QVector3D cameraUpDir) { cameraPosition_ = cameraPos; cameraFocus_ = cameraFocus; cameraUpDirection_ = cameraUpDir; } //------------------------------------------------------------------------------------------ void Renderer::enableAnisotropicTextureFiltering(bool status) { bTextureAnisotropicFiltering = status; } void Renderer::enableClipYZPlane(bool status) { // enabledClipYZPlane = _status; if(!isValid()) { return; } makeCurrent(); if (status) { glEnable (GL_CLIP_PLANE0); } else { glDisable (GL_CLIP_PLANE0); } doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::hideInvisibleParticles(bool status) { bHideInvisibleParticles = status; } //------------------------------------------------------------------------------------------ void Renderer::setParticleViewMode(int view_mode) { currentParticleViewMode = static_cast<ParticleViewMode>(view_mode); } //------------------------------------------------------------------------------------------ void Renderer::setParticleColorMode(int color_mode) { currentParticleColorMode = static_cast<ParticleColorMode>(color_mode); if(!vboParticles.isCreated()) { qDebug() << "vaoParticles is not created!"; return; } GLREAL* colorArray; switch(color_mode) { case COLOR_RANDOM: colorArray = particleRandomColors; break; case COLOR_RAMP: colorArray = particleRampColors; break; default: return; } vboParticles.bind(); vboParticles.write(4 * num_particles_ * sizeof(GLREAL), colorArray, 3 * num_particles_ * sizeof(GLREAL)); vboParticles.release(); } //------------------------------------------------------------------------------------------ void Renderer::setParticlePositions(real_t* pd_positions, real_t* sph_positions, int* pd_activities, int* sph_activities, int current_frame) { if(!isValid()) { return; } if(!vboParticles.isCreated()) { PRINT_ERROR("vboParticle is not created!") return; } makeCurrent(); current_frame_ = current_frame; vboParticles.bind(); vboParticles.write(0, pd_positions, num_pd_particles_ * 4 * sizeof(GLREAL)); vboParticles.write(num_pd_particles_ * 4 * sizeof(GLREAL), sph_positions, num_sph_particles_ * 4 * sizeof(GLREAL)); if(bHideInvisibleParticles) { vboParticles.write(num_particles_ * sizeof(GLREAL) * (4 + 3), pd_activities, num_pd_particles_ * sizeof(GLint)); vboParticles.write(num_particles_ * sizeof(GLREAL) * (4 + 3) + num_pd_particles_ * sizeof(GLint), sph_activities, num_sph_particles_ * sizeof(GLint)); // int max_print = num_pd_particles_ < 100 ? num_pd_particles_ : 100; // qDebug() << "max_print: " << max_print; // for(int i = 0; i < max_print; ++i) // { // qDebug() << i << " " << pd_activities[i]; // } } vboParticles.release(); // initParticlesVAO(PROGRAM_POINT_SPHERE_VIEW); isParticlesReady = true; doneCurrent(); // qDebug() << "Num sph: " << num_sph_particles_; #if 0 { QFile fOutPD(QString("/Users/nghia/GoogleDrive/Research/Data/Txt/frame.%1.pd.txt").arg( current_frame_)); if (fOutPD.open(QFile::WriteOnly | QFile::Text)) { QTextStream s(&fOutPD); s << "particle_radius " << pd_particle_radius_ << '\n'; for (int i = 0; i < num_pd_particles_; ++i) { s << pd_positions[i * 4] << " " << pd_positions[i * 4 + 1] << " " << pd_positions[i * 4 + 2] << '\n'; } } else { qDebug() << "error opening output file"; exit(EXIT_FAILURE); } fOutPD.close(); QFile fOutSPH(QString("/Users/nghia/GoogleDrive/Research/Data/Txt/frame.%1.sph.txt").arg( current_frame_)); if (fOutSPH.open(QFile::WriteOnly | QFile::Text)) { QTextStream s(&fOutSPH); s << "particle_radius " << sph_particle_radius_ << '\n'; for (int i = 0; i < num_sph_particles_; ++i) { s << sph_positions[i * 4] << " " << sph_positions[i * 4 + 1] << " " << sph_positions[i * 4 + 2] << '\n'; } } else { qDebug() << "error opening output file"; exit(EXIT_FAILURE); } fOutSPH.close(); qDebug() << "Frame written: " << current_frame_; } #endif #if 0 //////////////////////////////////////////////////////////////////////////////// { QFile fOutPD(QString("/Users/nghia/OBJ/frame.%1.pd.txt").arg(_currentFrame)); if (fOutPD.open(QFile::WriteOnly | QFile::Text)) { QTextStream s(&fOutPD); // s << "particle_radius " << PeridynamicsParticleRadius << '\n'; for (int i = 0; i < numPeridynamicsParticles; ++i) { s << "v " << _pdParticles[i * 4] << " " << _pdParticles[i * 4 + 1] << " " << _pdParticles[i * 4 + 2] << '\n'; } } else { qDebug() << "error opening output file"; exit(EXIT_FAILURE); } fOutPD.close(); QFile fOutSPH(QString("/Users/nghia/OBJ/frame.%1.sph.txt").arg(_currentFrame)); if (fOutSPH.open(QFile::WriteOnly | QFile::Text)) { QTextStream s(&fOutSPH); // s << "particle_radius " << SPHParticleRadius << '\n'; for (int i = numPeridynamicsParticles; i < numTotalParticles; ++i) { s << "v " << _pdParticles[i * 4] << " " << _pdParticles[i * 4 + 1] << " " << _pdParticles[i * 4 + 2] << '\n'; } } else { qDebug() << "error opening output file"; exit(EXIT_FAILURE); } fOutSPH.close(); } qDebug() << "Files written."; #endif } //------------------------------------------------------------------------------------------ void Renderer::setParticleDensitiesPositions(real_t* _pdParticles, real_t* _sphParticles, int* pd_activities, int* sph_activities, real_t* sph_densities, int current_frame) { if(!isValid()) { return; } if(!vboParticles.isCreated()) { PRINT_ERROR("vboParticle is not created!") return; } // find the max and min of density real_t maxDensity = -1e10; real_t minDensity = 1e10; #pragma unroll 8 for(int i = 0; i < num_sph_particles_; ++i) { if(maxDensity < sph_densities[i]) { maxDensity = sph_densities[i]; } if(minDensity > sph_densities[i]) { minDensity = sph_densities[i]; } // qDebug() << _densities[i]; } // qDebug() << maxDensity << minDensity; // for(int i = 0; i < numSPHParticles; ++i) // { // qDebug() << _sphParticles[i * 4] << _sphParticles[i * 4 + 1] << _sphParticles[i * 4 + 2]; // } real_t scale = maxDensity - minDensity; if(scale == 0.0) { scale = 1.0; } real_t t; #pragma unroll 8 for(int i = 0; i < num_pd_particles_; ++i) { t = 0; colorRamp(t, &(particleSimulationColors)[i * 3]); } for(int i = 0; i < num_sph_particles_; ++i) { t = (sph_densities[i] - minDensity) / scale; colorRamp(t, &(particleSimulationColors)[(i + num_pd_particles_) * 3]); } makeCurrent(); current_frame_ = current_frame; vboParticles.bind(); vboParticles.write(0, _pdParticles, num_pd_particles_ * 4 * sizeof(GLREAL)); vboParticles.write(num_pd_particles_ * 4 * sizeof(GLREAL), _sphParticles, num_sph_particles_ * 4 * sizeof(GLREAL)); vboParticles.write(4 * num_particles_ * sizeof(GLREAL), particleSimulationColors, 3 * num_particles_ * sizeof(GLREAL)); if(bHideInvisibleParticles) { vboParticles.write(num_particles_ * sizeof(GLREAL) * (4 + 3), pd_activities, num_pd_particles_ * sizeof(GLint)); vboParticles.write(num_particles_ * sizeof(GLREAL) * (4 + 3) + num_pd_particles_ * sizeof(GLint), sph_activities, num_sph_particles_ * sizeof(GLint)); } vboParticles.release(); isParticlesReady = true; doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::setParticleStiffnesPositions(real_t* pd_positions, real_t* sph_positions, int* pd_activities, int* sph_activities, real_t* pd_stiffness, int current_frame) { if(!isValid()) { return; } if(!vboParticles.isCreated()) { PRINT_ERROR("vboParticle is not created!") return; } // find the max and min of density real_t maxStiff = -1e100; real_t minStiff = 1e100; #pragma unroll 8 for(int i = 0; i < num_pd_particles_; ++i) { if(maxStiff < pd_stiffness[i]) { maxStiff = pd_stiffness[i]; } if(minStiff > pd_stiffness[i]) { minStiff = pd_stiffness[i]; } // qDebug() << _particleStiffness[i]; } // qDebug() << minStiff<< maxStiff; //qDebug() << numPeridynamicsParticles; real_t scale = (real_t)(maxStiff - minStiff); if(scale == 0.0) { scale = 1.0; } real_t t; #pragma unroll 8 for(int i = 0; i < num_pd_particles_; ++i) { // qDebug() << _particleStretches[i]; t = (real_t)(pd_stiffness[i] - minStiff) / scale; // if(t < 0.0 || t > 1.0) // { // t = 0.99; // } colorRamp(t, &(particleSimulationColors)[i * 3]); } for(int i = num_pd_particles_; i < num_particles_; ++i) { colorRamp(0.2, &(particleSimulationColors)[i * 3]); } makeCurrent(); current_frame_ = current_frame; vboParticles.bind(); vboParticles.write(0, pd_positions, num_pd_particles_ * 4 * sizeof(GLREAL)); vboParticles.write(num_pd_particles_ * 4 * sizeof(GLREAL), sph_positions, num_sph_particles_ * 4 * sizeof(GLREAL)); vboParticles.write(4 * num_particles_ * sizeof(GLREAL), particleSimulationColors, 3 * num_particles_ * sizeof(GLREAL)); if(bHideInvisibleParticles) { vboParticles.write(num_particles_ * sizeof(GLREAL) * (4 + 3), pd_activities, num_pd_particles_ * sizeof(GLint)); vboParticles.write(num_particles_ * sizeof(GLREAL) * (4 + 3) + num_pd_particles_ * sizeof(GLint), sph_activities, num_sph_particles_ * sizeof(GLint)); } vboParticles.release(); isParticlesReady = true; doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::setParticleActivitiesPositions(real_t* pd_positions, real_t* sph_positions, int* pd_activities, int* sph_activities, int current_frame) { if(!isValid()) { return; } if(!vboParticles.isCreated()) { PRINT_ERROR("vboParticle is not created!") return; } // find the max and min of density #pragma unroll 8 for(int i = 0; i < num_pd_particles_; ++i) { colorRamp((real_t)(pd_activities[i]) / (real_t)NUM_ACTIVITY_MODE, &(particleSimulationColors)[i * 3]); } for(int i = 0; i < num_sph_particles_; ++i) { colorRamp((real_t)(sph_activities[i]) / (real_t)NUM_ACTIVITY_MODE, &(particleSimulationColors)[(i + num_pd_particles_) * 3]); } makeCurrent(); current_frame_ = current_frame; vboParticles.bind(); vboParticles.write(0, pd_positions, num_pd_particles_ * 4 * sizeof(GLREAL)); vboParticles.write(num_pd_particles_ * 4 * sizeof(GLREAL), sph_positions, num_sph_particles_ * 4 * sizeof(GLREAL)); vboParticles.write(4 * num_particles_ * sizeof(GLREAL), particleSimulationColors, 3 * num_particles_ * sizeof(GLREAL)); if(bHideInvisibleParticles) { vboParticles.write(num_particles_ * sizeof(GLREAL) * (4 + 3), pd_activities, num_pd_particles_ * sizeof(GLint)); vboParticles.write(num_particles_ * sizeof(GLREAL) * (4 + 3) + num_pd_particles_ * sizeof(GLint), sph_activities, num_sph_particles_ * sizeof(GLint)); } vboParticles.release(); isParticlesReady = true; doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::setEnvironmentTexture(int texture) { currentEnvironmentTexture = static_cast<EnvironmentTexture>(texture); } //------------------------------------------------------------------------------------------ void Renderer::setFloorTexture(int texture) { currentFloorTexture = static_cast<FloorTexture>(texture); } //------------------------------------------------------------------------------------------ void Renderer::setMouseTransformationTarget(MouseTransformationTarget mouse_target) { currentMouseTransTarget = mouse_target; } //------------------------------------------------------------------------------------------ void Renderer::setLightIntensity(int intensity) { if(!isValid()) { return; } makeCurrent(); light.intensity = (GLfloat)intensity / 100.0f; glBindBuffer(GL_UNIFORM_BUFFER, UBOLight); glBufferData(GL_UNIFORM_BUFFER, light.getStructSize(), &light, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); doneCurrent(); update(); } //------------------------------------------------------------------------------------------ void Renderer::resetCameraPosition() { cameraPosition_ = DEFAULT_CAMERA_POSITION; cameraFocus_ = DEFAULT_CAMERA_FOCUS; cameraUpDirection_ = QVector3D(0.0f, 1.0f, 0.0f); update(); } //------------------------------------------------------------------------------------------ void Renderer::resetLightPosition() { makeCurrent(); light.position = DEFAULT_LIGHT_DIRECTION; glBindBuffer(GL_UNIFORM_BUFFER, UBOLight); glBufferData(GL_UNIFORM_BUFFER, light.getStructSize(), &light, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); doneCurrent(); } //------------------------------------------------------------------------------------------ void Renderer::enableImageOutput(bool status) { enabledImageOutput = status; } //------------------------------------------------------------------------------------------ void Renderer::pauseImageOutput(bool status) { pausedImageOutput = status; } //------------------------------------------------------------------------------------------ void Renderer::setImageOutputPath(QString output_path) { imageOutputPath = output_path; } //------------------------------------------------------------------------------------------ void Renderer::checkOpenGLVersion() { QString verStr = QString((const char*)glGetString(GL_VERSION)); int major = verStr.left(verStr.indexOf(".")).toInt(); int minor = verStr.mid(verStr.indexOf(".") + 1, 1).toInt(); if(!(major >= 4 && minor >= 1)) { QMessageBox::critical(this, "Error", QString("Your OpenGL version is %1.%2, which does not satisfy this program requirement (OpenGL >= 4.1)") .arg(major).arg(minor)); close(); } // qDebug() << major << minor; // qDebug() << verStr; // TRUE_OR_DIE(major >= 4 && minor >= 1, "OpenGL version must >= 4.1"); } //------------------------------------------------------------------------------------------ void Renderer::initScene() { initShaderPrograms(); initTexture(); initSceneMemory(); initVertexArrayObjects(); initSharedBlockUniform(); initSceneMatrices(); initFrameBufferObject(); glEnable(GL_DEPTH_TEST); } //------------------------------------------------------------------------------------------ void Renderer::initShaderPrograms() { vertexShaderSourceMap.insert(PROGRAM_POINT_SPHERE_VIEW, "shaders/point-sphere-view.vs.glsl"); vertexShaderSourceMap.insert(PROGRAM_SURFACE_VIEW, "shaders/surface-view.vs.glsl"); vertexShaderSourceMap.insert(PROGRAM_RENDER_BACKGROUND, "shaders/background.vs.glsl"); vertexShaderSourceMap.insert(PROGRAM_RENDER_GROUND, "shaders/ground.vs.glsl"); vertexShaderSourceMap.insert(PROGRAM_RENDER_BOX, "shaders/box.vs.glsl"); vertexShaderSourceMap.insert(PROGRAM_RENDER_LIGHT, "shaders/light.vs.glsl"); vertexShaderSourceMap.insert(PROGRAM_RENDER_DEPTH_BUFFER, "shaders/depth-map.vs.glsl"); fragmentShaderSourceMap.insert(PROGRAM_POINT_SPHERE_VIEW, "shaders/point-sphere-view.fs.glsl"); fragmentShaderSourceMap.insert(PROGRAM_SURFACE_VIEW, "shaders/surface-view.fs.glsl"); fragmentShaderSourceMap.insert(PROGRAM_RENDER_BACKGROUND, "shaders/background.fs.glsl"); fragmentShaderSourceMap.insert(PROGRAM_RENDER_GROUND, "shaders/ground.fs.glsl"); fragmentShaderSourceMap.insert(PROGRAM_RENDER_BOX, "shaders/box.fs.glsl"); fragmentShaderSourceMap.insert(PROGRAM_RENDER_LIGHT, "shaders/light.fs.glsl"); fragmentShaderSourceMap.insert(PROGRAM_RENDER_DEPTH_BUFFER, "shaders/depth-map.fs.glsl"); // for(int i = 0; i < NUM_GLSL_PROGRAMS; ++i) // { // TRUE_OR_DIE(initProgram(static_cast<GLSLPrograms>(i)), "Cannot init program"); // } TRUE_OR_DIE(initRenderBackgroundProgram(), "Cannot init program drawing background"); TRUE_OR_DIE(initRenderGroundProgram(), "Cannot init program drawing ground"); TRUE_OR_DIE(initRenderBoxProgram(), "Cannot init program drawing box"); TRUE_OR_DIE(initRenderLightProgram(), "Cannot init program drawing light"); TRUE_OR_DIE(initRenderDepthBufferProgram(), "Cannot init program depth-buffer"); TRUE_OR_DIE(initPointSphereViewProgram(), "Cannot init program point-sphere-view"); } //------------------------------------------------------------------------------------------ bool Renderer::validateShaderPrograms(GLSLPrograms program) { GLint status; GLint logLen; GLchar log[1024]; glValidateProgram(glslPrograms[program]->programId()); glGetProgramiv(glslPrograms[program]->programId(), GL_VALIDATE_STATUS, &status); glGetProgramiv(glslPrograms[program]->programId(), GL_INFO_LOG_LENGTH, &logLen); if(logLen > 0) { glGetProgramInfoLog(glslPrograms[program]->programId(), logLen, &logLen, log); if(QString(log).trimmed().length() != 0) { qDebug() << "ShadingMode: " << program << ", log: " << log; } } return (status == GL_TRUE); } //------------------------------------------------------------------------------------------ bool Renderer::initSurfaceViewProgram() { return true; } //------------------------------------------------------------------------------------------ bool Renderer::initPointSphereViewProgram() { GLint location; glslPrograms[PROGRAM_POINT_SPHERE_VIEW] = new QOpenGLShaderProgram; QOpenGLShaderProgram* program = glslPrograms[PROGRAM_POINT_SPHERE_VIEW]; bool success; success = program->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShaderSourceMap.value(PROGRAM_POINT_SPHERE_VIEW)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShaderSourceMap.value(PROGRAM_POINT_SPHERE_VIEW)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->link(); TRUE_OR_DIE(success, "Cannot link GLSL program."); location = program->attributeLocation("v_coord"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute vertex coordinate."); attrVertex[PROGRAM_POINT_SPHERE_VIEW] = location;; location = program->attributeLocation("v_activity"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute activity."); attrActivity[PROGRAM_POINT_SPHERE_VIEW] = location; location = program->attributeLocation("v_color"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute vertex coordinate."); attrColor[PROGRAM_POINT_SPHERE_VIEW] = location; location = glGetUniformBlockIndex(program->programId(), "Matrices"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMatrices[PROGRAM_POINT_SPHERE_VIEW] = location; location = glGetUniformBlockIndex(program->programId(), "Light"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniLight[PROGRAM_POINT_SPHERE_VIEW] = location; location = glGetUniformBlockIndex(program->programId(), "Material"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMaterial[PROGRAM_POINT_SPHERE_VIEW] = location; return true; } //------------------------------------------------------------------------------------------ bool Renderer::initRenderBackgroundProgram() { GLint location; glslPrograms[PROGRAM_RENDER_BACKGROUND] = new QOpenGLShaderProgram; QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_BACKGROUND]; bool success; success = program->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShaderSourceMap.value(PROGRAM_RENDER_BACKGROUND)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShaderSourceMap.value(PROGRAM_RENDER_BACKGROUND)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->link(); TRUE_OR_DIE(success, "Cannot link GLSL program."); location = program->attributeLocation("v_coord"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute vertex coordinate."); attrVertex[PROGRAM_RENDER_BACKGROUND] = location; location = glGetUniformBlockIndex(program->programId(), "Matrices"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMatrices[PROGRAM_RENDER_BACKGROUND] = location; location = program->uniformLocation("cameraPosition"); TRUE_OR_DIE(location >= 0, "Cannot bind uniform cameraPosition."); uniCameraPosition[PROGRAM_RENDER_BACKGROUND] = location; location = program->uniformLocation("envTex"); TRUE_OR_DIE(location >= 0, "Cannot bind uniform envTex."); uniObjTexture[PROGRAM_RENDER_BACKGROUND] = location; return true; } //------------------------------------------------------------------------------------------ bool Renderer::initRenderGroundProgram() { QOpenGLShaderProgram* program; GLint location; ///////////////////////////////////////////////////////////////// glslPrograms[PROGRAM_RENDER_GROUND] = new QOpenGLShaderProgram; program = glslPrograms[PROGRAM_RENDER_GROUND]; bool success; success = program->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShaderSourceMap.value(PROGRAM_RENDER_GROUND)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShaderSourceMap.value(PROGRAM_RENDER_GROUND)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->link(); TRUE_OR_DIE(success, "Cannot link GLSL program."); location = program->attributeLocation("v_coord"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute vertex coordinate."); attrVertex[PROGRAM_RENDER_GROUND] = location; location = program->attributeLocation("v_normal"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute vertex normal."); attrNormal[PROGRAM_RENDER_GROUND] = location; location = program->attributeLocation("v_texCoord"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute texture coordinate."); attrTexCoord[PROGRAM_RENDER_GROUND] = location; location = glGetUniformBlockIndex(program->programId(), "Matrices"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMatrices[PROGRAM_RENDER_GROUND] = location; location = glGetUniformBlockIndex(program->programId(), "Light"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniLight[PROGRAM_RENDER_GROUND] = location; location = glGetUniformBlockIndex(program->programId(), "Material"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMaterial[PROGRAM_RENDER_GROUND] = location; location = program->uniformLocation("cameraPosition"); TRUE_OR_DIE(location >= 0, "Cannot bind uniform cameraPosition."); uniCameraPosition[PROGRAM_RENDER_GROUND] = location; location = program->uniformLocation("objTex"); TRUE_OR_DIE(location >= 0, "Cannot bind uniform objTex."); uniObjTexture[PROGRAM_RENDER_GROUND] = location; location = program->uniformLocation("hasObjTex"); TRUE_OR_DIE(location >= 0, "Cannot bind uniform hasObjTex."); uniHasObjTexture[PROGRAM_RENDER_GROUND] = location; return true; } //------------------------------------------------------------------------------------------ bool Renderer::initRenderBoxProgram() { QOpenGLShaderProgram* program; GLint location; ///////////////////////////////////////////////////////////////// glslPrograms[PROGRAM_RENDER_BOX] = new QOpenGLShaderProgram; program = glslPrograms[PROGRAM_RENDER_BOX]; bool success; success = program->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShaderSourceMap.value(PROGRAM_RENDER_BOX)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShaderSourceMap.value(PROGRAM_RENDER_BOX)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->link(); TRUE_OR_DIE(success, "Cannot link GLSL program."); location = program->attributeLocation("v_coord"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute vertex coordinate."); attrVertex[PROGRAM_RENDER_BOX] = location; location = program->attributeLocation("v_normal"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute vertex normal."); attrNormal[PROGRAM_RENDER_BOX] = location; location = glGetUniformBlockIndex(program->programId(), "Matrices"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMatrices[PROGRAM_RENDER_BOX] = location; location = glGetUniformBlockIndex(program->programId(), "Light"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniLight[PROGRAM_RENDER_BOX] = location; location = glGetUniformBlockIndex(program->programId(), "Material"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMaterial[PROGRAM_RENDER_BOX] = location; location = program->uniformLocation("cameraPosition"); TRUE_OR_DIE(location >= 0, "Cannot bind uniform cameraPosition."); uniCameraPosition[PROGRAM_RENDER_BOX] = location; location = program->uniformLocation("objTex"); TRUE_OR_DIE(location >= 0, "Cannot bind uniform objTex."); uniObjTexture[PROGRAM_RENDER_BOX] = location; location = program->uniformLocation("hasObjTex"); TRUE_OR_DIE(location >= 0, "Cannot bind uniform hasObjTex."); uniHasObjTexture[PROGRAM_RENDER_BOX] = location; return true; } //------------------------------------------------------------------------------------------ bool Renderer::initRenderLightProgram() { GLint location; glslPrograms[PROGRAM_RENDER_LIGHT] = new QOpenGLShaderProgram; QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_LIGHT]; bool success; success = program->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShaderSourceMap.value(PROGRAM_RENDER_LIGHT)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShaderSourceMap.value(PROGRAM_RENDER_LIGHT)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->link(); TRUE_OR_DIE(success, "Cannot link GLSL program."); location = glGetUniformBlockIndex(program->programId(), "Matrices"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMatrices[PROGRAM_RENDER_LIGHT] = location; location = glGetUniformBlockIndex(program->programId(), "Light"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniLight[PROGRAM_RENDER_LIGHT] = location; return true; } //------------------------------------------------------------------------------------------ bool Renderer::initRenderDepthBufferProgram() { GLint location; glslPrograms[PROGRAM_RENDER_DEPTH_BUFFER] = new QOpenGLShaderProgram; QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_DEPTH_BUFFER]; bool success; success = program->addShaderFromSourceFile(QOpenGLShader::Vertex, vertexShaderSourceMap.value(PROGRAM_RENDER_DEPTH_BUFFER)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->addShaderFromSourceFile(QOpenGLShader::Fragment, fragmentShaderSourceMap.value(PROGRAM_RENDER_DEPTH_BUFFER)); TRUE_OR_DIE(success, "Cannot compile shader from file."); success = program->link(); TRUE_OR_DIE(success, "Cannot link GLSL program."); location = program->attributeLocation("v_coord"); TRUE_OR_DIE(location >= 0, "Cannot bind attribute vertex coordinate."); attrVertex[PROGRAM_RENDER_DEPTH_BUFFER] = location; location = glGetUniformBlockIndex(program->programId(), "Matrices"); TRUE_OR_DIE(location >= 0, "Cannot bind block uniform."); uniMatrices[PROGRAM_RENDER_DEPTH_BUFFER] = location; return true; } //------------------------------------------------------------------------------------------ void Renderer::initSceneMatrices() { ///////////////////////////////////////////////////////////////// // background backgroundCubeModelMatrix.setToIdentity(); backgroundCubeModelMatrix.scale(1000.0f); ///////////////////////////////////////////////////////////////// // ground groundModelMatrix.setToIdentity(); groundModelMatrix.translate(DEFAULT_GROUND_POSITION); groundModelMatrix.scale(GROUND_PLANE_SIZE); groundNormalMatrix = QMatrix4x4(groundModelMatrix.normalMatrix()); ///////////////////////////////////////////////////////////////// // box boxModelMatrix.setToIdentity(); boxModelMatrix.scale(1, 1, 2); boxModelMatrix.translate(DEFAULT_BOX_POSITION); boxNormalMatrix = QMatrix4x4(boxModelMatrix.normalMatrix()); ///////////////////////////////////////////////////////////////// // particles particlesModelMatrix.setToIdentity(); // particlesModelMatrix.translate(DEFAULT_BOX_POSITION); } //------------------------------------------------------------------------------------------ void Renderer::initSharedBlockUniform() { ///////////////////////////////////////////////////////////////// // setup the light and material light.position = DEFAULT_LIGHT_DIRECTION; light.intensity = 0.8f; groundMaterial.setDiffuse(QVector4D(-1.0f, 0.45f, 1.0f, 1.0f)); groundMaterial.setSpecular(QVector4D(0.5f, 0.5f, 0.5f, 1.0f)); groundMaterial.shininess = 150.0f; boxMaterial.setDiffuse(QVector4D(0.4f, 0.5f, 0.0f, 1.0f)); boxMaterial.setSpecular(QVector4D(0.5f, 0.5f, 0.5f, 1.0f)); boxMaterial.shininess = 150.0f; surfaceMaterial.setDiffuse(QVector4D(0.02f, 0.45f, 1.0f, 1.0f)); surfaceMaterial.setSpecular(QVector4D(0.5f, 0.5f, 0.5f, 1.0f)); surfaceMaterial.shininess = 150.0f; pointSphereSPHMaterial.setDiffuse(QVector4D(0.82f, 0.45f, 1.0f, 1.0f)); pointSphereSPHMaterial.setSpecular(QVector4D(0.5f, 0.5f, 0.5f, 1.0f)); pointSphereSPHMaterial.shininess = 150.0f; pointSpherePDMaterial.setDiffuse(QVector4D(0.42f, 1.0f, 0.5f, 1.0f)); pointSpherePDMaterial.setSpecular(QVector4D(0.5f, 0.5f, 0.5f, 1.0f)); pointSpherePDMaterial.shininess = 150.0f; ///////////////////////////////////////////////////////////////// // setup binding points for block uniform for(int i = 0; i < NUM_BINDING_POINTS; ++i) { UBOBindingIndex[i] = i + 1; } ///////////////////////////////////////////////////////////////// // setup data for block uniform glGenBuffers(1, &UBOMatrices); glBindBuffer(GL_UNIFORM_BUFFER, UBOMatrices); glBufferData(GL_UNIFORM_BUFFER, 4 * SIZE_OF_MAT4, NULL, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &UBOLight); glBindBuffer(GL_UNIFORM_BUFFER, UBOLight); glBufferData(GL_UNIFORM_BUFFER, light.getStructSize(), &light, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &UBOSurfaceMaterial); glBindBuffer(GL_UNIFORM_BUFFER, UBOSurfaceMaterial); glBufferData(GL_UNIFORM_BUFFER, surfaceMaterial.getStructSize(), &surfaceMaterial, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &UBOPointSphereSPHMaterial); glBindBuffer(GL_UNIFORM_BUFFER, UBOPointSphereSPHMaterial); glBufferData(GL_UNIFORM_BUFFER, pointSphereSPHMaterial.getStructSize(), &pointSphereSPHMaterial, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &UBOPointSpherePDMaterial); glBindBuffer(GL_UNIFORM_BUFFER, UBOPointSpherePDMaterial); glBufferData(GL_UNIFORM_BUFFER, pointSpherePDMaterial.getStructSize(), &pointSpherePDMaterial, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &UBOGroundMaterial); glBindBuffer(GL_UNIFORM_BUFFER, UBOGroundMaterial); glBufferData(GL_UNIFORM_BUFFER, groundMaterial.getStructSize(), &groundMaterial, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &UBOBoxMaterial); glBindBuffer(GL_UNIFORM_BUFFER, UBOBoxMaterial); glBufferData(GL_UNIFORM_BUFFER, boxMaterial.getStructSize(), &boxMaterial, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } //------------------------------------------------------------------------------------------ void Renderer::initTexture() { //////////////////////////////////////////////////////////////////////////////// // environment texture QMap<EnvironmentTexture, QString> envTexture2StrMap; envTexture2StrMap[SKY1] = "sky1"; envTexture2StrMap[SKY2] = "sky2"; envTexture2StrMap[SKY3] = "sky3"; TRUE_OR_DIE(envTexture2StrMap.size() == (NUM_ENVIRONMENT_TEXTURES - 1), "Ohh, you forget to initialize some environment texture..."); for(int i = 1; i < NUM_ENVIRONMENT_TEXTURES; ++i) { EnvironmentTexture tex = static_cast<EnvironmentTexture>(i); QString posXFile = QString("textures/%1/posx.png").arg(envTexture2StrMap[tex]); TRUE_OR_DIE(QFile::exists(posXFile), "Cannot load texture from file."); QString negXFile = QString("textures/%1/negx.png").arg(envTexture2StrMap[tex]); TRUE_OR_DIE(QFile::exists(negXFile), "Cannot load texture from file."); QString posYFile = QString("textures/%1/posy.png").arg(envTexture2StrMap[tex]); TRUE_OR_DIE(QFile::exists(posYFile), "Cannot load texture from file."); QString negYFile = QString("textures/%1/negy.png").arg(envTexture2StrMap[tex]); TRUE_OR_DIE(QFile::exists(negYFile), "Cannot load texture from file."); QString posZFile = QString("textures/%1/posz.png").arg(envTexture2StrMap[tex]); TRUE_OR_DIE(QFile::exists(posZFile), "Cannot load texture from file."); QString negZFile = QString("textures/%1/negz.png").arg(envTexture2StrMap[tex]); TRUE_OR_DIE(QFile::exists(negZFile), "Cannot load texture from file."); QImage posXTex = QImage(posXFile).convertToFormat(QImage::Format_RGBA8888); QImage negXTex = QImage(negXFile).convertToFormat(QImage::Format_RGBA8888); QImage posYTex = QImage(posYFile).convertToFormat(QImage::Format_RGBA8888); QImage negYTex = QImage(negYFile).convertToFormat(QImage::Format_RGBA8888); QImage posZTex = QImage(posZFile).convertToFormat(QImage::Format_RGBA8888); QImage negZTex = QImage(negZFile).convertToFormat(QImage::Format_RGBA8888); cubeMapEnvTexture[i] = new QOpenGLTexture(QOpenGLTexture::TargetCubeMap); cubeMapEnvTexture[i]->create(); cubeMapEnvTexture[i]->setSize(posXTex.width(), posXTex.height()); cubeMapEnvTexture[i]->setFormat(QOpenGLTexture::RGBA8_UNorm); cubeMapEnvTexture[i]->allocateStorage(); cubeMapEnvTexture[i]->setData(0, 0, QOpenGLTexture::CubeMapPositiveX, QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, posXTex.constBits()); cubeMapEnvTexture[i]->setData(0, 0, QOpenGLTexture::CubeMapNegativeX, QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, negXTex.constBits()); cubeMapEnvTexture[i]->setData(0, 0, QOpenGLTexture::CubeMapPositiveY, QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, posYTex.constBits()); cubeMapEnvTexture[i]->setData(0, 0, QOpenGLTexture::CubeMapNegativeY, QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, negYTex.constBits()); cubeMapEnvTexture[i]->setData(0, 0, QOpenGLTexture::CubeMapPositiveZ, QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, posZTex.constBits()); cubeMapEnvTexture[i]->setData(0, 0, QOpenGLTexture::CubeMapNegativeZ, QOpenGLTexture::RGBA, QOpenGLTexture::UInt8, negZTex.constBits()); cubeMapEnvTexture[i]->setWrapMode(QOpenGLTexture::DirectionS, QOpenGLTexture::ClampToEdge); cubeMapEnvTexture[i]->setWrapMode(QOpenGLTexture::DirectionT, QOpenGLTexture::ClampToEdge); cubeMapEnvTexture[i]->setMinificationFilter(QOpenGLTexture::LinearMipMapLinear); cubeMapEnvTexture[i]->setMagnificationFilter(QOpenGLTexture::LinearMipMapLinear); } if(QOpenGLContext::currentContext()->hasExtension("GL_ARB_seamless_cube_map")) { qDebug() << "GL_ARB_seamless_cube_map: enabled"; glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); } else { // qDebug() << "GL_ARB_seamless_cube_map: disabled"; glDisable(GL_TEXTURE_CUBE_MAP_SEAMLESS); } //////////////////////////////////////////////////////////////////////////////// // floor texture QMap<FloorTexture, QString> floorTexture2StrMap; floorTexture2StrMap[CHECKERBOARD1] = "checkerboard1.png"; floorTexture2StrMap[CHECKERBOARD2] = "checkerboard2.png"; floorTexture2StrMap[STONE1] = "stone1.png"; floorTexture2StrMap[STONE2] = "stone2.png"; floorTexture2StrMap[WOOD1] = "wood1.png"; floorTexture2StrMap[WOOD2] = "wood2.png"; TRUE_OR_DIE(floorTexture2StrMap.size() == (NUM_FLOOR_TEXTURES - 1), "Ohh, you forget to initialize some floor texture..."); for(int i = 1; i < NUM_FLOOR_TEXTURES; ++i) { FloorTexture tex = static_cast<FloorTexture>(i); QString texFile = QString("textures/%1").arg(floorTexture2StrMap[tex]); TRUE_OR_DIE(QFile::exists(texFile), "Cannot load texture from file."); floorTextures[tex] = new QOpenGLTexture(QImage(texFile).mirrored()); floorTextures[tex]->setMinificationFilter(QOpenGLTexture::LinearMipMapLinear); floorTextures[tex]->setMagnificationFilter(QOpenGLTexture::LinearMipMapLinear); floorTextures[tex]->setWrapMode(QOpenGLTexture::Repeat); } } //------------------------------------------------------------------------------------------ void Renderer::initSceneMemory() { initBackgroundMemory(); initGroundMemory(); initBoxMemory(); initLightObjectMemory(); //initParticlesMemory(); } //------------------------------------------------------------------------------------------ void Renderer::initBackgroundMemory() { if(!cubeObject) { cubeObject = new UnitCube; } if(vboBackground.isCreated()) { vboBackground.destroy(); } if(iboBackground.isCreated()) { iboBackground.destroy(); } vboBackground.create(); vboBackground.bind(); //////////////////////////////////////////////////////////////////////////////// // init memory for background cube vboBackground.create(); vboBackground.bind(); vboBackground.allocate(cubeObject->getVertexOffset()); vboBackground.write(0, cubeObject->getVertices(), cubeObject->getVertexOffset()); vboBackground.release(); // indices iboBackground.create(); iboBackground.bind(); iboBackground.allocate(cubeObject->getIndices(), cubeObject->getIndexOffset()); iboBackground.release(); } //------------------------------------------------------------------------------------------ void Renderer::initGroundMemory() { if(!planeObject) { planeObject = new UnitPlane; } if(vboGround.isCreated()) { vboGround.destroy(); } if(iboGround.isCreated()) { iboGround.destroy(); } //////////////////////////////////////////////////////////////////////////////// // init memory for billboard object vboGround.create(); vboGround.bind(); vboGround.allocate(2 * planeObject->getVertexOffset() + planeObject->getTexCoordOffset()); vboGround.write(0, planeObject->getVertices(), planeObject->getVertexOffset()); vboGround.write(planeObject->getVertexOffset(), planeObject->getNormals(), planeObject->getVertexOffset()); vboGround.write(2 * planeObject->getVertexOffset(), planeObject->getTexureCoordinates(GROUND_PLANE_SIZE), planeObject->getTexCoordOffset()); vboGround.release(); // indices iboGround.create(); iboGround.bind(); iboGround.allocate(planeObject->getIndices(), planeObject->getIndexOffset()); iboGround.release(); } //------------------------------------------------------------------------------------------ void Renderer::initBoxMemory() { if(!cubeObject) { cubeObject = new UnitCube; } if(vboBox.isCreated()) { vboBox.destroy(); } if(iboBox.isCreated()) { iboBox.destroy(); } //////////////////////////////////////////////////////////////////////////////// // init memory for cube vboBox.create(); vboBox.bind(); vboBox.allocate(2 * cubeObject->getVertexOffset() + cubeObject->getTexCoordOffset()); vboBox.write(0, cubeObject->getVertices(), cubeObject->getVertexOffset()); vboBox.write(cubeObject->getVertexOffset(), cubeObject->getNormals(), cubeObject->getVertexOffset()); vboBox.write(2 * cubeObject->getVertexOffset(), cubeObject->getTexureCoordinates(1.0f), cubeObject->getTexCoordOffset()); vboBox.release(); // indices iboBox.create(); iboBox.bind(); iboBox.allocate(cubeObject->getLineIndices(), cubeObject->getLineIndexOffset()); iboBox.release(); } //------------------------------------------------------------------------------------------ void Renderer::initLightObjectMemory() { if(vboLight.isCreated()) { vboLight.destroy(); } //////////////////////////////////////////////////////////////////////////////// // init memory for cube vboLight.create(); vboLight.bind(); vboLight.allocate(3 * sizeof(GLfloat)); QVector3D lightPos(DEFAULT_LIGHT_DIRECTION); vboLight.write(0, &lightPos, 3 * sizeof(GLfloat)); vboLight.release(); } //------------------------------------------------------------------------------------------ void Renderer::initParticlesRandomColors() { //////////////////////////////////////////////////////////////////////////////// // init memory for random color srand(15646); if(particleRandomColors) { delete[] particleRandomColors; } particleRandomColors = new GLREAL[num_particles_ * 3]; for(int i = 0; i < num_particles_; ++i) { (particleRandomColors)[i * 3 + 0] = (GLREAL) (rand() / (GLREAL) RAND_MAX); (particleRandomColors)[i * 3 + 1] = (GLREAL) (rand() / (GLREAL) RAND_MAX); (particleRandomColors)[i * 3 + 2] = (GLREAL) (rand() / (GLREAL) RAND_MAX); } } //------------------------------------------------------------------------------------------ void Renderer::initParticlesRampColors() { //////////////////////////////////////////////////////////////////////////////// // init memory for ramp color if(particleRampColors) { delete[] particleRampColors; } particleRampColors = new GLREAL[num_particles_ * 3]; float t; for (int i = 0; i < num_pd_particles_; ++i) { t = (float)i / (float) num_pd_particles_; colorRamp(t, &(particleRampColors)[i * 3]); } for (int i = 0; i < num_sph_particles_; ++i) { t = (float)i / (float) num_sph_particles_; colorRamp(t, &(particleRampColors)[(i + num_pd_particles_) * 3]); } } //------------------------------------------------------------------------------------------ void Renderer::initVertexArrayObjects() { initBackgroundVAO(); initGroundVAO(); initBoxVAO(); initLightVAO(); // initParticlesVAO(PROGRAM_POINT_SPHERE_VIEW); } //------------------------------------------------------------------------------------------ void Renderer::initBackgroundVAO() { if(vaoBackground.isCreated()) { vaoBackground.destroy(); } QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_BACKGROUND]; vaoBackground.create(); vaoBackground.bind(); vboBackground.bind(); program->enableAttributeArray(attrVertex[PROGRAM_RENDER_BACKGROUND]); program->setAttributeBuffer(attrVertex[PROGRAM_RENDER_BACKGROUND], GL_FLOAT, 0, 3); iboBackground.bind(); // release vao before vbo and ibo vaoBackground.release(); vboBackground.release(); iboBackground.release(); } //------------------------------------------------------------------------------------------ void Renderer::initGroundVAO() { if(vaoGround.isCreated()) { vaoGround.destroy(); } QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_GROUND]; vaoGround.create(); vaoGround.bind(); vboGround.bind(); program->enableAttributeArray(attrVertex[PROGRAM_RENDER_GROUND]); program->setAttributeBuffer(attrVertex[PROGRAM_RENDER_GROUND], GL_FLOAT, 0, 3); program->enableAttributeArray(attrNormal[PROGRAM_RENDER_GROUND]); program->setAttributeBuffer(attrNormal[PROGRAM_RENDER_GROUND], GL_FLOAT, planeObject->getVertexOffset(), 3); program->enableAttributeArray(attrTexCoord[PROGRAM_RENDER_GROUND]); program->setAttributeBuffer(attrTexCoord[PROGRAM_RENDER_GROUND], GL_FLOAT, 2 * planeObject->getVertexOffset(), 2); iboGround.bind(); // release vao before vbo and ibo vaoGround.release(); vboGround.release(); iboGround.release(); } //------------------------------------------------------------------------------------------ void Renderer::initBoxVAO() { if(vaoBox.isCreated()) { vaoBox.destroy(); } QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_BOX]; vaoBox.create(); vaoBox.bind(); vboBox.bind(); program->enableAttributeArray(attrVertex[PROGRAM_RENDER_BOX]); program->setAttributeBuffer(attrVertex[PROGRAM_RENDER_BOX], GL_FLOAT, 0, 3); program->enableAttributeArray(attrNormal[PROGRAM_RENDER_BOX]); program->setAttributeBuffer(attrNormal[PROGRAM_RENDER_BOX], GL_FLOAT, cubeObject->getVertexOffset(), 3); program->enableAttributeArray(attrTexCoord[PROGRAM_RENDER_BOX]); program->setAttributeBuffer(attrTexCoord[PROGRAM_RENDER_BOX], GL_FLOAT, 2 * cubeObject->getVertexOffset(), 2); iboBox.bind(); // release vao before vbo and ibo vaoBox.release(); vboBox.release(); iboBox.release(); } //------------------------------------------------------------------------------------------ void Renderer::initLightVAO() { if(vaoLight.isCreated()) { vaoLight.destroy(); } QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_LIGHT]; vaoLight.create(); vaoLight.bind(); vboLight.bind(); program->enableAttributeArray(attrVertex[PROGRAM_RENDER_LIGHT]); program->setAttributeBuffer(attrVertex[PROGRAM_RENDER_LIGHT], GL_FLOAT, 0, 3); // release vao before vbo and ibo vaoLight.release(); vboLight.release(); } //------------------------------------------------------------------------------------------ void Renderer::initParticlesVAO(GLSLPrograms program_type) { if(vaoParticles.isCreated()) { vaoParticles.destroy(); } QOpenGLShaderProgram* program = glslPrograms[program_type]; vaoParticles.create(); vaoParticles.bind(); vboParticles.bind(); program->enableAttributeArray(attrVertex[program_type]); program->setAttributeBuffer(attrVertex[program_type], GL_REAL, 0, 4); program->enableAttributeArray(attrColor[program_type]); program->setAttributeBuffer(attrColor[program_type], GL_REAL, num_particles_ * sizeof(GLREAL) * 4, 3); program->enableAttributeArray(attrActivity[program_type]); // program->setAttributeBuffer(attrActivity[program_type], GL_INT, // num_particles_ * sizeof(GLREAL) * (4 + 3), 1); // use this command to avoid converting int to float glVertexAttribIPointer(attrActivity[program_type], 1, GL_INT, 0, (GLvoid*) ( num_particles_ * sizeof(GLREAL) * (4 + 3))); // release vao before vbo and ibo vaoParticles.release(); vboParticles.release(); } //------------------------------------------------------------------------------------------ void Renderer::initFrameBufferObject() { // if(depthTexture) // { // depthTexture->destroy(); // delete depthTexture; // } depthTexture = new QOpenGLTexture(QOpenGLTexture::Target2D); depthTexture->create(); depthTexture->setSize(DEPTH_TEXTURE_SIZE, DEPTH_TEXTURE_SIZE); depthTexture->setFormat(QOpenGLTexture::D32); depthTexture->allocateStorage(); depthTexture->setMinificationFilter(QOpenGLTexture::Linear); depthTexture->setMagnificationFilter(QOpenGLTexture::Linear); depthTexture->setWrapMode(QOpenGLTexture::DirectionS, QOpenGLTexture::ClampToEdge); depthTexture->setWrapMode(QOpenGLTexture::DirectionT, QOpenGLTexture::ClampToEdge); depthTexture->bind(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); // frame buffer FBODepth = new QOpenGLFramebufferObject(DEPTH_TEXTURE_SIZE, DEPTH_TEXTURE_SIZE); FBODepth->bind(); // glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, // dTex, 0); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthTexture->textureId(), 0); TRUE_OR_DIE(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Framebuffer is imcomplete!"); FBODepth->release(); } //------------------------------------------------------------------------------------------ void Renderer::updateCamera() { zoomCamera(); ///////////////////////////////////////////////////////////////// // flush camera data to uniform buffer viewMatrix.setToIdentity(); viewMatrix.lookAt(cameraPosition_, cameraFocus_, cameraUpDirection_); glBindBuffer(GL_UNIFORM_BUFFER, UBOMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 2 * SIZE_OF_MAT4, SIZE_OF_MAT4, viewMatrix.constData()); glBindBuffer(GL_UNIFORM_BUFFER, 0); } //------------------------------------------------------------------------------------------ void Renderer::translateCamera() { translation_ *= MOVING_INERTIA; if(translation_.lengthSquared() < 1e-4) { return; } QVector3D eyeVector = cameraFocus_ - cameraPosition_; float scale = sqrt(eyeVector.length()) * 0.01f; QVector3D u = cameraUpDirection_; QVector3D v = QVector3D::crossProduct(eyeVector, u); u = QVector3D::crossProduct(v, eyeVector); u.normalize(); v.normalize(); cameraPosition_ -= scale * (translation_.x() * v + translation_.y() * u); cameraFocus_ -= scale * (translation_.x() * v + translation_.y() * u); } //------------------------------------------------------------------------------------------ void Renderer::rotateCamera() { rotation_ *= MOVING_INERTIA; if(rotation_.lengthSquared() < 1e-4) { return; } QVector3D nEyeVector = cameraPosition_ - cameraFocus_ ; QVector3D u = cameraUpDirection_; QVector3D v = QVector3D::crossProduct(-nEyeVector, u); u = QVector3D::crossProduct(v, -nEyeVector); u.normalize(); v.normalize(); float scale = sqrt(nEyeVector.length()) * 0.02f; QQuaternion qRotation = QQuaternion::fromAxisAndAngle(v, rotation_.y() * scale) * QQuaternion::fromAxisAndAngle(u, rotation_.x() * scale) * QQuaternion::fromAxisAndAngle(nEyeVector, rotation_.z() * scale); nEyeVector = qRotation.rotatedVector(nEyeVector); QQuaternion qCamRotation = QQuaternion::fromAxisAndAngle(v, rotation_.y() * scale) * QQuaternion::fromAxisAndAngle(nEyeVector, rotation_.z() * scale); cameraPosition_ = cameraFocus_ + nEyeVector; cameraUpDirection_ = qCamRotation.rotatedVector(cameraUpDirection_); } //------------------------------------------------------------------------------------------ void Renderer::zoomCamera() { zooming_ *= MOVING_INERTIA; if(fabs(zooming_) < 1e-4) { return; } QVector3D nEyeVector = cameraPosition_ - cameraFocus_ ; float len = nEyeVector.length(); nEyeVector.normalize(); len += sqrt(len) * zooming_ * 0.1f; if(len < 0.1f) { len = 0.1f; } cameraPosition_ = len * nEyeVector + cameraFocus_; } //------------------------------------------------------------------------------------------ void Renderer::translateLight() { translation_ *= MOVING_INERTIA; if(translation_.lengthSquared() < 1e-4) { return; } QVector3D eyeVector = cameraFocus_ - cameraPosition_; float scale = sqrt(eyeVector.length()) * 0.05f; QVector3D u(0.0f, 1.0f, 0.0f); QVector3D v = QVector3D::crossProduct(eyeVector, u); u = QVector3D::crossProduct(v, eyeVector); u.normalize(); v.normalize(); QVector3D objectTrans = scale * (translation_.x() * v + translation_.y() * u); QMatrix4x4 translationMatrix; translationMatrix.setToIdentity(); translationMatrix.translate(objectTrans); light.position = translationMatrix * light.position; glBindBuffer(GL_UNIFORM_BUFFER, UBOLight); glBufferData(GL_UNIFORM_BUFFER, light.getStructSize(), &light, GL_STREAM_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } //------------------------------------------------------------------------------------------ void Renderer::renderScene() { glViewport(0, 0, width() * retinaScale, height() * retinaScale); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); renderBackground(); renderGround(); renderLight(); renderBox(); if(!isParticlesReady) { return; } switch(currentParticleViewMode) { case POINTS_VIEW: renderParticlesAsPointSphere(true); break; case SPHERES_VIEW: renderParticlesAsPointSphere(false); break; case OPAQUE_SURFACE_VIEW: renderParticlesAsSurface(0.0); break; case TRANSPARENT_SURFACE_VIEW: renderParticlesAsSurface(0.8); break; } if(enabledImageOutput && !pausedImageOutput) { exportScreenToImage(); } } //------------------------------------------------------------------------------------------ void Renderer::renderBackground() { if(currentEnvironmentTexture == NO_ENVIRONMENT_TEXTURE) { return; } QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_BACKGROUND]; program->bind(); ///////////////////////////////////////////////////////////////// // flush the model matrices glBindBuffer(GL_UNIFORM_BUFFER, UBOMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 0, SIZE_OF_MAT4, backgroundCubeModelMatrix.constData()); glBindBuffer(GL_UNIFORM_BUFFER, 0); ///////////////////////////////////////////////////////////////// // set the uniform program->setUniformValue(uniCameraPosition[PROGRAM_RENDER_BACKGROUND], cameraPosition_); program->setUniformValue(uniObjTexture[PROGRAM_RENDER_BACKGROUND], 0); glUniformBlockBinding(program->programId(), uniMatrices[PROGRAM_RENDER_BACKGROUND], UBOBindingIndex[BINDING_MATRICES]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_MATRICES], UBOMatrices); ///////////////////////////////////////////////////////////////// // render the background vaoBackground.bind(); cubeMapEnvTexture[currentEnvironmentTexture]->bind(0); glDrawElements(GL_TRIANGLES, cubeObject->getNumIndices(), GL_UNSIGNED_SHORT, 0); cubeMapEnvTexture[currentEnvironmentTexture]->release(); vaoBackground.release(); program->release(); } //------------------------------------------------------------------------------------------ void Renderer::renderGround() { if(currentFloorTexture == NO_FLOOR) { return; } glBindBuffer(GL_UNIFORM_BUFFER, UBOMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 0, SIZE_OF_MAT4, groundModelMatrix.constData()); glBufferSubData(GL_UNIFORM_BUFFER, SIZE_OF_MAT4, SIZE_OF_MAT4, groundNormalMatrix.constData()); glBindBuffer(GL_UNIFORM_BUFFER, 0); QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_GROUND]; program->bind(); ///////////////////////////////////////////////////////////////// // set the uniform program->setUniformValue(uniHasObjTexture[PROGRAM_RENDER_GROUND], GL_TRUE); program->setUniformValue(uniObjTexture[PROGRAM_RENDER_GROUND], 0); program->setUniformValue(uniCameraPosition[PROGRAM_RENDER_GROUND], cameraPosition_); glUniformBlockBinding(program->programId(), uniMatrices[PROGRAM_RENDER_GROUND], UBOBindingIndex[BINDING_MATRICES]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_MATRICES], UBOMatrices); glUniformBlockBinding(program->programId(), uniLight[PROGRAM_RENDER_GROUND], UBOBindingIndex[BINDING_LIGHT]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_LIGHT], UBOLight); glUniformBlockBinding(program->programId(), uniMaterial[PROGRAM_RENDER_GROUND], UBOBindingIndex[BINDING_GROUND_MATERIAL]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_GROUND_MATERIAL], UBOGroundMaterial); ///////////////////////////////////////////////////////////////// // render the floor vaoGround.bind(); floorTextures[currentFloorTexture]->bind(0); if(bTextureAnisotropicFiltering) { GLfloat fLargest; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &fLargest); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, fLargest); } else { glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); } glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); floorTextures[currentFloorTexture]->release(); vaoGround.release(); } //------------------------------------------------------------------------------------------ void Renderer::renderLight() { if(!vaoLight.isCreated()) { qDebug() << "vaoLight is not created!"; return; } QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_LIGHT]; program->bind(); ///////////////////////////////////////////////////////////////// // set the uniform glUniformBlockBinding(program->programId(), uniMatrices[PROGRAM_RENDER_LIGHT], UBOBindingIndex[BINDING_MATRICES]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_MATRICES], UBOMatrices); glUniformBlockBinding(program->programId(), uniLight[PROGRAM_RENDER_LIGHT], UBOBindingIndex[BINDING_LIGHT]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_LIGHT], UBOLight); program->setUniformValue("pointDistance", (cameraPosition_ - cameraFocus_).length()); vaoLight.bind(); glEnable (GL_POINT_SPRITE); glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); glEnable (GL_DEPTH_TEST); glDrawArrays(GL_POINTS, 0, 1); glDisable(GL_POINT_SPRITE); vaoLight.release(); program->release(); } //------------------------------------------------------------------------------------------ void Renderer::renderBox() { if(!vaoBox.isCreated()) { qDebug() << "vaoBox is not created!"; return; } ///////////////////////////////////////////////////////////////// // flush the model and normal matrices glBindBuffer(GL_UNIFORM_BUFFER, UBOMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 0, SIZE_OF_MAT4, boxModelMatrix.constData()); glBufferSubData(GL_UNIFORM_BUFFER, SIZE_OF_MAT4, SIZE_OF_MAT4, boxNormalMatrix.constData()); glBindBuffer(GL_UNIFORM_BUFFER, 0); QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_BOX]; program->bind(); ///////////////////////////////////////////////////////////////// // set the uniform program->setUniformValue(uniHasObjTexture[PROGRAM_RENDER_BOX], GL_FALSE); program->setUniformValue("lineView", GL_TRUE); glUniformBlockBinding(program->programId(), uniMatrices[PROGRAM_RENDER_BOX], UBOBindingIndex[BINDING_MATRICES]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_MATRICES], UBOMatrices); glUniformBlockBinding(program->programId(), uniLight[PROGRAM_RENDER_BOX], UBOBindingIndex[BINDING_LIGHT]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_LIGHT], UBOLight); glUniformBlockBinding(program->programId(), uniMaterial[PROGRAM_RENDER_BOX], UBOBindingIndex[BINDING_BOX_MATERIAL]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_BOX_MATERIAL], UBOBoxMaterial); ///////////////////////////////////////////////////////////////// // render the cube vaoBox.bind(); // glDrawElements(GL_LINES, cubeObject->getNumIndices(), GL_UNSIGNED_SHORT, 0); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // glDrawElements(GL_TRIANGLES, cubeObject->getNumIndices(), GL_UNSIGNED_SHORT, 0); glDrawElements(GL_LINES, cubeObject->getNumLineIndices(), GL_UNSIGNED_SHORT, 0); // glDrawElements(GL_LINES, 8*2, GL_UNSIGNED_SHORT, 0); vaoBox.release(); } //------------------------------------------------------------------------------------------ void Renderer::renderParticlesAsPointSphere(bool bPointView) { if(!vaoParticles.isCreated()) { qDebug() << "vaoParticles is not created!"; return; } ///////////////////////////////////////////////////////////////// // flush the model and normal matrices glBindBuffer(GL_UNIFORM_BUFFER, UBOMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 0, SIZE_OF_MAT4, particlesModelMatrix.constData()); glBindBuffer(GL_UNIFORM_BUFFER, 0); QOpenGLShaderProgram* program = glslPrograms[PROGRAM_POINT_SPHERE_VIEW]; program->bind(); ///////////////////////////////////////////////////////////////// // set the uniform glUniformBlockBinding(program->programId(), uniMatrices[PROGRAM_POINT_SPHERE_VIEW], UBOBindingIndex[BINDING_MATRICES]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_MATRICES], UBOMatrices); glUniformBlockBinding(program->programId(), uniLight[PROGRAM_POINT_SPHERE_VIEW], UBOBindingIndex[BINDING_LIGHT]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_LIGHT], UBOLight); // qDebug() << bHideInvisibleParticles; program->setUniformValue("pointView", bPointView); program->setUniformValue("hideInvisibleParticles", bHideInvisibleParticles); program->setUniformValue("cameraPosition", cameraPosition_); program->setUniformValue("pointScale", height() / tanf(45 * 0.5f * (float) M_PI / 180.0f)); if(currentParticleColorMode == COLOR_RANDOM || currentParticleColorMode == COLOR_RAMP || currentParticleColorMode == COLOR_DENSITY || currentParticleColorMode == COLOR_STIFFNESS || currentParticleColorMode == COLOR_ACTIVITY) { program->setUniformValue("hasVertexColor", GL_TRUE); } else { program->setUniformValue("hasVertexColor", GL_FALSE); } vaoParticles.bind(); glEnable (GL_POINT_SPRITE); glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); glEnable (GL_DEPTH_TEST); glUniformBlockBinding(program->programId(), uniMaterial[PROGRAM_POINT_SPHERE_VIEW], UBOBindingIndex[BINDING_POINT_SPHERE_PD_MATERIAL]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_POINT_SPHERE_PD_MATERIAL], UBOPointSpherePDMaterial); program->setUniformValue("pointRadius", pd_particle_radius_); glDrawArrays(GL_POINTS, 0, num_pd_particles_); glUniformBlockBinding(program->programId(), uniMaterial[PROGRAM_POINT_SPHERE_VIEW], UBOBindingIndex[BINDING_POINT_SPHERE_SPH_MATERIAL]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_POINT_SPHERE_SPH_MATERIAL], UBOPointSphereSPHMaterial); program->setUniformValue("pointRadius", sph_particle_radius_); glDrawArrays(GL_POINTS, num_pd_particles_, num_sph_particles_); glDisable(GL_POINT_SPRITE); vaoParticles.release(); program->release(); } //------------------------------------------------------------------------------------------ void Renderer::renderParticlesAsSurface(float transparency) { if(!vaoParticles.isCreated()) { qDebug() << "vaoParticles is not created!"; return; } renderParticlesToDepthBuffer(); // render surface makeCurrent(); glViewport(0, 0, width() * retinaScale, height() * retinaScale); } //------------------------------------------------------------------------------------------ void Renderer::renderParticlesToDepthBuffer() { // FBODepth->bind(); // glViewport(0, 0, DEPTH_TEXTURE_SIZE, DEPTH_TEXTURE_SIZE); // glDrawBuffer(GL_NONE); glClearDepth(1.0); glClear(GL_DEPTH_BUFFER_BIT); glBindBuffer(GL_UNIFORM_BUFFER, UBOMatrices); glBufferSubData(GL_UNIFORM_BUFFER, 0, SIZE_OF_MAT4, particlesModelMatrix.constData()); glBindBuffer(GL_UNIFORM_BUFFER, 0); QOpenGLShaderProgram* program = glslPrograms[PROGRAM_RENDER_DEPTH_BUFFER]; program->bind(); glUniformBlockBinding(program->programId(), uniMatrices[PROGRAM_RENDER_DEPTH_BUFFER], UBOBindingIndex[BINDING_MATRICES]); glBindBufferBase(GL_UNIFORM_BUFFER, UBOBindingIndex[BINDING_MATRICES], UBOMatrices); // program->setUniformValue("cameraPosition", cameraPosition); program->setUniformValue("pointScale", height() / tanf(45 * 0.5f * (float) M_PI / 180.0f)); vaoParticles.bind(); glEnable (GL_POINT_SPRITE); glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); glEnable (GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); program->setUniformValue("pointRadius", pd_particle_radius_); glDrawArrays(GL_POINTS, 0, num_pd_particles_); program->setUniformValue("pointRadius", sph_particle_radius_); glDrawArrays(GL_POINTS, num_pd_particles_, num_sph_particles_); glDisable(GL_POINT_SPRITE); vaoParticles.release(); program->release(); FBODepth->release(); } //------------------------------------------------------------------------------------------ void Renderer::exportScreenToImage() { glReadPixels(0, 0, width(), height(), GL_RGBA, GL_UNSIGNED_BYTE, outputImage->bits()); outputImage->mirrored().save(QString(imageOutputPath + "/frame.%1.png").arg( current_frame_)); qDebug() << "Saved image: " << current_frame_; } //------------------------------------------------------------------------------------------
33.560582
134
0.57146
[ "render", "object", "model" ]
eb29c5f17d320d65d0799d3f5a6e5913eb411640
5,552
hpp
C++
cadical/src/heap.hpp
CInet/CInet-Alien-CaDiCaL
809aca7088ac8b3af61e5b954c5365230ec1010b
[ "Artistic-2.0" ]
1
2020-08-25T11:54:29.000Z
2020-08-25T11:54:29.000Z
cadical/src/heap.hpp
CInet/CInet-Alien-CaDiCaL
809aca7088ac8b3af61e5b954c5365230ec1010b
[ "Artistic-2.0" ]
null
null
null
cadical/src/heap.hpp
CInet/CInet-Alien-CaDiCaL
809aca7088ac8b3af61e5b954c5365230ec1010b
[ "Artistic-2.0" ]
2
2020-08-25T11:54:37.000Z
2020-12-16T10:01:49.000Z
#ifndef _heap_hpp_INCLUDED #define _heap_hpp_INCLUDED #include "util.hpp" // Alphabetically after 'heap.hpp'. namespace CaDiCaL { using namespace std; // This is a priority queue with updates for unsigned integers implemented // as binary heap. We need to map integer elements added (through // 'push_back') to positions on the binary heap in 'array'. This map is // stored in the 'pos' array. This approach is really wasteful (at least in // terms of memory) if only few and a sparse set of integers is added. So // it should not be used in this situation. A generic priority queue would // implement the mapping externally provided by another template parameter. // Since we use 'UINT_MAX' as 'not contained' flag, we can only have // 'UINT_MAX - 1' elements in the heap. const unsigned invalid_heap_position = UINT_MAX; template<class C> class heap { vector<unsigned> array; // actual binary heap vector<unsigned> pos; // positions of elements in array C less; // less-than for elements // Map an element to its position entry in the 'pos' map. // unsigned & index (unsigned e) { assert (e >= 0); while ((size_t) e >= pos.size ()) pos.push_back (invalid_heap_position); unsigned & res = pos[e]; assert (res == invalid_heap_position || (size_t) res < array.size ()); return res; } bool has_parent (unsigned e) { return index (e) > 0; } bool has_left (unsigned e) { return (size_t) 2*index (e) + 1 < size (); } bool has_right (unsigned e) { return (size_t) 2*index (e) + 2 < size (); } unsigned parent (unsigned e) { assert(has_parent (e)); return array[(index(e)-1)/2]; } unsigned left (unsigned e) { assert(has_left (e)); return array[2*index(e)+1]; } unsigned right (unsigned e) { assert(has_right (e)); return array[2*index(e)+2]; } // Exchange elements 'a' and 'b' in 'array' and fix their positions. // void exchange (unsigned a, unsigned b) { unsigned & i = index (a), & j = index (b); swap (array[i], array[j]); swap (i, j); } // Bubble up an element as far as necessary. // void up (unsigned e) { unsigned p; while (has_parent (e) && less ((p = parent (e)), e)) exchange (p, e); } // Bubble down an element as far as necessary. // void down (unsigned e) { while (has_left (e)) { unsigned c = left (e); if (has_right (e)) { unsigned r = right (e); if (less (c, r)) c = r; } if (!less (e, c)) break; exchange (e, c); } } // Very expensive checker for the main 'heap' invariant. Can be enabled // to find violations of antisymmetry in the client implementation of // 'less' and as well of course bugs in this heap implementation. It // should be enabled during testing applications of the heap. // void check () { #if 0 // EXPENSIVE HEAP CHECKING IF ENABLED #warning "expensive checking in heap enabled" assert (array.size () <= invalid_heap_position); for (size_t i = 0; i < array.size (); i++) { size_t l = 2*i + 1, r = 2*i + 2; if (l < array.size ()) assert (!less (array[i], array[l])); if (r < array.size ()) assert (!less (array[i], array[r])); assert (array[i] >= 0); { assert ((size_t) array[i] < pos.size ()); assert (i == (size_t) pos[array[i]]); } } for (size_t i = 0; i < pos.size (); i++) { if (pos[i] == invalid_heap_position) continue; assert (pos[i] < array.size ()); assert (array[pos[i]] == (unsigned) i); } #endif } public: heap (const C & c) : less (c) { } // Number of elements in the heap. // size_t size () const { return array.size (); } // Check if no more elements are in the heap. // bool empty () const { return array.empty (); } // Check whether 'e' is already in the heap. // bool contains (unsigned e) const { assert (e >= 0); if ((size_t) e >= pos.size ()) return false; return pos[e] != invalid_heap_position; } // Add a new (not contained) element 'e' to the heap. // void push_back (unsigned e) { assert (!contains (e)); size_t i = array.size (); assert (i < (size_t) invalid_heap_position); array.push_back (e); index (e) = (unsigned) i; up (e); down (e); check (); } // Returns the maximum element in the heap. // unsigned front () const { assert (!empty ()); return array[0]; } // Removes the maximum element in the heap. // unsigned pop_front () { assert (!empty ()); unsigned res = array[0], last = array.back (); if (size () > 1) exchange (res, last); index (res) = invalid_heap_position; array.pop_back (); if (size () > 1) down (last); check (); return res; } // Notify the heap, that evaluation of 'less' has changed for 'e'. // void update (unsigned e) { assert (contains (e)); up (e); down (e); check (); } void clear () { array.clear (); pos.clear (); } void erase () { erase_vector (array); erase_vector (pos); } void shrink () { shrink_vector (array); shrink_vector (pos); } // Standard iterators 'inherited' from 'vector'. // typedef typename vector<unsigned>::iterator iterator; typedef typename vector<unsigned>::const_iterator const_iterator; iterator begin () { return array.begin (); } iterator end () { return array.end (); } const_iterator begin () const { return array.begin (); } const_iterator end () const { return array.end (); } }; } #endif
27.621891
77
0.606448
[ "vector" ]
eb32b7780eee06232e3bb2ca2a171a0ea4821539
60,255
cpp
C++
MInteraction/SimulXYGraph.cpp
vanch3d/DEMIST
f49e3409cf5eca8df6b03f1a1bbc0f9f4ca44521
[ "MIT" ]
null
null
null
MInteraction/SimulXYGraph.cpp
vanch3d/DEMIST
f49e3409cf5eca8df6b03f1a1bbc0f9f4ca44521
[ "MIT" ]
null
null
null
MInteraction/SimulXYGraph.cpp
vanch3d/DEMIST
f49e3409cf5eca8df6b03f1a1bbc0f9f4ca44521
[ "MIT" ]
1
2021-01-11T09:52:21.000Z
2021-01-11T09:52:21.000Z
// SimulXYGraph.cpp : implementation file // #include "stdafx.h" #include "simul.h" #include "LearnerTrace.h" #include "SimulDoc.h" #include "SimulXYGraph.h" #include <MInstruction\LearningUnit.h> #include <MSimulation\Model.h> #include "SelectParamDlg.h" #include <MInteraction\Format.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define DEMO_MAX_GRAPHS 16 COLORREF DefaultGraphColors[DEMO_MAX_GRAPHS] = {RGB(128, 0, 255), RGB(64, 128, 128), RGB(0, 0, 255), RGB(255, 255, 0), RGB(0, 255, 255), 32768, 128, 8388736, 8421440, 12615808, 8421504, 33023, 16711935, 12632256, 32896, RGB(0, 0, 0)}; ///////////////////////////////////////////////////////////////////////////// // CViewPhasePlot IMPLEMENT_DYNCREATE(CViewPhasePlot, CScrollView) CViewPhasePlot::CViewPhasePlot() { m_nTransData = -1; // m_nCurrTTask=0; m_pER = NULL; // m_GraphCount = 0; m_pSelData = NULL; m_pHypData = NULL; m_pHypData2 = m_pHypData3 = NULL; m_bCanEdit = FALSE; m_nMaxTime = 0; m_nCurrTime = 0; /* x[0] = 5; y[0] = 70; x[1] = 30; y[1] = 30; x[2] = 40; y[2] = 4; x[3] = 70; y[3] = 50; x[4] = 80; y[4] = 80;*/ // init // m_fXScale = 1.0f; // zooming scale // m_fYScale = 1.0f; // m_fDelta = 1.2f; m_nMAPMode = MM_TEXT; m_nScale = 0; m_bCanDraw = TRUE; m_bMemDraw = TRUE; m_bTitle = TRUE; m_bLegend = TRUE; m_bBoundary = FALSE; m_bGrid = TRUE; m_bStabPt = TRUE; m_bCurrT = TRUE; m_nXData = m_nYData = -1; SetScaleType(); //m_pGraph = &m_XLinearYLog; m_nBkColor = m_pGraph->GetBackColor(); m_pGraph->SetRange(0, 0, 100, 100); m_pGraph->EnableMemoryDraw(m_bMemDraw); m_pGraph->EnableLegend(m_bLegend); m_pGraph->SetBackColor(m_nBkColor); m_strTitle = _T("Phase Plot"); } CViewPhasePlot::~CViewPhasePlot() { CTrace::T_CLOSE(GetParentFrame()); for (int i=0;i<m_cPPData.GetSize();i++) { CPhasePlotData* pData = m_cPPData.GetAt(i); if (!pData) continue; delete pData; } m_cPPData.RemoveAll(); for (i=0;i<m_cUserData.GetSize();i++) { CPhasePlotData* pData = m_cUserData.GetAt(i); if (!pData) continue; delete pData; } m_cUserData.RemoveAll(); for (i=0;i<m_cIsocline.GetSize();i++) { CPhasePlotData* pData = m_cIsocline.GetAt(i); if (!pData) continue; delete pData; } m_cIsocline.RemoveAll(); } CFormatPhasePlot* CViewPhasePlot::GetFormats() { CFormatPhasePlot* pDlg = NULL; if (!m_pER) return pDlg; int nbF = m_pER->m_cFormatSet.GetSize(); if (nbF) { CFormat *pPage = m_pER->m_cFormatSet.GetAt(0); pDlg = DYNAMIC_DOWNCAST(CFormatPhasePlot,pPage); } return pDlg; } int CViewPhasePlot::GetTranslation() { int nTrans = 0; CFormatTranslation* pDlg = NULL; if (!m_pER) return nTrans; int nbF = m_pER->m_cFormatSet.GetSize(); if (nbF>=2) { CFormat *pPage = m_pER->m_cFormatSet.GetAt(1); pDlg = DYNAMIC_DOWNCAST(CFormatTranslation,pPage); } if (pDlg) nTrans = pDlg->m_nTranslation; return nTrans; } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a DOC_UPDATE_VIEWCONTENT notification. /// /// Called just before the view is displayed for the first time, this function just /// assignes to the data member m_pER a pointer to the Learning Unit (see CLearningUnit) /// associated with that view. ///////////////////////////////////////////////////////////////////////////// LRESULT CViewPhasePlot::OnUpdateInitContent(WPARAM wp, LPARAM lp) { m_pER = (CExternRepUnit*)lp; return 0; } LRESULT CViewPhasePlot::OnActivateER(WPARAM wp, LPARAM lp) { static BOOL bFirst = TRUE; if (!bFirst) CTrace::T_SWITCH(this, (CWnd*)wp); bFirst = FALSE; return 0; } BEGIN_MESSAGE_MAP(CViewPhasePlot, CScrollView) //{{AFX_MSG_MAP(CViewPhasePlot) ON_WM_CREATE() ON_WM_SIZE() ON_WM_ERASEBKGND() ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview) ON_COMMAND(ID_SELECTDATA, OnSelectData) ON_WM_DESTROY() ON_WM_LBUTTONDBLCLK() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_COMMAND(ID_EDIT_COPY, OnEditCopy) //}}AFX_MSG_MAP ON_MESSAGE(DOC_UPDATE_VIEWCONTENT, OnUpdateInitContent) ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) //ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) //ON_COMMAND_RANGE(ID_TRANS_INDEPENDENT,ID_TRANS_DYNALINKED,OnTranslationTasks) ON_UPDATE_COMMAND_UI_RANGE(ID_TRANS_INDEPENDENT,ID_TRANS_DYNALINKED,OnUpdateTransTasks) ON_COMMAND_RANGE(ID_XYGRAPH_SCALETYPE_LINEAR,ID_XYGRAPH_SCALETYPE_XYLOG,OnSetScaleType) ON_UPDATE_COMMAND_UI_RANGE(ID_XYGRAPH_SCALETYPE_LINEAR,ID_XYGRAPH_SCALETYPE_XYLOG,OnUpdateScaleType) ON_MESSAGE(TRACE_VIEW_ACTIVATE, OnActivateER) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CViewPhasePlot diagnostics #ifdef _DEBUG void CViewPhasePlot::AssertValid() const { CScrollView::AssertValid(); } void CViewPhasePlot::Dump(CDumpContext& dc) const { CScrollView::Dump(dc); } CSimulDoc* CViewPhasePlot::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSimulDoc))); return (CSimulDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CViewGraph printing BOOL CViewPhasePlot::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CViewPhasePlot::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CViewPhasePlot::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } void CViewPhasePlot::OnPrint(CDC* pDC, CPrintInfo* pInfo) { // TODO: Add your specialized code here and/or call the base class // Get a DC for the current window (will be a screen DC for print previewing) /* CDC *pCurrentDC = GetDC(); // will have dimensions of the client area if (!pCurrentDC) return; CSize PaperPixelsPerInch(pDC->GetDeviceCaps(LOGPIXELSX), pDC->GetDeviceCaps(LOGPIXELSY)); CSize ScreenPixelsPerInch(pCurrentDC->GetDeviceCaps(LOGPIXELSX), pCurrentDC->GetDeviceCaps(LOGPIXELSY)); CSize m_CharSize = pDC->GetTextExtent(_T("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSATUVWXYZ"),52); m_CharSize.cx /= 52; // Get the page sizes (physical and logical) CSize m_PaperSize = CSize(pDC->GetDeviceCaps(HORZRES), pDC->GetDeviceCaps(VERTRES)); CSize m_LogicalPageSize; m_LogicalPageSize.cx = ScreenPixelsPerInch.cx * m_PaperSize.cx / PaperPixelsPerInch.cx * 3 / 2; m_LogicalPageSize.cy = ScreenPixelsPerInch.cy * m_PaperSize.cy / PaperPixelsPerInch.cy * 3 / 2; pDC->SetMapMode(MM_ISOTROPIC); //pDC->SetWindowExt(CSize(1200,600));//m_DocSize); pDC->SetWindowExt(m_LogicalPageSize); pDC->SetViewportExt(pInfo->m_rectDraw.Width(),pInfo->m_rectDraw.Height()); */ CScrollView::OnPrint(pDC, pInfo); } ///////////////////////////////////////////////////////////////////////////// // CViewPhasePlot drawing BOOL CViewPhasePlot::OnEraseBkgnd(CDC* pDC) { // TODO: Add your message handler code here and/or call default return FALSE; } void CViewPhasePlot::OnDraw(CDC* pDC) { CDocument* pDoc = GetDocument(); // TODO: add draw code here CRect rect; if (pDC->IsPrinting()) { rect.left = rect.top = 0; rect.right = pDC->GetDeviceCaps(HORZRES); rect.bottom = pDC->GetDeviceCaps(VERTRES); m_pGraph->SetPrintScale(pDC->m_hDC, rect); } else { CSize size = GetTotalSize(); rect.left = rect.top = 0; rect.right = size.cx; rect.bottom= size.cy; } m_pGraph->BeginDraw(pDC->m_hDC); DrawFrame(rect, RGB(255, 0, 0), m_strTitle); if (m_bStabPt) { CLearningUnit* pLU = GetDocument()->GetCurrentLU(); int n1=-1; int n2=-1; int n3=-1; int n4=-1; CFormatPhasePlot *pDlg = GetFormats(); if (pDlg) { n1 = pDlg->m_nIsoX0; n2 =pDlg->m_nIsoY0; n3 = pDlg->m_nIsoXN; n4 = pDlg->m_nIsoYN; } if (n1!=-1 || n2 != -1) { for (int k=0;k<m_cPPData.GetSize();k++) { CPhasePlotData *pData = m_cPPData.GetAt(k); if (!pData) continue; CMdData *pp1 = NULL; CMdData *pp2 = NULL; CTPoint<double> pt1[2]; if (n1!=-1 && n2 != -1) { pp1 = pLU->GetDataAt(n1); pp2 = pLU->GetDataAt(n2); pt1[0] = CTPoint<double>(0, pp1->GetAt(0,pData->m_nExpSet)); pt1[1] = CTPoint<double>(pp2->GetAt(0,pData->m_nExpSet),0); } else if (n1!=-1) { pp1 = pLU->GetDataAt(n1); //pp2 = pLU->GetDataAt(n4); pt1[0] = CTPoint<double>(pp1->GetAt(0,pData->m_nExpSet),yRange.x); pt1[1] = CTPoint<double>(pp1->GetAt(0,pData->m_nExpSet),yRange.y); } else { pp2 = pLU->GetDataAt(n2); pt1[0] = CTPoint<double>(xRange.x,pp2->GetAt(0,pData->m_nExpSet)); pt1[1] = CTPoint<double>(xRange.y,pp2->GetAt(0,pData->m_nExpSet)); } /* CMdData *pp1 = pLU->GetDataAt(n1); CMdData *pp2 = pLU->GetDataAt(n2); CTPoint<double> pt1[2]; pt1[0] = CTPoint<double>(0, pp1->GetAt(0,pData->m_nExpSet)); pt1[1] = CTPoint<double>(pp2->GetAt(0,pData->m_nExpSet),0); COLORREF cr1 = pp1->GetDataInfo()->GetColor();*/ COLORREF cr1 = (pp1) ? pp1->GetDataInfo()->GetColor() : pp2->GetDataInfo()->GetColor(); CString mstr1; mstr1.Format(_T("%s isocline"),m_strXPlot); m_pGraph->Lines(pt1, 2, cr1,m_cPPData.GetSize()+2+2,mstr1); } } if (n3!=-1 || n4 != -1) { for (int k=0;k<m_cPPData.GetSize();k++) { CPhasePlotData *pData = m_cPPData.GetAt(k); if (!pData) continue; CMdData *pp1 = NULL; CMdData *pp2 = NULL; CTPoint<double> pt1[2]; if (n3!=-1 && n4 != -1) { pp1 = pLU->GetDataAt(n3); pp2 = pLU->GetDataAt(n4); pt1[0] = CTPoint<double>(0, pp1->GetAt(0,pData->m_nExpSet)); pt1[1] = CTPoint<double>(pp2->GetAt(0,pData->m_nExpSet),0); } else if (n3!=-1) { pp1 = pLU->GetDataAt(n3); //pp2 = pLU->GetDataAt(n4); pt1[0] = CTPoint<double>(pp1->GetAt(0,pData->m_nExpSet),yRange.x); pt1[1] = CTPoint<double>(pp1->GetAt(0,pData->m_nExpSet),yRange.y); } else { pp2 = pLU->GetDataAt(n4); pt1[0] = CTPoint<double>(0,pp2->GetAt(0,pData->m_nExpSet)); pt1[1] = CTPoint<double>(50,pp2->GetAt(0,pData->m_nExpSet)); } COLORREF cr1 = (pp1) ? pp1->GetDataInfo()->GetColor() : pp2->GetDataInfo()->GetColor(); CString mstr1; mstr1.Format(_T("%s isocline"),m_strYPlot); m_pGraph->Lines(pt1, 2, cr1,m_cPPData.GetSize()+2+3,mstr1); } } } // int nCT = GetDocument()->m_currTimer; int nCT = m_nCurrTime; int nRT = GetDocument()->GetRunTime(); if (m_nMaxTime) { int nItem = m_nMaxTime; //nCT+1; if (m_pER) { //nItem = (m_pER->m_nMode) ? m_nMaxTime : nCT+1 ; nItem = nRT+1; } for (int k=0;k<m_cPPData.GetSize();k++) { CPhasePlotData *pData = m_cPPData.GetAt(k); if (!pData) continue; m_pGraph->Lines(pData->m_pXaxis, pData->m_pYaxis, nItem, DefaultGraphColors[k], k+1, pData->m_strName); } } if (m_bCurrT) { CLearningUnit* pLU = GetDocument()->GetCurrentLU(); for (int k=0;k<m_cPPData.GetSize();k++) { CPhasePlotData *pData = m_cPPData.GetAt(k); if (!pData) continue; CMdData *pPrey = pLU->GetDataAt(pData->m_nXData); CMdData *pPred = pLU->GetDataAt(pData->m_nYData); CTPoint<double> ptTime[1]; ptTime[0].x = pData->m_pXaxis[nCT]; ptTime[0].y = pData->m_pYaxis[nCT]; CString mstr; mstr.Format(_T("Time : %d"),nCT); COLORREF mclr = RGB(192, 192,192); if (m_nTransData == -1) mclr = RGB(192, 192,192); else if (pData->m_bSelected==1) mclr = pPrey->GetDataInfo()->GetColor(); else if (pData->m_bSelected==2) mclr = pPred->GetDataInfo()->GetColor(); else if (pData->m_bSelected==3) mclr = DefaultGraphColors[k]; else continue; int nMode = m_pGraph->FCIRCLE; int nSize = 4; if (m_bCanEdit && pData->m_bEditable) //if (m_pSelData == pData && ptTime[0].x == GetDocument()->GetRunTime()) { nMode = m_pGraph->FDIAMOND; nSize = 5; } m_pGraph->Markers(ptTime, 1, mclr,nMode , m_cPPData.GetSize()+2, mstr,nSize); if (pData->m_bSelected) m_pGraph->Markers(ptTime, 1, mclr,nMode , k+1, pData->m_strName,nSize); /* if (m_nTransData == -1) { CTPoint<double> ptTime[1]; ptTime[0].x = pData->m_pXaxis[nCT]; ptTime[0].y = pData->m_pYaxis[nCT]; CString mstr; mstr.Format(_T("Time : %d"),nCT); COLORREF mclr = RGB(192, 192,192); //if (m_nTransData ==k) // mclr = DefaultGraphColors[k]; m_pGraph->Markers(ptTime, 1, mclr, m_pGraph->FCIRCLE, m_cPPData.GetSize()+2, mstr,4); //m_pGraph->Markers(ptTime, 1, DefaultGraphColors[k], m_pGraph->FCIRCLE, k+1, pData->m_strName,4); } else if (pData->m_bSelected) { CTPoint<double> ptTime[1]; ptTime[0].x = pData->m_pXaxis[nCT]; ptTime[0].y = pData->m_pYaxis[nCT]; CString mstr; mstr.Format(_T("Time : %d"),nCT); CMdData *pPrey = pLU->GetDataAt(pData->m_nXData); CMdData *pPred = pLU->GetDataAt(pData->m_nYData); COLORREF mclr = pData->m_clrData; if (pData->m_bSelected==1) mclr = pPrey->GetDataInfo()->GetColor(); else if (pData->m_bSelected==2) mclr = pPred->GetDataInfo()->GetColor(); else mclr = DefaultGraphColors[k]; //if (m_nTransData ==k) // mclr = DefaultGraphColors[k]; m_pGraph->Markers(ptTime, 1, mclr, m_pGraph->FCIRCLE, m_cPPData.GetSize()+2, mstr,4); m_pGraph->Markers(ptTime, 1, mclr, m_pGraph->FCIRCLE, k+1, pData->m_strName,4); }*/ } } for (int i=0;i<m_cUserData.GetSize();i++) { CPhasePlotData* pUserData = m_cUserData.GetAt(i); if (!pUserData) continue; CTPoint<double> ptTime[2]; if (pUserData->m_nXData !=-1) { ptTime[0].x = pUserData->m_pXaxis[0]; ptTime[0].y = yRange.x; ptTime[1].x = pUserData->m_pXaxis[0]; ptTime[1].y = yRange.y; } if (pUserData->m_nYData !=-1) { ptTime[0].y = pUserData->m_pYaxis[0]; ptTime[0].x = xRange.x; ptTime[1].y = pUserData->m_pYaxis[0]; ptTime[1].x = xRange.y; } COLORREF mclr = pUserData->m_clrData; int nMode = m_pGraph->FSQUARE; int nSize = 4; int nwidth= 1; if (m_pHypData && m_pHypData==pUserData) { nwidth= 2; } CString strHyp; strHyp.Format(_T("Hypothesis (T = %d)"),(int)pUserData->m_bSelected); m_pGraph->Markers(ptTime, 1 ,RGB(192,192,192), nMode,m_cPPData.GetSize()+4, strHyp, 0); //m_pGraph->Markers(ptTime, 1, mclr, nMode,m_cPPData.GetSize()+5+i,pUserData->m_strName,nSize); m_pGraph->Lines(ptTime,2, mclr, m_cPPData.GetSize()+5+i, pUserData->m_strName,nwidth,PS_SOLID); } // m_pGraph->MoveTo(CTPoint<double>(2, 2)); // m_pGraph->LineTo(CTPoint<double>(95, 95)); m_pGraph->EndDraw(pDC->m_hDC); } void CViewPhasePlot::DrawFrame(CRect& rect, COLORREF cr, const char* Title) { m_pGraph->RecalcRects(rect); if (m_bBoundary) m_pGraph->DrawBoundary(cr, 2); if (m_bTitle) { CLearningUnit* pLU = GetDocument()->GetCurrentLU(); //int nTT = GetDocument()->m_currTimer; int nTT = m_nCurrTime; if (pLU && m_nMaxTime) { CMdData *pPrey = pLU->GetDataAt(m_nXData); CMdData *pPred = pLU->GetDataAt(m_nYData); //CTPoint<double> ptTime[1]; //ptTime[0].x = x[nTT]; //ptTime[0].y = y[nTT]; CString mstr; COLORREF oldClr = m_pGraph->GetTitleColor(); //mstr.Format(_T("%s : %.4g"),mstr1,ptTime[0].x); m_pGraph->SetTitleColor(pPrey->GetDataInfo()->GetColor()); m_pGraph->XAxisTitle(m_strXPlot); //mstr.Format(_T("%s : %.4g"),mstr2,ptTime[0].y); m_pGraph->SetTitleColor(pPred->GetDataInfo()->GetColor()); m_pGraph->YAxisTitle(m_strYPlot); //m_pGraph->Title(Title); m_pGraph->SetTitleColor(oldClr); } } m_pGraph->Axes(); if (m_bGrid) m_pGraph->Grid(); } ///////////////////////////////////////////////////////////////////////////// // CViewPhasePlot message handlers int CViewPhasePlot::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CScrollView::OnCreate(lpCreateStruct) == -1) return -1; // ****** Add your code below this line ********** // //if (!m_cToolBar.Create( GetParent(),WS_CHILD | WS_VISIBLE | CBRS_TOP,120) || if (!m_cToolBar.CreateEx(GetParent(), TBSTYLE_FLAT | TBSTYLE_TOOLTIPS, WS_CHILD | WS_VISIBLE | CBRS_TOP | /*CBRS_GRIPPER | */CBRS_TOOLTIPS | CBRS_FLYBY | CCS_ADJUSTABLE, CRect(0, 0, 0, 0), 120) || !m_cToolBar.LoadToolBar(IDR_SIMULGRAPH)) { TRACE0("Failed to create toolbar1\n"); return -1; // fail to create } CRect rect; GetClientRect(rect); // m_GraphWnd.Create(_T("Graph Window"), rect, this, 11000); return 0; } void CViewPhasePlot::OnSize(UINT nType, int cx, int cy) { CScrollView::OnSize(nType, cx, cy); // m_GraphWnd.MoveWindow(0, 0, cx, cy); if(cx <= 0 || cy <= 0) return; RecalcSize(); if (m_cToolBar && ::IsWindow(m_cToolBar.m_hWnd)) { UINT tt = ID_TASK_CANCELTASK; UINT nID,nStyle; int nImage; m_cToolBar.GetButtonInfo(2,nID,nStyle,nImage); m_cToolBar.SetButtonInfo(2,nID,TBBS_SEPARATOR,cx-100); } } void CViewPhasePlot::RecalcSize() { CRect rect; CSize sizeTotal; GetClientRect(rect); sizeTotal = rect.Size(); SetScaleToFitSize(sizeTotal); // make it similar to CView if(m_bCanDraw) m_pGraph->RecalcRects(rect); } LRESULT CViewPhasePlot::OnUpdateObjTooltip(WPARAM wp, LPARAM lp) { if (!lp || !wp) { myToolTip.Activate(FALSE); return 0L; } CPhasePlotData *pData = (CPhasePlotData*)wp; CLearningUnit* pLU = GetDocument()->GetCurrentLU(); //CMdData *pObj = pLU->GetDataAt(pData->m_nYData); CString mstr = pData->m_strName;//pObj->GetDataName(FALSE); myToolTip.UpdateTipText(mstr,this); if (!myToolTip.IsWindowVisible()) { CRect mmmm; mmmm.SetRectEmpty(); myToolTip.GetMargin(mmmm); myToolTip.Activate(TRUE); } return 0L; } void CViewPhasePlot::OnInitialUpdate() { if (m_pER) GetParentFrame()->SetWindowText(m_pER->GetName()); CTrace::T_OPEN(GetParentFrame()); myToolTip.Create(this); myToolTip.AddTool(this); myToolTip.SetDelayTime(TTDT_INITIAL,10); myToolTip.SetDelayTime(TTDT_RESHOW,100); CFormatPhasePlot *pDlg = GetFormats(); if (pDlg) { SetScaleType(pDlg->m_nScale); m_bStabPt = pDlg->m_bShowStab; m_bCurrT = pDlg->m_bShowCurrTime; m_bTitle = pDlg->m_bShowLegend; m_bGrid = pDlg->m_bShowAxe; } OnUpdateTimer(); CScrollView::OnInitialUpdate(); CSimulDoc *pDoc = GetDocument(); BOOL bDrawPoints= TRUE; double x_range = pDoc->GetMaxTime()-1; m_nDeltaTime = 1.0; CRect rect; GetClientRect(&rect); CSize sizeTotal = CSize(rect.right-rect.left, rect.bottom-rect.top); SetScaleToFitSize(sizeTotal); // this demo only support MM_TEXT mode ASSERT(m_nMAPMode == MM_TEXT); // CFormatPhasePlot *pDlg = GetFormats(); /* if (pDlg) { m_bStabPt = pDlg->m_bShowStab; m_bCurrT = pDlg->m_bShowCurrTime; m_bTitle = pDlg->m_bShowLegend; m_bGrid = pDlg->m_bShowAxe; }*/ POSITION pos = pDoc->m_cUserInput.GetStartPosition(); while (pos) { CUserOutput pUser; int nb; pDoc->m_cUserInput.GetNextAssoc(pos,nb,pUser); POSITION pos2 = pUser.m_lUserInput.GetStartPosition(); while (pos2) { CUserData pUserData; unsigned long ptime; pUser.m_lUserInput.GetNextAssoc(pos2,ptime,pUserData); if (pUserData.m_nType == BREAKP_TEST) { OnUpdateHypothesis(&pUserData); } } } m_pGraph->EnableLegend(m_bTitle==TRUE); RecalcSize(); // Invalidate(); CWnd *pWnd = GetParent(); CRect mrect; if (pWnd) { pWnd->GetWindowRect(mrect); pWnd->SetWindowPos(NULL,0,0,mrect.Width()-1,mrect.Height(),SWP_NOZORDER|SWP_NOMOVE); } } BOOL CViewPhasePlot::CanEdit() { CSimulDoc *pDoc = GetDocument(); if (!pDoc) return FALSE; int nTrans = GetTranslation(); if (nTrans != TRANS_DYNAL) return FALSE; BOOL bD = pDoc->m_bTaskDone; int nCBP = pDoc->m_nCurrBP; // int nCT = pDoc->GetCurrTime(); int nCT = m_nCurrTime; int nMT = pDoc->GetMaxTime(); int nRT = pDoc->GetRunTime(); CTimerBreakPoint pBP; BOOL bEditable = pDoc->GetCurrentLU()->GetTimerBPAt(nCBP,pBP); if (!bEditable) return FALSE; bEditable = (nCT==nRT && nCT==nCBP) && (pBP.m_nBPType == BREAKP_ACTION/* || pBP.m_nBPType == BREAKP_HYPOT*/) && !bD; return bEditable; } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a DOC_UPDATE_ALLDATA notification. /// /// Response to data update ///////////////////////////////////////////////////////////////////////////// BOOL CViewPhasePlot::OnUpdateData() { CSimulDoc *pDoc = GetDocument(); if (!pDoc) return FALSE; CMdEquation* m_pEqu = pDoc->GetCurrentModel(); if (!m_pEqu) return FALSE; CLearningUnit* pLU = pDoc->GetCurrentLU(); if (!pLU) return FALSE; m_nTransData = -1; m_pSelData = NULL; m_pHypData = NULL; m_pHypData2 = m_pHypData3 = NULL; int nGType; CFormatPhasePlot *pDlg = GetFormats(); if (pDlg) { nGType = pDlg->m_nScale; } m_nMaxTime = 0; //if (pLU->m_simulID < 2) return; for (int kk=0;kk<m_cPPData.GetSize();kk++) { CPhasePlotData* pData = m_cPPData.GetAt(kk); if (!pData) continue; delete pData; } m_cPPData.RemoveAll(); int nbOutC = m_pER->m_cOutputSet.GetSize(); double xMin = 45000000; double yMin = 45000000; double xMax = -45000000; double yMax = -45000000; int nExpSet = pLU->m_cExpSet.GetSize(); int nbPar = m_pEqu->m_cParSet.GetSize(); CMdData *pTime = pLU->GetDataAt(nbPar); if (pTime) { CString m_strXPlot = pTime->GetDataName(pLU->m_bShowAbbrev); double d1 = pTime->GetAt(0,0); double d2 = pTime->GetAt(1,0); m_nDeltaTime = d2-d1; } for (int i=0;i<nbOutC;i+=2) { COutcomes *pCo= m_pER->m_cOutputSet.GetAt(i); if (!pCo) continue; if (m_nXData == -1) m_nXData = pCo->m_nData; COutcomes *pCo2= m_pER->m_cOutputSet.GetAt(i+1); if (!pCo2) continue; if (m_nYData == -1) m_nYData = pCo2->m_nData; if (!pCo->m_nSelected || !pCo2->m_nSelected) continue; if (pCo->m_nExpSet>= nExpSet) continue; if (pCo->m_nExpSet == pCo2->m_nExpSet) { int maxT = pLU->GetMaxTimer(); m_nMaxTime = maxT; CPhasePlotData *pData=new CPhasePlotData(maxT+2); pData->m_nExpSet = pCo->m_nExpSet; pData->m_strName = pLU->m_cExpSet.GetAt(pData->m_nExpSet)->GetName(); pData->m_nXData = m_nXData; pData->m_nYData = m_nYData; m_cPPData.Add(pData); int nb = pLU->GetDataSize(); //int nExpSet = 0; //int nbExpSet = pLU->m_cExpSet.GetSize(); CMdData *pPrey = pLU->GetDataAt(m_nXData); m_strXPlot = pPrey->GetDataName(pLU->m_bShowAbbrev); //m_pGraph->XAxisTitle(mstr); CMdData *pPred = pLU->GetDataAt(m_nYData); m_strYPlot = pPred->GetDataName(pLU->m_bShowAbbrev); //m_pGraph->YAxisTitle(mstr); BOOL bXEdit=FALSE; BOOL bYEdit=FALSE; CModelObj* pObj = pPrey->GetDataInfo(); if (pObj) bXEdit = (pObj->GetIcon() <=2); pObj = pPred->GetDataInfo(); if (pObj) bYEdit = (pObj->GetIcon() <=2); bYEdit*=2; pData->m_bEditable = bXEdit + bYEdit; for (int i=0;i<=maxT;i++) { pData->m_pXaxis[i] = pPrey->GetAt(i,pData->m_nExpSet); pData->m_pYaxis[i] = pPred->GetAt(i,pData->m_nExpSet); //if (nbExpSet >=2) } double nMin,nMax; pPrey->GetMinMax(&nMin,&nMax,pData->m_nExpSet); double nMin1,nMax1; pPred->GetMinMax(&nMin1,&nMax1,pData->m_nExpSet); //CFormatPhasePlot *pDlg = GetFormats(); /* double dx = nMax - nMin; double dy = nMax1 - nMin1; dx = (5.+dx)/5.; int bg = 5*(int)(dx); dy = (5.+dy)/5.; int bg2 = 5*(int)(dy); // dx = dx / 50; // dy = dy / 50; double xlMin = floor(nMin); double ylMin = floor(nMin1); double xlMax = ceil(nMax); double ylMax = ceil(nMax1); bg = (int)((bg-(xlMax-xlMin)) / 2); bg2 = (int)((bg2-(ylMax-ylMin)) / 2); xMin = min(xMin,(xlMin-bg)); yMin = min(yMin,ylMin); xMax = max(xMax,1+xlMax+bg); yMax = max(yMax,ylMax);*/ xMin = min(xMin,nMin); yMin = min(yMin,nMin1); xMax = max(xMax,nMax); yMax = max(yMax,nMax1); if (pDlg) { int n1 = pDlg->m_nIsoX0; int n2 =pDlg->m_nIsoY0; int n3 = pDlg->m_nIsoXN; int n4 = pDlg->m_nIsoYN; if (n1!=-1) { CMdData *pp1 = pLU->GetDataAt(n1); if (pp1) { double dd = pp1->GetAt(0,pData->m_nExpSet); yMax = max(yMax,dd); } } if (n2!=-1) { CMdData *pp1 = pLU->GetDataAt(n2); if (pp1) { double dd = pp1->GetAt(0,pData->m_nExpSet); xMax = max(xMax,dd); } } if (n3!=-1) { CMdData *pp1 = pLU->GetDataAt(n3); if (pp1) { double dd = pp1->GetAt(0,pData->m_nExpSet); yMax = max(yMax,dd); } } if (n4!=-1) { CMdData *pp1 = pLU->GetDataAt(n4); if (pp1) { double dd = pp1->GetAt(0,pData->m_nExpSet); xMax = max(xMax,dd); } } } } } int nXTicks = 8; int nYTicks = 8; if (nGType==1 || nGType==3) { if (xMin<0.1) xMin=0.1; if (xMax<0.1) xMax=0.1; double ddd = log10(xMax); ddd = ceil(ddd); xMax = pow(10.0, ddd); double bbb = log10(xMin); bbb = floor(bbb); xMin = pow(10.0, bbb); } if (nGType==2 || nGType==3) { if (yMin<0.1) yMin=0.1; if (yMax<0.1) yMax=0.1; double ddd = log10(yMax); ddd = ceil(ddd); yMax = pow(10.0, ddd); double bbb = log10(yMin); bbb = floor(bbb); yMin = pow(10.0, bbb); } if (nGType==0 || nGType==2) // X lineare { double range = xMax-xMin; double cc = log10(range); int dec = (int)floor(cc); double mul = pow(10.0, dec); int rrr = (int)(ceil(range / mul) * mul); nXTicks = (int)(rrr / mul); if (nXTicks<=2) nXTicks*=5; if (nXTicks<=5) nXTicks*=2; int nn = (int)(yMin /mul); //xMin = nn * mul; xMin = floor(xMin / mul) * mul; xMax = ceil(xMax / mul) * mul; nXTicks = (int)((xMax-xMin)/mul); if (nXTicks<=2) nXTicks*=5; if (nXTicks<=5) nXTicks*=2; if (!nXTicks) nXTicks = 10; } if (nGType==0 || nGType==1) // Y lineare { double range = yMax-yMin; double cc = log10(range); int dec = (int)floor(cc); double mul = pow(10.0, dec); int rrr = (int)(ceil(range / mul) * mul); nYTicks = (int)(rrr / mul); if (nYTicks<=2) nYTicks*=5; if (nYTicks<=5) nYTicks*=2; int nn = (int)(yMin /mul); //yMin = nn * mul; yMin = floor(yMin / mul) * mul; yMax = ceil(yMax / mul) * mul; nYTicks = (int)((yMax-yMin)/mul); if (nYTicks<=2) nYTicks*=5; if (nYTicks<=5) nYTicks*=2; if (!nYTicks) nYTicks = 10; } if (yMin==yMax) { yMin -= yMin*.1; yMax += yMax*.1; } if (xMin==xMax) { xMin -= xMin*.1; xMax += xMax*.1; } xRange.x = xMin; xRange.y = xMax; yRange.x = yMin; yRange.y = yMax; m_pGraph->SetRange(xMin,yMin, xMax, yMax); m_pGraph->SetRatio(0,0 , 1, 1); m_pGraph->SetXDecimal(2); m_pGraph->SetYDecimal(2); m_strTitle = m_pEqu->GetSimulationName(); m_pGraph->SetYNumOfGridTicks(nYTicks); m_pGraph->SetYNumOfTicks(nYTicks*5); m_pGraph->SetYNumOfSep(nYTicks); m_pGraph->SetXNumOfGridTicks(nXTicks); m_pGraph->SetXNumOfTicks(nXTicks*5); m_pGraph->SetXNumOfSep(nXTicks); //m_pGraph->SetYNumOfSep(nTicks); return TRUE; } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a DOC_UPDATE_TIMERDATA notification. /// /// Response to data update ///////////////////////////////////////////////////////////////////////////// BOOL CViewPhasePlot::OnUpdateTimer() { // int deb = GetDocument()->m_currTimer; // int nbExpSet = pLU->m_cExpSet.GetSize(); // nbExpSet = 0; // m_nTransData = -1; /**** CMdData *pPreyL = pLU->GetDataAt(nbX); CString mstr = pPreyL->GetDataName(); CMdData *pPredL = pLU->GetDataAt(nbY); mstr = pPredL->GetDataName(); pt[0].x = pPreyL->GetAt(deb,nbExpSet); pt[0].y = pPredL->GetAt(deb,nbExpSet);*/////// // } /*else if (lHint==TRANSLATION_ACTION) { CUserData *pData = (CUserData *)pHint; OnUpdateAction(pData); //Invalidate(); }*/ m_bCanEdit = FALSE; m_pSelData = NULL; m_pHypData = NULL; m_pHypData2 = m_pHypData3 = NULL; // m_nTransData = -1; m_nCurrTime = GetDocument()->GetCurrTime(); m_bCanEdit = CanEdit(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a DOC_UPDATE_BREAKPOINT notification. /// /// Response to data update ///////////////////////////////////////////////////////////////////////////// BOOL CViewPhasePlot::OnUpdateBreakPoint(int nBPTime,int nBPType) { m_bCanEdit = CanEdit(); m_bCanEdit = FALSE; m_pSelData = NULL; m_pHypData = NULL; m_pHypData2 = m_pHypData3 = NULL; return TRUE; } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a TRANSLATION_ACTION notification. /// /// Response to data update ///////////////////////////////////////////////////////////////////////////// BOOL CViewPhasePlot::OnUpdateAction(CUserData *pData) { int nbTrans = GetTranslation(); BOOL bTrans = (nbTrans<TRANS_DYNAL); BOOL bRet = FALSE; if (pData && !pData->m_bUpdateNow) { if (bTrans) return FALSE; for (int i=0;i<m_cPPData.GetSize();i++) { CPhasePlotData* pUserData = m_cPPData.GetAt(i); if (!pUserData) continue; if (pUserData->m_nExpSet != pData->m_nExpSet) continue; if (pUserData->m_nYData== pData->m_nOutcome) { //pUserData->m_pXaxis[pData->m_nTime] = pData->m_nTime; pUserData->m_pYaxis[pData->m_nTime] = pData->m_dValue; bRet = TRUE; //break; } if (pUserData->m_nXData== pData->m_nOutcome) { //pUserData->m_pXaxis[pData->m_nTime] = pData->m_nTime; pUserData->m_pXaxis[pData->m_nTime] = pData->m_dValue; bRet = TRUE; } } } else bRet = OnUpdateData(); return bRet; } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a TRANSLATION_HYPOTHESIS notification. /// /// Response to data update ///////////////////////////////////////////////////////////////////////////// BOOL CViewPhasePlot::OnUpdateHypothesis(CUserData *pData) { if (!pData) return FALSE; int nbTrans = GetTranslation(); if (nbTrans<TRANS_DYNAL) return FALSE; BOOL bFound = FALSE; for (int i=0;i<m_cUserData.GetSize();i++) { CPhasePlotData* pUserData = m_cUserData.GetAt(i); if (!pUserData) continue; if (pUserData->m_nExpSet == pData->m_nExpSet) { if (pUserData->m_nYData== pData->m_nOutcome) { //pUserData->m_pXaxis[0] = pData->m_nTime; pUserData->m_pYaxis[0] = pData->m_dValue; bFound = TRUE; break; } else if (pUserData->m_nXData== pData->m_nOutcome) { //pUserData->m_pXaxis[0] = pData->m_nTime; pUserData->m_pXaxis[0] = pData->m_dValue; bFound = TRUE; break; } } } if (bFound) return TRUE; CSimulDoc *pDoc = GetDocument(); if (!pDoc) return FALSE; CMdEquation* m_pEqu = pDoc->GetCurrentModel(); if (!m_pEqu) return FALSE; CLearningUnit* pLU = pDoc->GetCurrentLU(); if (!pLU) return FALSE; int nbOutC = m_pER->m_cOutputSet.GetSize(); BOOL bDisplay = FALSE; int nXY = 0; for (i=0;i<nbOutC;i+=2) { COutcomes *pCoX= m_pER->m_cOutputSet.GetAt(i); if (!pCoX) continue; COutcomes *pCoY= m_pER->m_cOutputSet.GetAt(i+1); if (!pCoY) continue; //if (!pCo->m_nSelected) continue; if (pCoX->m_nData == pData->m_nOutcome && pCoX->m_nExpSet == pData->m_nExpSet) { bDisplay = TRUE; nXY |= 1; } if (pCoY->m_nData == pData->m_nOutcome && pCoX->m_nExpSet == pData->m_nExpSet) { bDisplay = TRUE; nXY |= 2; } } if (!nXY) return FALSE; CMdData *pX = pLU->GetDataAt(pData->m_nOutcome); //int nbPar = m_pEqu->m_cParSet.GetSize(); CPhasePlotData* pUserData = new CPhasePlotData(1); pUserData->m_bPred = TRUE; pUserData->m_bEditable = TRUE; pUserData->m_nExpSet = pData->m_nExpSet; pUserData->m_bSelected = pData->m_nTime; pUserData->m_nXData = -1; pUserData->m_nYData = -1; if (nXY & 1) { pUserData->m_nXData = pData->m_nOutcome; pUserData->m_pXaxis[0] = pData->m_dValue; } if (nXY & 2) { pUserData->m_nYData = pData->m_nOutcome; pUserData->m_pYaxis[0] = pData->m_dValue; } pUserData->m_clrData = pX->GetDataInfo()->GetColor(); CString strExpSet = pLU->m_cExpSet.GetAt(pData->m_nExpSet)->GetName(); CString m_strYPlot = pX->GetDataName(pLU->m_bShowAbbrev); pUserData->m_strName = pX->GetDataName(pLU->m_bShowAbbrev) + _T(" (") + strExpSet + _T(")"); m_cUserData.Add(pUserData); return TRUE; } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a TRANSLATION_MAPRELATION notification. /// /// Response to data update ///////////////////////////////////////////////////////////////////////////// BOOL CViewPhasePlot::OnUpdateMapRelation(CTranslationInfo *mTInfo ) { if (mTInfo) { //CTranslationInfo *mTInfo = (CTranslationInfo *)pHint; m_nTransData = -1; int nTime = -1;//mTInfo->m_nTime; int nExpSet = -1;//mTInfo->m_nExpSet; int nData = -1;//mTInfo->m_nData; int nb = mTInfo->m_nDatas.GetSize(); m_nCurrTime = mTInfo->m_nTime; if (nb == 2) { CTranslationInfo::CTInfo tt1 = mTInfo->m_nDatas.GetAt(0); CTranslationInfo::CTInfo tt2 = mTInfo->m_nDatas.GetAt(1); tt1.nData; tt1.nExpSet; for (int kk=0;kk<m_cPPData.GetSize();kk++) { CPhasePlotData* pData = m_cPPData.GetAt(kk); if (!pData) continue; pData->m_bSelected = FALSE; if ( (((pData->m_nXData ==tt1.nData) && (pData->m_nExpSet ==tt1.nExpSet)) || ((pData->m_nXData ==tt2.nData) && (pData->m_nExpSet ==tt2.nExpSet))) && (((pData->m_nYData ==tt1.nData) && (pData->m_nExpSet ==tt1.nExpSet)) || ((pData->m_nYData ==tt2.nData) && (pData->m_nExpSet ==tt2.nExpSet))) ) { pData->m_bSelected = 3; m_nTransData = kk; //break; } //else // pData->m_bSelected = FALSE; } } else if (nb) { CTranslationInfo::CTInfo tt1 = mTInfo->m_nDatas.GetAt(0); nData = tt1.nData; nExpSet = tt1.nExpSet; for (int kk=0;kk<m_cPPData.GetSize();kk++) { CPhasePlotData* pData = m_cPPData.GetAt(kk); if (!pData) continue; if (((pData->m_nXData ==nData) || (pData->m_nYData ==nData)) && pData->m_nExpSet == nExpSet) { if (pData->m_nXData ==nData) pData->m_bSelected = 1; else pData->m_bSelected = 2; m_nTransData = kk; //break; } else pData->m_bSelected = FALSE; } } } else { m_nTransData = -1; for (int kk=0;kk<m_cPPData.GetSize();kk++) { CPhasePlotData* pData = m_cPPData.GetAt(kk); if (!pData) continue; pData->m_bSelected = FALSE; } } m_bCanEdit = CanEdit(); return TRUE; } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a notification message. /// /// \param pSender Points to the view that modified the document, or NULL if all views are to be updated. /// \param lHint Contains information about the modifications. /// \param pHint Points to an object storing information about the modifications. /// /// This member function proceeds and/or dispatches all the messages sent by the framework /// to the relevant function. ///////////////////////////////////////////////////////////////////////////// void CViewPhasePlot::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { // TODO: Add your specialized code here and/or call the base class CMdEquation* m_pEqu = GetDocument()->GetCurrentModel(); if (!m_pEqu) return; CLearningUnit* pLU = GetDocument()->GetCurrentLU(); if (!pLU) return; int nbTrans = GetTranslation(); BOOL bRet = TRUE; if (lHint == DOC_UPDATE_TIMERDATA) { OnUpdateTimer(); } if (lHint == TRANSLATION_HYPOTHESIS ) { CUserData *pData = (CUserData *)pHint; bRet = OnUpdateHypothesis(pData); } else if (lHint==TRANSLATION_ACTION) { CUserData *pData = (CUserData *)pHint; OnUpdateAction(pData); //Invalidate(); } if (lHint == DOC_UPDATE_BREAKPOINT ) { CTimerBreakPoint *mTInfo = (CTimerBreakPoint *)pHint; int nBPTime = mTInfo->m_tBreakPt; int nBPType = mTInfo->m_nBPType; bRet = OnUpdateBreakPoint(nBPTime,0); } if (lHint == TRANSLATION_MAPRELATION) { if (nbTrans==TRANS_INDEP) { bRet = FALSE; } else { CTranslationInfo *mTInfo = (CTranslationInfo *)pHint; bRet = OnUpdateMapRelation(mTInfo); } } if (lHint == DOC_UPDATE_ER || !lHint) { CFormatPhasePlot *pDlg = GetFormats(); if (pDlg) { m_bStabPt = pDlg->m_bShowStab; m_bCurrT = pDlg->m_bShowCurrTime; m_bTitle = pDlg->m_bShowLegend; m_bGrid = pDlg->m_bShowAxe; if (lHint == DOC_UPDATE_ER) SetScaleType(pDlg->m_nScale); } m_pGraph->EnableLegend(m_bTitle==TRUE); } if (lHint == DOC_UPDATE_RESTARTSIMUL) { for (int i=0;i<m_cUserData.GetSize();i++) { CPhasePlotData* pData = m_cUserData.GetAt(i); if (!pData) continue; delete pData; } m_cUserData.RemoveAll(); OnUpdateTimer(); bRet = OnUpdateData(); } if (!lHint || lHint == DOC_UPDATE_ALLDATA) { bRet = OnUpdateData(); } if (bRet) { RecalcSize(); Invalidate(); UpdateWindow(); } } BOOL CViewPhasePlot::SetScaleType(int nScale) { BOOL bRet = TRUE; switch (nScale) { case 0: m_pGraph = &m_Linear; break; case 1: m_pGraph = &m_XLogYLinear; break; case 2: m_pGraph = &m_XLinearYLog; break; case 3: m_pGraph = &m_XLogYLog; break; default: bRet=FALSE; } return bRet; } void CViewPhasePlot::OnSetScaleType(UINT nID) { // TODO: Add your command handler code here BOOL nRedraw = TRUE; switch (nID){ case ID_XYGRAPH_SCALETYPE_LINEAR: //m_pGraph = &m_Linear; //break; case ID_XYGRAPH_SCALETYPE_XLOG: //m_pGraph = &m_XLogYLinear; //break; case ID_XYGRAPH_SCALETYPE_YLOG: //m_pGraph = &m_XLinearYLog; //break; case ID_XYGRAPH_SCALETYPE_XYLOG: //m_pGraph = &m_XLogYLog; nRedraw = SetScaleType(nID-ID_XYGRAPH_SCALETYPE_LINEAR); break; default: nRedraw = FALSE; break; } if (nRedraw) { OnUpdate(NULL,0,NULL); RecalcSize(); Invalidate(); UpdateWindow(); } } void CViewPhasePlot::OnUpdateScaleType(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here BOOL bSetCheck = FALSE; switch (pCmdUI->m_nID){ case ID_XYGRAPH_SCALETYPE_LINEAR: bSetCheck = (m_pGraph == &m_Linear); break; case ID_XYGRAPH_SCALETYPE_XLOG: bSetCheck = (m_pGraph == &m_XLogYLinear); break; case ID_XYGRAPH_SCALETYPE_YLOG: bSetCheck = (m_pGraph == &m_XLinearYLog); break; case ID_XYGRAPH_SCALETYPE_XYLOG: bSetCheck = (m_pGraph == &m_XLogYLog); break; default: break; } pCmdUI->SetCheck(bSetCheck); } void CViewPhasePlot::OnFilePrintPreview() { // TODO: Add your command handler code here CScrollView::OnFilePrintPreview(); } void CViewPhasePlot::OnEndPrintPreview(CDC* pDC, CPrintInfo* pInfo, POINT point, CPreviewView* pView) { // TODO: Add your specialized code here and/or call the base class CScrollView::OnEndPrintPreview(pDC, pInfo, point, pView); RecalcSize(); } void CViewPhasePlot::OnSelectData() { // TODO: Add your command handler code here if (!m_pER) return; CSelectOutcomeDlg dlg(this,GetDocument()); dlg.m_bForceSync = TRUE; for (int i=0;i<m_pER->m_cOutputSet.GetSize();i++) { COutcomes *po = m_pER->m_cOutputSet.GetAt(i)->Clone(); dlg.m_cLocOutputSet.Add(po); } CLearningUnit *pLU = GetDocument()->GetCurrentLU(); for (i=0;i<pLU->m_cExpSet.GetSize();i++) { CString str= pLU->m_cExpSet.GetAt(i)->GetName(); dlg.m_cTabLabel.Add(str); } if (dlg.DoModal() == IDOK) { for(int i = 0; i < m_pER->m_cOutputSet.GetSize();i++ ) delete m_pER->m_cOutputSet.GetAt(i); m_pER->m_cOutputSet.RemoveAll(); for (i=0;i<dlg.m_cLocOutputSet.GetSize();i++) { COutcomes *po =dlg.m_cLocOutputSet.GetAt(i)->Clone(); m_pER->m_cOutputSet.Add(po); } CTrace::T_CHANGEOUTCOME(this,&(m_pER->m_cOutputSet)); //InitView(); OnUpdate(0,0,0) ; } } void CViewPhasePlot::OnTranslationTasks(UINT nID) { // TODO: Add your command handler code here switch (nID) { case ID_TASK_MAPFACT: case ID_TASK_MAPRELATION: case ID_TASK_SUPPORTACTION: // m_nCurrTTask = nID - ID_TASK_MAPFACT+1; break; case ID_TASK_CANCELTASK: default: // m_nCurrTTask = 0; break; } } void CViewPhasePlot::OnUpdateTransTasks(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here BOOL bEnab = FALSE; BOOL bCheck = FALSE; UINT nT = GetTranslation(); //UINT nCT = m_nCurrTTask; switch (pCmdUI->m_nID) { case ID_TRANS_INDEPENDENT: case ID_TRANS_MAPRELATION: case ID_TRANS_DYNALINKED: bCheck = (nT == (pCmdUI->m_nID - ID_TRANS_INDEPENDENT)); bEnab = bCheck; break; default: break; } pCmdUI->Enable(bEnab); pCmdUI->SetCheck(bCheck); } void CViewPhasePlot::OnDestroy() { CTrace::T_CLOSE(GetParentFrame()); CScrollView::OnDestroy(); // TODO: Add your message handler code here } int CViewPhasePlot::HitTest(CPoint mPt,CPhasePlotData *pData,int nLim/*=-1*/) { int nRet = -1; BOOL bFound = FALSE; int nCount = (nLim == -1) ? pData->m_nData : nLim; if (pData->m_bPred) { CTPoint<double> ptTime[2]; CRect mrect; if (pData->m_nXData !=-1) { ptTime[0].x = pData->m_pXaxis[0]; ptTime[0].y = yRange.x; ptTime[1].x = pData->m_pXaxis[0]; ptTime[1].y = yRange.y; CPoint npt1 = m_pGraph->GetTPoint(ptTime[0]); CPoint npt2 = m_pGraph->GetTPoint(ptTime[1]); mrect = CRect(npt1,npt2); mrect.InflateRect(5,0,5,0); mrect.NormalizeRect(); } if (pData->m_nYData !=-1) { ptTime[0].y = pData->m_pYaxis[0]; ptTime[0].x = xRange.x; ptTime[1].y = pData->m_pYaxis[0]; ptTime[1].x = xRange.y; CPoint npt1 = m_pGraph->GetTPoint(ptTime[0]); CPoint npt2 = m_pGraph->GetTPoint(ptTime[1]); mrect = CRect(npt1,npt2); mrect.InflateRect(0,5,0,5); } bFound = mrect.PtInRect(mPt); if (bFound) nRet = 0; //nCount=0; } else for (int i=nCount;i>=0 && !bFound;i--) { CTPoint<double> pt1; pt1.x = pData->m_pXaxis[i]; pt1.y = pData->m_pYaxis[i]; CPoint npt = m_pGraph->GetTPoint(pt1); CRect mrect(npt,npt); mrect.InflateRect(10,10); bFound = mrect.PtInRect(mPt); if (bFound) nRet = i; } return nRet; } void CViewPhasePlot::OnLButtonDown(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default m_pSelData = NULL; m_pHypData = NULL; m_pHypData2 = m_pHypData3 = NULL; CSimulDoc *pDoc = GetDocument(); if (!pDoc) return; int nCBP = pDoc->m_nCurrBP; int nRT = pDoc->m_runTimer; CTimerBreakPoint pBP; BOOL bEditable = pDoc->GetCurrentLU()->GetTimerBPAt(nCBP,pBP); if (!bEditable) return; // CTPoint<double> pt1 = m_pGraph->GetTValue(point); // CTPoint<double> nDelta; if (m_nTransData != -1 && m_bCanEdit && pBP.m_nBPType==BREAKP_ACTION) { CPhasePlotData *pData = m_cPPData.GetAt(m_nTransData); if (pData && pData->m_bEditable) { //int nTest = pData->HitTest(m_pGraph,point,pt1,nDelta,GetDocument()->m_runTimer); int nTest = HitTest(point,pData,GetDocument()->m_runTimer); if (nTest == GetDocument()->m_runTimer) { //m_nEditData = m_nTransData; m_pSelData = pData; } } } else if (nCBP==nRT && pBP.m_nBPType==BREAKP_HYPOT && !pDoc->m_bTaskDone) { BOOL bFound = FALSE; int nb = m_cUserData.GetSize(); for (int i=0;i<nb;i++) { CPhasePlotData *pData = m_cUserData.GetAt(i); if (!pData) continue; int nTest = HitTest(point,pData,GetDocument()->m_runTimer); if (nTest!=-1) { m_pHypData = pData; bFound = TRUE; break; } } if (!bFound && m_nTransData != -1) { CPhasePlotData *pData = m_cPPData.GetAt(m_nTransData); int nTest = HitTest(point,pData,GetDocument()->m_runTimer); if (nTest != GetDocument()->m_runTimer) return; int nSel = pData->m_bSelected; int nb = m_cUserData.GetSize(); for (int i=0;i<nb;i++) { CPhasePlotData *pUData = m_cUserData.GetAt(i); if (!pUData) continue; if (pUData->m_nExpSet == pData->m_nExpSet && pUData->m_nYData == pData->m_nYData) { if (nSel==2) { m_pHypData = pUData; return; } else if (nSel==3) { m_pHypData3 = pUData; m_pHypData= pUData; } } if (pUData->m_nExpSet == pData->m_nExpSet && pUData->m_nXData == pData->m_nXData) { if (nSel==1) { m_pHypData = pUData; return; } else if (nSel==3) { m_pHypData2 = pUData; m_pHypData= pUData; } } } if (m_pHypData2 || m_pHypData3) return; CUserOutput pT2; BOOL bOutput = GetDocument()->m_cUserInput.Lookup(nCBP,pT2); if (!bOutput) return; CLearningUnit* pLU = GetDocument()->GetCurrentLU(); BOOL bEditable = pLU->GetTimerBPAt(pT2.m_nTime,pBP); if (!bEditable) return; if (nSel==1) { CUserData pUData; pUData.m_nExpSet = pData->m_nExpSet; pUData.m_nOutcome = pData->m_nXData; pUData.m_nTime = pT2.m_nTime; pUData.m_dOldValue = pData->m_pXaxis[nCBP]; pUData.m_dValue = pData->m_pXaxis[nCBP]; if (OnUpdateHypothesis(&pUData)) { nb = m_cUserData.GetSize(); m_pHypData = m_cUserData.GetAt(nb-1); } } else if (nSel==2) { CUserData pUData; pUData.m_nExpSet = pData->m_nExpSet; pUData.m_nOutcome = pData->m_nYData; pUData.m_nTime = pT2.m_nTime; pUData.m_dOldValue = pData->m_pYaxis[nCBP]; pUData.m_dValue = pData->m_pYaxis[nCBP]; if (OnUpdateHypothesis(&pUData)) { nb = m_cUserData.GetSize(); m_pHypData = m_cUserData.GetAt(nb-1); } } else if (nSel==3) { CUserData pUData; pUData.m_nExpSet = pData->m_nExpSet; pUData.m_nOutcome = pData->m_nXData; pUData.m_nTime = pT2.m_nTime; pUData.m_dOldValue = pData->m_pXaxis[nCBP]; pUData.m_dValue = pData->m_pXaxis[nCBP]; if (OnUpdateHypothesis(&pUData)) { nb = m_cUserData.GetSize(); m_pHypData2 = m_cUserData.GetAt(nb-1); } CUserData pUData2; pUData2.m_nExpSet = pData->m_nExpSet; pUData2.m_nOutcome = pData->m_nYData; pUData2.m_nTime = pT2.m_nTime; pUData2.m_dOldValue = pData->m_pYaxis[nCBP]; pUData2.m_dValue = pData->m_pYaxis[nCBP]; if (OnUpdateHypothesis(&pUData2)) { nb = m_cUserData.GetSize(); m_pHypData3 = m_cUserData.GetAt(nb-1); } } if (m_pHypData3) m_pHypData=m_pHypData3; if (m_pHypData2) m_pHypData=m_pHypData2; } } CScrollView::OnLButtonDown(nFlags, point); } BOOL CViewPhasePlot::OnMoveData(CPhasePlotData* m_pHypData,CPoint point) { if (!m_pHypData) return FALSE; double x = m_pHypData->m_pXaxis[0]; double y = m_pHypData->m_pYaxis[0]; CTPoint<double> pt1 = m_pGraph->GetTValue(point); y = pt1.y; x = pt1.x; if (y>yRange.y) y=yRange.y; if (y<yRange.x) y=yRange.x; if (x>xRange.y) x=xRange.y; if (x<xRange.x) x=xRange.x; CUserData pUData; pUData.m_nExpSet = m_pHypData->m_nExpSet; pUData.m_nTime = m_pHypData->m_bSelected;//pgvItem->row-1; if (m_pHypData->m_nYData !=-1) { pUData.m_dOldValue = m_pHypData->m_pYaxis[0]; pUData.m_nOutcome = m_pHypData->m_nYData; m_pHypData->m_pYaxis[0] = y; pUData.m_dValue = m_pHypData->m_pYaxis[0]; } if (m_pHypData->m_nXData !=-1) { pUData.m_dOldValue = m_pHypData->m_pXaxis[0]; pUData.m_nOutcome = m_pHypData->m_nXData; m_pHypData->m_pXaxis[0] = x; pUData.m_dValue = m_pHypData->m_pXaxis[0]; } GetDocument()->UpdateUserData(NULL,&pUData); return TRUE; } void CViewPhasePlot::OnMouseMove(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default CScrollView::OnMouseMove(nFlags, point); BOOL bUpdate = FALSE; int nCBP = GetDocument()->m_nCurrBP; int nRT = GetDocument()->m_runTimer; CTimerBreakPoint pBP; BOOL bEditable = GetDocument()->GetCurrentLU()->GetTimerBPAt(nCBP,pBP); // if (!bEditable) { CRect m_PlotRect = m_pGraph->m_PlotRect; CRect m_Rect; GetClientRect(m_Rect); //m_pGraph->GetPixelRect(mrect2); int GL = m_PlotRect.left; int GR = m_PlotRect.right; int GT = m_PlotRect.top; int GB = m_PlotRect.bottom; int PX = GR - GL; int PY = GB - GT; //m_Scale.dx = (m_Scale.xmax- m_Scale.xmin) / PX; //m_Scale.dy = (m_Scale.ymax- m_Scale.ymin) / PY; CSize m_Size; m_Size.cx = (PY < PX) ? PY : PX; LOGFONT m_LogFont; m_LogFont.lfHeight = (int)(m_Size.cx / -25.0); m_LogFont.lfHeight = -10; m_LogFont.lfWeight = 500; m_LogFont.lfOrientation= 0; m_LogFont.lfEscapement = 0; CFont m_Font; m_Font.CreateFontIndirect(&m_LogFont); int n = (m_Rect.right - GR) / 20 + 1; int xb = GR + 2 * n; int xe = xb + 4 * n; for (int k=0;k<m_cPPData.GetSize();k++) { int Index=k+1; int y = GT - 3 * Index * m_LogFont.lfHeight / 2; CRect rTest(xb,y-6,m_Rect.right,y+6); BOOL bFound = rTest.PtInRect(point); CPhasePlotData *pData = m_cPPData.GetAt(k); if (bFound) { OnUpdateObjTooltip((WPARAM)pData,TRUE); return; } } { int Index=m_cPPData.GetSize()+2; int y = GT - 3 * Index * m_LogFont.lfHeight / 2; CRect rTest(xb,y-6,m_Rect.right,y+6); BOOL bFound = rTest.PtInRect(point); if (bFound) { //return; } } for (int i=0;i<m_cUserData.GetSize();i++) { int Index=m_cPPData.GetSize()+5+i; int y = GT - 3 * Index * m_LogFont.lfHeight / 2; CRect rTest(xb,y-6,m_Rect.right,y+6); BOOL bFound = rTest.PtInRect(point); if (bFound) { CPhasePlotData *pData = m_cUserData.GetAt(i); OnUpdateObjTooltip((WPARAM)pData,TRUE); return; } } OnUpdateObjTooltip(NULL,NULL); } if (!bEditable) return; if (m_pSelData && m_nTransData !=-1) { double x = m_pSelData->m_pXaxis[GetDocument()->m_runTimer]; double y = m_pSelData->m_pYaxis[GetDocument()->m_runTimer]; CTPoint<double> pt1 = m_pGraph->GetTValue(point); if (m_pSelData->m_bSelected == 3) // X & Y { x = pt1.x; y = pt1.y; } else if (m_pSelData->m_bSelected == 2) // Y { y = pt1.y; } else if (m_pSelData->m_bSelected == 1) // X { x = pt1.x; } CPhasePlotData *pRRData = m_cPPData.GetAt(m_nTransData); CLearningUnit* pLU = GetDocument()->GetCurrentLU(); CMdData *pObjData = pLU->GetDataAt(pRRData->m_nYData); if (!pObjData) return; CModelObj *pObj = pObjData->GetDataInfo(); CModelPar *pVarObj = DYNAMIC_DOWNCAST( CModelPar, pObj); double dNewVal = y; if (pVarObj) { double dmin = pVarObj->GetMin(); double dmax = pVarObj->GetMax(); y = min(max(dNewVal,dmin),dmax); /* if (dNewVal<dmin|| dNewVal>dmax) { int precision = 15; UINT nIDPrompt = AFX_IDP_PARSE_REAL_RANGE; TCHAR szMin[32], szMax[32]; CString prompt; _stprintf(szMin, _T("%.*g"), precision, dmin); _stprintf(szMax, _T("%.*g"), precision, dmax); AfxFormatString2(prompt, nIDPrompt, szMin, szMax); AfxMessageBox(prompt, MB_ICONEXCLAMATION, nIDPrompt); m_pSelData = NULL; m_pHypData = NULL; return; }*/ } pObjData = pLU->GetDataAt(pRRData->m_nXData); if (!pObjData) return; pObj = pObjData->GetDataInfo(); pVarObj = DYNAMIC_DOWNCAST( CModelPar, pObj); dNewVal = x; if (pVarObj) { double dmin = pVarObj->GetMin(); double dmax = pVarObj->GetMax(); x = min(max(dNewVal,dmin),dmax); } m_pSelData->m_pXaxis[GetDocument()->m_runTimer] = x; m_pSelData->m_pYaxis[GetDocument()->m_runTimer] = y; double xMin = min(xRange.x,x); double xMax = max(xRange.y,x); double yMin = min(yRange.x,y); double yMax = max(yRange.y,y); m_pGraph->SetRange(xMin,yMin, xMax, yMax); //m_pGraph->SetYNumOfTicks(nTicks*5); //m_pGraph->SetYNumOfSep(nTicks); //m_pGraph->SetYNumOfGridTicks(nTicks); int m_nExpSet = m_pSelData->m_nExpSet; int m_nYData = m_pSelData->m_nYData; int m_nXData = m_pSelData->m_nXData; //CLearningUnit *pLU = GetDocument()->GetCurrentLU(); CMdEquation* pEqu = GetDocument()->GetCurrentModel(); CMdData *pPrey= pLU->m_cDataPoints.GetAt(m_nXData); CString mstrX=pPrey->GetDataName(pLU->m_bShowAbbrev); CMdData *pPred= pLU->m_cDataPoints.GetAt(m_nYData); CString mstrY=pPred->GetDataName(pLU->m_bShowAbbrev); double nXo = pPrey->GetAt(GetDocument()->m_runTimer,m_nExpSet); double nXn = x;//m_pSelData->m_pXaxis[GetDocument()->m_runTimer]; double nYo = pPred->GetAt(GetDocument()->m_runTimer,m_nExpSet); double nYn = y;//m_pSelData->m_pYaxis[GetDocument()->m_runTimer]; CUserData pUData; pUData.m_nExpSet = m_nExpSet; pUData.m_nOutcome = m_nXData; pUData.m_nTime = GetDocument()->m_runTimer;//pgvItem->row-1; pUData.m_dOldValue = nXo; pUData.m_dValue = nXn; pUData.m_bUpdateNow = FALSE; GetDocument()->UpdateUserData(NULL,&pUData); CUserData pUData2; pUData2.m_nExpSet = m_nExpSet; pUData2.m_nOutcome = m_nYData; pUData2.m_nTime = GetDocument()->m_runTimer;//pgvItem->row-1; pUData2.m_dOldValue = nYo; pUData2.m_dValue = nYn; pUData2.m_bUpdateNow = FALSE; GetDocument()->UpdateUserData(NULL,&pUData2); bUpdate = TRUE; } else if (m_pHypData && nCBP==nRT && pBP.m_nBPType==BREAKP_HYPOT && !GetDocument()->m_bTaskDone) { if (m_pHypData2 || m_pHypData3) { if (m_pHypData2) bUpdate = OnMoveData(m_pHypData2,point); if (m_pHypData3) bUpdate = OnMoveData(m_pHypData3,point); } else bUpdate = OnMoveData(m_pHypData,point); } if (bUpdate) { //CPhasePlotData *pData = m_pSelData; RecalcSize(); Invalidate(); UpdateWindow(); } } void CViewPhasePlot::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default BOOL bUpdate = FALSE; if (m_pSelData) { int m_nExpSet = m_pSelData->m_nExpSet; int m_nYData = m_pSelData->m_nYData; int m_nXData = m_pSelData->m_nXData; CLearningUnit *pLU = GetDocument()->GetCurrentLU(); CMdEquation* pEqu = GetDocument()->GetCurrentModel(); CMdData *pPrey= pLU->m_cDataPoints.GetAt(m_nXData); CString mstrX=pPrey->GetDataName(pLU->m_bShowAbbrev); CMdData *pPred= pLU->m_cDataPoints.GetAt(m_nYData); CString mstrY=pPred->GetDataName(pLU->m_bShowAbbrev); double nXo = pPrey->GetAt(GetDocument()->m_runTimer,m_nExpSet); double nXn = m_pSelData->m_pXaxis[GetDocument()->m_runTimer]; double nYo = pPred->GetAt(GetDocument()->m_runTimer,m_nExpSet); double nYn = m_pSelData->m_pYaxis[GetDocument()->m_runTimer]; CUserData pUData; pUData.m_nExpSet = m_nExpSet; pUData.m_nOutcome = m_nXData; pUData.m_nTime = GetDocument()->m_runTimer;//pgvItem->row-1; pUData.m_dOldValue = nXo; pUData.m_dValue = nXn; GetDocument()->UpdateUserData(this,&pUData); CUserData pUData2; pUData2.m_nExpSet = m_nExpSet; pUData2.m_nOutcome = m_nYData; pUData2.m_nTime = GetDocument()->m_runTimer;//pgvItem->row-1; pUData2.m_dOldValue = nYo; pUData2.m_dValue = nYn; GetDocument()->UpdateUserData(this,&pUData2); bUpdate = TRUE; m_pSelData = NULL; //m_pHypData = NULL; m_nTransData = -1; } else if (m_pHypData) { bUpdate = TRUE; } m_pSelData = NULL; m_pHypData = NULL; //m_pHypData2 = m_pHypData3 = NULL; if (bUpdate) { // OnUpdateMapRelation(NULL); RecalcSize(); Invalidate(); UpdateWindow(); } CScrollView::OnLButtonUp(nFlags, point); } void CViewPhasePlot::OnLButtonDblClk(UINT nFlags, CPoint point) { // TODO: Add your message handler code here and/or call default BOOL bFound = FALSE; int nTrans = GetTranslation(); { CRect m_PlotRect = m_pGraph->m_PlotRect; CRect m_Rect; GetClientRect(m_Rect); //m_pGraph->GetPixelRect(mrect2); int GL = m_PlotRect.left; int GR = m_PlotRect.right; int GT = m_PlotRect.top; int GB = m_PlotRect.bottom; int PX = GR - GL; int PY = GB - GT; //m_Scale.dx = (m_Scale.xmax- m_Scale.xmin) / PX; //m_Scale.dy = (m_Scale.ymax- m_Scale.ymin) / PY; CSize m_Size; m_Size.cx = (PY < PX) ? PY : PX; LOGFONT m_LogFont; m_LogFont.lfHeight = (int)(m_Size.cx / -25.0); m_LogFont.lfHeight = -10; m_LogFont.lfWeight = 500; m_LogFont.lfOrientation= 0; m_LogFont.lfEscapement = 0; CFont m_Font; m_Font.CreateFontIndirect(&m_LogFont); int n = (m_Rect.right - GR) / 20 + 1; int xb = GR + 2 * n; int xe = xb + 4 * n; for (int k=0;k<m_cPPData.GetSize();k++) { int Index=k+1; int y = GT - 3 * Index * m_LogFont.lfHeight / 2; CRect rTest(xb,y-6,m_Rect.right,y+6); BOOL bFound = rTest.PtInRect(point); if (bFound) { CString mstr; mstr.Format(_T("Data : %d"),k); //AfxMessageBox(mstr); CTranslationInfo mTInfo; CPhasePlotData *pData = m_cPPData.GetAt(k); mTInfo.m_nTransLvl = TRANS_MAPRELAT; mTInfo.m_nTime=m_nCurrTime; mTInfo.m_nDatas.RemoveAll(); CTranslationInfo::CTInfo tt={m_nCurrTime,pData->m_nXData,pData->m_nExpSet}; mTInfo.m_nDatas.Add(tt); CTranslationInfo::CTInfo tt1={m_nCurrTime,pData->m_nYData,pData->m_nExpSet}; mTInfo.m_nDatas.Add(tt1); OnUpdateMapRelation(&mTInfo); Invalidate(); UpdateWindow(); OnUpdateObjTooltip((WPARAM)pData,TRUE); return; } } /* { int Index=m_cPPData.GetSize()+2; int y = GT - 3 * Index * m_LogFont.lfHeight / 2; CRect rTest(xb,y-6,m_Rect.right,y+6); BOOL bFound = rTest.PtInRect(point); if (bFound) { //AfxMessageBox(_T("Time")); OnUpdateMapRelation(NULL); //GetDocument()->UpdateMapRelation(NULL,NULL); return; } }*/ for (int i=0;i<m_cUserData.GetSize();i++) { int Index=m_cPPData.GetSize()+5+i; int y = GT - 3 * Index * m_LogFont.lfHeight / 2; CRect rTest(xb,y-6,m_Rect.right,y+6); BOOL bFound = rTest.PtInRect(point); if (bFound) { CPhasePlotData *pData = m_cUserData.GetAt(i); CString mstr; mstr.Format(_T("Hypothesis : %d"),i); //AfxMessageBox(mstr); m_pHypData = pData; Invalidate(); UpdateWindow(); OnUpdateObjTooltip((WPARAM)pData,TRUE); return; } } } /* if (nTrans < TRANS_MAPRELAT) { //GetDocument()->UpdateMapRelation(NULL,NULL); return; }*/ CTPoint<double> pt1 = m_pGraph->GetTValue(point); CTPoint<double> nDelta; nDelta.x = (xRange.y - xRange.x) / 40; nDelta.y = (yRange.y - yRange.x) / 40; for (int k=0;k<m_cPPData.GetSize();k++) { CPhasePlotData *pData = m_cPPData.GetAt(k); if (!pData) continue; //int nTest = pData->HitTest(m_pGraph,point,pt1,nDelta,GetDocument()->m_runTimer); int nTest = HitTest(point,pData,GetDocument()->m_runTimer); if (nTest != -1) { CTranslationInfo mTInfo; mTInfo.m_nTransLvl = TRANS_MAPRELAT; mTInfo.m_nTime=nTest; mTInfo.m_nDatas.RemoveAll(); CTranslationInfo::CTInfo tt={nTest,pData->m_nXData,pData->m_nExpSet}; mTInfo.m_nDatas.Add(tt); CTranslationInfo::CTInfo tt1={nTest,pData->m_nYData,pData->m_nExpSet}; mTInfo.m_nDatas.Add(tt1); //GetDocument()->m_currTimer = nTest; //GetDocument()->UpdateAllViews(NULL,TRANSLATION_MAPRELATION,(CObject*)&mTInfo); if (nTrans==TRANS_INDEP) { OnUpdateMapRelation(&mTInfo); //OnUpdate(this,TRANSLATION_MAPRELATION,(CObject*)&mTInfo); Invalidate(); UpdateWindow(); } else GetDocument()->UpdateMapRelation(this,&mTInfo); //GetDocument()->UpdateMapRelation(this,&mTInfo); bFound = TRUE; break; } } if (!bFound) { if (nTrans==TRANS_INDEP) { //OnUpdate(this,TRANSLATION_MAPRELATION,NULL); OnUpdateMapRelation(NULL); Invalidate(); UpdateWindow(); } else GetDocument()->UpdateMapRelation(NULL,NULL); //GetDocument()->UpdateMapRelation(NULL,NULL); } //GetDocument()->UpdateAllViews(NULL,TRANSLATION_MAPRELATION,NULL); CScrollView::OnLButtonDblClk(nFlags, point); } void CViewPhasePlot::OnEditCopy() { // TODO: Add your command handler code here CBitmap bitmap; CClientDC dc(this); CDC memDC; BeginWaitCursor(); memDC.CreateCompatibleDC(&dc); CRect m_rectArea; GetClientRect(&m_rectArea); bitmap.CreateCompatibleBitmap(&dc, m_rectArea.Width(),m_rectArea.Height() ); CBitmap* pOldBitmap = memDC.SelectObject(&bitmap); OnDraw(&memDC); OpenClipboard() ; EmptyClipboard() ; SetClipboardData (CF_BITMAP, bitmap.GetSafeHandle() ) ; CloseClipboard () ; bitmap.Detach(); EndWaitCursor(); } BOOL CViewPhasePlot::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class if(pMsg->message== WM_LBUTTONDOWN || pMsg->message== WM_LBUTTONUP || pMsg->message== WM_MOUSEMOVE) myToolTip.RelayEvent(pMsg); return CScrollView::PreTranslateMessage(pMsg); }
24.919355
106
0.645606
[ "object", "model" ]
eb350c8552e2adc93d2335ac11865671eb99fd58
16,107
cpp
C++
src/sources/generator.cpp
ebachard/ImStudio
35d196993e29ceee7475f1cc74645227c642e06d
[ "MIT" ]
1
2022-02-08T06:46:12.000Z
2022-02-08T06:46:12.000Z
src/sources/generator.cpp
ebachard/ImStudio
35d196993e29ceee7475f1cc74645227c642e06d
[ "MIT" ]
null
null
null
src/sources/generator.cpp
ebachard/ImStudio
35d196993e29ceee7475f1cc74645227c642e06d
[ "MIT" ]
null
null
null
#include "../includes.h" #include "object.h" #include "buffer.h" #include "generator.h" void ImStudio::Recreate(BaseObject obj, std::string* output, bool staticlayout) { std::string bfs; if (obj.type == "button") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::Button(\"{}\", ImVec2({},{})); ",obj.value_s, obj.size.x, obj.size.y); bfs += "//remove size argument (ImVec2) to auto-resize\n\n"; } if (obj.type == "radio") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tstatic bool r1{} = false;\n",obj.id); bfs += fmt::format("\tImGui::RadioButton(\"{}\", r1{});\n\n",obj.label, obj.id); } if (obj.type == "checkbox") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tstatic bool c1{} = false;\n",obj.id); bfs += fmt::format("\tImGui::Checkbox(\"{}\", &c1{});\n\n",obj.label, obj.id); } if (obj.type == "text") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::Text(\"{}\");\n\n",obj.value_s); } if (obj.type == "bullet") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += "\tImGui::Bullet();\n\n"; } if (obj.type == "arrow") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += "\tImGui::ArrowButton(\"##left\", ImGuiDir_Left);\n"; bfs += "\tImGui::SameLine();\n"; bfs += "\tImGui::ArrowButton(\"##right\", ImGuiDir_Right);\n\n"; } if (obj.type == "combo") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); bfs += fmt::format("\tstatic int item_current{} = 0;\n",obj.id); bfs += fmt::format("\tconst char *items{}[] = {{\"Never\", \"Gonna\", \"Give\", \"You\", \"Up\"}};\n",obj.id); bfs += fmt::format("\tImGui::Combo(\"{0}\", &item_current{1}, items{1}, IM_ARRAYSIZE(items{1}));\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "listbox") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); bfs += fmt::format("\tstatic int item_current{} = 0;\n",obj.id); bfs += fmt::format("\tconst char *items{}[] = {{\"Never\", \"Gonna\", \"Give\", \"You\", \"Up\"}};\n",obj.id); bfs += fmt::format("\tImGui::ListBox(\"{0}\", &item_current{1}, items{1}, IM_ARRAYSIZE(items{1}));\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "textinput") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({}); ",obj.width); bfs += "//NOTE: (Push/Pop)ItemWidth is optional\n"; //static char str0[128] = "Hello, world!"; //ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); bfs += fmt::format("\tstatic char str{}[128] = \"{}\";\n",obj.id,obj.value_s); bfs += fmt::format("\tImGui::InputText(\"{0}\", str{1}, IM_ARRAYSIZE(str{1}));\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "inputint") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static int i0 = 123; //ImGui::InputInt("input int", &i0); bfs += fmt::format("\tstatic int i{} = 123;\n",obj.id); bfs += fmt::format("\tImGui::InputInt(\"{}\", &i{});\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "inputfloat") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float f0 = 0.001f; //ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f"); bfs += fmt::format("\tstatic float f{} = 0.001f;\n",obj.id); bfs += fmt::format("\tImGui::InputFloat(\"{}\", &f{}, 0.01f, 1.0f, \"%.3f\");\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "inputdouble") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static double d0 = 999999.00000001; //ImGui::InputDouble("input double", &d0, 0.01f, 1.0f, "%.8f"); bfs += fmt::format("\tstatic double d{} = 999999.00000001;\n",obj.id); bfs += fmt::format("\tImGui::InputDouble(\"{}\", &d{}, 0.01f, 1.0f, \"%.8f\");\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "inputscientific") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float f1 = 1.e10f; //ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e"); bfs += fmt::format("\tstatic float f{} = 1.e10f;\n",obj.id); bfs += fmt::format("\tImGui::InputFloat(\"{}\", &f{}, 0.0f, 0.0f, \"%e\");\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "inputfloat3") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; //ImGui::InputFloat3("input float3", vec4a); bfs += fmt::format("\tstatic float vec4a{}[4] = {{ 0.10f, 0.20f, 0.30f, 0.44f }};\n",obj.id); bfs += fmt::format("\tImGui::InputFloat3(\"{}\", vec4a{});\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "dragint") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static int i1 = 50; //ImGui::DragInt("drag int", &i1, 1); bfs += fmt::format("\tstatic int i1{0} = 50;\n",obj.id); bfs += fmt::format("\tImGui::DragInt(\"{}\", &i1{}, 1);\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "dragint100") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static int i2 = 42; //ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp); bfs += fmt::format("\tstatic int i2{0} = 42;\n",obj.id); bfs += fmt::format("\tImGui::DragInt(\"{}\", &i2{}, 1, 0, 100, \"%d%%\", ImGuiSliderFlags_AlwaysClamp);\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "dragfloat") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float f1 = 1.00f; //ImGui::DragFloat("drag float", &f1, 0.005f); bfs += fmt::format("\tstatic float f1{0} = 1.00f;\n",obj.id); bfs += fmt::format("\tImGui::DragFloat(\"{}\", &f1{}, 0.005f);\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "dragfloatsmall") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float f2 = 0.0067f; //ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); bfs += fmt::format("\tstatic float f2{0} = 0.0067f;\n",obj.id); bfs += fmt::format("\tImGui::DragFloat(\"{}\", &f2{}, 0.0001f, 0.0f, 0.0f, \"%.06f ns\");\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "sliderint") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static int i1 = 0; //ImGui::SliderInt("slider int", &i1, -1, 3); bfs += fmt::format("\tstatic int i1{0} = 0;\n",obj.id); bfs += fmt::format("\tImGui::SliderInt(\"{}\", &i1{}, -1, 3);\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "sliderfloat") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float f1 = 0.123f; //ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); bfs += fmt::format("\tstatic float f1{0} = 0.123f;\n",obj.id); bfs += fmt::format("\tImGui::SliderFloat(\"{}\", &f1{}, 0.0f, 1.0f, \"ratio = %.3f\");\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "sliderfloatlog") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float f2 = 0.0f; //ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic); bfs += fmt::format("\tstatic float f2{0} = 0.0f;\n",obj.id); bfs += fmt::format("\tImGui::SliderFloat(\"{}\", &f2{}, -10.0f, 10.0f, \"%.4f\", ImGuiSliderFlags_Logarithmic);\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "sliderangle") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float angle = 0.0f; //ImGui::SliderAngle("slider angle", &angle); bfs += fmt::format("\tstatic float angle{0} = 0.0f;\n",obj.id); bfs += fmt::format("\tImGui::SliderAngle(\"{}\", &angle{});\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "color1") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } //static float col1[3] = {1.0f, 0.0f, 0.2f}; //ImGui::ColorEdit3(label.c_str(), col1, ImGuiColorEditFlags_NoInputs); bfs += fmt::format("\tstatic float col1{0}[3] = {{1.0f, 0.0f, 0.2f}};\n",obj.id); bfs += fmt::format("\tImGui::ColorEdit3(\"{}\", col1{}, ImGuiColorEditFlags_NoInputs);\n\n",obj.label,obj.id); } if (obj.type == "color2") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float col2[3] = {1.0f, 0.0f, 0.2f}; //ImGui::ColorEdit3(label.c_str(), col2); bfs += fmt::format("\tstatic float col2{0}[3] = {{1.0f, 0.0f, 0.2f}};\n",obj.id); bfs += fmt::format("\tImGui::ColorEdit3(\"{}\", col2{});\n\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "color3") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float col3[4] = {0.4f, 0.7f, 0.0f, 0.5f}; //ImGui::ColorEdit4(label.c_str(), col3); bfs += fmt::format("\tstatic float col3{0}[4] = {{0.4f, 0.7f, 0.0f, 0.5f}};\n",obj.id); bfs += fmt::format("\tImGui::ColorEdit4(\"{}\", col3{});\n\n",obj.label,obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } if (obj.type == "sameline") { if (staticlayout) { bfs += "\tImGui::SameLine();\n\n"; } } if (obj.type == "newline") { if (staticlayout) { bfs += "\tImGui::NewLine();\n\n"; } } if (obj.type == "separator") { if (staticlayout) { bfs += "\tImGui::Separator();\n\n"; } } if (obj.type == "progressbar") { if (!staticlayout) { bfs += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",obj.pos.x,obj.pos.y); } bfs += fmt::format("\tImGui::PushItemWidth({});\n",obj.width); //static float progress = 0.0f; //ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f)); bfs += fmt::format("\tstatic float progress{} = 0.0f;\n",obj.id); bfs += fmt::format("\tImGui::ProgressBar(progress{}, ImVec2(0.0f, 0.0f));\n",obj.id); bfs += "\tImGui::PopItemWidth();\n\n"; } output->append(bfs); } void ImStudio::GenerateCode(std::string* output, BufferWindow* bw) { #ifdef __EMSCRIPTEN__ *output = "/*\nGENERATED CODE | READ-ONLY\nCopy by clicking the above button\n*/\n\n"; #else *output = "/*\nGENERATED CODE | READ-ONLY\nYou can directly copy from here, or from File > Export to clipboard\n*/\n\n"; #endif *output += "static bool window = true;\n"; *output += fmt::format("ImGui::SetNextWindowSize(ImVec2({},{}));\n", bw->size.x, bw->size.y); *output += "//!! You might want to use these ^^ values in the OS window instead, and add the ImGuiWindowFlags_NoTitleBar flag in the ImGui window !!\n\n"; *output += "if (ImGui::Begin(\"window_name\", &window))\n{\n\n"; for (auto i = bw->objects.begin(); i != bw->objects.end(); ++i) { Object &o = *i; if (o.type != "child") { Recreate(o, output, bw->staticlayout); } else { if (!bw->staticlayout) { *output += fmt::format("\tImGui::SetCursorPos(ImVec2({},{}));\n",o.child.freerect.Min.x,o.child.freerect.Min.y); } *output += fmt::format("\tImGui::BeginChild({}, ImVec2({},{}), {});\n\n", o.child.id, o.child.freerect.GetSize().x, o.child.freerect.GetSize().y, o.child.border); for (auto i = o.child.objects.begin(); i != o.child.objects.end(); ++i) { BaseObject &cw = *i;// child widget Recreate(cw, output, bw->staticlayout); } *output += "\tImGui::EndChild();\n\n"; } } *output += "\n\tImGui::End();\n}\n"; *output += "\n/*\nReminder: some widgets may have the same label \"##\" (if you didn't change it), and can lead to undesired ID collisions.\nMore info: https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-about-the-id-stack-system\n*/\n"; ImGui::InputTextMultiline("##source", output, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 64), ImGuiInputTextFlags_ReadOnly); }
41.620155
248
0.517787
[ "object" ]
eb35d1942d0e9fffce97dff440e5dd6998c34809
8,556
cpp
C++
engine/parser.cpp
CarlaCruz146/Solar-System
8ecacbaaaf8f964f10ea66bb20777cab17362f65
[ "MIT" ]
null
null
null
engine/parser.cpp
CarlaCruz146/Solar-System
8ecacbaaaf8f964f10ea66bb20777cab17362f65
[ "MIT" ]
null
null
null
engine/parser.cpp
CarlaCruz146/Solar-System
8ecacbaaaf8f964f10ea66bb20777cab17362f65
[ "MIT" ]
null
null
null
#include "headers/parser.h" #include "headers/Point.h" int readPointsFile(string filename, vector<Point*> *points, vector<Point*> *normalList, vector<float> *textureList){ string l, t; int index,j; ifstream file(filename); string token; vector<float>tokens; int i; if (!file.is_open()) { cout << "Unable to open file: " << filename << "." << endl; return -1; } else { index = 0; getline(file, l); int numVertex = atoi(l.c_str()); for(int i=0; i < numVertex; i++){ getline(file,l); stringstream ss(l); j = 0; while(j < 3 && getline(ss,token,',')) { tokens.push_back(stof(token)); j++; } Point *p = new Point(tokens[index++],tokens[index++],tokens[index++]); points->push_back(p); } index = 0; getline(file, l); int numNormals = atoi(l.c_str()); for(int i=0; i < numNormals; i++){ getline(file,l); stringstream ss(l); j = 0; while(j < 3 && getline(ss,token,',')) { tokens.push_back(stof(token)); j++; } Point *p = new Point(tokens[index++],tokens[index++],tokens[index++]); normalList->push_back(p); } index = 0; getline(file, l); int numTexture = atoi(l.c_str()); for(int i=0; i < numTexture; i++){ getline(file,l); stringstream ss(l); j = 0; while(j < 2 && getline(ss,token,',')) { tokens.push_back(stof(token)); j++; } textureList->push_back(token[index++]); textureList->push_back(token[index++]); } file.close(); } return 0; } Group* loadXMLfile(string filename) { Group* group = nullptr; XMLDocument xmlDoc; XMLNode *pRoot; XMLElement *pElement; string fileDir = "../../files/" + filename; XMLError eResult = xmlDoc.LoadFile(fileDir.c_str()); if (eResult == XML_SUCCESS) { pRoot = xmlDoc.FirstChild(); if (pRoot != nullptr) { group = new Group(); pElement = pRoot->FirstChildElement("group"); parseGroup(group,pElement); } } else { cout << "Unable to open file: " << filename << "." << endl; } return group; } void parseRotate (Group* group, XMLElement* element) { float angle = 0, x = 0, y = 0, z = 0; string type = "rotation"; Transformation *t; if(element->Attribute("time")) { float time = stof(element->Attribute("time")); angle = 360 / (time * 1000); type = "rotateTime"; } else if(element->Attribute("angle")) angle = stof(element->Attribute("angle")); if(element->Attribute("X")) x = stof(element->Attribute("X")); if(element->Attribute("Y")) y = stof(element->Attribute("Y")); if(element->Attribute("Z")) z = stof(element->Attribute("Z")); t = new Transformation(type,angle,x,y,z); group->addTransformation(t); } void parseTranslate (Group *group, XMLElement *element) { float x=0, y=0, z=0, time = 0; vector<Point*> cPoints; Transformation *t; if (element->Attribute("time")) { bool deriv = false; if (element->Attribute("derivative")) deriv = (stoi(element->Attribute("derivative"))== 1) ? true : false; time = stof(element->Attribute("time")); time = 1 / (time * 1000); element = element->FirstChildElement("point"); while (element != nullptr) { x = stof(element->Attribute("X")); y = stof(element->Attribute("Y")); z = stof(element->Attribute("Z")); Point *p = new Point(x,y,z); cPoints.push_back(p); element = element->NextSiblingElement("point"); } t = new Transformation(time,cPoints,deriv,"translateTime"); group->addTransformation(t); } else{ if(element->Attribute("X")) x = stof(element->Attribute("X")); if(element->Attribute("Y")) y = stof(element->Attribute("Y")); if(element->Attribute("Z")) z = stof(element->Attribute("Z")); t = new Transformation("translate",0,x,y,z); group->addTransformation(t); } } void parseScale (Group *group, XMLElement *element){ float x=1, y=1, z=1; string type = "scale"; Transformation *t; if(element->Attribute("X")) x = stof(element->Attribute("X")); if(element->Attribute("Y")) y = stof(element->Attribute("Y")); if(element->Attribute("Z")) z = stof(element->Attribute("Z")); t = new Transformation(type,0,x,y,z); group->addTransformation(t); } void parseColour (Group *group, XMLElement *element){ float x=1, y=1, z=1; string type = "colour"; Transformation *t; if(element->Attribute("R")) x = stof(element->Attribute("R")); if(element->Attribute("G")) y = stof(element->Attribute("G")); if(element->Attribute("B")) z = stof(element->Attribute("B")); t = new Transformation(type,0,x,y,z); group->addTransformation(t); } void parseModels (Group *group, XMLElement *element) { string file; vector<Shape*> shapes; element = element->FirstChildElement("model"); if (element == nullptr) { cout << "XML error: Models are not available!" << endl; return; } while (element != nullptr) { file = element->Attribute("file"); string fileDir = "../../files/" + file; if(!file.empty()) { vector<Point*> points; readPointsFile(fileDir, &points); if (points.size()) { Shape *shape = new Shape(points); shapes.push_back(shape); } } element = element->NextSiblingElement("model"); } if (shapes.size()) group->setShapes(shapes); } void parseGroup (Group *group, XMLElement *gElement) { XMLElement *element = gElement->FirstChildElement(); while (element) { if (strcmp(element->Name(),"translate") == 0) parseTranslate(group,element); else if (strcmp(element->Name(),"scale") == 0) parseScale(group,element); else if (strcmp(element->Name(),"rotate") == 0) parseRotate(group,element); else if (strcmp(element->Name(),"models") == 0) parseModels(group, element); else if (strcmp(element->Name(),"colour") == 0) parseColour(group, element); else if (strcmp(element->Name(),"group") == 0) { Group *child = new Group(); group->addGroup(child); parseGroup(child,element); } element = element->NextSiblingElement(); } } void parseMaterial(Shape* shape, XMLElement* element) { Point* diffuse = new Point(0.0, 0.0, 0.0); Point* ambient = new Point(0.0, 0.0, 0.0); Point* specular = new Point(0.0, 0.0, 0.0); Point* emission = new Point(0.0, 0.0, 0.0); // Diffuse if(element->Attribute("diffR")) diffuse->setX(atof(element->Attribute("diffR"))); if(element->Attribute("diffG")) diffuse->setY(atof(element->Attribute("diffG"))); if(element->Attribute("diffB")) diffuse->setZ(atof(element->Attribute("diffB"))); // Ambient if(element->Attribute("ambR")) ambient->setX(atof(element->Attribute("ambR"))); if(element->Attribute("ambG")) ambient->setY(atof(element->Attribute("ambG"))); if(element->Attribute("ambB")) ambient->setZ(atof(element->Attribute("ambB"))); // Specular if(element->Attribute("specR")) specular->setX(atof(element->Attribute("specR"))); if(element->Attribute("specG")) specular->setY(atof(element->Attribute("specG"))); if(element->Attribute("specB")) specular->setZ(atof(element->Attribute("specB"))); // Emission if(element->Attribute("emiR")) emission->setX(atof(element->Attribute("emiR"))); if(element->Attribute("emiG")) emission->setY(atof(element->Attribute("emiG"))); if(element->Attribute("emiB")) emission->setZ(atof(element->Attribute("emiB"))); Material* m = new Material(diffuse, ambient, specular, emission); shape->setParseMat(m); }
27.248408
116
0.543245
[ "shape", "vector", "model" ]
eb36413844cbb3af3da465c6e830edc19f7162fc
716
cpp
C++
Leetcode/0360. Sort Transformed Array/0360.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0360. Sort Transformed Array/0360.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0360. Sort Transformed Array/0360.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) { const int n = nums.size(); const bool upward = a > 0; vector<int> ans(n); vector<int> quad; for (const int num : nums) quad.push_back(f(num, a, b, c)); int i = upward ? n - 1 : 0; for (int l = 0, r = n - 1; l <= r;) if (upward) // maximum in both ends ans[i--] = quad[l] > quad[r] ? quad[l++] : quad[r--]; else // minimum in both ends ans[i++] = quad[l] < quad[r] ? quad[l++] : quad[r--]; return ans; } private: // the concavity of f only depends on a's sign int f(int x, int a, int b, int c) { return (a * x + b) * x + c; } };
25.571429
76
0.519553
[ "vector" ]
eb3b7411b7297d521b4e040308241fdc3d25830e
7,591
cpp
C++
Source/ImGui/Private/ImGuiContextProxy.cpp
melchior-haven/UnrealImGui
237d61b93a405852357bb8b4bbdeddbaa2ae4686
[ "MIT" ]
1
2022-01-14T00:45:39.000Z
2022-01-14T00:45:39.000Z
Source/ImGui/Private/ImGuiContextProxy.cpp
melchior-haven/UnrealImGui
237d61b93a405852357bb8b4bbdeddbaa2ae4686
[ "MIT" ]
null
null
null
Source/ImGui/Private/ImGuiContextProxy.cpp
melchior-haven/UnrealImGui
237d61b93a405852357bb8b4bbdeddbaa2ae4686
[ "MIT" ]
null
null
null
// Distributed under the MIT License (MIT) (see accompanying LICENSE file) #include "ImGuiContextProxy.h" #include "ImGuiDelegatesContainer.h" #include "ImGuiImplementation.h" #include "ImGuiInteroperability.h" #include "Utilities/Arrays.h" #include "VersionCompatibility.h" #include <GenericPlatform/GenericPlatformFile.h> #include <Misc/Paths.h> static constexpr float DEFAULT_CANVAS_WIDTH = 3840.f; static constexpr float DEFAULT_CANVAS_HEIGHT = 2160.f; namespace { FString GetSaveDirectory() { #if ENGINE_COMPATIBILITY_LEGACY_SAVED_DIR const FString SavedDir = FPaths::GameSavedDir(); #else const FString SavedDir = FPaths::ProjectSavedDir(); #endif FString Directory = FPaths::Combine(*SavedDir, TEXT("ImGui")); // Make sure that directory is created. IPlatformFile::GetPlatformPhysical().CreateDirectory(*Directory); return Directory; } FString GetIniFile(const FString& Name) { static FString SaveDirectory = GetSaveDirectory(); return FPaths::Combine(SaveDirectory, Name + TEXT(".ini")); } struct FGuardCurrentContext { FGuardCurrentContext() : OldContext(ImGui::GetCurrentContext()) { } ~FGuardCurrentContext() { if (bRestore) { ImGui::SetCurrentContext(OldContext); } } FGuardCurrentContext(FGuardCurrentContext&& Other) : OldContext(MoveTemp(Other.OldContext)) { Other.bRestore = false; } FGuardCurrentContext& operator=(FGuardCurrentContext&&) = delete; FGuardCurrentContext(const FGuardCurrentContext&) = delete; FGuardCurrentContext& operator=(const FGuardCurrentContext&) = delete; private: ImGuiContext* OldContext = nullptr; bool bRestore = true; }; } FImGuiContextProxy::FImGuiContextProxy(const FString& InName, int32 InContextIndex, ImFontAtlas* InFontAtlas, float InDPIScale) : Name(InName) , ContextIndex(InContextIndex) , IniFilename(TCHAR_TO_ANSI(*GetIniFile(InName))) { // Create context. Context = ImGui::CreateContext(InFontAtlas); // Set this context in ImGui for initialization (any allocations will be tracked in this context). SetAsCurrent(); // Start initialization. ImGuiIO& IO = ImGui::GetIO(); // Set session data storage. IO.IniFilename = IniFilename.c_str(); // Activate Docking feature // Is it the right place? IO.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Start with the default canvas size. ResetDisplaySize(); IO.DisplaySize = { DisplaySize.X, DisplaySize.Y }; // Set the initial DPI scale. SetDPIScale(InDPIScale); // Initialize key mapping, so context can correctly interpret input state. ImGuiInterops::SetUnrealKeyMap(IO); // Begin frame to complete context initialization (this is to avoid problems with other systems calling to ImGui // during startup). BeginFrame(); } FImGuiContextProxy::~FImGuiContextProxy() { if (Context) { // It seems that to properly shutdown context we need to set it as the current one (at least in this framework // version), even though we can pass it to the destroy function. SetAsCurrent(); // Save context data and destroy. ImGui::DestroyContext(Context); } } void FImGuiContextProxy::ResetDisplaySize() { DisplaySize = { DEFAULT_CANVAS_WIDTH, DEFAULT_CANVAS_HEIGHT }; } void FImGuiContextProxy::SetDPIScale(float Scale) { if (DPIScale != Scale) { DPIScale = Scale; ImGuiStyle NewStyle = ImGuiStyle(); NewStyle.ScaleAllSizes(Scale); FGuardCurrentContext GuardContext; SetAsCurrent(); ImGui::GetStyle() = MoveTemp(NewStyle); } } void FImGuiContextProxy::DrawEarlyDebug() { if (bIsFrameStarted && !bIsDrawEarlyDebugCalled) { bIsDrawEarlyDebugCalled = true; SetAsCurrent(); // Delegates called in order specified in FImGuiDelegates. BroadcastMultiContextEarlyDebug(); BroadcastWorldEarlyDebug(); } } void FImGuiContextProxy::DrawDebug() { if (bIsFrameStarted && !bIsDrawDebugCalled) { bIsDrawDebugCalled = true; // Make sure that early debug is always called first to guarantee order specified in FImGuiDelegates. DrawEarlyDebug(); SetAsCurrent(); // Delegates called in order specified in FImGuiDelegates. BroadcastWorldDebug(); BroadcastMultiContextDebug(); } } void FImGuiContextProxy::Tick(float DeltaSeconds) { // Making sure that we tick only once per frame. if (LastFrameNumber < GFrameNumber) { LastFrameNumber = GFrameNumber; SetAsCurrent(); if (bIsFrameStarted) { // Make sure that draw events are called before the end of the frame. DrawDebug(); // Ending frame will produce render output that we capture and store for later use. This also puts context to // state in which it does not allow to draw controls, so we want to immediately start a new frame. EndFrame(); } // Update context information (some data need to be collected before starting a new frame while some other data // may need to be collected after). bHasActiveItem = ImGui::IsAnyItemActive(); MouseCursor = ImGuiInterops::ToSlateMouseCursor(ImGui::GetMouseCursor()); // Begin a new frame and set the context back to a state in which it allows to draw controls. BeginFrame(DeltaSeconds); // Update remaining context information. bWantsMouseCapture = ImGui::GetIO().WantCaptureMouse; } } void FImGuiContextProxy::BeginFrame(float DeltaTime) { if (!bIsFrameStarted) { ImGuiIO& IO = ImGui::GetIO(); IO.DeltaTime = DeltaTime; ImGuiInterops::CopyInput(IO, InputState); InputState.ClearUpdateState(); IO.DisplaySize = { DisplaySize.X, DisplaySize.Y }; ImGui::NewFrame(); bIsFrameStarted = true; bIsDrawEarlyDebugCalled = false; bIsDrawDebugCalled = false; } } void FImGuiContextProxy::EndFrame() { if (bIsFrameStarted) { // Prepare draw data (after this call we cannot draw to this context until we start a new frame). ImGui::Render(); // Update our draw data, so we can use them later during Slate rendering while ImGui is in the middle of the // next frame. UpdateDrawData(ImGui::GetDrawData()); bIsFrameStarted = false; } } void FImGuiContextProxy::UpdateDrawData(ImDrawData* DrawData) { if (DrawData && DrawData->CmdListsCount > 0) { DrawLists.SetNum(DrawData->CmdListsCount, false); for (int Index = 0; Index < DrawData->CmdListsCount; Index++) { DrawLists[Index].TransferDrawData(*DrawData->CmdLists[Index]); } } else { // If we are not rendering then this might be a good moment to empty the array. DrawLists.Empty(); } } void FImGuiContextProxy::BroadcastWorldEarlyDebug() { if (ContextIndex != Utilities::INVALID_CONTEXT_INDEX) { FSimpleMulticastDelegate& WorldEarlyDebugEvent = FImGuiDelegatesContainer::Get().OnWorldEarlyDebug(ContextIndex); if (WorldEarlyDebugEvent.IsBound()) { WorldEarlyDebugEvent.Broadcast(); } } } void FImGuiContextProxy::BroadcastMultiContextEarlyDebug() { FSimpleMulticastDelegate& MultiContextEarlyDebugEvent = FImGuiDelegatesContainer::Get().OnMultiContextEarlyDebug(); if (MultiContextEarlyDebugEvent.IsBound()) { MultiContextEarlyDebugEvent.Broadcast(); } } void FImGuiContextProxy::BroadcastWorldDebug() { if (DrawEvent.IsBound()) { DrawEvent.Broadcast(); } if (ContextIndex != Utilities::INVALID_CONTEXT_INDEX) { FSimpleMulticastDelegate& WorldDebugEvent = FImGuiDelegatesContainer::Get().OnWorldDebug(ContextIndex); if (WorldDebugEvent.IsBound()) { WorldDebugEvent.Broadcast(); } } } void FImGuiContextProxy::BroadcastMultiContextDebug() { FSimpleMulticastDelegate& MultiContextDebugEvent = FImGuiDelegatesContainer::Get().OnMultiContextDebug(); if (MultiContextDebugEvent.IsBound()) { MultiContextDebugEvent.Broadcast(); } }
24.726384
127
0.747859
[ "render" ]
eb406ef931e223ea6c4301eb604d174bfc6af214
5,218
hpp
C++
include/JsonLexer.hpp
alevarn/json-parser
ffef66c6ade70b15ccea023db58d060ff62fae97
[ "MIT" ]
1
2020-07-06T20:36:48.000Z
2020-07-06T20:36:48.000Z
include/JsonLexer.hpp
alevarn/json-parser
ffef66c6ade70b15ccea023db58d060ff62fae97
[ "MIT" ]
1
2020-09-03T14:03:35.000Z
2020-09-04T14:33:08.000Z
include/JsonLexer.hpp
alevarn/json-parser
ffef66c6ade70b15ccea023db58d060ff62fae97
[ "MIT" ]
null
null
null
/* The MIT License (MIT) Copyright (c) 2020 Marcus Alevärn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef JSON_LEXER_HPP #define JSON_LEXER_HPP #include <string> namespace json { /** * A list of all valid token types that can be found in JSON text. */ enum class JsonTokenType { BeginArray, // [ BeginObject, // { EndArray, // ] EndObject, // } NameSeparator, // : ValueSeparator, // , False, // false True, // true Null, // null Number, String, EndOfFile }; /** * A JsonToken object will store the token type and a string value. */ struct JsonToken { JsonTokenType type; // This field is used when we find a number or string in the JSON text. std::string value; JsonToken(JsonTokenType type); JsonToken(JsonTokenType type, std::string &&value); }; /** * A class for doing lexical analysis on JSON text. */ class JsonLexer { public: /** * Returns the next token from the input stream. */ static JsonToken nextToken(std::istream &input); private: /** * Will read characters from the stream and make sure they match the desired string that was passed in with this method. * If they don't match a std::runtime_error expection will be thrown. */ static void read(std::istream &input, const std::string &str); /** * Will read a number from the stream and return it as a string. * The number must satisfy the following ABNF rules (taken from RFC 8259): * * number = [ minus ] int [ frac ] [ exp ] * decimal-point = %x2E ; . * digit1-9 = %x31-39 ; 1-9 * e = %x65 / %x45 ; e E * exp = e [ minus / plus ] 1*DIGIT * frac = decimal-point 1*DIGIT * int = zero / ( digit1-9 *DIGIT ) * minus = %x2D ; - * plus = %x2B ; + * zero = %x30 ; 0 * * Upon violation a std::runtime_error will be thrown. */ static std::string readNumber(std::istream &input, char previous); /** * Will read digits from the input stream and returns them as a string. */ static std::string readDigits(std::istream &input); /** * Will read a fraction. */ static std::string readFraction(std::istream &input); /** * Will read an exponent. */ static std::string readExponent(std::istream &input); /** * Will read a "json-string" from the stream and return it as a string. * The "json-string" must satisfy the following ABNF rules (taken from RFC 8259): * * string = quotation-mark *char quotation-mark * char = unescaped / * escape ( * %x22 / ; " quotation mark U+0022 * %x5C / ; \ reverse solidus U+005C * %x2F / ; / solidus U+002F * %x62 / ; b backspace U+0008 * %x66 / ; f form feed U+000C * %x6E / ; n line feed U+000A * %x72 / ; r carriage return U+000D * %x74 / ; t tab U+0009 * %x75 4HEXDIG ) ; uXXXX U+XXXX * * escape = %x5C ; \ * quotation-mark = %x22 ; " * unescaped = %x20-21 / %x23-5B / %x5D-10FFFF * * Upon violation a std::runtime_error will be thrown. */ static std::string readString(std::istream &input); /** * Will read an escape sequence and unescape it. */ static std::string readEscapeSequence(std::istream &input); /** * Will read an unicode escape sequence for exampe \u2661. */ static std::string readUnicodeEscapeSequence(std::istream &input); }; } // namespace json #endif
33.883117
128
0.555385
[ "object" ]
eb426d593611a896df893351f44b7f7e06eb781d
8,708
cpp
C++
src/common/core/FramebufferCreator.cpp
congard/algine
81b532b503877e283bd28d441d7e87dcb62aa99c
[ "MIT" ]
12
2019-04-26T14:32:41.000Z
2021-12-30T19:08:05.000Z
src/common/core/FramebufferCreator.cpp
congard/algine
81b532b503877e283bd28d441d7e87dcb62aa99c
[ "MIT" ]
null
null
null
src/common/core/FramebufferCreator.cpp
congard/algine
81b532b503877e283bd28d441d7e87dcb62aa99c
[ "MIT" ]
4
2019-11-01T10:24:40.000Z
2021-03-05T18:01:22.000Z
#include <algine/core/FramebufferCreator.h> #include <algine/core/JsonHelper.h> #include <algine/core/PtrMaker.h> #include "FramebufferConfigTools.h" #include "internal/PublicObjectTools.h" using namespace std; using namespace nlohmann; using namespace algine::internal; namespace algine { namespace Config { constant(Attachment, "attachment"); constant(Attachments, "attachments"); constant(OutputLists, "outputLists"); } void FramebufferCreator::setOutputLists(const vector<OutputList> &lists) { m_outputLists = {}; for (const auto & list : lists) { m_outputLists.emplace_back(list); } } void FramebufferCreator::setOutputLists(const vector<OutputListCreator> &lists) { m_outputLists = lists; } void FramebufferCreator::addOutputList(const OutputListCreator &list) { m_outputLists.emplace_back(list); } const vector<OutputListCreator>& FramebufferCreator::getOutputLists() const { return m_outputLists; } FramebufferCreator::RenderbufferAttachments& FramebufferCreator::renderbufferAttachments() { return m_renderbufferAttachments; } FramebufferCreator::Texture2DAttachments& FramebufferCreator::texture2DAttachments() { return m_texture2DAttachments; } FramebufferCreator::TextureCubeAttachments& FramebufferCreator::textureCubeAttachments() { return m_textureCubeAttachments; } FramebufferPtr FramebufferCreator::get() { return PublicObjectTools::getPtr<FramebufferPtr>(this); } template<typename T> struct type_holder { using type = T; }; #define type_holder_get(holder) typename decltype(holder)::type FramebufferPtr FramebufferCreator::create() { FramebufferPtr framebuffer = PtrMaker::make(); framebuffer->setName(m_name); // init output lists framebuffer->removeOutputLists(); for (const auto & list : m_outputLists) { framebuffer->addOutputList(list.create()); } // attach objects auto attachAll = [&](auto &attachments, auto type) { auto attach = [&](const auto &ptr, Attachment attachment) { using Type = PtrMaker::PtrType<remove_reference_t<decltype(ptr)>>; if constexpr (is_same_v<Type, Renderbuffer>) { framebuffer->attachRenderbuffer(ptr, attachment); } if constexpr (is_same_v<Type, Texture2D> || is_same_v<Type, TextureCube>) { framebuffer->attachTexture(ptr, attachment); } }; auto attachByPath = [&](const string &path, Attachment attachment, auto creatorType) { using TCreator = type_holder_get(creatorType); TCreator creator; creator.setIOSystem(io()); creator.setWorkingDirectory(m_workingDirectory); creator.importFromFile(path); attach(creator.get(), attachment); }; auto attachByName = [&](const string &name, Attachment attachment, auto objType) { using Type = type_holder_get(objType); // try to find object by name auto ptr = Type::getByName(name); if (ptr == nullptr) throw runtime_error("Public Object '" + name + "' does not exist"); // attach object attach(ptr, attachment); }; // attach using creators, paths and names using T = typename std::remove_reference_t<decltype(attachments)>::type; for (auto &p : attachments.value) { auto &v = p.second; if (auto path = std::get_if<Path>(&v); path) { attachByPath(path->str, p.first, type_holder<T>()); } else if (auto name = std::get_if<Name>(&v); name) { attachByName(name->str, p.first, type); } else if (auto creator = std::get_if<T>(&v); creator) { creator->setIOSystem(io()); attach(creator->get(), p.first); } } }; framebuffer->bind(); attachAll(m_renderbufferAttachments, type_holder<Renderbuffer>()); attachAll(m_texture2DAttachments, type_holder<Texture2D>()); attachAll(m_textureCubeAttachments, type_holder<TextureCube>()); framebuffer->update(); framebuffer->unbind(); PublicObjectTools::postCreateAccessOp("Framebuffer", this, framebuffer); return framebuffer; } template<typename T> inline string typeName() { using TPlain = remove_reference_t<T>; if constexpr (is_same_v<TPlain, FramebufferCreator::RenderbufferAttachments>) return Config::Renderbuffer; if constexpr (is_same_v<TPlain, FramebufferCreator::Texture2DAttachments>) return Config::Texture2D; if constexpr (is_same_v<TPlain, FramebufferCreator::TextureCubeAttachments>) return Config::TextureCube; throw invalid_argument("Invalid template type"); } void FramebufferCreator::import(const JsonHelper &jsonHelper) { const json &config = jsonHelper.json; auto importAttachments = [&](auto &obj) { const json &attachments = config[Config::Attachments]; for (const auto & item : attachments) { if (item[Config::Type] == typeName<decltype(obj)>()) { auto attachment = Config::stringToAttachment(item[Config::Attachment]); if (item.contains(Config::Dump)) { using TCreator = typename std::remove_reference_t<decltype(obj)>::type; TCreator creator; creator.setWorkingDirectory(m_workingDirectory); creator.import(item[Config::Dump]); obj.add(creator, attachment); } else if (item.contains(Config::Path)) { obj.addPath(item[Config::Path], attachment); } else if (item.contains(Config::Name)) { obj.addName(item[Config::Name], attachment); } } } }; // load XXXAttachments if (config.contains(Config::Attachments)) { importAttachments(m_renderbufferAttachments); importAttachments(m_texture2DAttachments); importAttachments(m_textureCubeAttachments); } // load output lists if (config.contains(Config::OutputLists)) { for (const auto & list : config[Config::OutputLists]) { OutputListCreator outputListCreator; outputListCreator.import(list); m_outputLists.emplace_back(outputListCreator); } } Creator::import(jsonHelper); } JsonHelper FramebufferCreator::dump() { json config; // write attachments { // array with attachments of all types json attachments; // dump Attachments object and append it to the attachments json auto append = [&](auto &obj) { // array with attachments of obj type json attachmentsType; auto writeBlock = [&](const string &storeMethod, const json &data, uint attachment) { json block; block[Config::Type] = typeName<decltype(obj)>(); block[Config::Attachment] = Config::attachmentToString(attachment); block[storeMethod] = data; attachmentsType.emplace_back(block); }; // Creator type using T = typename std::remove_reference_t<decltype(obj)>::type; for (auto &p : obj.value) { auto &v = p.second; if (auto path = std::get_if<Path>(&v); path) { writeBlock(Config::Path, path->str, p.first); } else if (auto name = std::get_if<Name>(&v); name) { writeBlock(Config::Name, name->str, p.first); } else if (auto creator = std::get_if<T>(&v); creator) { writeBlock(Config::Dump, creator->dump().json, p.first); } } // append to attachments if (!attachmentsType.empty()) { if (attachments.empty()) { attachments = attachmentsType; } else { attachments.insert(attachments.end(), attachmentsType.begin(), attachmentsType.end()); } } }; append(m_renderbufferAttachments); append(m_texture2DAttachments); append(m_textureCubeAttachments); if (!attachments.empty()) { config[Config::Attachments] = attachments; } } // write output lists for (auto & outputList : m_outputLists) { if (const auto &list = outputList.dump(); !list.empty()) { config[Config::OutputLists].emplace_back(list.json); } } JsonHelper result(config); result.append(Creator::dump()); return result; } }
31.781022
106
0.618282
[ "object", "vector" ]
eb4ce3c21dfcfe4c52ca248e35e0b1aceb29850f
9,187
cpp
C++
PyDK/DCCamera.cpp
hhg128/DKGL
c61bc6546ac5655da97462cc532a9034ba08516d
[ "PSF-2.0", "BSD-3-Clause" ]
14
2015-09-12T01:32:05.000Z
2021-10-13T02:52:53.000Z
PyDK/DCCamera.cpp
hhg128/DKGL
c61bc6546ac5655da97462cc532a9034ba08516d
[ "PSF-2.0", "BSD-3-Clause" ]
null
null
null
PyDK/DCCamera.cpp
hhg128/DKGL
c61bc6546ac5655da97462cc532a9034ba08516d
[ "PSF-2.0", "BSD-3-Clause" ]
3
2015-11-10T03:12:49.000Z
2018-10-15T15:38:31.000Z
#include <Python.h> #include <structmember.h> #include <datetime.h> #include <DK/DK.h> #include "DCObject.h" struct DCCamera { PyObject_HEAD DKObject<DKCamera> camera; }; static PyObject* DCCameraNew(PyTypeObject* type, PyObject* args, PyObject* kwds) { DCCamera* self = (DCCamera*)type->tp_alloc(type, 0); if (self) { new (&self->camera) DKObject<DKCamera>(); return (PyObject*)self; } return NULL; } static int DCCameraInit(DCCamera *self, PyObject *args, PyObject *kwds) { if (self->camera == NULL) { self->camera = DKObject<DKCamera>::New(); DCObjectSetAddress(self->camera, (PyObject*)self); } return 0; } static void DCCameraDealloc(DCCamera* self) { if (self->camera) { DCObjectSetAddress(self->camera, NULL); self->camera = NULL; } self->camera.~DKObject<DKCamera>(); Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject* DCCameraSetView(DCCamera* self, PyObject* args) { DCOBJECT_VALIDATE(self->camera, NULL); DKVector3 pos, dir, up; if (!PyArg_ParseTuple(args, "O&O&O&", &DCVector3Converter, &pos, &DCVector3Converter, &dir, &DCVector3Converter, &up)) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "argument must be three Vector3 objects."); return NULL; } self->camera->SetView(pos, dir, up); Py_RETURN_NONE; } static PyObject* DCCameraSetPerspective(DCCamera* self, PyObject* args) { DCOBJECT_VALIDATE(self->camera, NULL); float fov, aspect, nz, fz; if (!PyArg_ParseTuple(args, "ffff", &fov, &aspect, &nz, &fz)) return NULL; if (fov <= 0 || aspect <= 0 || nz <= 0 || fz <= 0) { PyErr_SetString(PyExc_ValueError, "all arguments must be greater than zero."); return NULL; } if (nz >= fz) { PyErr_SetString(PyExc_ValueError, "fourth argument must be greater than third argument."); return NULL; } self->camera->SetPerspective(fov, aspect, nz, fz); Py_RETURN_NONE; } static PyObject* DCCameraSetOrthographic(DCCamera* self, PyObject* args) { DCOBJECT_VALIDATE(self->camera, NULL); float width, height, nz, fz; if (!PyArg_ParseTuple(args, "ffff", &width, &height, &nz, &fz)) return NULL; if (width <= 0) { PyErr_SetString(PyExc_ValueError, "first arguments must be greater than zero."); return NULL; } if (height <= 0) { PyErr_SetString(PyExc_ValueError, "second arguments must be greater than zero."); return NULL; } if (nz >= fz) { PyErr_SetString(PyExc_ValueError, "fourth argument must be greater than third argument."); return NULL; } self->camera->SetOrthographic(width, height, nz, fz); Py_RETURN_NONE; } static PyObject* DCCameraViewMatrix(DCCamera* self, PyObject*) { DCOBJECT_VALIDATE(self->camera, NULL); DKMatrix4 mat = self->camera->ViewMatrix(); return DCMatrix4FromObject(&mat); } static PyObject* DCCameraSetViewMatrix(DCCamera* self, PyObject* args) { DCOBJECT_VALIDATE(self->camera, NULL); DKMatrix4 mat; if (!PyArg_ParseTuple(args, "O&", &DCMatrix4Converter, &mat)) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "argument must be Matrix4 object."); return NULL; } self->camera->SetView(mat); Py_RETURN_NONE; } static PyObject* DCCameraProjectionMatrix(DCCamera* self, PyObject*) { DCOBJECT_VALIDATE(self->camera, NULL); DKMatrix4 mat = self->camera->ProjectionMatrix(); return DCMatrix4FromObject(&mat); } static PyObject* DCCameraSetProjectionMatrix(DCCamera* self, PyObject* args) { DCOBJECT_VALIDATE(self->camera, NULL); DKMatrix4 mat; if (!PyArg_ParseTuple(args, "O&", &DCMatrix4Converter, &mat)) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "argument must be Matrix4 object."); return NULL; } self->camera->SetProjection(mat); Py_RETURN_NONE; } static PyObject* DCCameraViewProjectionMatrix(DCCamera* self, PyObject*) { DCOBJECT_VALIDATE(self->camera, NULL); DKMatrix4 mat = self->camera->ViewProjectionMatrix(); return DCMatrix4FromObject(&mat); } static PyObject* DCCameraSetViewProjectionMatrix(DCCamera* self, PyObject* args) { DCOBJECT_VALIDATE(self->camera, NULL); DKMatrix4 v, p; if (!PyArg_ParseTuple(args, "O&O&", &DCMatrix4Converter, &v, &DCMatrix4Converter, &p)) { PyErr_Clear(); PyErr_SetString(PyExc_TypeError, "arguments must be two Matrix4 objects."); return NULL; } self->camera->SetViewProjection(v, p); Py_RETURN_NONE; } static PyObject* DCCameraPosition(DCCamera* self, PyObject*) { DCOBJECT_VALIDATE(self->camera, NULL); DKVector3 pos = self->camera->ViewPosition(); return DCVector3FromObject(&pos); } static PyObject* DCCameraDirection(DCCamera* self, PyObject*) { DCOBJECT_VALIDATE(self->camera, NULL); DKVector3 pos = self->camera->ViewDirection(); return DCVector3FromObject(&pos); } static PyObject* DCCameraUp(DCCamera* self, PyObject*) { DCOBJECT_VALIDATE(self->camera, NULL); DKVector3 pos = self->camera->ViewUp(); return DCVector3FromObject(&pos); } static PyObject* DCCameraIsPerspective(DCCamera* self, PyObject*) { DCOBJECT_VALIDATE(self->camera, NULL); if (self->camera->IsPerspective()) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyObject* DCCameraIsOrthographic(DCCamera* self, PyObject*) { DCOBJECT_VALIDATE(self->camera, NULL); if (self->camera->IsOrthographic()) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyObject* DCCameraIsPointInside(DCCamera* self, PyObject* args) { DCOBJECT_VALIDATE(self->camera, NULL); DKVector3 pt; if (!PyArg_ParseTuple(args, "O&", &DCVector3Converter, &pt)) return NULL; if (self->camera->IsPointInside(pt)) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyObject* DCCameraIsSphereInside(DCCamera* self, PyObject* args) { DCOBJECT_VALIDATE(self->camera, NULL); DKVector3 center; float radius; if (!PyArg_ParseTuple(args, "O&f", &DCVector3Converter, &center, &radius)) return NULL; if (self->camera->IsSphereInside(center, radius)){ Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyMethodDef methods[] = { { "setView", (PyCFunction)&DCCameraSetView, METH_VARARGS }, { "setPerspective", (PyCFunction)&DCCameraSetPerspective, METH_VARARGS }, { "setOrthographic", (PyCFunction)&DCCameraSetOrthographic, METH_VARARGS }, { "viewMatrix", (PyCFunction)&DCCameraViewMatrix, METH_NOARGS }, { "setViewMatrix", (PyCFunction)&DCCameraSetViewMatrix, METH_VARARGS }, { "projectionMatrix", (PyCFunction)&DCCameraProjectionMatrix, METH_NOARGS }, { "setProjectionMatrix", (PyCFunction)&DCCameraSetProjectionMatrix, METH_VARARGS }, { "viewProjectionMatrix", (PyCFunction)&DCCameraViewProjectionMatrix, METH_NOARGS }, { "setViewProjectionMatrix", (PyCFunction)&DCCameraSetViewProjectionMatrix, METH_VARARGS }, { "position", (PyCFunction)&DCCameraPosition, METH_NOARGS }, { "direction", (PyCFunction)&DCCameraDirection, METH_NOARGS }, { "up", (PyCFunction)&DCCameraUp, METH_NOARGS }, { "isPerspective", (PyCFunction)&DCCameraIsPerspective, METH_NOARGS }, { "isOrthographic", (PyCFunction)&DCCameraIsOrthographic, METH_NOARGS }, { "isPointInside", (PyCFunction)&DCCameraIsPointInside, METH_NOARGS }, { "isSphereInside", (PyCFunction)&DCCameraIsSphereInside, METH_NOARGS }, { NULL, NULL, NULL, NULL } /* Sentinel */ }; static PyTypeObject objectType = { PyVarObject_HEAD_INIT(NULL, 0) PYDK_MODULE_NAME ".Camera", /* tp_name */ sizeof(DCCamera), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)&DCCameraDealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ 0, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)&DCCameraInit, /* tp_init */ 0, /* tp_alloc */ &DCCameraNew, /* tp_new */ }; PyTypeObject* DCCameraTypeObject(void) { return &objectType; } PyObject* DCCameraFromObject(DKCamera* camera) { if (camera) { DCCamera* self = (DCCamera*)DCObjectFromAddress(camera); if (self) { Py_INCREF(self); return (PyObject*)self; } else { PyObject* args = PyTuple_New(0); PyObject* kwds = PyDict_New(); self = (DCCamera*)DCObjectCreateDefaultClass(&objectType, args, kwds); if (self) { self->camera = camera; DCObjectSetAddress(self->camera, (PyObject*)self); Py_TYPE(self)->tp_init((PyObject*)self, args, kwds); } Py_XDECREF(args); Py_XDECREF(kwds); return (PyObject*)self; } } Py_RETURN_NONE; } DKCamera* DCCameraToObject(PyObject* obj) { if (obj && PyObject_TypeCheck(obj, &objectType)) { return ((DCCamera*)obj)->camera; } return NULL; }
26.475504
92
0.686514
[ "object" ]
eb522ac6a8ea87e7f53a3fb2607c36c1da96acf0
1,551
cc
C++
project1/solutions/test_main/test_cpp_printer.cc
magic3007/AutoGrad
a04b2be5c778f6d12ca833b9bed82b5d6c80b888
[ "MIT" ]
3
2020-07-05T17:43:55.000Z
2021-10-01T14:38:57.000Z
project1/solutions/test_main/test_cpp_printer.cc
magic3007/AutoGrad
a04b2be5c778f6d12ca833b9bed82b5d6c80b888
[ "MIT" ]
null
null
null
project1/solutions/test_main/test_cpp_printer.cc
magic3007/AutoGrad
a04b2be5c778f6d12ca833b9bed82b5d6c80b888
[ "MIT" ]
null
null
null
#include "../CPPPrinter.h" #include "../parser.h" using namespace Boost::Internal; using std::pair; using std::string; using std::vector; int main(int argc, char *argv[]) { vector<pair<string, string> > texts = { {"example", "A<32, 16>[i, j] = C<32, 16>[i, j] * B<32, 16>[i, j];"}, {"case1", "A<32, 16>[i, j] = 2;"}, {"case4", "A<16, 32>[i, j] = A<16, 32>[i, j] + B<16, 32>[i, k] * C<32, 32>[k, " "j];"}, {"case5", "A<16, 32>[i, j] = A<16, 32>[i, j] + alpha<1> * (B<16, 32>[i, k] * " "C<32, 32>[k, j]); A<16, 32>[i, j] = A<16, 32>[i, j] + beta<1> * " "D<16, 32>[i, j];"}, {"case6", "A<2, 8, 5, 5>[n, k, p, q] = A<2, 8, 5, 5>[n, k, p, q] + B<2, 16, 7, " "7>[n, c, p + r, q + s] * C<8, 16, 3, 3>[k, c, r, s];"}, {"case7", "B<16, 32>[i, j] = A<32, 16>[j, i];"}, {"case10", "A<8, 8>[i, j] = (B<10, 10>[i, j] + B<10, 10>[i + 1, j] + B<10, 10>[i " "+ 2, j]) / 3;"}, {"case_extra", "A<9, 9>[i, j] = (B<10, 10>[i, j] + B<10, 10>[i + 5 + j, j] + B<10, " "10>[i // 2, j]) / 3;"}, }; for (auto &e : texts) { auto &case_name = e.first; auto &text = e.second; fprintf(stdout, "=========================================\n"); fprintf(stdout, "%s: %s\n", case_name.c_str(), text.c_str()); Group kernel = parser::ParseFromString(text, 0); // printer CPPPrinter printer; std::cout << printer.print(kernel); } return 0; }
36.928571
80
0.399097
[ "vector" ]
eb5b2d6c21eafd75c62d3160305a40b2f0b191ef
2,935
cpp
C++
all/native/vectorelements/NMLModel.cpp
ShaneCoufreur/mobile-sdk
0d99aa530d7b8a2b15064ed25d4b97c921fe6043
[ "BSD-3-Clause" ]
155
2016-10-20T08:39:13.000Z
2022-02-27T14:08:32.000Z
all/native/vectorelements/NMLModel.cpp
ShaneCoufreur/mobile-sdk
0d99aa530d7b8a2b15064ed25d4b97c921fe6043
[ "BSD-3-Clause" ]
448
2016-10-20T12:33:06.000Z
2022-03-22T14:42:58.000Z
all/native/vectorelements/NMLModel.cpp
ShaneCoufreur/mobile-sdk
0d99aa530d7b8a2b15064ed25d4b97c921fe6043
[ "BSD-3-Clause" ]
64
2016-12-05T16:04:31.000Z
2022-02-07T09:36:22.000Z
#include "NMLModel.h" #include "core/BinaryData.h" #include "components/Exceptions.h" #include "geometry/PointGeometry.h" #include "renderers/drawdatas/NMLModelDrawData.h" #include "styles/NMLModelStyle.h" #include "styles/NMLModelStyleBuilder.h" #include "utils/Const.h" #include <nml/Package.h> namespace carto { NMLModel::NMLModel(const std::shared_ptr<Billboard>& baseBillboard, const std::shared_ptr<NMLModelStyle>& style) : Billboard(baseBillboard), _rotationAxis(0, 0, 1), _scale(1), _style(style) { if (!style) { throw NullArgumentException("Null style"); } } NMLModel::NMLModel(const std::shared_ptr<Geometry>& geometry, const std::shared_ptr<NMLModelStyle>& style) : Billboard(geometry), _rotationAxis(0, 0, 1), _scale(1), _style(style) { if (!style) { throw NullArgumentException("Null style"); } } NMLModel::NMLModel(const MapPos& mapPos, const std::shared_ptr<NMLModelStyle>& style) : Billboard(mapPos), _rotationAxis(0, 0, 1), _scale(1), _style(style) { if (!style) { throw NullArgumentException("Null style"); } } NMLModel::~NMLModel() { } float NMLModel::getRotationAngle() const { return Billboard::getRotation(); } void NMLModel::setRotationAngle(float angle) { Billboard::setRotation(angle); } MapVec NMLModel::getRotationAxis() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _rotationAxis; } void NMLModel::setRotationAxis(const MapVec& axis) { { std::lock_guard<std::recursive_mutex> lock(_mutex); _rotationAxis = axis; } notifyElementChanged(); } void NMLModel::setRotation(const MapVec& axis, float angle) { { std::lock_guard<std::recursive_mutex> lock(_mutex); _rotationAxis = axis; _rotation = angle; } notifyElementChanged(); } float NMLModel::getScale() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _scale; } void NMLModel::setScale(float scale) { { std::lock_guard<std::recursive_mutex> lock(_mutex); _scale = scale; } notifyElementChanged(); } std::shared_ptr<NMLModelStyle> NMLModel::getStyle() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _style; } void NMLModel::setStyle(const std::shared_ptr<NMLModelStyle>& style) { if (!style) { throw NullArgumentException("Null style"); } { std::lock_guard<std::recursive_mutex> lock(_mutex); _style = style; } notifyElementChanged(); } }
26.441441
118
0.586371
[ "geometry" ]
eb5b68c1072a89fc37edcec3be85d86bf2d82d50
40,102
cpp
C++
src/impl/readGffFileWithEverything.cpp
illarionovaanastasia/GEAN
b81bbf45dd869ffde2833fd1eb78463d09de45cb
[ "MIT" ]
34
2019-01-17T22:47:17.000Z
2021-12-20T08:36:44.000Z
src/impl/readGffFileWithEverything.cpp
illarionovaanastasia/GEAN
b81bbf45dd869ffde2833fd1eb78463d09de45cb
[ "MIT" ]
7
2019-04-23T02:50:13.000Z
2021-05-05T07:32:46.000Z
src/impl/readGffFileWithEverything.cpp
illarionovaanastasia/GEAN
b81bbf45dd869ffde2833fd1eb78463d09de45cb
[ "MIT" ]
5
2019-03-14T23:05:46.000Z
2020-08-17T09:14:17.000Z
// // Created by Baoxing song on 08.08.18. // #include "readGffFileWithEverything.h" void readGffFileWithEveryThing (const std::string& filePath, std::map<std::string, std::vector<std::string> > & geneNameMap, std::map<std::string, Gene > & geneHashMap, std::map<std::string, Transcript> & transcriptHashMap){ std::set<std::string> cdsParentRegex; std::set<std::string> transcriptParentRegex; std::set<std::string> transcriptIdRegex; std::set<std::string> geneIdRegex; //tair10 begin cdsParentRegex.insert("Parent=([\\s\\S]*?)[;,]");//CDS cdsParentRegex.insert("Parent=([\\s\\S^,^;]*?)$");//exon transcriptParentRegex.insert("Parent=([\\s\\S]*?)[;,]"); transcriptIdRegex.insert("ID=([\\s\\S]*?)[;,]"); //geneIdRegex.insert("ID=([\\s\\S]*?)[;,;]"); geneIdRegex.insert("ID=([-_0-9:a-zA-Z.]*?)[;,]"); geneIdRegex.insert("ID=([-_0-9:a-zA-Z.]*?)$"); //melon // tair10 end //ensembl begin cdsParentRegex.insert("transcript_id\\s*\"([\\s\\S]*?)\"[;,]"); transcriptParentRegex.insert("gene_id\\s*\"([\\s\\S]*?)\"[;,]"); transcriptIdRegex.insert("transcript_id\\s*\"([\\s\\S]*?)\"[;,]"); geneIdRegex.insert("gene_id\\s*\"([\\s\\S]*?)\"[;,]"); //ensembl end /* //begin cdsParentRegex.insert("transcript_id \"([\\s\\S]*?)\"[;,]"); transcriptParentRegex.insert(""); transcriptIdRegex.insert(); geneIdRegex.insert(); end */ transcriptParentRegex.insert("Parent=([-_0-9:a-zA-Z.]*?)$"); std::set<std::string> transcriptNickNames; transcriptNickNames.insert("transcript"); transcriptNickNames.insert("pseudogenic_transcript"); transcriptNickNames.insert("mRNA"); transcriptNickNames.insert("miRNA"); transcriptNickNames.insert("tRNA"); transcriptNickNames.insert("ncRNA"); transcriptNickNames.insert("mRNA_TE_gene"); transcriptNickNames.insert("rRNA"); transcriptNickNames.insert("snoRNA"); transcriptNickNames.insert("snRNA"); transcriptNickNames.insert("lincRNA"); std::set<std::string> geneNickNames; geneNickNames.insert("gene"); geneNickNames.insert("pseudogene"); geneNickNames.insert("transposable_element_gene"); geneNickNames.insert("lincRNA_gene"); geneNickNames.insert("tRNA_gene"); /* std::set<std::string> transcriptNickNames; transcriptNickNames.insert("transcript"); transcriptNickNames.insert("pseudogenic_transcript"); transcriptNickNames.insert("mRNA"); transcriptNickNames.insert("miRNA"); transcriptNickNames.insert("tRNA"); transcriptNickNames.insert("ncRNA"); transcriptNickNames.insert("mRNA_TE_gene"); transcriptNickNames.insert("rRNA"); transcriptNickNames.insert("snoRNA"); transcriptNickNames.insert("snRNA"); transcriptNickNames.insert("lincRNA"); std::set<std::string> geneNickNames; geneNickNames.insert("gene"); geneNickNames.insert("pseudogene"); geneNickNames.insert("transposable_element_gene"); geneNickNames.insert("tRNA_gene"); geneNickNames.insert("lincRNA_gene"); geneNickNames.insert("miRNA_gene"); */ std::set<std::string> ignoreTypes; // ignoreTypes.insert("pseudogene"); // ignoreTypes.insert("pseudogenic_transcript"); // ignoreTypes.insert("pseudogenic_exon"); // ignoreTypes.insert("transposable_element_gene"); // ignoreTypes.insert("mRNA_TE_gene"); ignoreTypes.insert("start_codon"); ignoreTypes.insert("stop_codon"); ignoreTypes.insert("protein"); ignoreTypes.insert("chromosome"); ignoreTypes.insert("transposable_element"); ignoreTypes.insert("transposon_fragment"); ignoreTypes.insert("contig"); ignoreTypes.insert("miRNA_gene"); readGffFileWithEveryThing (filePath, geneNameMap, geneHashMap, transcriptHashMap, cdsParentRegex, transcriptParentRegex, transcriptIdRegex, geneIdRegex, transcriptNickNames, geneNickNames, ignoreTypes); } void readGffFileWithEveryThing (const std::string& filePath, std::map<std::string, std::vector<std::string> > & geneNameMap, std::map<std::string, Gene > & geneHashMap, std::map<std::string, Transcript> & transcriptHashMap, std::set<std::string> & cdsParentRegex, std::set<std::string> & transcriptParentRegex, std::set<std::string> & transcriptIdRegex, std::set<std::string> & geneIdRegex, std::set<std::string> & transcriptNickNames, std::set<std::string> & geneNickNames, std::set<std::string> & ignoreTypes){ std::ifstream infile(filePath); if( ! infile.good()){ std::cerr << "error in opening GFF/GTF file " << filePath << std::endl; exit (1); } std::vector<std::regex> regCdsParents; for( std::string cds : cdsParentRegex ){ std::regex regCdsParent(cds); regCdsParents.push_back(regCdsParent); } std::vector<std::regex> regTranscriptIds; for( std::string transcript : transcriptIdRegex ){ std::regex regTranscript(transcript); regTranscriptIds.push_back(regTranscript); } std::vector<std::regex> regTranscriptParents; for( std::string transcript : transcriptParentRegex ){ std::regex regTranscript(transcript); regTranscriptParents.push_back(regTranscript); } std::vector<std::regex> regGeneIds; for( std::string gene : geneIdRegex ){ std::regex regGene(gene); regGeneIds.push_back(regGene); } char splim='\t'; std::string line; std::smatch match; std::string chromosomeName; std::string score; std::string source; std::string lastColumnInformation; bool matched; while (std::getline(infile, line)){ if(line[0]=='#' || line.size()<9){ }else { std::vector<std::string> elemetns; split(line, splim, elemetns); if(elemetns.size()==9){ int start = stoi(elemetns[3]); int end = stoi(elemetns[4]); if (start > end) { int temp = start; start = end; end = temp; } STRAND strand; if (elemetns[6].compare("-") == 0) { strand = NEGATIVE; } else { strand = POSITIVE; } chromosomeName = elemetns[0]; source = elemetns[1]; score = elemetns[5]; lastColumnInformation = elemetns[8]; if (geneNickNames.find(elemetns[2]) != geneNickNames.end()) { // std::cout << "line 119" << std::endl; matched = false; for (std::regex regGene : regGeneIds) { regex_search(lastColumnInformation, match, regGene); if (!match.empty()) { std::string geneId = match[1]; if (geneHashMap.find(geneId) != geneHashMap.end()) { } else { Gene gene1(geneId, chromosomeName, strand); geneHashMap[geneId] = gene1; } // std::cout << "line 170 " << geneId << std::endl; geneHashMap[geneId].setStart(start); geneHashMap[geneId].setEnd(end); geneHashMap[geneId].setSource(source); geneHashMap[geneId].setScore(score); geneHashMap[geneId].setLastColumnInformation(lastColumnInformation); matched = true; break; //jump out for loop } } if (!matched) { std::cout << "the gene record does not fellow the regular expression provided for finding gene ID, please check" << std::endl << line << std::endl; } } else if (transcriptNickNames.find(elemetns[2]) != transcriptNickNames.end()) { // std::cout << "line 141" << std::endl; matched = false; std::string transcriptId = ""; for (std::regex regTranscriptId : regTranscriptIds) { regex_search(lastColumnInformation, match, regTranscriptId); if (!match.empty()) { transcriptId = match[1]; matched = true; break; //jump out for loop } } if (!matched) { std::cout << "the transcript record does not fellow the regular expression provided for finding transcript ID, please check" << std::endl << line << std::endl; continue; //goto next line in the gff file } // std::cout << "line 156" << std::endl; matched = false; for (std::regex regTranscriptParent : regTranscriptParents) { regex_search(lastColumnInformation, match, regTranscriptParent); if (!match.empty()) { std::string geneId = match[1]; if (transcriptHashMap.find(transcriptId) != transcriptHashMap.end()) { } else { Transcript transcript1(transcriptId, elemetns[0], strand); transcriptHashMap[transcriptId] = transcript1; } transcriptHashMap[transcriptId].setStart(start); transcriptHashMap[transcriptId].setEnd(end); transcriptHashMap[transcriptId].setSource(source); transcriptHashMap[transcriptId].setScore(score); transcriptHashMap[transcriptId].setLastColumnInformation(lastColumnInformation); transcriptHashMap[transcriptId].setType(elemetns[2]); //std::cout << "transcript " << transcriptId << std::endl; if (geneHashMap.find(geneId) != geneHashMap.end()) { } else { //std::cout << "there is something wrong with the gff file, maybe could not generate correct result" << std::endl; Gene gene1(geneId, chromosomeName, strand); geneHashMap[geneId] = gene1; } geneHashMap[geneId].addTranscript(transcriptHashMap[transcriptId]); //std::cout << "line 178 very good very good " << geneHashMap[geneId].getName() << " " << transcriptHashMap[transcriptId].getName() << std::endl; matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the transcript record does not fellow the regular expression provided for finding gene ID, please check" << std::endl << line << std::endl; } } else if (elemetns[2].compare("CDS") == 0) { // std::cout << "line 188" << std::endl; matched = false; for (std::regex regCdsParent : regCdsParents) { regex_search(lastColumnInformation, match, regCdsParent); if (!match.empty()) { std::string transcriptId = match[1]; if (transcriptHashMap.find(transcriptId) != transcriptHashMap.end()) { } else { Transcript transcript1(transcriptId, chromosomeName, strand); transcript1.setSource(elemetns[3]); transcriptHashMap[transcriptId] = transcript1; } GenomeBasicFeature cds(start, end, score, elemetns[7], lastColumnInformation); cds.setType(elemetns[2]); transcriptHashMap[transcriptId].addCds(cds); // std::cout << transcriptId << "adding cds" << std::endl; matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the CDS record does not fellow the regular expression provided, please check" << std::endl << line << std::endl; } } else if (elemetns[2].compare("exon") == 0 || elemetns[2].compare("pseudogenic_exon") == 0) { // std::cout << "line 208 " << line << std::endl; matched = false; for (std::regex regCdsParent : regCdsParents) { regex_search(lastColumnInformation, match, regCdsParent); if (!match.empty()) { std::string transcriptId = match[1]; if (transcriptHashMap.find(transcriptId) != transcriptHashMap.end()) { } else { Transcript transcript1(transcriptId, chromosomeName, strand); transcript1.setSource(source); transcriptHashMap[transcriptId] = transcript1; } GenomeBasicFeature exon(start, end, score, elemetns[7], lastColumnInformation); exon.setType(elemetns[2]); transcriptHashMap[transcriptId].addExon(exon); // std::cout << transcriptId << "adding exon" << std::endl; matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the exon record does not fellow the regular expression provided, please check" << std::endl << line << std::endl; } } else if (elemetns[2].compare("five_prime_utr") == 0 || elemetns[2].compare("five_prime_UTR") == 0) { // std::cout << "line 231" << std::endl; matched = false; for (std::regex regCdsParent : regCdsParents) { regex_search(lastColumnInformation, match, regCdsParent); if (!match.empty()) { std::string transcriptId = match[1]; if (transcriptHashMap.find(transcriptId) != transcriptHashMap.end()) { } else { Transcript transcript1(transcriptId, chromosomeName, strand); transcript1.setSource(source); transcriptHashMap[transcriptId] = transcript1; } GenomeBasicFeature five_prime_utr(start, end, score, elemetns[7], lastColumnInformation); five_prime_utr.setType(elemetns[2]); transcriptHashMap[transcriptId].addFivePrimerUtr(five_prime_utr); matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the five_prime_utr record does not fellow the regular expression provided, please check" << std::endl << line << std::endl; } } else if (elemetns[2].compare("three_prime_utr") == 0 || elemetns[2].compare("three_prime_UTR") == 0) { // std::cout << "line 255" << std::endl; matched = false; for (std::regex regCdsParent : regCdsParents) { regex_search(lastColumnInformation, match, regCdsParent); if (!match.empty()) { std::string transcriptId = match[1]; if (transcriptHashMap.find(transcriptId) != transcriptHashMap.end()) { } else { Transcript transcript1(transcriptId, chromosomeName, strand); transcript1.setSource(source); transcriptHashMap[transcriptId] = transcript1; } GenomeBasicFeature three_prime_utr(start, end, score, elemetns[7], lastColumnInformation); three_prime_utr.setType(elemetns[2]); transcriptHashMap[transcriptId].addThreePrimerUtr(three_prime_utr); matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the three_prime_utr record does not fellow the regular expression provided, please check" << std::endl << line << std::endl; } } else if (ignoreTypes.find(elemetns[2]) != ignoreTypes.end()) { // ignore those elements } else { // std::cout << "we could not analysis the line in the gff/gtf file: " << line << std::endl; } } } } std::map<std::string, std::vector<Gene>> geneHashSet; for (std::map<std::string, Gene>::iterator it=geneHashMap.begin(); it!=geneHashMap.end(); ++it){ if(geneHashSet.find(it->second.getChromeSomeName()) == geneHashSet.end() ){ geneHashSet[it->second.getChromeSomeName()]=std::vector<Gene>(); } // std::cout << it->second.getName() << "\t" << it->second.getTranscriptVector().size() << "\t" << std::endl; for( std::vector<std::string>::iterator transcript= it->second.getTranscriptVector().begin(); transcript != it->second.getTranscriptVector().end(); ++transcript){ if( transcriptHashMap[*transcript].getCdsVector().size()>0 ){ transcriptHashMap[*transcript].updateInforCds(); } } geneHashSet[it->second.getChromeSomeName()].push_back(it->second); //geneNameMap[it->second.getChromeSomeName()].push_back(it->second.getName()); } // the purpose of geneHashSet if to keep the IDs in geneNameMap in order // this is very important for the gff record transformation for (std::map<std::string, std::vector<Gene>>::iterator it=geneHashSet.begin(); it!=geneHashSet.end(); ++it){ std::sort(it->second.begin(), it->second.end(), [](Gene a, Gene b) { return a.getStart() < b.getStart(); }); if(geneNameMap.find(it->first) == geneNameMap.end() ){ geneNameMap[it->first]=std::vector<std::string>(); } for( Gene gene : it->second ){ geneNameMap[it->first].push_back(gene.getName()); } } } /** * the following two functions are used to reads the gff file with duplication gene ids and transcripts id * for example the output of liftover annotation for de novo assembly genome sequence * */ void readGffFileWithEveryThing (const std::string& filePath, std::map<std::string, std::vector<Gene> > & geneMap){ std::set<std::string> cdsParentRegex; std::set<std::string> transcriptParentRegex; std::set<std::string> transcriptIdRegex; std::set<std::string> geneIdRegex; //tair10 begin cdsParentRegex.insert("Parent=([\\s\\S]*?)[;,]");//CDS cdsParentRegex.insert("Parent=([\\s\\S^,^;]*?)$");//exon transcriptParentRegex.insert("Parent=([\\s\\S]*?)[;,]"); transcriptIdRegex.insert("ID=([\\s\\S]*?)[;,]"); geneIdRegex.insert("ID=([-_0-9:a-zA-Z.]*?)[;,]"); geneIdRegex.insert("ID=([-_0-9:a-zA-Z.]*?)$"); //melon // tair10 end //ensembl begin cdsParentRegex.insert("transcript_id\\s*\"([\\s\\S]*?)\"[;,]"); transcriptParentRegex.insert("gene_id\\s*\"([\\s\\S]*?)\"[;,]"); transcriptIdRegex.insert("transcript_id\\s*\"([\\s\\S]*?)\"[;,]"); geneIdRegex.insert("gene_id\\s*\"([\\s\\S]*?)\"[;,]"); //ensembl end /* //begin cdsParentRegex.insert("transcript_id \"([\\s\\S]*?)\"[;,]"); transcriptParentRegex.insert(""); transcriptIdRegex.insert(); geneIdRegex.insert(); end */ /* std::set<std::string> transcriptNickNames; transcriptNickNames.insert("transcript"); transcriptNickNames.insert("pseudogenic_transcript"); transcriptNickNames.insert("mRNA"); transcriptNickNames.insert("miRNA"); transcriptNickNames.insert("tRNA"); transcriptNickNames.insert("ncRNA"); transcriptNickNames.insert("mRNA_TE_gene"); transcriptNickNames.insert("rRNA"); transcriptNickNames.insert("snoRNA"); transcriptNickNames.insert("snRNA"); transcriptNickNames.insert("lincRNA"); std::set<std::string> geneNickNames; geneNickNames.insert("gene"); geneNickNames.insert("pseudogene"); geneNickNames.insert("transposable_element_gene"); geneNickNames.insert("tRNA_gene"); geneNickNames.insert("lincRNA_gene"); geneNickNames.insert("miRNA_gene"); */ std::set<std::string> transcriptNickNames; transcriptNickNames.insert("transcript"); transcriptNickNames.insert("pseudogenic_transcript"); transcriptNickNames.insert("mRNA"); transcriptNickNames.insert("miRNA"); transcriptNickNames.insert("tRNA"); transcriptNickNames.insert("ncRNA"); transcriptNickNames.insert("mRNA_TE_gene"); transcriptNickNames.insert("rRNA"); transcriptNickNames.insert("snoRNA"); transcriptNickNames.insert("snRNA"); transcriptNickNames.insert("lincRNA"); std::set<std::string> geneNickNames; geneNickNames.insert("gene"); geneNickNames.insert("pseudogene"); geneNickNames.insert("transposable_element_gene"); geneNickNames.insert("lincRNA_gene"); geneNickNames.insert("tRNA_gene"); std::set<std::string> ignoreTypes; // ignoreTypes.insert("pseudogene"); // ignoreTypes.insert("pseudogenic_transcript"); // ignoreTypes.insert("pseudogenic_exon"); // ignoreTypes.insert("transposable_element_gene"); // ignoreTypes.insert("mRNA_TE_gene"); ignoreTypes.insert("start_codon"); ignoreTypes.insert("stop_codon"); ignoreTypes.insert("protein"); ignoreTypes.insert("chromosome"); ignoreTypes.insert("transposable_element"); ignoreTypes.insert("transposon_fragment"); ignoreTypes.insert("miRNA_gene"); // std::cout << "line 519" << std::endl; readGffFileWithEveryThing (filePath, geneMap, cdsParentRegex, transcriptParentRegex, transcriptIdRegex, geneIdRegex, transcriptNickNames, geneNickNames, ignoreTypes); } void readGffFileWithEveryThing (const std::string& filePath, std::map<std::string, std::vector<Gene> > & geneMap, std::set<std::string> & cdsParentRegex, std::set<std::string> & transcriptParentRegex, std::set<std::string> & transcriptIdRegex, std::set<std::string> & geneIdRegex, std::set<std::string> & transcriptNickNames, std::set<std::string> & geneNickNames, std::set<std::string> & ignoreTypes){ std::ifstream infile(filePath); if( ! infile.good()){ std::cerr << "error in opening GFF/GTF file " << filePath << std::endl; exit (1); } std::vector<std::regex> regCdsParents; for( std::string cds : cdsParentRegex ){ std::regex regCdsParent(cds); regCdsParents.push_back(regCdsParent); } std::vector<std::regex> regTranscriptIds; for( std::string transcript : transcriptIdRegex ){ std::regex regTranscript(transcript); regTranscriptIds.push_back(regTranscript); } std::vector<std::regex> regTranscriptParents; for( std::string transcript : transcriptParentRegex ){ std::regex regTranscript(transcript); regTranscriptParents.push_back(regTranscript); } std::vector<std::regex> regGeneIds; for( std::string gene : geneIdRegex ){ std::regex regGene(gene); regGeneIds.push_back(regGene); } char splim='\t'; std::string line; std::smatch match; std::string chromosomeName; std::string score; std::string source; std::string lastColumnInformation; bool matched; while (std::getline(infile, line)){ if(line[0]=='#' || line.size()<9){ }else { std::vector<std::string> elemetns; split(line, splim, elemetns); if(elemetns.size()==9){ int start = stoi(elemetns[3]); int end = stoi(elemetns[4]); if (start > end) { int temp = start; start = end; end = temp; } STRAND strand; if (elemetns[6].compare("-") == 0) { strand = NEGATIVE; } else { strand = POSITIVE; } chromosomeName = elemetns[0]; source = elemetns[1]; score = elemetns[5]; lastColumnInformation = elemetns[8]; if(geneMap.find(chromosomeName) == geneMap.end() ){ geneMap[chromosomeName]=std::vector<Gene>(); } // std::cout << "line 587" << std::endl; if (geneNickNames.find(elemetns[2]) != geneNickNames.end()) { // std::cout << "line 589" << line << std::endl; matched = false; for (std::regex regGene : regGeneIds) { regex_search(lastColumnInformation, match, regGene); if (!match.empty()) { // std::cout << "line 594" << line << std::endl; std::string geneId = match[1]; Gene gene1(geneId, chromosomeName, strand); geneMap[chromosomeName].push_back(gene1); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].setStart(start); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].setEnd(end); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].setSource(source); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].setScore(score); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].setLastColumnInformation(lastColumnInformation); matched = true; break; //jump out for loop } } if (!matched) { std::cout << "the gene record does not fellow the regular expression provided for finding gene ID, please check" << std::endl << line << std::endl; } } else if (transcriptNickNames.find(elemetns[2]) != transcriptNickNames.end()) { // std::cout << "line 141 " << line << std::endl; matched = false; std::string transcriptId = ""; for (std::regex regTranscriptId : regTranscriptIds) { regex_search(lastColumnInformation, match, regTranscriptId); if (!match.empty()) { transcriptId = match[1]; matched = true; break; //jump out for loop } } if (!matched) { std::cout << "the transcript record does not fellow the regular expression provided for finding transcript ID, please check" << std::endl << line << std::endl; continue; //goto next line in the gff file } // std::cout << "line 156 " << lastColumnInformation << std::endl; matched = false; for (std::regex regTranscriptParent : regTranscriptParents) { // std::cout << "line 633" << std::endl; regex_search(lastColumnInformation, match, regTranscriptParent); // std::cout << "line 635" << std::endl; if (!match.empty()) { std::string geneId = match[1]; if( geneMap.find(chromosomeName) != geneMap.end() && geneMap[chromosomeName].size()>0 && geneId.compare(geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getName()) == 0 ){ // std::cout << geneId << " " << geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getName() << std::endl; Transcript transcript1(transcriptId, elemetns[0], strand); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().push_back(transcript1); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].setStart(start); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].setEnd(end); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].setSource(source); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].setScore(score); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].setLastColumnInformation(lastColumnInformation); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].setType(elemetns[2]); } matched = true; break; // jump out for loop } // std::cout << "line 650" << std::endl; } // std::cout << "line 651" << std::endl; if (!matched) { std::cout << "the transcript record does not fellow the regular expression provided for finding gene ID, please check" << std::endl << line << std::endl; } } else if (elemetns[2].compare("CDS") == 0) { // std::cout << "line 188 " << line << std::endl; matched = false; for (std::regex regCdsParent : regCdsParents) { regex_search(lastColumnInformation, match, regCdsParent); if (!match.empty()) { std::string transcriptId = match[1]; if( transcriptId.compare(geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].getName()) == 0 ){ GenomeBasicFeature cds(start, end, score, elemetns[7], lastColumnInformation); cds.setType(elemetns[2]); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].addCds(cds); // std::cout << transcriptId << "adding cds" << std::endl; } matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the CDS record does not fellow the regular expression provided, please check" << std::endl << line << std::endl; } } else if (elemetns[2].compare("exon") == 0 || elemetns[2].compare("pseudogenic_exon") == 0) { // std::cout << "line 208 " << line << std::endl; matched = false; for (std::regex regCdsParent : regCdsParents) { regex_search(lastColumnInformation, match, regCdsParent); if (!match.empty()) { std::string transcriptId = match[1]; if( geneMap.find(chromosomeName)!=geneMap.end() && geneMap[chromosomeName].size()>0 && geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()>0 && transcriptId.compare(geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].getName()) == 0 ){ GenomeBasicFeature exon(start, end, score, elemetns[7], lastColumnInformation); exon.setType(elemetns[2]); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].addExon(exon); // std::cout << transcriptId << "adding exon" << std::endl; } matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the exon record does not fellow the regular expression provided, please check" << std::endl << line << std::endl; } } else if (elemetns[2].compare("five_prime_utr") == 0 || elemetns[2].compare("five_prime_UTR") == 0) { // std::cout << "line 231" << std::endl; matched = false; for (std::regex regCdsParent : regCdsParents) { regex_search(lastColumnInformation, match, regCdsParent); if (!match.empty()) { std::string transcriptId = match[1]; if( transcriptId.compare(geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].getName()) == 0 ){ GenomeBasicFeature five_prime_utr(start, end, score, elemetns[7], lastColumnInformation); five_prime_utr.setType(elemetns[2]); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].addFivePrimerUtr(five_prime_utr); } matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the five_prime_utr record does not fellow the regular expression provided, please check" << std::endl << line << std::endl; } } else if (elemetns[2].compare("three_prime_utr") == 0 || elemetns[2].compare("three_prime_UTR") == 0) { // std::cout << "line 255" << std::endl; matched = false; for (std::regex regCdsParent : regCdsParents) { regex_search(lastColumnInformation, match, regCdsParent); if (!match.empty()) { std::string transcriptId = match[1]; if( transcriptId.compare(geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].getName()) == 0 ){ GenomeBasicFeature three_prime_utr(start, end, score, elemetns[7], lastColumnInformation); three_prime_utr.setType(elemetns[2]); geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts()[geneMap[chromosomeName][geneMap[chromosomeName].size()-1].getTranscripts().size()-1].addThreePrimerUtr(three_prime_utr); } matched = true; break; // jump out for loop } } if (!matched) { std::cout << "the three_prime_utr record does not fellow the regular expression provided, please check" << std::endl << line << std::endl; } } else if (ignoreTypes.find(elemetns[2]) != ignoreTypes.end()) { // ignore those elements } else { //std::cout << "we could not analysis the line in the gff/gtf file " << line << std::endl; } // std::cout << "line 746" << std::endl; } } } // std::cout << "749" << std::endl; for (std::map<std::string, std::vector<Gene>>::iterator it=geneMap.begin(); it!=geneMap.end(); ++it){ std::sort(it->second.begin(), it->second.end(), [](Gene a, Gene b) { return a.getStart() < b.getStart(); }); } for (std::map<std::string, std::vector<Gene>>::iterator it1=geneMap.begin(); it1!=geneMap.end(); ++it1){ for( std::vector<Gene>::iterator it=it1->second.begin(); it!=it1->second.end(); ++it){ for( std::vector<Transcript>::iterator transcriptIt = it->getTranscripts().begin(); transcriptIt != it->getTranscripts().end(); ++transcriptIt){ if( (*transcriptIt).getCdsVector().size()>0 ){ (*transcriptIt).updateInforCds(); } } } } }
51.611326
240
0.518253
[ "vector" ]
eb63df147c9c6d915867b7b6d5c38ea280d90e41
22,130
cpp
C++
examples/Bounded_Packet_Relay/Thread_Bounded_Packet_Relay.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
examples/Bounded_Packet_Relay/Thread_Bounded_Packet_Relay.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
examples/Bounded_Packet_Relay/Thread_Bounded_Packet_Relay.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
//============================================================================= /** * @file Thread_Bounded_Packet_Relay.cpp * * $Id: Thread_Bounded_Packet_Relay.cpp 93639 2011-03-24 13:32:13Z johnnyw $ * * Method definitions for the threaded-bounded packet relay class. * * * @author Chris Gill <cdgill@cs.wustl.edu> and Douglas C. Schmidt <schmidt@cs.wustl.edu> Based on the Timer Queue Test example written by Carlos O'Ryan <coryan@cs.wustl.edu> and Douglas C. Schmidt <schmidt@cs.wustl.edu> and Sergio Flores-Gaitan <sergio@cs.wustl.edu> */ //============================================================================= #include "ace/OS_NS_string.h" #include "ace/OS_NS_sys_time.h" #include "ace/Condition_T.h" #include "ace/Null_Mutex.h" #include "Thread_Bounded_Packet_Relay.h" typedef Thread_Bounded_Packet_Relay_Driver::MYCOMMAND DRIVER_CMD; typedef ACE_Command_Callback<BPR_Handler_Base, BPR_Handler_Base::ACTION> HANDLER_CMD; typedef ACE_Command_Callback<Send_Handler, Send_Handler::ACTION> SEND_HANDLER_CMD; // Constructor. Text_Input_Device_Wrapper::Text_Input_Device_Wrapper (ACE_Thread_Manager *input_task_mgr, size_t read_length, const char* text, int logging) : Input_Device_Wrapper_Base (input_task_mgr), read_length_ (read_length), text_ (text), index_ (0), logging_ (logging), packet_count_ (0) { } // Destructor. Text_Input_Device_Wrapper::~Text_Input_Device_Wrapper (void) { } // Modifies device settings based on passed pointer to a u_long. int Text_Input_Device_Wrapper::modify_device_settings (void *logging) { packet_count_ = 0; if (logging) logging_ = *static_cast<int *> (logging); else ACE_ERROR_RETURN ((LM_ERROR, "Text_Input_Device_Wrapper::modify_device_settings: " "null argument"), -1); return 0; } // Creates a new message block, carrying data // read from the underlying input device. ACE_Message_Block * Text_Input_Device_Wrapper::create_input_message (void) { // Construct a new message block to send. ACE_Message_Block *mb = 0; ACE_NEW_RETURN (mb, ACE_Message_Block (read_length_), 0); // Zero out a "read" buffer to hold data. char read_buf [BUFSIZ]; ACE_OS::memset (read_buf, 0, BUFSIZ); // Loop through the text, filling in data to copy into the read // buffer (leaving room for a terminating zero). for (size_t i = 0; i < read_length_ - 1; ++i) { read_buf [i] = text_ [index_]; index_ = (index_ + 1) % ACE_OS::strlen (text_); } // Copy buf into the Message_Block and update the wr_ptr (). if (mb->copy (read_buf, read_length_) < 0) { delete mb; ACE_ERROR_RETURN ((LM_ERROR, "read buffer copy failed"), 0); } // log packet creation if logging is turned on if (logging_ & Text_Input_Device_Wrapper::LOG_MSGS_CREATED) { ++packet_count_; ACE_DEBUG ((LM_DEBUG, "input message %d created\n", packet_count_)); } return mb; } // Constructor. Text_Output_Device_Wrapper::Text_Output_Device_Wrapper (int logging) : logging_ (logging) { } // Consume and possibly print out the passed message. int Text_Output_Device_Wrapper::write_output_message (void *message) { if (message) { ++packet_count_; if (logging_ & Text_Output_Device_Wrapper::LOG_MSGS_RCVD) ACE_DEBUG ((LM_DEBUG, "output message %d received\n", packet_count_)); if (logging_ & Text_Output_Device_Wrapper::PRINT_MSGS_RCVD) ACE_DEBUG ((LM_DEBUG, "output message %d:\n[%s]\n", packet_count_, static_cast<ACE_Message_Block *> (message)->rd_ptr ())); delete static_cast<ACE_Message_Block *> (message); return 0; } ACE_ERROR_RETURN ((LM_ERROR, "Text_Output_Device_Wrapper::" "write_output_message: null argument"), -1); } // Modifies device settings based on passed pointer to a u_long. int Text_Output_Device_Wrapper::modify_device_settings (void *logging) { packet_count_ = 0; if (logging) logging_ = *static_cast<int *> (logging); else ACE_ERROR_RETURN ((LM_ERROR, "Text_Output_Device_Wrapper::modify_device_settings: " "null argument"), -1); return 0; } // Constructor. User_Input_Task::User_Input_Task (Bounded_Packet_Relay *relay, Thread_Timer_Queue *queue, Thread_Bounded_Packet_Relay_Driver &tbprd) : ACE_Task_Base (ACE_Thread_Manager::instance ()), usecs_ (ACE_ONE_SECOND_IN_USECS), relay_ (relay), queue_ (queue), driver_ (tbprd) { } // Destructor. User_Input_Task::~User_Input_Task (void) { this->clear_all_timers (); } // Runs the main event loop. int User_Input_Task::svc (void) { for (;;) // Call back to the driver's implementation of how to read and // parse input. if (this->driver_.get_next_request () == -1) break; // We are done. this->relay_->end_transmission (Bounded_Packet_Relay::CANCELLED); this->queue_->deactivate (); ACE_DEBUG ((LM_DEBUG, "terminating user input thread\n")); this->clear_all_timers (); return 0; } // Sets the number of packets for the next transmission. int User_Input_Task::set_packet_count (void *argument) { if (argument) { driver_.packet_count (*static_cast<int *> (argument)); return 0; } ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::set_packet_count: null argument"), -1); } // Sets the input device packet arrival period (usecs) for the next // transmission. int User_Input_Task::set_arrival_period (void *argument) { if (argument) { driver_.arrival_period (*static_cast<int *> (argument)); return 0; } ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::set_arrival_period: null argument"), -1); } // Sets the period between output device sends (usecs) for the next // transmission. int User_Input_Task::set_send_period (void *argument) { if (argument) { driver_.send_period (*static_cast<int *> (argument)); return 0; } ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::set_send_period: null argument"), -1); } // Sets a limit on the transmission duration (usecs). int User_Input_Task::set_duration_limit (void *argument) { if (argument) { driver_.duration_limit (*static_cast<int *> (argument)); return 0; } ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::set_duration_limit: null argument"), -1); } // Sets logging level (0 or 1) for output device for the next // transmission. int User_Input_Task::set_logging_level (void *argument) { if (argument) { driver_.logging_level (*static_cast<int *> (argument)); return 0; } ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::set_logging_level: null argument"), -1); } // Runs the next transmission (if one is not in progress). int User_Input_Task::run_transmission (void *) { if (relay_) { switch (relay_->start_transmission (driver_.packet_count (), driver_.arrival_period (), driver_.logging_level ())) { case 1: ACE_DEBUG ((LM_DEBUG, "\nRun transmission: " " Transmission already in progress\n")); return 0; /* NOTREACHED */ case 0: { ACE_Time_Value now = ACE_OS::gettimeofday (); ACE_Time_Value send_every (0, driver_.send_period ()); ACE_Time_Value send_at (send_every + now); Send_Handler *send_handler; ACE_NEW_RETURN (send_handler, Send_Handler (driver_.packet_count (), send_every, *relay_, *queue_, driver_), -1); if (queue_->schedule (send_handler, 0, send_at) < 0) { delete send_handler; ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::run_transmission: " "failed to schedule send handler"), -1); } if (driver_.duration_limit ()) { ACE_Time_Value terminate_at (0, driver_.duration_limit ()); terminate_at += now; Termination_Handler *termination_handler; termination_handler = new Termination_Handler (*relay_, *queue_, driver_); if (! termination_handler) { this->clear_all_timers (); ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::run_transmission: " "failed to allocate termination " "handler"), -1); } if (queue_->schedule (termination_handler, 0, terminate_at) < 0) { delete termination_handler; this->clear_all_timers (); ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::run_transmission: " "failed to schedule termination " "handler"), -1); } } return 0; } /* NOTREACHED */ default: return -1; /* NOTREACHED */ } } ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::run_transmission: " "relay not instantiated"), -1); } // Ends the current transmission (if one is in progress). int User_Input_Task::end_transmission (void *) { if (relay_) { switch (relay_->end_transmission (Bounded_Packet_Relay::CANCELLED)) { case 1: ACE_DEBUG ((LM_DEBUG, "\nEnd transmission: " "no transmission in progress\n")); /* Fall through to next case */ case 0: // Cancel any remaining timers. this->clear_all_timers (); return 0; /* NOTREACHED */ default: return -1; /* NOTREACHED */ } } ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::end_transmission: " "relay not instantiated"), -1); } // Reports statistics for the previous transmission // (if one is not in progress). int User_Input_Task::report_stats (void *) { if (relay_) { switch (relay_->report_statistics ()) { case 1: ACE_DEBUG ((LM_DEBUG, "\nRun transmission: " "\ntransmission already in progress\n")); return 0; /* NOTREACHED */ case 0: this->clear_all_timers (); return 0; /* NOTREACHED */ default: return -1; /* NOTREACHED */ } } ACE_ERROR_RETURN ((LM_ERROR, "User_Input_Task::report_stats: " "relay not instantiated"), -1); } // Shut down the task. int User_Input_Task::shutdown (void *) { // Clear any outstanding timers. this->clear_all_timers (); #if !defined (ACE_LACKS_PTHREAD_CANCEL) // Cancel the thread timer queue task "preemptively." ACE_Thread::cancel (this->queue_->thr_id ()); #else // Cancel the thread timer queue task "voluntarily." this->queue_->deactivate (); #endif /* ACE_LACKS_PTHREAD_CANCEL */ // -1 indicates we are shutting down the application. return -1; } // Helper method: clears all timers. int User_Input_Task::clear_all_timers (void) { // loop through the timers in the queue, cancelling each one for (ACE_Timer_Node_T <ACE_Event_Handler *> *node; (node = queue_->timer_queue ()->get_first ()) != 0; ) queue_->timer_queue ()->cancel (node->get_timer_id (), 0, 0); return 0; } // Constructor. BPR_Handler_Base::BPR_Handler_Base (Bounded_Packet_Relay &relay, Thread_Timer_Queue &queue) : relay_ (relay), queue_ (queue) { } // Destructor. BPR_Handler_Base::~BPR_Handler_Base (void) { } // Helper method: clears all timers. int BPR_Handler_Base::clear_all_timers (void *) { // Loop through the timers in the queue, cancelling each one. for (ACE_Timer_Node_T <ACE_Event_Handler *> *node; (node = queue_.timer_queue ()->get_first ()) != 0; ) queue_.timer_queue ()->cancel (node->get_timer_id (), 0, 0); // queue_.cancel (node->get_timer_id (), 0); // Invoke the handler's (virtual) destructor delete this; return 0; } // Constructor. Send_Handler::Send_Handler (u_long send_count, const ACE_Time_Value &duration, Bounded_Packet_Relay &relay, Thread_Timer_Queue &queue, Thread_Bounded_Packet_Relay_Driver &driver) : BPR_Handler_Base (relay, queue), send_count_ (send_count), duration_ (duration), driver_ (driver) { } // Destructor. Send_Handler::~Send_Handler (void) { } // Call back hook. int Send_Handler::handle_timeout (const ACE_Time_Value &, const void *) { switch (relay_.send_input ()) { case 0: // Decrement count of packets to relay. --send_count_; /* Fall through to next case. */ case 1: if (send_count_ > 0) { // Enqueue a deferred callback to the reregister command. SEND_HANDLER_CMD *re_register_callback_; ACE_NEW_RETURN (re_register_callback_, SEND_HANDLER_CMD (*this, &Send_Handler::reregister), -1); return queue_.enqueue_command (re_register_callback_); } else { // All packets are sent, time to end the transmission, redisplay // the user menu, cancel any other timers, and go away. relay_.end_transmission (Bounded_Packet_Relay::COMPLETED); driver_.display_menu (); // Enqueue a deferred callback to the clear_all_timers command. HANDLER_CMD *clear_timers_callback_; ACE_NEW_RETURN (clear_timers_callback_, HANDLER_CMD (*this, &BPR_Handler_Base::clear_all_timers), -1); return queue_.enqueue_command (clear_timers_callback_); } /* NOTREACHED */ default: return -1; } } // Cancellation hook. int Send_Handler::cancelled (void) { delete this; return 0; } // Helper method: re-registers this timer int Send_Handler::reregister (void *) { // Re-register the handler for a new timeout. if (queue_.schedule (this, 0, duration_ + ACE_OS::gettimeofday ()) < 0) ACE_ERROR_RETURN ((LM_ERROR, "Send_Handler::reregister: " "failed to reschedule send handler"), -1); return 0; } // Constructor. Termination_Handler::Termination_Handler (Bounded_Packet_Relay &relay, Thread_Timer_Queue &queue, Thread_Bounded_Packet_Relay_Driver &driver) : BPR_Handler_Base (relay, queue), driver_ (driver) { } // Destructor. Termination_Handler::~Termination_Handler (void) { } // Call back hook. int Termination_Handler::handle_timeout (const ACE_Time_Value &, const void *) { // Transmission timed out, so end the transmission, display the user // menu, and register a callback to clear the timer queue and then // make this object go away. relay_.end_transmission (Bounded_Packet_Relay::TIMED_OUT); driver_.display_menu (); // Enqueue a deferred callback to the clear_all_timers command. HANDLER_CMD *clear_timers_callback_; ACE_NEW_RETURN (clear_timers_callback_, HANDLER_CMD (*this, &BPR_Handler_Base::clear_all_timers), -1); return queue_.enqueue_command (clear_timers_callback_); } // Cancellation hook int Termination_Handler::cancelled (void) { delete this; return 0; } // Constructor. Thread_Bounded_Packet_Relay_Driver::Thread_Bounded_Packet_Relay_Driver (Bounded_Packet_Relay *relay) : input_task_ (relay, &timer_queue_, *this) { } // Destructor. Thread_Bounded_Packet_Relay_Driver::~Thread_Bounded_Packet_Relay_Driver (void) { } // Display the user menu. int Thread_Bounded_Packet_Relay_Driver::display_menu (void) { static char menu[] = "\n\n Options:\n" " ----------------------------------------------------------------------\n" " 1 <number of packets to relay in one transmission = %d>\n" " min = 1 packet.\n" " 2 <input packet arrival period (in usec) = %d>\n" " min = 1.\n" " 3 <output packet transmission period (in usec) = %d>\n" " min = 1.\n" " 4 <limit on duration of transmission (in usec) = %d>\n" " min = 1, no limit = 0.\n" " 5 <logging level flags = %d>\n" " no logging = 0,\n" " log packets created by input device = 1,\n" " log packets consumed by output device = 2,\n" " logging options 1,2 = 3,\n" " print contents of packets consumed by output put device = 4,\n" " logging options 1,4 = 5,\n" " logging options 2,4 = 6,\n" " logging options 1,2,4 = 7.\n" " ----------------------------------------------------------------------\n" " 6 - runs a transmission using the current settings\n" " 7 - cancels a transmission (if there is one running)\n" " 8 - reports statistics from the most recent transmission\n" " 9 - quits the program\n" " ----------------------------------------------------------------------\n" " Please enter your choice: "; ACE_DEBUG ((LM_DEBUG, menu, this->packet_count (), this->arrival_period (), this->send_period (), this->duration_limit (), this->logging_level ())); return 0; } // Initialize the driver. int Thread_Bounded_Packet_Relay_Driver::init (void) { // Initialize the <Command> objects with their corresponding // methods from <User_Input_Task>. ACE_NEW_RETURN (packet_count_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::set_packet_count), -1); ACE_NEW_RETURN (arrival_period_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::set_arrival_period), -1); ACE_NEW_RETURN (transmit_period_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::set_send_period), -1); ACE_NEW_RETURN (duration_limit_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::set_duration_limit), -1); ACE_NEW_RETURN (logging_level_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::set_logging_level), -1); ACE_NEW_RETURN (run_transmission_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::run_transmission), -1); ACE_NEW_RETURN (cancel_transmission_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::end_transmission), -1); ACE_NEW_RETURN (report_stats_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::report_stats), -1); ACE_NEW_RETURN (shutdown_cmd_, DRIVER_CMD (input_task_, &User_Input_Task::shutdown), -1); if (this->input_task_.activate () == -1) ACE_ERROR_RETURN ((LM_ERROR, "cannot activate input task"), -1); else if (this->timer_queue_.activate () == -1) ACE_ERROR_RETURN ((LM_ERROR, "cannot activate timer queue"), -1); else if (ACE_Thread_Manager::instance ()->wait () == -1) ACE_ERROR_RETURN ((LM_ERROR, "wait on Thread_Manager failed"), -1); return 0; } // Run the driver int Thread_Bounded_Packet_Relay_Driver::run (void) { this->init (); return 0; }
29.118421
291
0.541211
[ "object" ]
eb677a0d2c14a7cf39237ec6793d8a3ab1bb6782
1,041
cc
C++
Code/1255-reverse-subarray-to-maximize-array-value.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
2
2019-12-06T14:08:57.000Z
2020-01-15T15:25:32.000Z
Code/1255-reverse-subarray-to-maximize-array-value.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
1
2020-01-15T16:29:16.000Z
2020-01-26T12:40:13.000Z
Code/1255-reverse-subarray-to-maximize-array-value.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
null
null
null
class Solution { public: int maxValueAfterReverse(vector<int>& nums) { int size = nums.size(); if (size == 1) { return nums[0]; } int smallestBigger = max(nums[0], nums[1]); int biggestSmaller = min(nums[0], nums[1]); int origin = smallestBigger - biggestSmaller; int diff = 0; for (int i = 1; i < nums.size() - 1; i++) { // the origin value origin += abs(nums[i] - nums[i + 1]); // reverse inner part smallestBigger = min(smallestBigger, max(nums[i], nums[i + 1])); // smallest bigger one biggestSmaller = max(biggestSmaller, min(nums[i], nums[i + 1])); // biggest smaller one // reverse edge part diff = max(diff, abs(nums[i + 1] - nums[0]) - abs(nums[i + 1] - nums[i])); diff = max(diff, abs(nums[size - 1] - nums[i]) - abs(nums[i + 1] - nums[i])); } diff = max(diff, 2 * (biggestSmaller - smallestBigger)); return diff + origin; } };
41.64
99
0.516811
[ "vector" ]
eb68017bfc008ba64e5284225f6c8d63f9ae0b37
14,346
cpp
C++
test/saber/test_saber_conv_pooling_int8.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
533
2018-05-18T06:14:04.000Z
2022-03-23T11:46:30.000Z
test/saber/test_saber_conv_pooling_int8.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
100
2018-05-26T08:32:48.000Z
2022-03-17T03:26:25.000Z
test/saber/test_saber_conv_pooling_int8.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
167
2018-05-18T06:14:35.000Z
2022-02-14T01:44:20.000Z
#include "saber/core/context.h" #include "saber/funcs/conv_pooling.h" #include "saber/core/tensor_op.h" #include "saber/saber_types.h" #include "test_saber_func.h" #include "conv_func_helper.h" #include <vector> using namespace anakin::saber; template <typename dtype> int count_diff(const dtype* src1, const dtype* src2, int size, double max_ratio) { if (max_ratio <= 0) { max_ratio = 0.1; } int count = 0; for (int i = 0; i < size; ++i) { double ratio = fabs(src1[i] - src2[i]) / fabs(src1[i] + src2[i] + 1e-12); if (ratio > max_ratio) { ++count; } } return count; } template<typename TargetType, typename TargetType_H> int test_conv_pool_results(int group, int input_num, int in_channels, int height, int width, int out_channels, int conv_kernel_h, int conv_kernel_w, int conv_stride_h, int conv_stride_w, int conv_dilation_h, int conv_dilation_w, int conv_pad_h, int conv_pad_w, bool bias_term, bool relu, int pool_stride_h, int pool_stride_w, int pool_pad_h, int pool_pad_w, int pool_kernel_h, int pool_kernel_w, PoolingType pool_type, SaberImplStrategy strategy, ImplEnum imp) { LOG(INFO) << " conv param: " << " input_num = " << input_num << " in_channels = " << in_channels << " height = " << height << " width = " << width << " group = " << group << " conv_pad_h = " << conv_pad_h << " conv_pad_w = " << conv_pad_w << " conv_stride_h = " << conv_stride_h << " conv_stride_w = " << conv_stride_w << " conv_dilation_h = " << conv_dilation_h << " conv_dilation_w = " << conv_dilation_w << " conv_kernel_h = " << conv_kernel_h << " conv_kernel_w = " << conv_kernel_w << " pool_pad_h = " << pool_pad_h << " pool_pad_w = " << pool_pad_w << " pool_stride_h = " << pool_stride_h << " pool_stride_w = " << pool_stride_w << " pool_kernel_h = " << pool_kernel_h << " pool_kernel_w = " << pool_kernel_w << " out_channels = " << out_channels << " relu = " << (relu ? "true" : "false") << " bias_term = " << (bias_term ? "true" : "false"); #ifdef USE_CUDA return 0; #endif #ifdef USE_X86_PLACE Shape input_s({input_num, height, width, in_channels}, Layout_NHWC); Shape weights_s({out_channels, in_channels, conv_kernel_h, conv_kernel_w}, Layout_NCHW); Shape weights_s_dw({group, in_channels / group, conv_kernel_h, conv_kernel_w}, Layout_NCHW); Shape bias_s({1, out_channels, 1, 1}, Layout_NCHW); // generate conv_output shape int conv_out_height = (conv_pad_h * 2 + height - (conv_dilation_h * (conv_kernel_h - 1) + 1)) / conv_stride_h + 1; int conv_out_width = (conv_pad_w * 2 + width - (conv_dilation_w * (conv_kernel_w - 1) + 1)) / conv_stride_w + 1; Shape conv_output_s({input_num, conv_out_height, conv_out_width, out_channels}, Layout_NHWC); // generate conv_pool_output shape int out_height = (conv_out_height + 2 * pool_pad_h - pool_kernel_h) / pool_stride_h + 1; int out_width = (conv_out_width + 2 * pool_pad_w - pool_kernel_w) / pool_stride_w + 1; Shape output_s({input_num, out_height, out_width, out_channels}, Layout_NHWC); // init input Tensor Tensor<TargetType> input_dev; Tensor<TargetType_H> input_host; input_dev.re_alloc(input_s, AK_UINT8); input_host.re_alloc(input_s, AK_UINT8); fill_tensor_rand(input_dev, 0.0f, 32.0f); input_host.copy_from(input_dev); input_dev.set_scale({1 / 512.f}); // init weights Tensor Tensor<TargetType> weights_dev; Tensor<TargetType_H> weights_host; if (group > 1) { weights_dev.re_alloc(weights_s_dw, AK_INT8); weights_host.re_alloc(weights_s_dw, AK_INT8); } else { weights_dev.re_alloc(weights_s, AK_INT8); weights_host.re_alloc(weights_s, AK_INT8); } fill_tensor_rand(weights_dev, -64.0f, 64.0f); weights_host.copy_from(weights_dev); std::vector<float> scale_w_init; for (int i = 0; i < out_channels; i ++) { scale_w_init.push_back(1 / 128.f); } weights_dev.set_scale(scale_w_init); Tensor<TargetType> bias_dev; Tensor<TargetType_H> bias_host; if (bias_term) { bias_dev.re_alloc(bias_s, AK_INT32); bias_host.re_alloc(bias_s, AK_INT32); fill_tensor_rand(bias_dev, -1.0f, 1.0f); bias_host.copy_from(bias_dev); } Tensor<TargetType_H> check_host; Context<TargetType> ctx1(0, 1, 1); ActivationParam<TargetType> act_param; if (relu) { ActivationParam<TargetType> act_relu_param(Active_relu); act_param = act_relu_param; } ConvParam<TargetType> conv_param(group, conv_pad_h, conv_pad_w, conv_stride_h, conv_stride_w, conv_dilation_h, conv_dilation_w, &weights_dev, bias_term ? &bias_dev : nullptr, act_param, 1.f, 0.f,AK_UINT8, round_mode::nearest); PoolingParam<TargetType> pool_param(pool_kernel_h, pool_kernel_w, pool_pad_h, pool_pad_w, pool_stride_h, pool_stride_w, pool_type); ConvPoolingParam<TargetType> param(conv_param, pool_param); // init output Tensor Tensor<TargetType> output_dev; Tensor<TargetType_H> output_host; Tensor<TargetType_H> conv_output_host; if (conv_param.activation_param.has_active) { output_dev.re_alloc(output_s, AK_UINT8); conv_output_host.re_alloc(conv_output_s, AK_UINT8); output_host.re_alloc(output_s, AK_UINT8); output_dev.set_scale({1 / 256.0f}); conv_output_host.set_scale({1 / 256.0f}); } else { output_dev.re_alloc(output_s, AK_INT8); conv_output_host.re_alloc(conv_output_s, AK_INT8); output_host.re_alloc(output_s, AK_INT8); output_dev.set_scale({1 / 128.0f}); conv_output_host.set_scale({1 / 128.0f}); } output_host.copy_from(output_dev); ConvPooling<TargetType, AK_INT8> conv_pooling; std::vector<Tensor<TargetType>* > input_v; std::vector<Tensor<TargetType>* > output_v; input_v.push_back(&input_dev); output_v.push_back(&output_dev); // conv.compute_output_shape(input_v, output_v, param); // output_dev.re_alloc(output_dev.valid_shape(), AK_INT8); if (conv_pooling.init(input_v, output_v, param, strategy, imp, ctx1) == SaberSuccess) { conv_pooling(input_v, output_v, param, ctx1); } else { LOG(INFO) << "init return non Success!"; return -1; } typename Tensor<TargetType>::API::stream_t stream = ctx1.get_compute_stream(); output_v[0]->record_event(stream); output_v[0]->sync(); if (conv_param.activation_param.has_active) { output_host.re_alloc(output_dev.valid_shape(), AK_UINT8); output_host.copy_from(output_dev); // print_tensor_valid(output_host); check_host.re_alloc(output_host.valid_shape(), AK_UINT8); } else { output_host.re_alloc(output_dev.valid_shape(), AK_INT8); output_host.copy_from(output_dev); check_host.re_alloc(output_host.valid_shape(), AK_INT8); } // calc scale info std::vector<float> scale; float scale_in = input_dev.get_scale()[0]; float scale_out = output_dev.get_scale()[0]; auto scale_w = weights_dev.get_scale(); std::vector<float>().swap(scale); for (int i = 0; i < scale_w.size(); i++) { scale.push_back((scale_w[i] * scale_in) / scale_out); } conv_basic_check_int8<X86>(input_host, conv_output_host, (const char*)weights_host.data(), bias_term ? (const int*)bias_host.data() : nullptr, group, conv_kernel_w, conv_kernel_h, conv_stride_w, conv_stride_h, conv_dilation_w, conv_dilation_h, conv_pad_w, conv_pad_h, bias_term, conv_param.activation_param.has_active, scale); pool_basic_check_int8(conv_output_host, check_host, pool_kernel_w, pool_kernel_h, pool_stride_w, pool_stride_h, pool_pad_w, pool_pad_h, pool_type); int count = count_diff((const unsigned char*)output_host.data(), (const unsigned char*)check_host.data(), check_host.valid_size(), 2e-1); // print_tensor_valid(check_host); // double max_ratio = 0.0; // double max_diff = 0.0; // tensor_cmp_host((const float*)output_host.data(), (const float*)check_host.data(), // check_host.valid_size(), max_ratio, max_diff); if ((double)count / output_host.valid_size() < 0.02) { // LOG(INFO) << " PASS!!! max_ratio = " << max_ratio << " max_diff = " << max_diff; LOG(INFO) << "PASS!!! count = " << count; return 0; } else { print_tensor_valid(output_host); print_tensor_valid(check_host); // LOG(FATAL) << "FAIL!!! max_ratio = " << max_ratio << " max_diff = " << max_diff LOG(FATAL) << "FAIL!!! count = " << count << " conv param: " << " input_num = " << input_num << " in_channels = " << in_channels << " height = " << height << " width = " << width << " group = " << group << " conv_pad_h = " << conv_pad_h << " conv_pad_w = " << conv_pad_w << " conv_stride_h = " << conv_stride_h << " conv_stride_w = " << conv_stride_w << " conv_dilation_h = " << conv_dilation_h << " conv_dilation_w = " << conv_dilation_w << " conv_kernel_h = " << conv_kernel_h << " conv_kernel_w = " << conv_kernel_w << " pool_pad_h = " << pool_pad_h << " pool_pad_w = " << pool_pad_w << " pool_stride_h = " << pool_stride_h << " pool_stride_w = " << pool_stride_w << " pool_kernel_h = " << pool_kernel_h << " pool_kernel_w = " << pool_kernel_w << " out_channels = " << out_channels << " relu = " << (relu ? "true" : "false") << " bias_term = " << (bias_term ? "true" : "false"); return -1; } #endif } TEST(TestSaberFunc, test_saber_conv_int8_results) { #ifdef USE_CUDA Env<NV>::env_init(); Env<NVHX86>::env_init(); #endif #ifdef USE_X86_PLACE Env<X86>::env_init(); #endif std::vector<int> groups{1}; std::vector<int> conv_kernel_h_v{3}; std::vector<int> conv_kernel_w_v{3}; std::vector<int> conv_pad_h_v{0}; std::vector<int> conv_pad_w_v{0}; std::vector<int> conv_stride_h_v{1}; std::vector<int> conv_stride_w_v{1}; std::vector<int> conv_dilation_h_v{1}; std::vector<int> conv_dilation_w_v{1}; std::vector<int> pool_kernel_h_v{2, 3}; std::vector<int> pool_kernel_w_v{2, 3}; std::vector<int> pool_pad_h_v{0}; std::vector<int> pool_pad_w_v{0}; std::vector<int> pool_stride_h_v{2, 3}; std::vector<int> pool_stride_w_v{2, 3}; std::vector<PoolingType> pool_type_v{Pooling_max}; std::vector<int> in_channels_v{16}; std::vector<int> out_channels_v{16}; std::vector<int> in_h_v{32}; std::vector<int> in_w_v{32}; std::vector<int> input_num_v{1}; std::vector<bool> bias_term_v{true}; std::vector<bool> relu_v{true}; for (auto group : groups) { for (auto input_num : input_num_v) { for (auto out_channels : out_channels_v) { for (auto in_channels : in_channels_v) { for (auto conv_kernel_h : conv_kernel_h_v) { for (auto conv_kernel_w : conv_kernel_w_v) { for (auto height : in_h_v) { for (auto width : in_w_v) { for (auto conv_stride_h : conv_stride_h_v) { for (auto conv_stride_w : conv_stride_w_v) { for (auto conv_dilation_h : conv_dilation_h_v) { for (auto conv_dilation_w : conv_dilation_w_v) { for (auto conv_pad_h : conv_pad_h_v) { for (auto conv_pad_w : conv_pad_w_v) { for (auto pool_kernel_h : pool_kernel_h_v) { for (auto pool_kernel_w : pool_kernel_w_v) { for (auto pool_stride_h : pool_stride_h_v) { for (auto pool_stride_w : pool_stride_w_v) { for (auto pool_pad_h : pool_pad_h_v) { for (auto pool_pad_w : pool_pad_w_v) { for (auto pool_type : pool_type_v) { for (auto bias_term : bias_term_v) { for (auto relu : relu_v) { #ifdef USE_CUDA #endif #ifdef USE_X86_PLACE if (jit::mayiuse( jit::avx512_core)&&jit::mayiuse( jit::avx512_core_vnni)) { test_conv_pool_results<X86, X86>( group, input_num, in_channels, height, width, out_channels, conv_kernel_h, conv_kernel_w, conv_stride_h, conv_stride_w, conv_dilation_h, conv_dilation_w, conv_pad_h, conv_pad_w, bias_term, relu, pool_stride_h, pool_stride_w, pool_pad_h, pool_pad_w, pool_kernel_h, pool_kernel_w, pool_type, SPECIFY, SABER_IMPL); } #endif } } } } } } } } } } } } } } } } } } } } } } } } int main(int argc, const char** argv) { // initial logger //logger::init(argv[0]); // InitTest(); // RUN_ALL_TESTS(argv[0]); return 0; }
36.879177
116
0.576258
[ "shape", "vector" ]
eb6c7453ef5e6fc6f403c8dcbf073145672a1ce3
13,356
hpp
C++
RobWork/src/rw/geometry/TriangleUtil.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/geometry/TriangleUtil.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/geometry/TriangleUtil.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef RW_GEOMETRY_TRIANGLEUTIL_HPP_ #define RW_GEOMETRY_TRIANGLEUTIL_HPP_ #if !defined(SWIG) #include "PlainTriMesh.hpp" #include "Plane.hpp" #include "TriMesh.hpp" #include "Triangle.hpp" #include <rw/math/Vector3D.hpp> #include <stack> #endif namespace rw { namespace geometry { //! @addtogroup geometry // @{ /** * @brief utility for triangle manipulation */ class TriangleUtil { private: template< class T > struct VertexCmp { public: VertexCmp () : vertIdx (-1) {} VertexCmp (const rw::math::Vector3D< T >& val, int tidx, int vidx, int* axisp) : n (val), triIdx (tidx), vertIdx (vidx), _axisPtr (axisp) {} bool operator< (VertexCmp< T > const& other) const { return n[*_axisPtr] < other.n[*_axisPtr]; } rw::math::Vector3D< T > n; int triIdx; int vertIdx; int* _axisPtr; }; struct SortJob { public: SortJob (int a, int f, int t) : axis (a), from (f), to (t) {} int axis; int from; int to; void print () const { std::cout << "Job: " << axis << " " << from << "-->" << to << std::endl; } }; /** * @brief creates a sorted indexed verticelist. The vertice list is * indexed into the triangle mesh so that each vertice "knows" the triangle * that its comming from. */ template< class T > static std::vector< VertexCmp< T > >* createSortedVerticeIdxList (const TriMesh& triMesh, double epsilon) { using namespace rw::math; std::vector< VertexCmp< T > >* verticesIdx = new std::vector< VertexCmp< T > > (triMesh.getSize () * 3); int axis = 0; // now copy all relevant info into the compare list rw::geometry::Triangle< T > tri; for (size_t i = 0; i < triMesh.getSize (); i++) { int vIdx = (int) i * 3; triMesh.getTriangle (i, tri); RW_ASSERT (vIdx + 0 < (int) verticesIdx->size ()); RW_ASSERT (vIdx + 1 < (int) verticesIdx->size ()); RW_ASSERT (vIdx + 2 < (int) verticesIdx->size ()); (*verticesIdx)[vIdx + 0] = VertexCmp< T > (tri[0], (int) i, 0, &axis); (*verticesIdx)[vIdx + 1] = VertexCmp< T > (tri[1], (int) i, 1, &axis); (*verticesIdx)[vIdx + 2] = VertexCmp< T > (tri[2], (int) i, 2, &axis); } // first sort all vertices into one large array axis = 0; std::sort (verticesIdx->begin (), verticesIdx->end ()); // run through the semi sorted list and merge vertices that are alike std::stack< SortJob > sjobs; sjobs.push (SortJob (0, 0, (int) (verticesIdx->size () - 1))); while (!sjobs.empty ()) { SortJob job = sjobs.top (); sjobs.pop (); if (job.from == job.to) continue; // locate the next end int j = job.from; RW_ASSERT_MSG (j < (int) verticesIdx->size (), j << "<" << verticesIdx->size ()); RW_ASSERT (job.axis < 3); T axisVal, lastAxisVal = (*verticesIdx)[j].n[job.axis]; do { j++; axisVal = (*verticesIdx)[j].n[job.axis]; } while (axisVal < lastAxisVal + epsilon && j < job.to); // if j==job.to, then we might have two possible outcomes, // we change j to point to the element that is not equal to lastVal if (j == job.to && axisVal < lastAxisVal + epsilon) j++; // the previus has determined an interval [job.from;j] in which values in job.axis // equal now add the unproccessed in a new job [j;job.to] if (j < job.to) sjobs.push (SortJob (job.axis, j, job.to)); if (job.axis == 0) sjobs.push (SortJob (job.axis + 1, job.from, j - 1)); axis = job.axis + 1; std::sort (verticesIdx->begin () + job.from, verticesIdx->begin () + j); } return verticesIdx; } public: /** * @brief Takes a general triangle mesh and creates an indexed * triangle mesh. All data is copied. * * The order of the triangles in the new mesh will be the same as that of * the old mesh. This is not true for the vertices. * @param triMesh [in] the tri mesh that is to be converted * @param epsilon [in] if two vertices are closer than epsilon they * are considered the equal. */ template< class TRILIST > static rw::core::Ptr< TRILIST > toIndexedTriMesh (const TriMesh& triMesh, double epsilon = 0.00001) { typedef typename TRILIST::value_type T; typedef typename TRILIST::tri_type TRI; typedef typename TRILIST::index_type S; typedef typename TRILIST::TriangleArray TriangleArray; using namespace rw::math; if (triMesh.getSize () == 0) RW_THROW ("Size of mesh must be more than 0!"); // create a sorted vertice list with backreference to the triangle list std::vector< VertexCmp< T > >* verticesIdx = createSortedVerticeIdxList< T > (triMesh, epsilon); // Now copy all sorted vertices into the vertice array // and make sure vertices that are close to each other are discarded std::vector< Vector3D< T > >* vertices = new std::vector< Vector3D< T > > (triMesh.getSize () * 3); // allocate enough memory TriangleArray* triangles = new TriangleArray (triMesh.getSize ()); S vertCnt = 0; Vector3D< T > lastVert = (*verticesIdx)[0].n; (*vertices)[vertCnt] = lastVert; TRI& itri = (*triangles)[(*verticesIdx)[0].triIdx]; itri[(*verticesIdx)[0].vertIdx] = vertCnt; for (size_t i = 1; i < verticesIdx->size (); i++) { // check if vertices are too close if (MetricUtil::dist2 (lastVert, (*verticesIdx)[i].n) > epsilon) { lastVert = (*verticesIdx)[i].n; vertCnt++; (*vertices)[vertCnt] = lastVert; } S triIdx = (*verticesIdx)[i].triIdx; S vertTriIdx = (*verticesIdx)[i].vertIdx; // update the triangle index for this vertice ((*triangles)[triIdx])[vertTriIdx] = vertCnt; } vertices->resize (vertCnt + 1); delete verticesIdx; return rw::core::ownedPtr ( new TRILIST (rw::core::ownedPtr (vertices), rw::core::ownedPtr (triangles))); } /** * @brief Recalculate the normals of \b trimesh */ template< class T > static void recalcNormals (rw::geometry::PlainTriMesh< rw::geometry::TriangleN1< T > >& trimesh) { using namespace rw::math; for (size_t i = 0; i < trimesh.getSize (); i++) { Vector3D< T > normal = trimesh[i].calcFaceNormal (); trimesh[i].getFaceNormal () = normal; } } /** * @brief Divided \b trimesh using the specified plane * * Triangles is cut by the plane and replaced with new triangles. * Triangles lying in the plane is placed with the triangles behind. * * @return First item in the pair is the triangles in front of the plane and second item is * the triangles behind or in the plane. */ template< class TRI > static std::pair< TriMesh::Ptr, TriMesh::Ptr > divide (TriMesh::Ptr trimesh, Plane::Ptr plane) { typedef typename TRI::value_type T; using namespace rw::math; typename PlainTriMesh< TRI >::Ptr front = rw::core::ownedPtr (new PlainTriMesh< TRI > ()); typename PlainTriMesh< TRI >::Ptr back = rw::core::ownedPtr (new PlainTriMesh< TRI > ()); for (size_t i = 0; i < trimesh->size (); i++) { const rw::geometry::Triangle < double >& tri = trimesh->getTriangle (i); double d0 = plane->distance (tri.getVertex (0)); double d1 = plane->distance (tri.getVertex (1)); double d2 = plane->distance (tri.getVertex (2)); // std::cout<<"d0 = "<<d0<<" d1 = "<<d1<<" d2 = "<<d2<<std::endl; if (d0 <= 0 && d1 <= 0 && d2 <= 0) { back->add (tri); } else if (d0 >= 0 && d1 >= 0 && d2 >= 0) { front->add (tri); } else { std::vector< int > behind; std::vector< int > infront; if (d0 < 0) behind.push_back (0); else infront.push_back (0); if (d1 < 0) behind.push_back (1); else infront.push_back (1); if (d2 < 0) behind.push_back (2); else infront.push_back (2); if (behind.size () == 2) { Vector3D< T > b1 = tri.getVertex (behind[0]); Vector3D< T > b2 = tri.getVertex (behind[1]); Vector3D< T > f1 = tri.getVertex (infront[0]); Vector3D< T > i1 = plane->intersection (b1, f1); Vector3D< T > i2 = plane->intersection (b2, f1); if (d0 > 0 || d2 > 0) { TRI trib1 (b1, i2, i1); TRI trib2 (b1, b2, i2); TRI trif1 (i1, i2, f1); back->add (trib1); back->add (trib2); front->add (trif1); } else { TRI trib1 (b1, i1, i2); TRI trib2 (b1, i2, b2); TRI trif1 (i1, f1, i2); back->add (trib1); back->add (trib2); front->add (trif1); } } else { // inFront.size() == 2 Vector3D< T > b1 = tri.getVertex (behind[0]); Vector3D< T > f1 = tri.getVertex (infront[0]); Vector3D< T > f2 = tri.getVertex (infront[1]); Vector3D< T > i1 = plane->intersection (b1, f1); Vector3D< T > i2 = plane->intersection (b1, f2); if (d0 < 0 || d2 < 0) { TRI trif1 (f1, i2, i1); TRI trif2 (f1, f2, i2); TRI trib1 (b1, i1, i2); front->add (trif1); front->add (trif2); back->add (trib1); } else { TRI trif1 (f1, i1, i2); TRI trif2 (f1, i2, f2); TRI trib1 (b1, i2, i1); front->add (trif1); front->add (trif2); back->add (trib1); } } } } return std::make_pair (front, back); } }; // @} }} // namespace rw::geometry #endif // end include guard
40.228916
124
0.454328
[ "mesh", "geometry", "vector" ]
eb6ef8212c12f7fdf8c5a868215a8e9136ef7bfb
904
cpp
C++
auto_mutex.cpp
alecmus/leccore
42d81fbf513e069396c372367161e341d66ba5f3
[ "MIT" ]
null
null
null
auto_mutex.cpp
alecmus/leccore
42d81fbf513e069396c372367161e341d66ba5f3
[ "MIT" ]
1
2021-07-08T20:43:24.000Z
2021-07-08T20:49:48.000Z
auto_mutex.cpp
alecmus/leccore
42d81fbf513e069396c372367161e341d66ba5f3
[ "MIT" ]
1
2021-05-13T20:02:10.000Z
2021-05-13T20:02:10.000Z
// // auto_mutex.cpp - auto mutex implementation // // leccore library, part of the liblec library // Copyright (c) 2019 Alec Musasa (alecmus at live dot com) // // Released under the MIT license. For full details see the // file LICENSE.txt // #include "leccore_common.h" #include <mutex> class mutex; // Wrapper for the std::mutex object. class liblec::leccore::mutex::impl { std::mutex _mtx; public: impl() {} ~impl() {} void lock() { _mtx.lock(); } void unlock() { _mtx.unlock(); } }; liblec::leccore::mutex::mutex() : _d(*new impl()) {} liblec::leccore::mutex::~mutex() { delete& _d; } class liblec::leccore::auto_mutex::impl { mutex& _mtx; public: impl(mutex& mtx) : _mtx(mtx) { _mtx._d.lock(); } ~impl() { _mtx._d.unlock(); } }; liblec::leccore::auto_mutex::auto_mutex(mutex& mtx) : _d(*new impl(mtx)) {} liblec::leccore::auto_mutex::~auto_mutex() { delete& _d; }
17.384615
75
0.646018
[ "object" ]
eb7568043c5d21699a3f5ee4a0782d943c6a1a3c
1,967
cc
C++
garnet/lib/ui/gfx/util/tests/collection_utils_unittest.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
1
2019-04-21T18:02:26.000Z
2019-04-21T18:02:26.000Z
garnet/lib/ui/gfx/util/tests/collection_utils_unittest.cc
zhangpf/fuchsia-rs
903568f28ddf45f09157ead36d61b50322c9cf49
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
garnet/lib/ui/gfx/util/tests/collection_utils_unittest.cc
ZVNexus/fuchsia
c5610ad15208208c98693618a79c705af935270c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "garnet/lib/ui/gfx/util/collection_utils.h" #include <gtest/gtest.h> namespace { using namespace scenic_impl::gfx; class WeakValue { public: WeakValue(int value) : value_(value), weak_factory_(this) {} int value() const { return value_; } fxl::WeakPtr<WeakValue> GetWeakPtr() { return weak_factory_.GetWeakPtr(); } private: int value_; fxl::WeakPtrFactory<WeakValue> weak_factory_; // must be last }; } // anonymous namespace TEST(CollectionUtils, ApplyToCompactedVector) { auto weak1 = std::make_unique<WeakValue>(1); auto weak2 = std::make_unique<WeakValue>(2); auto weak3 = std::make_unique<WeakValue>(3); auto weak4 = std::make_unique<WeakValue>(4); auto weak5 = std::make_unique<WeakValue>(5); auto weak6 = std::make_unique<WeakValue>(6); std::vector<fxl::WeakPtr<WeakValue>> values{ weak1->GetWeakPtr(), weak2->GetWeakPtr(), weak3->GetWeakPtr(), weak4->GetWeakPtr(), weak5->GetWeakPtr(), weak6->GetWeakPtr(), }; int sum = 0; auto AddToSum = [&sum](WeakValue* val) { sum += val->value(); }; ApplyToCompactedVector(&values, AddToSum); EXPECT_EQ(sum, 21); EXPECT_EQ(values.size(), 6U); // Delete the third value; the sum should be reduced by 3 and the size of the // vector by 1. sum = 0; weak3.reset(); ApplyToCompactedVector(&values, AddToSum); EXPECT_EQ(sum, 18); EXPECT_EQ(values.size(), 5U); // Reapply the closure; the result and vector size should remain unchanged. sum = 0; ApplyToCompactedVector(&values, AddToSum); EXPECT_EQ(sum, 18); EXPECT_EQ(values.size(), 5U); // Delete multiple values, including the first and last ones. sum = 0; weak1.reset(); weak4.reset(); weak6.reset(); ApplyToCompactedVector(&values, AddToSum); EXPECT_EQ(sum, 7); EXPECT_EQ(values.size(), 2U); }
28.507246
79
0.696492
[ "vector" ]
eb78ddfd357813b18b5281c59bde45ffc18910f7
2,137
hpp
C++
rmf_traffic/src/rmf_traffic/agv/internal_Planner.hpp
MakinoharaShouko/rmf_core
727048469f9ce14d6e76628dec96a84ca1ce99f9
[ "Apache-2.0" ]
null
null
null
rmf_traffic/src/rmf_traffic/agv/internal_Planner.hpp
MakinoharaShouko/rmf_core
727048469f9ce14d6e76628dec96a84ca1ce99f9
[ "Apache-2.0" ]
null
null
null
rmf_traffic/src/rmf_traffic/agv/internal_Planner.hpp
MakinoharaShouko/rmf_core
727048469f9ce14d6e76628dec96a84ca1ce99f9
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef SRC__RMF_TRAFFIC__AGV__INTERNAL_PLANNER_HPP #define SRC__RMF_TRAFFIC__AGV__INTERNAL_PLANNER_HPP #include <rmf_traffic/agv/Planner.hpp> #include "internal_planning.hpp" namespace rmf_traffic { namespace agv { //============================================================================== class Plan::Waypoint::Implementation { public: Eigen::Vector3d position; rmf_traffic::Time time; rmf_utils::optional<std::size_t> graph_index; Graph::Lane::EventPtr event; template<typename... Args> static Waypoint make(Args&& ... args) { Waypoint wp; wp._pimpl = rmf_utils::make_impl<Implementation>( Implementation{std::forward<Args>(args)...}); return wp; } }; //============================================================================== class Planner::Result::Implementation { public: rmf_traffic::internal::planning::CacheManager cache_mgr; rmf_traffic::internal::planning::State state; rmf_utils::optional<Plan> plan; static Result generate( rmf_traffic::internal::planning::CacheManager cache_mgr, const std::vector<Planner::Start>& starts, Planner::Goal goal, Planner::Options options); static Result setup( rmf_traffic::internal::planning::CacheManager cache_mgr, const std::vector<Planner::Start>& starts, Planner::Goal goal, Planner::Options options); static const Implementation& get(const Result& r); }; } // namespace agv } // namespace rmf_traffic #endif // SRC__RMF_TRAFFIC__AGV__INTERNAL_PLANNER_HPP
26.060976
80
0.680861
[ "vector" ]
eb853f78762b25bdf9827e7ff7fcabafcc1da144
5,847
cpp
C++
lib/util.cpp
soyfestivo/socialite
fe33627bb21dcedd49a42cd03958b284bdf9f413
[ "MIT" ]
1
2018-04-02T12:54:58.000Z
2018-04-02T12:54:58.000Z
lib/util.cpp
soyfestivo/socialite
fe33627bb21dcedd49a42cd03958b284bdf9f413
[ "MIT" ]
2
2018-03-09T05:34:03.000Z
2018-03-22T18:58:33.000Z
lib/util.cpp
soyfestivo/socialite
fe33627bb21dcedd49a42cd03958b284bdf9f413
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <ctime> #include <fcntl.h> #include <unistd.h> #include <sys/wait.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <math.h> #include <cmath> #include <float.h> #include <openssl/ssl.h> #include <openssl/sha.h> #include <regex> #include <iomanip> #include "util.h" using std::string; using std::regex; using std::smatch; string Socialite::Util::toHttpTimestamp(time_t stamp) { struct tm* t = gmtime(&stamp); char buffer[256]; strftime(buffer, 256, "%a, %e %b %Y %T GMT", t); return string(buffer); } time_t Socialite::Util::parseHttpTimestamp(string stamp) { //Mon, 13 Jun 2016 21:24:31 GMT smatch matcher; // regex shape("^(?:[A-Za-z]{3}), ([0-9]{1,2}) ([A-Za-z]{3,4}) ([0-9]{4}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}) ([A-Za-z]{3,4})$"); const char* dates[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; if(regex_match(stamp, matcher, shape)) { regex_search(stamp, matcher, shape); //cout << matcher[4] << "\n"; int m = 0; string tmp = matcher[2]; char* month = (char*) tmp.c_str(); for(int i = 0; i < 12; i++) { if(strcmp(dates[i], month) == 0) { m = i; } } time_t now; time(&now); struct tm* t = localtime(&now); t->tm_year = std::stoi(matcher[3]) - 1900; t->tm_mon = m; t->tm_mday = std::stoi(matcher[1]); t->tm_hour = std::stoi(matcher[4]); t->tm_min = std::stoi(matcher[5]); t->tm_sec = std::stoi(matcher[6]); return mktime(t); } return (time_t) 0; } string Socialite::Util::getTimestampTime(time_t stamp) { struct tm* t = localtime(&stamp); char buffer[256]; strftime(buffer, 256, "%T", t); return string(buffer); } void Socialite::Util::mapPostData(std::map<std::string, std::string>& mapper, std::string str) { std::smatch matcher; std::regex shape("([A-Za-z0-9\\-]+)=([^&]*)"); //std::cout << "Socialite::Util::mapPostData " << str << "\n"; while(std::regex_search(str, matcher, shape)) { mapper[string(matcher[1])] = string(matcher[2]); str = matcher.suffix().str(); } } string Socialite::Util::sha256(string str) { char* c_string = (char*) str.c_str(); char outputBuffer[65]; unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256_CTX sha256; SHA256_Init(&sha256); SHA256_Update(&sha256, c_string, strlen(c_string)); SHA256_Final(hash, &sha256); int i = 0; for(i = 0; i < SHA256_DIGEST_LENGTH; i++) { sprintf(outputBuffer + (i * 2), "%02x", hash[i]); } outputBuffer[64] = 0; return string(outputBuffer); } const char base64_url_alphabet[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' }; std::string base64Encode(const std::string& in) { std::string out; int val =0, valb=-6; size_t len = in.length(); unsigned int i = 0; for (i = 0; i < len; i++) { unsigned char c = in[i]; val = (val<<8) + c; valb += 8; while (valb >= 0) { out.push_back(base64_url_alphabet[(val>>valb)&0x3F]); valb -= 6; } } if (valb > -6) { out.push_back(base64_url_alphabet[((val<<8)>>(valb+8))&0x3F]); } return out; } std::string base64Decode(const std::string& in) { std::string out; std::vector<int> T(256, -1); unsigned int i; for (i =0; i < 64; i++) T[base64_url_alphabet[i]] = i; int val = 0, valb = -8; for (i = 0; i < in.length(); i++) { unsigned char c = in[i]; if (T[c] == -1) break; val = (val<<6) + T[c]; valb += 6; if (valb >= 0) { out.push_back(char((val>>valb)&0xFF)); valb -= 8; } } return out; } std::string removeChar(std::string str, char c) { std::stringstream ss; for(int i = 0; i < str.length(); i++) { if(str[i] != c) { ss << str[i]; } } return ss.str(); } std::string Socialite::Util::generateJwt(Json::Value value, std::string secretKey) { Json::Value jwtHeader; jwtHeader["alg"] = "HS256"; jwtHeader["typ"] = "JWT"; std::string jwtHeaderBase64 = removeChar(base64Encode(jwtHeader.toStyledString()), '='); std::string contentBase64 = removeChar(base64Encode(value.toStyledString()), '='); std::string messageToEncrypt = jwtHeaderBase64 + "." + contentBase64; unsigned char hash[32]; HMAC_CTX hmac; HMAC_CTX_init(&hmac); HMAC_Init_ex(&hmac, &secretKey[0], secretKey.length(), EVP_sha256(), NULL); HMAC_Update(&hmac, (unsigned char*) &messageToEncrypt[0], messageToEncrypt.length()); unsigned int len = 32; HMAC_Final(&hmac, hash, &len); HMAC_CTX_cleanup(&hmac); std::stringstream ss; ss << std::setfill('0'); for (int i = 0; i < len; i++) { ss << hash[i]; } std::string hmacSignatureBase64 = removeChar(base64Encode(ss.str()), '='); return jwtHeaderBase64 + "." + contentBase64 + "." + hmacSignatureBase64; } std::string Socialite::Util::generateRandomString(int length) { const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; char buffer[length+1]; for (int i = 0; i < length; ++i) { buffer[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } buffer[length] = 0; return std::string(buffer); } Json::Value Socialite::Util::verifyAndReadJwt(std::string jwt, std::string secretKey) { smatch matcher; regex jwtShape("^.*\\.(.*)\\..*$"); std::string payload; if(regex_match(jwt, matcher, jwtShape)) { payload = base64Decode(matcher[1]); } Json::Value root; Json::Reader reader; reader.parse(payload, root); if(generateJwt(root, secretKey) != jwt) { throw -1; } return root; }
26.577273
130
0.590217
[ "shape", "vector" ]
eb85a44434877e6efdb34448c22db57ae31f4ee6
51,007
cxx
C++
Interaction/Widgets/Testing/Cxx/TestCellCentersPointPlacer.cxx
inviCRO/VTK
a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48
[ "BSD-3-Clause" ]
2
2017-12-08T07:50:51.000Z
2018-07-22T19:12:56.000Z
Interaction/Widgets/Testing/Cxx/TestCellCentersPointPlacer.cxx
inviCRO/VTK
a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48
[ "BSD-3-Clause" ]
14
2015-04-25T17:54:13.000Z
2017-01-13T15:30:39.000Z
Interaction/Widgets/Testing/Cxx/TestCellCentersPointPlacer.cxx
inviCRO/VTK
a2dc2e79d4ecb8f6da900535b32e1a2a702c7f48
[ "BSD-3-Clause" ]
1
2015-03-13T17:21:31.000Z
2015-03-13T17:21:31.000Z
/*========================================================================= Program: Visualization Toolkit Module: TestGenericCell.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // This test demonstrates the vtkCellCentersPointPlacer. The placer may // be used to constrain handle widgets to the centers of cells. Thus it // may be used by any of the widgets that use the handles (distance, angle // etc). // Here we demonstrates constraining the distance widget to the centers // of various cells. // #include <vtkSmartPointer.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkUnstructuredGrid.h> #include <vtkDataSetMapper.h> #include <vtkActor.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <vtkCamera.h> #include <vtkTransformFilter.h> #include <vtkMatrixToLinearTransform.h> #include <vtkMatrix4x4.h> #include <vtkProperty.h> #include <vtkDistanceWidget.h> #include <vtkDistanceRepresentation2D.h> #include <vtkCellCentersPointPlacer.h> #include <vtkPointHandleRepresentation3D.h> #include <vtkCellPicker.h> #include <vtkAxisActor2D.h> #include <vtkProperty2D.h> #include <vtkTesting.h> #include <vtkHexagonalPrism.h> #include <vtkHexahedron.h> #include <vtkPentagonalPrism.h> #include <vtkPolyhedron.h> #include <vtkPyramid.h> #include <vtkTetra.h> #include <vtkVoxel.h> #include <vtkWedge.h> #include <vector> //--------------------------------------------------------------------------- const char TestCellCentersPointPlacerEventLog[] = "# StreamVersion 1\n" "EnterEvent 384 226 0 0 0 0 0\n" "MouseMoveEvent 384 226 0 0 0 0 0\n" "RenderEvent 384 226 0 0 0 0 0\n" "MouseMoveEvent 384 226 0 0 0 0 0\n" "MouseMoveEvent 383 226 0 0 0 0 0\n" "MouseMoveEvent 382 227 0 0 0 0 0\n" "MouseMoveEvent 381 227 0 0 0 0 0\n" "MouseMoveEvent 381 229 0 0 0 0 0\n" "MouseMoveEvent 379 229 0 0 0 0 0\n" "MouseMoveEvent 377 230 0 0 0 0 0\n" "MouseMoveEvent 376 231 0 0 0 0 0\n" "MouseMoveEvent 374 232 0 0 0 0 0\n" "MouseMoveEvent 370 234 0 0 0 0 0\n" "MouseMoveEvent 366 236 0 0 0 0 0\n" "MouseMoveEvent 360 237 0 0 0 0 0\n" "MouseMoveEvent 355 237 0 0 0 0 0\n" "MouseMoveEvent 348 237 0 0 0 0 0\n" "MouseMoveEvent 342 237 0 0 0 0 0\n" "MouseMoveEvent 336 237 0 0 0 0 0\n" "MouseMoveEvent 330 237 0 0 0 0 0\n" "MouseMoveEvent 324 237 0 0 0 0 0\n" "MouseMoveEvent 318 237 0 0 0 0 0\n" "MouseMoveEvent 313 237 0 0 0 0 0\n" "MouseMoveEvent 307 237 0 0 0 0 0\n" "MouseMoveEvent 303 237 0 0 0 0 0\n" "MouseMoveEvent 299 237 0 0 0 0 0\n" "MouseMoveEvent 293 237 0 0 0 0 0\n" "MouseMoveEvent 290 235 0 0 0 0 0\n" "MouseMoveEvent 287 234 0 0 0 0 0\n" "MouseMoveEvent 285 233 0 0 0 0 0\n" "MouseMoveEvent 282 232 0 0 0 0 0\n" "MouseMoveEvent 280 231 0 0 0 0 0\n" "MouseMoveEvent 278 230 0 0 0 0 0\n" "MouseMoveEvent 276 230 0 0 0 0 0\n" "MouseMoveEvent 275 229 0 0 0 0 0\n" "MouseMoveEvent 274 229 0 0 0 0 0\n" "MouseMoveEvent 274 228 0 0 0 0 0\n" "MouseMoveEvent 272 221 0 0 0 0 0\n" "MouseMoveEvent 272 213 0 0 0 0 0\n" "MouseMoveEvent 270 202 0 0 0 0 0\n" "MouseMoveEvent 269 193 0 0 0 0 0\n" "MouseMoveEvent 269 184 0 0 0 0 0\n" "MouseMoveEvent 267 174 0 0 0 0 0\n" "MouseMoveEvent 267 165 0 0 0 0 0\n" "MouseMoveEvent 267 157 0 0 0 0 0\n" "MouseMoveEvent 267 151 0 0 0 0 0\n" "MouseMoveEvent 265 147 0 0 0 0 0\n" "MouseMoveEvent 264 144 0 0 0 0 0\n" "MouseMoveEvent 263 142 0 0 0 0 0\n" "MouseMoveEvent 262 139 0 0 0 0 0\n" "MouseMoveEvent 262 137 0 0 0 0 0\n" "MouseMoveEvent 261 134 0 0 0 0 0\n" "MouseMoveEvent 259 132 0 0 0 0 0\n" "MouseMoveEvent 259 129 0 0 0 0 0\n" "MouseMoveEvent 257 127 0 0 0 0 0\n" "MouseMoveEvent 256 124 0 0 0 0 0\n" "MouseMoveEvent 255 123 0 0 0 0 0\n" "MouseMoveEvent 254 121 0 0 0 0 0\n" "MouseMoveEvent 253 121 0 0 0 0 0\n" "MouseMoveEvent 251 121 0 0 0 0 0\n" "MouseMoveEvent 251 120 0 0 0 0 0\n" "MouseMoveEvent 250 120 0 0 0 0 0\n" "MouseMoveEvent 249 120 0 0 0 0 0\n" "MouseMoveEvent 248 120 0 0 0 0 0\n" "MouseMoveEvent 247 120 0 0 0 0 0\n" "MouseMoveEvent 246 120 0 0 0 0 0\n" "MouseMoveEvent 245 120 0 0 0 0 0\n" "MouseMoveEvent 244 119 0 0 0 0 0\n" "MouseMoveEvent 242 119 0 0 0 0 0\n" "MouseMoveEvent 240 119 0 0 0 0 0\n" "MouseMoveEvent 238 119 0 0 0 0 0\n" "MouseMoveEvent 237 119 0 0 0 0 0\n" "MouseMoveEvent 236 119 0 0 0 0 0\n" "MouseMoveEvent 235 119 0 0 0 0 0\n" "MouseMoveEvent 234 119 0 0 0 0 0\n" "MouseMoveEvent 233 119 0 0 0 0 0\n" "MouseMoveEvent 229 119 0 0 0 0 0\n" "MouseMoveEvent 227 119 0 0 0 0 0\n" "MouseMoveEvent 224 119 0 0 0 0 0\n" "MouseMoveEvent 220 119 0 0 0 0 0\n" "MouseMoveEvent 217 118 0 0 0 0 0\n" "MouseMoveEvent 215 117 0 0 0 0 0\n" "MouseMoveEvent 213 116 0 0 0 0 0\n" "MouseMoveEvent 211 115 0 0 0 0 0\n" "MouseMoveEvent 209 114 0 0 0 0 0\n" "MouseMoveEvent 207 114 0 0 0 0 0\n" "MouseMoveEvent 205 113 0 0 0 0 0\n" "MouseMoveEvent 204 111 0 0 0 0 0\n" "MouseMoveEvent 203 111 0 0 0 0 0\n" "MouseMoveEvent 202 110 0 0 0 0 0\n" "MouseMoveEvent 201 110 0 0 0 0 0\n" "MouseMoveEvent 200 110 0 0 0 0 0\n" "MouseMoveEvent 199 109 0 0 0 0 0\n" "MouseMoveEvent 198 108 0 0 0 0 0\n" "MouseMoveEvent 198 107 0 0 0 0 0\n" "MouseMoveEvent 197 106 0 0 0 0 0\n" "LeftButtonPressEvent 197 106 0 0 0 0 0\n" "RenderEvent 197 106 0 0 0 0 0\n" "LeftButtonReleaseEvent 197 106 0 0 0 0 0\n" "MouseMoveEvent 197 106 0 0 0 0 0\n" "RenderEvent 197 106 0 0 0 0 0\n" "MouseMoveEvent 197 107 0 0 0 0 0\n" "RenderEvent 197 107 0 0 0 0 0\n" "MouseMoveEvent 198 107 0 0 0 0 0\n" "RenderEvent 198 107 0 0 0 0 0\n" "MouseMoveEvent 199 107 0 0 0 0 0\n" "RenderEvent 199 107 0 0 0 0 0\n" "MouseMoveEvent 199 108 0 0 0 0 0\n" "RenderEvent 199 108 0 0 0 0 0\n" "MouseMoveEvent 201 108 0 0 0 0 0\n" "RenderEvent 201 108 0 0 0 0 0\n" "MouseMoveEvent 201 109 0 0 0 0 0\n" "RenderEvent 201 109 0 0 0 0 0\n" "MouseMoveEvent 202 110 0 0 0 0 0\n" "RenderEvent 202 110 0 0 0 0 0\n" "MouseMoveEvent 204 110 0 0 0 0 0\n" "RenderEvent 204 110 0 0 0 0 0\n" "MouseMoveEvent 205 112 0 0 0 0 0\n" "RenderEvent 205 112 0 0 0 0 0\n" "MouseMoveEvent 208 114 0 0 0 0 0\n" "RenderEvent 208 114 0 0 0 0 0\n" "MouseMoveEvent 209 114 0 0 0 0 0\n" "RenderEvent 209 114 0 0 0 0 0\n" "MouseMoveEvent 211 116 0 0 0 0 0\n" "RenderEvent 211 116 0 0 0 0 0\n" "MouseMoveEvent 214 117 0 0 0 0 0\n" "RenderEvent 214 117 0 0 0 0 0\n" "MouseMoveEvent 216 119 0 0 0 0 0\n" "RenderEvent 216 119 0 0 0 0 0\n" "MouseMoveEvent 219 121 0 0 0 0 0\n" "RenderEvent 219 121 0 0 0 0 0\n" "MouseMoveEvent 222 122 0 0 0 0 0\n" "RenderEvent 222 122 0 0 0 0 0\n" "MouseMoveEvent 226 124 0 0 0 0 0\n" "RenderEvent 226 124 0 0 0 0 0\n" "MouseMoveEvent 229 126 0 0 0 0 0\n" "RenderEvent 229 126 0 0 0 0 0\n" "MouseMoveEvent 232 128 0 0 0 0 0\n" "RenderEvent 232 128 0 0 0 0 0\n" "MouseMoveEvent 236 130 0 0 0 0 0\n" "RenderEvent 236 130 0 0 0 0 0\n" "MouseMoveEvent 240 132 0 0 0 0 0\n" "RenderEvent 240 132 0 0 0 0 0\n" "MouseMoveEvent 245 133 0 0 0 0 0\n" "RenderEvent 245 133 0 0 0 0 0\n" "MouseMoveEvent 250 135 0 0 0 0 0\n" "RenderEvent 250 135 0 0 0 0 0\n" "MouseMoveEvent 255 138 0 0 0 0 0\n" "RenderEvent 255 138 0 0 0 0 0\n" "MouseMoveEvent 264 141 0 0 0 0 0\n" "RenderEvent 264 141 0 0 0 0 0\n" "MouseMoveEvent 269 142 0 0 0 0 0\n" "RenderEvent 269 142 0 0 0 0 0\n" "MouseMoveEvent 275 144 0 0 0 0 0\n" "RenderEvent 275 144 0 0 0 0 0\n" "MouseMoveEvent 279 146 0 0 0 0 0\n" "RenderEvent 279 146 0 0 0 0 0\n" "MouseMoveEvent 286 149 0 0 0 0 0\n" "RenderEvent 286 149 0 0 0 0 0\n" "MouseMoveEvent 288 151 0 0 0 0 0\n" "RenderEvent 288 151 0 0 0 0 0\n" "MouseMoveEvent 289 152 0 0 0 0 0\n" "RenderEvent 289 152 0 0 0 0 0\n" "MouseMoveEvent 292 155 0 0 0 0 0\n" "RenderEvent 292 155 0 0 0 0 0\n" "MouseMoveEvent 295 158 0 0 0 0 0\n" "RenderEvent 295 158 0 0 0 0 0\n" "MouseMoveEvent 296 159 0 0 0 0 0\n" "RenderEvent 296 159 0 0 0 0 0\n" "MouseMoveEvent 299 162 0 0 0 0 0\n" "RenderEvent 299 162 0 0 0 0 0\n" "MouseMoveEvent 302 164 0 0 0 0 0\n" "RenderEvent 302 164 0 0 0 0 0\n" "MouseMoveEvent 305 167 0 0 0 0 0\n" "RenderEvent 305 167 0 0 0 0 0\n" "MouseMoveEvent 307 168 0 0 0 0 0\n" "RenderEvent 307 168 0 0 0 0 0\n" "MouseMoveEvent 310 170 0 0 0 0 0\n" "RenderEvent 310 170 0 0 0 0 0\n" "MouseMoveEvent 313 171 0 0 0 0 0\n" "RenderEvent 313 171 0 0 0 0 0\n" "MouseMoveEvent 314 173 0 0 0 0 0\n" "RenderEvent 314 173 0 0 0 0 0\n" "MouseMoveEvent 317 175 0 0 0 0 0\n" "RenderEvent 317 175 0 0 0 0 0\n" "MouseMoveEvent 319 177 0 0 0 0 0\n" "RenderEvent 319 177 0 0 0 0 0\n" "MouseMoveEvent 321 179 0 0 0 0 0\n" "RenderEvent 321 179 0 0 0 0 0\n" "MouseMoveEvent 323 180 0 0 0 0 0\n" "RenderEvent 323 180 0 0 0 0 0\n" "MouseMoveEvent 325 181 0 0 0 0 0\n" "RenderEvent 325 181 0 0 0 0 0\n" "MouseMoveEvent 326 182 0 0 0 0 0\n" "RenderEvent 326 182 0 0 0 0 0\n" "MouseMoveEvent 330 185 0 0 0 0 0\n" "RenderEvent 330 185 0 0 0 0 0\n" "MouseMoveEvent 332 186 0 0 0 0 0\n" "RenderEvent 332 186 0 0 0 0 0\n" "MouseMoveEvent 333 187 0 0 0 0 0\n" "RenderEvent 333 187 0 0 0 0 0\n" "MouseMoveEvent 336 188 0 0 0 0 0\n" "RenderEvent 336 188 0 0 0 0 0\n" "MouseMoveEvent 337 189 0 0 0 0 0\n" "RenderEvent 337 189 0 0 0 0 0\n" "MouseMoveEvent 339 190 0 0 0 0 0\n" "RenderEvent 339 190 0 0 0 0 0\n" "MouseMoveEvent 340 190 0 0 0 0 0\n" "RenderEvent 340 190 0 0 0 0 0\n" "MouseMoveEvent 341 191 0 0 0 0 0\n" "RenderEvent 341 191 0 0 0 0 0\n" "MouseMoveEvent 342 191 0 0 0 0 0\n" "RenderEvent 342 191 0 0 0 0 0\n" "MouseMoveEvent 343 192 0 0 0 0 0\n" "RenderEvent 343 192 0 0 0 0 0\n" "MouseMoveEvent 344 193 0 0 0 0 0\n" "RenderEvent 344 193 0 0 0 0 0\n" "MouseMoveEvent 345 193 0 0 0 0 0\n" "RenderEvent 345 193 0 0 0 0 0\n" "MouseMoveEvent 346 193 0 0 0 0 0\n" "RenderEvent 346 193 0 0 0 0 0\n" "MouseMoveEvent 347 193 0 0 0 0 0\n" "RenderEvent 347 193 0 0 0 0 0\n" "MouseMoveEvent 347 194 0 0 0 0 0\n" "RenderEvent 347 194 0 0 0 0 0\n" "MouseMoveEvent 348 194 0 0 0 0 0\n" "RenderEvent 348 194 0 0 0 0 0\n" "MouseMoveEvent 349 194 0 0 0 0 0\n" "RenderEvent 349 194 0 0 0 0 0\n" "MouseMoveEvent 350 194 0 0 0 0 0\n" "RenderEvent 350 194 0 0 0 0 0\n" "MouseMoveEvent 350 195 0 0 0 0 0\n" "RenderEvent 350 195 0 0 0 0 0\n" "MouseMoveEvent 351 195 0 0 0 0 0\n" "RenderEvent 351 195 0 0 0 0 0\n" "MouseMoveEvent 352 195 0 0 0 0 0\n" "RenderEvent 352 195 0 0 0 0 0\n" "MouseMoveEvent 353 195 0 0 0 0 0\n" "RenderEvent 353 195 0 0 0 0 0\n" "MouseMoveEvent 354 195 0 0 0 0 0\n" "RenderEvent 354 195 0 0 0 0 0\n" "MouseMoveEvent 355 195 0 0 0 0 0\n" "RenderEvent 355 195 0 0 0 0 0\n" "MouseMoveEvent 356 195 0 0 0 0 0\n" "RenderEvent 356 195 0 0 0 0 0\n" "MouseMoveEvent 357 195 0 0 0 0 0\n" "RenderEvent 357 195 0 0 0 0 0\n" "MouseMoveEvent 357 194 0 0 0 0 0\n" "RenderEvent 357 194 0 0 0 0 0\n" "MouseMoveEvent 359 194 0 0 0 0 0\n" "RenderEvent 359 194 0 0 0 0 0\n" "MouseMoveEvent 360 194 0 0 0 0 0\n" "RenderEvent 360 194 0 0 0 0 0\n" "MouseMoveEvent 361 194 0 0 0 0 0\n" "RenderEvent 361 194 0 0 0 0 0\n" "MouseMoveEvent 362 194 0 0 0 0 0\n" "RenderEvent 362 194 0 0 0 0 0\n" "LeftButtonPressEvent 362 194 0 0 0 0 0\n" "RenderEvent 362 194 0 0 0 0 0\n" "LeftButtonReleaseEvent 362 194 0 0 0 0 0\n" "MouseMoveEvent 362 194 0 0 0 0 0\n" "RenderEvent 362 194 0 0 0 0 0\n" "MouseMoveEvent 360 194 0 0 0 0 0\n" "RenderEvent 360 194 0 0 0 0 0\n" "MouseMoveEvent 357 194 0 0 0 0 0\n" "RenderEvent 357 194 0 0 0 0 0\n" "MouseMoveEvent 354 194 0 0 0 0 0\n" "RenderEvent 354 194 0 0 0 0 0\n" "MouseMoveEvent 350 194 0 0 0 0 0\n" "RenderEvent 350 194 0 0 0 0 0\n" "MouseMoveEvent 344 194 0 0 0 0 0\n" "RenderEvent 344 194 0 0 0 0 0\n" "MouseMoveEvent 336 194 0 0 0 0 0\n" "RenderEvent 336 194 0 0 0 0 0\n" "MouseMoveEvent 328 194 0 0 0 0 0\n" "RenderEvent 328 194 0 0 0 0 0\n" "MouseMoveEvent 320 192 0 0 0 0 0\n" "RenderEvent 320 192 0 0 0 0 0\n" "MouseMoveEvent 310 191 0 0 0 0 0\n" "RenderEvent 310 191 0 0 0 0 0\n" "MouseMoveEvent 302 188 0 0 0 0 0\n" "RenderEvent 302 188 0 0 0 0 0\n" "MouseMoveEvent 291 184 0 0 0 0 0\n" "RenderEvent 291 184 0 0 0 0 0\n" "MouseMoveEvent 280 179 0 0 0 0 0\n" "RenderEvent 280 179 0 0 0 0 0\n" "MouseMoveEvent 268 175 0 0 0 0 0\n" "RenderEvent 268 175 0 0 0 0 0\n" "MouseMoveEvent 258 169 0 0 0 0 0\n" "RenderEvent 258 169 0 0 0 0 0\n" "MouseMoveEvent 247 166 0 0 0 0 0\n" "RenderEvent 247 166 0 0 0 0 0\n" "MouseMoveEvent 238 162 0 0 0 0 0\n" "RenderEvent 238 162 0 0 0 0 0\n" "MouseMoveEvent 231 157 0 0 0 0 0\n" "RenderEvent 231 157 0 0 0 0 0\n" "MouseMoveEvent 224 153 0 0 0 0 0\n" "RenderEvent 224 153 0 0 0 0 0\n" "MouseMoveEvent 219 150 0 0 0 0 0\n" "RenderEvent 219 150 0 0 0 0 0\n" "MouseMoveEvent 214 146 0 0 0 0 0\n" "RenderEvent 214 146 0 0 0 0 0\n" "MouseMoveEvent 211 143 0 0 0 0 0\n" "RenderEvent 211 143 0 0 0 0 0\n" "MouseMoveEvent 209 141 0 0 0 0 0\n" "RenderEvent 209 141 0 0 0 0 0\n" "MouseMoveEvent 209 139 0 0 0 0 0\n" "RenderEvent 209 139 0 0 0 0 0\n" "MouseMoveEvent 209 138 0 0 0 0 0\n" "RenderEvent 209 138 0 0 0 0 0\n" "MouseMoveEvent 209 136 0 0 0 0 0\n" "RenderEvent 209 136 0 0 0 0 0\n" "MouseMoveEvent 209 134 0 0 0 0 0\n" "RenderEvent 209 134 0 0 0 0 0\n" "MouseMoveEvent 209 133 0 0 0 0 0\n" "RenderEvent 209 133 0 0 0 0 0\n" "MouseMoveEvent 209 132 0 0 0 0 0\n" "RenderEvent 209 132 0 0 0 0 0\n" "MouseMoveEvent 209 131 0 0 0 0 0\n" "RenderEvent 209 131 0 0 0 0 0\n" "MouseMoveEvent 209 130 0 0 0 0 0\n" "RenderEvent 209 130 0 0 0 0 0\n" "MouseMoveEvent 209 129 0 0 0 0 0\n" "RenderEvent 209 129 0 0 0 0 0\n" "MouseMoveEvent 210 128 0 0 0 0 0\n" "RenderEvent 210 128 0 0 0 0 0\n" "MouseMoveEvent 212 127 0 0 0 0 0\n" "RenderEvent 212 127 0 0 0 0 0\n" "MouseMoveEvent 214 126 0 0 0 0 0\n" "RenderEvent 214 126 0 0 0 0 0\n" "MouseMoveEvent 215 126 0 0 0 0 0\n" "RenderEvent 215 126 0 0 0 0 0\n" "MouseMoveEvent 215 125 0 0 0 0 0\n" "RenderEvent 215 125 0 0 0 0 0\n" "MouseMoveEvent 215 124 0 0 0 0 0\n" "RenderEvent 215 124 0 0 0 0 0\n" "MouseMoveEvent 214 123 0 0 0 0 0\n" "RenderEvent 214 123 0 0 0 0 0\n" "MouseMoveEvent 213 122 0 0 0 0 0\n" "RenderEvent 213 122 0 0 0 0 0\n" "MouseMoveEvent 212 121 0 0 0 0 0\n" "RenderEvent 212 121 0 0 0 0 0\n" "MouseMoveEvent 211 118 0 0 0 0 0\n" "RenderEvent 211 118 0 0 0 0 0\n" "MouseMoveEvent 209 117 0 0 0 0 0\n" "RenderEvent 209 117 0 0 0 0 0\n" "MouseMoveEvent 209 116 0 0 0 0 0\n" "RenderEvent 209 116 0 0 0 0 0\n" "MouseMoveEvent 209 115 0 0 0 0 0\n" "RenderEvent 209 115 0 0 0 0 0\n" "MouseMoveEvent 208 114 0 0 0 0 0\n" "RenderEvent 208 114 0 0 0 0 0\n" "MouseMoveEvent 208 113 0 0 0 0 0\n" "RenderEvent 208 113 0 0 0 0 0\n" "MouseMoveEvent 207 113 0 0 0 0 0\n" "RenderEvent 207 113 0 0 0 0 0\n" "MouseMoveEvent 207 112 0 0 0 0 0\n" "RenderEvent 207 112 0 0 0 0 0\n" "MouseMoveEvent 206 112 0 0 0 0 0\n" "RenderEvent 206 112 0 0 0 0 0\n" "MouseMoveEvent 205 112 0 0 0 0 0\n" "RenderEvent 205 112 0 0 0 0 0\n" "MouseMoveEvent 204 112 0 0 0 0 0\n" "RenderEvent 204 112 0 0 0 0 0\n" "MouseMoveEvent 203 112 0 0 0 0 0\n" "RenderEvent 203 112 0 0 0 0 0\n" "MouseMoveEvent 203 111 0 0 0 0 0\n" "RenderEvent 203 111 0 0 0 0 0\n" "MouseMoveEvent 203 110 0 0 0 0 0\n" "RenderEvent 203 110 0 0 0 0 0\n" "MouseMoveEvent 202 110 0 0 0 0 0\n" "RenderEvent 202 110 0 0 0 0 0\n" "LeftButtonPressEvent 202 110 0 0 0 0 0\n" "RenderEvent 202 110 0 0 0 0 0\n" "MouseMoveEvent 202 111 0 0 0 0 0\n" "RenderEvent 202 111 0 0 0 0 0\n" "MouseMoveEvent 202 112 0 0 0 0 0\n" "RenderEvent 202 112 0 0 0 0 0\n" "MouseMoveEvent 202 114 0 0 0 0 0\n" "RenderEvent 202 114 0 0 0 0 0\n" "MouseMoveEvent 202 116 0 0 0 0 0\n" "RenderEvent 202 116 0 0 0 0 0\n" "MouseMoveEvent 202 123 0 0 0 0 0\n" "RenderEvent 202 123 0 0 0 0 0\n" "MouseMoveEvent 202 127 0 0 0 0 0\n" "RenderEvent 202 127 0 0 0 0 0\n" "MouseMoveEvent 202 132 0 0 0 0 0\n" "RenderEvent 202 132 0 0 0 0 0\n" "MouseMoveEvent 202 139 0 0 0 0 0\n" "RenderEvent 202 139 0 0 0 0 0\n" "MouseMoveEvent 202 144 0 0 0 0 0\n" "RenderEvent 202 144 0 0 0 0 0\n" "MouseMoveEvent 202 152 0 0 0 0 0\n" "RenderEvent 202 152 0 0 0 0 0\n" "MouseMoveEvent 202 159 0 0 0 0 0\n" "RenderEvent 202 159 0 0 0 0 0\n" "MouseMoveEvent 202 166 0 0 0 0 0\n" "RenderEvent 202 166 0 0 0 0 0\n" "MouseMoveEvent 202 174 0 0 0 0 0\n" "RenderEvent 202 174 0 0 0 0 0\n" "MouseMoveEvent 202 179 0 0 0 0 0\n" "RenderEvent 202 179 0 0 0 0 0\n" "MouseMoveEvent 202 185 0 0 0 0 0\n" "RenderEvent 202 185 0 0 0 0 0\n" "MouseMoveEvent 202 189 0 0 0 0 0\n" "RenderEvent 202 189 0 0 0 0 0\n" "MouseMoveEvent 202 195 0 0 0 0 0\n" "RenderEvent 202 195 0 0 0 0 0\n" "MouseMoveEvent 202 199 0 0 0 0 0\n" "RenderEvent 202 199 0 0 0 0 0\n" "MouseMoveEvent 202 203 0 0 0 0 0\n" "RenderEvent 202 203 0 0 0 0 0\n" "MouseMoveEvent 202 206 0 0 0 0 0\n" "RenderEvent 202 206 0 0 0 0 0\n" "MouseMoveEvent 202 209 0 0 0 0 0\n" "RenderEvent 202 209 0 0 0 0 0\n" "MouseMoveEvent 202 211 0 0 0 0 0\n" "RenderEvent 202 211 0 0 0 0 0\n" "MouseMoveEvent 202 212 0 0 0 0 0\n" "RenderEvent 202 212 0 0 0 0 0\n" "MouseMoveEvent 202 215 0 0 0 0 0\n" "RenderEvent 202 215 0 0 0 0 0\n" "MouseMoveEvent 202 216 0 0 0 0 0\n" "RenderEvent 202 216 0 0 0 0 0\n" "MouseMoveEvent 203 217 0 0 0 0 0\n" "RenderEvent 203 217 0 0 0 0 0\n" "MouseMoveEvent 203 218 0 0 0 0 0\n" "RenderEvent 203 218 0 0 0 0 0\n" "MouseMoveEvent 203 219 0 0 0 0 0\n" "RenderEvent 203 219 0 0 0 0 0\n" "MouseMoveEvent 203 220 0 0 0 0 0\n" "RenderEvent 203 220 0 0 0 0 0\n" "MouseMoveEvent 203 221 0 0 0 0 0\n" "RenderEvent 203 221 0 0 0 0 0\n" "MouseMoveEvent 203 222 0 0 0 0 0\n" "RenderEvent 203 222 0 0 0 0 0\n" "MouseMoveEvent 203 223 0 0 0 0 0\n" "RenderEvent 203 223 0 0 0 0 0\n" "MouseMoveEvent 203 224 0 0 0 0 0\n" "RenderEvent 203 224 0 0 0 0 0\n" "MouseMoveEvent 203 226 0 0 0 0 0\n" "RenderEvent 203 226 0 0 0 0 0\n" "MouseMoveEvent 203 227 0 0 0 0 0\n" "RenderEvent 203 227 0 0 0 0 0\n" "MouseMoveEvent 203 228 0 0 0 0 0\n" "RenderEvent 203 228 0 0 0 0 0\n" "MouseMoveEvent 203 229 0 0 0 0 0\n" "RenderEvent 203 229 0 0 0 0 0\n" "MouseMoveEvent 203 230 0 0 0 0 0\n" "RenderEvent 203 230 0 0 0 0 0\n" "MouseMoveEvent 204 231 0 0 0 0 0\n" "RenderEvent 204 231 0 0 0 0 0\n" "MouseMoveEvent 204 233 0 0 0 0 0\n" "RenderEvent 204 233 0 0 0 0 0\n" "MouseMoveEvent 204 234 0 0 0 0 0\n" "RenderEvent 204 234 0 0 0 0 0\n" "MouseMoveEvent 204 235 0 0 0 0 0\n" "RenderEvent 204 235 0 0 0 0 0\n" "LeftButtonReleaseEvent 204 235 0 0 0 0 0\n" "RenderEvent 204 235 0 0 0 0 0\n" "MouseMoveEvent 204 235 0 0 0 0 0\n" "RenderEvent 204 235 0 0 0 0 0\n" "MouseMoveEvent 206 233 0 0 0 0 0\n" "RenderEvent 206 233 0 0 0 0 0\n" "MouseMoveEvent 209 232 0 0 0 0 0\n" "RenderEvent 209 232 0 0 0 0 0\n" "MouseMoveEvent 213 227 0 0 0 0 0\n" "RenderEvent 213 227 0 0 0 0 0\n" "MouseMoveEvent 220 224 0 0 0 0 0\n" "RenderEvent 220 224 0 0 0 0 0\n" "MouseMoveEvent 230 220 0 0 0 0 0\n" "RenderEvent 230 220 0 0 0 0 0\n" "MouseMoveEvent 241 213 0 0 0 0 0\n" "RenderEvent 241 213 0 0 0 0 0\n" "MouseMoveEvent 273 198 0 0 0 0 0\n" "RenderEvent 273 198 0 0 0 0 0\n" "MouseMoveEvent 286 191 0 0 0 0 0\n" "RenderEvent 286 191 0 0 0 0 0\n" "MouseMoveEvent 298 185 0 0 0 0 0\n" "RenderEvent 298 185 0 0 0 0 0\n" "MouseMoveEvent 311 180 0 0 0 0 0\n" "RenderEvent 311 180 0 0 0 0 0\n" "MouseMoveEvent 327 175 0 0 0 0 0\n" "RenderEvent 327 175 0 0 0 0 0\n" "MouseMoveEvent 334 173 0 0 0 0 0\n" "RenderEvent 334 173 0 0 0 0 0\n" "MouseMoveEvent 337 172 0 0 0 0 0\n" "RenderEvent 337 172 0 0 0 0 0\n" "MouseMoveEvent 341 172 0 0 0 0 0\n" "RenderEvent 341 172 0 0 0 0 0\n" "MouseMoveEvent 344 172 0 0 0 0 0\n" "RenderEvent 344 172 0 0 0 0 0\n" "MouseMoveEvent 345 172 0 0 0 0 0\n" "RenderEvent 345 172 0 0 0 0 0\n" "MouseMoveEvent 345 173 0 0 0 0 0\n" "RenderEvent 345 173 0 0 0 0 0\n" "MouseMoveEvent 345 174 0 0 0 0 0\n" "RenderEvent 345 174 0 0 0 0 0\n" "MouseMoveEvent 346 174 0 0 0 0 0\n" "RenderEvent 346 174 0 0 0 0 0\n" "MouseMoveEvent 346 175 0 0 0 0 0\n" "RenderEvent 346 175 0 0 0 0 0\n" "MouseMoveEvent 346 176 0 0 0 0 0\n" "RenderEvent 346 176 0 0 0 0 0\n" "MouseMoveEvent 346 177 0 0 0 0 0\n" "RenderEvent 346 177 0 0 0 0 0\n" "MouseMoveEvent 347 177 0 0 0 0 0\n" "RenderEvent 347 177 0 0 0 0 0\n" "MouseMoveEvent 348 178 0 0 0 0 0\n" "RenderEvent 348 178 0 0 0 0 0\n" "MouseMoveEvent 349 179 0 0 0 0 0\n" "RenderEvent 349 179 0 0 0 0 0\n" "MouseMoveEvent 350 179 0 0 0 0 0\n" "RenderEvent 350 179 0 0 0 0 0\n" "MouseMoveEvent 352 179 0 0 0 0 0\n" "RenderEvent 352 179 0 0 0 0 0\n" "MouseMoveEvent 353 179 0 0 0 0 0\n" "RenderEvent 353 179 0 0 0 0 0\n" "MouseMoveEvent 354 180 0 0 0 0 0\n" "RenderEvent 354 180 0 0 0 0 0\n" "MouseMoveEvent 355 181 0 0 0 0 0\n" "RenderEvent 355 181 0 0 0 0 0\n" "MouseMoveEvent 356 182 0 0 0 0 0\n" "RenderEvent 356 182 0 0 0 0 0\n" "MouseMoveEvent 356 183 0 0 0 0 0\n" "RenderEvent 356 183 0 0 0 0 0\n" "MouseMoveEvent 356 184 0 0 0 0 0\n" "RenderEvent 356 184 0 0 0 0 0\n" "MouseMoveEvent 356 185 0 0 0 0 0\n" "RenderEvent 356 185 0 0 0 0 0\n" "MouseMoveEvent 356 186 0 0 0 0 0\n" "RenderEvent 356 186 0 0 0 0 0\n" "MouseMoveEvent 356 187 0 0 0 0 0\n" "RenderEvent 356 187 0 0 0 0 0\n" "MouseMoveEvent 357 188 0 0 0 0 0\n" "RenderEvent 357 188 0 0 0 0 0\n" "MouseMoveEvent 357 189 0 0 0 0 0\n" "RenderEvent 357 189 0 0 0 0 0\n" "MouseMoveEvent 358 189 0 0 0 0 0\n" "RenderEvent 358 189 0 0 0 0 0\n" "MouseMoveEvent 359 190 0 0 0 0 0\n" "RenderEvent 359 190 0 0 0 0 0\n" "MouseMoveEvent 360 190 0 0 0 0 0\n" "RenderEvent 360 190 0 0 0 0 0\n" "MouseMoveEvent 361 190 0 0 0 0 0\n" "RenderEvent 361 190 0 0 0 0 0\n" "MouseMoveEvent 362 190 0 0 0 0 0\n" "RenderEvent 362 190 0 0 0 0 0\n" "MouseMoveEvent 362 191 0 0 0 0 0\n" "RenderEvent 362 191 0 0 0 0 0\n" "MouseMoveEvent 363 191 0 0 0 0 0\n" "RenderEvent 363 191 0 0 0 0 0\n" "MouseMoveEvent 363 192 0 0 0 0 0\n" "RenderEvent 363 192 0 0 0 0 0\n" "LeftButtonPressEvent 363 192 0 0 0 0 0\n" "RenderEvent 363 192 0 0 0 0 0\n" "MouseMoveEvent 363 193 0 0 0 0 0\n" "RenderEvent 363 193 0 0 0 0 0\n" "MouseMoveEvent 365 196 0 0 0 0 0\n" "RenderEvent 365 196 0 0 0 0 0\n" "MouseMoveEvent 367 198 0 0 0 0 0\n" "RenderEvent 367 198 0 0 0 0 0\n" "MouseMoveEvent 372 202 0 0 0 0 0\n" "RenderEvent 372 202 0 0 0 0 0\n" "MouseMoveEvent 383 213 0 0 0 0 0\n" "RenderEvent 383 213 0 0 0 0 0\n" "MouseMoveEvent 390 219 0 0 0 0 0\n" "RenderEvent 390 219 0 0 0 0 0\n" "MouseMoveEvent 397 226 0 0 0 0 0\n" "RenderEvent 397 226 0 0 0 0 0\n" "MouseMoveEvent 404 233 0 0 0 0 0\n" "RenderEvent 404 233 0 0 0 0 0\n" "MouseMoveEvent 412 239 0 0 0 0 0\n" "RenderEvent 412 239 0 0 0 0 0\n" "MouseMoveEvent 419 247 0 0 0 0 0\n" "RenderEvent 419 247 0 0 0 0 0\n" "MouseMoveEvent 429 255 0 0 0 0 0\n" "RenderEvent 429 255 0 0 0 0 0\n" "MouseMoveEvent 437 261 0 0 0 0 0\n" "RenderEvent 437 261 0 0 0 0 0\n" "MouseMoveEvent 445 270 0 0 0 0 0\n" "RenderEvent 445 270 0 0 0 0 0\n" "MouseMoveEvent 452 277 0 0 0 0 0\n" "RenderEvent 452 277 0 0 0 0 0\n" "MouseMoveEvent 458 284 0 0 0 0 0\n" "RenderEvent 458 284 0 0 0 0 0\n" "MouseMoveEvent 465 290 0 0 0 0 0\n" "RenderEvent 465 290 0 0 0 0 0\n" "MouseMoveEvent 471 295 0 0 0 0 0\n" "RenderEvent 471 295 0 0 0 0 0\n" "MouseMoveEvent 476 299 0 0 0 0 0\n" "RenderEvent 476 299 0 0 0 0 0\n" "MouseMoveEvent 482 304 0 0 0 0 0\n" "RenderEvent 482 304 0 0 0 0 0\n" "MouseMoveEvent 486 308 0 0 0 0 0\n" "RenderEvent 486 308 0 0 0 0 0\n" "MouseMoveEvent 488 310 0 0 0 0 0\n" "RenderEvent 488 310 0 0 0 0 0\n" "MouseMoveEvent 490 311 0 0 0 0 0\n" "RenderEvent 490 311 0 0 0 0 0\n" "MouseMoveEvent 491 312 0 0 0 0 0\n" "RenderEvent 491 312 0 0 0 0 0\n" "MouseMoveEvent 491 313 0 0 0 0 0\n" "RenderEvent 491 313 0 0 0 0 0\n" "MouseMoveEvent 491 314 0 0 0 0 0\n" "RenderEvent 491 314 0 0 0 0 0\n" "MouseMoveEvent 491 315 0 0 0 0 0\n" "RenderEvent 491 315 0 0 0 0 0\n" "LeftButtonReleaseEvent 491 315 0 0 0 0 0\n" "RenderEvent 491 315 0 0 0 0 0\n" "MouseMoveEvent 490 315 0 0 0 0 0\n" "RenderEvent 490 315 0 0 0 0 0\n" "MouseMoveEvent 487 315 0 0 0 0 0\n" "RenderEvent 487 315 0 0 0 0 0\n" "MouseMoveEvent 482 315 0 0 0 0 0\n" "RenderEvent 482 315 0 0 0 0 0\n" "MouseMoveEvent 475 314 0 0 0 0 0\n" "RenderEvent 475 314 0 0 0 0 0\n" "MouseMoveEvent 466 312 0 0 0 0 0\n" "RenderEvent 466 312 0 0 0 0 0\n" "MouseMoveEvent 455 310 0 0 0 0 0\n" "RenderEvent 455 310 0 0 0 0 0\n" "MouseMoveEvent 438 309 0 0 0 0 0\n" "RenderEvent 438 309 0 0 0 0 0\n" "MouseMoveEvent 415 306 0 0 0 0 0\n" "RenderEvent 415 306 0 0 0 0 0\n" "MouseMoveEvent 386 300 0 0 0 0 0\n" "RenderEvent 386 300 0 0 0 0 0\n" "MouseMoveEvent 354 295 0 0 0 0 0\n" "RenderEvent 354 295 0 0 0 0 0\n" "MouseMoveEvent 322 288 0 0 0 0 0\n" "RenderEvent 322 288 0 0 0 0 0\n" "MouseMoveEvent 287 279 0 0 0 0 0\n" "RenderEvent 287 279 0 0 0 0 0\n" "MouseMoveEvent 255 269 0 0 0 0 0\n" "RenderEvent 255 269 0 0 0 0 0\n" "MouseMoveEvent 230 263 0 0 0 0 0\n" "RenderEvent 230 263 0 0 0 0 0\n" "MouseMoveEvent 214 259 0 0 0 0 0\n" "RenderEvent 214 259 0 0 0 0 0\n" "MouseMoveEvent 202 256 0 0 0 0 0\n" "RenderEvent 202 256 0 0 0 0 0\n" "MouseMoveEvent 194 253 0 0 0 0 0\n" "RenderEvent 194 253 0 0 0 0 0\n" "MouseMoveEvent 189 250 0 0 0 0 0\n" "RenderEvent 189 250 0 0 0 0 0\n" "MouseMoveEvent 187 248 0 0 0 0 0\n" "RenderEvent 187 248 0 0 0 0 0\n" "MouseMoveEvent 185 247 0 0 0 0 0\n" "RenderEvent 185 247 0 0 0 0 0\n" "MouseMoveEvent 183 246 0 0 0 0 0\n" "RenderEvent 183 246 0 0 0 0 0\n" "MouseMoveEvent 183 245 0 0 0 0 0\n" "RenderEvent 183 245 0 0 0 0 0\n" "MouseMoveEvent 183 244 0 0 0 0 0\n" "RenderEvent 183 244 0 0 0 0 0\n" "MouseMoveEvent 182 244 0 0 0 0 0\n" "RenderEvent 182 244 0 0 0 0 0\n" "MouseMoveEvent 181 244 0 0 0 0 0\n" "RenderEvent 181 244 0 0 0 0 0\n" "MouseMoveEvent 180 243 0 0 0 0 0\n" "RenderEvent 180 243 0 0 0 0 0\n" "MouseMoveEvent 180 242 0 0 0 0 0\n" "RenderEvent 180 242 0 0 0 0 0\n" "MouseMoveEvent 179 241 0 0 0 0 0\n" "RenderEvent 179 241 0 0 0 0 0\n" "MouseMoveEvent 178 240 0 0 0 0 0\n" "RenderEvent 178 240 0 0 0 0 0\n" "MouseMoveEvent 178 239 0 0 0 0 0\n" "RenderEvent 178 239 0 0 0 0 0\n" "MouseMoveEvent 178 238 0 0 0 0 0\n" "RenderEvent 178 238 0 0 0 0 0\n" "MouseMoveEvent 178 237 0 0 0 0 0\n" "RenderEvent 178 237 0 0 0 0 0\n" "MouseMoveEvent 178 235 0 0 0 0 0\n" "RenderEvent 178 235 0 0 0 0 0\n" "MouseMoveEvent 178 233 0 0 0 0 0\n" "RenderEvent 178 233 0 0 0 0 0\n" "MouseMoveEvent 179 231 0 0 0 0 0\n" "RenderEvent 179 231 0 0 0 0 0\n" "MouseMoveEvent 183 228 0 0 0 0 0\n" "RenderEvent 183 228 0 0 0 0 0\n" "MouseMoveEvent 184 227 0 0 0 0 0\n" "RenderEvent 184 227 0 0 0 0 0\n" "MouseMoveEvent 185 227 0 0 0 0 0\n" "RenderEvent 185 227 0 0 0 0 0\n" "MouseMoveEvent 186 227 0 0 0 0 0\n" "RenderEvent 186 227 0 0 0 0 0\n" "MouseMoveEvent 187 227 0 0 0 0 0\n" "RenderEvent 187 227 0 0 0 0 0\n" "MouseMoveEvent 188 227 0 0 0 0 0\n" "RenderEvent 188 227 0 0 0 0 0\n" "MouseMoveEvent 189 228 0 0 0 0 0\n" "RenderEvent 189 228 0 0 0 0 0\n" "MouseMoveEvent 190 229 0 0 0 0 0\n" "RenderEvent 190 229 0 0 0 0 0\n" "MouseMoveEvent 192 229 0 0 0 0 0\n" "RenderEvent 192 229 0 0 0 0 0\n" "MouseMoveEvent 193 230 0 0 0 0 0\n" "RenderEvent 193 230 0 0 0 0 0\n" "MouseMoveEvent 195 231 0 0 0 0 0\n" "RenderEvent 195 231 0 0 0 0 0\n" "MouseMoveEvent 196 231 0 0 0 0 0\n" "RenderEvent 196 231 0 0 0 0 0\n" "MouseMoveEvent 198 231 0 0 0 0 0\n" "RenderEvent 198 231 0 0 0 0 0\n" "MouseMoveEvent 198 232 0 0 0 0 0\n" "RenderEvent 198 232 0 0 0 0 0\n" "MouseMoveEvent 199 232 0 0 0 0 0\n" "RenderEvent 199 232 0 0 0 0 0\n" "MouseMoveEvent 200 232 0 0 0 0 0\n" "RenderEvent 200 232 0 0 0 0 0\n" "MouseMoveEvent 201 233 0 0 0 0 0\n" "RenderEvent 201 233 0 0 0 0 0\n" "MouseMoveEvent 202 234 0 0 0 0 0\n" "RenderEvent 202 234 0 0 0 0 0\n" "MouseMoveEvent 203 235 0 0 0 0 0\n" "RenderEvent 203 235 0 0 0 0 0\n" "MouseMoveEvent 203 236 0 0 0 0 0\n" "RenderEvent 203 236 0 0 0 0 0\n" "MouseMoveEvent 204 236 0 0 0 0 0\n" "RenderEvent 204 236 0 0 0 0 0\n" "MouseMoveEvent 205 236 0 0 0 0 0\n" "RenderEvent 205 236 0 0 0 0 0\n" "MouseMoveEvent 206 236 0 0 0 0 0\n" "RenderEvent 206 236 0 0 0 0 0\n" "MouseMoveEvent 207 237 0 0 0 0 0\n" "RenderEvent 207 237 0 0 0 0 0\n" "MouseMoveEvent 208 237 0 0 0 0 0\n" "RenderEvent 208 237 0 0 0 0 0\n" "MouseMoveEvent 210 238 0 0 0 0 0\n" "RenderEvent 210 238 0 0 0 0 0\n" "MouseMoveEvent 212 239 0 0 0 0 0\n" "RenderEvent 212 239 0 0 0 0 0\n" "MouseMoveEvent 213 239 0 0 0 0 0\n" "RenderEvent 213 239 0 0 0 0 0\n" "MouseMoveEvent 213 240 0 0 0 0 0\n" "RenderEvent 213 240 0 0 0 0 0\n" "MouseMoveEvent 213 241 0 0 0 0 0\n" "RenderEvent 213 241 0 0 0 0 0\n" "LeftButtonPressEvent 213 241 0 0 0 0 0\n" "RenderEvent 213 241 0 0 0 0 0\n" "MouseMoveEvent 215 241 0 0 0 0 0\n" "RenderEvent 215 241 0 0 0 0 0\n" "MouseMoveEvent 218 239 0 0 0 0 0\n" "RenderEvent 218 239 0 0 0 0 0\n" "MouseMoveEvent 224 236 0 0 0 0 0\n" "RenderEvent 224 236 0 0 0 0 0\n" "MouseMoveEvent 231 232 0 0 0 0 0\n" "RenderEvent 231 232 0 0 0 0 0\n" "MouseMoveEvent 239 227 0 0 0 0 0\n" "RenderEvent 239 227 0 0 0 0 0\n" "MouseMoveEvent 248 223 0 0 0 0 0\n" "RenderEvent 248 223 0 0 0 0 0\n" "MouseMoveEvent 258 217 0 0 0 0 0\n" "RenderEvent 258 217 0 0 0 0 0\n" "MouseMoveEvent 278 206 0 0 0 0 0\n" "RenderEvent 278 206 0 0 0 0 0\n" "MouseMoveEvent 288 201 0 0 0 0 0\n" "RenderEvent 288 201 0 0 0 0 0\n" "MouseMoveEvent 296 196 0 0 0 0 0\n" "RenderEvent 296 196 0 0 0 0 0\n" "MouseMoveEvent 306 193 0 0 0 0 0\n" "RenderEvent 306 193 0 0 0 0 0\n" "MouseMoveEvent 314 190 0 0 0 0 0\n" "RenderEvent 314 190 0 0 0 0 0\n" "MouseMoveEvent 321 188 0 0 0 0 0\n" "RenderEvent 321 188 0 0 0 0 0\n" "MouseMoveEvent 327 185 0 0 0 0 0\n" "RenderEvent 327 185 0 0 0 0 0\n" "MouseMoveEvent 333 183 0 0 0 0 0\n" "RenderEvent 333 183 0 0 0 0 0\n" "MouseMoveEvent 338 181 0 0 0 0 0\n" "RenderEvent 338 181 0 0 0 0 0\n" "MouseMoveEvent 342 181 0 0 0 0 0\n" "RenderEvent 342 181 0 0 0 0 0\n" "MouseMoveEvent 345 179 0 0 0 0 0\n" "RenderEvent 345 179 0 0 0 0 0\n" "MouseMoveEvent 348 178 0 0 0 0 0\n" "RenderEvent 348 178 0 0 0 0 0\n" "MouseMoveEvent 350 178 0 0 0 0 0\n" "RenderEvent 350 178 0 0 0 0 0\n" "MouseMoveEvent 353 178 0 0 0 0 0\n" "RenderEvent 353 178 0 0 0 0 0\n" "MouseMoveEvent 356 177 0 0 0 0 0\n" "RenderEvent 356 177 0 0 0 0 0\n" "MouseMoveEvent 359 176 0 0 0 0 0\n" "RenderEvent 359 176 0 0 0 0 0\n" "MouseMoveEvent 363 175 0 0 0 0 0\n" "RenderEvent 363 175 0 0 0 0 0\n" "MouseMoveEvent 366 175 0 0 0 0 0\n" "RenderEvent 366 175 0 0 0 0 0\n" "MouseMoveEvent 369 174 0 0 0 0 0\n" "RenderEvent 369 174 0 0 0 0 0\n" "MouseMoveEvent 372 173 0 0 0 0 0\n" "RenderEvent 372 173 0 0 0 0 0\n" "MouseMoveEvent 377 173 0 0 0 0 0\n" "RenderEvent 377 173 0 0 0 0 0\n" "MouseMoveEvent 379 172 0 0 0 0 0\n" "RenderEvent 379 172 0 0 0 0 0\n" "MouseMoveEvent 382 171 0 0 0 0 0\n" "RenderEvent 382 171 0 0 0 0 0\n" "MouseMoveEvent 383 171 0 0 0 0 0\n" "RenderEvent 383 171 0 0 0 0 0\n" "MouseMoveEvent 386 171 0 0 0 0 0\n" "RenderEvent 386 171 0 0 0 0 0\n" "MouseMoveEvent 388 170 0 0 0 0 0\n" "RenderEvent 388 170 0 0 0 0 0\n" "MouseMoveEvent 391 169 0 0 0 0 0\n" "RenderEvent 391 169 0 0 0 0 0\n" "MouseMoveEvent 394 169 0 0 0 0 0\n" "RenderEvent 394 169 0 0 0 0 0\n" "MouseMoveEvent 396 167 0 0 0 0 0\n" "RenderEvent 396 167 0 0 0 0 0\n" "MouseMoveEvent 399 167 0 0 0 0 0\n" "RenderEvent 399 167 0 0 0 0 0\n" "MouseMoveEvent 400 166 0 0 0 0 0\n" "RenderEvent 400 166 0 0 0 0 0\n" "MouseMoveEvent 402 165 0 0 0 0 0\n" "RenderEvent 402 165 0 0 0 0 0\n" "MouseMoveEvent 403 165 0 0 0 0 0\n" "RenderEvent 403 165 0 0 0 0 0\n" "MouseMoveEvent 405 165 0 0 0 0 0\n" "RenderEvent 405 165 0 0 0 0 0\n" "MouseMoveEvent 408 165 0 0 0 0 0\n" "RenderEvent 408 165 0 0 0 0 0\n" "MouseMoveEvent 411 165 0 0 0 0 0\n" "RenderEvent 411 165 0 0 0 0 0\n" "MouseMoveEvent 413 165 0 0 0 0 0\n" "RenderEvent 413 165 0 0 0 0 0\n" "MouseMoveEvent 420 164 0 0 0 0 0\n" "RenderEvent 420 164 0 0 0 0 0\n" "MouseMoveEvent 422 163 0 0 0 0 0\n" "RenderEvent 422 163 0 0 0 0 0\n" "MouseMoveEvent 427 163 0 0 0 0 0\n" "RenderEvent 427 163 0 0 0 0 0\n" "MouseMoveEvent 431 162 0 0 0 0 0\n" "RenderEvent 431 162 0 0 0 0 0\n" "MouseMoveEvent 433 162 0 0 0 0 0\n" "RenderEvent 433 162 0 0 0 0 0\n" "MouseMoveEvent 436 162 0 0 0 0 0\n" "RenderEvent 436 162 0 0 0 0 0\n" "MouseMoveEvent 439 162 0 0 0 0 0\n" "RenderEvent 439 162 0 0 0 0 0\n" "MouseMoveEvent 442 162 0 0 0 0 0\n" "RenderEvent 442 162 0 0 0 0 0\n" "MouseMoveEvent 445 162 0 0 0 0 0\n" "RenderEvent 445 162 0 0 0 0 0\n" "MouseMoveEvent 447 162 0 0 0 0 0\n" "RenderEvent 447 162 0 0 0 0 0\n" "MouseMoveEvent 448 162 0 0 0 0 0\n" "RenderEvent 448 162 0 0 0 0 0\n" "MouseMoveEvent 449 162 0 0 0 0 0\n" "RenderEvent 449 162 0 0 0 0 0\n" "MouseMoveEvent 451 162 0 0 0 0 0\n" "RenderEvent 451 162 0 0 0 0 0\n" "MouseMoveEvent 453 162 0 0 0 0 0\n" "RenderEvent 453 162 0 0 0 0 0\n" "MouseMoveEvent 454 162 0 0 0 0 0\n" "RenderEvent 454 162 0 0 0 0 0\n" "MouseMoveEvent 456 162 0 0 0 0 0\n" "RenderEvent 456 162 0 0 0 0 0\n" "MouseMoveEvent 457 162 0 0 0 0 0\n" "RenderEvent 457 162 0 0 0 0 0\n" "MouseMoveEvent 458 162 0 0 0 0 0\n" "RenderEvent 458 162 0 0 0 0 0\n" "MouseMoveEvent 460 162 0 0 0 0 0\n" "RenderEvent 460 162 0 0 0 0 0\n" "MouseMoveEvent 462 162 0 0 0 0 0\n" "RenderEvent 462 162 0 0 0 0 0\n" "MouseMoveEvent 464 162 0 0 0 0 0\n" "RenderEvent 464 162 0 0 0 0 0\n" "MouseMoveEvent 467 160 0 0 0 0 0\n" "RenderEvent 467 160 0 0 0 0 0\n" "MouseMoveEvent 471 159 0 0 0 0 0\n" "RenderEvent 471 159 0 0 0 0 0\n" "MouseMoveEvent 475 159 0 0 0 0 0\n" "RenderEvent 475 159 0 0 0 0 0\n" "MouseMoveEvent 476 159 0 0 0 0 0\n" "RenderEvent 476 159 0 0 0 0 0\n" "MouseMoveEvent 477 159 0 0 0 0 0\n" "RenderEvent 477 159 0 0 0 0 0\n" "MouseMoveEvent 478 159 0 0 0 0 0\n" "RenderEvent 478 159 0 0 0 0 0\n" "LeftButtonReleaseEvent 478 159 0 0 0 0 0\n" "RenderEvent 478 159 0 0 0 0 0\n" "MouseMoveEvent 478 159 0 0 0 0 0\n" "RenderEvent 478 159 0 0 0 0 0\n" "MouseMoveEvent 476 159 0 0 0 0 0\n" "RenderEvent 476 159 0 0 0 0 0\n" "MouseMoveEvent 475 158 0 0 0 0 0\n" "RenderEvent 475 158 0 0 0 0 0\n" "MouseMoveEvent 474 158 0 0 0 0 0\n" "RenderEvent 474 158 0 0 0 0 0\n" "MouseMoveEvent 474 157 0 0 0 0 0\n" "RenderEvent 474 157 0 0 0 0 0\n" "MouseMoveEvent 473 157 0 0 0 0 0\n" "RenderEvent 473 157 0 0 0 0 0\n" "MouseMoveEvent 472 157 0 0 0 0 0\n" "RenderEvent 472 157 0 0 0 0 0\n" "MouseMoveEvent 470 157 0 0 0 0 0\n" "RenderEvent 470 157 0 0 0 0 0\n" "MouseMoveEvent 469 157 0 0 0 0 0\n" "RenderEvent 469 157 0 0 0 0 0\n" "MouseMoveEvent 468 157 0 0 0 0 0\n" "RenderEvent 468 157 0 0 0 0 0\n" "MouseMoveEvent 467 157 0 0 0 0 0\n" "RenderEvent 467 157 0 0 0 0 0\n" "MouseMoveEvent 466 157 0 0 0 0 0\n" "RenderEvent 466 157 0 0 0 0 0\n" "MouseMoveEvent 464 157 0 0 0 0 0\n" "RenderEvent 464 157 0 0 0 0 0\n" "MouseMoveEvent 463 157 0 0 0 0 0\n" "RenderEvent 463 157 0 0 0 0 0\n" "MouseMoveEvent 462 157 0 0 0 0 0\n" "RenderEvent 462 157 0 0 0 0 0\n" "MouseMoveEvent 461 157 0 0 0 0 0\n" "RenderEvent 461 157 0 0 0 0 0\n" "MouseMoveEvent 460 157 0 0 0 0 0\n" "RenderEvent 460 157 0 0 0 0 0\n" "MouseMoveEvent 459 157 0 0 0 0 0\n" "RenderEvent 459 157 0 0 0 0 0\n" "MouseMoveEvent 458 157 0 0 0 0 0\n" "RenderEvent 458 157 0 0 0 0 0\n" "MouseMoveEvent 455 157 0 0 0 0 0\n" "RenderEvent 455 157 0 0 0 0 0\n" "MouseMoveEvent 453 157 0 0 0 0 0\n" "RenderEvent 453 157 0 0 0 0 0\n" "MouseMoveEvent 451 156 0 0 0 0 0\n" "RenderEvent 451 156 0 0 0 0 0\n" "MouseMoveEvent 449 155 0 0 0 0 0\n" "RenderEvent 449 155 0 0 0 0 0\n" "MouseMoveEvent 447 155 0 0 0 0 0\n" "RenderEvent 447 155 0 0 0 0 0\n" "MouseMoveEvent 444 155 0 0 0 0 0\n" "RenderEvent 444 155 0 0 0 0 0\n" "MouseMoveEvent 442 155 0 0 0 0 0\n" "RenderEvent 442 155 0 0 0 0 0\n" "MouseMoveEvent 439 155 0 0 0 0 0\n" "RenderEvent 439 155 0 0 0 0 0\n" "MouseMoveEvent 434 155 0 0 0 0 0\n" "RenderEvent 434 155 0 0 0 0 0\n" "MouseMoveEvent 430 155 0 0 0 0 0\n" "RenderEvent 430 155 0 0 0 0 0\n" "MouseMoveEvent 426 155 0 0 0 0 0\n" "RenderEvent 426 155 0 0 0 0 0\n" "MouseMoveEvent 422 155 0 0 0 0 0\n" "RenderEvent 422 155 0 0 0 0 0\n" "MouseMoveEvent 418 155 0 0 0 0 0\n" "RenderEvent 418 155 0 0 0 0 0\n" "MouseMoveEvent 415 155 0 0 0 0 0\n" "RenderEvent 415 155 0 0 0 0 0\n" "MouseMoveEvent 412 155 0 0 0 0 0\n" "RenderEvent 412 155 0 0 0 0 0\n" "MouseMoveEvent 409 155 0 0 0 0 0\n" "RenderEvent 409 155 0 0 0 0 0\n" "MouseMoveEvent 403 155 0 0 0 0 0\n" "RenderEvent 403 155 0 0 0 0 0\n" "MouseMoveEvent 399 155 0 0 0 0 0\n" "RenderEvent 399 155 0 0 0 0 0\n" "MouseMoveEvent 395 155 0 0 0 0 0\n" "RenderEvent 395 155 0 0 0 0 0\n" "MouseMoveEvent 391 155 0 0 0 0 0\n" "RenderEvent 391 155 0 0 0 0 0\n" "MouseMoveEvent 382 155 0 0 0 0 0\n" "RenderEvent 382 155 0 0 0 0 0\n" "MouseMoveEvent 377 155 0 0 0 0 0\n" "RenderEvent 377 155 0 0 0 0 0\n" "MouseMoveEvent 374 155 0 0 0 0 0\n" "RenderEvent 374 155 0 0 0 0 0\n" "MouseMoveEvent 371 155 0 0 0 0 0\n" "RenderEvent 371 155 0 0 0 0 0\n" "MouseMoveEvent 369 155 0 0 0 0 0\n" "RenderEvent 369 155 0 0 0 0 0\n" "KeyPressEvent 369 155 0 0 113 1 q\n" "CharEvent 369 155 0 0 113 1 q\n" "ExitEvent 369 155 0 0 113 1 q\n" ; //--------------------------------------------------------------------------- // Create cells of various types void CreateHexahedronActor(vtkActor* actor); void CreatePentagonalPrismActor(vtkActor* actor); void CreatePyramidActor(vtkActor* actor); void CreateTetraActor(vtkActor* actor); void CreateVoxelActor(vtkActor* actor); void CreateWedgeActor(vtkActor* actor); //--------------------------------------------------------------------------- int TestCellCentersPointPlacer(int argc, char *argv[]) { std::vector<vtkSmartPointer<vtkActor> > actors; vtkSmartPointer<vtkActor> hexahedronActor = vtkSmartPointer<vtkActor>::New(); CreateHexahedronActor(hexahedronActor); actors.push_back(hexahedronActor); vtkSmartPointer<vtkActor> pentagonalPrismActor = vtkSmartPointer<vtkActor>::New(); CreatePentagonalPrismActor(pentagonalPrismActor); actors.push_back(pentagonalPrismActor); vtkSmartPointer<vtkActor> pyramidActor = vtkSmartPointer<vtkActor>::New(); CreatePyramidActor(pyramidActor); actors.push_back(pyramidActor); vtkSmartPointer<vtkActor> tetraActor = vtkSmartPointer<vtkActor>::New(); CreateTetraActor(tetraActor); actors.push_back(tetraActor); vtkSmartPointer<vtkActor> voxelActor = vtkSmartPointer<vtkActor>::New(); CreateVoxelActor(voxelActor); actors.push_back(voxelActor); vtkSmartPointer<vtkActor> wedgeActor = vtkSmartPointer<vtkActor>::New(); CreateWedgeActor(wedgeActor); actors.push_back(wedgeActor); vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer< vtkRenderer >::New(); int gridDimensions = 3; int rendererSize = 200; // Create a render window, renderer and render window interactor. // Add the cells to the renderer, in a grid layout. We accomplish // this by using a transform filter to translate and arrange on // a grid. vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->SetSize( rendererSize*gridDimensions, rendererSize*gridDimensions); renderWindow->AddRenderer(renderer); renderer->SetBackground(.2, .3, .4); // Create a point placer to constrain to the cell centers and add // each of the actors to the placer, so that it includes them in // its constraints. vtkSmartPointer<vtkCellCentersPointPlacer> pointPlacer = vtkSmartPointer<vtkCellCentersPointPlacer>::New(); for(int row = 0; row < gridDimensions; row++) { for(int col = 0; col < gridDimensions; col++) { int index = row * gridDimensions + col; if(index > static_cast< int >(actors.size() - 1)) { continue; } vtkSmartPointer< vtkTransformFilter > transformFilter = vtkSmartPointer< vtkTransformFilter >::New(); vtkSmartPointer< vtkMatrix4x4 > matrix = vtkSmartPointer< vtkMatrix4x4 >::New(); matrix->SetElement(0,3,5*col); matrix->SetElement(1,3,5*row); vtkSmartPointer< vtkMatrixToLinearTransform > mlt = vtkSmartPointer< vtkMatrixToLinearTransform >::New(); mlt->SetInput(matrix); transformFilter->SetInputConnection( actors[index]->GetMapper()->GetInputConnection(0, 0)); transformFilter->SetTransform(mlt); transformFilter->Update(); vtkSmartPointer< vtkDataSetMapper > mapper2 = vtkSmartPointer< vtkDataSetMapper >::New(); mapper2->SetInputConnection(transformFilter->GetOutputPort()); actors[index]->SetMapper(mapper2); renderer->AddActor(actors[index]); pointPlacer->AddProp(actors[index]); } } // Default colors actors[0]->GetProperty()->SetColor(1,0,0.5); actors[1]->GetProperty()->SetColor(0,1,0); actors[2]->GetProperty()->SetColor(0,0,1); actors[3]->GetProperty()->SetColor(1,1,0); actors[4]->GetProperty()->SetColor(1,0,1); actors[5]->GetProperty()->SetColor(0,1,1); renderer->ResetCamera(); renderer->GetActiveCamera()->Azimuth(30); renderer->GetActiveCamera()->Elevation(-30); renderer->ResetCameraClippingRange(); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderWindow->Render(); // Now add a distance widget. vtkSmartPointer<vtkDistanceWidget> widget = vtkSmartPointer<vtkDistanceWidget>::New(); widget->CreateDefaultRepresentation(); vtkSmartPointer< vtkDistanceRepresentation2D > rep = vtkSmartPointer< vtkDistanceRepresentation2D >::New(); rep->GetAxis()->GetProperty()->SetColor( 1.0, 0.0, 0.0 ); // Create a 3D handle reprensentation template for this distance // widget vtkSmartPointer< vtkPointHandleRepresentation3D > handleRep3D = vtkSmartPointer< vtkPointHandleRepresentation3D >::New(); handleRep3D->GetProperty()->SetLineWidth(4.0); rep->SetHandleRepresentation( handleRep3D ); handleRep3D->GetProperty()->SetColor( 0.8, 0.2, 0 ); widget->SetRepresentation(rep); // Instantiate the handles and have them be constrained by the // placer. rep->InstantiateHandleRepresentation(); rep->GetPoint1Representation()->SetPointPlacer(pointPlacer); rep->GetPoint2Representation()->SetPointPlacer(pointPlacer); // With a "snap" constraint, we can't have a smooth motion anymore, so // turn it off. static_cast< vtkPointHandleRepresentation3D * >( rep->GetPoint1Representation())->SmoothMotionOff(); static_cast< vtkPointHandleRepresentation3D * >( rep->GetPoint2Representation())->SmoothMotionOff(); widget->SetInteractor(renderWindowInteractor); widget->SetEnabled(1); renderWindow->Render(); return vtkTesting::InteractorEventLoop( argc, argv, renderWindowInteractor, TestCellCentersPointPlacerEventLog ); } //--------------------------------------------------------------------------- void CreateHexahedronActor(vtkActor* actor) { // Setup the coordinates of eight points // (the two faces must be in counter clockwise order as viewd from the outside) // Create the points vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint(0.0, 0.0, 0.0); points->InsertNextPoint(1.0, 0.0, 0.0); points->InsertNextPoint(1.0, 1.0, 0.0); points->InsertNextPoint(0.0, 1.0, 0.0); points->InsertNextPoint(0.0, 0.0, 1.0); points->InsertNextPoint(1.0, 0.0, 1.0); points->InsertNextPoint(1.0, 1.0, 1.0); points->InsertNextPoint(0.0, 1.0, 1.0); // Create a hexahedron from the points vtkSmartPointer<vtkHexahedron> hex = vtkSmartPointer<vtkHexahedron>::New(); hex->GetPointIds()->SetId(0,0); hex->GetPointIds()->SetId(1,1); hex->GetPointIds()->SetId(2,2); hex->GetPointIds()->SetId(3,3); hex->GetPointIds()->SetId(4,4); hex->GetPointIds()->SetId(5,5); hex->GetPointIds()->SetId(6,6); hex->GetPointIds()->SetId(7,7); // Add the hexahedron to a cell array vtkSmartPointer<vtkCellArray> hexs = vtkSmartPointer<vtkCellArray>::New(); hexs->InsertNextCell(hex); // Add the points and hexahedron to an unstructured grid vtkSmartPointer<vtkUnstructuredGrid> uGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); uGrid->SetPoints(points); uGrid->InsertNextCell(hex->GetCellType(), hex->GetPointIds()); // Visualize vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputData(uGrid); actor->SetMapper(mapper); } //--------------------------------------------------------------------------- void CreatePentagonalPrismActor(vtkActor* actor) { // Create the points vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint(1, 0, 0); points->InsertNextPoint(3, 0, 0); points->InsertNextPoint(4, 2, 0); points->InsertNextPoint(2, 4, 0); points->InsertNextPoint(0, 2, 0); points->InsertNextPoint(1, 0, 4); points->InsertNextPoint(3, 0, 4); points->InsertNextPoint(4, 2, 4); points->InsertNextPoint(2, 4, 4); points->InsertNextPoint(0, 2, 4); // Pentagonal Prism vtkSmartPointer<vtkPentagonalPrism> pentagonalPrism = vtkSmartPointer<vtkPentagonalPrism>::New(); pentagonalPrism->GetPointIds()->SetId(0,0); pentagonalPrism->GetPointIds()->SetId(1,1); pentagonalPrism->GetPointIds()->SetId(2,2); pentagonalPrism->GetPointIds()->SetId(3,3); pentagonalPrism->GetPointIds()->SetId(4,4); pentagonalPrism->GetPointIds()->SetId(5,5); pentagonalPrism->GetPointIds()->SetId(6,6); pentagonalPrism->GetPointIds()->SetId(7,7); pentagonalPrism->GetPointIds()->SetId(8,8); pentagonalPrism->GetPointIds()->SetId(9,9); vtkSmartPointer<vtkCellArray> cellArray = vtkSmartPointer<vtkCellArray>::New(); cellArray->InsertNextCell(pentagonalPrism); // Add the points and hexahedron to an unstructured grid vtkSmartPointer<vtkUnstructuredGrid> uGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); uGrid->SetPoints(points); uGrid->InsertNextCell(pentagonalPrism->GetCellType(), pentagonalPrism->GetPointIds()); // Visualize vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputData(uGrid); actor->SetMapper(mapper); } //--------------------------------------------------------------------------- void CreatePyramidActor(vtkActor* actor) { vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); float p0[3] = {1.0, 1.0, 1.0}; float p1[3] = {-1.0, 1.0, 1.0}; float p2[3] = {-1.0, -1.0, 1.0}; float p3[3] = {1.0, -1.0, 1.0}; float p4[3] = {0.0, 0.0, 0.0}; points->InsertNextPoint(p0); points->InsertNextPoint(p1); points->InsertNextPoint(p2); points->InsertNextPoint(p3); points->InsertNextPoint(p4); vtkSmartPointer<vtkPyramid> pyramid = vtkSmartPointer<vtkPyramid>::New(); pyramid->GetPointIds()->SetId(0,0); pyramid->GetPointIds()->SetId(1,1); pyramid->GetPointIds()->SetId(2,2); pyramid->GetPointIds()->SetId(3,3); pyramid->GetPointIds()->SetId(4,4); vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); cells->InsertNextCell (pyramid); vtkSmartPointer<vtkUnstructuredGrid> ug = vtkSmartPointer<vtkUnstructuredGrid>::New(); ug->SetPoints(points); ug->InsertNextCell(pyramid->GetCellType(),pyramid->GetPointIds()); //Create an actor and mapper vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputData(ug); actor->SetMapper(mapper); } //--------------------------------------------------------------------------- void CreateTetraActor(vtkActor* actor) { vtkSmartPointer< vtkPoints > points = vtkSmartPointer< vtkPoints > :: New(); points->InsertNextPoint(0, 0, 0); points->InsertNextPoint(1, 0, 0); points->InsertNextPoint(1, 1, 0); points->InsertNextPoint(0, 1, 1); points->InsertNextPoint(5, 5, 5); points->InsertNextPoint(6, 5, 5); points->InsertNextPoint(6, 6, 5); points->InsertNextPoint(5, 6, 6); vtkSmartPointer<vtkUnstructuredGrid> unstructuredGrid = vtkSmartPointer<vtkUnstructuredGrid>::New(); unstructuredGrid->SetPoints(points); vtkSmartPointer<vtkTetra> tetra = vtkSmartPointer<vtkTetra>::New(); tetra->GetPointIds()->SetId(0, 0); tetra->GetPointIds()->SetId(1, 1); tetra->GetPointIds()->SetId(2, 2); tetra->GetPointIds()->SetId(3, 3); vtkSmartPointer<vtkCellArray> cellArray = vtkSmartPointer<vtkCellArray>::New(); cellArray->InsertNextCell(tetra); unstructuredGrid->SetCells(VTK_TETRA, cellArray); // Create a mapper and actor vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputData(unstructuredGrid); actor->SetMapper(mapper); } //--------------------------------------------------------------------------- void CreateVoxelActor(vtkActor* actor) { vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint(0, 0, 0); points->InsertNextPoint(1, 0, 0); points->InsertNextPoint(0, 1, 0); points->InsertNextPoint(1, 1, 0); points->InsertNextPoint(0, 0, 1); points->InsertNextPoint(1, 0, 1); points->InsertNextPoint(0, 1, 1); points->InsertNextPoint(1, 1, 1); vtkSmartPointer<vtkVoxel> voxel = vtkSmartPointer<vtkVoxel>::New(); voxel->GetPointIds()->SetId(0, 0); voxel->GetPointIds()->SetId(1, 1); voxel->GetPointIds()->SetId(2, 2); voxel->GetPointIds()->SetId(3, 3); voxel->GetPointIds()->SetId(4, 4); voxel->GetPointIds()->SetId(5, 5); voxel->GetPointIds()->SetId(6, 6); voxel->GetPointIds()->SetId(7, 7); vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); cells->InsertNextCell(voxel); vtkSmartPointer<vtkUnstructuredGrid> ug = vtkSmartPointer<vtkUnstructuredGrid>::New(); ug->SetPoints(points); ug->InsertNextCell(voxel->GetCellType(),voxel->GetPointIds()); // Visualize vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputData(ug); actor->SetMapper(mapper); } //--------------------------------------------------------------------------- void CreateWedgeActor(vtkActor* actor) { vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); points->InsertNextPoint(0, 1, 0); points->InsertNextPoint(0, 0, 0); points->InsertNextPoint(0, .5, .5); points->InsertNextPoint(1, 1, 0); points->InsertNextPoint(1, 0.0, 0.0); points->InsertNextPoint(1, .5, .5); vtkSmartPointer<vtkWedge> wedge = vtkSmartPointer<vtkWedge>::New(); wedge->GetPointIds()->SetId(0,0); wedge->GetPointIds()->SetId(1,1); wedge->GetPointIds()->SetId(2,2); wedge->GetPointIds()->SetId(3,3); wedge->GetPointIds()->SetId(4,4); wedge->GetPointIds()->SetId(5,5); vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); cells->InsertNextCell(wedge); vtkSmartPointer<vtkUnstructuredGrid> ug = vtkSmartPointer<vtkUnstructuredGrid>::New(); ug->SetPoints(points); ug->InsertNextCell(wedge->GetCellType(),wedge->GetPointIds()); // Visualize vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputData(ug); actor->SetMapper(mapper); }
34.936301
88
0.689768
[ "render", "vector", "transform", "3d" ]
eb88eb09074599fcc5790b11fa2fde7c25a35e09
3,312
hpp
C++
modules/core/linalg/include/nt2/linalg/functions/lu.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/linalg/include/nt2/linalg/functions/lu.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/linalg/include/nt2/linalg/functions/lu.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2014 - Jean-Thierry Lapresté // Copyright 2003 - 2013 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2013 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_LINALG_FUNCTIONS_LU_HPP_INCLUDED #define NT2_LINALG_FUNCTIONS_LU_HPP_INCLUDED #include <nt2/include/functor.hpp> #include <nt2/sdk/meta/size_as.hpp> #include <nt2/sdk/meta/value_as.hpp> #include <nt2/core/container/dsl/size.hpp> #include <nt2/sdk/meta/tieable_hierarchy.hpp> #include <nt2/core/container/dsl/value_type.hpp> namespace nt2 { namespace tag { struct lu_ : ext::tieable_<lu_> { typedef ext::tieable_<lu_> parent; template<class... Args> static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args) BOOST_AUTO_DECLTYPE_BODY( dispatching_lu_( ext::adl_helper(), static_cast<Args&&>(args)... ) ) }; } namespace ext { template<class Site, class... Ts> BOOST_FORCEINLINE generic_dispatcher<tag::lu_, Site> dispatching_lu_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...) { return generic_dispatcher<tag::lu_, Site>(); } template<class... Args> struct impl_lu_; } /** y = lu(a) tie(l,u) = lu(a) tie(l,u) = lu(a, raw_) tie(l,u,p) = lu(a) tie(l,u,p) = lu(a,vector_/matrix_) the lu function expresses a matrix a as the product of two essentially triangular matrices, one of them a permutation of a lower triangular matrix and the other an upper triangular matrix. the factorization is often called the LU factorization. Input matrix a can be rectangular. y = lu(a) returns matrix y that is the direct first output from the LAPACK d/sgetrf or z/cgetrf routines. the permutation matrix p is lost. tie(y, ls) = lu(a, raw_) returns matrix y that is the output from the LAPACK d/sgetrf or z/cgetrf routines. Care that the permutation vector ls is in Lapack Swap lines form. tie(l,u) = lu(a) returns an upper triangular matrix in u and a permuted lower triangular matrix in l such that a = l*u. return value l is a product of lower triangular and permutation matrices. tie(l,u,p) = lu(a) or tie(l,u,p) = lu(a,matrix_) returns an upper triangular matrix in u, a lower triangular matrix l with a unit diagonal, and a permutation matrix p, such that l*u = p*a. tie(l,u,ip) = lu(a,vector_) returns the permutation information in a vector of integers ip such that l*u = a(ip, _). except raw_ option that does not exist for Matlab the syntax is quite identical as defined by Matlab lu for dense matrices. **/ NT2_FUNCTION_IMPLEMENTATION(tag::lu_, lu, 1) NT2_FUNCTION_IMPLEMENTATION(tag::lu_, lu, 2) } namespace nt2 { namespace ext { template<class Domain, int N, class Expr> struct size_of<tag::lu_,Domain,N,Expr> : meta::size_as<Expr,0> {}; } } #endif
35.612903
163
0.644324
[ "vector" ]
eb8d60d2eac6b87b110b8b2e71e677d4db34fca9
7,111
cpp
C++
src/graph/Node.cpp
ragedb/ragedb
0470f4cb154ce551ddb920453f2ea8467dbc4857
[ "Apache-2.0" ]
58
2021-07-08T14:20:54.000Z
2022-03-31T08:20:39.000Z
src/graph/Node.cpp
ragedb/ragedb
0470f4cb154ce551ddb920453f2ea8467dbc4857
[ "Apache-2.0" ]
15
2021-07-29T14:37:57.000Z
2022-03-31T04:22:36.000Z
src/graph/Node.cpp
ragedb/ragedb
0470f4cb154ce551ddb920453f2ea8467dbc4857
[ "Apache-2.0" ]
2
2021-07-29T14:24:57.000Z
2021-09-08T10:14:52.000Z
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Node.h" #include <utility> #include "Shard.h" namespace ragedb { Node::Node() = default; Node::Node(uint64_t id, std::string type, std::string key) : id(id), type(std::move(type)), key(std::move(key)) {} Node::Node(uint64_t id, std::string type, std::string key, std::map<std::string, std::any> properties) : id(id), type(std::move(type)), key(std::move(key)), properties(std::move(properties)) {} uint64_t Node::getId() const { return id; } uint16_t Node::getTypeId() const { return Shard::externalToTypeId(id); } std::string Node::getKey() const { return key; } std::string Node::getType() const { return type; } std::map<std::string, std::any> Node::getProperties() const { return properties; } sol::table Node::getPropertiesLua(sol::this_state ts) { sol::state_view lua = ts; sol::table property_map = lua.create_table(); for (auto [_key, value] : getProperties()) { const auto& value_type = value.type(); if(value_type == typeid(std::string)) { property_map[_key] = sol::make_object(lua, std::any_cast<std::string>(value)); } if(value_type == typeid(int64_t)) { property_map[_key] = sol::make_object(lua, std::any_cast<int64_t>(value)); } if(value_type == typeid(double)) { property_map[_key] = sol::make_object(lua, std::any_cast<double>(value)); } // Booleans are stored in std::any as a bit reference so we can't use if(value.type() == typeid(bool)) { if(value_type == typeid(std::_Bit_reference)) { if (std::any_cast<std::_Bit_reference>(value) ) { property_map[_key] = sol::make_object(lua, true); } else { property_map[_key] = sol::make_object(lua, false); } continue; } if(value_type == typeid(std::vector<std::string>)) { return sol::make_object(lua, sol::as_table(std::any_cast<std::vector<std::string>>(value))); } if(value_type == typeid(std::vector<int64_t>)) { return sol::make_object(lua, sol::as_table(std::any_cast<std::vector<int64_t>>(value))); } if(value_type == typeid(std::vector<double>)) { return sol::make_object(lua, sol::as_table(std::any_cast<std::vector<double>>(value))); } if(value_type == typeid(std::vector<bool>)) { return sol::make_object(lua, sol::as_table(std::any_cast<std::vector<bool>>(value))); } } return sol::as_table(property_map); } std::any Node::getProperty(const std::string& property) { std::map<std::string, std::any>::iterator it; it = properties.find(property); if (it != std::end(properties)) { return it->second; } return {}; } std::ostream& operator<<(std::ostream& os, const Node& node) { os << "{ \"id\": " << node.id << R"(, "type": ")" << node.type << R"(", "key": )" << "\"" << node.key << "\"" << ", \"properties\": { "; bool initial = true; for (auto [key, value] : node.properties) { if (!initial) { os << ", "; } initial = false; os << "\"" << key << "\": "; if(value.type() == typeid(std::string)) { os << "\"" << std::any_cast<std::string>(value) << "\""; continue; } if(value.type() == typeid(int64_t)) { os << std::any_cast<int64_t>(value); continue; } if(value.type() == typeid(double)) { os << std::any_cast<double>(value); continue; } // Booleans are stored in std::any as a bit reference so we can't use if(value.type() == typeid(bool)) { if(value.type() == typeid(std::_Bit_reference)) { if (std::any_cast<std::_Bit_reference>(value) ) { os << "true" ; } else { os << "false"; } continue; } if(value.type() == typeid(std::vector<std::string>)) { os << '['; bool nested_initial = true; for (const auto& item : std::any_cast<std::vector<std::string>>(value)) { if (!nested_initial) { os << ", "; } os << "\"" << item << "\""; nested_initial = false; } os << ']'; continue; } if(value.type() == typeid(std::vector<int64_t>)) { os << '['; bool nested_initial = true; for (const auto& item : std::any_cast<std::vector<int64_t>>(value)) { if (!nested_initial) { os << ", "; } os << item; nested_initial = false; } os << ']'; continue; } if(value.type() == typeid(std::vector<double>)) { os << '['; bool nested_initial = true; for (const auto& item : std::any_cast<std::vector<double>>(value)) { if (!nested_initial) { os << ", "; } os << item; nested_initial = false; } os << ']'; continue; } if(value.type() == typeid(std::vector<bool>)) { os << '['; bool nested_initial = true; for (const auto& item : std::any_cast<std::vector<bool>>(value)) { if (!nested_initial) { os << ", "; } if (item) { os << "true"; } else { os << "false"; } nested_initial = false; } os << ']'; continue; } } os << " } }"; return os; } }
34.023923
198
0.46421
[ "vector" ]
eb8e732409957c328d579cebe5fe5e30177e02c9
15,326
hpp
C++
deps/cinder/include/boost/geometry/algorithms/covered_by.hpp
multi-os-engine/cinder-natj-binding
969b66fdd49e4ca63442baf61ce90ae385ab8178
[ "Apache-2.0" ]
1,210
2020-08-18T07:57:36.000Z
2022-03-31T15:06:05.000Z
deps/cinder/include/boost/geometry/algorithms/covered_by.hpp
multi-os-engine/cinder-natj-binding
969b66fdd49e4ca63442baf61ce90ae385ab8178
[ "Apache-2.0" ]
39
2019-07-06T02:51:39.000Z
2022-02-18T11:48:33.000Z
deps/cinder/include/boost/geometry/algorithms/covered_by.hpp
multi-os-engine/cinder-natj-binding
969b66fdd49e4ca63442baf61ce90ae385ab8178
[ "Apache-2.0" ]
275
2020-08-18T08:35:16.000Z
2022-03-31T15:06:07.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // This file was modified by Oracle on 2013, 2014. // Modifications copyright (c) 2013, 2014 Oracle and/or its affiliates. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle #ifndef BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP #define BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP #include <cstddef> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> #include <boost/variant/variant_fwd.hpp> #include <boost/geometry/algorithms/not_implemented.hpp> #include <boost/geometry/algorithms/within.hpp> #include <boost/geometry/strategies/cartesian/point_in_box.hpp> #include <boost/geometry/strategies/cartesian/box_in_box.hpp> #include <boost/geometry/strategies/default_strategy.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace covered_by { struct use_point_in_geometry { template <typename Geometry1, typename Geometry2, typename Strategy> static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& strategy) { return detail::within::point_in_geometry(geometry1, geometry2, strategy) >= 0; } }; struct use_relate { template <typename Geometry1, typename Geometry2, typename Strategy> static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& /*strategy*/) { return Strategy::apply(geometry1, geometry2); } }; }} // namespace detail::covered_by #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template < typename Geometry1, typename Geometry2, typename Tag1 = typename tag<Geometry1>::type, typename Tag2 = typename tag<Geometry2>::type > struct covered_by : not_implemented<Tag1, Tag2> {}; template <typename Point, typename Box> struct covered_by<Point, Box, point_tag, box_tag> { template <typename Strategy> static inline bool apply(Point const& point, Box const& box, Strategy const& strategy) { ::boost::ignore_unused_variable_warning(strategy); return strategy.apply(point, box); } }; template <typename Box1, typename Box2> struct covered_by<Box1, Box2, box_tag, box_tag> { template <typename Strategy> static inline bool apply(Box1 const& box1, Box2 const& box2, Strategy const& strategy) { assert_dimension_equal<Box1, Box2>(); ::boost::ignore_unused_variable_warning(strategy); return strategy.apply(box1, box2); } }; // P/P template <typename Point1, typename Point2> struct covered_by<Point1, Point2, point_tag, point_tag> : public detail::covered_by::use_point_in_geometry {}; template <typename Point, typename MultiPoint> struct covered_by<Point, MultiPoint, point_tag, multi_point_tag> : public detail::covered_by::use_point_in_geometry {}; // P/L template <typename Point, typename Segment> struct covered_by<Point, Segment, point_tag, segment_tag> : public detail::covered_by::use_point_in_geometry {}; template <typename Point, typename Linestring> struct covered_by<Point, Linestring, point_tag, linestring_tag> : public detail::covered_by::use_point_in_geometry {}; template <typename Point, typename MultiLinestring> struct covered_by<Point, MultiLinestring, point_tag, multi_linestring_tag> : public detail::covered_by::use_point_in_geometry {}; // P/A template <typename Point, typename Ring> struct covered_by<Point, Ring, point_tag, ring_tag> : public detail::covered_by::use_point_in_geometry {}; template <typename Point, typename Polygon> struct covered_by<Point, Polygon, point_tag, polygon_tag> : public detail::covered_by::use_point_in_geometry {}; template <typename Point, typename MultiPolygon> struct covered_by<Point, MultiPolygon, point_tag, multi_polygon_tag> : public detail::covered_by::use_point_in_geometry {}; // L/L template <typename Linestring1, typename Linestring2> struct covered_by<Linestring1, Linestring2, linestring_tag, linestring_tag> : public detail::covered_by::use_relate {}; template <typename Linestring, typename MultiLinestring> struct covered_by<Linestring, MultiLinestring, linestring_tag, multi_linestring_tag> : public detail::covered_by::use_relate {}; template <typename MultiLinestring, typename Linestring> struct covered_by<MultiLinestring, Linestring, multi_linestring_tag, linestring_tag> : public detail::covered_by::use_relate {}; template <typename MultiLinestring1, typename MultiLinestring2> struct covered_by<MultiLinestring1, MultiLinestring2, multi_linestring_tag, multi_linestring_tag> : public detail::covered_by::use_relate {}; // L/A template <typename Linestring, typename Ring> struct covered_by<Linestring, Ring, linestring_tag, ring_tag> : public detail::covered_by::use_relate {}; template <typename MultiLinestring, typename Ring> struct covered_by<MultiLinestring, Ring, multi_linestring_tag, ring_tag> : public detail::covered_by::use_relate {}; template <typename Linestring, typename Polygon> struct covered_by<Linestring, Polygon, linestring_tag, polygon_tag> : public detail::covered_by::use_relate {}; template <typename MultiLinestring, typename Polygon> struct covered_by<MultiLinestring, Polygon, multi_linestring_tag, polygon_tag> : public detail::covered_by::use_relate {}; template <typename Linestring, typename MultiPolygon> struct covered_by<Linestring, MultiPolygon, linestring_tag, multi_polygon_tag> : public detail::covered_by::use_relate {}; template <typename MultiLinestring, typename MultiPolygon> struct covered_by<MultiLinestring, MultiPolygon, multi_linestring_tag, multi_polygon_tag> : public detail::covered_by::use_relate {}; // A/A template <typename Ring1, typename Ring2> struct covered_by<Ring1, Ring2, ring_tag, ring_tag> : public detail::covered_by::use_relate {}; template <typename Ring, typename Polygon> struct covered_by<Ring, Polygon, ring_tag, polygon_tag> : public detail::covered_by::use_relate {}; template <typename Polygon, typename Ring> struct covered_by<Polygon, Ring, polygon_tag, ring_tag> : public detail::covered_by::use_relate {}; template <typename Polygon1, typename Polygon2> struct covered_by<Polygon1, Polygon2, polygon_tag, polygon_tag> : public detail::covered_by::use_relate {}; template <typename Ring, typename MultiPolygon> struct covered_by<Ring, MultiPolygon, ring_tag, multi_polygon_tag> : public detail::covered_by::use_relate {}; template <typename MultiPolygon, typename Ring> struct covered_by<MultiPolygon, Ring, multi_polygon_tag, ring_tag> : public detail::covered_by::use_relate {}; template <typename Polygon, typename MultiPolygon> struct covered_by<Polygon, MultiPolygon, polygon_tag, multi_polygon_tag> : public detail::covered_by::use_relate {}; template <typename MultiPolygon, typename Polygon> struct covered_by<MultiPolygon, Polygon, multi_polygon_tag, polygon_tag> : public detail::covered_by::use_relate {}; template <typename MultiPolygon1, typename MultiPolygon2> struct covered_by<MultiPolygon1, MultiPolygon2, multi_polygon_tag, multi_polygon_tag> : public detail::covered_by::use_relate {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH namespace resolve_strategy { struct covered_by { template <typename Geometry1, typename Geometry2, typename Strategy> static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& strategy) { concept::within::check < typename tag<Geometry1>::type, typename tag<Geometry2>::type, typename tag_cast<typename tag<Geometry2>::type, areal_tag>::type, Strategy >(); concept::check<Geometry1 const>(); concept::check<Geometry2 const>(); assert_dimension_equal<Geometry1, Geometry2>(); return dispatch::covered_by<Geometry1, Geometry2>::apply(geometry1, geometry2, strategy); } template <typename Geometry1, typename Geometry2> static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, default_strategy) { typedef typename point_type<Geometry1>::type point_type1; typedef typename point_type<Geometry2>::type point_type2; typedef typename strategy::covered_by::services::default_strategy < typename tag<Geometry1>::type, typename tag<Geometry2>::type, typename tag<Geometry1>::type, typename tag_cast<typename tag<Geometry2>::type, areal_tag>::type, typename tag_cast < typename cs_tag<point_type1>::type, spherical_tag >::type, typename tag_cast < typename cs_tag<point_type2>::type, spherical_tag >::type, Geometry1, Geometry2 >::type strategy_type; return covered_by::apply(geometry1, geometry2, strategy_type()); } }; } // namespace resolve_strategy namespace resolve_variant { template <typename Geometry1, typename Geometry2> struct covered_by { template <typename Strategy> static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& strategy) { return resolve_strategy::covered_by ::apply(geometry1, geometry2, strategy); } }; template <BOOST_VARIANT_ENUM_PARAMS(typename T), typename Geometry2> struct covered_by<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>, Geometry2> { template <typename Strategy> struct visitor: boost::static_visitor<bool> { Geometry2 const& m_geometry2; Strategy const& m_strategy; visitor(Geometry2 const& geometry2, Strategy const& strategy) : m_geometry2(geometry2), m_strategy(strategy) {} template <typename Geometry1> bool operator()(Geometry1 const& geometry1) const { return covered_by<Geometry1, Geometry2> ::apply(geometry1, m_geometry2, m_strategy); } }; template <typename Strategy> static inline bool apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry1, Geometry2 const& geometry2, Strategy const& strategy) { return boost::apply_visitor(visitor<Strategy>(geometry2, strategy), geometry1); } }; template <typename Geometry1, BOOST_VARIANT_ENUM_PARAMS(typename T)> struct covered_by<Geometry1, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> > { template <typename Strategy> struct visitor: boost::static_visitor<bool> { Geometry1 const& m_geometry1; Strategy const& m_strategy; visitor(Geometry1 const& geometry1, Strategy const& strategy) : m_geometry1(geometry1), m_strategy(strategy) {} template <typename Geometry2> bool operator()(Geometry2 const& geometry2) const { return covered_by<Geometry1, Geometry2> ::apply(m_geometry1, geometry2, m_strategy); } }; template <typename Strategy> static inline bool apply(Geometry1 const& geometry1, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> const& geometry2, Strategy const& strategy) { return boost::apply_visitor(visitor<Strategy>(geometry1, strategy), geometry2); } }; template < BOOST_VARIANT_ENUM_PARAMS(typename T1), BOOST_VARIANT_ENUM_PARAMS(typename T2) > struct covered_by< boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)>, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> > { template <typename Strategy> struct visitor: boost::static_visitor<bool> { Strategy const& m_strategy; visitor(Strategy const& strategy): m_strategy(strategy) {} template <typename Geometry1, typename Geometry2> bool operator()(Geometry1 const& geometry1, Geometry2 const& geometry2) const { return covered_by<Geometry1, Geometry2> ::apply(geometry1, geometry2, m_strategy); } }; template <typename Strategy> static inline bool apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const& geometry1, boost::variant<BOOST_VARIANT_ENUM_PARAMS(T2)> const& geometry2, Strategy const& strategy) { return boost::apply_visitor(visitor<Strategy>(strategy), geometry1, geometry2); } }; } // namespace resolve_variant /*! \brief \brief_check12{is inside or on border} \ingroup covered_by \details \details_check12{covered_by, is inside or on border}. \tparam Geometry1 \tparam_geometry \tparam Geometry2 \tparam_geometry \param geometry1 \param_geometry which might be inside or on the border of the second geometry \param geometry2 \param_geometry which might cover the first geometry \return true if geometry1 is inside of or on the border of geometry2, else false \note The default strategy is used for covered_by detection \qbk{[include reference/algorithms/covered_by.qbk]} */ template<typename Geometry1, typename Geometry2> inline bool covered_by(Geometry1 const& geometry1, Geometry2 const& geometry2) { return resolve_variant::covered_by<Geometry1, Geometry2> ::apply(geometry1, geometry2, default_strategy()); } /*! \brief \brief_check12{is inside or on border} \brief_strategy \ingroup covered_by \details \details_check12{covered_by, is inside or on border}, \brief_strategy. \details_strategy_reasons \tparam Geometry1 \tparam_geometry \tparam Geometry2 \tparam_geometry \param geometry1 \param_geometry which might be inside or on the border of the second geometry \param geometry2 \param_geometry which might cover the first geometry \param strategy strategy to be used \return true if geometry1 is inside of or on the border of geometry2, else false \qbk{distinguish,with strategy} \qbk{[include reference/algorithms/covered_by.qbk]} */ template<typename Geometry1, typename Geometry2, typename Strategy> inline bool covered_by(Geometry1 const& geometry1, Geometry2 const& geometry2, Strategy const& strategy) { return resolve_variant::covered_by<Geometry1, Geometry2> ::apply(geometry1, geometry2, strategy); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_COVERED_BY_HPP
32.333333
114
0.713232
[ "geometry" ]
eb90592440fe8875cb2b1063d7e76ae84cf1d3ed
879
cxx
C++
src/sdp_solve/SDP/SDP/read_blocks/read_block_stream/Block_Parser/StartArray.cxx
ChrisPattison/sdpb
4668f72c935e7feba705dd8247d9aacb23185f1c
[ "MIT" ]
45
2015-02-10T15:45:22.000Z
2022-02-24T07:45:01.000Z
src/sdp_solve/SDP/SDP/read_blocks/read_block_stream/Block_Parser/StartArray.cxx
ChrisPattison/sdpb
4668f72c935e7feba705dd8247d9aacb23185f1c
[ "MIT" ]
58
2015-02-27T10:03:18.000Z
2021-08-10T04:21:42.000Z
src/sdp_solve/SDP/SDP/read_blocks/read_block_stream/Block_Parser/StartArray.cxx
ChrisPattison/sdpb
4668f72c935e7feba705dd8247d9aacb23185f1c
[ "MIT" ]
38
2015-02-10T11:11:27.000Z
2022-02-11T20:59:42.000Z
#include "../Block_Parser.hxx" bool Block_Parser::StartArray() { if(inside) { if(parsing_c) { c_state.json_start_array(); } else if(parsing_B) { B_state.json_start_array(); } else if(parsing_bilinear_bases_even) { bilinear_bases_even_state.json_start_array(); } else if(parsing_bilinear_bases_odd) { bilinear_bases_odd_state.json_start_array(); } else { throw std::runtime_error( "Invalid input file. Found an array not inside " + c_state.name + ", " + B_state.name + ", " + bilinear_bases_even_state.name + ", " + bilinear_bases_odd_state.name + "."); } } else { throw std::runtime_error("Found an array outside of the main object."); } return true; }
23.756757
77
0.550626
[ "object" ]
eb90f95b70b22402b2003187e2afcfd91c40c4b0
7,664
cpp
C++
Formats/simplehtml.cpp
viva64/plog-converter
90f22163420b7e8f1c374465e3890ce8344e6ff9
[ "Apache-2.0" ]
11
2019-08-06T10:13:56.000Z
2022-02-21T17:19:18.000Z
Formats/simplehtml.cpp
viva64/plog-converter
90f22163420b7e8f1c374465e3890ce8344e6ff9
[ "Apache-2.0" ]
2
2021-09-11T14:28:39.000Z
2021-12-10T12:49:59.000Z
Formats/simplehtml.cpp
viva64/plog-converter
90f22163420b7e8f1c374465e3890ce8344e6ff9
[ "Apache-2.0" ]
3
2020-04-20T07:18:54.000Z
2022-02-16T06:37:35.000Z
// 2006-2008 (c) Viva64.com Team // 2008-2020 (c) OOO "Program Verification Systems" // 2020-2021 (c) PVS-Studio LLC #include <algorithm> #include "simplehtml.h" namespace PlogConverter { using namespace std; SimpleHTMLOutput::SimpleHTMLOutput(const ProgramOptions &opt) : IOutput(opt, "html") { } SimpleHTMLOutput::~SimpleHTMLOutput() = default; const int SimpleHTMLOutput::DefaultCweColumnWidth = 6; //% const int SimpleHTMLOutput::DefaultSASTColumnWidth = 9; //% const int SimpleHTMLOutput::DefaultMessageColumnWidth = 65; //% static char HtmlHead[] = R"( <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en"> <head> <title>Messages</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <style type="text/css"> td { padding: 0; text-align: left; vertical-align: top; } legend { color: blue; font: 1.2em bold Comic Sans MS Verdana; text-align: center; } </style> </head> <body> <table style="width: 100%; font: 12pt normal Century Gothic;"> )"; static char HtmlEnd[] = R"( </table> </body> </html> )"; void SimpleHTMLOutput::PrintHtmlStart() { m_ostream << HtmlHead << std::endl; } void SimpleHTMLOutput::PrintHtmlEnd() { m_ostream << HtmlEnd << std::endl; } void SimpleHTMLOutput::PrintHeading(const std::string &text) { m_ostream << R"( <tr style='background: lightcyan;'>)" << endl; m_ostream << R"( <td colspan='5' style='color: red; text-align: center; font-size: 1.2em;'>)" << text << R"(</td>)" << endl; m_ostream << R"( </tr>)" << endl; } int SimpleHTMLOutput::GetMessageColumnWidth() const { int width = DefaultMessageColumnWidth; bool showSAST = false; bool showCWE = false; DetectShowTags(&showCWE, &showSAST); if (showCWE) width -= GetCweColumnWidth(); if (showSAST) width -= GetSASTColumnWidth(); return width; } int SimpleHTMLOutput::GetCweColumnWidth() const { return DefaultCweColumnWidth; } int SimpleHTMLOutput::GetSASTColumnWidth() const { return DefaultSASTColumnWidth; } void SimpleHTMLOutput::PrintTableCaption() { #ifdef WIN32 m_ostream << R"( <caption style="font-weight: bold;background: #fff;color: #000;border: none !important;">MESSAGES</caption>)" << endl; m_ostream << R"( <tr style="background: black; color: white;">)" << endl; m_ostream << R"( <th style="width: 10%;">Project</th>)" << endl; m_ostream << R"( <th style="width: 20%;">File</th>)" << endl; m_ostream << R"( <th style="width: 5%;">Code</th>)" << endl; m_ostream << R"( <th style="width: 45%;">Message</th>)" << endl; m_ostream << R"( <th style="width: 20%;">Analyzed Source File(s)</th>)" << endl; m_ostream << R"( </tr>)" << endl; #else m_ostream << R"( <caption style="font-weight: bold;background: #fff;color: #000;border: none !important;">MESSAGES</caption>)" << endl; m_ostream << R"( <tr style="background: black; color: white;">)" << endl; m_ostream << R"( <th style="width: 30%;">Location</th>)" << endl; m_ostream << R"( <th style="width: 5%;">Code</th>)" << endl; bool showCwe = false; bool showSast = false; DetectShowTags(&showCwe, &showSast); if (showCwe) { m_ostream << R"( <th style="width: )" << GetCweColumnWidth() << R"(%;">CWE</th>)" << endl; } if (showSast) { m_ostream << R"( <th style="width: )" << GetSASTColumnWidth() << R"(%;">SAST</th>)" << endl; } m_ostream << R"( <th style="width: 65%;">Message</th>)" << endl; m_ostream << R"( </tr>)" << endl; #endif } void SimpleHTMLOutput::PrintMessages(const std::vector<Warning> &messages, const std::string &caption) { if (messages.empty()) { return; } PrintHeading(caption); for (const auto &err : messages) { #ifdef WIN32 std::string fileUTF8 = err.GetFileUTF8(); m_ostream << R"( <tr>)" << endl; m_ostream << R"( <td style='width: 10%;'></td>)" << endl; m_ostream << R"( <td style='width: 20%;'><div title=")" << EscapeHtml(fileUTF8) << R"(">)" << FileBaseName(fileUTF8) << " (" << err.GetLine() << R"()</div></td>)" << endl; m_ostream << R"( <td style='width: 5%;'><a target="_blank" href=')" << err.GetVivaUrl() << R"('>)" << err.code << R"(</a></td>)" << endl; m_ostream << R"( <td style='width: 45%;'>)" << EscapeHtml(err.message) << R"(</td>)" << endl; m_ostream << R"( <td style='width: 20%;'></td>)" << endl; m_ostream << R"( </tr>)" << endl; #else m_ostream << R"( <tr>)" << endl; m_ostream << R"( <td style='width: 30%;'><div title=")" << EscapeHtml(err.GetFile()) << R"(">)" << FileBaseName(err.GetFile()) << " (" << err.GetLine() << R"()</div></td>)" << endl; m_ostream << R"( <td style='width: 5%;'><a target="_blank" href=')" << err.GetVivaUrl() << R"('>)" << err.code << R"(</a></td>)" << endl; bool showCwe = false; bool showSast = false; DetectShowTags(&showCwe, &showSast); if (showCwe) { if (err.HasCWE()) m_ostream << R"( <td style='width: )" << GetCweColumnWidth() << R"(%;'><a target="_blank" href=')" << err.GetCWEUrl() << R"('>)" << err.GetCWEString() << R"(</a></td>)" << endl; else m_ostream << R"( <th style="width: )" << GetCweColumnWidth() << R"(%;"></th>)" << endl; } if (showSast) { if (err.HasSAST()) m_ostream << R"( <td style='width: )" << GetSASTColumnWidth() << R"(%;'>)" << err.sastId << R"(</td>)" << endl; else m_ostream << R"( <th style="width: )" << GetSASTColumnWidth() << R"(%;"></th>)" << endl; } m_ostream << R"( <td style='width: )" << GetMessageColumnWidth() << R"(%;'>)" << EscapeHtml(err.message) << R"(</td>)" << endl; m_ostream << R"( </tr>)" << endl; #endif } } void SimpleHTMLOutput::PrintTableBody() { PrintMessages(m_info, "Fails/Info"); PrintMessages(m_ga, "General Analysis (GA)"); PrintMessages(m_op, "Micro-optimizations (OP)"); PrintMessages(m_64, "64-bit errors (64)"); PrintMessages(m_cs, "Customers Specific (CS)"); PrintMessages(m_misra, "MISRA"); PrintMessages(m_autosar, "AUTOSAR"); PrintMessages(m_owasp, "OWASP"); } void SimpleHTMLOutput::Start() { PrintHtmlStart(); } bool SimpleHTMLOutput::Write(const Warning& msg) { if (msg.IsDocumentationLinkMessage()) { return false; } AnalyzerType analyzerType = msg.GetType(); if (analyzerType == AnalyzerType::General) m_ga.push_back(msg); else if (analyzerType == AnalyzerType::Optimization) m_op.push_back(msg); else if (analyzerType == AnalyzerType::Viva64) m_64.push_back(msg); else if (analyzerType == AnalyzerType::CustomerSpecific) m_cs.push_back(msg); else if (analyzerType == AnalyzerType::Misra) m_misra.push_back(msg); else if (analyzerType == AnalyzerType::Autosar) m_autosar.push_back(msg); else if (analyzerType == AnalyzerType::Owasp) m_owasp.push_back(msg); else m_info.push_back(msg); return true; } void SimpleHTMLOutput::Finish() { if (m_ga.empty() && m_op.empty() && m_64.empty() && m_cs.empty() && m_misra.empty() && m_info.empty() && m_owasp.empty() && m_autosar.empty()) { m_ostream << "No messages generated" << std::endl; } else { PrintTableCaption(); PrintTableBody(); } PrintHtmlEnd(); } }
29.251908
144
0.585073
[ "vector" ]
eb94010a93a6e73870c4bcbd7153c95271f3cdae
2,842
cpp
C++
Utils/tetovm2vtk/tetovm2vtk.cpp
msraig/CE-PolyCube
e46aff6e0594b711735118bfa902a91bc3d392ca
[ "MIT" ]
19
2020-08-13T05:15:09.000Z
2022-03-31T14:51:29.000Z
Utils/tetovm2vtk/tetovm2vtk.cpp
xh-liu-tech/CE-PolyCube
86d4ed0023215307116b6b3245e2dbd82907cbb8
[ "MIT" ]
2
2020-09-08T07:03:04.000Z
2021-08-04T05:43:27.000Z
Utils/tetovm2vtk/tetovm2vtk.cpp
xh-liu-tech/CE-PolyCube
86d4ed0023215307116b6b3245e2dbd82907cbb8
[ "MIT" ]
10
2020-08-06T02:37:46.000Z
2021-07-01T09:12:06.000Z
#include <iostream> #include <fstream> #include <string> // Include the file manager header #include <OpenVolumeMesh/FileManager/FileManager.hh> // Include the polyhedral mesh header #include <OpenVolumeMesh/Mesh/PolyhedralMesh.hh> //do not consider cell order, might need to be changed int main(int argc, char** argv) { //input must be two file name if (argc != 3) { std::cout << "input format: " << "input.ovm output.vtk" << std::endl; } OpenVolumeMesh::GeometricPolyhedralMeshV3d myMesh; // Create file manager object OpenVolumeMesh::IO::FileManager fileManager; // Read mesh from file "myMesh.ovm" in the current directory fileManager.readFile(argv[1], myMesh); /*std::ifstream inputfile(argv[1]); std::ofstream outputfile(argv[2]);*/ std::vector<double> x, y, z; std::vector<std::vector<int>> indices; for (OpenVolumeMesh::VertexIter v_it = myMesh.vertices_begin(); v_it != myMesh.vertices_end(); ++v_it) { int v_id = v_it->idx(); OpenVolumeMesh::Geometry::Vec3d p = myMesh.vertex(*v_it); //dpx[v_id] = p[0]; dpy[v_id] = p[1]; dpz[v_id] = p[2]; x.push_back(p[0]); y.push_back(p[1]); z.push_back(p[2]); } std::vector<OpenVolumeMesh::HalfFaceHandle> hff_vec; for (OpenVolumeMesh::CellIter c_it = myMesh.cells_begin(); c_it != myMesh.cells_end(); ++c_it) { double cv_count = 0.0; int c_id = c_it->idx(); std::vector<int> tmp_indices; const std::vector<OpenVolumeMesh::VertexHandle>& vertices_ = myMesh.cell(*c_it).vertices(); hff_vec = myMesh.cell(*c_it).halffaces(); assert(hff_vec.size() == 4); OpenVolumeMesh::HalfFaceVertexIter hfv_it = myMesh.hfv_iter(hff_vec[0]); //unsigned int i = 0; std::set<int> face_set; for (hfv_it; hfv_it; ++hfv_it) { tmp_indices.push_back(hfv_it->idx()); face_set.insert(hfv_it->idx()); } for (unsigned i = 0; i < vertices_.size(); ++i) { int v_id = vertices_[i]; auto it = face_set.find(v_id); if (it == face_set.end()) { tmp_indices.push_back(v_id); } } assert(tmp_indices.size() == 4); indices.push_back(tmp_indices); } std::ofstream outputfile(argv[2]); outputfile << "# vtk DataFile Version 3.0\n" << "Volume mesh\n" << "ASCII\n" << "DATASET UNSTRUCTURED_GRID\n"; int n_point = x.size(); int n_cell = indices.size(); outputfile << "POINTS " << n_point << " double" << std::endl; for (size_t i = 0; i < n_point; i++) { outputfile << x[i] << " " << y[i] << " " << z[i] << std::endl; } outputfile << "CELLS " << n_cell << " " << 5 * n_cell << std::endl; for (size_t i = 0; i < n_cell; i++) { outputfile << "4 "; for (size_t j = 0; j < 4; j++) { outputfile << indices[i][j] << " "; } outputfile << std::endl; } outputfile << "CELL_TYPES " << n_cell << std::endl; for (size_t i = 0; i < n_cell; i++) { outputfile << "10" << std::endl; } outputfile.close(); }
26.811321
103
0.638635
[ "mesh", "geometry", "object", "vector" ]
eb946ed5ea5cd194781c2f50d23dfddefcfe63b5
3,908
cc
C++
shill/technology.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
5
2019-01-19T15:38:48.000Z
2021-10-06T03:59:46.000Z
shill/technology.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
null
null
null
shill/technology.cc
emersion/chromiumos-platform2
ba71ad06f7ba52e922c647a8915ff852b2d4ebbd
[ "BSD-3-Clause" ]
1
2019-02-15T23:05:30.000Z
2019-02-15T23:05:30.000Z
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shill/technology.h" #include <set> #include <string> #include <vector> #include <base/stl_util.h> #include <base/strings/string_split.h> #include <chromeos/dbus/service_constants.h> #include "shill/error.h" #include "shill/logging.h" namespace shill { using std::set; using std::string; using std::vector; namespace { constexpr char kLoopbackName[] = "loopback"; constexpr char kTunnelName[] = "tunnel"; constexpr char kPPPName[] = "ppp"; constexpr char kUnknownName[] = "unknown"; } // namespace // static Technology::Identifier Technology::IdentifierFromName(const string& name) { if (name == kTypeEthernet) { return kEthernet; } else if (name == kTypeEthernetEap) { return kEthernetEap; } else if (name == kTypeWifi) { return kWifi; } else if (name == kTypeWimax) { return kWiMax; } else if (name == kTypeCellular) { return kCellular; } else if (name == kTypeVPN) { return kVPN; } else if (name == kTypePPPoE) { return kPPPoE; } else if (name == kLoopbackName) { return kLoopback; } else if (name == kTunnelName) { return kTunnel; } else if (name == kPPPName) { return kPPP; } else { return kUnknown; } } // static string Technology::NameFromIdentifier(Technology::Identifier id) { if (id == kEthernet) { return kTypeEthernet; } else if (id == kEthernetEap) { return kTypeEthernetEap; } else if (id == kWifi) { return kTypeWifi; } else if (id == kWiMax) { return kTypeWimax; } else if (id == kCellular) { return kTypeCellular; } else if (id == kVPN) { return kTypeVPN; } else if (id == kLoopback) { return kLoopbackName; } else if (id == kTunnel) { return kTunnelName; } else if (id == kPPP) { return kPPPName; } else if (id == kPPPoE) { return kTypePPPoE; } else { return kUnknownName; } } // static Technology::Identifier Technology::IdentifierFromStorageGroup( const string& group) { vector<string> group_parts = base::SplitString( group, "_", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (group_parts.empty()) { return kUnknown; } return IdentifierFromName(group_parts[0]); } // static bool Technology::GetTechnologyVectorFromString( const string& technologies_string, vector<Identifier>* technologies_vector, Error* error) { CHECK(technologies_vector); CHECK(error); vector<string> technology_parts; set<Technology::Identifier> seen; technologies_vector->clear(); // Check if |technologies_string| is empty as some versions of // base::SplitString return a vector with one empty string when given an // empty string. if (!technologies_string.empty()) { technology_parts = base::SplitString( technologies_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); } for (const auto& name : technology_parts) { Technology::Identifier identifier = Technology::IdentifierFromName(name); if (identifier == Technology::kUnknown) { Error::PopulateAndLog(FROM_HERE, error, Error::kInvalidArguments, name + " is an unknown technology name"); return false; } if (base::ContainsKey(seen, identifier)) { Error::PopulateAndLog(FROM_HERE, error, Error::kInvalidArguments, name + " is duplicated in the list"); return false; } seen.insert(identifier); technologies_vector->push_back(identifier); } return true; } // static bool Technology::IsPrimaryConnectivityTechnology(Identifier technology) { return (technology == kCellular || technology == kEthernet || technology == kWifi || technology == kWiMax || technology == kPPPoE); } } // namespace shill
26.228188
79
0.667605
[ "vector" ]
eb98dd12bbe0f170fb683288a7fc8fd2772f81ac
10,184
cpp
C++
isis/src/base/objs/ProcessByBrick/unitTest.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
1
2022-02-17T01:07:03.000Z
2022-02-17T01:07:03.000Z
isis/src/base/objs/ProcessByBrick/unitTest.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
null
null
null
isis/src/base/objs/ProcessByBrick/unitTest.cpp
gknorman/ISIS3
4800a8047626a864e163cc74055ba60008c105f7
[ "CC0-1.0" ]
null
null
null
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include "Isis.h" #include "ProcessByBrick.h" #include "Cube.h" #include <iostream> #include <string> using namespace std; using namespace Isis; void oneInAndOut(Buffer &ob, Buffer &ib); void twoInAndOut(vector<Buffer *> &ib, vector<Buffer *> &ob); class Functor2 { public: void operator()(Buffer & in, Buffer & out) const { oneInAndOut(in, out); }; }; class Functor3 { public: void operator()(vector<Buffer *> &ib, vector<Buffer *> &ob) const { twoInAndOut(ib, ob); }; }; class Functor4 { public: void operator()(Buffer &in, Buffer &out) const { for (int i = 0; i < out.size(); i++) { out[i] = in.Sample(i) + in.Line(i) * 10 + in.Band(i) * 100; } }; }; class Functor5 { public: void operator()(Buffer &inout) const { for (int i = 0; i < inout.size(); i++) { inout[i] = inout[i] * 2; } }; }; void IsisMain() { Preference::Preferences(true); Cube *icube; ProcessByBrick p; cout << "Testing Functors\n"; { cout << "Functor2 - ProcessCube One Thread\n"; //No cubes entered...will fail try{ p.VerifyCubes(ProcessByBrick::InPlace); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "1:" + exMsg.toStdString() << endl; } //InputCubes.size() !=1, will fail try{ p.VerifyCubes(ProcessByBrick::InputOutput); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "2:" + exMsg.toStdString() << endl; } icube = p.SetInputCube("FROM"); p.SetBrickSize(10, 10, 2); //Input cube set, but output cube unset. Will fail try{ p.VerifyCubes(ProcessByBrick::InputOutput); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "3:" + exMsg.toStdString() << endl; } p.EndProcess(); icube = p.SetInputCube("FROM"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount()+10, icube->lineCount(), icube->bandCount()); //Samples don't match try{ p.VerifyCubes(ProcessByBrick::InputOutput); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "4:" + exMsg.toStdString() << endl; } p.EndProcess(); icube = p.SetInputCube("FROM"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount()+10, icube->bandCount()); //Lines don't match try{ p.VerifyCubes(ProcessByBrick::InputOutput); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "5:" + exMsg.toStdString() << endl; } p.EndProcess(); icube = p.SetInputCube("FROM"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount(), icube->bandCount()+10); //Bands don't match try{ p.VerifyCubes(ProcessByBrick::InputOutput); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "6:" + exMsg.toStdString() << endl; } p.EndProcess(); icube = p.SetInputCube("FROM"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount(), icube->bandCount()); p.VerifyCubes(ProcessByBrick::InputOutput); //Everything is correct icube = p.SetInputCube("FROM"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount(), icube->bandCount()); try{ p.VerifyCubes(ProcessByBrick::InPlace); //Will fail } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "7:" + exMsg.toStdString() << endl; } p.EndProcess(); Functor2 functor; icube = p.SetInputCube("FROM"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount(), icube->bandCount()); p.ProcessCube(functor, false); p.EndProcess(); cout << "\n"; } { cout << "Functor3 - ProcessCubes One Thread\n"; // No input cubes specified, will fail try{ p.VerifyCubes(ProcessByBrick::InputOutputList); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "8:" + exMsg.toStdString() << endl; } p.EndProcess(); Cube *icube = p.SetInputCube("FROM"); p.SetInputCube("FROM2"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount()+10, icube->bandCount()); p.SetOutputCube("TO2", icube->sampleCount(), icube->lineCount(), icube->bandCount()); } { //Output[0] cube does not have the same number of lines as input[0] cube try{ p.VerifyCubes(ProcessByBrick::InputOutputList); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "9:" + exMsg.toStdString() << endl; } p.EndProcess(); } { Cube *icube = p.SetInputCube("FROM"); p.SetInputCube("FROM2"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount(), icube->bandCount()+10); p.SetOutputCube("TO2", icube->sampleCount(), icube->lineCount(), icube->bandCount()); //Output[0] cube does not have the same number of bands as input[0] cube try{ p.VerifyCubes(ProcessByBrick::InputOutputList); } catch(Isis::IException &ex){ QString exMsg = ex.toString(); cout << "10:" + exMsg.toStdString() << endl; } p.EndProcess(); } { Functor3 functor; Cube *icube = p.SetInputCube("FROM"); p.SetInputCube("FROM2"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount(), icube->bandCount()+10); p.SetOutputCube("TO2", icube->sampleCount(), icube->lineCount(), icube->bandCount()); p.ProcessCubes(functor, false); p.EndProcess(); cout << "\n"; } { cout << "Functor4 - ProcessCube Threaded\n"; Cube *icube = p.SetInputCube("FROM"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount(), icube->bandCount()); Functor4 functor; p.ProcessCube(functor,false); p.EndProcess(); Cube cube; cube.open(Application::GetUserInterface().GetCubeName("TO")); Statistics *statsBand1 = cube.statistics(1); Statistics *statsBand2 = cube.statistics(2); std::cerr << "Averages: " << statsBand1->Average() << ", " << statsBand2->Average() << "\n"; cout << "\n"; } { cout << "Functor5 - ProcessCubeInPlace Threaded\n"; Cube *cube = new Cube; cube->open(Application::GetUserInterface().GetCubeName("TO"), "rw"); p.SetBrickSize(10, 10, 2); p.SetInputCube(cube); Functor5 functor; try{ p.VerifyCubes(ProcessByBrick::InputOutputList); } catch(Isis::IException &ex){ QString msg = ex.toString(); cout << msg.toStdString() << endl; } p.VerifyCubes(ProcessByBrick::InPlace); p.ProcessCubeInPlace(functor,false); p.EndProcess(); cube->close(); cube = new Cube; cube->open(Application::GetUserInterface().GetCubeName("TO"), "rw"); Statistics *statsBand1 = cube->statistics(1); Statistics *statsBand2 = cube->statistics(2); delete cube; std::cerr << "Averages: " << statsBand1->Average() << ", " << statsBand2->Average() << "\n"; cout << "\n"; } cout << "End Testing Functors\n\n"; cout << "Testing StartProcess\n"; { Cube *icube = p.SetInputCube("FROM"); p.SetInputCube("FROM2"); p.SetBrickSize(10, 10, 2); p.SetOutputCube("TO", icube->sampleCount(), icube->lineCount(), icube->bandCount()); p.SetOutputCube("TO2", icube->sampleCount(), icube->lineCount(), icube->bandCount()); p.StartProcess(twoInAndOut); p.EndProcess(); } Cube cube; cube.open("$temporary/isisProcessByBrick_01"); cube.close(true); cube.open("$temporary/isisProcessByBrick_02"); cube.close(true); } void oneInAndOut(Buffer &ib, Buffer &ob) { if((ib.Line() == 1) && (ib.Band() == 1)) { cout << endl; cout << "Testing one input and output cube ... " << endl; cout << "Buffer Samples: " << ib.size() << endl; cout << "Buffer Lines: " << ib.LineDimension() << endl; cout << "Buffer Bands: " << ib.BandDimension() << endl; cout << endl; } cout << "Sample: " << ib.Sample() << " Line: " << ib.Line() << " Band: " << ib.Band() << endl; if((ib.Sample() != ob.Sample()) || (ib.Line() != ob.Line()) || (ib.Band() != ob.Band())) { cout << "Bogus error #1" << endl; } } void twoInAndOut(vector<Buffer *> &ib, vector<Buffer *> &ob) { static bool firstTime = true; if(firstTime) { firstTime = false; cout << "Testing two input and output cubes ... " << endl; cout << "Number of input cubes: " << ib.size() << endl; cout << "Number of output cubes: " << ob.size() << endl; cout << endl; } Buffer &inone = *ib[0]; Buffer &intwo = *ib[1]; Buffer &outone = *ob[0]; Buffer &outtwo = *ob[1]; cout << "Sample: " << inone.Sample() << ":" << intwo.Sample() << " Line: " << inone.Line() << ":" << intwo.Line() << " Band: " << inone.Band() << ":" << intwo.Band() << endl; if((inone.Sample() != intwo.Sample()) || (inone.Line() != intwo.Line())) { cout << "Bogus error #1" << endl; } if((inone.Sample() != outone.Sample()) || (inone.Line() != outone.Line()) || (inone.Band() != outone.Band())) { cout << "Bogus error #2" << endl; } if((outone.Sample() != outtwo.Sample()) || (outone.Line() != outtwo.Line()) || (outone.Band() != outtwo.Band())) { cout << "Bogus error #3" << endl; } }
24.778589
91
0.576296
[ "vector" ]
eb9a6e7c63ad40aa6786d51438be94eec4498509
16,056
hpp
C++
src/external/xgboost/src/tree/updater_basemaker-inl.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
src/external/xgboost/src/tree/updater_basemaker-inl.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
src/external/xgboost/src/tree/updater_basemaker-inl.hpp
Bpowers4/turicreate
73dad213cc1c4f74337b905baea2b3a1e5a0266c
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
/*! * Copyright 2014 by Contributors * \file updater_basemaker-inl.hpp * \brief implement a common tree constructor * \author Tianqi Chen */ #ifndef XGBOOST_TREE_UPDATER_BASEMAKER_INL_HPP_ #define XGBOOST_TREE_UPDATER_BASEMAKER_INL_HPP_ #include <vector> #include <algorithm> #include <string> #include <limits> #include <xgboost/src/sync/sync.h> #include <xgboost/src/utils/random.h> #include <xgboost/src/utils/quantile.h> // GLC parallel lambda premitive #include <core/parallel/lambda_omp.hpp> #include <core/parallel/pthread_tools.hpp> namespace xgboost { namespace tree { /*! * \brief base tree maker class that defines common operation * needed in tree making */ class BaseMaker: public IUpdater { public: // destructor virtual ~BaseMaker(void) {} // set training parameter virtual void SetParam(const char *name, const char *val) { param.SetParam(name, val); } protected: // helper to collect and query feature meta information struct FMetaHelper { public: /*! \brief find type of each feature, use column format */ inline void InitByCol(IFMatrix *p_fmat, const RegTree &tree) { fminmax.resize(tree.param.num_feature * 2); std::fill(fminmax.begin(), fminmax.end(), -std::numeric_limits<bst_float>::max()); // start accumulating statistics utils::IIterator<ColBatch> *iter = p_fmat->ColIterator(); iter->BeforeFirst(); while (iter->Next()) { const ColBatch &batch = iter->Value(); for (bst_uint i = 0; i < batch.size; ++i) { const bst_uint fid = batch.col_index[i]; const ColBatch::Inst &c = batch[i]; if (c.length != 0) { fminmax[fid * 2 + 0] = std::max(-c[0].fvalue, fminmax[fid * 2 + 0]); fminmax[fid * 2 + 1] = std::max(c[c.length - 1].fvalue, fminmax[fid * 2 + 1]); } } } rabit::Allreduce<rabit::op::Max>(BeginPtr(fminmax), fminmax.size()); } // get feature type, 0:empty 1:binary 2:real inline int Type(bst_uint fid) const { utils::Assert(fid * 2 + 1 < fminmax.size(), "FeatHelper fid exceed query bound "); bst_float a = fminmax[fid * 2]; bst_float b = fminmax[fid * 2 + 1]; if (a == -std::numeric_limits<bst_float>::max()) return 0; if (-a == b) { return 1; } else { return 2; } } inline bst_float MaxValue(bst_uint fid) const { return fminmax[fid *2 + 1]; } inline void SampleCol(float p, std::vector<bst_uint> *p_findex) const { std::vector<bst_uint> &findex = *p_findex; findex.clear(); for (size_t i = 0; i < fminmax.size(); i += 2) { const bst_uint fid = static_cast<bst_uint>(i / 2); if (this->Type(fid) != 0) findex.push_back(fid); } unsigned n = static_cast<unsigned>(p * findex.size()); random::Shuffle(findex); findex.resize(std::max<unsigned>(n, 1)); // sync the findex if it is subsample std::string s_cache; utils::MemoryBufferStream fc(&s_cache); utils::IStream &fs = fc; if (rabit::GetRank() == 0) { fs.Write(findex); } rabit::Broadcast(&s_cache, 0); fs.Read(&findex); } private: std::vector<bst_float> fminmax; }; // ------static helper functions ------ // helper function to get to next level of the tree /*! \brief this is helper function for row based data*/ inline static int NextLevel(const RowBatch::Inst &inst, const RegTree &tree, int nid) { const RegTree::Node &n = tree[nid]; bst_uint findex = n.split_index(); for (unsigned i = 0; i < inst.length; ++i) { if (findex == inst[i].index) { if (inst[i].fvalue < n.split_cond()) { return n.cleft(); } else { return n.cright(); } } } return n.cdefault(); } /*! \brief get number of omp thread in current context */ inline static int get_nthread(void) { int nthread; // #pragma omp parallel // { // nthread = omp_get_num_threads(); // } nthread = turi::thread::cpu_count(); return nthread; } // ------class member helpers--------- /*! \brief initialize temp data structure */ inline void InitData(const std::vector<bst_gpair> &gpair, const IFMatrix &fmat, const std::vector<unsigned> &root_index, const RegTree &tree) { utils::Assert(tree.param.num_nodes == tree.param.num_roots, "TreeMaker: can only grow new tree"); { // setup position position.resize(gpair.size()); if (root_index.size() == 0) { std::fill(position.begin(), position.end(), 0); } else { for (size_t i = 0; i < position.size(); ++i) { position[i] = root_index[i]; utils::Assert(root_index[i] < (unsigned)tree.param.num_roots, "root index exceed setting"); } } // mark delete for the deleted datas for (size_t i = 0; i < position.size(); ++i) { if (gpair[i].hess < 0.0f) position[i] = ~position[i]; } // mark subsample if (param.subsample < 1.0f) { for (size_t i = 0; i < position.size(); ++i) { if (gpair[i].hess < 0.0f) continue; if (random::SampleBinary(param.subsample) == 0) position[i] = ~position[i]; } } } { // expand query qexpand.reserve(256); qexpand.clear(); for (int i = 0; i < tree.param.num_roots; ++i) { qexpand.push_back(i); } this->UpdateNode2WorkIndex(tree); } } /*! \brief update queue expand add in new leaves */ inline void UpdateQueueExpand(const RegTree &tree) { std::vector<int> newnodes; for (size_t i = 0; i < qexpand.size(); ++i) { const int nid = qexpand[i]; if (!tree[nid].is_leaf()) { newnodes.push_back(tree[nid].cleft()); newnodes.push_back(tree[nid].cright()); } } // use new nodes for qexpand qexpand = newnodes; this->UpdateNode2WorkIndex(tree); } // return decoded position inline int DecodePosition(bst_uint ridx) const { const int pid = position[ridx]; return pid < 0 ? ~pid : pid; } // encode the encoded position value for ridx inline void SetEncodePosition(bst_uint ridx, int nid) { if (position[ridx] < 0) { position[ridx] = ~nid; } else { position[ridx] = nid; } } /*! * \brief this is helper function uses column based data structure, * reset the positions to the lastest one * \param nodes the set of nodes that contains the split to be used * \param p_fmat feature matrix needed for tree construction * \param tree the regression tree structure */ inline void ResetPositionCol(const std::vector<int> &nodes, IFMatrix *p_fmat, const RegTree &tree) { // set the positions in the nondefault this->SetNonDefaultPositionCol(nodes, p_fmat, tree); // set rest of instances to default position const std::vector<bst_uint> &rowset = p_fmat->buffered_rowset(); // set default direct nodes to default // for leaf nodes that are not fresh, mark then to ~nid, // so that they are ignored in future statistics collection const bst_omp_uint ndata = static_cast<bst_omp_uint>(rowset.size()); // #pragma omp parallel for schedule(static) // for (bst_omp_uint i = 0; i < ndata; ++i) { turi::parallel_for (0, ndata, [&](size_t i) { const bst_uint ridx = rowset[i]; const int nid = this->DecodePosition(ridx); if (tree[nid].is_leaf()) { // mark finish when it is not a fresh leaf if (tree[nid].cright() == -1) { position[ridx] = ~nid; } } else { // push to default branch if (tree[nid].default_left()) { this->SetEncodePosition(ridx, tree[nid].cleft()); } else { this->SetEncodePosition(ridx, tree[nid].cright()); } } }); } /*! * \brief this is helper function uses column based data structure, * update all positions into nondefault branch, if any, ignore the default branch * \param nodes the set of nodes that contains the split to be used * \param p_fmat feature matrix needed for tree construction * \param tree the regression tree structure */ virtual void SetNonDefaultPositionCol(const std::vector<int> &nodes, IFMatrix *p_fmat, const RegTree &tree) { // step 1, classify the non-default data into right places std::vector<unsigned> fsplits; for (size_t i = 0; i < nodes.size(); ++i) { const int nid = nodes[i]; if (!tree[nid].is_leaf()) { fsplits.push_back(tree[nid].split_index()); } } std::sort(fsplits.begin(), fsplits.end()); fsplits.resize(std::unique(fsplits.begin(), fsplits.end()) - fsplits.begin()); utils::IIterator<ColBatch> *iter = p_fmat->ColIterator(fsplits); while (iter->Next()) { const ColBatch &batch = iter->Value(); for (size_t i = 0; i < batch.size; ++i) { ColBatch::Inst col = batch[i]; const bst_uint fid = batch.col_index[i]; const bst_omp_uint ndata = static_cast<bst_omp_uint>(col.length); // #pragma omp parallel for schedule(static) // for (bst_omp_uint j = 0; j < ndata; ++j) { turi::parallel_for (0, ndata, [&](size_t j) { const bst_uint ridx = col[j].index; const float fvalue = col[j].fvalue; const int nid = this->DecodePosition(ridx); // go back to parent, correct those who are not default if (!tree[nid].is_leaf() && tree[nid].split_index() == fid) { if (fvalue < tree[nid].split_cond()) { this->SetEncodePosition(ridx, tree[nid].cleft()); } else { this->SetEncodePosition(ridx, tree[nid].cright()); } } }); } } } /*! brief helper function to get statistics from a tree */ template<typename TStats> inline void GetNodeStats(const std::vector<bst_gpair> &gpair, const IFMatrix &fmat, const RegTree &tree, const BoosterInfo &info, std::vector< std::vector<TStats> > *p_thread_temp, std::vector<TStats> *p_node_stats) { std::vector< std::vector<TStats> > &thread_temp = *p_thread_temp; thread_temp.resize(this->get_nthread()); p_node_stats->resize(tree.param.num_nodes); // #pragma omp parallel { // const int tid = omp_get_thread_num(); turi::in_parallel([&](size_t tid, size_t num_threads) { thread_temp[tid].resize(tree.param.num_nodes, TStats(param)); for (size_t i = 0; i < qexpand.size(); ++i) { const unsigned nid = qexpand[i]; thread_temp[tid][nid].Clear(); } }); } const std::vector<bst_uint> &rowset = fmat.buffered_rowset(); // setup position const bst_omp_uint ndata = static_cast<bst_omp_uint>(rowset.size()); // #pragma omp parallel for schedule(static) // for (bst_omp_uint i = 0; i < ndata; ++i) { turi::parallel_for (0, ndata, [&](size_t i) { const bst_uint ridx = rowset[i]; const int nid = position[ridx]; // const int tid = omp_get_thread_num(); const int tid = turi::thread::thread_id(); if (nid >= 0) { thread_temp[tid][nid].Add(gpair, info, ridx); } }); // sum the per thread statistics together for (size_t j = 0; j < qexpand.size(); ++j) { const int nid = qexpand[j]; TStats &s = (*p_node_stats)[nid]; s.Clear(); for (size_t tid = 0; tid < thread_temp.size(); ++tid) { s.Add(thread_temp[tid][nid]); } } } /*! \brief common helper data structure to build sketch */ struct SketchEntry { /*! \brief total sum of amount to be met */ double sum_total; /*! \brief statistics used in the sketch */ double rmin, wmin; /*! \brief last seen feature value */ bst_float last_fvalue; /*! \brief current size of sketch */ double next_goal; // pointer to the sketch to put things in utils::WXQuantileSketch<bst_float, bst_float> *sketch; // initialize the space inline void Init(unsigned max_size) { next_goal = -1.0f; rmin = wmin = 0.0f; sketch->temp.Reserve(max_size + 1); sketch->temp.size = 0; } /*! * \brief push a new element to sketch * \param fvalue feature value, comes in sorted ascending order * \param w weight * \param max_size */ inline void Push(bst_float fvalue, bst_float w, unsigned max_size) { if (next_goal == -1.0f) { next_goal = 0.0f; last_fvalue = fvalue; wmin = w; return; } if (last_fvalue != fvalue) { double rmax = rmin + wmin; if (rmax >= next_goal && sketch->temp.size != max_size) { if (sketch->temp.size == 0 || last_fvalue > sketch->temp.data[sketch->temp.size-1].value) { // push to sketch sketch->temp.data[sketch->temp.size] = utils::WXQuantileSketch<bst_float, bst_float>:: Entry(static_cast<bst_float>(rmin), static_cast<bst_float>(rmax), static_cast<bst_float>(wmin), last_fvalue); utils::Assert(sketch->temp.size < max_size, "invalid maximum size max_size=%u, stemp.size=%lu\n", max_size, sketch->temp.size); ++sketch->temp.size; } if (sketch->temp.size == max_size) { next_goal = sum_total * 2.0f + 1e-5f; } else { next_goal = static_cast<bst_float>(sketch->temp.size * sum_total / max_size); } } else { if (rmax >= next_goal) { rabit::TrackerPrintf("INFO: rmax=%g, sum_total=%g, next_goal=%g, size=%lu\n", rmax, sum_total, next_goal, sketch->temp.size); } } rmin = rmax; wmin = w; last_fvalue = fvalue; } else { wmin += w; } } /*! \brief push final unfinished value to the sketch */ inline void Finalize(unsigned max_size) { double rmax = rmin + wmin; if (sketch->temp.size == 0 || last_fvalue > sketch->temp.data[sketch->temp.size-1].value) { utils::Assert(sketch->temp.size <= max_size, "Finalize: invalid maximum size, max_size=%u, stemp.size=%lu", sketch->temp.size, max_size); // push to sketch sketch->temp.data[sketch->temp.size] = utils::WXQuantileSketch<bst_float, bst_float>:: Entry(static_cast<bst_float>(rmin), static_cast<bst_float>(rmax), static_cast<bst_float>(wmin), last_fvalue); ++sketch->temp.size; } sketch->PushTemp(); } }; /*! \brief training parameter of tree grower */ TrainParam param; /*! \brief queue of nodes to be expanded */ std::vector<int> qexpand; /*! * \brief map active node to is working index offset in qexpand, * can be -1, which means the node is node actively expanding */ std::vector<int> node2workindex; /*! * \brief position of each instance in the tree * can be negative, which means this position is no longer expanding * see also Decode/EncodePosition */ std::vector<int> position; private: inline void UpdateNode2WorkIndex(const RegTree &tree) { // update the node2workindex std::fill(node2workindex.begin(), node2workindex.end(), -1); node2workindex.resize(tree.param.num_nodes); for (size_t i = 0; i < qexpand.size(); ++i) { node2workindex[qexpand[i]] = static_cast<int>(i); } } }; } // namespace tree } // namespace xgboost #endif // XGBOOST_TREE_UPDATER_BASEMAKER_INL_HPP_
36.574032
97
0.584392
[ "vector" ]
ebb1f08218f9713a405eef8c1bae88fef736866d
5,278
cpp
C++
examples/C++/Keys/keys.cpp
ruffsl/Fast-RTPS
ae7cf4e961801956e59cba37a5c17cdc2258ec6c
[ "Apache-2.0" ]
1
2018-03-20T21:31:38.000Z
2018-03-20T21:31:38.000Z
examples/C++/Keys/keys.cpp
ruffsl/Fast-RTPS
ae7cf4e961801956e59cba37a5c17cdc2258ec6c
[ "Apache-2.0" ]
null
null
null
examples/C++/Keys/keys.cpp
ruffsl/Fast-RTPS
ae7cf4e961801956e59cba37a5c17cdc2258ec6c
[ "Apache-2.0" ]
1
2018-09-19T10:12:29.000Z
2018-09-19T10:12:29.000Z
#include <iostream> #include <string> #include <fastrtps/participant/Participant.h> #include <fastrtps/attributes/ParticipantAttributes.h> #include <fastrtps/subscriber/Subscriber.h> #include <fastrtps/attributes/SubscriberAttributes.h> #include <fastrtps/publisher/Publisher.h> #include <fastrtps/attributes/PublisherAttributes.h> #include <fastrtps/Domain.h> #include <fastrtps/subscriber/SampleInfo.h> #include <fastrtps/utils/eClock.h> #include "samplePubSubTypes.h" using namespace eprosima::fastrtps; using namespace eprosima::fastrtps::rtps; //Enums and configuration structure enum Reliability_type { Best_Effort, Reliable }; enum Durability_type { Transient_Local, Volatile }; enum HistoryKind_type { Keep_Last, Keep_All }; enum Key_type { No_Key, With_Key}; typedef struct{ Reliability_type reliability; Durability_type durability; HistoryKind_type historykind; Key_type keys; uint16_t history_size; uint8_t depth; uint8_t no_keys; uint16_t max_samples_per_key; } example_configuration; void keys(); int main(){ keys(); return 0; } void keys(){ samplePubSubType sampleType; sample my_sample; SampleInfo_t sample_info; ParticipantAttributes PparamPub; PparamPub.rtps.builtin.domainId = 0; PparamPub.rtps.builtin.leaseDuration = c_TimeInfinite; PparamPub.rtps.setName("PublisherParticipant"); Participant *PubParticipant = Domain::createParticipant(PparamPub); if(PubParticipant == nullptr){ std::cout << " Something went wrong while creating the Publisher Participant..." << std::endl; return; } Domain::registerType(PubParticipant,(TopicDataType*) &sampleType); //Publisher config PublisherAttributes Pparam; Pparam.topic.topicDataType = sampleType.getName(); Pparam.topic.topicName = "samplePubSubTopic"; Pparam.historyMemoryPolicy = DYNAMIC_RESERVE_MEMORY_MODE; Pparam.topic.topicKind = WITH_KEY; Pparam.topic.historyQos.kind = KEEP_ALL_HISTORY_QOS; Pparam.qos.m_durability.kind = VOLATILE_DURABILITY_QOS; Pparam.qos.m_reliability.kind = RELIABLE_RELIABILITY_QOS; Pparam.topic.resourceLimitsQos.max_samples = 100; Pparam.topic.resourceLimitsQos.allocated_samples = 100; Pparam.topic.resourceLimitsQos.max_instances = 5; Pparam.topic.resourceLimitsQos.max_samples_per_instance = 20; std::cout << "Creating Publisher..." << std::endl; Publisher *myPub= Domain::createPublisher(PubParticipant, Pparam, nullptr); if(myPub == nullptr){ std::cout << "Something went wrong while creating the Publisher..." << std::endl; return; } ParticipantAttributes PparamSub; PparamSub.rtps.builtin.domainId = 0; PparamSub.rtps.builtin.leaseDuration = c_TimeInfinite; PparamSub.rtps.setName("SubscriberParticipant"); Participant *SubParticipant = Domain::createParticipant(PparamSub); if(SubParticipant == nullptr){ std::cout << " Something went wrong while creating the Subscriber Participant..." << std::endl; return; } Domain::registerType(SubParticipant,(TopicDataType*) &sampleType); //Keep All Sub SubscriberAttributes Rparam; Rparam.topic.topicDataType = sampleType.getName(); Rparam.topic.topicName = "samplePubSubTopic"; Rparam.historyMemoryPolicy = DYNAMIC_RESERVE_MEMORY_MODE; Rparam.topic.topicKind = WITH_KEY; Rparam.topic.historyQos.kind = KEEP_ALL_HISTORY_QOS; Rparam.qos.m_durability.kind = VOLATILE_DURABILITY_QOS; Rparam.qos.m_reliability.kind = RELIABLE_RELIABILITY_QOS; Rparam.topic.resourceLimitsQos.max_samples = 100; Rparam.topic.resourceLimitsQos.allocated_samples = 100; Rparam.topic.resourceLimitsQos.max_instances = 5; Rparam.topic.resourceLimitsQos.max_samples_per_instance = 20; std::cout << "Creating Subscriber..." << std::endl; Subscriber *mySub1= Domain::createSubscriber(PubParticipant, Rparam, nullptr); if(myPub == nullptr){ std::cout << "Something went wrong while creating the Subscriber..." << std::endl; return; } //Send 10 samples std::cout << "Publishing 5 keys, 10 samples per key..." << std::endl; for(uint8_t i=0; i < 5; i++){ for(uint8_t j=0; j < 10; j++){ my_sample.index(j+1); my_sample.key_value(i+1); myPub->write(&my_sample); } } eClock::my_sleep(1500); std::cout << "Publishing 10 more samples on a key 3..." << std::endl; for(uint8_t j=0; j < 10; j++){ my_sample.index(j+11); my_sample.key_value(3); myPub->write(&my_sample); } eClock::my_sleep(1500); //Read the contents of both histories: std::vector< std::pair<int,int> > sampleList; std::cout << "The Subscriber holds: " << std::endl; while(mySub1->readNextData(&my_sample, &sample_info)){ sampleList.push_back(std::pair<int,int>(my_sample.index(),my_sample.key_value())); } for(int key=1;key<=5;key++){ std::cout << " On key " << std::to_string(key) << ": "; for(std::pair<int,int> n : sampleList){ if(n.second == key) std::cout << std::to_string(n.first) << " "; } std::cout << std::endl; } std::cout << std::endl; }
33.405063
103
0.692687
[ "vector" ]
ebb2f2a6f826dc0934b874f0ee4cfca8ae26d800
4,120
cpp
C++
tools/Vitis-AI-Library/overview/samples/facelandmark/test_accuracy_facelandmark_mt.cpp
Carles-Figuerola/Vitis-AI
fc043ea4aca1f9fe4e18962e6a6ae397812bb34b
[ "Apache-2.0" ]
1
2020-12-18T14:49:19.000Z
2020-12-18T14:49:19.000Z
tools/Vitis-AI-Library/overview/samples/facelandmark/test_accuracy_facelandmark_mt.cpp
guochunhe/Vitis-AI
e86b6efae11f8703ee647e4a99004dc980b84989
[ "Apache-2.0" ]
null
null
null
tools/Vitis-AI-Library/overview/samples/facelandmark/test_accuracy_facelandmark_mt.cpp
guochunhe/Vitis-AI
e86b6efae11f8703ee647e4a99004dc980b84989
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <glog/logging.h> #include <fstream> #include <iostream> #include <memory> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <vitis/ai/demo_accuracy.hpp> #include <vitis/ai/nnpp/facelandmark.hpp> #include <vitis/ai/facelandmark.hpp> #include <xir/graph/graph.hpp> extern int g_last_frame_id; // A struct that can storage model info struct ModelInfo { int w; int h; } model_info_landmark; namespace vitis { namespace ai { static ModelInfo get_model_zise(const std::string& filename ) { std::string model_name = "/usr/share/vitis_ai_library/models/" + filename + "/" + filename + ".xmodel"; auto graph = xir::Graph::deserialize(model_name); auto root = graph->get_root_subgraph(); auto children = root->children_topological_sort(); if (children.empty()) { cout << "no subgraph" << endl; } for (auto c : children) { CHECK(c->has_attr("device")); auto device = c->get_attr<std::string>("device"); if (device == "DPU") { auto inputs = c->get_input_tensors(); for (auto input : inputs) { int height = input->get_shape().at(1); int width = input->get_shape().at(2); // std::cout << "model width: " << width << " model heigth: " << height << std::endl; return ModelInfo{width, height}; } } } return {0, 0}; } static std::vector<std::string> split(const std::string& s, const std::string& delim) { std::vector<std::string> elems; size_t pos = 0; size_t len = s.length(); size_t delim_len = delim.length(); if (delim_len == 0) return elems; while (pos < len) { int find_pos = s.find(delim, pos); if (find_pos < 0) { elems.push_back(s.substr(pos, len - pos)); break; } elems.push_back(s.substr(pos, find_pos - pos)); pos = find_pos + delim_len; } return elems; } struct FaceLandmarkAcc : public AccThread { FaceLandmarkAcc(std::string output_file) : AccThread(), of(output_file, std::ofstream::out) { dpu_result.frame_id = -1; } virtual ~FaceLandmarkAcc() { of.close(); } static std::shared_ptr<FaceLandmarkAcc> instance(std::string output_file) { static std::weak_ptr<FaceLandmarkAcc> the_instance; std::shared_ptr<FaceLandmarkAcc> ret; if (the_instance.expired()) { ret = std::make_shared<FaceLandmarkAcc>(output_file); the_instance = ret; } ret = the_instance.lock(); assert(ret != nullptr); return ret; } void process_result(DpuResultInfo dpu_result) { auto result = (FaceLandmarkResult*)dpu_result.result_ptr.get(); of << split(dpu_result.single_name, ".")[0] << std::endl; auto points = result->points; for (int i = 0; i < 5; ++i) { of << (int)(points[i].first * model_info_landmark.w) << " "; } for (int i = 0; i < 5; i++) { of << (int)(points[i].second * model_info_landmark.h) << " "; } } virtual int run() override { if (g_last_frame_id == int(dpu_result.frame_id)) return -1; if (queue_->pop(dpu_result, std::chrono::milliseconds(50000))) process_result(dpu_result); return 0; } DpuResultInfo dpu_result; std::ofstream of; }; } // namespace ai } // namespace vitis int main(int argc, char* argv[]) { model_info_landmark = vitis::ai::get_model_zise(argv[1]); return vitis::ai::main_for_accuracy_demo( argc, argv, [&] { return vitis::ai::FaceLandmark::create(argv[1]); }, vitis::ai::FaceLandmarkAcc::instance(argv[3]), 2); }
30.518519
105
0.651214
[ "vector", "model" ]
ebb97b0418808df675e5485562a54b0f44feaa25
3,976
cpp
C++
aws-cpp-sdk-gamelift/source/model/CreateGameServerGroupRequest.cpp
orinem/aws-sdk-cpp
f38413cc1f278689ef14e9ebdd74a489a48776be
[ "Apache-2.0" ]
1
2020-07-16T19:02:58.000Z
2020-07-16T19:02:58.000Z
aws-cpp-sdk-gamelift/source/model/CreateGameServerGroupRequest.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-gamelift/source/model/CreateGameServerGroupRequest.cpp
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/gamelift/model/CreateGameServerGroupRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::GameLift::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateGameServerGroupRequest::CreateGameServerGroupRequest() : m_gameServerGroupNameHasBeenSet(false), m_roleArnHasBeenSet(false), m_minSize(0), m_minSizeHasBeenSet(false), m_maxSize(0), m_maxSizeHasBeenSet(false), m_launchTemplateHasBeenSet(false), m_instanceDefinitionsHasBeenSet(false), m_autoScalingPolicyHasBeenSet(false), m_balancingStrategy(BalancingStrategy::NOT_SET), m_balancingStrategyHasBeenSet(false), m_gameServerProtectionPolicy(GameServerProtectionPolicy::NOT_SET), m_gameServerProtectionPolicyHasBeenSet(false), m_vpcSubnetsHasBeenSet(false), m_tagsHasBeenSet(false) { } Aws::String CreateGameServerGroupRequest::SerializePayload() const { JsonValue payload; if(m_gameServerGroupNameHasBeenSet) { payload.WithString("GameServerGroupName", m_gameServerGroupName); } if(m_roleArnHasBeenSet) { payload.WithString("RoleArn", m_roleArn); } if(m_minSizeHasBeenSet) { payload.WithInteger("MinSize", m_minSize); } if(m_maxSizeHasBeenSet) { payload.WithInteger("MaxSize", m_maxSize); } if(m_launchTemplateHasBeenSet) { payload.WithObject("LaunchTemplate", m_launchTemplate.Jsonize()); } if(m_instanceDefinitionsHasBeenSet) { Array<JsonValue> instanceDefinitionsJsonList(m_instanceDefinitions.size()); for(unsigned instanceDefinitionsIndex = 0; instanceDefinitionsIndex < instanceDefinitionsJsonList.GetLength(); ++instanceDefinitionsIndex) { instanceDefinitionsJsonList[instanceDefinitionsIndex].AsObject(m_instanceDefinitions[instanceDefinitionsIndex].Jsonize()); } payload.WithArray("InstanceDefinitions", std::move(instanceDefinitionsJsonList)); } if(m_autoScalingPolicyHasBeenSet) { payload.WithObject("AutoScalingPolicy", m_autoScalingPolicy.Jsonize()); } if(m_balancingStrategyHasBeenSet) { payload.WithString("BalancingStrategy", BalancingStrategyMapper::GetNameForBalancingStrategy(m_balancingStrategy)); } if(m_gameServerProtectionPolicyHasBeenSet) { payload.WithString("GameServerProtectionPolicy", GameServerProtectionPolicyMapper::GetNameForGameServerProtectionPolicy(m_gameServerProtectionPolicy)); } if(m_vpcSubnetsHasBeenSet) { Array<JsonValue> vpcSubnetsJsonList(m_vpcSubnets.size()); for(unsigned vpcSubnetsIndex = 0; vpcSubnetsIndex < vpcSubnetsJsonList.GetLength(); ++vpcSubnetsIndex) { vpcSubnetsJsonList[vpcSubnetsIndex].AsString(m_vpcSubnets[vpcSubnetsIndex]); } payload.WithArray("VpcSubnets", std::move(vpcSubnetsJsonList)); } if(m_tagsHasBeenSet) { Array<JsonValue> tagsJsonList(m_tags.size()); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); } payload.WithArray("Tags", std::move(tagsJsonList)); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection CreateGameServerGroupRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "GameLift.CreateGameServerGroup")); return headers; }
28.198582
154
0.76836
[ "model" ]
ebba78ff9b6617b9e34baa59bf5956f112473590
3,215
cpp
C++
Projects/Lesson19/Classes3/Source.cpp
aaviants/armath-edu2021
c0df17d59bbddda7448028838e02db67b065ad4d
[ "MIT" ]
null
null
null
Projects/Lesson19/Classes3/Source.cpp
aaviants/armath-edu2021
c0df17d59bbddda7448028838e02db67b065ad4d
[ "MIT" ]
null
null
null
Projects/Lesson19/Classes3/Source.cpp
aaviants/armath-edu2021
c0df17d59bbddda7448028838e02db67b065ad4d
[ "MIT" ]
null
null
null
#include <iostream> #include <string> struct vector { int x; int y; vector() { x = 0; y = 0; } vector(int value1, int value2) { x = value1; y = value2; } vector operator + (vector second) { vector v; v.x = x + second.x; v.y = y + second.y; return v; } vector operator - (vector second) { vector v; v.x = x - second.x; v.y = y - second.y; return v; } int operator * (vector second) { return x * second.x + y * second.y; } vector operator * (int number) { vector v; v.x = x * number; v.y = y * number; return v; } vector operator *= (int number) { vector v; v.x = x * number; v.y = y * number; return v; } }; struct text { char* letters; int length; }; void f1() { vector v1 = {}; v1.x = 5; v1.y = 10; vector v2 = v1; vector v3 = v1 + v2; vector v4 = v1 - v2; int prod = v1 * v3; vector v5 = v3 * 7; vector v6(3, 4); v2 *= 4; text t1 = {}; t1.letters = new char[10]; t1.length = 10; strcpy_s(t1.letters, 10, "Gvidon"); std::cout << t1.letters << std::endl; text t2 = {}; t2.letters = new char[t1.length]; t2.length = t1.length; strcpy_s(t2.letters, 10, t1.letters); delete[] t1.letters; std::cout << t2.letters << std::endl; delete[] t2.letters; } class string { private: char* buffer; int length; public: string() { buffer = nullptr; length = 0; } string(const char* text) { length = strlen(text); buffer = new char[length + 1]; strcpy_s(buffer, length + 1, text); } string(const string& other) { length = strlen(other.buffer); buffer = new char[length + 1]; strcpy_s(buffer, length + 1, other.buffer); } ~string() { if (buffer != nullptr) delete[] buffer; } string operator = (string other) { setText(other.getText()); return *this; } string operator + (string tail) { string result; result.length = length + tail.length; result.buffer = new char[result.length + 1]; strcpy_s(result.buffer, result.length + 1, buffer); strcpy_s(result.buffer + length, result.length + 1 - length, tail.buffer); return result; } void setText(const char* text) { length = strlen(text); if (buffer != nullptr) delete[] buffer; buffer = new char[length + 1]; strcpy_s(buffer, length + 1, text); } const char* getText() { return buffer; } int getLength() { return length; } string join(string tail) { string result; result.length = length + tail.length; result.buffer = new char[result.length + 1]; strcpy_s(result.buffer, result.length + 1, buffer); strcpy_s(result.buffer + length, result.length + 1 - length, tail.buffer); return result; } }; void f2() { string a; a.setText("Gvidon"); a.setText("Peprush"); string b = a; string d(a); string c; c = b; c = a; d = c = b = a; string e = "Ara"; string f("Ara"); std::cout << a.getText() << std::endl; std::cout << b.getText() << std::endl; } int main() { f1(); f2(); string name; name.setText("Ara "); string surname; surname.setText("Petrosyan"); string fullName = name.join(surname); std::cout << fullName.getText() << std::endl; string fullName2 = name + surname; std::cout << fullName2.getText() << std::endl; return 0; }
13.978261
76
0.599689
[ "vector" ]